Print all integers

52

5

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>

Fatalize

Posted 2016-09-16T08:50:56.507

Reputation: 32 976

Related, related, related. – Fatalize – 2016-09-16T08:51:46.477

4If our language supports infinite lists, can we output the list from a function rather than printing? (Calling print on such a list would print its elements one at a time forever.) – xnor – 2016-09-16T08:57:14.493

@xnor If any given integer gets printed after a finite amount of time, it's fine. – Fatalize – 2016-09-16T09:04:51.413

1May we give an expression that evaluates to an infinite list? I realized that in Haskell, a function that takes no inputs look just like an expression. – xnor – 2016-09-16T09:07:28.307

1@xnor The only constraint is that any integer must be printed after a finite amount of time. – Fatalize – 2016-09-16T09:10:16.023

6I feel like the requirement on arbitrary-size integers does nothing but discourage languages without such integers from participating. They either have to have an import they can use or solve a totally different challenge from everyone else. – xnor – 2016-09-16T09:10:53.297

3@xnor Changed, though that kinds of ruins the very name of the challenge. – Fatalize – 2016-09-16T09:14:23.230

@Fatalize Is unary output allowed too? – flawr – 2016-09-16T09:25:44.287

@flawr No, unless your language only supports that. – Fatalize – 2016-09-16T09:28:20.380

If the default data type is double floating point can we use that? That will work for integers up to 2^53 – Luis Mendo – 2016-09-16T09:40:20.773

@LuisMendo Yes if the decimal part is always the same (.0 I assume). – Fatalize – 2016-09-16T09:41:29.540

6@xnor, languages with arbitrary precision integers still have to solve a different problem from everyone else, so all that that change has accomplished is to make this problem boringly trivial in a lot of languages. – Peter Taylor – 2016-09-16T09:54:12.783

3@PeterTaylor Yeah, this is unfortunate. The wrapping solutions don't feel to me like they are printing any negatives, but I don't see a way to firmly specify the difference when it's a matter of representation. – xnor – 2016-09-16T09:58:07.363

@flawr and Fatalize: In sed you have no integer type, so an unary string is the most natural format. I already gave an answer in sed, but that is ~200 bytes, because I emulate the increment of integers. If I want to use unary, how should I represent negative numbers? Like -000 for -3?

– seshoumara – 2016-09-16T11:02:27.393

2Do you accept -0 as a valid representation of 0? (Provided there is no other 0 or +0 in the output.) – Martin Ender – 2016-09-16T11:49:55.110

@MartinEnder Yes. – Fatalize – 2016-09-16T11:51:03.753

Last bullet point clearly contradicts the first sentence. – MatthewRock – 2016-09-16T14:00:24.960

1Doesn't the program need to terminate once it's printed all of the integers to be correct? – cleblanc – 2016-09-16T14:14:08.573

@cleblanc - presumably, unless you have arbitrary sized integers in your language. – Periata Breatta – 2016-09-16T16:40:06.750

Second-to-last bullet point: Is there supposed to be a space or two around the first ,? – Joe – 2016-09-17T04:08:28.827

@Joe Yes, fixed. For some reason copying unbreakable spaces from the sandbox to here transformed it to a normal space. – Fatalize – 2016-09-17T08:02:43.917

How can we do it "provably"? – Buffer Over Read – 2016-09-18T00:21:24.870

@seshoumara I guess that would be acceptable, though I don't see why you would use a language with no integers for such a challenge. – Fatalize – 2016-09-18T07:08:56.070

2The arbitrarily long integers is not a big delimiter. Languages without them can still golf decently using string arrays (instead of integer arithmetic). See my ~300 byte C answer for example. – LambdaBeta – 2016-09-19T17:26:55.233

Answers

20

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)

Dennis

Posted 2016-09-16T08:50:56.507

Reputation: 196 637

how is this 3 bytes ? – HopefullyHelpful – 2016-11-27T01:39:36.277

1The readme on GitHub (linked in the header) explains in detail how the instructions are encoded. – Dennis – 2016-11-27T02:47:43.647

16 hex digits / 2 = 3 bytes @HopefullyHelpful – Stan Strum – 2017-09-12T20:45:18.100

@StanStrum thanks – HopefullyHelpful – 2017-09-13T14:29:12.800

47

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.

xnor

Posted 2016-09-16T08:50:56.507

Reputation: 115 687

2I love [n,1-n]! – flawr – 2016-09-16T09:22:23.493

3IMHO [1-n,n] would produce nicer output. – Neil – 2016-09-16T09:47:16.540

@Neil I agree, changed it. – xnor – 2016-09-16T09:51:58.343

2Ah, that's monadese for concatMap (\n -> [1-n, n]) [1..], right? Nice! – Carsten S – 2016-09-17T16:17:03.223

@CarstenS Yes, exactly. – xnor – 2016-09-17T18:51:37.460

31

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!

flawr

Posted 2016-09-16T08:50:56.507

Reputation: 40 560

3Nice, this is the shortest Brainfuck answer I've seen so far on PPCG. – Kevin Cruijssen – 2016-09-16T11:10:15.263

1This won't work for brainfuck versions with unbounded cells. Please fix (even if as a separate answer) – John Dvorak – 2016-09-16T12:55:55.207

18@JanDvorak Answers don't need to work in every implementation, just in any one of them. – Martin Ender – 2016-09-16T13:39:14.387

1@martin that's why I suggested putting it in a separate answer. I guess "fix" might not have been the best word, though. – John Dvorak – 2016-09-16T13:41:31.827

7Could 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. – gtwebb – 2016-09-17T02:41:16.040

1@gtwebb I think it's because each character is a number, through the ASCII code. – Fund Monica's Lawsuit – 2016-09-17T08:04:33.550

@gtwebb We have to use the native number representation of the language, which is (as discussed in the meta post I linked) the byte value. Most BF interpreters do separate the outputs anyway and since each number is just one byte, you don't really need a separator anyway. Explicitly printing a character as separator would violate the rule, that each number can only be displayed once. – flawr – 2016-09-17T08:52:25.900

1I think it could be argued equally well that each cell on the BF tape represents a digit. – primo – 2016-09-17T09:46:56.627

1Given infinite time and infinite memory. With infinite memory, how do you expect to wrap around to the negative values? – SQB – 2016-09-17T17:59:20.633

5@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. – flawr – 2016-09-17T19:06:39.180

28

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

ETHproductions

Posted 2016-09-16T08:50:56.507

Reputation: 47 880

4Nice diagram! :) Did you create that by hand or write a tool to generate it? – Martin Ender – 2016-09-16T18:02:08.577

5@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. – ETHproductions – 2016-09-16T18:21:52.210

20

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

Luis Mendo

Posted 2016-09-16T08:50:56.507

Reputation: 87 464

Why is there such a big delay before it starts printing? – Fatalize – 2016-09-16T09:45:24.737

@Fatalize I think Octave needs to be restarted for every time you run a MATL program in TIO, and that takes some time. – flawr – 2016-09-16T09:47:13.717

@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 – Luis Mendo – 2016-09-16T09:48:45.910

@flawr That's true, but the delay caused by that is not so large – Luis Mendo – 2016-09-16T09:49:20.707

1Smart idea to do @_@XD rather than @_D@D so you can include the 0 on the first run. – Sanchises – 2016-09-16T10:22:26.230

@sanchises Thanks! That makes the code less "symmetric" but hey, one byte fewer... – Luis Mendo – 2016-09-16T10:34:13.393

@LuisMendo, interation index, is that a MATL specific thing? =P – Stewie Griffin – 2016-09-16T12:00:13.627

@WeeingIfFirst Of course! It's an iteration with integer index :-P Corrected, thanks – Luis Mendo – 2016-09-16T12:59:01.717

3XD +1 for smiley – TuxCrafting – 2016-09-16T18:37:53.967

1@_@ +1 for smiley – None – 2019-12-14T06:37:09.653

17

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

Christallkeks

Posted 2016-09-16T08:50:56.507

Reputation: 377

1I like this. It's terrible for golfing, but wonderful for reading. – swinefish – 2016-09-19T07:36:48.820

Typo on the last line of the explanation. Let us return to scene II. should be scene I. – Oliver Ni – 2016-10-08T23:08:50.420

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) – Christallkeks – 2016-10-13T07:15:05.993

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? – Hello Goodbye – 2019-11-21T17:24:13.317

15

Python 2, 27 bytes

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

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

xnor

Posted 2016-09-16T08:50:56.507

Reputation: 115 687

10

05AB1E, 9 6 bytes

Saved 3 bytes thanks to Adnan

