67
\$\begingroup\$

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

Leaderboard

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>

\$\endgroup\$
25
  • 6
    \$\begingroup\$ 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.) \$\endgroup\$
    – xnor
    Commented Sep 16, 2016 at 8:57
  • 7
    \$\begingroup\$ 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. \$\endgroup\$
    – xnor
    Commented Sep 16, 2016 at 9:10
  • 3
    \$\begingroup\$ @xnor Changed, though that kinds of ruins the very name of the challenge. \$\endgroup\$
    – Fatalize
    Commented Sep 16, 2016 at 9:14
  • 6
    \$\begingroup\$ @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. \$\endgroup\$ Commented Sep 16, 2016 at 9:54
  • 3
    \$\begingroup\$ @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. \$\endgroup\$
    – xnor
    Commented Sep 16, 2016 at 9:58

165 Answers 165

1
2 3 4 5 6
51
\$\begingroup\$

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.

\$\endgroup\$
6
  • 4
    \$\begingroup\$ I love [n,1-n]! \$\endgroup\$
    – flawr
    Commented Sep 16, 2016 at 9:22
  • 5
    \$\begingroup\$ IMHO [1-n,n] would produce nicer output. \$\endgroup\$
    – Neil
    Commented Sep 16, 2016 at 9:47
  • 1
    \$\begingroup\$ @Neil I agree, changed it. \$\endgroup\$
    – xnor
    Commented Sep 16, 2016 at 9:51
  • 2
    \$\begingroup\$ Ah, that's monadese for concatMap (\n -> [1-n, n]) [1..], right? Nice! \$\endgroup\$
    – Carsten S
    Commented Sep 17, 2016 at 16:17
  • \$\begingroup\$ @CarstenS Yes, exactly. \$\endgroup\$
    – xnor
    Commented Sep 17, 2016 at 18:51
31
\$\begingroup\$

Brainfuck, 6 bytes

This makes use of the cell wrapping and prints all possible values. In Brainfuck, the native integer representation is by byte value.

.+[.+]

Try it online!

\$\endgroup\$
10
  • 4
    \$\begingroup\$ Nice, this is the shortest Brainfuck answer I've seen so far on PPCG. \$\endgroup\$ Commented Sep 16, 2016 at 11:10
  • 19
    \$\begingroup\$ @JanDvorak Answers don't need to work in every implementation, just in any one of them. \$\endgroup\$ Commented Sep 16, 2016 at 13:39
  • 9
    \$\begingroup\$ Could i get an explanation of why this is valid? There are no seperators as mentioned in the question and no negatives. As well as the fact that you can output values greater then 9 in brainfuck. Im inexperience at code golf and started working on something that output negative and positive seperated upto higher numbers before gicing up. \$\endgroup\$
    – gtwebb
    Commented Sep 17, 2016 at 2:41
  • 2
    \$\begingroup\$ I think it could be argued equally well that each cell on the BF tape represents a digit. \$\endgroup\$
    – primo
    Commented Sep 17, 2016 at 9:46
  • 5
    \$\begingroup\$ @SQB Even with unlimited memory, the native type of integers is still 8bit. A Java int doesn't suddenly have more or less bits just because you added or removed some ram. \$\endgroup\$
    – flawr
    Commented Sep 17, 2016 at 19:06
31
\$\begingroup\$

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:

enter image description here

The IP starts on the red trail at the far left of the image. It then runs OSo;, which does the following:

  • O Print the TOS (top-of-stack) as an integer. At the beginning of the program, the stack contains infinite zeroes, so this prints 0.
  • S Push 32, the char code for the space character.
  • o Print the TOS as a character. This prints a space.
  • ; Pop the TOS. Removes the 32 from 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:

  1. Output the current number and a space.
  2. If the current number is negative, decrement it by 1.
  3. 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).

