Print all integers

Write a program or function which will provably print all integers exactly once given infinite time and memory.

Possible outputs could be:

0, 1, -1, 2, -2, 3, -3, 4, -4, …

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -2, -3, -4, -5, -6, -7, -8, -9, 10, 11, …


This is not a valid output, as this would never enumerate negative numbers:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …

• The output must be in decimal, unless your language does not support decimal integer (in that case use the natural representation of integers your language uses).

• Your program has to work up to the numbers with the biggest magnitude of the standard integer type of your language.

• Each integer must be separated from the next using any separator (a space, a comma, a linebreak, etc.) that is not a digit nor the negative sign of your language.

• The separator must not change at any point.

• The separator can consist of multiple characters, as long as none of them is a digit nor the negative sign (e.g. ,  is as valid as just ,).

• Any supported integer must eventually be printed after a finite amount of time.

Scoring

This is , so the shortest answer in bytes wins

var QUESTION_ID=93441,OVERRIDE_USER=41723;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

• If our language supports infinite lists, can we output the list from a function rather than printing? (Calling print on such a list would print its elements one at a time forever.) – xnor Sep 16 '16 at 8:57
• I feel like the requirement on arbitrary-size integers does nothing but discourage languages without such integers from participating. They either have to have an import they can use or solve a totally different challenge from everyone else. – xnor Sep 16 '16 at 9:10
• @xnor Changed, though that kinds of ruins the very name of the challenge. – Fatalize Sep 16 '16 at 9:14
• @xnor, languages with arbitrary precision integers still have to solve a different problem from everyone else, so all that that change has accomplished is to make this problem boringly trivial in a lot of languages. – Peter Taylor Sep 16 '16 at 9:54
• @PeterTaylor Yeah, this is unfortunate. The wrapping solutions don't feel to me like they are printing any negatives, but I don't see a way to firmly specify the difference when it's a matter of representation. – xnor Sep 16 '16 at 9:58

><>, 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:

say ++(state $= 0) # prints ｢1␤｣ first time around, then ｢2␤｣ ｢3␤｣ etc }  bash, 46 Bytes echo 0;for((i=1;;i++)){ echo -e "$i\n-\$i"; }

• You don't need a space after ;, or after {. – Peter Cordes Sep 16 '17 at 7:37

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.

• "In case anyone finds these to be of interest" ... I do! ;-) – user19214 Sep 17 '16 at 6:34

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

• This solution requires infinite time to actually print anything contradicts Any supported integer must eventually be printed after a finite amount of time – Fatalize Sep 17 '16 at 13:01
• @Fatalize Integers will be printed after a finite amount of time, if there's a finite amount of memory available. – Mego Sep 17 '16 at 17:59
• and they will never get printed in a finite amount of time with an infinite amount of memory, so this answer is invalid – Fatalize Sep 17 '16 at 18:13
• @Fatalize Then please clarify that in the challenge body. – Mego Sep 17 '16 at 20:46

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.

• Seems invalid: "The separator must not change at any point." – primo Sep 17 '16 at 8:09
• @primo, better now? – Mark Sep 17 '16 at 16:47

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.

Haxe, 46 bytes

function f(){var i=0;while(0<1)trace(i++,-i);}


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))


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

• You can avoid the first printf entirely by replacing (* i -1) with (- -1 i). – Steven H. Oct 7 '16 at 6:17
• Thanks for the suggestion. I have added it to my answer. – rnso Oct 7 '16 at 6:29

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. ;(

ForceLang, 8767 59 bytes

def w io.writeln
w 0
label a
w set i 1+i
w i.mult -1
goto a


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.

MATL, 9 bytes

0t_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)


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.

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.

Try it online

(@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:

Try it online

(({})()){([([({})])]())}


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.

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++));


JS (NON - ES6), 25 bytes

for(n=0;;)alert([~n,n++])


Uses binary NOT (~) for reverse sign and deincrement.

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.