[ND,±,

Try it online!

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

Emigna

Posted 2016-09-16T08:50:56.507

Reputation: 50 798

2

I was able to get it down to 6 bytes using some bitwise magic: [N,N±,.

– Adnan – 2016-09-16T10:44:02.670

1@Adnan: Nice! I tried to do something similar earlier, but didn't use ± and it ended up 3 bytes longer than yours. – Emigna – 2016-09-16T11:10:52.763

I know it's been a while, but D, can be replaced with = to save a byte. – Kevin Cruijssen – 2019-04-09T10:11:46.300

10

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.

seshoumara

Posted 2016-09-16T08:50:56.507

Reputation: 2 878

10

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

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

primo

Posted 2016-09-16T08:50:56.507

Reputation: 30 891

9

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.

flawr

Posted 2016-09-16T08:50:56.507

Reputation: 40 560

5This answer is... shady. – Conor O'Brien – 2016-09-16T12:50:33.060

1I was wondering who came up with the language name, then I noticed what language it descended from. – John Dvorak – 2016-09-16T12:59:56.567

9

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 

rturnbull

Posted 2016-09-16T08:50:56.507

Reputation: 3 689

2You can replace while(1) with repeat to save a char. – JDL – 2016-09-16T16:10:46.910

@JDL Thanks! I forget that construct exists sometimes. – rturnbull – 2016-09-16T19:32:56.120

8

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

Neil

Posted 2016-09-16T08:50:56.507

Reputation: 95 035

7

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

Kevin Cruijssen

Posted 2016-09-16T08:50:56.507

Reputation: 67 575

1

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.

– flawr – 2016-09-16T09:32:52.610

@flawr Thanks! Removing that check saved 12 bytes. – Kevin Cruijssen – 2016-09-16T09:39:19.927

Anyway it seems that the requirement of having to output all integers has been droped, so you dont need BigInteger anymore. – flawr – 2016-09-16T09:41:46.303

@flawr Ah, that's too bad.. :( I'll add it then, but I will leave my original answer. Infinite loop was more interesting, although I can understand that not every language can comply to the challenge. – Kevin Cruijssen – 2016-09-16T09:46:01.027

1Your int-version program, given infinite time, will print every integer an infinite amount of time. – Olivier Grégoire – 2016-09-18T10:13:25.177

1@OlivierGrégoire Ah, of course, MAX_VALUE + 1 is MIN_VALUE.. sigh. I've edited it, thanks for pointing it out. – Kevin Cruijssen – 2016-09-18T10:45:12.760

1If you want to golf more (ie. getting rid of MAX_VALUE, you can check ou my answer (probably still on last page). – Olivier Grégoire – 2016-09-18T11:08:23.733

@OlivierGrégoire Ah yes, forgot about that tip.. I'm glad it's weekend, because my mind is slow.. Thanks again. I've +1 yours.

– Kevin Cruijssen – 2016-09-18T12:46:39.867

1Your 53 byte solution is a snippet, not a function or program, and thus is not valid. – Mego – 2016-09-26T06:41:54.263

6

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

JosiahRyanW

Posted 2016-09-16T08:50:56.507

Reputation: 2 600

6

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}

Value Ink

Posted 2016-09-16T08:50:56.507

Reputation: 10 608

You are outputting numeric values here, so p will do it also. – manatwork – 2016-09-16T09:20:07.387

0.step{|n|p n,~n} for 17 bytes. – m-chrzan – 2016-09-19T02:15:01.747

1@m-chrzan because order doesn't matter as much, I was able to shave an extra byte off, on top of your suggestion! – Value Ink – 2016-09-19T02:26:35.760

6

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

user19214

Posted 2016-09-16T08:50:56.507

Reputation:

+? for "sooner or later ... sooner than you might expect" – Greg Martin – 2016-09-16T19:55:21.400

2Instead of [-]P, do 45P. "GNU-Dc or OpenBSD-Dc" - Are there any other versions commonly found out there in the wild? – Digital Trauma – 2016-09-16T22:35:11.850

1I 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. – Joe – 2016-09-17T04:39:16.350

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

– None – 2016-09-17T04:41:21.273

@DigitalTrauma I may be so bold as to say it runs on a "modern dc"! – Joe – 2016-09-17T04:42:29.000

@GregMartin ...all the versions will run out of memory if running a loooooong time because even if they operate on only one number, this one will take up all memory somewhen. Versions which additionally let the stack grow will run out of memory sooner... – None – 2016-09-17T04:47:44.903

@Joe ...if your solutions are different, just post... and maybe someone has ideas for optimisations... – None – 2016-09-17T05:01:16.697

@DigitalTrauma ... maybe "Dc ($xyzzy Version)" would be better? At least for puzzles where the scores table is built by a script. I need to sleep on it. Meanwhile I think just "Dc" without naming the flavour and a link to the page where "AT&T Dc" is shown like being the "basic" version may be good enough... – None – 2016-09-17T05:12:59.747

2@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. – Digital Trauma – 2016-09-17T05:41:41.903

Technically it is written dc (all lowercase) even at the start of the sentence. Wiki does it too.

– seshoumara – 2016-09-17T07:04:01.347

BASIC is all uppercase because being an abbreviation and Lua is Lua because it means moon instead of being an abbreviation... so DC being "desktop calculator" would make sense in uppercase too. Sure Dc makes the least sense... ok... I'll choose DC... – None – 2016-09-17T07:15:34.543

6

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.

Arnauld

Posted 2016-09-16T08:50:56.507

Reputation: 111 334

You can drop the function boilerplate and call it a full program. – Conor O'Brien – 2016-09-16T12:54:40.240

@ConorO'Brien - Oh, you're right. Thanks :) – Arnauld – 2016-09-16T13:07:26.870

n[a,b,c] returns n[c], so you can drop the parentheses in n[(a||n.unshift(1),0)]. – ETHproductions – 2016-09-17T00:42:14.473

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 ;-) – ETHproductions – 2016-10-03T15:08:35.950

6

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)

alex

Posted 2016-09-16T08:50:56.507

Reputation: 161

Aren't these snippets and not functions/full programs? – pinkfloydx33 – 2016-09-16T18:35:15.370

Sorry, full program added – alex – 2016-09-16T20:21:33.327

2You can omit the public modifiers and save 14 bytes. The defaults will do equally well. – Alejandro – 2016-09-17T14:20:41.193

@Alejandro thank you, it is my first post :) – alex – 2016-09-17T15:04:15.770

6

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!

Paul Schmitz

Posted 2016-09-16T08:50:56.507

Reputation: 1 089

1How about [i++,-i].map(alert) instead of alert(i++),alert(-i)? – Conor O'Brien – 2016-09-16T12:53:06.827

for(;;) is one byte shorter than while(1) – Patrick Roberts – 2016-09-16T14:42:35.897

@ConorO'Brien map is ES6 – Paul Schmitz – 2016-09-17T11:56:32.433

@PaulSchmitz Nope, 5th edition.

– Conor O'Brien – 2016-09-17T15:27:11.797

You can move the i=0; bit inside the for loop to save a byte. – Conor O'Brien – 2016-09-18T13:05:54.907

6

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.

seshoumara

Posted 2016-09-16T08:50:56.507

Reputation: 2 878

1 byte shorter: for(;;){i;-++i} – Digital Trauma – 2016-09-16T22:51:33.467

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

– seshoumara – 2016-09-16T23:45:49.637

Or for(;;){i++;-i} (same length). – sch – 2016-09-18T10:56:34.710

6

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.

Martin Ender

Posted 2016-09-16T08:50:56.507

Reputation: 184 808

This is what I came up with before seeing your answer: http://pastebin.com/VHzAvABe

– Robert Hickman – 2016-11-10T16:03:33.103

5

Brachylog, 2 bytes

ẉ⊥

Try it online!

ẉ     Print with a newline
      the input,
 ⊥    then try again.

Since the program is given no input, the main predicate's input variable is left unconstrained. At first, it is assumed to be 0, but when execution hits , it backtracks to the only possible point of failure: the choice of value for the input variable. So then it tries 1, and -1, and every other integer, printing each one separated by newlines forever because always forces backtracking, and the effect of is executed immediately.

Unrelated String

Posted 2016-09-16T08:50:56.507

Reputation: 5 300

5

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

Shaun Wild

Posted 2016-09-16T08:50:56.507

Reputation: 2 329

3biggest magnitude of the standard integer type of your language int is the standard integer type of Java. – Shaun Wild – 2016-09-16T09:38:36.817

1Sorry about that, the requirements have changed in meantime... – flawr – 2016-09-16T09:42:39.973

2You can golf it to ()->{for(int i=0;;)System.out.print(i+" "+(1-i++));}; (53 bytes) – Kevin Cruijssen – 2016-09-16T09:45:16.087

@KevinCruijssen That fucks up the spacing... – Shaun Wild – 2016-09-16T10:32:05.730

