| Bytes | Lang | Time | Link |
|---|---|---|---|
| 035 | Tcl | 170202T003645Z | sergiol |
| nan | Piet + asciipiet | 241108T100825Z | Aiden Ch |
| 016 | Knight v1 | 241108T023635Z | Aiden Ch |
| 026 | Bash | 241025T061140Z | roblogic |
| 044 | BrainChild | 241101T041215Z | ATaco |
| 005 | iogii | 241028T013106Z | Unrelate |
| 135 | C gcc | 241026T140618Z | jdt |
| 049 | Icon | 241025T081215Z | Galen Iv |
| nan | Bash | 241023T221134Z | Laszlo P |
| 029 | Forth gforth | 241024T133139Z | david |
| 006 | Japt | 241023T151811Z | Shaggy |
| 012 | Rattle | 240725T194805Z | d01 |
| 040 | Setanta | 240723T231802Z | bb94 |
| 014 | Uiua | 240724T071051Z | Europe20 |
| 032 | Swift 5.9 | 240314T235804Z | macOSist |
| 018 | Uiua | 240314T214105Z | Zylviij |
| nan | Pascal | 240314T201502Z | Kai Burg |
| 021 | TurboBasic XL Atari 800XL | 240314T180723Z | Lars |
| 015 | Ruby | 160916T085856Z | Value In |
| 008 | Befunge93 | 230723T151140Z | Joe |
| 1625 | Vyxal | 230719T180010Z | The Empt |
| 058 | C | 160916T141720Z | cleblanc |
| 018 | Commodore Basic | 160916T234722Z | Mark |
| 034 | Fortran GFortran | 230608T123550Z | roblogic |
| 024 | Commodore C64 BASIC | 230608T114223Z | Shaun Be |
| 048 | Kotlin | 220710T080210Z | wartoshi |
| 022 | Regenerate a | 220628T144950Z | Deadcode |
| 208 | Bash | 200505T004535Z | David G. |
| 012 | GolfScript | 210601T233340Z | Soup Gir |
| 005 | Vyxal | 220628T072059Z | emanresu |
| 019 | APOL | 220114T184052Z | Ginger |
| 017 | APL | 220114T153541Z | Jayant C |
| 038 | JavaScript Node.js | 220113T185303Z | Larry Ba |
| 007 | Vyxal | 220113T215308Z | das code |
| 012 | Dyalog APL | 210629T103012Z | AviFS |
| 042 | Pure yash and echo or POSIXcompatible shell | 210602T132425Z | user1004 |
| 032 | AWK | 210601T072659Z | Pedro Ma |
| 014 | convey | 210601T141440Z | ZeroCode |
| 018 | BRASCA | 210512T100904Z | SjoerdPe |
| 008 | Vyxal 5 | 210601T064428Z | Undersla |
| 019 | Jellyfish | 210512T091856Z | Razetime |
| 024 | Julia | 210502T133451Z | MarcMush |
| 014 | Hexagony | 210501T223531Z | Undersla |
| 018 | V vim | 210430T061634Z | Razetime |
| 023 | Add++ v0.2 | 170606T194554Z | caird co |
| 046 | F# .NET Core | 200509T074826Z | user9206 |
| 055 | C | 200423T205206Z | JustinCB |
| 037 | Symja | 200504T233228Z | lyxal |
| 460 | Turing Machine Code | 200503T151730Z | ouflak |
| 037 | Red | 200503T201303Z | Brangles |
| 097 | LaTeX | 200424T175245Z | corvus_1 |
| 007 | cQuents | 200424T031706Z | PkmnQ |
| 008 | MathGolf | 200423T135412Z | Kevin Cr |
| 006 | Pyth | 200201T001516Z | isaacg |
| 065 | W d | 191214T064426Z | user8505 |
| 047 | x8616 | 200118T155304Z | 640KB |
| 032 | Python 2 | 161229T180631Z | SanBot |
| 024 | Runic Enchantments | 191212T205506Z | Draco18s |
| 009 | Keg | 191206T220711Z | lyxal |
| 050 | Wren | 191208T113856Z | user8505 |
| 1614 | GolfScript | 191123T144055Z | user8505 |
| 036 | C gcc | 170201T220515Z | G B |
| 017 | MarioLANG | 191121T164237Z | CoedRhyf |
| 565 | Poetic | 191121T101431Z | JosiahRy |
| 044 | Python 3 | 191003T175618Z | Sagittar |
| 002 | Brachylog | 190409T075724Z | Unrelate |
| 023 | QBasic | 180713T182115Z | Taylor R |
| 092 | Small Basic | 180713T181637Z | Taylor R |
| 048 | Zephyr | 180330T054353Z | DLosc |
| 007 | Gol><> | 180330T052718Z | Bubbler |
| 010 | Japt | 180329T150952Z | Oliver |
| 112 | Scala | 180330T020800Z | firephil |
| 096 | Javascript | 180329T175721Z | Yair Ran |
| 020 | SmileBASIC | 170201T212217Z | 12Me21 |
| 069 | F# | 180328T230640Z | Ciaran_M |
| 095 | Visual Basic .NET Mono | 180328T225843Z | Taylor R |
| 022 | Yabasic | 180328T223923Z | Taylor R |
| 038 | MYBASIC | 180328T225047Z | Taylor R |
| 024 | uBASIC | 180328T224806Z | Taylor R |
| 024 | R | 160916T104511Z | rturnbul |
| nan | Prolog SWI | 160916T090504Z | Emigna |
| 009 | Milky Way | 180221T114130Z | ovs |
| 025 | Coconut | 180221T112250Z | ovs |
| 011 | Pyt | 180217T225159Z | qqq |
| 041 | Appleseed | 180217T220455Z | DLosc |
| 021 | Forked | 180212T050042Z | MD XF |
| 026 | Momema | 180212T031056Z | Esolangi |
| 002 | Husk | 180212T015147Z | Weijun Z |
| 008 | Wumpus | 180211T112811Z | Martin E |
| 004 | Implicit | 170910T030837Z | MD XF |
| 042 | Common Lisp | 171120T140648Z | Renzo |
| 002 | Pyke | 160916T103346Z | Blue |
| 016 | ><> | 171118T072115Z | Bolce Bu |
| 009 | Aceto | 171118T211925Z | qqq |
| 020 | Excel VBA | 161230T124718Z | Taylor R |
| 021 | Triangular | 170615T162533Z | MD XF |
| 019 | Powershell | 160916T133314Z | colsw |
| 025 | JS NON ES6 | 170406T195621Z | user5882 |
| 010 | CJam | 170406T185939Z | Erik the |
| 007 | Pushy | 161224T150504Z | FlipTack |
| 012 | Cubix | 160916T153536Z | ETHprodu |
| 087 | Java 8 | 161205T190157Z | Xanderha |
| 026 | Straw | 161205T181815Z | TuxCraft |
| nan | BrainFlak | 160916T141024Z | Wheat Wi |
| 076 | SQL | 161109T163440Z | Pete Ard |
| 014 | QBIC | 160929T150501Z | steenber |
| 025 | q KDB+ | 161109T142041Z | Adam J |
| 039 | Rust | 161109T125605Z | user6126 |
| 009 | MATL | 160916T093606Z | Sanchise |
| 084 | C++ | 160917T154540Z | oMittens |
| 044 | C | 161013T230618Z | celtschk |
| 227 | Shakespeare Programming Language | 160917T121534Z | Christal |
| 059 | ForceLang | 161010T224303Z | SuperJed |
| 021 | RProgN | 161007T054801Z | ATaco |
| 056 | Racket | 160917T071811Z | rnso |
| 007 | LI | 161004T063111Z | Steven H |
| 018 | Hexagony | 161004T071748Z | Sunny Pu |
| 026 | JavaScript | 160916T100318Z | Arnauld |
| 026 | PHP | 160926T085418Z | aross |
| nan | 160916T135820Z | Crypto | |
| 040 | Python | 160919T145149Z | vpzomtrr |
| 027 | PHP | 160916T094805Z | user5917 |
| 046 | Haxe | 160926T074157Z | Yytsi |
| 118 | Java 7 | 160916T092754Z | Kevin Cr |
| 053 | C# function | 160920T172959Z | Grax32 |
| 331 | C | 160919T172202Z | LambdaBe |
| 029 | R | 160919T124534Z | sebastia |
| 029 | JavaScript ES5 | 160916T124722Z | Paul Sch |
| 049 | Java | 160918T104925Z | Olivier |
| 127 | Brainfuck | 160916T170847Z | primo |
| 009 | Labyrinth | 160917T152452Z | Martin E |
| 010 | Brainfuck | 160917T181304Z | SQB |
| 020 | k | 160917T153806Z | skeevey |
| 074 | C# | 160916T124351Z | alex |
| 012 | Burlesque | 160917T123932Z | mroman |
| 019 | Retina | 160916T120327Z | Martin E |
| 016 | DC GNU or OpenBSD flavour | 160916T094058Z | user1921 |
| 007 | Actually | 160917T075234Z | user4594 |
| 016 | dc | 160917T061608Z | juh |
| 005 | Jelly | 160916T180925Z | Dennis |
| 222 | C# | 160917T025238Z | Grax32 |
| 016 | bc | 160916T180449Z | seshouma |
| 026 | Bash + GNU utilities | 160916T230338Z | Digital |
| 018 | Powershell | 160916T124057Z | whatever |
| 015 | ><> | 160916T104855Z | Sok |
| 046 | bash | 160916T193325Z | rexkogit |
| 034 | Swift 3 | 160916T184715Z | mklbtz |
| 143 | C++ with Boost | 160916T175906Z | user5946 |
| 019 | Vim | 160916T182556Z | DJMcMayh |
| 050 | C | 160916T160555Z | Cody |
| 003 | Sesos | 160916T175054Z | Dennis |
| 055 | Bash | 160916T142728Z | seshouma |
| 009 | Nonwrapping Brain**** | 160916T132017Z | Steven H |
| 068 | Oracle SQL 11.2 | 160916T152557Z | Jeto |
| 019 | Perl | 160916T151118Z | Ton Hosp |
| 043 | Lua | 160916T144355Z | Jör |
| nan | GNU sed | 160916T104623Z | seshouma |
| 008 | Befunge 93 | 160916T141414Z | Martin E |
| 022 | Perl 6 | 160916T141228Z | Brad Gil |
| 065 | MATLAB | 160916T140230Z | Richard |
| 007 | Pyth | 160916T132854Z | Rod |
| 011 | ><> | 160916T132614Z | Sp3000 |
| 008 | MATL | 160916T094318Z | Luis Men |
| 026 | PowerShell v2+ | 160916T125405Z | AdmBorkB |
| 012 | Reticular | 160916T124901Z | Conor O& |
| 025 | J | 160916T123024Z | Conor O& |
| 064 | MATLAB | 160916T122405Z | Richard |
| 030 | Octave | 160916T120733Z | Stewie G |
| 066 | C# | 160916T102753Z | Daniel L |
| 083 | C# | 160916T101014Z | Pete Ard |
| 006 | 05AB1E | 160916T090210Z | Emigna |
| 054 | Java | 160916T093617Z | Shaun Wi |
| 028 | Caché ObjectScript | 160916T095722Z | adaptun |
| 003 | ShadyAsFuck | 160916T095314Z | flawr |
| 019 | Haskell | 160916T091627Z | xnor |
| 056 | Batch | 160916T094024Z | Neil |
| 027 | Python 2 | 160916T085503Z | xnor |
Piet + ascii-piet, 20 bytes (10×2=20 codels)
tL RrN?FmBnDbAjBsCiq
The separator is ASCII 1. You can confirm the separator is ASCII 1 by copy pasting the output from the Piet code into the input of this Python script.
Knight (v1), 18 16 bytes
-2 bytes thanks to @emanresu A
;=i 0W=i+i!OiO~i
I usually would use the interpreter on knight-lang.netlify.app but it doesn't really handle infinite loops in the way that I wanted it to so I switched to this hacky JS interpreter instead.
Bash, 24 26 bytes
echo "$[i++]
$[--j]"&&. $0
Added 2 bytes for the requirement "the separator must not change"
Similar loop in 'pure' Zsh, 26 bytes:
while echo "$[i++]
$[--j]"
BrainChild, 44 bytes
include*;int i;while(++i)printf("$0,-$0,",i)
Prints all 32bit unsigned numbers, and also the same numbers with a minus behind them. Abuses the fact that all ints are initialised to 0 by default.
iogii, 7 5 bytes
e;1<-
-2 inspired by Darren Smith!
e Expand (iterate from nil (coerces to 0)):
1< Is the value less than 1?
; - Subtract the original value from that.
expand and iterate technically aren't actual iteration constructs, but they can be reasoned about as such.
C (gcc), 135 bytes
char*b,*l=-1,s=3;i(d){d<0?asprintf(&b,"%0*d ",++l+1,0),*b+=!!l:++b[d]>57?b[d]=48,i(d-1):0;}main(){for(;;s=!printf("%s-%s"+s,b,b))i(l);}
Generates integers continuously until memory is exhausted or patience runs out.
- -1 byte thanks to ceilingcat!
Ungolfed:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *buffer;
long length = -1; // Track the current length of the integer string
int start_index = 3; // Controls the starting format of the print string
void increment_digit(int index) {
// Base case: if `index` is negative, we've hit a new power of 10.
if (index < 0) {
// Expand buffer to hold an additional digit and add a space at the end
length++;
buffer = realloc(buffer, length + 4); // +4 to account for new digit, space, and null terminator
sprintf(buffer, "%0*d ", length + 1, 0); // Zero-padded format to length+1 digits, initialized to "000...0 "
// Special case: set first digit to '1' if `length` is non-zero, creating "100...0 " instead of "000...0 "
if (length > 0) {
buffer[0] = '1';
}
} else {
// Otherwise, increment the digit at the current index
buffer[index]++;
// If the digit surpasses '9', reset to '0' and carry over to the next higher place
if (buffer[index] > '9') {
buffer[index] = '0';
increment_digit(index - 1); // Recursive carry
}
}
}
int main() {
buffer = 0; // Initialize buffer to NULL for the first allocation
for (;;) {
increment_digit(length); // Increment the last digit position in buffer
// Print the buffer, effectively showing the current "number" and a trailing space
printf("%s-%s" + start_index, buffer, buffer);
start_index = 0; // Reset start_index to 0 for continuous printing
}
free(buffer); // Cleanup (though technically unreachable here)
return 0;
}
Bash, 65 61 58 39 bytes
Original : echo 0;e=1;while echo $e $((${e}*-1));do e=$(($e+1));done (65 bytes)
WheatWizard's : e=0;while true;do echo $e;e=$(($e+1));echo $((${e}*-1));done (60 bytes)
Edited : echo 0;e=1;while echo $e $((${e}*-1));do e=$(($e+1));done(58 bytes)
Mantawork's : e=0;while echo $e;do echo $[-++e];done (39 bytes)
Japt, 6 bytes
You go years without using a particular method, then get to use it twice in one day!
@OpX}c
@OpX}c
@ :Function taking an integer X as an argument
OpX : Output X with trailing newline and, crucially, return undefined.
} :End function
c :Pass each integer in the sequence [0,-1,1,-2,2,...] to that function until one of them returns truthy, which will never happen
Rattle, 12 bytes
p[+[p*_1]2]0
Try it Online! [NOTE: this code will time out because of the infinite loop, if you want to see any output then change the 0 for a finite value (e.g. 100). There is no output with the infinite loop because of how the online interpreter is set up, if run offline there would be infinite output.]
Explanation
p print 0
[ ]0 infinite loop
+ increment
[ ]2 loop twice
p print value
*_1 multiply by -1
Uiua, 14 characters
⍢(¯-<0±..).1 0
Explanation
⍢(¯-<0±..).1 0
1 0 starting values
. condition for while (Uiua has no booleans, so 1 is true)
⍢( ) infinite loop
.. creates 2 copies of the current value
<0± determines if the number is negative
¯- negate the number, but additionally add one to it if the condition was true
Swift 5.9, 32 bytes
(0...).map{print($0)
print(~$0)}
I tried desperately to merge the two calls to print(_:separator:terminator:) into one, but the fact that terminator is a newline by default seriously complicates things.
Uiua, 18 bytes
⍥(+⟜⊃±∵&s)∞¯1_1&s0
Explanation:
⍥(+⟜⊃±∵&s)∞¯1_1&s0
# ^ ^ ^^^ ^^ ^
# | | ||| || └- print 0
# | | ||| |└----- [-1 1]
# | | ||| └------ do infinitely
# | | ||└---------- print each
# | | |└----------- sign of elements
# | | └------------ fork both functions
# | └-------------- increment by sign
# └---------------- repeat until
Pascal, N/A
Pascal enforces good programming style. Pascal forces you to ignore the fact that your code will (eventually) run on a computer with technical limitations. This is a consistent design choice. You – the programmer – are supposed to focus on the algorithm.
The “native integer type” in Pascal is called integer.
However, you cannot inspect from your Pascal source code its implementation characteristics.
The built‑in implementation‐defined constant maxInt is associated with minimum requirements.
Technically it is possible and not forbidden that integer can store even more integer values.
program z(output);var n:integer;begin for n:=-maxInt to maxInt do writeLn(n)end.
program z(output);var n:integer;begin n:=maxInt;for n:=-n to n do writeLn(n)end.
If your processor supports Extended Pascal (ISO standard 10206), you can also use a set‑membership‐iteration statement. Note the specific order values are printed is implementation‐dependent.
program z(output);var n:integer;begin n:=maxInt;for n in[-n..n]do writeLn(n)end.
If the implementation‐defined value of the default minimum printing width is at least \$\lfloor \log_{10}\text{maxInt}\rfloor + 3\$ (+3 to accommodate a sign and at least one intervening space), you can drop the Ln:
program z(output);var n:integer;begin for n:=−maxInt to maxInt do write(n)end.
TurboBasic XL (Atari 800XL), 21 Bytes
DO:I=I+1:?1-I,I,:LOOP
Output is: 0 1 -1 2 -2 3 -3 4 ...
Buildin Basic (Atari 800XL), 18 Bytes
0I=I+1:?1-I,I,:G.0
Ruby, 26 22 19 16 15 bytes
Prints numbers separated by newlines. -3 bytes from @manatwork. -3 bytes from @m-chrzan. -1 bytes from @CGOneHanded via upgrading to Ruby 2.7+.
0.step{p~_1,_1}
Befunge-93, 8 bytes
.1+::&*.
Explanation
v // Make this explanation be able to run (downwards)
. // Print top of stack as integer (if first iteration, stack is initialized at 0, so 0 is the first integer printed)
1
+ // Increment
:
: // Duplicate number so it isn't lost doing operations and printing
&
* // Negate. When input is empty, getting user input with & returns -1.
. // Output negative integer
// Continue to next iteration, where top of stack (positive integer) will get printed
C, 64 58 Bytes
Thanks to @12431234123412341234123
f(n){printf(",%d,-%d",n,n);f(++n);}main(){f(printf("0"));}
A full program that terminates after printing all the integers it can represent.
Output
0,1,-1,2,-2,3,-3,4,-4,5,-5,6,-6,7,-7,8,-8,9,-9,10,...
Commodore Basic, 18 bytes
1N=N+1:?N,1-N,:G┌1
PETSCII substitution: ┌ = SHIFT+O
Prints the sequence "1, 0, 2, -1, 3, -2...", with characters separated by tabs.
- Work up to the numbers with the biggest magnitude of the standard integer type? Yes. Commodore Basic integers have a range of -32768 to +32767; this program uses 40-bit floats with a 32-bit mantissa, and can print any number between -999999999 and 999999999.
- Output in decimal? Yes. Integers stored in a floating-point number are printed as integers as long as they are nine digits or less.
- Each integer separated from the next using any separator? Yes. There is always a tab character between two integers.
- The separator must not change? Yes. The separator is always exactly one tab character.
- The separator can consist of multiple characters, as long as none of them is a digit nor the negative sign? Yes. A tab character is neither a digit nor a negative sign.
- Any supported integer must eventually be printed after a finite amount of time? Yes. After about 25 minutes, it'll print the sequence
32767 -32766 32768 -32767 32769 -32768, finishing out the set of Commodore Basic-supported integers.
Fortran (GFortran), 34 bytes
i=0
1 i=i+1;print*,1-i,i;goto1;end
Boringly had to waste 4 bytes setting i=0 otherwise Fortran just initialises the variable to anything
Commodore C64 BASIC, 29 BASIC Bytes (does not end gracefully), 24 PETSCII characters with keyword abbreviations
0?i%,nO(i%),;:i%=i%+1:gO
By declaring a variable with a % identifier, you are telling Commodore BASIC to produce only integer representations of any floating point number, and this is within the range of -32768 to +32767 inclusive. The nO command, or NOT is a bitwise operator which may only be used with the same range previously mentioned (PRINT NOT (32768) for instance produces an ?ILLEGAL QUANTITY ERROR. Further reading about this is detailed here.
Because we are using line 0, we don't need to specify a line number with the GOTO command (at least not in BASIC 2.0 on the C64 and VIC-20; this may not be the same for all versions of Commodore BASIC).
The output is produced like:
0 -1 1 -2
and will continue until the maximum range is met, and produce an error.
With a graceful ending, 39 BASIC Bytes, 35 PETSCII characters with keyword abbreviations
0?i%,nO(i%),;:i%=i%+1:ifi%<32768then0
The same as above, but an IF condition is added. We can just use THEN0 rather than THEN GOTO 0 to save some typing.
Kotlin, 49 48 bytes
(Int.MIN_VALUE..Int.MAX_VALUE).onEach(::println)
Saved one byte by using another iterator function
49 bytes variant
(Int.MIN_VALUE..Int.MAX_VALUE).forEach(::println)
Expected output
-2147483648
-2147483647
-2147483646
...
-1
0
1
2
...
2147483645
2147483646
2147483647
The program will take a while since this is only a single threaded printing and integer values reach -2147483648 to 2147483647.
Regenerate -a, 22 bytes
0|($2[0-9]!-?[1-9]())+
Thanks to thejonymyster for the idea to use this language to answer this question.
In pretty-printed format:
0
|
(
$2 # only matches after $2 has been set
[0-9] # all subsequent digits
!
-? # negative or positive
[1-9] # first digit
() # capture group $2
)+ # Repeat the above 1 to infinity times
The first main alternative is 0. Once that has been used, it moves on to the second main alternative, which is split into two sub-alternatives. They are split using ! instead of |, so whichever choice is made will be locked-in once it no longer results in any changes of state.
The first time through, the $2[0-9] branch cannot be taken, since $2 is unset and results in a non-match. So the branch -?[1-9]() will be taken – and it results in a change of state: the capture group $2 becomes set rather than unset.
Due to the change of state, the (...!...) set of alternatives is given another chance to be chosen, if it is repeated. Since $2 is now set, the first alternative will be taken, and this locks it in – from this point forward, it is the only alternative that will be taken.
...or at least, that's my current best understanding of how it works. I don't think it's correct, otherwise 0|($4($3[0-9]![1-9]())!-?()){2,} (32 bytes) should do the same thing as the 22 byte version, but it doesn't. The ! operand is undocumented, so it'll take analyzing Regenerate's source code or asking to author to figure out how exactly it works.
...but as it turns out, 0|($2[0-9]!$3[1-9]()!-?()){2,} (31 chars / 33 bytes), with a zero width joiner inserted after the -?, does work, so my explanation may be accurate. The problem may just be that alternatives don't work the same way when they make a zero-width match.
Regenerate -a (staging), 15 bytes
0|-?[1-9][0-9]*
In the latest version of the language, the obvious solution now works. Before the fix, this would only print nonnegative integers beginning with the digit 1:
Attempt This Online! - presumably this link will eventually show the same behavior as the above one, when the new version of Regenerate graduates from staging
Regenerate -a, 12 bytes (10 characters)
0|(+)-?#1
If outputting invisible whitespace is allowed, this can be used to "cheat":
0
|
(+) # $1 = Repeat U+200D (Zero Width Joiner), 1 to infinity times
-? # Optionally match a negative sign
#1 # Match the length of $1 as a number in decimal
Regenerate would theoretically keep printing all integers indefinitely, but in practice it stops due to hitting a recursion limit. It can't actually repeat anything more than 994 times on Attempt This Online, for example.
Bash, with no external utilities, and no integer size limits, 210 208 bytes
echo 0
while
j=$i@
do
while
k=${j/9@/@0}
[ $k != $j ]
do
j=$k
done
j=${j/0@/1}
j=${j/1@/2}
j=${j/2@/3}
j=${j/3@/4}
j=${j/4@/5}
j=${j/5@/6}
j=${j/6@/7}
j=${j/7@/8}
j=${j/8@/9}
i=${j/@/1}
echo $i
echo -$i
done
If you wish to see it run with large integers, initialize i to a large integer.
GolfScript, 12 bytes
0{.p.~p).}do
0 # push 0 to the stack
{ # this block will execute at least once, even though the TOS is 0
.p # print the current number
.~p # print the bitwise NOT of the current number
) # increments the current number
.}do # creates an infinite loop
Because the bitwise NOT of x = (-x - 1), as the number increments, the inverse decrements. The bitwise NOT of 0 is -1, therefore it can be trivially proven that all integers are counted exactly once.
I know there's already a (longer) GolfScript solution here, I apologise if this is breaking any rules.
APOL, 19 bytes
w(T p(∈) p(-(0 ∈)))
Pretty self-explanatory.
APL, 17 bytes
Pretty self explanatory
{∇⊃⎕←(⊢,-)1+⍵}⎕←0
Dyalog APL, 18 17 15 14 12 bytes
{∇-⎕←1-⎕←⍵}0
{ Begin function
∇ Call recursively with new argument and repeat: -⍵-1
- Negate sign to make it negative again: -⍵-1
⎕← Print current value: ⍵+1
1- Subtract it from 1, flipping the sign and incrementing the absolute value: ⍵+1
⎕← Print current value: -⍵
- Negate sign to make it negative: -⍵
⍵ Argument to function, starts at 0 and increments by one each time: ⍵
} End function
0 Call function with 0
Thanks to @Razetime & @Adám for their help golfing my original 18 bytes to 12. It started as ⎕←0⋄{∇⊃1+|⎕←-⎕←⍵}1 and is far more elegant now, not to mention more competitive!
Pure yash and echo (or POSIX-compatible shell), 42 bytes
Separator is space or LF.
while echo ${#a} ${a+-${#a}};do a=.$a;done
How it works
${#a}is length of string contained in the variable.${a+xxx}is content of variable a, if a is null string; otherwise string xxx.- Undefined variable is expanded to null string.
AWK, 33 32 bytes
This code prints all integers in one line:
BEGIN{for(ORS=FS;;)print -i++,i}
An alternative 33-byte answer, which prints one integer per line:
BEGIN{for(;;)print n+=i++*(-1)^i}
BRASCA, 20 18 bytes
-2 bytes thanks to RezNesX
nEo1[:nEo:0$-nEo}]
Explanation (old)
<implicit> - The stack has infinite zeroes at the bottom
nEo - Print "0" and a space
1[a A] - Infinite loop:
}:nEo - Print next positive integer and a space
$ - Swap to the negative number on the stack
{:nEo - Print next negative integer and a space
$ - Swap back to the positive number on the stack
Vyxal 5, 8 bytes
∞›(n,n⌐,
Explanation:
∞›(n,n⌐, # main program
∞› # creates an infinite generator starting at 1
( # iterates over it
n, # prints the numbers [1, ∞)
n⌐, # prints the numbers (-∞, 0]
Mapping would be better, but currently mapping generator output is not optimal.
Jellyfish, 19 bytes
\~-0
0~p
~-
~>
p
A (Sort-of) port of Dennis' Jelly solution.
Explanation
(~ is function composition)
\ iterate the following function
0 on 0
0 till 0 occurs:
~- negate the result of
~p printing
~- the negation of
~> addition of 1 to
p printing the argument.
Hexagony, 14 bytes
Compacted:
!~{/")!;/;"~{/
Formatted:
! ~ {
/ " ) !
; / ; " ~
{ / . .
. . .
Improves upon @Sunny Pun's answer by not using the middle -> edge branches, but instead uses a more linear control flow, while delimiting with null bytes (didn't see anything against this) which are the default state of memory in Hexagony.
V (vim), 18 bytes
i0<esc>qqYp<c-a>Yi-<esc>p@qq@q
a small improvement by shuffling around the loop and removing the 1 from James' answer.
Add++ v0.2, 23 bytes
This is the current version on TIO. The latest should be able to do it in less but it is untested so I decided not to post it.
O
V
+1
W,G,+1,O,~,O,~,V
How does it work?
O Output the accumulator (x) as a number (0)
V Save x in the second stack
+1 Add one to x
W, While x is true:
G, Set x to the popped item from the second stack
+1, Add 1 to x
O, Output x as a number
~, Negate x
O, Output x as a number
~, Negate x
V Save x in the second stack
Add++ v5.10, 13 bytes
Dx,O,#,+1,O,#
C, 55 Bytes
i=1;f(){putc('0');while(i>0){printf(",%d,%d",-i,i++);}}
Explanation
/*int*/ i = 1;
int f()
{
putc('0');/*Print out 0 because -0 isn't a number*/
while(i>0) /*i>0 handles overflow, ensuring all valid *
* integers are printed once and only once */ {
printf(",%d,%d",-i,i++);
/* Unpacking the above line:
the 1st %d prints out -i
the 2nd %d prints out i
i++ adds 1 to i(after it's passed to the printf)*/
}
}
I put the comma at the beginning of the printf statement so that I didn't have to put it at the end of the puts and at the end of the printf.
Output: 0,-1,1,-2,2...
Edit: full C program version
@cleblanc made an answer that is a full C program, rather than a function, so I decided to do that too(Our answers are otherwise completely separate).
C, 58 Bytes
i=1;main(){putc('0');while(i>0){printf(",%d,%d",-i,i++);}}
Explanation
More or less the same as the original answer, but changing the function's name to main makes it a standalone program, rather than a function.
Symja, 38 37 bytes
i=0;While(0<1,Print(i);i++;Print(-i))
To see that this will work for all integers, view this demonstration for numbers up to 100.
Turing Machine Code, 460 bytes
This prints the list in Unary so I'm hoping this still counts since, in Turing Machine Code, the concept of a 'number base' isn't built in. I'm going to mull over a base ten solution and post it separately if it exists and I find it.
0 * 1 r 2
2 * , r 3
3 * - r 4
4 * 1 r 5
5 * * r 5
5 _ , r 6
6 * * r 6
6 _ 1 * 7
7 * * l 7
7 , , l 8
8 * * l 8
8 - - r 9
9 1 @ r a
8 , , r g
g 1 @ r a
g - - r a
a * * r a
a _ 1 l b
b * * l b
b @ 1 r c
c 1 @ r a
c , , r d
d * * l d
d - - r 6
d , , r e
e * * r e
e _ , r f
f _ - r h
h * * l h
h , , l i
i * * l i
i , , r j
j 1 @ r k
j , , r m
k * * r k
m * * r m
m _ , r n
k _ 1 * o
o * * l o
o , , l p
p * * l p
p , , r q
p @ 1 r j
q * * r q
q _ , r n
n _ 1 r 7
Red, 37 bytes
n: 1 forever[print[n 0 - n]n: n + 1]0
LaTeX, 97 bytes
\def\f{\typeout0\newcount\n\n=1\loop\typeout{\the\n}\typeout{-\the\n}\advance\n1\ifnum1=1\repeat}
Defines a macro \f that writes to stdout.
Explanation
\def\f{ % define a macro \f
\typeout0 % write a 0
\newcount\n % define a new counter n
\n=1 % set n to 1
\loop % this is like a do-while loop
\typeout{\the\n} % write n
\typeout{-\the\n} % write -n
\advance \n 1 % increment n by 1
\ifnum 1=1 % this is the loop condition, continue if 1=1
\repeat % jump to the loop start
}
MathGolf, 8 bytes
0Æ∙p~p)∟
Explanation:
0 # Push a 0
∟ # Do-while true without popping,
Æ # using the following 5 commands:
∙ # Triplicate the top of the stack
p # Pop and print with trailing newline
~ # Take the bitwise-NOT
p # Also pop and print it with trailing newline
) # And increase the top value by 1
Pyth, 6 bytes
0f!
_
In string representation, this is "0f!\n_\n".
We print 0 explicitly, then use f in "count up from 1 until result truthy" mode, where the function prints the input, negates it, prints that, and then boolean negates the result so f will never halt.
W d, 6 5 bytes
Newline-separated. Look ma, no bitwise magic!
▲h(2Z
Explanation
Decompressed:
0 % Print 0 (the implicit not-given operand, to be precise)
i E % In the range 1..infinity...
a % Explicit loop variable
P % Print the number with a newline
_ % Negate the number
% Implicit print on each iteration
% Make sure that the second-to-top executes (this is now implicit)
x86-16, IBM PC DOS, 47 bytes
Binary:
00000000: 33c9 bd0a 0050 0bc0 7d09 50b8 2d0e cd10 3....P..}.P.-...
00000010: 58f7 d833 d2f7 f552 410b c075 f658 b40e X..3...RA..u.X..
00000020: 0c30 cd10 e2f7 b020 cd10 5840 75d7 c3 .0..... ..X@u..
Build and test using xxd -r
Unassembled listing:
33 C9 XOR CX, CX ; clear counter
B3 0A MOV BL, 10 ; BX is divisor
INT_LOOP:
50 PUSH AX ; save registers
0B C0 OR AX, AX ; is AX negative?
7D 09 JGE DIGIT_LOOP ; if positive, start digit loop
50 PUSH AX ; save number
B8 0E2D MOV AX, 0E2DH ; BIOS tty function, '-' char output
CD 10 INT 10H ; write to console
58 POP AX ; restore AX
F7 D8 NEG AX ; AX = -AX
DIGIT_LOOP:
33 D2 XOR DX, DX ; clear high word of dividend
F7 F3 DIV BX ; AX = quotient, DX = remainder
52 PUSH DX ; save remainder on stack
41 INC CX ; increment counter
0B C0 OR AX, AX ; quotient = 0?
75 F6 JNE DIGIT_LOOP ; no, keep going
PRINT_LOOP:
58 POP AX ; restore digit in AL
B4 0E MOV AH, 0EH ; BIOS tty function
0C 30 OR AL, '0' ; convert to ASCII
CD 10 INT 10H ; write to console
E2 F7 LOOP PRINT_LOOP ; loop until all digits displayed
B0 20 MOV AL, ' ' ; space char
CD 10 INT 10H ; write to console
58 POP AX ; restore counter
40 INC AX ; increment to next number
75 D7 JNZ INT_LOOP ; loop until 0
C3 RET ; return to DOS
(This program is basically just an itoa() function...)
Output
A standalone DOS executable. Using default 16-bit integer size for 8088, writes all numbers in decimal to console.
Head:
Tail:
Python 2, 32 bytes
i=0
while 1:print i;print~i;i+=1
Runic Enchantments, 24 bytes
8?;>0$' $01+:$' $Z:$' $Z
' $ is just as long as any other way of printing a character (such as ak$) so with a required separator, that's as short as it gets.
Will print forever until the value exceeds the binary representation and sign-overflows (which is acceptable for questions with an infinite memory assumption), whereupon it will repeat.
Keg, -pn, 15 9 bytes
0.1{:④±.⑨
Answer History
15 bytes
0. ,1{④± ,④ ,±⑨
Really messy I know, but it works. Integers are space seperated
Wren, 50 bytes
var n=0
while(n)n=-System.print(1-System.print(n))
Explanation
var n=0 // Set n as 0
while(n) // While n is an integer:
System.print(n) // Output n
System.print(1- ) // Output 1-n
n=- // Set n as the number negated
GolfScript, 16 14 bytes
1{.p.1\-p).}do
Explanation:
1 # Set counter to 1
{ .}do # While counter is nonzero:
.p # Print counter
.1\-p # Print counter - 1
) # Increment counter by 1
C (gcc), 40 38 36 bytes
main(i){for(;printf("%d ",i),i++;);}
Explanation:
The first argument to main() is argc, which is 1 if the program is run without additional parameters. When we reach the max positive integer, i wraps around and becomes negative. The program stops when i==0, after printing it.
Thanks @ceilingcat for -3 bytes
MarioLANG, 17 bytes
:<
+"
)(
-:
>!
=#
Vertical loops are normally shorter in MarioLANG. This outputs:
0 -1 1 -2 2 -3 3 -4 4 -5 5 -6 6 -7 7 -8 8 -9 9 -10 10 -11 11 .......
Poetic, 565 bytes
even as a child, i had a dream i was a person in the movies
it makes a lot of sense,i did think
o,a million people was an image in mind
i inspire folks to see a comedy
o-m-g,how i am funny
o,i mean i laugh,i cry,i scream,i am the funniest
i made a comedy i was pretty proud of
like a galaxy,i am given a star on a big California byway
i make a movie,i make a sequel to a film i edited
i had a vision i was a celeb;as in,an actor
i had a dream i had a legacy
i am asleep now
i quietly awaken
was it truth,or nothing but a fantasy world?o,a whole lot of doubts for me
Outputs the following forever:
0,1,-1,2,-2,3,-3,4,-4,5,-5,6,-6,7,-7,8,-8,9,-9,10,-10,11,-11,...
Brachylog, 2 bytes
ẉ⊥
ẉ Print with a newline
the input,
⊥ then try again.
Since the program is given no input, the main predicate's input variable is left unconstrained. At first, it is assumed to be 0, but when execution hits ⊥, it backtracks to the only possible point of failure: the choice of value for the input variable. So then it tries 1, and -1, and every other integer, printing each one separated by newlines forever because ⊥ always forces backtracking, and the effect of ẉ is executed immediately.
QBasic, 23 bytes
Script that takes no input and outputs to the console. Values are newline delimited and increment in the order of \$0, -1, 1, -2, 2, \cdots\$.
?0
Do
i=i+1
?-i
?i
Loop
Small Basic, 92 bytes
A Script that takes no input and outputs to the TextWindow object.
TextWindow.Write(0+" ")
While 1=1
i=i+1
TextWindow.Write(Text.Append(-i+" ",i+" "))
EndWhile
Zephyr, 48 bytes
set i to 0
while 1=1
print-i,i+1...
inc i
repeat
Space-separated. If the separator could alternate between space and newline, the ... could be removed for -3 bytes. Try it online!
Gol><>, 7 bytes
lN01l-N
How it works
lN01l-N
l push current stack length (n)
N pop and print with newline
01l push 0, 1, then stack length (n+2)
- pop n+2, 1, then push 1 - (n+2) = -n-1
N pop and print with newline
now the stack length is n+1; repeat indefinitely
Japt, 12 10 bytes
_OlU°,Un}a
Explanation:
_OlU°,Un}a
| Implicit U = 0
_ }a | Start an infinite loop
Ol | Write to the console:
U° | U++
, | and
Un | 0-U
Scala, 112 bytes
val x=Int.MaxValue
val y=Int.MinValue
print(0)
for(a <-1 until x) print(","+a + "," + a * -1)
print(","+x+","+y)
Testable Running Program with limits [-10,10]
Scala, 143 bytes
object ListNumbers extends App {
val x = 10
val y = -10
print(0)
for(a <- 1 until x) print(","+a + "," + a * -1)
print(","+x+","+y)
}
Using Java 8 Streams just for fun, it generates a lazy populated string
types declarations can be omitted but I included for "documentation"
Scala, 253 bytes
val zero :Stream[String] = Stream("0")
val positive :Stream[Int]= Stream.from(1)
val negative :Stream[Int]= positive.map(_* -1)
val stream = zero ++ positive.zip(negative).map(x => x._1.toString()+","+x._2.toString())
//stream.take(Int.MaxValue).toList
Javascript, 96 bytes
f=n=>f([].concat(...n.map(i=>alert(+i?i+' -'+i:i)||+i?y.map(o=>i+o):[])));f(y=[...`0123456789`])
Alerts all integers in the sequence (0, 1, -1, 2, -2, ...), using strings to go beyond JS's usual max safe integer 9007199254740991. This is equivalent to the "Infinite version" in Arnauld's earlier answer.
SmileBASIC, 20 bytes
@L?N,-N-1N=N+1GOTO@L
A very boring answer.
Alternative:
@L?N
INC N?-N
GOTO @L
F#, 69 bytes
let f=
let mutable i=0m
while 1>0 do
printf"%O,-%O,"i i
i<-i+1m
It's pretty straight forward. The 0m sets i as 0, but of type decimal. Since we're allowed to print 0, -0 I'm doing that. i gets incremented with every iteration of the loop, and the value is printed out.
I my initial idea would have been 70 bytes but (like most of my initial ideas) it would never have worked:
let g=Seq.iter(fun x->printfn"%O,-%O"x x)[0m..System.Decimal.MaxValue]
In this one [0m..System.Decimal.MaxValue] creates an array starting at 0, adding 1 each time and going all the way to the maximum decimal value. (Another example would be the expression [1..10] creates an array with {1,2,3,4,5,6,7,8,9,10}).
Seq.iter would then apply the function for printing to that array.
The problem with this is that the array must be constructed before iterating through it. So for all integers, with infinite memory the array could be constructed - but it would also take an infinite amount of time, so nothing would ever be printed out!
Visual Basic .NET (Mono), 95 bytes
A declared subroutine that takes no input and outputs to the console.
Module M
Sub Main
Dim i
Do
Console.WriteLine(-i &IIf(i," "&i,""))
i=i+1
Loop
End Sub
End Module
Yabasic, 22 bytes
An anonymous yabasic answer that takes no input and outputs all integers to the console.
?0
Do
i=i+1
?-i,i
Loop
uBASIC, 24 bytes
An anonymous ubasic answer that takes no input and outputs to the console.
0?0
1i=i+1:?i,0-i:GoTo1:
Try it online! (and yes, the terminal : is necessary)
R, 25 24 bytes
Golfed one byte thanks to @JDL.
repeat cat(-F,F<-F+1,'')
Example output:
0 1 -1 2 -2 3 -3 4 -4 5 -5 6 -6 7 -7 8 -8 9 -9 10
Prolog (SWI), 33+3 = 36 bytes
A*B:-C is B-A,writeln(C),C*(1-B).
Called as 0*0.
Prints 0, 1, -1, 2, -2 ... separated by newlines.
Saved 5 bytes thanks to SQB
Saved 16 bytes thanks to user3744156
Milky Way, 9 bytes
&{!k1-!j}
How?
initial Stack: ["", 0]
&{ } infinite loop
! output ToS
k negative absolute value
1- subtract 1
! output ToS
j absolute value
Pyt, 11 bytes
00Ƥ`⁺ĐĐ~ƤƤł
00 pushes 0 twice Ƥ prints with a newline separator ` indicator for looping ⁺ increments ĐĐ duplicates twice ~ negates top value ƤƤ prints positive and negative value ł loops till top is zero (never)
Appleseed, 41 bytes
(def I(q(((n 0))(cons n(I(sub(less? n 1)n
Defines a function I that takes no arguments and returns an infinite list of integers, starting (0 1 -1 2 -2 ...). Try it online!
Note: Appleseed is in the early stages of development at the moment, so if this code stops working at some point in the future, ping me and I'll update it.
Ungolfed + explanation
; Load the library for functions & macros such as lambda
(load library)
; Define all-integers to be...
(def all-integers
; a lambda function with one optional argument, n, whose default value is 0
(lambda ((n 0))
; The function prepends n to...
(cons n
; the result of a recursive call...
(all-integers
; whose argument is (n<1) - n, i.e. -n if n is positive, else -n+1
(sub (less? n 1) n)))))
Forked, 21 bytes
%A!v
>1+%A!AF*!%A!
First, this does %A! (print 0 followed by a newline), then executes the code in my original answer below, before I realized we were supposed to print 0 too:
Forked, 12 bytes
1+%A!AF*!%A!
1+- add 1 to the top of the stack%- print top of stack as integerA!- print 0xA (ASCII newline)AF*!- print 0xA × 0xF = 0x2D (ASCII-)%- print top of stack as integerA!- print 0xA (ASCII newline)
Forked is two-dimensional, so the IP wraps upon hitting the edge of the playing field.
This just loops through every integer, prints it followed by a newline, then prints it again, preceded by a - and proceeded by a newline.
Momema, 26 bytes
z0-8*0-9 00+1*0-8-*0-9 0z1
This outputs null bytes as the separator (though TIO displays them as spaces).
Alternatively, at a cost of 1 byte, here's a version that uses tabs instead of null bytes:
z0-8*0-9 9 0+1*0-8-*0-9 9z1
Explanation
# a = 0
z 0 # label z0: jump past label z0 (no-op) # while true {
-8 *0 # output number [0] # print a
-9 0 # output chr 0 # print '\0'
0 +1*0 # [0] = [0] + 1 # a++
-8 -*0 # output number -[0] # print -a
-9 0 # output chr 0 # print '\0'
z 1 # label z1: jump past label z1 # }
Husk, 2 bytes
İZ
I know Husk is created after the post of the challenge but I think it is still worth mentioning.
Wumpus, 8 bytes
=nON
=)N
Prints the integers in the order -1, 0, -2, 1, -3, 2, ... using linefeed separation.
Explanation
Let's look at the actual grid first:
The instruction pointer starts in the top left corner moving east and will reflect off the edge whenever it reaches a boundary of the code. Hence, this program loops through the code indefinitely, but we reuse the single O (because it's executed both before and after entering the top right corner).
So the loop body looks like this:
=nONON)=
Let's go through this:
= Duplicate the top of the stack. Initially, this is an implicit zero,
but in general this will be the non-negative number of each pair we print.
n Bitwise NOT. Turns the copy of n into -n-1.
O Output -n-1.
N Output a linefeed.
O Output n.
N Output a linefeed.
) Increment n to n+1.
= Duplicate it (because one copy of it will be printed in the next iteration).
Implicit, 6 5 4 bytes on TIO
(%.ß
Requires that the input box on TIO be empty.
(... « do..while top of stack truthy »;
% « print top of stack as int »;
. « increment (reads from input if stack empty) »;
ß « print space »;
¶ « (implicit) just kidding, loop forever »;
Implicit, 5 bytes
0(%.ß
0 « push 0 »;
(%.ß « (same as above) »;
><>, 17 16 Bytes
0:n1+ao:0$-nao0?
Could shave off 4 bytes, at the cost of separation in the output.
Current output:
0
-1
1
-2
2
...
Explanation:
0:n | Puts 0 on the stack, duplicates it, and prints it.
1+ | Increments the value
ao | Prints a new line.
:0$-n | Duplicates the value, prints it negative.
ao | Print a new line.
0? | Skip the next command (pushing 0), repeat.
Previous solution:
0:n1+ao:0$-nao01.
Teleports to the command after the 0, instead of just skipping it.
Aceto, 9 bytes
dpnd~pnIO
d duplicates the top val p prints it n does a newline ~ negates the top val I Increments the top val O returns to the beginning of the program
Excel VBA, 25 20 Bytes
Anonymous VBE immediate window function that takes no input and outputs to the vbe immediate window
Do:?1-n;n:n=n+1:Loop
Note: Excel will appear to be non-responsive after executing to n=6012, adding a DoEvents: call at the beginning of any of the lines in the do...loop corrects this visual bug, but is not necessary for correct execution.
Triangular, 21 bytes
()ip.%@,|<.>A@\/A|%p<
(Does not work on the TIO version yet.) Formats into this triangle:
(
) i
p . %
@ , | <
. > A @ \
/ A | % p <
This got really messy once I realized there had to be delimiters between the numbers.
The directionals (<,>\/) poke the IP around to get this code executed:
(i%|A@p%|A@p)
How it works:
(opens a loop.iincrements the top of stack.%prints the top of stack as an integer.|negates the top of stack.Apushes 10 to the stack.@prints the top of stack as ASCII\n.ppops the 10. Now the top of stack is the negated value.%prints the top of stack (negated value).|un-negates the top of stack.Apushes 10 to the stack again.@prints as ASCII\n.ppops the top of stack.)unconditionally jumps back to the loop.
Powershell, 26 19 Bytes
for(){($b++);$b*-1}
updated because I should have done it months ago.
very straightforward, takes a variable $a, initializes as 0, then initiates an infinite loop with while(1){} and then displays the current value $a - increments it $a++ and displays the negative version of it $a*-1
output is automatically on a new line for each display, so the resulting output is:
0
-1
1
-2
2
-3
3
-4
JS (NON - ES6), 25 bytes
for(n=0;;)alert([~n,n++])
Uses binary NOT (~) for reverse sign and deincrement.
Pushy, 7 bytes
0[~#|h#
Try it online! (will eventually cut the output)
Explanation:
0 \ Push 0 as the starting counter
[ \ Infinitely:
~# \ Negate counter (and print)
|h \ Push abs(counter)+1
# \ Print counter
This prints in the pattern 0 1 -1 2 -2 3 -3..., separated by newlines.
Pushy's reference implementation is in Python, which uses arbitrarily sized integers, and so there won't be any overflow if you run this for a long time. However, the integer would eventually get too large and cause a MemoryError.
Cubix, 14 12 bytes
.(.\OSo;?.>~
Test it online! You can now adjust the speed if you want it to run faster or slower.
How it works
The first thing the interpreter does is remove all whitespace and pad the code with no-ops . until it fits perfectly on a cube. That means that the above code can also be written like this:
. (
. \
O S o ; ? . > ~
. . . . . . . .
. .
. .
Now the code is run. The IP (instruction pointer) starts out at the top left corner of the far left face, pointed east. Here's the paths it takes throughout the course of running the program:
The IP starts on the red trail at the far left of the image. It then runs OSo;, which does the following:
OPrint the TOS (top-of-stack) as an integer. At the beginning of the program, the stack contains infinite zeroes, so this prints0.SPush32, the char code for the space character.oPrint the TOS as a character. This prints a space.;Pop the TOS. Removes the32from the stack.
Now the IP hits the ?, which directs it left, right, or straight depending on the sign of the TOS. Right now, the TOS is 0, so it goes straight. This is the blue path; . does nothing, and the IP hits the arrow >, which directs it east along the red path again. ~ takes the bitwise NOT of the TOS, changing it to -1.
Here the IP reaches the right edge of the net, which wraps it back around to the left; this again prints the TOS (this time -1) and a space.
Now the IP hits the ? again. This time, the TOS is -1; since this is negative, the IP turns left, taking the green path. The mirror \ deflects the IP to the (, which decrements the TOS, changing it to -2. It comes back around and hits the arrow; ~ takes bitwise NOT again, turning the -2 to 1.
Again the TOS is outputted and a space printed. This time when the IP hits the ?, the TOS is 1; since this is positive, the IP turns right, taking the yellow path. The first operator it encounters is S, pushing an extra 32; the ; pops it before it can cause any trouble.
Now the IP comes back around to the arrow and performs its routine, ~ changing the TOS to -2 and O printing it. Since the TOS is negative again, the IP takes the green path once more. And it just keeps cycling like that forever*: red, green, red, yellow, red, green, red, yellow..., printing in the following cycle:
0 -1 1 -2 2 -3 3 -4 4 -5 5 -6 6 -7 7 -8 8 -9 9 -10 10 ...
TL;DR
This program repeatedly goes through these 3 easy steps:
- Output the current number and a space.
- If the current number is negative, decrement it by 1.
- Take bitwise NOT of the current number.
Non-separated version, 6 bytes
nO?~>~
Removing the separation simplifies the program so much that it can fit onto a unit cube:
n
O ? ~ >
~
* Note: Neither program is truly infinite, as they only count up to 252 (where JavaScript starts to lose integer precision).
Java 8, 87 bytes
Alternative solution using an IntStream to iterate through all integers.
java.util.stream.IntStream.rangeClosed(1<<31,~1<<31).forEach(n->System.out.println(n));
Alternative, 57 bytes
I didn't want to post this as my main answer, because it's just stolen from @KevinCruijssen's Java 7 answer, switched to go from negative to positive for no particular reason, and turned into a lambda. But it is technically shorter.
()->for(int i=1<<31;i<0;System.out.println(i+"\n"+~i++));
Straw, 26 bytes
~(~$:>(,-)>:>(,)>#0+~:&):&
~(~$:>(,-)>:>(,)>#0+~:&):&
~ ~ ~ Swap between the two stacks
( ) Push a string literal
$ Unary -> decimal
: : : Duplicate
> > > > Output
(,-) (,) String literal
# Decimal -> unary
0 Push the character '0'
+ Concatenate
& & Evaluate
It prints -0 too, not sure if it's allowed though
Brain-Flak, 28 + 3 = 31 bytes
To get a program that outputs every integer in some finite time (but the whole thing in infinite time) you need to use debug flags.
(@dv()@dv){([[{}]@dv]()@dv)}
The program is 28 bytes and the command line flag is 3 making the total 31.
An alternative that does not technically fit the specs:
(({})()){([([({})])]())}
If you run the program you will notice there is no output. This is because Brain-flak programs output when they terminate. It will output all the numbers at once once infinite time has elapsed. If you want to verify that it works try it online with debug flags.
SQL, 84 76 Bytes
Saved 8 Bytes thanks to steenbergh :)
Golfed:
DECLARE @n INT SET @n= 1 WHILE 1=1 BEGIN PRINT 1-@n PRINT @n SET @n=@n+1 END
Ungolfed:
DECLARE @n INT
SET @n= 1
WHILE 1=1
BEGIN
PRINT 1-@n
PRINT @n
SET @n=@n+1
END
Prints:
0
1
-1
2
-2
3
-3
4
-4
5
-5
...
QBIC, 14 bytes
{?1-q ?q q=q+1
qis 1 by default in QBIC, so this prints (1-1=) 0, 1, -1, 2, -2... separated by line breaks.
q KDB+, 25 bytes
n:-0W;while[n<0W;0N!n+:1]
Set n to negative infinity.
n:-0W
Increment and output n.
0N!n+:1
Loop until n < infinity.
n<0W
Possible alternate 17 bytes
(0N!1+)\[0W>;-0W]
Uses the \ (iterate) dyadic function to apply left hand side (plus 1 then output) from negative infinity (-0W) to infinity(0W).
Only problem is that it may throw a wsfull error eventually or at the very end after outputting all the integers.
Rust, 39 bytes
||for i in 0..{print!(" {} {}",i,-1-i)}
This uses i32. adding i64 right behind the zero would make it use that instead at a cost of 3 more bytes. Rust has no bignum types in the standard library. When overflowing, this will either panic or quietly wrap around, depending on compiler options.
MATL, 9 bytes
0`t_DQtDT
You can Try it online! (and let's hope that the process on the server actually terminates once you close your browser...)
Explanation:
0 % Push 0 on stack
` T % Start infinite loop
t_D % Duplicate top element, negate and display (which consumes the duplicate)
QtD % Add 1 to top of stack, duplicate and display (which consumes the duplicate)
C++, 84 Bytes
#include <iostream>
int main(){for(int i=0;;)std::cout<<i++<<','<<-i<<',';return 0;}
Edit: thanks for the debugging, commenters
C, 44 bytes
long l;f(){printf("%ld ",l);l=(l<=0)-l;f();}
Note that the (implicit) int return type does not cause f to require a return because f never reaches the end of the function.
This code uses the fact that globally defined variables are initialized to zero.
Note that on a system with unlimited memory (or with a compiler that does tail recursion elimination)there will be no stack overflow, therefore this program fulfils the requirements.
Shakespeare Programming Language, 227 bytes
.
Ajax,.
Puck,.
Act I:
Scene I:
[Enter Ajax,Puck]
Puck:You ox!
Ajax:Be me without myself.Open thy heart.
Scene II:
Ajax:Be thyself and ash.Open thy heart.Be me times you.Open thy heart.Be me times you.Let us return to scene II.
Obviously, this answer is nowhere near winning, but I liked that this is a use case that the SPL is comparatively well suited to.
Explained:
// Everything before the first dot is the play's title, the parser treats it as a comment.
.
// Dramatis personae. Must be characters from Shakespeare's plays, again with a comment.
Ajax,.
Puck,.
// Acts and scenes serve as labels. Like the whole play, they can have titles too,
// but for the sake of golfing I didn't give them any.
Act I:
// This scene would've been named "You are nothing"
Scene I:
// Characters can talk to each other when on stage
[Enter Ajax,Puck]
// Characters can assign each other values by talking. Nice nouns = 1, ugly nouns = -1.
Puck: You ox! // Assignment: $ajax = -1;
Ajax: Be me without myself. // Arithmetic: $puck = $ajax - $ajax;
Open thy heart. // Standard output in numerical form: echo $puck;
// Working title "The circle of life"
Scene II:
// Poor Ajax always doing all the work for us
Ajax: Be thyself and ash. // $puck = $puck + (-1);
Open thy heart. // echo $puck;
Be me times you. // $puck *= $ajax; (remember $ajax==-1 from scene I)
Open thy heart. // echo $puck;
Be me times you. // negate again
Let us return to scene II. // infinite goto loop
As you can see when comparing this code to my answer to the related challenge to count up forever (i.e. print all natural numbers), SPL code length grows rather badly when problem size increases...
ForceLang, 87 67 59 bytes
def w io.writeln
w 0
label a
w set i 1+i
w i.mult -1
goto a
RProgN, 22 21 Bytes
►0p11¿]p]0\-p1+]}
Note the trailing space IS required.
Saved a byte by replacing the -1 * n with a simple 0 - n, because defining -1 in ► form takes too many bytes.
Explination
► # Read this word as a single-character based command.
0p # Print the number 0
11 # Push two 1's to the stack.
¿ # While the top of the stack is truthy, pop the top of the stack.
] # Clone the top of the stack, containing i.
p # Print it.
] # Clone it again.
0 \ - * # Push 0 to the stack, swap the 0 and the object underneith it, giving 0, n instead of n, 0. Subtract giving -n.
p # Print it.
1+ # Add one to i
] # Clone it for the next truthy check
} # End the while statement
# Required to interpret the while loop correctly.
Output
0
1
-1
2
-2
3
-3
4
-4
5
...
This language looks nothing like it's former self. ;(
Racket 56 bytes
(saved 12 bytes with suggestion by @StevenH)
(λ()(let l((i 0))(printf"~a, ~a, "i(- -1 i))(l(+ 1 i))))
Ungolfed:
(define(f)
(let loop ((i 0))
(printf "~a, ~a, " i (- -1 i))
(loop (add1 i))))
Following can also be used:
(for((i(in-naturals)))(printf"~a, ~a, "i(- -1 i)))
or:
(for ((i (in-naturals)))
(printf "~a, ~a, " i (- -1 i)))
Testing:
(f)
0, -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, -14, 14, -15, 15, -16, 16, -17, 17, -18, 18, -19, 19, -20, 20, -21, 21, -22, 22, -23, 23
LI, 16 7 bytes
New solution:
R-0P-1P
I feel kinda silly for not realizing I could have done this before. I'm keeping the other one because it shows off more flow control and more functions.
LI is a (very) WIP language that relies primarily on recursion. Every program in LI must take in user-provided input, so the given program here accepts LI's "null" input of 0.
The current Python interpreter is just barely enough to meet the specifications of this challenge, albeit wordy; I'm working on a Racket interpreter that would be able to meet the specs of this challenge with three bytes, but unfortunately it's not even close to challenge-ready.
Explanation:
P Print input
-1 (1 - input)
P Print that too
-0 (- (1 - input))
R Rerun program with new input
Old solution:
R?>0i-0PyPi-0PYP
Roughly, this program translates to:
R Recurse program with input:
P print-return (implicit input)
Y Increment input
P Print incremented
-0 Invert sign
= -(i+1)
?>0i if i is not negative.
-0PyPi If i is negative, do the same but decrement (y) instead of increment.
For both solutions, output is of the following format:
0
1
-1
2
-2
3
-3
...
The default interpreter will run out of memory at -3338 (3342 with the new solution), if you're curious.
Hexagony, 22 18 bytes
!(~2016}Q2;'Oct4!~
Excuse me for keep editing.. After typing the explanations I managed to squeeze.. not so squeeze this into a 3-hexagon and there are still plenty of space to put today's date in.
Old Answer
I have a love at first sight with this language...
!(._/;'<~.2/~/!}Q/>.$>
Expanded
! ( . _ When n<=0, print (-ve number) and n--
/ ; ' < ~ After printing ,
. 2 / ~ / ! If n<=0, n=-n and print (the +ve number)
} Q / > . $ > Else n=-n and go into auto-if
. . . . . .
. . . . .
. . . . When n>0, do nothing as the number is printed at line 3
The basic algorithm is,
Loop: print, if(n<=0) n--, n=-n, then print ,
I come into this answer with the thought of using implicit if by going out of the corner:
! ( . .
. . . . .
. . . . . .
. ~ } Q 2 ; '
. . . . . .
. . . . .
! . . .
However it is real using a lot of bytes for no-ops in putting the ! there, and in the hope of getting the ! (print) back into the main middle loop, I found it hard to print the 0 since the if(n<=0)n-- is run before the main loop for printing. So keep drawing on a whiteboard (it is easier to overwrite a byte on a whiteboard than most of other tools) I came up with the above which puts one extra ~ (negation) after branching at line 2 but saves me from using the no-ops at the end.
Anyone who can guide me how to make beautiful Hexagony explanation images?
JavaScript, 29 26 bytes
Non-infinite version, 26 bytes
Saved 3 bytes thanks to ETHproductions
for(n=1;;)alert([1-n,n++])
will display all integers between -9007199254740991 and 9007199254740992.
Infinite version (ES6), 114 112 bytes
Saved 2 bytes thanks to ETHproductions
for(n=[-1];1;alert(n[a||n.unshift(1),0]?(x=n.join``)+' -'+x:0))for(i=n.length,a=0;i--;a=(n[i]+=1-a)>9?n[i]=0:1);
will display all integers, given infinite time and memory.
PHP, 27 26 bytes
Note that my answer actually outputs PHP_INT_MAX and PHP_INT_MIN, whereas others don't.
for(;;)echo+$i,_,~+$i++,_;
Run like this:
php -d error_reporting=30709 -r 'for(;;)echo+$i,_,~+$i++,_;';echo
This iterates from 0 to PHP_INT_MAX, obviously using post-increment to get the full range and not have an off-by-one error. Then get the negative range by binary negation.XOR-ing with -1
INT_MAX and INT_MIN
A signed integer actually has a 1 bigger range of negative values than positive values. In the case of 64-bit int (PHP default on 64-bit systems) it's -9223372036854775808 upto 92233720368547758087 inclusive. Many answers stop at -9223372036854775807, which is 1 short.
To see the tail of the output (with PHP_INT_MAX and PHP_INT_MIN), just do this:
php -d error_reporting=30709 -r 'for($i=PHP_INT_MAX-5;is_int($i);)echo+$i,_,~+$i++,_;';echo
The is_int is strictly not needed, it just makes sure the loop stops when $i exceeds PHP_INT_MAX and becomes a float, outputting junk for all eternity.
Tweaks
- Use binary negation instead of xor with
-1. Requires another cast tointto handle thenullcase. Saved a byte.
PHP, 24 26 bytes
(24 bytes not displaying PHP_INT_MIN)
for(;;)echo-$i++," $i ";
Output : 0 1 -1 2 -2 3 -3 4 -4 5 -5 6 -6 7 -7 8 -8 9 -9 10 -10 ...
As $i is not defined, you have to cast it as integer (with - or +0)
(26 bytes not displaying PHP_INT_MIN)
for(;;)echo$i+++0," -$i ";
Output : 0 -1 1 -2 2 -3 3 -4 4 -5 5 -6 6 -7 7 -8 8 -9 9 -10 10 ...
Python, 40 bytes
p=print
p(0)
i=1
while 1:p(i);p(-i);i+=1
PHP, 28 27 bytes
for(;1;)echo 1-++$i," $i ";
As aross pointed out in the comments this only outputs PHP_INT_MIN (or indeed PHP_INT_MIN + 1) on a 32 bit implementation of php.
Old versions:
for(;++$i;)echo 1-$i," $i ";
If a leading space is allowed then
for(;++$i;)echo" $i ",1-$i;
Is 1 byte shorter. (same length as new version)
Haxe, 46 bytes
function f(){var i=0;while(0<1)trace(i++,-i);}
Java 7, 151 134 122 118 bytes
import java.math.*;void c(){for(BigInteger i=BigInteger.ONE,y=i;;i=i.add(y))System.out.println(y.subtract(i)+"\n"+i);}
12 bytes saved thanks to @flawr (and @xnor indirectly)
After rule change.. (59 56 63 bytes)
void c(){for(int i=0;i>1<<31;)System.out.println(~--i+"\n"+i);}
Since in Java 2147483647 + 1 = -2147483648, we can't simply do i++ and continue infinitely, since the challenge was to print all numbers once. With the above code with added range, it will instead print all integers from -2147483648 to 2147483647 once each, in the following sequence: 0, -1, 1, -2, 2, -3, 3, -4, ..., 2147483646, -2147483647, 2147483647, -2147483648. Thanks to @OlivierGrégoire for pointing out Java's behavior regarding MIN_VALUE-1/MAX_VALUE+1. Try it here.
Ungolfed & test code:
Try it here - resulting in runtime error
import java.math.*;
class M{
static void c() {
for(BigInteger i = BigInteger.ONE, y = i; ; i = i.add(y)){
System.out.println(y.subtract(i) + "\n" + i);
}
}
public static void main(String[] a){
c();
}
}
Output:
0
1
-1
2
-2
3
-3
4
-4
5
-5
...
C# function 53 bytes
int j;void X(){for(;;)Console.Write($"{j++},-{j},");}
Explanation:
Create a variable "j" in class scope. This will default to have a value of zero. Write and increment value and then write the negative of that value. This will output "0,-1," on the first loop and "1,-2," on the 2nd loop.
C 331 bytes
Note that this outperforms the long version as it really can do as many as memory will permit. It seems like it is bounded by strings of length max(size_t) which is true, but also definitionally the maximum memory that c will let us grab. Unfortunately it is very slow since it thrashes memory.
#include<stdlib.h>
int main(_,a,b,c,d,e)char*a,*b;size_t c,d,e;{return(_==1?printf("0\n"),main(2,0,0,1,0,0):_==2?main(3,"",0,c,0,0),main(2,0,0,c+1,0,0):_==3?(c?d=strlen(a),b=malloc(d),memcpy(b,a,d),b[d+1]=0,main(4,b,0,d,c-1,9),free(b),0:(*a-48?printf("%s\n-%s\n",a,a):0)):(e+1?a[c]=e+48,main(3,a,0,d,0,0),main(4,a,0,c,d,e-1):0));}
Prints 0, then 9,8,7,... then 99,98,97... etcetera. Can save 3 characters if we assume we don't care about output buffering (swapping \n for a space).
Process:
Initial
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// prints base 0...0, base 0...1, etc with remaining digits after it.
void print_digit_permutations(char *base, size_t remaining)
{
int i;
char *newbase = malloc(strlen(base)+1);
if (!remaining) {
if (*base != '0')
printf("%s\n-%s\n",base,base);
return;
}
for (i = 0; base[i]; ++i) {
newbase[i] = base[i];
}
newbase[strlen(base)+1] = 0;
for (i = 0; i < 10; ++i) {
newbase[strlen(base)] = i + '0';
print_digit_permutations(newbase, remaining-1);
}
free(newbase);
}
int main()
{
char *base = "";
size_t i = 0;
printf("0\n");
for (;;) {
print_digit_permutations(base, ++i);
}
return 0;
}
Unrolled
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void base_copy(char *newbase, char *base)
{
if (*base) {
*newbase = *base;
base_copy(newbase+1,base+1);
}
}
void print_digit_permutations(char*,size_t);
void print_all_digits(char *newbase, size_t baselen, size_t remaining, size_t count)
{
if (count+1) {
newbase[baselen] = count + '0';
print_digit_permutations(newbase,remaining);
print_all_digits(newbase,baselen,remaining,count-1);
}
}
void print_digit_permutations(char *base, size_t remaining)
{
int i;
char *newbase = malloc(strlen(base)+1);
if (!remaining) {
if (*base != '0')
printf("%s\n-%s\n",base,base);
return;
}
base_copy(newbase,base);
newbase[strlen(base)+1] = 0;
print_all_digits(newbase,strlen(base),remaining-1,9);
free(newbase);
}
void all(size_t size)
{
print_digit_permutations("",size);
all(size+1);
}
int main()
{
printf("0\n");
all(1);
return 0;
}
Flat
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int print_digit_permutations(char *base, char *newbase, size_t remaining, size_t baselen, size_t _);
int print_all_digits(char *newbase, char *_, size_t baselen, size_t remaining, size_t count)
{
return (count+1?
newbase[baselen] = count + '0',
print_digit_permutations(newbase,newbase,remaining,0,0),
print_all_digits(newbase,newbase,baselen,remaining,count-1)
:
0);
}
int print_digit_permutations(char *base, char *newbase, size_t remaining, size_t baselen, size_t _)
{
return (remaining?
baselen=strlen(base),
newbase = malloc(baselen),
memcpy(newbase,base,baselen),
newbase[baselen+1] = 0,
print_all_digits(newbase,newbase,baselen,remaining-1,9),
free(newbase),
0
:
(*base-'0'?printf("%s\n-%s\n",base,base):0));
}
int all(char *_, char *_2, size_t size, size_t _3, size_t _4)
{
return print_digit_permutations("","",size,0,0),
all(_,_2,size+1,_3,_4);
}
int main()
{
return printf("0\n"),all("","",1,0,0);
}
Main
#include <stdlib.h>
/* _ values:
*
* 1 - main
* 2 - all
* 3 - print_digit_permutations
* 4 - print_all_digits
*/
int main(_,a,b,c,d,e)char*a,*b;size_t c,d,e;{
switch (_) {
case 1:
return printf("0\n"),main(2,0,0,1,0,0);
case 2:
return main(3,"",0,c,0,0),main(2,0,0,c+1,0,0);
case 3:
return (c?
d=strlen(a),
b=malloc(d),
memcpy(b,a,d),
b[d+1]=0,
main(4,b,0,d,c-1,9),
free(b),
0
:
(*a-'0'?printf("%s\n-%s\n",a,a):0));
case 4:
return (e+1?
a[c]=e+'0',
main(3,a,0,d,0,0),
main(4,a,0,c,d,e-1)
:0);
}
}
And after removing whitespace and making a few other small changes we arrive at the initial golfed code. It is interesting that the 'proper' initial code is the second shortest at just over 700 bytes.
R, 33 29 bytes
x=0;while(T)cat("",-x,x<-x+1)
Output (for < 10)
0 1 -1 2 -2 3 -3 4 -4 5 -5 6 -6 7 -7 8 -8 9 -9 10
Explanation
It works because x is set to 0, then prints -0 which displays as 0. It then increments and prints that, giving 1. The next element is the negative value of the last which is -1 and so on...
EDIT: Cut it down by 4 bytes after I realised that I could just have it loop forever. In R, T is TRUE by default.
JavaScript (ES5), 32 31 30 29 bytes
for(i=0;;)[i++,-i].map(alert)
Prints 0 -1 1 -2 2 -3 3 -4 4 -5 5 ...
Saved 1 byte thanks to Patrick Roberts! Saved 2 bytes thanks to Conor O'Brien!
Java, 49 bytes
o->{for(int n=1<<31;n<0;)o.println(n+"\n"+~n++);}
Notes:
ois ajava.io.PrintStreambut its import is not required given it's the parameter of a lambda expression.- This must be run on a Unix machine to properly use the same separator.
Ungolfed
import java.io.PrintStream;
import java.util.function.Consumer;
public class Main {
public static void main(String[] args) {
Consumer<PrintStream> func = o -> { // define the output and start the function.
for (int n = 1 << 31; n < 0; n++) { // for each negative integer increasing from Integer.MIN_VALUE
o.println(n + "\n" + ~n); // Print the negative number and its complement to 2 value.
}
};
func.accept(System.out);
}
}
Result
-2147483648
2147483647
-2147483647
2147483646
-2147483646
2147483645
-2147483645
2147483644
-2147483644
2147483643
-2147483643
2147483642
-2147483642
2147483641
-2147483641
2147483640
...
-7
6
-6
5
-5
4
-4
3
-3
2
-2
1
-1
0
Brainfuck, 127 bytes
+[-->+>+[<]>-]>-->+[[.<<<]>>-.>>+<[[-]>[->+<]++++++++[-<++++++>>-<]>--[++++++++++>->-<<[-<+<+>>]]>+>+<]<<<[.<<<]>>.+.>[>>>]<<<]
Given an infinite tape would theoretically run forever.
0,1,-1,2,-2,3,-3,4,-4,5,-5,6,-6,7,-7,8,-8,9,-9,10,-10,11,-11,12,-12,13,-13,14,-14,15,-15,16,-16,17,-17,18,-18,19,-19,20,-20,21,-21,22,-22,23,-23,24,-24,25,-25,26,-26,27,-27,28,-28,29,-29,30,-30,31,-31,32,-32,33,-33,34,-34,35,-35,36,-36,37,-37,38,-38,39,-39,40,-40,41,-41,42,-42,43,-43,44,-44,45,-45,46,-46,47,-47,48,-48,49,-49,50,-50,51,-51,52,-52,53,-53,54,-54,55,-55,56,-56,57,-57,58,-58,59,-59,60,-60,61,-61,62,-62,63,-63,64,-64,65,-65,66,-66,67,-67,68,-68,69,-69,70,-70,71,-71,72,-72,73,-73,74,-74,75,-75,76,-76,77,-77,78,-78,79,-79,80,-80,81,-81,82,-82,83,-83,84,-84,85,-85,86,-86,87,-87,88,-88,89,-89,90,-90,91,-91,92,-92,93,-93,94,-94,95,-95,96,-96,97,-97,98,-98,99,-99,...
Uncompressed
+[-->+>+[<]>-]>-->+
[
[.<<<]>>-.>>+<
[[-]>[->+<]
++++++++[-<++++++>>-<]>--
[++++++++++>->-<<[-<+<+>>]]>+>+<
]<<<
[.<<<]>>.+.>
[>>>]<<<
]
Labyrinth, 9 bytes
!`
\:"
(
This also works and is essentially the same:
"
`:(
\!
Explanation
The control flow in this code is rather funny. Remember that the instruction pointer (IP) in a Labyrinth program follows the path of non-space characters and examines the top of the stack at any junction to decide which path to take:
- If the top of the stack is positive, turn right.
- If the top of the stack is zero, keep moving straight ahead.
- If the top of the stack is negative, turn left.
When the IP hits a dead end, it turns around (executing the command at the end only once). And the IP starts in the top left corner moving east. Also note that the stack is implicitly filled with an infinite amount of zeros to begin with.
The program starts with this short bit:
! Print top of stack (0).
` Multiply by -1 (still 0).
: Duplicate.
Now the IP is at the relevant junction and moves straight ahead onto the ( which decrements the top of the stack to -1. The IP hits a dead end and turns around. : duplicates the top of the stack once more. Now the top of the stack is negative and the IP turns left (west). We now execute one more iteration of the main loop:
\ Print linefeed.
! Print top of stack (-1).
` Multiply by -1 (1).
: Duplicate.
This time, the top of the stack is positive, so IP turns right (west) and immediately executes another iteration of the main loop, which prints the 1. Then after it is negated again, we hit the : with -1 on the stack.
This time the IP turns left (east). The " is just a no-op and the IP turns around in the dead end. : makes another copy and this time the IP turns south. ( decrements the value to -2, the IP turns around again. With the top of the stack still negative, the IP now turns west on the : and does the next iteration of the main loop.
In this way, the IP will now iterate between a tight loop iteration, printing a positive number, and an iteration that goes through both dead ends to decrement the value before printing a negative number.
You might ask yourself why there's the " on the second line if it doesn't actually do anything: without it, when the IP reaches : on a negative value, it can't turn left (east) so it would turn right (west) instead (as a rule of thumb, if the usual direction at a junction isn't available, the IP will take the opposite direction). That means the IP would also never reach the ( at the bottom and we couldn't distinguish positive from negative iterations.
Brainfuck, 10 bytes
.+[>-.<.+]
Does not rely on cell wrapping to print the negative values. Does rely on accepting the cell value, which is commonly printed as a character by converting it to ASCII, to be the value to print.
k (20 bytes)
The function between curly braces is repeatedly iterated on it's result, starting at zero, until the result converges at 0W (k infinity).
{-1@'$?-1 1*x;x+1}/0
The function prints the argument and its negation and then returns incremented argument.
C# 74 bytes
class P{void Main(){for(var x=0m;;System.Console.Write(x+++","+-x+","));}}
class P
{
void Main()
{
for(var x = 0m; ; System.Console.Write(x++ + "," + -x + ","));
}
}
Output:
0,-1,1,-2,2,-3,3,-4,4,-5,5,-6,6,-7,7,-8,8,-9,9,-10,10,...
Try it:
dotnetfiddle.net (limited to 1000)
Burlesque, 12 bytes
0R@J-1?*_+[-
You can try a restricted version here.
0R@ Range from 0 to Infinity
J Duplicate
-1?* Multiply one Block by -1 (negative integeres)
_+ Concatenate
[- Tail to Remove the duplicate zero
Retina, 21 19 bytes
{M*`.
^
1
*`.+
-$.&
Try it online! (Takes about a minute before you see anything.)
DC (GNU or OpenBSD flavour) - 16 bytes
This version is not shorter than the version below but should be able to run without the stack exploding in your PC. Nevertheless infinite large numbers will take up infinite amounts of memory... somewhen...
Because of the r command it needs GNU-DC or OpenBSD-DC.
0[rp1+45Pprdx]dx
Test:
$ dc -e '0[rp1+45Pprdx]dx' | head
0
-1
1
-2
2
-3
3
-4
4
-5
DC - 16 bytes
A little bit mean now. ;-)
This version is abusing the stack length as counter while letting the stack grow.
z[pz45Ppllx]dslx
Test:
$ dc -e 'z[pz45Ppllx]dslx' | head
0
-1
1
-2
2
-3
3
-4
4
-5
DC - 17 bytes
Without dirty tricks.
0[p1+45Ppllx]dslx
Test:
$ dc -e '0[p1+45Ppllx]dslx' | head
0
-1
1
-2
2
-3
3
-4
4
-5
Actually, 7 bytes
01W;±@u
This solution requires infinite time to actually print anything. Finite memory will cause an out of memory error and premature printing. No TIO link for obvious reasons.
Explanation:
01W;±@u
0 push 0
1 push 1
W infinite loop:
; duplicate
± unary negate
@ swap with positive
u increment
This solution works for 8 bytes, prints a finite amount of numbers in a finite amount of time, and uses significantly less memory (the memory used doesn't start growing until after INT_MAX is printed, at which point Python seamlessly transitions to arbitrary-precision integers).
0■~W■±■~
Try it online! (only prints up to around 9292 due to timeout).
Explanation:
0■~W■±■~
0 push 0
■ print entire stack without popping (just the 0)
~ bitwise negate (~n is equivalent to -n-1)
W infinite loop:
■ print stack without popping
± unary negate
■ print without pop
~ bitwise negate
dc, 16 bytes
zpc[zp0r-prdx]dx
Explanation:
zp # Push stack depth (0) and peek (print top of stack and newline without popping)
c # Clear stack
[ # Open macro definition
z # Push stack depth (1 on first iteration, because this macro is on the stack)
p # Peek (print positive number)
0r- # Subtract ToS from 0 (make negative)
p # Peek (print negative number)
rdx # Rotate (move this macro on top of the negative number), duplicate, and execute
]dx # Duplicate string and execute as macro
This does feel a little too similar to yeti's answer; however, this solution makes use of all-natural, grass-fed, free-range negative numbers!
In case anyone finds these to be of interest, here are some other approaches I tried:
zp[zp_1/plax]dsax # uses a named macro rather than a stack-squatting macro
zpc[zdp;ar-prdx]dx # uses an array to fetch a 0 for subtracting from...in retrospect this
# is just a longer way of writing `0' and has no advantages whatsoever
0p[z1-p_1~+prdx]dx # uses ~ with -1 to convert a positive to a negative
0p[zp_1~+plax]dsax # uses ~ with _1 in a named macro
# The difference between the two above is in stack depth: Since the
# named macro doesn't reside perpetually on the stack, we don't lose
# access to a number through `z'. Because the first macro must stay on
# the stack, we have to decrement (`1-') to start with 1 and -1. (Both
# methods require explicitly printing 0 so that it's only printed once.)
0p[zp0r-pzz>a]dsax # uses an always-true conditional, which is also kind of pointless
0p[zp_1*ddp=a]dsax # `_1*' == `0r-'; `ddp=a' == `pzz>a'; just some alternative notations
z[p1+_1/p_1/lax]dsax # I don't remember what I was doing with these last two
[zpd_1/+z-p0d=a]dsax #
Even though these other methods are all longer, I think at least half the fun is in discovering new mechanisms that one could adapt for use in other situations.
Jelly, 5 bytes
Ṅ~ṄNß
How it works
Ṅ~ṄNß Main link. Argument: n. Implict argument: 0
Ṅ Print n and a linefeed.
~ Apply bitwise NOT, yielding -(n + 1).
Ṅ Print -(n + 1) and a linefeed.
N Negate, yielding n + 1.
ß Recursively call the main link with argument n + 1.
C# 222 bytes (Infinite output version)
Being more fond of the infinite output version of the print-all-integers program, I created this.
IEnumerable<string>g(){var w=new[]{'0'};yield return "0";while(true){var c=true;for (var r=w.Length-1;c&&r>=0;r--)if(c=++w[r]==58)w[r]='0';var b=new string(w);if(c)w=(b="1"+b).ToArray();yield return b;yield return "-"+b;}}
This function continuously returns the next greater positive and negative integers. The values are not limited by the integer type but since integers are used to handle the array, the program will fail when the number has more than 2,147,483,647 digits. However, it will most likely run out of memory long before that happens.
Usage:
static void Main(string[] args)
{
foreach (var n in g())
{
Console.WriteLine(n);
}
}
bc, 17 16 bytes
Edit: 1 byte less thanks to Digital Trauma.
Adding to the diversity of languages used so far, I present a bc solution that works with integers of arbitrary size. A newline is required after the code and it is counted in the bytes total.
for(;;){i;-++i}
In the first iteration i is not defined, but printing it gives 0 to my surprise.
Bash + GNU utilities, 26
seq NaN|sed '1i0
p;s/^/-/'
Powershell, 20 19 18 bytes
Improved by stealing shamelessly from TimmyD's answer
0;for(){-++$i;$i}
Output:
0
-1
1
-2
2
-3
3
-4
4
Old version:
for(){-$i;$i++;$i}
Not sure why tbh, but -undeclared variable (or -$null) is evaluted as 0, which saved us 2 bytes in this version...
><>, 19 15 bytes
1::1$-naonao1+!
This prints the following:
0
1
-1
2
-2
3
-3
... and so on. The separator is a newline.
Re-written after reading @xnor's answer to use a version of that algorithm. Starting at n=1, the program prints 1-n and n, each followed by a newline, before incrementing n. After overflowing the maximum value the program will end with an error of something smells fishy.... Exactly when this will happen depends on the interpreter implementation.
Previous version:
0:nao0$-:10{0(?$~+!
Starting at 0, the program loops indefinitely. On each loop, the current value is printed along with a newline. It is then negated, and incremented if positive.
bash, 46 Bytes
echo 0;for((i=1;;i++)){ echo -e "$i\n-$i"; }
Swift 3 (34 bytes)
(Int.min...Int.max).map{print($0)}
Really, we should be able to get this down to 30 bytes like so:
(Int.min...Int.max).map(print)
But the compiler doesn't allow this yet.
C++ with Boost, 143 bytes
#include <boost/multiprecision/cpp_int.hpp>
#include <iostream>
boost::multiprecision::cpp_int i;main(){while(++i)std::cout<<1-i<<','<<i<<',';}
Not very short, but it does use an arbitrary-precision type. To test that, I tried replacing ++i with i=2*i+1, and very soon there were numbers several hundred digits long being printed correctly. This should work until the number takes up all your stack memory.
Vim, 19 keystrokes
i0<cr>1<esc>qqYpi-<esc>p<C-a>@qq@q
Creates a recursive macro that duplicates a number, makes it negative, prints the original number again and increments it.
C, 51 50 bytes
void f(){long i=0;for(;;)printf("%d %d ",i++,-i);}
I could save a byte by doing int instead of long, but since this can go longer than int without wrapping I'm leaving it.
Output:
0 -1 1 -2 2 -3 3 -4 4 -5 5 -6 6 ...
Sesos, 113 3 bytes
0000000: c4ceb9 ...
Try it online! Check Debug to see the generated SBIN code.
Sesos assembly
The binary file above has been generated by assembling the following SASM code.
set numout
jmp ; implicitly promoted to nop
put, fwd 1
sub 1, put
rwd 1, add 1
; jnz (implicit)
Bash, 33 55 bytes
for((;;)){ echo -n $[-i++],$i,;((i==LLONG_MAX))&&exit;}
Unfortunately bash won't give an integer overflow error when $i exceeds the maximum size of the type used to store it. Therefore, I updated the code to include a termination criteria, that requires $LLONG_MAX to be defined in the environment or passed on the command line.
Run example: on my system bash uses signed 64-bit integers
LLONG_MAX=$[2**63-1] ./all_integers.sh
The following code is a 32 byte version (1 less) of my original post, that assumed undefined printing behavior after the integer overflow.
for((;;)){ echo -n $[-i++],$i,;}
Non-wrapping Brain****, 9 bytes
Thanks to Scepheo for saving one byte!
+[.+<.->]
Oracle SQL 11.2, 77 73 72 68 bytes
SELECT CEIL((LEVEL-1)/2)*(MOD(LEVEL,2)*2-1)FROM DUAL CONNECT BY 1=1;
Perl, 19 bytes
perl -E 'say-$}while say$}++'
In reality will get stuck when at some huge number $} switched to floating point and starts losing precision.
This 27 byte version will really print forever:
perl -E 's//0/;say"-".++$_ while say'
Lua , 43 Bytes
i=1;while 1 do print(1-i);print(i);i=i+1 end
GNU sed, 189 + 2(rn flags) = 191 bytes
This is most likely the longest solution, since sed has no integer type or arithmetic operations. As such, I had to emulate an arbitrary size increment operator using regular expressions only.
s/^/0/p
:
:i;s/9(@*)$/@\1/;ti
s/8(@*)$/9\1/
s/7(@*)$/8\1/
s/6(@*)$/7\1/
s/5(@*)$/6\1/
s/4(@*)$/5\1/
s/3(@*)$/4\1/
s/2(@*)$/3\1/
s/1(@*)$/2\1/
s/0(@*)$/1\1/
s/^@+/1&/;y/@/0/
s/^/-/p;s/-//p
t
Run:
echo | sed -rnf all_integers.sed
Output:
0
-1
1
-2
2
-3
3
etc.
Befunge 93, 8 bytes
:.-:0`!-
Explanation
Befunge's stack is thankfully filled with an implicit infinite amount of zeros, and printing a number also prints a trailing space.
:. Print the top of the stack.
- Subtract it from the implicit zero underneath, effectively multiplying by -1.
:0` Check whether its greater than 0.
! Logical NOT. Gives 0 if the current value is positive and 1 otherwise.
- Subtract from current value.
The source code is toroidal so this program repeats indefinitely.
Perl 6, 22 bytes
loop {say $--;say ++$}
Explanation:
loop {
say (state $ = 0)--; # prints 「0」 first time around, then 「-1」 「-2」 etc
say ++(state $ = 0) # prints 「1」 first time around, then 「2」 「3」 etc
}
MATLAB 65 bytes
My earlier post was faulty because the loop does not stop. A better try is this:
a=intmin('int64');(a:-a)'
but while this will work for the smaller int8 type it will not for int64 as the maximum array size will (of course) be exceeded. Note that transposing the vector prevents the console output from being interrupted by 'columns m to n' messages.
Another funny with MATLAB is that integers do NOT roll over, thus intmax('int64') + 1 == intmax('int64') not intmin('int64') as I expected. Also, MATLAB does not have a 'do' loop, So the best I can think of is this:
a=intmin('int64');b=-a;while(1) a, if a==b break, end; a=a+1; end
an then only if we allow the 'any separator' to allow this:
a =
-9223372036854775808
a =
-9223372036854775807
...
a =
9223372036854775806
a =
9223372036854775807
There must be a better way!
Pyth , 7 bytes
0.V1_bb
Explanation
0 # print 0
.V1 # increment 'b' forever, starting on 1
_b # print -b
b # print b
><>, 11 bytes
lnao0l-naol
Try it online! Uses the stack length as a counter.
ln Output length of stack
ao Output newline
0l-n Output 0 - (length of stack + 1), +1 because of the additional 0
ao Output newline
l Push length of stack, increasing the stack length by 1
(Implicit loop since ><> is toroidal)
MATL, 8 bytes
0`@_@XDT
This uses MATL's default data type, which is double, so it works up to 2^53 in absolute value. The output is
0
-1
1
-2
2
···
Explanation
0 % Push 0
` T % Do...while true: infinite loop
@_ % Push iteration index and negate
@ % Push iteration index
XD % Display the whole stack
PowerShell v2+, 26 bytes
0;for(;$i-lt2gb){$i;-++$i}
Covers all 32-bit [int] values, as that's the default number type for PowerShell. Prints 0, then loops up to 2gb (which is a special operator, not a constant, yielding 2147483648). Must be called as a full program so that $i properly defaults back to $null.
Example
PS C:\Tools\Scripts> 0;for(;$i-lt2gb){$i;-++$i}
0
-1
1
-2
2
...
2147483646
-2147483647
2147483647
-2147483648
Truly infinite, 34 bytes
0;for([bigint]$i=1;;$i+=1){$i;-$i}
For a truly infinite variation that will (eventually) print every single integer in existence given infinite time and memory, try the above. We simply tack on the [bigint] cast and change slightly how the loop is calculated.
Reticular, 12 bytes
0dp1+dpd0#2j
Explanation
0dp1+dpd0#2j ; stack
0 ; [0]
dp ; [0] PRINTED 0
1+ ; [1]
dp ; [1] PRINTED 1
d0# ; [1, -1]
2j ; skip two spaces after the j, wrapping to..
p ; [1] PRINTED -1
1+ ; [2]
dp ; [2] PRINTED 2
d0# ; [2] PRINTED -2
; etc.
J, 25 bytes
([:$:1:`-`(1+-)@.*[echo)0
Works on the online site, but I can't verify it on computer yet. Prints numbers like:
0
1
_1
2
_2
3
_3
4
etc.
MATLAB 64 bytes
As a start, with nothing clever:
fprintf('0');a=int64(1);while(1) fprintf(' %d',[a -a]);a=a+1;end
Enter at the console, generates 0 1 -1 2 -2...
There must be a better way than this! Come on, folks...
Octave, 30 bytes
x=0;while 1;disp([x++;-x]);end
Explanation:
x=1; % Initialize x to 1
while 1; % Infinite loop since 1 == true
[x++,-x] % x, then post increment and show the negative version
disp(___) % display it
end
Prints the following sequence, starting from 0:
0
-1
1
-2
2
-3
3
.
.
C# 86 66 bytes
New answer:
void b(){for(var i=0;;i++)Console.Write(i==0?","+i:","+i+",-"+i);}
Clear:
void b()
{
for(var i=0;;i++)
Console.Write(i == 0 ? "," + i : "," + i + ",-" + i);
}
Old answer (86 bytes):
void a(){Console.Write(String.Join(",",Enumerable.Range(int.MinValue,int.MaxValue)));}
Ungolfed:
void a()
{
Console.Write(String.Join(",", Enumerable.Range(int.MinValue, int.MaxValue)));
}
C#, 83 bytes
void f(){for(decimal n=0;;n++){Console.Write(n+",");if(n>0)Console.Write(-n+",");}}
Ungolfed:
void f()
{
for (decimal n=0;;n++)
{
Console.Write(n + ",");
if (n > 0) Console.Write(-n + ",");
}
}
Outputs:
0,1,-1,2,-2,3,-3,4,-4,5,-5,6,-6.......
05AB1E, 9 6 bytes
Saved 3 bytes thanks to Adnan
[ND,±,
Prints 0, -1, 1, -2, 2 ... separated by newlines.
Java, 65 54 bytes
i->{for(;;)System.out.print(i+++" "+(-i<i?-i+" ":""));
Ungolfed test code
public static void main(String[] args) {
Consumer<Integer> r = i -> {
for (;;) {
System.out.print(i++ + " " + (-i < i ? -i + " " : ""));
}
};
r.accept(0);
}
Caché ObjectScript, 28 bytes
w 0 f i=1:1 {w ",",i,",",-i}
ShadyAsFuck, 3 bytes
FVd
Explanation:
F prints the current cell value (0) and increases it by 1
V starts a loop and prints the current value
d increases the current value and ends the loop
This makes use of the cell wrapping and prints all possible values. In SAF, the native integer representation is by byte value.
Haskell, 19 bytes
do n<-[1..];[1-n,n]
Produces the infinite list [0,1,-1,2,-2,3,-3,4,-4,5,-5,6,-6,7,-7...
Haskell allows infinite lists natively. Printing such a list will prints its elements one a time forever.
Batch, 56 bytes
@set n=0
:l
@echo %n%
@set/an+=1
@echo -%n%
@goto l
Output:
0
-1
1
-2
2
-3
etc. Works up to 2147483647; 58 bytes if you want (-)2147483648 in the output:
@set n=0
:l
@echo %n:-=%
@set/an-=1
@echo %n%
@goto l
44 bytes if printing all supported positive integers, then all supported negative integers, then repeating endlessly, is acceptable:
@set n=0
:l
@echo %n%
@set/an+=1
@goto l
Python 2, 27 bytes
n=0
while 1:print~n,n,;n+=1
Prints -1 0 -2 1 -3 2 -4 3 ...