\$\endgroup\$
2
  • 4
    \$\begingroup\$ Nice diagram! :) Did you create that by hand or write a tool to generate it? \$\endgroup\$ Commented Sep 16, 2016 at 18:02
  • 5
    \$\begingroup\$ @MartinEnder Thank you! It was inspired by your Hexagony diagrams. I created that one by hand; though I'd like to write a tool for generating them when I have enough time to do so. \$\endgroup\$ Commented Sep 16, 2016 at 18:21
22
\$\begingroup\$

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)
\$\endgroup\$
3
  • 1
    \$\begingroup\$ how is this 3 bytes ? \$\endgroup\$ Commented Nov 27, 2016 at 1:39
  • 1
    \$\begingroup\$ The readme on GitHub (linked in the header) explains in detail how the instructions are encoded. \$\endgroup\$
    – Dennis
    Commented Nov 27, 2016 at 2:47
  • 3
    \$\begingroup\$ 6 hex digits / 2 = 3 bytes @HopefullyHelpful \$\endgroup\$
    – Stan Strum
    Commented Sep 12, 2017 at 20:45
21
\$\begingroup\$

Python 2, 27 bytes

n=0
while 1:print~n,n,;n+=1

Prints -1 0 -2 1 -3 2 -4 3 ...

\$\endgroup\$
1
  • 1
    \$\begingroup\$ TIO link \$\endgroup\$
    – naffetS
    Commented May 5, 2020 at 18:25
21
\$\begingroup\$

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

Try it online!

Explanation

