48
\$\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\$
  • 3
    \$\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 Sep 16 '16 at 8:57
  • 5
    \$\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 Sep 16 '16 at 9:10
  • 2
    \$\begingroup\$ @xnor Changed, though that kinds of ruins the very name of the challenge. \$\endgroup\$ – Fatalize Sep 16 '16 at 9:14
  • 5
    \$\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\$ – Peter Taylor Sep 16 '16 at 9:54
  • 2
    \$\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 Sep 16 '16 at 9:58

120 Answers 120

19
\$\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\$
  • \$\begingroup\$ how is this 3 bytes ? \$\endgroup\$ – HopefullyHelpful Nov 27 '16 at 1:39
  • 1
    \$\begingroup\$ The readme on GitHub (linked in the header) explains in detail how the instructions are encoded. \$\endgroup\$ – Dennis Nov 27 '16 at 2:47
  • 1
    \$\begingroup\$ 6 hex digits / 2 = 3 bytes @HopefullyHelpful \$\endgroup\$ – Stan Strum Sep 12 '17 at 20:45
  • \$\begingroup\$ @StanStrum thanks \$\endgroup\$ – HopefullyHelpful Sep 13 '17 at 14:29
46
\$\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\$
  • 2
    \$\begingroup\$ I love [n,1-n]! \$\endgroup\$ – flawr Sep 16 '16 at 9:22
  • 3
    \$\begingroup\$ IMHO [1-n,n] would produce nicer output. \$\endgroup\$ – Neil Sep 16 '16 at 9:47
  • \$\begingroup\$ @Neil I agree, changed it. \$\endgroup\$ – xnor Sep 16 '16 at 9:51
  • 1
    \$\begingroup\$ Ah, that's monadese for concatMap (\n -> [1-n, n]) [1..], right? Nice! \$\endgroup\$ – Carsten S Sep 17 '16 at 16:17
  • \$\begingroup\$ @CarstenS Yes, exactly. \$\endgroup\$ – xnor Sep 17 '16 at 18:51
29
\$\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\$
  • 2
    \$\begingroup\$ Nice, this is the shortest Brainfuck answer I've seen so far on PPCG. \$\endgroup\$ – Kevin Cruijssen Sep 16 '16 at 11:10
  • 1
    \$\begingroup\$ This won't work for brainfuck versions with unbounded cells. Please fix (even if as a separate answer) \$\endgroup\$ – John Dvorak Sep 16 '16 at 12:55
  • 16
    \$\begingroup\$ @JanDvorak Answers don't need to work in every implementation, just in any one of them. \$\endgroup\$ – Martin Ender Sep 16 '16 at 13:39
  • 7
    \$\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 Sep 17 '16 at 2:41
  • 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 Sep 17 '16 at 19:06
26
\$\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\$
  • 4
    \$\begingroup\$ Nice diagram! :) Did you create that by hand or write a tool to generate it? \$\endgroup\$ – Martin Ender Sep 16 '16 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\$ – ETHproductions Sep 16 '16 at 18:21
18
\$\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\$
  • \$\begingroup\$ Why is there such a big delay before it starts printing? \$\endgroup\$ – Fatalize Sep 16 '16 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 Sep 16 '16 at 9:47
  • \$\begingroup\$ @Fatalize I'm not sure. It happens in the online compiler, not offline. I thought it might have to do with Octave paging the output, but now I'm not sure whether that's the reason \$\endgroup\$ – Luis Mendo Sep 16 '16 at 9:48
  • 1
    \$\begingroup\$ Smart idea to do @_@XD rather than @_D@D so you can include the 0 on the first run. \$\endgroup\$ – Sanchises Sep 16 '16 at 10:22
  • 3
    \$\begingroup\$ XD +1 for smiley \$\endgroup\$ – TuxCrafting Sep 16 '16 at 18:37
16
\$\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\$
  • 1
    \$\begingroup\$ I like this. It's terrible for golfing, but wonderful for reading. \$\endgroup\$ – swinefish Sep 19 '16 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 Oct 8 '16 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\$ – Christallkeks Oct 13 '16 at 7:15