@BasicallyAlanTuring Ah, you're right.. This should work: i->{for(;;)System.out.print((1-++i)+" "+i+" ");}; (49 bytes) – Kevin Cruijssen – 2016-09-16T11:04:05.507

Thanks but I'd rather not just paste your answer lol, there's no point golfing stuff for me, because what's the point eh – Shaun Wild – 2016-09-16T11:41:16.883

I think you're missing a } character. Are you sure this compiles? – Dawood says reinstate Monica – 2016-09-17T10:52:56.087

1Given infinite time, it will print every integer an infinite amount of times each. – Olivier Grégoire – 2016-09-18T10:28:25.080

5

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

Pete Arden

Posted 2016-09-16T08:50:56.507

Reputation: 1 151

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. – Nico – 2016-09-16T10:34:37.583

Thanks. I didn't know if a delegate might be "cheating"? – Pete Arden – 2016-09-16T10:37:59.343

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)

– Kevin Cruijssen – 2016-09-16T10:48:53.347

1Oh 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! – Pete Arden – 2016-09-16T11:08:18.787

@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+",");}} :) – Kevin Cruijssen – 2016-09-16T11:14:23.503

@KevinCruijssen Awesome, pretty much half my initial effort! I'll take that! Cheers! :) – Pete Arden – 2016-09-16T11:27:15.940

5

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

Daniel Lerps

Posted 2016-09-16T08:50:56.507

Reputation: 151

1There are 2 useless whitespaces. One before Enumerable.Range and one before int.MaxValue. – Yytsi – 2016-09-16T11:19:14.920

1

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

– Kevin Cruijssen – 2016-09-16T11:59:23.850

@KevinCruijssen Thanks. Brakets are gone. – Daniel Lerps – 2016-09-16T12:03:39.000

5

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

Sok

Posted 2016-09-16T08:50:56.507

Reputation: 5 592

Is xnor unambiguously a "he"? Or are our unconscious biases showing...? – Greg Martin – 2016-09-16T19:57:26.170

2@GregMartin It's interesting, I don't think I've ever mentioned a gender. – xnor – 2016-09-16T20:41:13.323

5

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.

Conor O'Brien

Posted 2016-09-16T08:50:56.507

Reputation: 36 228

5

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

whatever

Posted 2016-09-16T08:50:56.507

Reputation: 161

1Welcome to PPCG! – AdmBorkBork – 2016-09-19T15:15:56.790

5

Bash + GNU utilities, 26

seq NaN|sed '1i0
p;s/^/-/'

Digital Trauma

Posted 2016-09-16T08:50:56.507

Reputation: 64 644

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. – seshoumara – 2016-09-17T07:36:36.157

Looks like a newer feature - see the source code. Adding 1 to NaN shouldn't cause a wraparound.

– Digital Trauma – 2016-09-17T17:31:27.567

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 – seshoumara – 2016-09-17T18:30:18.230

4

Pyke, 7 2 bytes

~I

Try it here!

7 bytes

oDID_)r

Try it here!

If printing +-0 is ok, oD_r

Blue

Posted 2016-09-16T08:50:56.507

Reputation: 26 661

4

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.

Dennis

Posted 2016-09-16T08:50:56.507

Reputation: 196 637

3

C (gcc), 40 38 36 bytes

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

Try it online!

Explanation:

The first argument to main() is argc, which is 1 if the program is run without additional parameters. When we reach the max positive integer, i wraps around and becomes negative. The program stops when i==0, after printing it.

Thanks @ceilingcat for -3 bytes

G B

Posted 2016-09-16T08:50:56.507

Reputation: 11 099

You can save 4 bytes by {while(i)printf("%d ",i++);} – Jasmes – 2017-04-06T19:13:06.493

1But then it would not print 0 at the end. – G B – 2017-04-07T07:14:59.307

1Your 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));} – Josh – 2019-10-03T19:59:56.287

1This doesn't print negative integers – Jo King – 2019-11-21T05:49:26.393

You are right, I rolled back to the non-recursive version (which was in fact 1 byte shorter than I previously thought). – G B – 2019-11-21T06:48:04.127

3

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

Martin Ender

Posted 2016-09-16T08:50:56.507

Reputation: 184 808

Figured out a one liner in the same amount of bytes. Try it online!

– Jo King – 2018-02-12T02:16:45.013

@JoKing neat! :) – Martin Ender – 2018-02-12T06:38:38.147

3

Husk, 2 bytes

İZ

Try it online!

I know Husk is created after the post of the challenge but I think it is still worth mentioning.

Weijun Zhou

Posted 2016-09-16T08:50:56.507

Reputation: 3 396

3

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

Emigna

Posted 2016-09-16T08:50:56.507

Reputation: 50 798

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. – SQB – 2016-09-17T18:19:26.163

@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. – Emigna – 2016-09-18T08:16:47.437

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. – SQB – 2016-09-18T08:21:35.390

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! – SQB – 2016-09-18T08:23:38.613

@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. – Emigna – 2016-09-18T12:08:45.683

I'm sorry to report that the behaviour of writeln/1 seems to be a bug in SWISh; I've opened an issue. So you probably will need to add two bytes and use two writeln/1s.

– SQB – 2016-09-20T14:36:52.517

@SQB: Technically I don't need to as the norm is that if the code works in an interpreter (even utilizing bugs) it is fair game. Though this entry is not contending for the throne in any case so I'll do it anyway :) – Emigna – 2016-09-20T17:11:49.813

Also, the big has been fixed and the online interpreter patched. – SQB – 2016-09-24T19:54:46.010

@SQB: Indeed, Thanks for the update :) – Emigna – 2016-09-24T20:28:43.190

A * B:-writeln(A),C is A+B,writeln(-C),C * B. 41 bytes – user3744156 – 2018-02-21T13:38:21.677

A * B:-C is B-A,writeln(C),C * (1-B). 33 bytes but hard for execute. (0*0 for start) – user3744156 – 2018-02-21T14:07:39.203

@user3744156: Cool, thanks! I like the way you removed the need for double writeln's. – Emigna – 2018-02-21T14:59:50.373

3

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.

AdmBorkBork

Posted 2016-09-16T08:50:56.507

Reputation: 41 581

3

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

Sp3000

Posted 2016-09-16T08:50:56.507

Reputation: 58 729

3

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.

James

Posted 2016-09-16T08:50:56.507

Reputation: 54 537

3

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?

Sunny Pun

Posted 2016-09-16T08:50:56.507

Reputation: 821

3

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

Pete Arden

Posted 2016-09-16T08:50:56.507

Reputation: 1 151

1Using 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 – steenbergh – 2016-11-11T09:54:17.847

@steenbergh Cool, thanks! It wouldn't let me declare and set on the same line, but still saved 8 Bytes! :) – Pete Arden – 2016-11-11T17:41:04.207

2

SmileBASIC, 20 bytes

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

A very boring answer.

Alternative:

@L?N
INC N?-N
GOTO @L

12Me21

Posted 2016-09-16T08:50:56.507

Reputation: 6 110

This will print 0 twice, making it an invalid answer. "print every integer exactly once" – snail_ – 2018-03-29T08:44:45.403

1Welll.... technically it prints negative 0 -0... But now it's fixed. – 12Me21 – 2018-03-29T14:55:07.483

2

tcl, 35

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

demo

sergiol

Posted 2016-09-16T08:50:56.507

Reputation: 3 055

2

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

caird coinheringaahing

Posted 2016-09-16T08:50:56.507

Reputation: 13 702

2

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

Bolce Bussiere

Posted 2016-09-16T08:50:56.507

Reputation: 970

2

MarioLANG, 17 bytes

:<
+"
)(
-:
>!
=#

Try it online!

Vertical loops are normally shorter in MarioLANG. This outputs:

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

CoedRhyfelwr

Posted 2016-09-16T08:50:56.507

Reputation: 272

2

Pyth, 6 bytes

0f!
_

Try it online!

In string representation, this is "0f!\n_\n".

We print 0 explicitly, then use f in "count up from 1 until result truthy" mode, where the function prints the input, negates it, prints that, and then boolean negates the result so f will never halt.

isaacg

Posted 2016-09-16T08:50:56.507

Reputation: 39 268

2

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)

user59178

Posted 2016-09-16T08:50:56.507

Reputation: 1 007

This won't output PHP_INT_MIN, so it's invalid – aross – 2016-09-26T08:23:41.030

sure it will, it switches over to a double representation which has enough precision to be accurate to php_int_min. – user59178 – 2016-09-26T08:53:21.777

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 – aross – 2016-09-26T08:59:47.813

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 – user59178 – 2016-09-26T09:34:52.040

