70
\$\begingroup\$

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

Possible outputs could be:

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

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

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

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

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

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

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

  • The separator must not change at any point.

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

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

Scoring

This is , so the shortest answer in bytes wins

Leaderboard

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

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

178 Answers 178

5
\$\begingroup\$

><>, 19 15 bytes

1::1$-naonao1+!

This prints the following:

0
1
-1
2
-2
3
-3

... and so on. The separator is a newline.

Re-written after reading @xnor's answer to use a version of that algorithm. Starting at n=1, the program prints 1-n and n, each followed by a newline, before incrementing n. After overflowing the maximum value the program will end with an error of something smells fishy.... Exactly when this will happen depends on the interpreter implementation.


Previous version:

0:nao0$-:10{0(?$~+!

Starting at 0, the program loops indefinitely. On each loop, the current value is printed along with a newline. It is then negated, and incremented if positive.

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

Pyke, 7 2 bytes

~I

Try it here!

7 bytes

oDID_)r

Try it here!

If printing +-0 is ok, oD_r

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

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.

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

convey, 14 bytes

}"0
 v^0
1-"-}

Try it online!

How it works (so cool):

How it works:

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

APOL, 19 bytes

w(T p(∈) p(-(0 ∈)))

Pretty self-explanatory.

\$\endgroup\$
4
\$\begingroup\$

Jelly, 5 bytes

Ṅ~ṄNß

Try it online!

How it works

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

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

SQL, 84 76 Bytes

Saved 8 Bytes thanks to steenbergh :)

Golfed:

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

Ungolfed:

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

Prints:

0
1
-1
2
-2
3
-3
4
-4
5
-5
...
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Using the 1-n trick you can drop the PRINT 0 at the start of your function: DECLARE @n INT = 1 WHILE 1=1 BEGIN PRINT 1-@n PRINT @n SET @n=@n+1 END \$\endgroup\$
    – steenbergh
    Commented Nov 11, 2016 at 9:54
  • \$\begingroup\$ @steenbergh Cool, thanks! It wouldn't let me declare and set on the same line, but still saved 8 Bytes! :) \$\endgroup\$
    – Pete Arden
    Commented Nov 11, 2016 at 17:41
  • 1
    \$\begingroup\$ Nice answer. FYI the DECLARE trick @steenbergh mentioned is version specific; it works only in SQL 2008 and later. SQL 2008 also added the @+=1 "compound" operator, which saves 2 bytes over @=@+1. You can use @ instead of @n for the variable; its weird but works. Finally, a label like A: with GOTO A is shorter than a WHILE loop. All that can bring it down to 49: DECLARE @ INT=1A:PRINT 1-@ PRINT @ SET @+=1GOTO A \$\endgroup\$
    – BradC
    Commented Apr 27, 2020 at 19:26
4
\$\begingroup\$

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.

\$\endgroup\$
0
4
\$\begingroup\$

Prolog (SWI), 33+3 = 36 bytes

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

Try it online!

Called as 0*0.

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

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

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

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

Hexagony, 14 bytes

