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

121 Answers 121

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\$
3
\$\begingroup\$

><>, 11 bytes

lnao0l-naol

Try it online! Uses the stack length as a counter.

ln             Output length of stack
  ao           Output newline
    0l-n       Output 0 - (length of stack + 1), +1 because of the additional 0
        ao     Output newline
          l    Push length of stack, increasing the stack length by 1
               (Implicit loop since ><> is toroidal)
\$\endgroup\$
3
\$\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\$
3
\$\begingroup\$

Jelly, 5 bytes

Ṅ~ṄNß

Try it online!

How it works

Ṅ~ṄNß  Main link. Argument: n. Implict argument: 0

Ṅ      Print n and a linefeed.
 ~     Apply bitwise NOT, yielding -(n + 1).
  Ṅ    Print -(n + 1) and a linefeed.
   N   Negate, yielding n + 1.
    ß  Recursively call the main link with argument n + 1.
\$\endgroup\$
3
\$\begingroup\$

Hexagony, 22 18 bytes

!(~2016}Q2;'Oct4!~

Try it Online!

Excuse me for keep editing.. After typing the explanations I managed to squeeze.. not so squeeze this into a 3-hexagon and there are still plenty of space to put today's date in.

Old Answer

Try it Online! (old answer)

I have a love at first sight with this language...

!(._/;'<~.2/~/!}Q/>.$>

Expanded

   ! ( . _        When n<=0, print (-ve number) and n--
  / ; ' < ~       After printing , 
 . 2 / ~ / !      If n<=0, n=-n and print (the +ve number)
} Q / > . $ >     Else n=-n and go into auto-if
 . . . . . .
  . . . . . 
   . . . .        When n>0, do nothing as the number is printed at line 3

The basic algorithm is,

Loop: print, if(n<=0) n--, n=-n, then print ,

I come into this answer with the thought of using implicit if by going out of the corner:

   ! ( . .
  . . . . .
 . . . . . .
. ~ } Q 2 ; '
 . . . . . .
  . . . . .
   ! . . .

However it is real using a lot of bytes for no-ops in putting the ! there, and in the hope of getting the ! (print) back into the main middle loop, I found it hard to print the 0 since the if(n<=0)n-- is run before the main loop for printing. So keep drawing on a whiteboard (it is easier to overwrite a byte on a whiteboard than most of other tools) I came up with the above which puts one extra ~ (negation) after branching at line 2 but saves me from using the no-ops at the end.

Anyone who can guide me how to make beautiful Hexagony explanation images?

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

SQL, 84 76 Bytes

Saved 8 Bytes thanks to steenbergh :)

Golfed:

DECLARE @n INT SET @n= 1 WHILE 1=1 BEGIN PRINT 1-@n PRINT @n SET @n=@n+1 END

Ungolfed:

DECLARE @n INT 
SET @n= 1
WHILE 1=1 
BEGIN 
PRINT 1-@n 
PRINT @n 
SET @n=@n+1
END

Prints:

0
1
-1
2
-2
3
-3
4
-4
5
-5
...
\$\endgroup\$
  • 1
    \$\begingroup\$ Using the 1-n trick you can drop the PRINT 0 at the start of your function: DECLARE @n INT = 1 WHILE 1=1 BEGIN PRINT 1-@n PRINT @n SET @n=@n+1 END \$\endgroup\$ – steenbergh Nov 11 '16 at 9:54
  • \$\begingroup\$ @steenbergh Cool, thanks! It wouldn't let me declare and set on the same line, but still saved 8 Bytes! :) \$\endgroup\$ – Pete Arden Nov 11 '16 at 17:41
3
\$\begingroup\$

Wumpus, 8 bytes

=nON
=)N

Try it online!

Prints the integers in the order -1, 0, -2, 1, -3, 2, ... using linefeed separation.

Explanation

Let's look at the actual grid first:

Control flow diagram

The instruction pointer starts in the top left corner moving east and will reflect off the edge whenever it reaches a boundary of the code. Hence, this program loops through the code indefinitely, but we reuse the single O (because it's executed both before and after entering the top right corner).

So the loop body looks like this:

=nONON)=

Let's go through this:

=   Duplicate the top of the stack. Initially, this is an implicit zero,
    but in general this will be the non-negative number of each pair we print.
