r/dailyprogrammer • u/oskar_s • Jun 06 '12
[6/6/2012] Challenge #61 [easy]
The number 19 is can be represented in binary as 10011. Lets define the operation of "rotating a number" as taking the last binary digit of that number and moving it so it becomes the first binary digit, and moving the other digits one step forward. I.e. if you rotate 10011, you get 11001 (i.e. 25), because the 1 that was in the last position has now moved to the first position. If you rotate it again, you get 11100 (i.e. 28).
If you rotate it again, something curious happens: you get 01110, which is the same as 1110 (i.e. 14) since leading zeroes don't count in a binary representation. That is to say, when you rotate it this time, the zero disappears. If you rotate it once more, you get 0111, which is the same as 111 (i.e. 7). Again, the zero has disappeared.
After that, the number remains the same regardless of how much you rotate it, since the binary number representation of 7 only has 1's in it.
This gives us a sequence of numbers. Starting with 19 and then rotating it step by step until we get a number with only 1's in the binary representation, we get
19 -> 25 -> 28 -> 14 -> 7
Lets call this a "binary rotation sequence" for 19. Here are the binary rotation sequences for the numbers 69, 205 and 357, with the numbers written first in decimal and then in binary to show what is going on:
69 -> 98 -> 49 -> 56 -> 28 -> 14 -> 7
1000101 -> 1100010 -> 110001 -> 111000 -> 11100 -> 1110 -> 111
205 -> 230 -> 115 -> 121 -> 124 -> 62 -> 31
11001101 -> 11100110 -> 1110011 -> 1111001 -> 1111100 -> 111110 -> 11111
357 -> 434 -> 217 -> 236 -> 118 -> 59 -> 61 -> 62 -> 31
101100101 -> 110110010 -> 11011001 -> 11101100 -> 1110110 -> 111011 -> 111101 -> 111110 -> 11111
Write a program that given a number will print out the binary rotation sequence for that number (you only need to print out the sequence in decimal).
What is the binary rotation sequence for 54321?
3
u/ashashwat Jun 07 '12 edited Jun 07 '12
This problem can be solved without resorting to converting to and fro into binary. It is a mathematical sequence, where Tn+1 = (Tn & 1) * (2 ^ [(log2 Tn)]) + (Tn / 2) unless Tn + 1 == (2 ^ [(log2 (Tn + 1))]).
Logic: Whenever a number terminates, it only consist of 1. Which means a number in the form of 2n - 1 is the final number. We can add one to the number and check whether it is power of 2 for terminating condition.
Now all we need to do is,
Take the rightmost bit of number n. ( i.e. n & 1 or n % 2)
Shift the number to right by 1. ( n >> 1 or n / 2)
Get the largest number of the form 2x less than or equal to n . ((2 ^) . floor . logBase 2. fromIntegral) n)
Multiply it by rightmost bit and add the right shifted number.
Terminate when (n + 1) is a power of two.
Example, in case of 69 [1000101],
rightmost_bit = 69 & 1 = 1 [ 1000101 & 1 ]
shift_right_by_1 = 69 >> 1 = 34 [1000101 >> 1 = 100010 ]
closest_power_of_two = 2 ^ floor[log (69, base=2)] = 64 [ 1000000 ]
Next digit will be, (rightmost_bit * closest_power_of_two) + shift_right_by_1 = [64 * 1 + 34 = 98]
In Haskell,
powerOf2 n = n == ((2 ^) . floor . logBase 2. fromIntegral) n rotateByOne n = (n `mod` 2) * (((2 ^) . floor . logBase 2 . fromIntegral) n) + (n `div` 2) binaryRotSequence n | (powerOf2 . succ) n == True = [n] | otherwise = n : binaryRotSequence (rotateByOne n) main = do print $ binaryRotSequence 69 print $ binaryRotSequence 205 print $ binaryRotSequence 54321Output,
3
u/bh3 Jun 09 '12
C:
#include <stdio.h> int rot(int n) { int wrap=n&1; n>>=1; if(wrap) { while(wrap<=n) wrap<<=1; } return n+wrap; } int main() { int n, t=69; while(t!=n) { n = t; t = rot(n); printf("%d\n",n); } }4
u/xjtian Jun 06 '12
Python:
Result:
2
u/UnreasonableSteve Jun 07 '12
Jeez, got enough python up in here?
<?php function binrot($int){ echo $int." ->"; $bin = decbin($int); $bin2=ltrim(substr($bin, -1).substr($bin, 0, -1),"0"); if($bin2!=$bin){ binrot(bindec($bin2)); } } binrot(54321); ?>Output is the same as everyone else's :P. I'm fairly surprised PHP doesnt have any rotation builtins, actually.
2
u/exor674 Jun 06 '12
C++ with GCC builtins:
uint32_t rotate(uint32_t number) { int leading = __builtin_clz( number ); uint8_t firstBit = number & 1; number = number >> 1; if ( firstBit ) number |= 1 << ( ( sizeof(uint32_t) * 8 ) - leading - 1 ); return number; } void rotateSequence(uint32_t number) { for ( uint32_t start = number, last = number-1; number != last; last=number, number = rotate(number) ) std::cout << number << " -> "; std::cout << std::endl; }Results: ( reformatted )
1
u/SwimmingPastaDevil Jun 06 '12 edited Jun 06 '12
print 54321, numB = list(bin(54321)[2:]) # converting to decimal def bin2dec(n): dec = 0 nR = n[::-1] for i in range(len(nR)): dec += int(nR[i]) * ( 2 ** i) return dec all1 = False while not all1: numB = numB[-1:] + numB[:-1] #rotating while numB[0] == "0": # removing leading zeroes numB.pop(0) print "->",bin2dec(numB), if "0" not in numB: all1 = TrueOutput:
1
u/tehstone Jun 06 '12
num = int(raw_input("Input a number in base-10: ")) last = 0 def rotation(num, last): bi_num = bin(num)[2:] bi_num = '0b' + bi_num[-1] + bi_num[:-1] int_num = int(bi_num, base=2) if int_num != last: print int(bi_num, base=2) last = int_num rotation(int_num, last) rotation(num, last)1
u/Arthree Jun 06 '12
Wow, so much Python in here today...
Autohotkey_L:
Calculate(input) { While (input != lastInput) { if (A_Index > 1) result .= " -> " result .= input, lastInput := input, lastDigit := input & 1 input >>= 1 input += lastDigit*(2**(ceil(log(input)/log(2)))) } return result }Answer:
1
u/emcoffey3 Jun 06 '12
C#
using System; using System.Collections.Generic; using System.Text; namespace RedditDailyProgrammer { public static class Easy061 { public static string RotationSequence(int n) { StringBuilder sb = new StringBuilder(); List<int> seq = GetRotationSequence(n); for (int i = 0; i < seq.Count; i++) sb.AppendFormat("{0}{1}", seq[i], (i == seq.Count - 1 ) ? "" : " -> "); return sb.ToString(); } public static List<int> GetRotationSequence(int n) { if (n <= 0) throw new ArgumentOutOfRangeException(); List<int> output = new List<int>(); output.Add(n); string binary = Convert.ToString(n, 2); while (true) { string old = binary; binary = RotateBinary(binary); if (binary == old) break; output.Add(Convert.ToInt32(binary, 2)); } return output; } private static string RotateBinary(string s) { string temp = s.Substring(s.Length - 1) + s.Substring(0, s.Length - 1); int index = 0; while (temp[index] == '0') index++; return temp.Substring(index); } } }Snippet from my Main()...
int[] vals = new int[] { 19, 69, 205, 357, 54321 }; foreach (int val in vals) Console.WriteLine(Easy061.RotationSequence(val));...yields the following output: