| Bytes | Lang | Time | Link |
|---|---|---|---|
| 013 | cQuents | 250207T021921Z | Stephen |
| 008 | Japt | 230518T214439Z | Shaggy |
| 062 | Desmos | 250203T222816Z | emanresu |
| 098 | Desmos | 250202T043611Z | DesmosEn |
| 1816 | x8664 machine code | 230203T153053Z | m90 |
| 011 | Uiua | 231108T110358Z | chunes |
| 107 | Scala | 230421T122526Z | 138 Aspe |
| 005 | Thunno 2 M | 230816T103041Z | The Thon |
| 227 | C gcc with lgmp | 230203T235008Z | ErikF |
| 078 | Julia 1.0 | 230217T184134Z | Ashlin H |
| 012 | MATL | 230217T192450Z | Suever |
| 059 | R | 230203T125440Z | Dominic |
| 057 | JavaScript ES6 | 230203T153817Z | Arnauld |
| 057 | Python | 230204T023744Z | loopy wa |
| 006 | Vyxal g | 230204T135954Z | The Thon |
| 061 | C gcc | 230203T123826Z | Noodle9 |
| 060 | Perl 5 ListUtil | 230204T172511Z | Kjetil S |
| 008 | Japt g | 230203T161306Z | noodle p |
| 061 | Python | 230203T162635Z | solid.py |
| 068 | Excel | 230203T085541Z | Jos Wool |
| 073 | Python 2.7 | 230203T175733Z | DaveM552 |
| 005 | Jelly | 230203T162933Z | The Thon |
| nan | Fig | 230203T164846Z | Seggan |
| 095 | Desmos | 230203T163433Z | Aiden Ch |
| 016 | K ngn/k | 230203T163210Z | coltim |
| 043 | Factor | 230203T152423Z | chunes |
| 007 | Husk | 230203T152608Z | Dominic |
| 070 | Zsh | 230203T150511Z | roblogic |
| 018 | Charcoal | 230203T143830Z | Neil |
| 055 | Retina 0.8.2 | 230203T143549Z | Neil |
| 076 | Python 2 | 230203T130944Z | ElPedro |
| 071 | R | 230203T112452Z | pajonk |
| 009 | APL Dyalog Extended | 230203T085234Z | Adá |
| 091 | ><> Fish | 230203T085004Z | mousetai |
| 063 | JavaScript Node.js | 230203T084800Z | l4m2 |
| 073 | Octave | 230203T084231Z | Stewie G |
| 118 | Java 10 | 230203T082645Z | Kevin Cr |
| 016 | J | 230203T081125Z | m90 |
| 006 | 05AB1E | 230203T074307Z | Kevin Cr |
cQuents, 13 bytes
Kmb$
&\RJn);$
Takes advantage of the fact that the minimum is the same in binary and decimal.
Explanation
Kmb$ first line
implicit mode : is sequence 1, outputs the sequence indefinitely
each term is
K from base 2 ( )
m min ( )
b second line ( )
$ current index
&\RJn);$ second line
& mode & is sequence 2, outputs the first n terms in the sequence
each term is
\R ; rotate ( , by )
J ) base 2 of ( )
n n
$ current index
Japt, 8 bytes
ƤéXÃÍÎÍ
ƤéXÃÍÎÍ :Implicit input of integer U
Æ :Map each X in the range [0,U)
¤ : Convert U to binary string
éX : Rotate right by X characters
à :End map
Í :Sort
Î :First element
Í :Convert to decimal
Desmos, 62 bytes
L=floor(log_2n)
i=2^{[0...L]}
f(n)=min((n+mod(n,i)(2^L2-1))/i)
Try it on Desmos (prettified)!
-4 thanks to Aiden Chow (removing backslashes)
This uses some ideas from DesmosEnthusiast's answer (along with stealing its test harness) - go upvote that!
The way this works is that, if we want to shift a L-bit number n left by x bits:
L=8
/------\
11011001
We can multiply the last x bits of the number, i.e. n mod 2^x, by 2^L-1, and add it to the original:
11011001
+ 001
- 001
= 00111011
And then divide by 2^x to get the shifted number, in this case 00111011.
The expression (n+\mod(n,i)(2^L2-1))/i does this - i is a power of 2, and this shifts up the trailing digits then shifts down the whole number. But, instead of applying this to one power of two at a time, we let i be a vector of all the powers of 2 up to n (i=2^{[0...L]}), and this gives an array of all possible rotations which we can then take the minimum of.
Desmos, 98 bytes
f(n)=r(n,n,0,\floor(\log_2n))
r(u,a,i,L)=\{i=L:a,r(t,\min(t,a),i+1,L)\}
t=m2^L+(u-m)/2
m=\mod(u,2)
This program works by simplifying bit rotations to the following logic:
If the least significant bit is 0:
Divide by 2
If the least significant bit is 1:
Subtract 1
Divide by 2
Add most significant bit
For the 177 case, to rotate it to the right, we look at the least significant bit by applying mod(177,2). The resulting 1 tells us the rotated number is (177 - 1) / 2 + 128 = 216. This method is recursively called, and the minimum is passed back. The power of this method is there is no converting to and from binary, and the recursion avoids the need to support list comprehension.
x86-64 machine code, 18 16 bytes
0F BD D7 0F 43 C7 0F B3 D7 D1 D7 39 F8 75 F4 C3
Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes \$n\$ in EDI and returns its smallest bit rotation in EAX.
In assembly:
f: bsr edx, edi # Set EDX to the highest position of a 1 bit in n.
r: cmovnc eax, edi # (EAX will hold the lowest rotation found so far.)
# Set EAX to EDI if CF=0. The first iteration, CF=0 always:
# the value of CF after BSR is officially undefined, but it is
# consistently 0 (as this code needs) on at least some CPUs.
# (To not rely on this, add CLC before this for +1 byte.)
# On later iterations, CF=0 if EDI ≤ EAX (from the cmp).
btr edi, edx # Set the bit at position EDX in EDI to 0.
# Set CF to the previous value of that bit.
rcl edi, 1 # Rotate EDI and CF together left by 1,
# putting the removed bit back in at the end.
cmp eax, edi # Compare EAX and EDI.
jne r # Jump back if they are not equal.
# (Once a value repeats, all possible values have been seen.)
ret # Return.
Scala, 107 bytes
Golfed version. Try it online!
n=>{val b=n.toBinaryString;(0 to b.size-1).map(i=>Integer.parseInt(b.substring(i)+b.substring(0,i),2)).min}
Ungolfed version.
object Main {
def main(args: Array[String]): Unit = {
println(minBinaryRotation(177))
}
def minBinaryRotation(n: Int): Int = {
val binaryString = n.toBinaryString
val rotations = for (i <- 0 until binaryString.length) yield {
val rotated = binaryString.substring(i) + binaryString.substring(0, i)
Integer.parseInt(rotated, 2)
}
rotations.min
}
}
Thunno 2 M, 5 bytes
ḃż€ẒḂ
Explanation
ḃż€ẒḂ # Implicit input
ḃ # Convert to binary
ż # Push [1..length]
€Ẓ # Rotate right
Ḃ # Convert from binary
# Take the minimum
# Implicit output
C (gcc) with -lgmp, 233 231 227 bytes
- -6 thanks to ceilingcat
As it uses the GMP library, the maximum integer that this function handles is quite large. Takes a number as a string to avoid overflowing native types.
#import<gmp.h>
f(s,v,w,x,y)char*s,*v;{mpz_t c,l;mpz_init_set_str(c,s,10);mpz_init(l);for(y=x=strlen(v=mpz_get_str(0,2,c));y--;mpz_cmp(c,l)>0?mpz_set(c,l):0)w=v[x-1],bcopy(v,v+1,x-1),*v=w,mpz_set_str(l,v,2);gmp_printf("%Zd",c);}
Ungolfed:
#import<gmp.h>
f(s, // input value
v, // bit representation of value
w, // rotated bit
x,y // bit string length and loop counter
)char*s,*v; {
mpz_t c,l; // current lowest value, test value
mpz_init_set_str(c,s,10); // initialize variables
mpz_init(l);
for(
y=x=strlen(v=mpz_get_str(0,2,c)); // initialize bit string
y--;
mpz_cmp(c,l)>0?mpz_set(c,l):0) { // adjust lowest value
w=v[x-1]; // get rotated bit
bcopy(v,v+1,x-1); // rotate
*v=w; // put rotated bit at top
mpz_set_str(l,v,2); // get test value
}
gmp_printf("%Zd",c);
}
Julia 1.0, 84 78 bytes
!x=(c=string(x,base=2);r=keys(c);min((r.|>i->parse(Int,"0b"*(c^2)[i.+r]))...))
cis the bitstring of inputx. Another method would belstrip(bitstring(x),'0').rcontains the indices incand is iterated over the repeated bitstringc^2to get each rotation.mintreats a vectorVas a single value, so the splat operator is used:min(V...). Another method would beminimum(V).
-6 bytes thanks to MarcMush:
- Replace range
1:length(c)with iteratorkeys(c) - Use broadcasting
MATL, 13 12 bytes
:"GB@YSXBvX<
1 byte saved thanks to @lmendo
Try it at MATL Online!
Explanation
% Implicitly grab the input (N)
: % Create an array from [1...N]
" % For each value in the array
G % Grab the input as a number
B % Convert to an array of booleans representing the binary equivalent
@YS % Circularly shift by the loop index
XB % Convert the result from binary to decimal
v % Vertically concatenate the entire stack
X< % Compute the minimum value so far
% Implicitly display the result
R, 62 59 bytes
Edit: -3 bytes thanks to pajonk
\(n,j=2^(0:(i=log2(n))))min(j%*%array(n%/%j%%2,2:3+i)[-1,])
Instead of iteratively rotating bits, we use them to fill a 2D array with one-too-many rows, with recycling, so that each column ends-up with the bits rotated (plus an extra useless row).
We can then use matrix multiplication (%*% in R) with a vector of powers-of-2 to easily calculate the values encoded by each column, and output the minimum one.
JavaScript (ES6), 57 bytes
-2 bytes thanks to @l4m2
n=>(m=g=q=>x--?g(q%2<<Math.log2(n,m=m<q?m:q)|q/2):m)(x=n)
Commented
n => ( // n = input
m = // m = minimum value, initially non-numeric
g = // g is a recursive function taking
q => // the current rotation q
x-- ? // if x is not equal to 0 (decrement it afterwards):
g( // do a recursive call:
q % 2 << // using the number of bits in the original
Math.log2( // input, left-shift the LSB so that it takes
n, // the place of the MSB
m = m < q ? // update m to min(m, q)
m // (this always updates m to q if m is
: // still non-numeric)
q //
) | q / 2 // right-shift all other bits by 1 position
) // end of recursive call
: // else:
m // stop and return m
)(x = n) // initial call to g with q = x = n
Python, 57 bytes
lambda n:int(min(h:=f"{n:b}",*[h:=h[1:]+k for k in h]),2)
Old Python, 58 bytes
lambda n:int(min([h:=f"{n:b}"]+[h:=h[1:]+k for k in h]),2)
Vyxal g, 7 6 bytes
ƛ?b$ǓB
- -1 thanks to a suggestion from Shaggy
Explanation
ƛ?b$ǓB # Implicit input
ƛ # Map over the range:
?b # Get the input in binary
$Ǔ # Rotate ^ ^^ times
B # Convert it back from binary
# g flag gets the minimum of this list
# Implicit output
Previous 7-byter:
b:ż¨VǓB # Implicit input
b # Convert the input to binary
:ż # Duplicate and push range(len(^))
¨V # Map over each element in ^:
Ǔ # Rotate ^^^ ^ places to the left
B # Convert each back from binary
# g flag gets the minimum of this list
# Implicit output
C (gcc), 73 61 bytes
s;l;r;f(n){for(l=r=log2(s=n);r--;s=s<n?s:n)n=n%2<<l|n/2;r=s;}
Saved a whopping 12 bytes thanks to c--!!!
Perl 5 List::Util, 60 bytes
sub{$r=1<<log($x=pop)/log 2;min map$x=$x%2*$r+($x>>1),1..$r}
Japt -g, 10 8 bytes
ƤéX ÍÃñ
Saved 2 thanks to Shaggy
ƤéX ÍÃñ : implicit input number
Æ : map over the range [0, input - 1]:
¤ : the input as a binary string
éX : rotated n places
Í : converted back to a number
à : end map, now we have all rotations
ñ : sort them, ascending
: -g: first element of list (i.e. the lowest rotation)
Python, 61 bytes
-5 bytes thanks to Shaggy and -5 bytes thanks to M Virts.
Takes a positive integer n as input. Outputs its smallest bit rotation in integer form.
lambda n:min(int((a:=f'{n:b}')[i:]+a[:i],2)for i in range(n))
Excel, 81 80 71 68 bytes
=LET(a,DEC2BIN(n),b,LEN(a),c,SEQUENCE(b),MIN(BIN2DEC(MID(a&a,c,b))))
Input n
With many thanks to @KevinCruijssen for the great suggestions and 11-byte improvement!
Python 2.7, 73 bytes
x=bin(input())[2:]
print min([int(x[i:]+x[:i],2)for i in range(len(x))])
Jelly, 5 bytes
BṙRḄṂ
Explanation
BṙRḄṂ # Implicit input (n)
B # Convert n into binary
ṙ # Rotate this string this many times:
R # Each of the numbers in [1..n]
# (this will generate some duplicates, but that's fine)
Ḅ # Convert each one back from binary
Ṃ # Get the minimum of this list
# Implicit output
Fig, \$18\log_{256}(96)\approx\$ 14.816 bytes
[KeBtLbxGWbxO'J]xq
Fig is missing a few important builtins, so this is longer than expected.
[KeBtLbxGWbxO'J]xq
bx # Get the binary form of this number
GW # Generate an infinite list from the binary
O' # Using the function...
J]xq # Rotate by prepending the last element to the tailless list
Lbx # Length of the binary representation
t # Take that many items from the infinite list
eB # Convert each from binary
K # Sort ascending
[ # Take the first element (i.e. the minimum one)
Desmos, 95 bytes
L=[floor(log_2N)...0]
B=mod(floor(N/2^L),2)
f(N)=[total(join(B[i+1...],B[1...i])2^L)fori=L].min
Even worse than the fish answer... at least it beats Java :P
K (ngn/k), 16 bytes
&/2/'{1_x,*x}\2\
2\convert (implicit) input to its binary representation{1_x,*x}\build a list of all rotations of the bits2/'convert each back to its decimal representation&/calculate, and (implicitly) return the minimum
Factor, 43 bytes
[ >bin all-rotations [ bin> ] map infimum ]
>bin ! convert input from decimal to a binary string
all-rotations ! get every rotation as a sequence of strings
[ bin> ] map ! convert each to decimal from binary
infimum ! get the smallest one
Husk, 7 bytes
ḋ▼U¡ṙ1ḋ
ḋ # convert to bits,
¡ # make infinite list by repeatedly
ṙ1 # rotating by one position,
U # get the longest unique prefix,
▼ # get the minimum of this,
ḋ # and get the value from the bits.
Charcoal, 18 bytes
≔⍘N²θI⍘⌊Eθ⭆θ§θ⁺κμ²
Try it online! Link is to verbose version of code. Explanation:
≔⍘N²θ
Convert the input to binary.
I⍘⌊Eθ⭆θ§θ⁺κμ²
Generate all of the rotations, take the minimum, and convert back to decimal.
Retina 0.8.2, 55 bytes
.+
$*
+r`\1(1+)
0$1
10
1
.
$&$'$`¶
1
10
+`01
110
O`
\G1
Try it online! Explanation:
.+
$*
Convert to unary.
+r`\1(1+)
0$1
10
1
Convert to mirrored binary i.e. LSB first, MSB last.
.
$&$'$`¶
Generate all of the rotations.
1
10
+`01
110
Convert each rotation back to unary.
O`
Sort.
\G1
Convert the shortest to decimal.
Python 2, 76 bytes
i,o=bin(input())[2:],[]
for x in i:i=i[-1]+i[:-1];o+=[int(i,2)]
print min(o)
Python2 because it accepts integers directly as input (no int() required) and it saves a space on the print statement by not needing brackets.
R, 80 78 75 71 bytes
f=\(n,b=2^(0:log2(n)),x=n%/%b%%2)if(n)min(x%*%b,f(n-1,b,c(x[-1],x[1])))
Recursive function that in every iteration rotates the binary representation by one place and keeps track of the minimum value.
APL (Dyalog Extended), 9 bytes
Anonymous tacit prefix function.
⌊/⍳⊥⍤⌽¨⊤¨
⌊/ the smallest (lit. minimum-reduction) of
⍳…¨⊤¨ for each integer in the range 1 through \$n\$, combined with the binary representation of \$n\$:
…⍤⌽ rotate that representation that integer steps left, and then:
⊥ convert back to a regular number
><> (Fish), 91 bytes
i0$1>:@$:@)?!v\
;n\^@+1$*2@ <r
$@:\?=@:$@:r-1/&~$?)@:&:
2+*2~v?:}:{%2:/.2b-%1:,
1$*2$/.38-
Instead of counting how many iterations happened, which would be expensive, this exits if the current value equals the minimum value.
JavaScript (Node.js), 63 bytes
x=>'0b'+[...y=x.toString(2)].map(t=>y=y.slice(1)+t).sort()[0]-0
t keeps being the needed digit
Octave, 73 bytes
It's not pretty, and it doesn't work on TIO. But it works in the program itself.
x=de2bi(k=input(''));for i=1:k,[ans,bi2de(circshift(x',i)')];end,min(ans)
x=de2bi(k=input(''));for i=1:k,[ans,bi2de(circshift(x',i)')];end,min(ans)
k=input('') % Take input, k = 177
x=de2bi(k=input('')); % Convert input to binary, k = [1 0 0 0 1 1 0 1],
% x = 177
for i=1:k,[...];end % Do k times (177 times)
% Shortest way to make something happen enough times
circshift(x',i)') % Transpose x to make a vertical vector
% Shift it i times, and transpose it back
% Must be transposed for circshift to work
bi2de(circshift(x',i)') % Convert to decimal
[ans,bi2de(...)] % Concatenate into a long vector 'ans'
min(ans) % The minimum of this vector
Java 10, 118 bytes
n->{var b=n.toString(n,2);for(int l=b.length(),i=l,t;i-->0;n=t<n?t:n)t=n.parseInt((b+b).substring(i,i+l),2);return n;}
Input \$n\$; outputs the smallest bit rotation.
Explanation:
n->{ // Method with Integer as both parameter and return-type
var b=n.toString(n,2); // Convert the input-integer to a binary-String
for(int l=b.length(), // Set `l` to the length of this binary-String
i=l,t;i-->0 // Loop `i` in the range (l,0]:
; // After every iteration:
n=t<n? // If `t` is smaller than `n`:
t:n) // Set `n` to this new minimum `t`
t= // Set `t` to:
n.parseInt( // The following binary converted to a base-10 integer:
(b+b) // Append the binary-String to itself
.substring(i,i+l) // And then get its substring in the range [i,i+l)
,2);
return n;} // Return the modified `n` holding the smallest result
J, 16 bytes
[:<./2#.i.|."{#:
#:: Convert \$n\$ to binary.i.|."{:i.makes a list of the integers from 0 (inclusive) to \$n\$ (exclusive), then|.uses that to rotate the binary expansion of \$n\$, with its ranks being set (") to the ranks of{so that it takes each integer as a separate rotation.2#.: Convert back from binary expansions to numbers.[:<./: Take the minimum, using a 'cap' to do so monadically.
05AB1E, 6 bytes
bā._Cß
Input \$n\$; outputs the smallest bit rotation.
Try it online or verify all test cases.
Both the \$[1,n]\$ list with an input \$n\$ and infinite list would be 2 bytes longer with a leading Lε or ∞ε respectively.
Try the infinite version online.
Explanation:
b # Convert the (implicit) input-integer to a binary-string
ā # Push a list in the range [1,length] (without popping the string)
._ # Map each integer v in the list to a v-times (left-)rotated version of the
# binary-string
C # Convert each binary-string in the list back to an integer
ß # Pop and leave the minimum
# (which is output implicitly as result)