So your answer is only valid in a very specific system, and you should note that – aross – 2016-09-26T09:40:37.597

2

Retina, 21 19 bytes

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

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

Martin Ender

Posted 2016-09-16T08:50:56.507

Reputation: 184 808

2

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

colsw

Posted 2016-09-16T08:50:56.507

Reputation: 3 195

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. – AdmBorkBork – 2016-10-07T18:51:02.807

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! – colsw – 2016-10-08T13:53:22.627

2

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

Crypto

Posted 2016-09-16T08:50:56.507

Reputation: 862

This won't output PHP_INT_MAX, so it's invalid – aross – 2016-09-26T08:21:50.597

Sorry, it doesn't output PHP_INT_MIN – aross – 2016-09-26T09:28:31.057

Still won't output PHP_INT_MIN. Look at my answer

– aross – 2016-09-29T14:27:15.207

I agree, I was editing. – Crypto – 2016-09-29T14:28:29.643

2

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.

Martin Ender

Posted 2016-09-16T08:50:56.507

Reputation: 184 808

2

Lua , 43 Bytes

i=1;while 1 do print(1-i);print(i);i=i+1 end

Jörg Hülsermann

Posted 2016-09-16T08:50:56.507

Reputation: 13 026

2

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'

Ton Hospel

Posted 2016-09-16T08:50:56.507

Reputation: 14 114

Nice. say"-".++$_ while say$_|0 should behave as your second solution if I'm not mistaken, and is 2 bytes shorter. – Dada – 2016-09-16T16:40:46.127

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 – Ton Hospel – 2016-09-16T16:53:36.623

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. – Dada – 2016-09-16T16:59:07.250

2

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.

Mark

Posted 2016-09-16T08:50:56.507

Reputation: 2 099

Seems invalid: "The separator must not change at any point." – primo – 2016-09-17T08:09:22.387

@primo, better now? – Mark – 2016-09-17T16:47:49.977

2

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

Grax32

Posted 2016-09-16T08:50:56.507

Reputation: 1 282

2

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

mroman

Posted 2016-09-16T08:50:56.507

Reputation: 1 382

2

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

Olivier Grégoire

Posted 2016-09-16T08:50:56.507

Reputation: 10 647

2

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.

sebastian-c

Posted 2016-09-16T08:50:56.507

Reputation: 121

1Hi, 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, ...? – Kevin Cruijssen – 2016-09-19T13:06:51.143

2It 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 – sebastian-c – 2016-09-19T14:53:54.487

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. – Kevin Cruijssen – 2016-09-19T15:02:10.750

2

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.

aross

Posted 2016-09-16T08:50:56.507

Reputation: 1 583

2

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.

Steven H.

Posted 2016-09-16T08:50:56.507

Reputation: 2 841

Where can we find the intepreter for this language? – Fatalize – 2016-10-04T06:32:06.193

https://github.com/Steven-Hewitt/LI/blob/master/Interpreter.py I'll edit it into the OP as well. – Steven H. – 2016-10-04T06:32:37.443

2

q KDB+, 25 bytes

n:-0W;while[n<0W;0N!n+:1]

Set n to negative infinity.

n:-0W

Increment and output n.

0N!n+:1

Loop until n < infinity.

n<0W

Possible alternate 17 bytes

(0N!1+)\[0W>;-0W]

Uses the \ (iterate) dyadic function to apply left hand side (plus 1 then output) from negative infinity (-0W) to infinity(0W).

Only problem is that it may throw a wsfull error eventually or at the very end after outputting all the integers.

Adam J

Posted 2016-09-16T08:50:56.507

Reputation: 81

1

Java 8, 87 bytes

Alternative solution using an IntStream to iterate through all integers.

java.util.stream.IntStream.rangeClosed(1<<31,~1<<31).forEach(n->System.out.println(n));

Alternative, 57 bytes

I didn't want to post this as my main answer, because it's just stolen from @KevinCruijssen's Java 7 answer, switched to go from negative to positive for no particular reason, and turned into a lambda. But it is technically shorter.

()->for(int i=1<<31;i<0;System.out.println(i+"\n"+~i++));

Xanderhall

Posted 2016-09-16T08:50:56.507

Reputation: 1 236

1

Python 2, 32 bytes

i=0
while 1:print i;print~i;i+=1

SanBot

Posted 2016-09-16T08:50:56.507

Reputation: 41

You could also do i=0 (newline) while 1:print i;print~i;i+=1 if you wanted – ETHproductions – 2016-12-29T18:16:17.720

2If you need rep for your chat bot account, consider making a meaningful contribution to the site. This adds absolutely nothing over the pre-existing 27 byte Python answer. – Dennis – 2016-12-29T22:34:47.050

1

Excel VBA, 25 20 Bytes

Anonymous VBE immediate window function that takes no input and outputs to the vbe immediate window

Do:?1-n;n:n=n+1:Loop

Note: Excel will appear to be non-responsive after executing to n=6012, adding a DoEvents: call at the beginning of any of the lines in the do...loop corrects this visual bug, but is not necessary for correct execution.

Taylor Scott

Posted 2016-09-16T08:50:56.507

Reputation: 6 709

1

JS (NON - ES6), 25 bytes

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

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

programmer5000

Posted 2016-09-16T08:50:56.507

Reputation: 7 828

1

Implicit, 6 5 4 bytes on TIO