14
\$\begingroup\$

Python 2, 27 bytes

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

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

\$\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\$
  • 2
    \$\begingroup\$ I was able to get it down to 6 bytes using some bitwise magic: [N,N±,. \$\endgroup\$ – Adnan Sep 16 '16 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 Sep 16 '16 at 11:10
  • \$\begingroup\$ I know it's been a while, but D, can be replaced with = to save a byte. \$\endgroup\$ – Kevin Cruijssen Apr 9 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\$
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\$
  • 5
    \$\begingroup\$ This answer is... shady. \$\endgroup\$ – Conor O'Brien Sep 16 '16 at 12:50
  • 1
    \$\begingroup\$ I was wondering who came up with the language name, then I noticed what language it descended from. \$\endgroup\$ – John Dvorak Sep 16 '16 at 12:59
9
\$\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\$
8
\$\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
    \$\begingroup\$ You can replace while(1) with repeat to save a char. \$\endgroup\$ – JDL Sep 16 '16 at 16:10
  • \$\begingroup\$ @JDL Thanks! I forget that construct exists sometimes. \$\endgroup\$ – rturnbull Sep 16 '16 at 19:32
7
\$\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\$
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\$
  • 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 Sep 16 '16 at 9:32
  • 1
    \$\begingroup\$ Your int-version program, given infinite time, will print every integer an infinite amount of time. \$\endgroup\$ – Olivier Grégoire Sep 18 '16 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\$ – Kevin Cruijssen Sep 18 '16 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\$ – Olivier Grégoire Sep 18 '16 at 11:08
  • 1
    \$\begingroup\$ Your 53 byte solution is a snippet, not a function or program, and thus is not valid. \$\endgroup\$ – Mego Sep 26 '16 at 6:41
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\$
  • \$\begingroup\$ +? for "sooner or later ... sooner than you might expect" \$\endgroup\$ – Greg Martin Sep 16 '16 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\$ – Digital Trauma Sep 16 '16 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\$ – Joe Sep 17 '16 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\$ – yeti Sep 17 '16 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\$ – Digital Trauma Sep 17 '16 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\$
  • \$\begingroup\$ Aren't these snippets and not functions/full programs? \$\endgroup\$ – pinkfloydx33 Sep 16 '16 at 18:35
  • \$\begingroup\$ Sorry, full program added \$\endgroup\$ – alex Sep 16 '16 at 20:21
  • 2
    \$\begingroup\$ You can omit the public modifiers and save 14 bytes. The defaults will do equally well. \$\endgroup\$ – Alejandro Sep 17 '16 at 14:20
  • \$\begingroup\$ @Alejandro thank you, it is my first post :) \$\endgroup\$ – alex Sep 17 '16 at 15:04
6
\$\begingroup\$

Ruby, 26 22 19 16 bytes

Prints numbers separated by newlines. -3 bytes from @manatwork. -3 bytes from @m-chrzan.

0.step{|n|p~n,n}
\$\endgroup\$
  • \$\begingroup\$ You are outputting numeric values here, so p will do it also. \$\endgroup\$ – manatwork Sep 16 '16 at 9:20
  • \$\begingroup\$ 0.step{|n|p n,~n} for 17 bytes. \$\endgroup\$ – m-chrzan Sep 19 '16 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 Sep 19 '16 at 2:26
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\$
  • \$\begingroup\$ You can drop the function boilerplate and call it a full program. \$\endgroup\$ – Conor O'Brien Sep 16 '16 at 12:54
  • \$\begingroup\$ @ConorO'Brien - Oh, you're right. Thanks :) \$\endgroup\$ – Arnauld Sep 16 '16 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\$ – ETHproductions Sep 17 '16 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\$ – ETHproductions Oct 3 '16 at 15:08
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\$
  • \$\begingroup\$ Is xnor unambiguously a "he"? Or are our unconscious biases showing...? \$\endgroup\$ – Greg Martin Sep 16 '16 at 19:57
  • 2
    \$\begingroup\$ @GregMartin It's interesting, I don't think I've ever mentioned a gender. \$\endgroup\$ – xnor Sep 16 '16 at 20:41
