wu :: forums
« wu :: forums - In-place Bit re-arrangement »

Welcome, Guest. Please Login or Register.
May 18th, 2024, 4:08pm

RIDDLES SITE WRITE MATH! Home Home Help Help Search Search Members Members Login Login Register Register
   wu :: forums
   riddles
   cs
(Moderators: william wu, Icarus, ThudnBlunder, Eigenray, towr, SMQ, Grimbal)
   In-place Bit re-arrangement
« Previous topic | Next topic »
Pages: 1  Reply Reply Notify of replies Notify of replies Send Topic Send Topic Print Print
   Author  Topic: In-place Bit re-arrangement  (Read 556 times)
ThePriest
Newbie
*





   


Gender: male
Posts: 16
In-place Bit re-arrangement  
« on: Feb 28th, 2008, 9:17am »
Quote Quote Modify Modify

This one is similar to the alternate in-place array rearrangement problem, posted a few days ago, but modified for a bit pattern.  
 
You are given a number (either 32 or 64 bit)containing some bit pattern (or numeric value). You have to place all the 0s in even position and 1s in odd position and if suppose number of 0s exceed the number of 1s or vice versa then keep them untouched. Generalize your solution for an N bit number.
 
It has to be done in O(n) time, without several single loops (only one pass) and O(1)space.
 
 
For e.g.
 
Input Number: 0 1 1 0 1 0 1 0 1 1 1 0 0 1 0 1 1  
 
output number: 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 1 1
IP Logged
Ved
Junior Member
**





   


Gender: male
Posts: 53
Re: In-place Bit re-arrangement  
« Reply #1 on: Jan 26th, 2010, 12:24am »
Quote Quote Modify Modify

{Sorry to resurrect a very old unanswered post}
Logic : We need to maintain two pointers – oddPtr which moves along the odd positions in the array and evenPtr which moves along the even positions. When we find an incorrect position, we swap this pointers and move along.
 
One interesting case is when one of the pointer moves past the last element, in that case, we have no way to compare the other pointer with. In this case, we simply swap one pointer with the other position.
IP Logged
R
Senior Riddler
****



Addicted!!!

   


Gender: male
Posts: 502
Re: In-place Bit re-arrangement  
« Reply #2 on: Jan 26th, 2010, 12:37am »
Quote Quote Modify Modify

on Feb 28th, 2008, 9:17am, ThePriest wrote:
if suppose number of 0s exceed the number of 1s or vice versa then keep them untouched. Generalize your solution for an N bit number.

Input Number: 0 1 1 0 1 0 1 0 1 1 1 1 1 1 0 0 0
 
output number: 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 1 1
 
The extra 1s here, cannot be left untouched. They will be pushed towards one end.
IP Logged

The first experience seems like Magic, but the second tells you the Trick behind it.
Pages: 1  Reply Reply Notify of replies Notify of replies Send Topic Send Topic Print Print

« Previous topic | Next topic »

Powered by YaBB 1 Gold - SP 1.4!
Forum software copyright © 2000-2004 Yet another Bulletin Board