0            % Push 0
  `     T    % Do...while true: infinite loop
   @_        % Push iteration index and negate
     @       % Push iteration index
      XD     % Display the whole stack
\$\endgroup\$
10
  • \$\begingroup\$ Why is there such a big delay before it starts printing? \$\endgroup\$
    – Fatalize
    Commented Sep 16, 2016 at 9:45
  • \$\begingroup\$ @Fatalize I think Octave needs to be restarted for every time you run a MATL program in TIO, and that takes some time. \$\endgroup\$
    – flawr
    Commented Sep 16, 2016 at 9:47
  • 1
    \$\begingroup\$ Smart idea to do @_@XD rather than @_D@D so you can include the 0 on the first run. \$\endgroup\$
    – Sanchises
    Commented Sep 16, 2016 at 10:22
  • 3
    \$\begingroup\$ XD +1 for smiley \$\endgroup\$ Commented Sep 16, 2016 at 18:37
  • 1
    \$\begingroup\$ @_@ +1 for smiley \$\endgroup\$
    – user85052
    Commented Dec 14, 2019 at 6:37
20
\$\begingroup\$

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

\$\endgroup\$
4
  • 2
    \$\begingroup\$ I like this. It's terrible for golfing, but wonderful for reading. \$\endgroup\$
    – swinefish
    Commented Sep 19, 2016 at 7:36
  • \$\begingroup\$ Typo on the last line of the explanation. Let us return to scene II. should be scene I. \$\endgroup\$
    – Oliver Ni
    Commented Oct 8, 2016 at 23:08
  • \$\begingroup\$ Thanks for pointing out the difference! The typo was actually in the upper code: We must not repeat scene I because it would reset $puck to 0 and then counting up wouldn't work anymore. I added the missing I in the code and corrected the byte length (which was a bit off anyways oops) \$\endgroup\$ Commented Oct 13, 2016 at 7:15
  • 1
    \$\begingroup\$ You are using extremely strange syntax. You can’t have a 0-length title, you did not terminate your act and scene names, you don’t separate entering characters with a comma (you need and), ‘be’ does not work for assignment, ‘without’ is not a thing for subtraction, and ‘times’ is also not a thing. What interpreter are you using, because this is certainly not the official interpreter? \$\endgroup\$ Commented Nov 21, 2019 at 17:24
11
\$\begingroup\$

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.
\$\endgroup\$
10
\$\begingroup\$

05AB1E, 9 6 bytes

Saved 3 bytes thanks to Adnan

[ND,±,

Try it online!

Prints 0, -1, 1, -2, 2 ... separated by newlines.

\$\endgroup\$
3
  • 2
    \$\begingroup\$ I was able to get it down to 6 bytes using some bitwise magic: [N,N±,. \$\endgroup\$
    – Adnan
    Commented Sep 16, 2016 at 10:44
  • 1
    \$\begingroup\$ @Adnan: Nice! I tried to do something similar earlier, but didn't use ± and it ended up 3 bytes longer than yours. \$\endgroup\$
    – Emigna
    Commented Sep 16, 2016 at 11:10
  • \$\begingroup\$ I know it's been a while, but D, can be replaced with = to save a byte. \$\endgroup\$ Commented Apr 9, 2019 at 10:11
10
\$\begingroup\$

Brainfuck, 127 bytes

+[-->+>+[<]>-]>-->+[[.<<<]>>-.>>+<[[-]>[->+<]++++++++[-<++++++>>-<]>--[++++++++++>->-<<[-<+<+>>]]>+>+<]<<<[.<<<]>>.+.>[>>>]<<<]

Try it online!

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

+[-->+>+[<]>-]>-->+
[
  [.<<<]>>-.>>+<
  [[-]>[->+<]
    ++++++++[-<++++++>>-<]>--
    [++++++++++>->-<<[-<+<+>>]]>+>+<
  ]<<<
  [.<<<]>>.+.>
  [>>>]<<<
]
\$\endgroup\$
0
10
\$\begingroup\$

R, 25 24 bytes

Golfed one byte thanks to @JDL.

repeat cat(-F,F<-F+1,'')

Try it online!

Example output:

0 1 -1 2 -2 3 -3 4 -4 5 -5 6 -6 7 -7 8 -8 9 -9 10 
\$\endgroup\$
2
  • 2
    \$\begingroup\$ You can replace while(1) with repeat to save a char. \$\endgroup\$
    – JDL
    Commented Sep 16, 2016 at 16:10
  • \$\begingroup\$ @JDL Thanks! I forget that construct exists sometimes. \$\endgroup\$
    – rturnbull
    Commented Sep 16, 2016 at 19:32
9
\$\begingroup\$

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.

\$\endgroup\$
4
  • 5
    \$\begingroup\$ This answer is... shady. \$\endgroup\$ Commented Sep 16, 2016 at 12:50
  • 1
    \$\begingroup\$ I was wondering who came up with the language name, then I noticed what language it descended from. \$\endgroup\$ Commented Sep 16, 2016 at 12:59
  • \$\begingroup\$ How does this print negative integers? \$\endgroup\$
    – Anthony
    Commented Apr 25, 2020 at 16:21
  • \$\begingroup\$ @Anthony As explained it is using cell wrapping - exactly how BF works! \$\endgroup\$
    – flawr
    Commented Apr 25, 2020 at 16:23
9
\$\begingroup\$

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

Try it online!

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

\$\endgroup\$
8
\$\begingroup\$

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
\$\endgroup\$
8
\$\begingroup\$

Bash + GNU utilities, 26

seq NaN|sed '1i0
p;s/^/-/'
\$\endgroup\$
3
  • 1
    \$\begingroup\$ I've never seen seq used that way, is this like a bug? Also, will it start to repeat numbers after a type overflow? I know that $[++i] does so in bash. \$\endgroup\$
    – seshoumara
    Commented Sep 17, 2016 at 7:36
  • 1
    \$\begingroup\$ Looks like a newer feature - see the source code. Adding 1 to NaN shouldn't cause a wraparound. \$\endgroup\$ Commented Sep 17, 2016 at 17:31
  • 1
    \$\begingroup\$ I left seq NaN to run and after 999999 the printing is done in scientific notation with 5 digit precision. In regards to the challenge, that value is then the biggest integer you print, which is fine since the rest won't repeat a previous number. Also noticed you can run seq with inf, case insensitive just like for nan. +1 \$\endgroup\$
    – seshoumara
    Commented Sep 17, 2016 at 18:30
7
\$\begingroup\$

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.

\$\endgroup\$
3
  • \$\begingroup\$ 1 byte shorter: for(;;){i;-++i} \$\endgroup\$ Commented Sep 16, 2016 at 22:51
  • \$\begingroup\$ @DigitalTrauma Thanks, I updated my answer. The funny thing is that I used that loop construct today in my other bash answer, but forgot that bc had it too. \$\endgroup\$
    – seshoumara
    Commented Sep 16, 2016 at 23:45
  • \$\begingroup\$ Or for(;;){i++;-i} (same length). \$\endgroup\$
    – sch
    Commented Sep 18, 2016 at 10:56
7
\$\begingroup\$

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
...
\$\endgroup\$
9
  • 1
    \$\begingroup\$ I think you could save some bytes by printing n and 1-n at the same time, this way you could remove the compraision. @xnor was the first to use this idea here. \$\endgroup\$
    – flawr
    Commented Sep 16, 2016 at 9:32
  • 1
    \$\begingroup\$ Your int-version program, given infinite time, will print every integer an infinite amount of time. \$\endgroup\$ Commented Sep 18, 2016 at 10:13
  • 1
    \$\begingroup\$ @OlivierGrégoire Ah, of course, MAX_VALUE + 1 is MIN_VALUE.. sigh. I've edited it, thanks for pointing it out. \$\endgroup\$ Commented Sep 18, 2016 at 10:45
  • 1
    \$\begingroup\$ If you want to golf more (ie. getting rid of MAX_VALUE, you can check ou my answer (probably still on last page). \$\endgroup\$ Commented Sep 18, 2016 at 11:08
  • 1
    \$\begingroup\$ Your 53 byte solution is a snippet, not a function or program, and thus is not valid. \$\endgroup\$
    – user45941
    Commented Sep 26, 2016 at 6:41
6
\$\begingroup\$

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

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ Commented Sep 19, 2016 at 15:15
6
\$\begingroup\$

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
\$\endgroup\$
11
  • \$\begingroup\$ +? for "sooner or later ... sooner than you might expect" \$\endgroup\$ Commented Sep 16, 2016 at 19:55
  • 2
    \$\begingroup\$ Instead of [-]P, do 45P. "GNU-Dc or OpenBSD-Dc" - Are there any other versions commonly found out there in the wild? \$\endgroup\$ Commented Sep 16, 2016 at 22:35
  • 1
    \$\begingroup\$ I have another solution (or a few), but they involve actual negative numbers. May I post them in a new answer? I'm asking because they look so similar to these, since dc only has a few operators. I did develop them independently from these. \$\endgroup\$
    – juh
    Commented Sep 17, 2016 at 4:39
  • \$\begingroup\$ @DigitalTrauma ... sure... the original Dc does/did not have r as "swap". I sometimes get confused when looking at the dofferent versions. Probably noone wants to code in ancient Dc any more (and there r would clear the stack). Maybe I'd change "Dc" to "AT&T dc"? ...and thanks for the 45P hint... \$\endgroup\$
    – user19214
    Commented Sep 17, 2016 at 4:41
  • 2
    \$\begingroup\$ @yeti I just put "dc" on my answers. I don't think people here are too worried it, especially given the ubiquity of the "modern" dc flavours. \$\endgroup\$ Commented Sep 17, 2016 at 5:41
6
\$\begingroup\$

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)

\$\endgroup\$
4
  • \$\begingroup\$ Aren't these snippets and not functions/full programs? \$\endgroup\$ Commented Sep 16, 2016 at 18:35
  • \$\begingroup\$ Sorry, full program added \$\endgroup\$
    – alex
    Commented Sep 16, 2016 at 20:21
  • 2
    \$\begingroup\$ You can omit the public modifiers and save 14 bytes. The defaults will do equally well. \$\endgroup\$
    – Alejandro
    Commented Sep 17, 2016 at 14:20
  • \$\begingroup\$ @Alejandro thank you, it is my first post :) \$\endgroup\$
    – alex
    Commented Sep 17, 2016 at 15:04
6
\$\begingroup\$

Labyrinth, 9 bytes

!`
\:"
 (

Try it online!

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.

\$\endgroup\$
1
6
\$\begingroup\$

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!

\$\endgroup\$
6
  • 1
    \$\begingroup\$ How about [i++,-i].map(alert) instead of alert(i++),alert(-i)? \$\endgroup\$ Commented Sep 16, 2016 at 12:53
  • \$\begingroup\$ for(;;) is one byte shorter than while(1) \$\endgroup\$ Commented Sep 16, 2016 at 14:42
  • \$\begingroup\$ @ConorO'Brien map is ES6 \$\endgroup\$ Commented Sep 17, 2016 at 11:56
  • \$\begingroup\$ @PaulSchmitz Nope, 5th edition. \$\endgroup\$ Commented Sep 17, 2016 at 15:27
  • \$\begingroup\$ You can move the i=0; bit inside the for loop to save a byte. \$\endgroup\$ Commented Sep 18, 2016 at 13:05
6
\$\begingroup\$

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.

\$\endgroup\$
4
  • \$\begingroup\$ You can drop the function boilerplate and call it a full program. \$\endgroup\$ Commented Sep 16, 2016 at 12:54
  • \$\begingroup\$ @ConorO'Brien - Oh, you're right. Thanks :) \$\endgroup\$
    – Arnauld
    Commented Sep 16, 2016 at 13:07
  • \$\begingroup\$ n[a,b,c] returns n[c], so you can drop the parentheses in n[(a||n.unshift(1),0)]. \$\endgroup\$ Commented Sep 17, 2016 at 0:42
  • \$\begingroup\$ You don't need the 1 in either for loop; for(;;) runs forever. You can save two more bytes with for(n=1;;)alert([1-n,n++]). Also, this no longer uses any ES6 features ;-) \$\endgroup\$ Commented Oct 3, 2016 at 15:08