n   Bitwise NOT. Turns the copy of n into -n-1.
O   Output -n-1.
N   Output a linefeed.
O   Output n.
N   Output a linefeed.
)   Increment n to n+1.
=   Duplicate it (because one copy of it will be printed in the next iteration).
\$\endgroup\$
  • \$\begingroup\$ Figured out a one liner in the same amount of bytes. Try it online! \$\endgroup\$ – Jo King Feb 12 '18 at 2:16
  • \$\begingroup\$ @JoKing neat! :) \$\endgroup\$ – Martin Ender Feb 12 '18 at 6:38
3
\$\begingroup\$

Prolog (SWI), 33+3 = 36 bytes

A*B:-C is B-A,writeln(C),C*(1-B).

Try it online!

Called as 0*0.

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

Saved 5 bytes thanks to SQB
Saved 16 bytes thanks to user3744156

\$\endgroup\$
  • \$\begingroup\$ You can shave off a couple of bytes by leaving out the p:-0*1 and calling it as 0*1 instead. You'd have to count those 3 bytes, I think. \$\endgroup\$ – SQB Sep 17 '16 at 18:19
  • \$\begingroup\$ @SQB: Do you have a meta on that? That sounds akin to requiring a program to take a specific input in order to work, which sounds like a questionable practice to me. \$\endgroup\$ – Emigna Sep 18 '16 at 8:16
  • \$\begingroup\$ No I don't, but I once got a similar comment on an entry in prolog. It does make some sense, though, or one could offload the byte count to the call. \$\endgroup\$ – SQB Sep 18 '16 at 8:21
  • \$\begingroup\$ Great entry, by the way. I'm a bit puzzled why the combination of writeln/1 and plain write/1 works the way it does, but... it does! \$\endgroup\$ – SQB Sep 18 '16 at 8:23
  • \$\begingroup\$ @SQB I suppose that makes sense for Prolog if, as you say we add the query to the byte count. I'm not sure either why writeln writes on a newline before it does nl. That's not the way it usually works in most languages. \$\endgroup\$ – Emigna Sep 18 '16 at 12:08
3
\$\begingroup\$

C (gcc), 40 38 bytes

main(i){printf("%d ",i++);i&&main(i);}

Try it online!

How:

When run without parameters, i is set to 1 (because it's the argc to a C program).

Thanks to Josh for a comment which helped me save 2 bytes.

\$\endgroup\$
  • \$\begingroup\$ You can save 4 bytes by {while(i)printf("%d ",i++);} \$\endgroup\$ – Jasmes Apr 6 '17 at 19:13
  • 1
    \$\begingroup\$ But then it would not print 0 at the end. \$\endgroup\$ – G B Apr 7 '17 at 7:14
  • 1
    \$\begingroup\$ Your answer inspired me to try recursion! Saves one byte, but at the cost of ugliness and undefined behavior: main(i){printf("%d ",i,i++&&main(i));} \$\endgroup\$ – Josh Oct 3 at 19:59
2
\$\begingroup\$

Befunge 93, 8 bytes

:.-:0`!-

Try it online!

Explanation

Befunge's stack is thankfully filled with an implicit infinite amount of zeros, and printing a number also prints a trailing space.

:.    Print the top of the stack.
-     Subtract it from the implicit zero underneath, effectively multiplying by -1.
:0`   Check whether its greater than 0.
!     Logical NOT. Gives 0 if the current value is positive and 1 otherwise.
-     Subtract from current value.

The source code is toroidal so this program repeats indefinitely.

\$\endgroup\$
2
\$\begingroup\$

Lua , 43 Bytes

i=1;while 1 do print(1-i);print(i);i=i+1 end
\$\endgroup\$
2
\$\begingroup\$

Perl, 19 bytes

perl -E 'say-$}while say$}++'

In reality will get stuck when at some huge number $} switched to floating point and starts losing precision.

This 27 byte version will really print forever:

perl -E 's//0/;say"-".++$_ while say'
\$\endgroup\$
  • \$\begingroup\$ Nice. say"-".++$_ while say$_|0 should behave as your second solution if I'm not mistaken, and is 2 bytes shorter. \$\endgroup\$ – Dada Sep 16 '16 at 16:40
  • \$\begingroup\$ Your version has the same problem as my first version: Once $_ gets big enough precission will freeze it. The essence of my second version is that $_ always contains a pure string representation of the number in which case perl will apply magic increment. Notice also that "-".++$_ is needed, -++$ would convert $_ back to a number. Replace s//0/ by $_=9x99 to see it in action \$\endgroup\$ – Ton Hospel Sep 16 '16 at 16:53
  • \$\begingroup\$ Ok, got it. I was trying to figure out why the second version was working while the first wasn't (more or less), thanks for the explanations. \$\endgroup\$ – Dada Sep 16 '16 at 16:59
