| Bytes | Lang | Time | Link |
|---|---|---|---|
| 094 | Raku 93 chars | 250612T001159Z | Mark Ree |
| 008 | Jelly | 161102T091452Z | Jonathan |
| 008 | Vyxal | 250612T094634Z | emanresu |
| 103 | C | 161102T155942Z | Noodle9 |
| 024 | J | 181217T114838Z | Olius |
| 103 | Labyrinth | 161103T165907Z | Robert H |
| 359 | C# | 161104T171727Z | Yodle |
| 065 | Ruby | 161102T182351Z | Cyoce |
| 115 | Python 2 | 161102T110245Z | Karl Nap |
| 070 | Ruby | 161104T032928Z | philomor |
| 105 | C | 161102T183724Z | cleblanc |
| 075 | Python 2 | 161102T120403Z | Dennis |
| 018 | CJam | 161102T230603Z | Linus |
| 012 | Pyth | 161102T222838Z | TheBikin |
| 065 | Perl | 161102T123117Z | Dom Hast |
| 082 | JavaScript | 161102T124022Z | ETHprodu |
| 095 | Python 3 | 161102T143406Z | Jimmy Jo |
| 116 | Retina | 161102T150104Z | mbomb007 |
| 107 | PHP | 161102T100318Z | Titus |
| 158 | PowerShell v2+ | 161102T132637Z | AdmBorkB |
| 097 | Haskell | 161102T103930Z | Angs |
| 099 | Mathematica | 161102T103111Z | LegionMa |
| 013 | MATL | 161102T100702Z | Luis Men |
| 018 | 05AB1E | 161102T094200Z | Emigna |
| 014 | Actually | 161102T093010Z | user4594 |
Raku (93 chars, 94 bytes)
$_=[~] get.comb».&{sprintf '%08b',.ord};repeat
{say .parse-base(2);s/^0*//;tr/01/10/}while $_
Jelly, 15 10 8 bytes
-5 bytes thanks to @Dennis (convert directly from base 256 after ordinal cast)
-2 bytes using language features added after the challenge was posted
Oḅ⁹BCḄƊƬ
How?
Oḅ⁹BCḄƊƬ - Main link: s e.g. "Inf"
O - cast to ordinals e.g. [73,110,102]
ḅ⁹ - convert from base 256 to integer e.g. 4812390
Ƭ - loop until no longer unique and collect results applying:
Ɗ - last three links as a monad:
B - convert to binary
C - complement
Ḅ - convert to integer
Vyxal, 8 bytes
C₈β≬b†B↲
C # Convert to a list of charcodes
₈β # And convert from base 256
≬---↲ # Collecting until the result no longer changes:
b # convert from binary
† # toggle each bit
B # and convert to binary again
C, 147 135 133 125 122 121 117 115 103 bytes
Saved 5 bytes thanks to @Cyoce!
Saved 2 bytes thanks to @Cyoce and @cleblanc!
Saved 12 bytes thanks to @ceilingcat
i,n;main(p,v)char**v;{while(*v[1])i=i*256+*v[1]++;for(;printf("%d\n",n=i),i;i^=p-1)for(p=2;n/=2;)p*=2;}
Ungolfed:
int i;
int main (c,v) {
char**v;
while (*v[1]) /* put first command line argument into i as binary */
i = i*256 + *v[1]++;
while (i != 0) {
printf("%d\n",i);
int p = 2,n = i;
while (n /= 2) /* calculate smallest power of 2 > i */
p *= 2;
i ^= p - 1; /* flip bits */
}
}
J, 24 bytes
256-.&.#:^:*^:a:@#.a.&i.
Explanation will come later!
Labyrinth, 104 103 bytes
' )25 }_';:_';_2/;{
''', 6 2 1 1 { (
' | / _ _ _}*2_ $
* _ :!\ }2_\ !:
652 @'''''''
Explanation:
The instruction pointer starts at the top-left most non-wall character (walls include spaces and any letter except v).
Orange:
This loop gets the input one character at a time as an ASCII code, adding it to the current value and multiplying the current value by 256.
'No-op,Push the ascii code of the next input char to the top of the stack or -1 if EOF. At this point if input was received, the code will turn right (moving down) because the top of the stack is potive. Otherwise it will turn left because the top of the stack is negative.|Pop the top two items from the stack and push the result of a bitwise OR._Push zero256Each digit seen popsxand pushesx*10+digit. So this combined with the push zero previous push 256 to the top of the stack.*Popy, popx, pushx*y. At this point since the top of the stack is positive the code will turn right to continue around the loop.
Blue:
)Increment the top of the stack. When the end of input is reached, the code will turn left to get to this point with a -1 on the stack which will get incremented to zero.256Having the top of the stack 0 allows us to push this 256./Popy, popxpushx/y(integer division). Since we were multiplying the input by 256 each loop, we need to revert the last multiplication.:Duplicate the top of the stack so we have a copy of the current value for later.!Pop the top of the stack and print the integer value to STDOUT.\Print a new line._2Push a two to the top of the stack.}Move the top of the stack to the top of the auxiliary stack.
Red:
This loop flips the bits of the current value by XOR with a particular value calculated in the inner (green) loop. It then outputs the current value and exits the program if the current value is zero.
_Push zero (control flow).;Discard the top of the stack (control flow).:Duplicate the current value. The copy will be used to calculate the XOR._Push zero (control flow).- (Green loop)
$Popy, popx, Pushx XOR y.:!Duplicate the current value and print the integer representation.- If the current value is 0, we continue straight into the
@and terminate. \Print a new line._2}Push 2 and move to the aux stack._1Push 1 (control flow).
Green:
This loop calculates the value by which we need to XOR the current value. This is done by repeatedly doubling the top of the auxiliary stack while halving a copy of the current value on the stop of the main stack until it reaches 0.
_Push zero (control flow).;Discard the current value which is only used to enforce control flow._2Push 2 in order to halve the current value./Divide{Move the top of the aux stack to the top of the main stack._2*Double the top of the stack}Move the top of the main stack back to the aux stack._1Push one for control flow.- After exiting the loop:
;Discard the left over zero from calculating the XOR.{Move the calculated XOR to the main stack.(Subtract one from XOR value.
C#, 360 359 bytes
using w=System.Console;using q=System.Convert;s={System.Func<int,int,string>S=q.ToString;string t="",f="";for(int i=0;i<s.Length;i++)t+=i>0?S(s[i],2).PadLeft(8,'0'):S(s[i],2);w.WriteLine(q.ToInt64(t,2).ToString());while(t!="0"){f="";foreach(var n in t)f+=n=='0'?'1':'0';t=f.TrimStart(new char[]{'0'});t+=t==""?"0":"";w.WriteLine(q.ToInt64(t,2).ToString());}};
Full program:
using w = System.Console;
using q = System.Convert;
class a
{
static void Main()
{
System.Action<string> b = s =>
{
System.Func<int,int,string> S = q.ToString;
string t = "", f = ""; // Var does not work here
for(int i = 0; i < s.Length; i++)
t += i > 0 ? S(s[i], 2).PadLeft(8, '0') : S(s[i], 2);
w.WriteLine(q.ToInt64(t, 2).ToString());
while(t != "0")
{
f = "";
foreach (var n in t) f += n== '0' ? '1' : '0';
t = f.TrimStart(new char[] { '0' });
t += t == "" ? "0" : "";
w.WriteLine(q.ToInt64(t, 2).ToString());
}
};
b("Inf");
b("Infinity");
w.Read(); // prevent close in VS
}
}
Ruby, 104 101 100 81 80 65 bytes
19 bytes saved thanks to @WayneConrad!
15 Bytes saved thanks to @philomory!
1 byte saved thanks to @LeeW!
p n=$*[0].unpack('B*')[0].to_i(2)
p n^=2**n.bit_length-1while n>0
Takes input via command line arguments.
Inspired by @JimmyJohnson's Python answer
Python 2, 117 115 bytes
Saving 2 bytes thanks to Cyoce.
Assumes input enclosed in quotes, e.g. "Inf"
s=input()
n=sum(ord(s[-i-1])<<i*8for i in range(len(s)))
while n:
print n;k,m=n,1
while k:k/=2;m*=2
n^=m-1
print 0
m counts up to the highest digit, so m-1 is a XOR mask to perform the desired operation. The longest part is converting the input into the initial bit sequence.
Example:
"Inf"
4812390
3576217
618086
430489
93798
37273
28262
4505
3686
409
102
25
6
1
0
"Infinity"
5291279215216915577
3932092821637860230
679593196789527673
473328307817319302
103132444486104185
40982743589751686
31074850448176249
4953946570787718
4053252683953273
450346943417222
112603010004089
28134478351238
7049893737593
1746199284614
452823970937
96931842950
40507110521
28212366214
6147372153
2442562438
1852404857
295078790
241792121
26643334
6911097
1477510
619641
428934
95353
35718
29817
2950
1145
902
121
6
1
0
Ruby - 70 bytes
λ cat inf.rb
n,=$*[0].unpack 'B*';loop{p n.to_i(2);n.tr!('10','01').sub!(/^0*/,'')}
λ ruby inf.rb Hello
310939249775
788572378000
310939249775
238816564112
36061342831
32658133904
1701604463
445879184
90991727
43226000
23882863
9671568
7105647
1282960
814191
234384
27759
5008
3183
912
111
16
15
0
inf.rb:1:in `block in <main>': undefined method `sub!' for nil:NilClass (NoMethodError)
from inf.rb:1:in `loop'
from inf.rb:1:in `<main>'
The program exits with an exception after completing, but my understanding is that that is fine as long as the error output goes to STDERR rather than STDOUT (which it does).
C, 129 120 117 110 107 105 Bytes
long long i,m,n;f(char*v){for(;*v;i<<=8,i+=*v++);for(;printf("%llu,",i),n=i;i^=m-1)for(m=2;n>>=1;m<<=1);}
Tested with
main (int c, char**v) {
f(v[1]);
}
output
5291279215216915577,3932092821637860230,679593196789527673,473328307817319302,103132444486104185,40982743589751686,31074850448176249,4953946570787718,4053252683953273,450346943417222,112603010004089,28134478351238,7049893737593,1746199284614,452823970937,96931842950,40507110521,28212366214,6147372153,2442562438,1852404857,295078790,241792121,26643334,6911097,1477510,619641,428934,95353,35718,29817,2950,1145,902,121,6,1,0,
Python 2, 89 82 77 76 75 bytes
n=0
for c in input():n=n<<8|ord(c)
while 1:print n;n^=2**n.bit_length()-n/n
Test it on Ideone.
How it works
After initializing n to 0, the second line performs the string-to-integer conversion specified in the challenges as follows.
In each step, n is shifted 8 units to the left, then bitwise OR-ed with the the code point of the next character c. For input Inf, this goes as follows.
n 0
a = n<<8 0
b = 'I' 1001001
n = a ^ b 1001001
a = n<<8 100100100000000
b = 'n' 1101110
n = a ^ b 100100101101110
a = n<<8 10010010110111000000000
b = 'f' 1100110
n = a ^ b 10010010110111001100110
Now we're ready to generate the output. To invert the bits of n, we proceed as follows.
First, we compute the bits in n's binary representation without leading zeroes. Let's call the result k. Then, we compute the kk power of 2, which has k+1 binary digits: a single 1, followed by k 0's. We subtract 1 from the result, yielding a number composed of k ones, which we then XOR with n to invert its bits. For input inf this goes as follows.
n 4812390 10010010110111001100110
k 23
t = 2**k 100000000000000000000000
t -= 1 11111111111111111111111
n ^= t 3576217 1101101001000110011001
k 22
t = 2**k 10000000000000000000000
t -= 1 1111111111111111111111
n ^= t 618086 10010110111001100110
.
.
.
n 6 110
k 3
t = 2**k 1000
t -= 1 111
n ^= t 1 1
k 1
t = 2**k 10
t -= 1 1
n ^= t 0 0
On additional hurdle in the implementation is that we have to print n before the first step, after the last step, and in all steps in between. Python doesn't have do-while loops and a single print statement costs 8 bytes, so we do the following instead.
In the straightforward implementation of the update step, i.e.,
while n:print n;n^=2**n.bit_length()-1
print n
we replace the loop with an infinite one (while 1) and compute the 1 in the loop as n/n. This is equivalent while n > 0.
Once n = 0, we stay in the loop, print the state once more, then try to update it. However, 0/0 triggers a ZeroDivisionError, breaking out of the loop and exiting with an error. Note that this causes stray output to STDERR, which is allowed by default.
CJam, 17 16 18 bytes
q256b0{_p2b:!2bj}j
q256b e# read printable ascii to integer
0 e# value for terminal case
{ e# recursive function
_p e# print current number
2b e# create binary representation with no leading zeros
:! e# flip bits
2b e# convert binary back to integer
j e# recursive call
}j e# end
NOTE: The old 16 byte version didn't behave correctly with empty strings:
q256b{_p2b:!2b}h
Also, thanks to Dennis for suggesting p which saves 1 byte over N\ putting newlines into the stack.
Pyth, 12 bytes
.usi!MjN2 2C
A program that takes input of a quoted string and prints the result as a list of integers.
How it works
.usi!MjN2 2C Program. Input: Q
C Convert Q to an integer by code-points using base-256 (implicit input)
.u Apply the following function A(N) until a repeat occurs, storing the results
in a list:
jN2 Convert to binary as a list
!M Map negation over the above
i 2 Convert from binary to integer
s Integer (Converts final False to 0)
Implicitly print
Perl, 65 bytes
53 bytes code + 12 for -Mbigint -p.
Thanks to @Dada for saving me 13 bytes!
$_=unpack"B*";say(0+"0b$_"),s/^0+//,y/10/01/while$_>0
Fairly straightforward approach, only different to most of these is that the number is stored as binary and printed out in decimal. I'm sure it can be improved, perhaps with storing details in an array. -Mbigint is a bit inconvenient but necessary.
Usage
echo -n 'Inf' | perl -Mbigint -pE'$_=unpack"B*";say(0+"0b$_"),s/^0+//,y/10/01/while$_>0'
4812390
3576217
618086
430489
93798
37273
28262
4505
3686
409
102
25
6
1
0
echo -n 'Infinity' | perl -Mbigint -pE'$_=unpack"B*";say(0+"0b$_"),s/^0+//,y/10/01/while$_>0'
5291279215216915577
3932092821637860230
679593196789527673
473328307817319302
103132444486104185
40982743589751686
31074850448176249
4953946570787718
4053252683953273
450346943417222
112603010004089
28134478351238
7049893737593
1746199284614
452823970937
96931842950
40507110521
28212366214
6147372153
2442562438
1852404857
295078790
241792121
26643334
6911097
1477510
619641
428934
95353
35718
29817
2950
1145
902
121
6
1
0
JavaScript, 82 bytes
Saved a byte thanks to @Arnuald
for(y of prompt(n=0))n=n<<8|y.charCodeAt()
for(;alert(n)|n;)for(i=1;i<=n;i*=2)n^=i
One of the very few times when a full program outperforms a function (and ES6 does not outperform ES5)...
The above supports up to 4-letter words. Add 4 bytes to support up to 6-letter words:
for(y of prompt(n=0))n=n*256+y.charCodeAt()
for(;alert(n)|n;n=i-n-1)for(i=1;i<=n;)i*=2
Python 3, 99 95 bytes
x=int.from_bytes(bytes(input(),'utf-8'),'big')
while x:print(x);x^=2**x.bit_length()-1
print(0)
Main idea is to convert string to bytes to to number. Each iteration print the output and XOR with all 1s to progress towards zero.
Retina, 116 bytes
Byte count assumes ISO 8859-1 encoding. Line 5 contains non-printable bytes. It's T`\x00-\xFF.
-2`
±
s{`±(.)
$&$1
}T`-`_o`±.
[^±]+
$.&
±
\d+
$*
+`(1+)\1
${1}0
01
1
{*(`1
01
+`10
011
^0+
)M`1
^0+
T`01`10
Don't try this with input longer than two characters. (It times out using the online interpreter.) We gotta convert the binary to unary before decimal. :D
Unfortunately, there's a trailing zero and linefeed, but I decided to assume that was okay because the output is still correct.
Explanation
-2` # Convert ASCII to decimal (ord)
±
s{`±(.)
$&$1
}T`-`_o`±.
[^±]+
$.&
±
\d+ # Decimal to binary
$*
+`(1+)\1
${1}0
01
1
{*(`1 # Loop; Loop print and undo; Convert binary to unary
01
+`10
011
^0+
)M`1 # Unary to decimal; End print and undo
^0+ # Remove leading zeros
T`01`10 # Flip bits; (implicit loop end)
PHP, 132 126 123 120 108 107 bytes
foreach(unpack("C*",$argv[1])as$i)$n=$n*256+$i;for(print$n;$n;)echo _.$n=bindec(strtr(decbin($n),"01",10));
- printing 0 after loop instead of initial value before loop saves 6 bytes.
unpackinstead ofstr_splitrendersord()obsolete -> -3 bytes- underscore
_as separator saves 3. bindecinstead ofltrimto remove leading zeroes: -12echoin loop body saves 1 byte overprintin loop head.
PowerShell v2+, 158 bytes
for($a=-join([char[]]$args[0]|%{([int][convert]::ToString(+$_,2)).ToString('0'*8)});$a){[convert]::ToInt64($a,2);$a=$a.TrimStart('0')-split0-replace1,0-join1}
Yeah, so, converting bases in PowerShell is really sucky. And we get to do it twice here.
OK, so this is just a for loop on $a -- i.e., we loop so long as $a exists. We'll eventually reach an empty string (which is falsey), so that's how we'll terminate.
The setup of the loop, $a=-join([char[]]$args[0]|%{([int][convert]::ToString(+$_,2)).ToString('0'*8)}), takes the input $args[0], casts it as a char-array, and loops through each character. We use the .NET [convert]::ToString(int,base) to convert each to a binary string. However, that doesn't include leading zeros, so we need to re-cast that string as an [int] and call its .ToString() method with 8 zeros as the mask. Then those strings are encapsulated in parens and -joined together, then saved into $a.
Inside the loop, we [convert]::ToInt64(string,base) to convert the binary number to a decimal number. That gets left on the pipeline and is subsequently flushed when the loop resets (and therefore implicitly printed). The next section performs the calculations -- we .TrimStart() to remove any leading zeros, -split0 to split on zeros and get a string-array of 1s, -replace those ones with zeros, and finally -join the array back together with 1s. Then, the loop begins again.
PS C:\Tools\Scripts\golfing> .\count-down-from-infinity.ps1 'PPCG'
1347437383
800046264
273695559
263175352
5260103
3128504
1065799
1031352
17223
15544
839
184
71
56
7
0
Haskell, 109 123 118 102 97 bytes
Thanks to @nimi for saving 5 bytes!
c 0=0
c n=1-mod n 2+2*c(div n 2)
(++[0]).fst.span(>0).iterate c.foldl((+).(256*))0.map fromEnum
Usage: (++[0]).fst.span(>0).iterate c.foldl((+).(256*))0.map fromEnum $ "Infinity"
Guaranteed to work on numbers up to 29 bits by the language, usually works up to 63-bit numbers on 64-bit systems. Use map(fromIntegral.fromEnum) instead (+14 bytes) to support arbitrarily large numbers.
Works for unicode range [0..255]. Recursively flips bits.
Mathematica, 99 bytes
a=FromDigits;b=IntegerDigits;NestWhileList[a[1-#~b~2,2]&,a[Join@@b[ToCharacterCode@#,2,8],2],#>0&]&
Anonymous function. Takes a string as input, and returns a list of numbers as output.
MATL, 13 bytes
8W:qZA`tB~XBt
Explanation
8W:q % Push array [0 1 ... 255]
ZA % Take input string and convert it from the base defined by the
% alphabet [0 1 ... 255] to decimal
` % Do...while
t % Duplicate
B % Convert to binary
~ % Negate
XB % Convert to decimal
t % Duplicate. Used as loop condition: exit if zero
05AB1E, 18 bytes
Uses CP-1252 encoding.
Çžz+b€¦J[CÐ,_#bS_J
Explanation
Ç # convert string to list of ascii codes
žz+ # add 256 to each
b # convert to binary
€¦ # remove the first digit of each list of digits
J # join
[ # start loop
C # convert to decimal
Ð # triplicate
, # print 1 copy
_# # if the 2nd copy is 0, break loop
b # convert 3rd copy to binary
S # split to list
_ # negate each in list
J # join
Actually, 14 bytes
2@├¿W■├♂≈♂Y2@¿
Explanation:
2@├¿W■├♂≈♂Y2@¿
@├ encode input in binary
2 ¿ convert from binary to decimal
W while the number is not 0:
■ print the number without popping
├ convert number to binary
♂≈ convert each character to an int
♂Y boolean negate each int
2@¿ convert from binary to decimal