6
\$\begingroup\$

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}

Attempt This Online! (with a 5 ms timeout)

\$\endgroup\$
5
  • \$\begingroup\$ You are outputting numeric values here, so p will do it also. \$\endgroup\$
    – manatwork
    Commented Sep 16, 2016 at 9:20
  • \$\begingroup\$ 0.step{|n|p n,~n} for 17 bytes. \$\endgroup\$
    – m-chrzan
    Commented Sep 19, 2016 at 2:15
  • 1
    \$\begingroup\$ @m-chrzan because order doesn't matter as much, I was able to shave an extra byte off, on top of your suggestion! \$\endgroup\$
    – Value Ink
    Commented Sep 19, 2016 at 2:26
  • \$\begingroup\$ With the release of Ruby 2.7, you can use numbered parameters to shave off a character: 0.step{p~_1,_1} \$\endgroup\$ Commented Jul 25, 2023 at 21:17
  • \$\begingroup\$ @CGOneHanded omg this is gonna be revolutionary for future golfing endeavors \$\endgroup\$
    – Value Ink
    Commented Jul 27, 2023 at 3:28
5
\$\begingroup\$

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);
}
\$\endgroup\$
8
  • 3
    \$\begingroup\$ biggest magnitude of the standard integer type of your language int is the standard integer type of Java. \$\endgroup\$
    – Shaun Wild
    Commented Sep 16, 2016 at 9:38
  • 1
    \$\begingroup\$ Sorry about that, the requirements have changed in meantime... \$\endgroup\$
    – flawr
    Commented Sep 16, 2016 at 9:42
  • 2
    \$\begingroup\$ You can golf it to ()->{for(int i=0;;)System.out.print(i+" "+(1-i++));}; (53 bytes) \$\endgroup\$ Commented Sep 16, 2016 at 9:45
  • \$\begingroup\$ @KevinCruijssen That fucks up the spacing... \$\endgroup\$
    – Shaun Wild
    Commented Sep 16, 2016 at 10:32
  • 1
    \$\begingroup\$ Given infinite time, it will print every integer an infinite amount of times each. \$\endgroup\$ Commented Sep 18, 2016 at 10:28