(%.ß

Requires that the input box on TIO be empty.

(...    « do..while top of stack truthy                 »;
 %      «  print top of stack as int                    »;
  .     «  increment (reads from input if stack empty)  »;
   ß    «  print space                                  »;
    ¶   « (implicit) just kidding, loop forever         »;

Try it online!

Implicit, 5 bytes

0(%.ß
0        « push 0           »;
 (%.ß    « (same as above)  »;

MD XF

Posted 2016-09-16T08:50:56.507

Reputation: 11 605

But how does this eventually print the negative numbers? – None – 2019-12-14T06:48:22.290

1

Common Lisp, 42 bytes

(do((i 0))(())(print(- i))(print(incf i)))

Try it online!

Renzo

Posted 2016-09-16T08:50:56.507

Reputation: 2 260

1

Momema, 26 bytes

z0-8*0-9 00+1*0-8-*0-9 0z1

Try it online!

This outputs null bytes as the separator (though TIO displays them as spaces).

Alternatively, at a cost of 1 byte, here's a version that uses tabs instead of null bytes:

z0-8*0-9 9 0+1*0-8-*0-9 9z1

Explanation

                                                   #  a = 0
z   0     #  label z0: jump past label z0 (no-op)  #  while true {
-8  *0    #            output number [0]           #    print a 
-9  0     #            output chr 0                #    print '\0'
0   +1*0  #            [0] = [0] + 1               #    a++
-8  -*0   #            output number -[0]          #    print -a
-9  0     #            output chr 0                #    print '\0'
z   1     #  label z1: jump past label z1          #  }

Esolanging Fruit

Posted 2016-09-16T08:50:56.507

Reputation: 13 542

1

Forked, 21 bytes

%A!v
   >1+%A!AF*!%A!

First, this does %A! (print 0 followed by a newline), then executes the code in my original answer below, before I realized we were supposed to print 0 too:


Forked, 12 bytes

1+%A!AF*!%A!

Try it online!

  • 1+ - add 1 to the top of the stack
  • % - print top of stack as integer
  • A! - print 0xA (ASCII newline)
  • AF*! - print 0xA × 0xF = 0x2D (ASCII -)
  • % - print top of stack as integer
  • A! - print 0xA (ASCII newline)

Forked is two-dimensional, so the IP wraps upon hitting the edge of the playing field.

This just loops through every integer, prints it followed by a newline, then prints it again, preceded by a - and proceeded by a newline.

MD XF

Posted 2016-09-16T08:50:56.507

Reputation: 11 605

1

Appleseed, 41 bytes

(def I(q(((n 0))(cons n(I(sub(less? n 1)n

Defines a function I that takes no arguments and returns an infinite list of integers, starting (0 1 -1 2 -2 ...). Try it online!

Note: Appleseed is in the early stages of development at the moment, so if this code stops working at some point in the future, ping me and I'll update it.

Ungolfed + explanation

; Load the library for functions & macros such as lambda
(load library)
; Define all-integers to be...
(def all-integers
  ; a lambda function with one optional argument, n, whose default value is 0
  (lambda ((n 0))
    ; The function prepends n to...
    (cons n
      ; the result of a recursive call...
      (all-integers
        ; whose argument is (n<1) - n, i.e. -n if n is positive, else -n+1
        (sub (less? n 1) n)))))

DLosc

Posted 2016-09-16T08:50:56.507

Reputation: 21 213

1

Pyt, 11 bytes

00Ƥ`⁺ĐĐ~ƤƤł

Try it online!

00   pushes 0 twice 
Ƥ    prints with a newline separator
`    indicator for looping
⁺    increments
ĐĐ   duplicates twice
~    negates top value
ƤƤ   prints positive and negative value
ł    loops till top is zero (never)

FantaC

Posted 2016-09-16T08:50:56.507

Reputation: 1 425

1

Coconut, 25 bytes

def f(n=0)=[n,~n]::f(n+1)

Try it online!

ovs

Posted 2016-09-16T08:50:56.507

Reputation: 21 408

1

Milky Way, 9 bytes

&{!k1-!j}

Try it online!

How?

           initial Stack: ["", 0]
&{      }  infinite loop
  !        output ToS
   k       negative absolute value
    1-     subtract 1
      !    output ToS
       j   absolute value

ovs

Posted 2016-09-16T08:50:56.507

Reputation: 21 408

1

QBasic, 23 bytes

Script that takes no input and outputs to the console. Values are newline delimited and increment in the order of \$0, -1, 1, -2, 2, \cdots\$.

?0
Do
i=i+1
?-i
?i
Loop

Taylor Scott

Posted 2016-09-16T08:50:56.507

Reputation: 6 709

1

Python 3, 44 bytes

i=0;print(i)
while 1:i+=1;print(i);print(-i)

Try it online!

Sagittarius

Posted 2016-09-16T08:50:56.507

Reputation: 169

1

GolfScript, 16 14 bytes

1{.p.1\-p).}do

Explanation:

1              # Set counter to 1
 {        .}do # While counter is nonzero:
  .p           # Print counter
    .1\-p      # Print counter - 1
         )     # Increment counter by 1

Try it online!

user85052

Posted 2016-09-16T08:50:56.507

Reputation:

1

Keg, -pn, 15 9 bytes

0.1{:④±.⑨

Try it online!

Answer History

15 bytes

0. ,1{④± ,④ ,±⑨

Try it online!

Really messy I know, but it works. Integers are space seperated

Lyxal

Posted 2016-09-16T08:50:56.507

Reputation: 5 253

1

Wren, 50 bytes

var n=0
while(n)n=-System.print(1-System.print(n))

Try it online!

Explanation

var n=0 // Set n as 0
while(n)                                   // While n is an integer:
                          System.print(n)  // Output n
           System.print(1-               ) // Output 1-n
        n=-                                // Set n as the number negated

user85052

Posted 2016-09-16T08:50:56.507

Reputation:

1

Runic Enchantments, 24 bytes

8?;>0$' $01+:$' $Z:$' $Z

Try it online!

' $ is just as long as any other way of printing a character (such as ak$) so with a required separator, that's as short as it gets.

Will print forever until the value exceeds the binary representation and sign-overflows (which is acceptable for questions with an infinite memory assumption), whereupon it will repeat.

Draco18s no longer trusts SE

Posted 2016-09-16T08:50:56.507

Reputation: 3 053

1

x86-16, IBM PC DOS, 47 bytes

Binary:

00000000: 33c9 bd0a 0050 0bc0 7d09 50b8 2d0e cd10  3....P..}.P.-...
00000010: 58f7 d833 d2f7 f552 410b c075 f658 b40e  X..3...RA..u.X..
00000020: 0c30 cd10 e2f7 b020 cd10 5840 75d7 c3    .0..... ..X@u..

Build and test using xxd -r

Unassembled listing:

33 C9       XOR  CX, CX         ; clear counter
B3 0A       MOV  BL, 10         ; BX is divisor              
        INT_LOOP: 
50          PUSH AX             ; save registers 
0B C0       OR   AX, AX         ; is AX negative? 
7D 09       JGE  DIGIT_LOOP     ; if positive, start digit loop 
50          PUSH AX             ; save number 
B8 0E2D     MOV  AX, 0E2DH      ; BIOS tty function, '-' char output 
CD 10       INT  10H            ; write to console 
58          POP  AX             ; restore AX 
F7 D8       NEG  AX             ; AX = -AX                
        DIGIT_LOOP: 
33 D2       XOR  DX, DX         ; clear high word of dividend   
F7 F3       DIV  BX             ; AX = quotient, DX = remainder 
52          PUSH DX             ; save remainder on stack 
41          INC  CX             ; increment counter 
0B C0       OR   AX, AX         ; quotient = 0?
75 F6       JNE  DIGIT_LOOP     ; no, keep going 
        PRINT_LOOP: 
58          POP  AX             ; restore digit in AL 
B4 0E       MOV  AH, 0EH        ; BIOS tty function 
0C 30       OR   AL, '0'        ; convert to ASCII 
CD 10       INT  10H            ; write to console 
E2 F7       LOOP PRINT_LOOP     ; loop until all digits displayed 
B0 20       MOV  AL, ' '        ; space char 
CD 10       INT  10H            ; write to console 
58          POP  AX             ; restore counter 
40          INC  AX             ; increment to next number 
75 D7       JNZ  INT_LOOP       ; loop until 0 
C3          RET                 ; return to DOS

(This program is basically just an itoa() function...)

Output

A standalone DOS executable. Using default 16-bit integer size for 8088, writes all numbers in decimal to console.

Head:

enter image description here

Tail:

enter image description here

640KB

Posted 2016-09-16T08:50:56.507

Reputation: 7 149

1

MATL, 9 bytes

0`t_DQtDT

You can Try it online! (and let's hope that the process on the server actually terminates once you close your browser...)

Explanation:

0             % Push 0 on stack
 `       T    % Start infinite loop
  t_D         % Duplicate top element, negate and display (which consumes the duplicate)
     QtD      % Add 1 to top of stack, duplicate and display (which consumes the duplicate)

Sanchises

Posted 2016-09-16T08:50:56.507

Reputation: 8 530

1

Caché ObjectScript, 28 bytes

w 0 f i=1:1 {w ",",i,",",-i}

adaptun

Posted 2016-09-16T08:50:56.507

Reputation: 161

1

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

Stewie Griffin

Posted 2016-09-16T08:50:56.507

Reputation: 43 471

1

MATLAB 64 bytes

As a start, with nothing clever:

fprintf('0');a=int64(1);while(1) fprintf(' %d',[a -a]);a=a+1;end

Enter at the console, generates 0 1 -1 2 -2...

There must be a better way than this! Come on, folks...

Richard

Posted 2016-09-16T08:50:56.507

Reputation: 11

Why int64? The octave answer might give you some "inspiration" – Stewie Griffin – 2016-09-16T16:39:35.037

I wrote this quite fast, so it can most likely be golfed a lot more, but this is a lot shorter: x=0;while 1;disp(x);x=x+1;disp(-x);end. It's 26 bytes shorter =) – Stewie Griffin – 2016-09-22T12:05:17.513

I know this is old, but what Stewie's saying is that the default int in MATLAB is int32, whereas the default double goes up to 2^53

– Sanchises – 2016-11-08T22:03:04.210

1

Reticular, 12 bytes

0dp1+dpd0#2j

Try it online!

Explanation

0dp1+dpd0#2j   ; stack
0              ; [0]   
 dp            ; [0]   PRINTED 0
   1+          ; [1]
     dp        ; [1]   PRINTED 1
       d0#     ; [1, -1]
          2j   ; skip two spaces after the j, wrapping to..
  p            ; [1]   PRINTED -1
   1+          ; [2]
     dp        ; [2]   PRINTED 2
       d0#     ; [2]   PRINTED -2
               ; etc.

Conor O'Brien

Posted 2016-09-16T08:50:56.507

Reputation: 36 228

1

Pyth , 7 bytes

0.V1_bb

Explanation

0       # print 0
 .V1    # increment 'b' forever, starting on 1
    _b  # print -b
      b # print b

Rod

Posted 2016-09-16T08:50:56.507

Reputation: 17 588

1

Brain-Flak, 28 + 3 = 31 bytes

To get a program that outputs every integer in some finite time (but the whole thing in infinite time) you need to use debug flags.

Try it online

(@dv()@dv){([[{}]@dv]()@dv)}

The program is 28 bytes and the command line flag is 3 making the total 31.

An alternative that does not technically fit the specs:

Try it online

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

If you run the program you will notice there is no output. This is because Brain-flak programs output when they terminate. It will output all the numbers at once once infinite time has elapsed. If you want to verify that it works try it online with debug flags.

Post Rock Garf Hunter

Posted 2016-09-16T08:50:56.507

Reputation: 55 382

1

Perl 6, 22 bytes

loop {say $--;say ++$}

Explanation:

loop {
  say   (state $ = 0)--; # prints 「0␤」 first time around, then 「-1␤」 「-2␤」 etc
  say ++(state $ = 0)    # prints 「1␤」 first time around, then 「2␤」 「3␤」 etc
}

Brad Gilbert b2gills

Posted 2016-09-16T08:50:56.507

Reputation: 12 713

1

bash, 46 Bytes

echo 0;for((i=1;;i++)){ echo -e "$i\n-$i"; }

rexkogitans

Posted 2016-09-16T08:50:56.507

Reputation: 589

You don't need a space after ;, or after {. – Peter Cordes – 2017-09-16T07:37:11.250

1

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.

Joe

Posted 2016-09-16T08:50:56.507

Reputation: 895

2"In case anyone finds these to be of interest" ... I do! ;-) – None – 2016-09-17T06:34:04.857

1

Racket 56 bytes

(saved 12 bytes with suggestion by @StevenH)

(λ()(let l((i 0))(printf"~a, ~a, "i(- -1 i))(l(+ 1 i))))

Ungolfed:

(define(f)
  (let loop ((i 0))
     (printf "~a, ~a, "  i  (- -1 i))
     (loop (add1 i))))

Following can also be used:

(for((i(in-naturals)))(printf"~a, ~a, "i(- -1 i)))

or:

(for ((i (in-naturals)))
   (printf "~a, ~a, " i (- -1 i)))

Testing:

(f)

0, -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, -14, 14, -15, 15, -16, 16, -17, 17, -18, 18, -19, 19, -20, 20, -21, 21, -22, 22, -23, 23

rnso

Posted 2016-09-16T08:50:56.507

Reputation: 1 635

You can avoid the first printf entirely by replacing (* i -1) with (- -1 i). – Steven H. – 2016-10-07T06:17:03.320

Thanks for the suggestion. I have added it to my answer. – rnso – 2016-10-07T06:29:30.697

1

Brainfuck, 10 bytes

.+[>-.<.+]

Does not rely on cell wrapping to print the negative values. Does rely on accepting the cell value, which is commonly printed as a character by converting it to ASCII, to be the value to print.

Try it online!

SQB

Posted 2016-09-16T08:50:56.507

Reputation: 681

1

C 331 bytes

Note that this outperforms the long version as it really can do as many as memory will permit. It seems like it is bounded by strings of length max(size_t) which is true, but also definitionally the maximum memory that c will let us grab. Unfortunately it is very slow since it thrashes memory.

#include<stdlib.h>
int main(_,a,b,c,d,e)char*a,*b;size_t c,d,e;{return(_==1?printf("0\n"),main(2,0,0,1,0,0):_==2?main(3,"",0,c,0,0),main(2,0,0,c+1,0,0):_==3?(c?d=strlen(a),b=malloc(d),memcpy(b,a,d),b[d+1]=0,main(4,b,0,d,c-1,9),free(b),0:(*a-48?printf("%s\n-%s\n",a,a):0)):(e+1?a[c]=e+48,main(3,a,0,d,0,0),main(4,a,0,c,d,e-1):0));}

Prints 0, then 9,8,7,... then 99,98,97... etcetera. Can save 3 characters if we assume we don't care about output buffering (swapping \n for a space).

Process:

Initial

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

// prints base 0...0, base 0...1, etc with remaining digits after it.
void print_digit_permutations(char *base, size_t remaining)
{
    int i;
    char *newbase = malloc(strlen(base)+1);

    if (!remaining) {
        if (*base != '0') 
            printf("%s\n-%s\n",base,base);
        return;
    }

    for (i = 0; base[i]; ++i) {
        newbase[i] = base[i];
    }
    newbase[strlen(base)+1] = 0;

    for (i = 0; i < 10; ++i) {
        newbase[strlen(base)] = i + '0';
        print_digit_permutations(newbase, remaining-1);
    }

    free(newbase);
}


int main()
{
    char *base = "";
    size_t i = 0;

    printf("0\n");

    for (;;) {
        print_digit_permutations(base, ++i);
    }

    return 0;
}

Unrolled

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void base_copy(char *newbase, char *base)
{
    if (*base) {
        *newbase = *base;
        base_copy(newbase+1,base+1);
    }
}

void print_digit_permutations(char*,size_t);
void print_all_digits(char *newbase, size_t baselen, size_t remaining, size_t count)
{
    if (count+1) {
        newbase[baselen] = count + '0';
        print_digit_permutations(newbase,remaining);
        print_all_digits(newbase,baselen,remaining,count-1);
    }
}

void print_digit_permutations(char *base, size_t remaining)
{
    int i;
    char *newbase = malloc(strlen(base)+1);

    if (!remaining) {
        if (*base != '0')
            printf("%s\n-%s\n",base,base);
        return;
    }

    base_copy(newbase,base);
    newbase[strlen(base)+1] = 0;

    print_all_digits(newbase,strlen(base),remaining-1,9);

    free(newbase);
}

void all(size_t size)
{
    print_digit_permutations("",size);
    all(size+1);
}

int main()
{
     printf("0\n");
     all(1);   

     return 0;
}

Flat

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int print_digit_permutations(char *base, char *newbase, size_t remaining, size_t baselen, size_t _);
int print_all_digits(char *newbase, char *_, size_t baselen, size_t remaining, size_t count)
{
    return (count+1?
                newbase[baselen] = count + '0',
                print_digit_permutations(newbase,newbase,remaining,0,0),
                print_all_digits(newbase,newbase,baselen,remaining,count-1)
                :
                0);
}

int print_digit_permutations(char *base, char *newbase, size_t remaining, size_t baselen, size_t _)
{
    return (remaining?
            baselen=strlen(base),
            newbase = malloc(baselen),
            memcpy(newbase,base,baselen),
            newbase[baselen+1] = 0,
            print_all_digits(newbase,newbase,baselen,remaining-1,9),
            free(newbase),
            0
            :
            (*base-'0'?printf("%s\n-%s\n",base,base):0));
}

int all(char *_, char *_2, size_t size, size_t _3, size_t _4)
{
    return print_digit_permutations("","",size,0,0),
           all(_,_2,size+1,_3,_4);
}

int main()
{
    return printf("0\n"),all("","",1,0,0);
}

Main

#include <stdlib.h>
/* _ values:
 *
 * 1 - main
 * 2 - all 
 * 3 - print_digit_permutations
 * 4 - print_all_digits
 */
int main(_,a,b,c,d,e)char*a,*b;size_t c,d,e;{
    switch (_) {
        case 1:
            return printf("0\n"),main(2,0,0,1,0,0);
        case 2:
            return main(3,"",0,c,0,0),main(2,0,0,c+1,0,0);
        case 3:
            return (c?
                    d=strlen(a),
                    b=malloc(d),
                    memcpy(b,a,d),
                    b[d+1]=0,
                    main(4,b,0,d,c-1,9),
                    free(b),
                    0
                    :
                    (*a-'0'?printf("%s\n-%s\n",a,a):0));
        case 4:
            return (e+1?
                        a[c]=e+'0',
                        main(3,a,0,d,0,0),
                        main(4,a,0,c,d,e-1)
                        :0);
    }
}

And after removing whitespace and making a few other small changes we arrive at the initial golfed code. It is interesting that the 'proper' initial code is the second shortest at just over 700 bytes.

LambdaBeta

Posted 2016-09-16T08:50:56.507

Reputation: 2 499

1

Haxe, 46 bytes

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

Yytsi

Posted 2016-09-16T08:50:56.507

Reputation: 3 582

1

RProgN, 22 21 Bytes

►0p11¿]p]0\-p1+]} 

Note the trailing space IS required.

Saved a byte by replacing the -1 * n with a simple 0 - n, because defining -1 in ► form takes too many bytes.

Explination

►           # Read this word as a single-character based command.
0p          # Print the number 0
11          # Push two 1's to the stack.
¿           # While the top of the stack is truthy, pop the top of the stack.
    ]       # Clone the top of the stack, containing i.
    p       # Print it.
    ]       # Clone it again.
    0 \ - * # Push 0 to the stack, swap the 0 and the object underneith it, giving 0, n instead of n, 0. Subtract giving -n.
    p       # Print it.
    1+      # Add one to i
    ]       # Clone it for the next truthy check
}           # End the while statement
            # Required to interpret the while loop correctly.