Compacted:

 !~{/")!;/;"~{/

Formatted:

   ! ~ {
  / " ) !
 ; / ; " ~
  { / . .
   . . .

Try it online!

Improves upon @Sunny Pun's answer by not using the middle -> edge branches, but instead uses a more linear control flow, while delimiting with null bytes (didn't see anything against this) which are the default state of memory in Hexagony.

\$\endgroup\$
4
\$\begingroup\$

Dyalog APL, 18 17 15 14 12 bytes

{∇-⎕←1-⎕←⍵}0

Try it online!

{       Begin function
  ∇     Call recursively with new argument and repeat: -⍵-1
  -     Negate sign to make it negative again: -⍵-1
  ⎕←    Print current value: ⍵+1
  1-    Subtract it from 1, flipping the sign and incrementing the absolute value: ⍵+1
  ⎕←    Print current value: -⍵
  -     Negate sign to make it negative: -⍵
  ⍵     Argument to function, starts at 0 and increments by one each time: ⍵
}       End function
0       Call function with 0

Thanks to @Razetime & @Adám for their help golfing my original 18 bytes to 12. It started as ⎕←0⋄{∇⊃1+|⎕←-⎕←⍵}1 and is far more elegant now, not to mention more competitive!

\$\endgroup\$
4
\$\begingroup\$

Bash, with no external utilities, and no integer size limits, 210 208 bytes

echo 0
while
j=$i@
do
while
k=${j/9@/@0}
[ $k != $j ]
do
j=$k
done
j=${j/0@/1}
j=${j/1@/2}
j=${j/2@/3}
j=${j/3@/4}
j=${j/4@/5}
j=${j/5@/6}
j=${j/6@/7}
j=${j/7@/8}
j=${j/8@/9}
i=${j/@/1}
echo $i
echo -$i
done

Try it online!

If you wish to see it run with large integers, initialize i to a large integer.

\$\endgroup\$
4
\$\begingroup\$

Regenerate -a, 22 bytes

0|($2[0-9]!-?[1-9]())+

Attempt This Online!

Thanks to thejonymyster for the idea to use this language to answer this question.

In pretty-printed format:

    0
|
    (
        $2       # only matches after $2 has been set
        [0-9]    # all subsequent digits
    !
        -?       # negative or positive
        [1-9]    # first digit
        ()       # capture group $2
    )+           # Repeat the above 1 to infinity times

The first main alternative is 0. Once that has been used, it moves on to the second main alternative, which is split into two sub-alternatives. They are split using ! instead of |, so whichever choice is made will be locked-in once it no longer results in any changes of state.

The first time through, the $2[0-9] branch cannot be taken, since $2 is unset and results in a non-match. So the branch -?[1-9]() will be taken – and it results in a change of state: the capture group $2 becomes set rather than unset.

Due to the change of state, the (...!...) set of alternatives is given another chance to be chosen, if it is repeated. Since $2 is now set, the first alternative will be taken, and this locks it in – from this point forward, it is the only alternative that will be taken.

...or at least, that's my current best understanding of how it works. I don't think it's correct, otherwise 0|($4($3[0-9]![1-9]())!-?()){2,} (32 bytes) should do the same thing as the 22 byte version, but it doesn't. The ! operand is undocumented, so it'll take analyzing Regenerate's source code or asking to author to figure out how exactly it works.

...but as it turns out, 0|($2[0-9]!$3[1-9]()!-?‍()){2,} (31 chars / 33 bytes), with a zero width joiner inserted after the -?, does work, so my explanation may be accurate. The problem may just be that alternatives don't work the same way when they make a zero-width match.

Regenerate -a (staging), 15 bytes

0|-?[1-9][0-9]*

Attempt This Online!

In the latest version of the language, the obvious solution now works. Before the fix, this would only print nonnegative integers beginning with the digit 1:

Attempt This Online! - presumably this link will eventually show the same behavior as the above one, when the new version of Regenerate graduates from staging

Regenerate -a, 12 bytes (10 characters)

0|(‍+)-?#1

Attempt This Online!

If outputting invisible whitespace is allowed, this can be used to "cheat":

    0
|
    (‍+)  # $1 = Repeat U+200D (Zero Width Joiner), 1 to infinity times
    -?   # Optionally match a negative sign
    #1   # Match the length of $1 as a number in decimal

Regenerate would theoretically keep printing all integers indefinitely, but in practice it stops due to hitting a recursion limit. It can't actually repeat anything more than 994 times on Attempt This Online, for example.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ I think your explanation is pretty spot-on (and clever use of !). I'm not entirely sure what's going on in the 32-byte version, but it probably has to do with the order of backtracking doing something unexpected. I'd have to analyze it step-by-step. \$\endgroup\$
    – DLosc
    Commented Jun 29, 2022 at 4:20
  • 1
    \$\begingroup\$ (After analysis, it turned out there was a bug with empty capture groups.) \$\endgroup\$
    – DLosc
    Commented Jun 30, 2022 at 2:58
3
\$\begingroup\$

PowerShell v2+, 26 bytes

0;for(;$i-lt2gb){$i;-++$i}

Covers all 32-bit [int] values, as that's the default number type for PowerShell. Prints 0, then loops up to 2gb (which is a special operator, not a constant, yielding 2147483648). Must be called as a full program so that $i properly defaults back to $null.

Example

PS C:\Tools\Scripts> 0;for(;$i-lt2gb){$i;-++$i}
0
-1
1
-2
2
...
2147483646
-2147483647
2147483647
-2147483648

Truly infinite, 34 bytes

0;for([bigint]$i=1;;$i+=1){$i;-$i}

For a truly infinite variation that will (eventually) print every single integer in existence given infinite time and memory, try the above. We simply tack on the [bigint] cast and change slightly how the loop is calculated.

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

><>, 11 bytes

lnao0l-naol

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

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

Perl, 19 bytes

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

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

This 27 byte version will really print forever:

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

Hexagony, 22 18 bytes

!(~2016}Q2;'Oct4!~

Try it Online!

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

Old Answer

Try it Online! (old answer)

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

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

Expanded

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

The basic algorithm is,

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

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

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

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

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

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

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.

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

Wumpus, 8 bytes

=nON
=)N

Try it online!

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

Explanation

Let's look at the actual grid first:

Control flow diagram

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

So the loop body looks like this:

=nONON)=

Let's go through this:

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

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

\$\endgroup\$
8
  • \$\begingroup\$ You can save 4 bytes by {while(i)printf("%d ",i++);} \$\endgroup\$
    – Jasmes
    Commented Apr 6, 2017 at 19:13
  • 2
    \$\begingroup\$ But then it would not print 0 at the end. \$\endgroup\$
    – G B
    Commented Apr 7, 2017 at 7:14
  • 1
    \$\begingroup\$ Your answer inspired me to try recursion! Saves one byte, but at the cost of ugliness and undefined behavior: main(i){printf("%d ",i,i++&&main(i));} \$\endgroup\$
    – Josh
    Commented Oct 3, 2019 at 19:59
  • 2
    \$\begingroup\$ This doesn't print negative integers \$\endgroup\$
    – Jo King
    Commented Nov 21, 2019 at 5:49
  • \$\begingroup\$ You are right, I rolled back to the non-recursive version (which was in fact 1 byte shorter than I previously thought). \$\endgroup\$
    – G B
    Commented Nov 21, 2019 at 6:48
3
\$\begingroup\$

Turing Machine Code, 460 bytes

This prints the list in Unary so I'm hoping this still counts since, in Turing Machine Code, the concept of a 'number base' isn't built in. I'm going to mull over a base ten solution and post it separately if it exists and I find it.

0 * 1 r 2
2 * , r 3
3 * - r 4
4 * 1 r 5
5 * * r 5
5 _ , r 6
6 * * r 6
6 _ 1 * 7
7 * * l 7
7 , , l 8
8 * * l 8
8 - - r 9
9 1 @ r a
8 , , r g
g 1 @ r a
g - - r a
a * * r a
a _ 1 l b
b * * l b
b @ 1 r c
c 1 @ r a
c , , r d
d * * l d
d - - r 6
d , , r e
e * * r e
e _ , r f
f _ - r h
h * * l h
h , , l i
i * * l i
i , , r j
j 1 @ r k
j , , r m
k * * r k
m * * r m
m _ , r n
k _ 1 * o
o * * l o
o , , l p
p * * l p 
p , , r q
p @ 1 r j
q * * r q
q _ , r n
n _ 1 r 7

Try it online!

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

V (vim), 18 bytes

i0<esc>qqYp<c-a>Yi-<esc>p@qq@q

Try it online!

a small improvement by shuffling around the loop and removing the 1 from James' answer.

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

Vyxal, 5 bytes

{N…ꜝ…

Try it Online!

{     # Forever...
 N    # Negate
  …   # Print
   ꜝ  # ~
    … # Print
\$\endgroup\$
3
  • \$\begingroup\$ Why not just Þn? \$\endgroup\$
    – lyxal
    Commented Jun 28, 2022 at 7:49
  • \$\begingroup\$ @lyxal That's a thing? Oh well :P \$\endgroup\$
    – emanresu A
    Commented Jun 28, 2022 at 7:50
  • \$\begingroup\$ #1122 \$\endgroup\$
    – lyxal
    Commented Jun 28, 2022 at 7:52
3
\$\begingroup\$

iogii, 7 5 bytes

e;1<-

run it here!!

-2 inspired by Darren Smith!

e        Expand (iterate from nil (coerces to 0)):
  1<     Is the value less than 1?
 ;  -    Subtract the original value from that.

expand and iterate technically aren't actual iteration constructs, but they can be reasoned about as such.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ I think 6 is possible with expand op! \$\endgroup\$ Commented Oct 29 at 20:49
3
\$\begingroup\$

Piet + ascii-piet, 20 bytes (10×2=20 codels)

tL RrN?FmBnDbAjBsCiq

Try Piet online!

The separator is ASCII 1. You can confirm the separator is ASCII 1 by copy pasting the output from the Piet code into the input of this Python script.

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

Octave, 30 bytes

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

Explanation:

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

Prints the following sequence, starting from 0:

   0
  -1
   1
  -2
   2
  -3
   3
   .
   .
\$\endgroup\$
2
\$\begingroup\$

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

\$\endgroup\$
3
  • \$\begingroup\$ Why int64? The octave answer might give you some "inspiration" 😊 \$\endgroup\$ Commented Sep 16, 2016 at 16:39
  • \$\begingroup\$ 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 =) \$\endgroup\$ Commented Sep 22, 2016 at 12:05
  • \$\begingroup\$ 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 \$\endgroup\$
    – Sanchises
    Commented Nov 8, 2016 at 22:03
2
\$\begingroup\$

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

Befunge 93, 8 bytes

:.-:0`!-

Try it online!

Explanation

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

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

The source code is toroidal so this program repeats indefinitely.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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