5
\$\begingroup\$

Bash + GNU utilities, 26

seq NaN|sed '1i0
p;s/^/-/'
\$\endgroup\$
  • \$\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 Sep 17 '16 at 7:36
  • \$\begingroup\$ Looks like a newer feature - see the source code. Adding 1 to NaN shouldn't cause a wraparound. \$\endgroup\$ – Digital Trauma Sep 17 '16 at 17:31
  • \$\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 Sep 17 '16 at 18:30
5
\$\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\$
  • \$\begingroup\$ 1 byte shorter: for(;;){i;-++i} \$\endgroup\$ – Digital Trauma Sep 16 '16 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 Sep 16 '16 at 23:45
  • \$\begingroup\$ Or for(;;){i++;-i} (same length). \$\endgroup\$ – sch Sep 18 '16 at 10:56
5
\$\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\$
5
\$\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\$
  • 1
    \$\begingroup\$ How about [i++,-i].map(alert) instead of alert(i++),alert(-i)? \$\endgroup\$ – Conor O'Brien Sep 16 '16 at 12:53
  • \$\begingroup\$ for(;;) is one byte shorter than while(1) \$\endgroup\$ – Patrick Roberts Sep 16 '16 at 14:42
  • \$\begingroup\$ @ConorO'Brien map is ES6 \$\endgroup\$ – Paul Schmitz Sep 17 '16 at 11:56
  • \$\begingroup\$ @PaulSchmitz Nope, 5th edition. \$\endgroup\$ – Conor O'Brien Sep 17 '16 at 15:27
  • \$\begingroup\$ You can move the i=0; bit inside the for loop to save a byte. \$\endgroup\$ – Conor O'Brien Sep 18 '16 at 13:05
4
\$\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\$
  • 3
    \$\begingroup\$ biggest magnitude of the standard integer type of your language int is the standard integer type of Java. \$\endgroup\$ – Shaun Wild Sep 16 '16 at 9:38
  • 1
    \$\begingroup\$ Sorry about that, the requirements have changed in meantime... \$\endgroup\$ – flawr Sep 16 '16 at 9:42
  • 2
    \$\begingroup\$ You can golf it to ()->{for(int i=0;;)System.out.print(i+" "+(1-i++));}; (53 bytes) \$\endgroup\$ – Kevin Cruijssen Sep 16 '16 at 9:45
  • \$\begingroup\$ @KevinCruijssen That fucks up the spacing... \$\endgroup\$ – Shaun Wild Sep 16 '16 at 10:32
  • 1
    \$\begingroup\$ Given infinite time, it will print every integer an infinite amount of times each. \$\endgroup\$ – Olivier Grégoire Sep 18 '16 at 10:28
4
\$\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\$
  • \$\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 Sep 16 '16 at 10:34
  • \$\begingroup\$ Thanks. I didn't know if a delegate might be "cheating"? \$\endgroup\$ – Pete Arden Sep 16 '16 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\$ – Kevin Cruijssen Sep 16 '16 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 Sep 16 '16 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\$ – Kevin Cruijssen Sep 16 '16 at 11:14
4
\$\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\$
  • 1
    \$\begingroup\$ There are 2 useless whitespaces. One before Enumerable.Range and one before int.MaxValue. \$\endgroup\$ – Yytsi Sep 16 '16 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\$ – Kevin Cruijssen Sep 16 '16 at 11:59
  • \$\begingroup\$ @KevinCruijssen Thanks. Brakets are gone. \$\endgroup\$ – Daniel Lerps Sep 16 '16 at 12:03
4
\$\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\$
4
\$\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
    \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ – AdmBorkBork Sep 19 '16 at 15:15
4
\$\begingroup\$

Pyke, 7 2 bytes

~I

Try it here!

7 bytes

oDID_)r

Try it here!

If printing +-0 is ok, oD_r

\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$

protected by Community Nov 20 '17 at 13:16

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

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