2
\$\begingroup\$

C# 222 bytes (Infinite output version)

Being more fond of the infinite output version of the print-all-integers program, I created this.

IEnumerable<string>g(){var w=new[]{'0'};yield return "0";while(true){var c=true;for (var r=w.Length-1;c&&r>=0;r--)if(c=++w[r]==58)w[r]='0';var b=new string(w);if(c)w=(b="1"+b).ToArray();yield return b;yield return "-"+b;}}

This function continuously returns the next greater positive and negative integers. The values are not limited by the integer type but since integers are used to handle the array, the program will fail when the number has more than 2,147,483,647 digits. However, it will most likely run out of memory long before that happens.

Usage:

static void Main(string[] args)
{
    foreach (var n in g())
    {
        Console.WriteLine(n);
    }
}
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
  • 2
    \$\begingroup\$ "In case anyone finds these to be of interest" ... I do! ;-) \$\endgroup\$ – yeti Sep 17 '16 at 6:34
2
\$\begingroup\$

Retina, 21 19 bytes

{M*`.
^
1
*`.+
-$.&

Try it online! (Takes about a minute before you see anything.)

\$\endgroup\$
2
\$\begingroup\$

Burlesque, 12 bytes

0R@J-1?*_+[-

You can try a restricted version here.

0R@  Range from 0 to Infinity
J    Duplicate
-1?* Multiply one Block by -1 (negative integeres)
_+   Concatenate
[-   Tail to Remove the duplicate zero
\$\endgroup\$
2
\$\begingroup\$

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.

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

Java, 49 bytes

o->{for(int n=1<<31;n<0;)o.println(n+"\n"+~n++);}

Notes:

  • o is a java.io.PrintStream but its import is not required given it's the parameter of a lambda expression.
  • This must be run on a Unix machine to properly use the same separator.

Ungolfed

import java.io.PrintStream;
import java.util.function.Consumer;

public class Main {
    public static void main(String[] args) {
        Consumer<PrintStream> func = o -> { // define the output and start the function.
          for (int n = 1 << 31; n < 0; n++) { // for each negative integer increasing from Integer.MIN_VALUE
            o.println(n + "\n" + ~n); // Print the negative number and its complement to 2 value.
          }
        };
        func.accept(System.out);
    }
}

Result

-2147483648
2147483647
-2147483647
2147483646
-2147483646
2147483645
-2147483645
2147483644
-2147483644
2147483643
-2147483643
2147483642
-2147483642
2147483641
-2147483641
2147483640
...
-7
6
-6
5
-5
4
-4
3
-3
2
-2
1
-1
0
\$\endgroup\$
2
\$\begingroup\$

R, 33 29 bytes

x=0;while(T)cat("",-x,x<-x+1)

Output (for < 10)

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

Explanation

It works because x is set to 0, then prints -0 which displays as 0. It then increments and prints that, giving 1. The next element is the negative value of the last which is -1 and so on...

EDIT: Cut it down by 4 bytes after I realised that I could just have it loop forever. In R, T is TRUE by default.

\$\endgroup\$
  • 1
    \$\begingroup\$ Hi, welcome to PPCG! Hmm, I've never programmed in R before, so correct me if I'm wrong, but doesn't this print 0 two times in the following sequence 0, 0, -1, 1, ...? \$\endgroup\$ – Kevin Cruijssen Sep 19 '16 at 13:06
  • 2
    \$\begingroup\$ It doesn't because it prints -0 (which prints as 0) then increments by 1 and prints that. An example of the output for x<10: 0 1 -1 2 -2 3 -3 4 -4 5 -5 6 -6 7 -7 8 -8 9 -9 10 \$\endgroup\$ – sebastian-c Sep 19 '16 at 14:53
  • \$\begingroup\$ Ah ok, thanks for clarifying and adding the explanation. I was asking because I made a similar mistake with my own answer before, which printed 0 and -0 (second 0). Like I said, I never used R myself, so I knew there was a small chance I just didn't fully understand the code. +1 from me, and once again welcome. \$\endgroup\$ – Kevin Cruijssen Sep 19 '16 at 15:02
2
\$\begingroup\$

PHP, 28 27 bytes

for(;1;)echo 1-++$i," $i ";

As aross pointed out in the comments this only outputs PHP_INT_MIN (or indeed PHP_INT_MIN + 1) on a 32 bit implementation of php.

Old versions:

for(;++$i;)echo 1-$i," $i ";

If a leading space is allowed then

for(;++$i;)echo" $i ",1-$i;

Is 1 byte shorter. (same length as new version)

\$\endgroup\$
  • \$\begingroup\$ This won't output PHP_INT_MIN, so it's invalid \$\endgroup\$ – aross Sep 26 '16 at 8:23
  • \$\begingroup\$ sure it will, it switches over to a double representation which has enough precision to be accurate to php_int_min. \$\endgroup\$ – user59178 Sep 26 '16 at 8:53
  • \$\begingroup\$ No it won't. Just set $i to a high number and let it run from there to see for yourself. It will output -9.2233720368548E+18 9.2233720368548E+18 (and will continue to output this for eternity). Adding 1 will not change the value of the float due to lack of precision. The last INTs in the output are -9223372036854775806 9223372036854775807 \$\endgroup\$ – aross Sep 26 '16 at 8:59
  • \$\begingroup\$ ah, maybe i should have been more precise: it will if you run it on a 32 bit version of php, such as php 5.6 on windows. where php_int_max is 2147483647 \$\endgroup\$ – user59178 Sep 26 '16 at 9:34
  • \$\begingroup\$ So your answer is only valid in a very specific system, and you should note that \$\endgroup\$ – aross Sep 26 '16 at 9:40
2
\$\begingroup\$

PHP, 24 26 bytes

(24 bytes not displaying PHP_INT_MIN)

for(;;)echo-$i++," $i ";

Output : 0 1 -1 2 -2 3 -3 4 -4 5 -5 6 -6 7 -7 8 -8 9 -9 10 -10 ...

As $i is not defined, you have to cast it as integer (with - or +0)

(26 bytes not displaying PHP_INT_MIN)

for(;;)echo$i+++0," -$i ";

Output : 0 -1 1 -2 2 -3 3 -4 4 -5 5 -6 6 -7 7 -8 8 -9 9 -10 10 ...

\$\endgroup\$
  • \$\begingroup\$ This won't output PHP_INT_MAX, so it's invalid \$\endgroup\$ – aross Sep 26 '16 at 8:21
  • \$\begingroup\$ Sorry, it doesn't output PHP_INT_MIN \$\endgroup\$ – aross Sep 26 '16 at 9:28
  • \$\begingroup\$ Still won't output PHP_INT_MIN. Look at my answer \$\endgroup\$ – aross Sep 29 '16 at 14:27
  • \$\begingroup\$ I agree, I was editing. \$\endgroup\$ – Crypto Sep 29 '16 at 14:28
2
\$\begingroup\$

PHP, 27 26 bytes

Note that my answer actually outputs PHP_INT_MAX and PHP_INT_MIN, whereas others don't.

for(;;)echo+$i,_,~+$i++,_;

Run like this:

php -d error_reporting=30709 -r 'for(;;)echo+$i,_,~+$i++,_;';echo

This iterates from 0 to PHP_INT_MAX, obviously using post-increment to get the full range and not have an off-by-one error. Then get the negative range by XOR-ing with -1 binary negation.

INT_MAX and INT_MIN

A signed integer actually has a 1 bigger range of negative values than positive values. In the case of 64-bit int (PHP default on 64-bit systems) it's -9223372036854775808 upto 92233720368547758087 inclusive. Many answers stop at -9223372036854775807, which is 1 short.

To see the tail of the output (with PHP_INT_MAX and PHP_INT_MIN), just do this:

php -d error_reporting=30709 -r 'for($i=PHP_INT_MAX-5;is_int($i);)echo+$i,_,~+$i++,_;';echo

The is_int is strictly not needed, it just makes sure the loop stops when $i exceeds PHP_INT_MAX and becomes a float, outputting junk for all eternity.

Tweaks

  • Use binary negation instead of xor with -1. Requires another cast to int to handle the null case. Saved a byte.
\$\endgroup\$
2
\$\begingroup\$

LI, 16 7 bytes

New solution:

R-0P-1P

I feel kinda silly for not realizing I could have done this before. I'm keeping the other one because it shows off more flow control and more functions.

LI is a (very) WIP language that relies primarily on recursion. Every program in LI must take in user-provided input, so the given program here accepts LI's "null" input of 0.

The current Python interpreter is just barely enough to meet the specifications of this challenge, albeit wordy; I'm working on a Racket interpreter that would be able to meet the specs of this challenge with three bytes, but unfortunately it's not even close to challenge-ready.

Explanation:

      P    Print input
    -1     (1 - input)
   P       Print that too
 -0        (- (1 - input))
R          Rerun program with new input

Old solution:

R?>0i-0PyPi-0PYP

Roughly, this program translates to:

R                        Recurse program with input:
                 P        print-return (implicit input)
                Y         Increment input
               P          Print incremented
             -0           Invert sign
                          = -(i+1)
 ?>0i                   if i is not negative.
      -0PyPi            If i is negative, do the same but decrement (y) instead of increment.

For both solutions, output is of the following format:

0
1
-1
2
-2
3
-3
...

The default interpreter will run out of memory at -3338 (3342 with the new solution), if you're curious.

\$\endgroup\$
2
\$\begingroup\$

Powershell, 26 19 Bytes

for(){($b++);$b*-1}

updated because I should have done it months ago.

very straightforward, takes a variable $a, initializes as 0, then initiates an infinite loop with while(1){} and then displays the current value $a - increments it $a++ and displays the negative version of it $a*-1

output is automatically on a new line for each display, so the resulting output is:

0
-1
1
-2
2
-3
3
-4
\$\endgroup\$
  • \$\begingroup\$ Nice to see another PowerShell golfer around! You could swap the while for a for, change how $b is initialized by encapsulating it in parens to place a copy on the pipeline, and turn $b*-1 into -$b. That gets you down to 17 -- for(){($b++);-$b} ... outputs 0 -1 1 -2 2... with newlines in between. \$\endgroup\$ – AdmBorkBork Oct 7 '16 at 18:51
  • \$\begingroup\$ didn't realize you could use a blank for - thought you needed to use for(;;) which is the same bytes as while() - thanks for the tips! \$\endgroup\$ – colsw Oct 8 '16 at 13:53
2
\$\begingroup\$

Add++, 23 bytes

This is the current version on TIO. The latest should be able to do it in less but it is untested so I decided not to post it.

O
V
+1
W,G,+1,O,~,O,~,V

Try it online!

How does it work?

O      Output the accumulator (x) as a number (0)
V      Save x in the second stack
+1     Add one to x
W,     While x is true:
  G,     Set x to the popped item from the second stack
  +1,    Add 1 to x
  O,     Output x as a number
  ~,     Negate x
  O,     Output x as a number
  ~,     Negate x
  V      Save x in the second stack
\$\endgroup\$
2
\$\begingroup\$

tcl, 35

puts 0
while 1 {puts [incr i]\n-$i}

demo

\$\endgroup\$
2
\$\begingroup\$

><>, 17 16 Bytes

0:n1+ao:0$-nao0?

Could shave off 4 bytes, at the cost of separation in the output.

Current output:

0
-1
1
-2
2
...

Explanation:

0:n                          | Puts 0 on the stack, duplicates it, and prints it.
   1+                        | Increments the value
     ao                      | Prints a new line.
       :0$-n                 | Duplicates the value, prints it negative.
            ao               | Print a new line.
              0?             | Skip the next command (pushing 0), repeat.

Previous solution:

0:n1+ao:0$-nao01.

Teleports to the command after the 0, instead of just skipping it.

\$\endgroup\$
2
\$\begingroup\$

SmileBASIC, 20 bytes

@L?N,-N-1N=N+1GOTO@L

A very boring answer.

Alternative:

@L?N
INC N?-N
GOTO @L
\$\endgroup\$
  • \$\begingroup\$ This will print 0 twice, making it an invalid answer. "print every integer exactly once" \$\endgroup\$ – snail_ Mar 29 '18 at 8:44
  • 1
    \$\begingroup\$ Welll.... technically it prints negative 0 -0... But now it's fixed. \$\endgroup\$ – 12Me21 Mar 29 '18 at 14:55
1
\$\begingroup\$

Caché ObjectScript, 28 bytes

w 0 f i=1:1 {w ",",i,",",-i}
\$\endgroup\$
1
\$\begingroup\$

Octave, 30 bytes

x=0;while 1;disp([x++;-x]);end

Explanation:

x=1;       % Initialize x to 1
while 1;   % Infinite loop since 1 == true
[x++,-x]   % x, then post increment and show the negative version
disp(___)  % display it
end

Prints the following sequence, starting from 0:

   0
  -1
   1
  -2
   2
  -3
   3
   .
   .
\$\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.