5
\$\begingroup\$

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.......
\$\endgroup\$
6
  • \$\begingroup\$ There are quite a few things that can be done to reduce the characters. First you program doesn't need a namespace. Second the class name doesn't need to be so long. Also you make two calls to console.writeline which can be simplified to a delegate. The while true can be simplified to a a for(;;) and the if statement can be removed with outputting the value of zero first through the delegate. \$\endgroup\$
    – Nico
    Commented Sep 16, 2016 at 10:34
  • \$\begingroup\$ Thanks. I didn't know if a delegate might be "cheating"? \$\endgroup\$
    – Pete Arden
    Commented Sep 16, 2016 at 10:37
  • \$\begingroup\$ Hi, welcome to PPCG! I think you might find this interesting to read through: Tips for golfing in C#. Also, you don't need a full program, just a function will do (unless the challenge says otherwise). So void f(){code_present_in_main} is enough for the byte-count. As for the code itself, you can golf it some more like this: void f(){for(decimal n=1;;)Console.Write((1-n)+","+n+++",");} (61 bytes) \$\endgroup\$ Commented Sep 16, 2016 at 10:48
  • 1
    \$\begingroup\$ Oh great, it's a much healthier 85 now, thanks! I wouldn't feel right using all of your answer, but it's definitely an improvement and those tips will help my future golfing! \$\endgroup\$
    – Pete Arden
    Commented Sep 16, 2016 at 11:08
  • \$\begingroup\$ @PeteArden I understand for not using my code, since it's a different approach. Hmm, you can still golf 2 bytes in your own answer by placing the decimal n=0 and n++; inside the for-loop though: void f(){for(decimal n=0;;n++){Console.Write(n+",");if(n>0)Console.Write(-n+",");}} :) \$\endgroup\$ Commented Sep 16, 2016 at 11:14