Output

0
1
-1
2
-2
3
-3
4
-4
5
...

This language looks nothing like it's former self. ;(

ATaco

Posted 2016-09-16T08:50:56.507

Reputation: 7 898

1

ForceLang, 87 67 59 bytes

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

SuperJedi224

Posted 2016-09-16T08:50:56.507

Reputation: 11 342

1

C, 44 bytes

long l;f(){printf("%ld ",l);l=(l<=0)-l;f();}

Note that the (implicit) int return type does not cause f to require a return because f never reaches the end of the function.

This code uses the fact that globally defined variables are initialized to zero.

Note that on a system with unlimited memory (or with a compiler that does tail recursion elimination)there will be no stack overflow, therefore this program fulfils the requirements.

celtschk

Posted 2016-09-16T08:50:56.507

Reputation: 4 650

1

Rust, 39 bytes

||for i in 0..{print!(" {} {}",i,-1-i)}

This uses i32. adding i64 right behind the zero would make it use that instead at a cost of 3 more bytes. Rust has no bignum types in the standard library. When overflowing, this will either panic or quietly wrap around, depending on compiler options.

Harald Korneliussen

Posted 2016-09-16T08:50:56.507

Reputation: 430

0

Straw, 26 bytes

~(~$:>(,-)>:>(,)>#0+~:&):&

Try it online!

~(~$:>(,-)>:>(,)>#0+~:&):&
~ ~                 ~      Swap between the two stacks
 (                     )   Push a string literal
   $                       Unary -> decimal
    :      :         :     Duplicate
     >    > >   >          Output
      (,-)   (,)           String literal
                 #         Decimal -> unary
                  0        Push the character '0'
                   +       Concatenate
                      &  & Evaluate

It prints -0 too, not sure if it's allowed though

TuxCrafting

Posted 2016-09-16T08:50:56.507

Reputation: 4 547

0

Pushy, 7 bytes

0[~#|h#

Try it online! (will eventually cut the output)

Explanation:

0     \ Push 0 as the starting counter
[     \ Infinitely:
 ~#   \   Negate counter (and print)
 |h   \   Push abs(counter)+1
 #    \   Print counter

This prints in the pattern 0 1 -1 2 -2 3 -3..., separated by newlines.

Pushy's reference implementation is in Python, which uses arbitrarily sized integers, and so there won't be any overflow if you run this for a long time. However, the integer would eventually get too large and cause a MemoryError.

FlipTack

Posted 2016-09-16T08:50:56.507

Reputation: 13 242

0

CJam, 10 bytes

0{_n~_nz}h

Try it online!

Erik the Outgolfer

Posted 2016-09-16T08:50:56.507

Reputation: 38 134

0

Triangular, 21 bytes

()ip.%@,|<.>A@\/A|%p<

(Does not work on the TIO version yet.) Formats into this triangle:

     (
    ) i
   p . %
  @ , | <
 . > A @ \
/ A | % p <

This got really messy once I realized there had to be delimiters between the numbers.

The directionals (<,>\/) poke the IP around to get this code executed:

(i%|A@p%|A@p)

How it works:

  • ( opens a loop.
  • i increments the top of stack.
  • % prints the top of stack as an integer.
  • | negates the top of stack.
  • A pushes 10 to the stack.
  • @ prints the top of stack as ASCII \n.
  • p pops the 10. Now the top of stack is the negated value.
  • % prints the top of stack (negated value).
  • | un-negates the top of stack.
  • A pushes 10 to the stack again.
  • @ prints as ASCII \n.
  • p pops the top of stack.
  • ) unconditionally jumps back to the loop.

MD XF

Posted 2016-09-16T08:50:56.507

Reputation: 11 605

0

Aceto, 9 bytes

dpnd~pnIO
d duplicates the top val
p prints it
n does a newline
~ negates  the top val
I Increments the top val
O returns to the beginning of the program

Try it online!

FantaC

Posted 2016-09-16T08:50:56.507

Reputation: 1 425

0

Yabasic, 22 bytes

An anonymous answer that takes no input and outputs all integers to the console.

?0
Do
i=i+1
?-i,i
Loop

Try it online!

Taylor Scott

Posted 2016-09-16T08:50:56.507

Reputation: 6 709

0

uBASIC, 24 bytes

An anonymous answer that takes no input and outputs to the console.

0?0
1i=i+1:?i,0-i:GoTo1:

Try it online! (and yes, the terminal : is necessary)

Taylor Scott

Posted 2016-09-16T08:50:56.507

Reputation: 6 709

0

MY-BASIC, 38 bytes

Print 0;
While 1
i=i+1
Print-i;i;
Wend

Try it online!

Taylor Scott

Posted 2016-09-16T08:50:56.507

Reputation: 6 709

0

Visual Basic .NET (Mono), 95 bytes

A declared subroutine that takes no input and outputs to the console.

Module M
Sub Main
Dim i
Do
Console.WriteLine(-i &IIf(i," "&i,""))
i=i+1
Loop
End Sub
End Module

Try it online!

Taylor Scott

Posted 2016-09-16T08:50:56.507

Reputation: 6 709

0

F#, 69 bytes

let f=
 let mutable i=0m
 while 1>0 do
  printf"%O,-%O,"i i
  i<-i+1m

It's pretty straight forward. The 0m sets i as 0, but of type decimal. Since we're allowed to print 0, -0 I'm doing that. i gets incremented with every iteration of the loop, and the value is printed out.

I my initial idea would have been 70 bytes but (like most of my initial ideas) it would never have worked:

let g=Seq.iter(fun x->printfn"%O,-%O"x x)[0m..System.Decimal.MaxValue]

In this one [0m..System.Decimal.MaxValue] creates an array starting at 0, adding 1 each time and going all the way to the maximum decimal value. (Another example would be the expression [1..10] creates an array with {1,2,3,4,5,6,7,8,9,10}).

Seq.iter would then apply the function for printing to that array.

The problem with this is that the array must be constructed before iterating through it. So for all integers, with infinite memory the array could be constructed - but it would also take an infinite amount of time, so nothing would ever be printed out!

Ciaran_McCarthy

Posted 2016-09-16T08:50:56.507

Reputation: 689

0

Japt, 12 10 bytes

_OlU°,Un}a

Try it online!

Explanation:

_OlU°,Un}a
            | Implicit U = 0
_       }a  | Start an infinite loop
 Ol         | Write to the console:
   U°       |   U++
     ,      |    and
      Un    |   0-U

Oliver

Posted 2016-09-16T08:50:56.507

Reputation: 7 160

0

Javascript, 96 bytes

f=n=>f([].concat(...n.map(i=>alert(+i?i+' -'+i:i)||+i?y.map(o=>i+o):[])));f(y=[...`0123456789`])

Alerts all integers in the sequence (0, 1, -1, 2, -2, ...), using strings to go beyond JS's usual max safe integer 9007199254740991. This is equivalent to the "Infinite version" in Arnauld's earlier answer.

Yair Rand

Posted 2016-09-16T08:50:56.507

Reputation: 381

0

Scala, 112 bytes

val x=Int.MaxValue
val y=Int.MinValue
print(0)
for(a <-1 until x) print(","+a + "," + a * -1)
print(","+x+","+y)

Try it online!

Testable Running Program with limits [-10,10]

Scala, 143 bytes

object ListNumbers extends App {
  val x = 10
  val y = -10
  print(0)
  for(a <- 1 until x) print(","+a + "," + a * -1)
  print(","+x+","+y)
}

Try it online!

Using Java 8 Streams just for fun, it generates a lazy populated string

types declarations can be omitted but I included for "documentation"

Scala, 253 bytes

val zero :Stream[String] = Stream("0")
val positive :Stream[Int]= Stream.from(1)
val negative :Stream[Int]= positive.map(_* -1)

val stream = zero ++ positive.zip(negative).map(x => x._1.toString()+","+x._2.toString())
//stream.take(Int.MaxValue).toList

Try it online!

firephil

Posted 2016-09-16T08:50:56.507

Reputation: 211

0

Gol><>, 7 bytes

lN01l-N

Try it online!

How it works

lN01l-N
l        push current stack length (n)
 N       pop and print with newline
  01l    push 0, 1, then stack length (n+2)
     -   pop n+2, 1, then push 1 - (n+2) = -n-1
      N  pop and print with newline
         now the stack length is n+1; repeat indefinitely

Bubbler

Posted 2016-09-16T08:50:56.507

Reputation: 16 616

0

Zephyr, 48 bytes

set i to 0
while 1=1
print-i,i+1...
inc i
repeat

Space-separated. If the separator could alternate between space and newline, the ... could be removed for -3 bytes. Try it online!

DLosc

Posted 2016-09-16T08:50:56.507

Reputation: 21 213

0

Small Basic, 92 bytes

A Script that takes no input and outputs to the TextWindow object.

TextWindow.Write(0+" ")
While 1=1
i=i+1
TextWindow.Write(Text.Append(-i+" ",i+" "))
EndWhile

Taylor Scott

Posted 2016-09-16T08:50:56.507

Reputation: 6 709

0

W d, 6 5 bytes

Newline-separated. Look ma, no bitwise magic!

▲h(2Z

Explanation

Decompressed:

0      % Print 0 (the implicit not-given operand, to be precise)
 i   E % In the range 1..infinity...
  a    % Explicit loop variable
   P   % Print the number with a newline
    _  % Negate the number
       % Implicit print on each iteration
       % Make sure that the second-to-top executes (this is now implicit)

user85052

Posted 2016-09-16T08:50:56.507

Reputation:

0

Non-wrapping Brain****, 9 bytes

Thanks to Scepheo for saving one byte!

+[.+<.->] 

Steven H.

Posted 2016-09-16T08:50:56.507

Reputation: 2 841

1Duplicate answer. (the first part anyway) – Martin Ender – 2016-09-16T13:39:44.653

Non-wrapping can be shorter by printing before decrementing: +[.+>.-<] – Scepheo – 2016-09-16T13:47:21.370

0

MATLAB 65 bytes

My earlier post was faulty because the loop does not stop. A better try is this:

a=intmin('int64');(a:-a)'

but while this will work for the smaller int8 type it will not for int64 as the maximum array size will (of course) be exceeded. Note that transposing the vector prevents the console output from being interrupted by 'columns m to n' messages.

Another funny with MATLAB is that integers do NOT roll over, thus intmax('int64') + 1 == intmax('int64') not intmin('int64') as I expected. Also, MATLAB does not have a 'do' loop, So the best I can think of is this:

a=intmin('int64');b=-a;while(1) a, if a==b break, end; a=a+1; end

an then only if we allow the 'any separator' to allow this:

a =
   -9223372036854775808
a =
   -9223372036854775807
...
a =
    9223372036854775806
a =
    9223372036854775807 

There must be a better way!

Richard

Posted 2016-09-16T08:50:56.507

Reputation: 1

0

C, 64 Bytes

f(n){printf(",%d",n);n>0?f(-n),f(++n):0;}main(){f(printf("0"));}

A full program that terminates after printing all the integers it can represent.

Output

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

cleblanc

Posted 2016-09-16T08:50:56.507

Reputation: 3 360

0

Bash, 33 55 bytes

for((;;)){ echo -n $[-i++],$i,;((i==LLONG_MAX))&&exit;}

Unfortunately bash won't give an integer overflow error when $i exceeds the maximum size of the type used to store it. Therefore, I updated the code to include a termination criteria, that requires $LLONG_MAX to be defined in the environment or passed on the command line.

Run example: on my system bash uses signed 64-bit integers

LLONG_MAX=$[2**63-1] ./all_integers.sh

The following code is a 32 byte version (1 less) of my original post, that assumed undefined printing behavior after the integer overflow.

for((;;)){ echo -n $[-i++],$i,;}

seshoumara

Posted 2016-09-16T08:50:56.507

Reputation: 2 878

0

Oracle SQL 11.2, 77 73 72 68 bytes

SELECT CEIL((LEVEL-1)/2)*(MOD(LEVEL,2)*2-1)FROM DUAL CONNECT BY 1=1;

Jeto

Posted 2016-09-16T08:50:56.507

Reputation: 1 601

0

C, 51 50 bytes

void f(){long i=0;for(;;)printf("%d %d ",i++,-i);}

I could save a byte by doing int instead of long, but since this can go longer than int without wrapping I'm leaving it.

Output:

0 -1 1 -2 2 -3 3 -4 4 -5 5 -6 6 ...

Cody

Posted 2016-09-16T08:50:56.507

Reputation: 447

This program will run forever, shouldn't it terminate after printing all the "longs"? P.S. you can save a byte using for(;;) in place of while(1) – cleblanc – 2016-09-16T17:30:41.070

A lot of the other answers here run forever, so I just went with it. That way, you can #define long into arbitrarily large types. Good tip on saving a byte though. – Cody – 2016-09-16T18:07:47.143

It's pointless to use long with a %d conversion (instead of %ld). On x86-64 with 64-bit long, printf it will only look at the low 32 bits of its args. I can't think of a plausible way for any normal calling convention on any ISA where %d would print a number outside the range of int; most calling conventions require functions to ignore garbage in high bits. You could save a ; by putting the variable declaration inside the for(). i.e. for(int i=0;;)printf.... Especially since you didn't omit the return-type or anything, so this is valid C99. – Peter Cordes – 2017-09-16T07:35:30.460

0

C++ with Boost, 143 bytes

#include <boost/multiprecision/cpp_int.hpp>
#include <iostream>
boost::multiprecision::cpp_int i;main(){while(++i)std::cout<<1-i<<','<<i<<',';}

Not very short, but it does use an arbitrary-precision type. To test that, I tried replacing ++i with i=2*i+1, and very soon there were numbers several hundred digits long being printed correctly. This should work until the number takes up all your stack memory.

user59468

Posted 2016-09-16T08:50:56.507

Reputation: 261

Suggest turning the while loop into a for loop, replacing ',' with 44 and deleting the space after #include. – ceilingcat – 2016-11-10T01:38:55.300

0

Swift 3 (34 bytes)

(Int.min...Int.max).map{print($0)}

Really, we should be able to get this down to 30 bytes like so:

(Int.min...Int.max).map(print)

But the compiler doesn't allow this yet.

mklbtz

Posted 2016-09-16T08:50:56.507

Reputation: 151

130 bytes: print(Array(Int.min...(.max))) – Tamás Sengel – 2018-03-29T20:55:23.467

0

Actually, 7 bytes

01W;±@u

This solution requires infinite time to actually print anything. Finite memory will cause an out of memory error and premature printing. No TIO link for obvious reasons.

Explanation:

01W;±@u
0        push 0
 1       push 1
  W      infinite loop:
   ;       duplicate
    ±      unary negate
     @     swap with positive
      u    increment

This solution works for 8 bytes, prints a finite amount of numbers in a finite amount of time, and uses significantly less memory (the memory used doesn't start growing until after INT_MAX is printed, at which point Python seamlessly transitions to arbitrary-precision integers).

0■~W■±■~

Try it online! (only prints up to around 9292 due to timeout).

Explanation:

0■~W■±■~
0         push 0
 ■        print entire stack without popping (just the 0)
  ~       bitwise negate (~n is equivalent to -n-1)
   W      infinite loop:
    ■       print stack without popping
     ±      unary negate
      ■     print without pop
       ~    bitwise negate

Mego

Posted 2016-09-16T08:50:56.507

Reputation: 32 998

This solution requires infinite time to actually print anything contradicts Any supported integer must eventually be printed after a finite amount of time – Fatalize – 2016-09-17T13:01:00.517

@Fatalize Integers will be printed after a finite amount of time, if there's a finite amount of memory available. – Mego – 2016-09-17T17:59:42.473

and they will never get printed in a finite amount of time with an infinite amount of memory, so this answer is invalid – Fatalize – 2016-09-17T18:13:19.597

@Fatalize Then please clarify that in the challenge body. – Mego – 2016-09-17T20:46:17.257

0

k (20 bytes)

The function between curly braces is repeatedly iterated on it's result, starting at zero, until the result converges at 0W (k infinity).

{-1@'$?-1 1*x;x+1}/0

The function prints the argument and its negation and then returns incremented argument.

skeevey

Posted 2016-09-16T08:50:56.507

Reputation: 4 139

0

C++, 84 Bytes

#include <iostream>
int main(){for(int i=0;;)std::cout<<i++<<','<<-i<<',';return 0;}

Edit: thanks for the debugging, commenters

oMittens

Posted 2016-09-16T08:50:56.507

Reputation: 1

Welcome to PPCG! All answers need to be full programs or functions and the relevant includes/namespaces need to be counted as well. If you make your submission a full program, it should compile in any existing compiler as is, and if it's a function it should be possible to drop it into any program and use and compile it without any other additional code.

– Martin Ender – 2016-09-17T15:53:11.627

That loop doesn't print a delimiter between the numbers. – celtschk – 2016-10-13T23:08:24.920

0

Python, 40 bytes

p=print
p(0)
i=1
while 1:p(i);p(-i);i+=1

vpzomtrrfrt

Posted 2016-09-16T08:50:56.507

Reputation: 201

You need to remove the p(0) line, or else 0 will be printed 3 times. – Mego – 2016-09-26T06:40:15.080

0

C# function 53 bytes

int j;void X(){for(;;)Console.Write($"{j++},-{j},");}

Explanation:

Create a variable "j" in class scope. This will default to have a value of zero. Write and increment value and then write the negative of that value. This will output "0,-1," on the first loop and "1,-2," on the 2nd loop.

Grax32

Posted 2016-09-16T08:50:56.507

Reputation: 1 282

0

QBIC, 14 bytes

{?1-q ?q q=q+1

qis 1 by default in QBIC, so this prints (1-1=) 0, 1, -1, 2, -2... separated by line breaks.

steenbergh

Posted 2016-09-16T08:50:56.507

Reputation: 7 772