5
\$\begingroup\$

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)));
}
\$\endgroup\$
3
  • 1
    \$\begingroup\$ There are 2 useless whitespaces. One before Enumerable.Range and one before int.MaxValue. \$\endgroup\$
    – Yytsi
    Commented Sep 16, 2016 at 11:19
  • 1
    \$\begingroup\$ Welcome to PPCG! +1 You might find this interesting to read: Tips for golfing in C#. In your current answer(s) the brackets for the for-loop can be removed, since there's only one line inside. Alternatively, this is a shorter approach: void f(){for(var n=1;;)Console.Write((1-n)+","+n+++",");} (57 bytes). \$\endgroup\$ Commented Sep 16, 2016 at 11:59
  • \$\begingroup\$ @KevinCruijssen Thanks. Brakets are gone. \$\endgroup\$ Commented Sep 16, 2016 at 12:03
5
\$\begingroup\$

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.

\$\endgroup\$
5
\$\begingroup\$

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.

\$\endgroup\$
5
\$\begingroup\$

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

\$\endgroup\$
2
  • \$\begingroup\$ Is xnor unambiguously a "he"? Or are our unconscious biases showing...? \$\endgroup\$ Commented Sep 16, 2016 at 19:57
  • 2
    \$\begingroup\$ @GregMartin It's interesting, I don't think I've ever mentioned a gender. \$\endgroup\$
    – xnor
    Commented Sep 16, 2016 at 20:41
1
2 3 4 5 6

Not the answer you're looking for? Browse other questions tagged or ask your own question.