title: Apply a wave to an array

text:
# Question
Title: Apply a wave to an array
Your task today is to apply a wave to an array of numbers. A wave looks like this: `[1, 0, -1, 0, 1, 0, -1, 0, 1...]` Applying it to a given array means adding together the first elements, the second elements, etc.

More precisely:

Your program or function will receive an array of integers. It must print or return an equally sized array with `1` added to the 1st, 5th, 9th, etc. element of the original array, `-1` added to the 3rd, 7th, 11th, etc. element of the original array, and the rest of the elements should be left untouched.

The input array is guaranteed to have at least one element.

Test cases:

```
Input                               | Output
[0]                                 | [1]
[-1]                                | [0]
[-4, 3, 0, 1, 7, 9, 8, -2, 11, -88] | [-3, 3, -1, 1, 8, 9, 7, -2, 12, -88]
[0, 0, 0, 0, 0]                     | [1 ,0 ,-1 ,0 ,1]
[1, 1]                              | [2, 1]

```

This is , shortest code wins!

# Answer
# Jelly, 5 bytes

```
Jı*Ċ+

```

Try it online!

### How it works

```
Jı*Ċ+  Main link. Argument: A (array)

J      Indices; yield [1, ..., len(A)].
 ı*    Elevate the imaginary unit to the power 1, ..., len(A), yielding
       [0+1i, -1+0i, 0-1i, 1+0i, ...].
   Ċ   Take the imaginary part of each result.
    +  Add the results to the corresponding elements of A.

```
> 8 votes

# Answer
# LOGO, 18 bytes

```
[map[?+sin 90*#]?]

```

There is no "Try it online!" link because all online LOGO interpreter does not support template-list.

That is a template-list (equivalent of lambda function in other languages).

Usage:

```
pr invoke [map[?+sin 90*#]?] [-4 3 0 1 7 9 8 -2 11 -88]

```

(`invoke` calls the function, `pr` prints the result)

prints `[-3 3 -1 1 8 9 7 -2 12 -88]`.

Explanation (already pretty understandable):

```
 map[?+sin 90*#]?       map a function over all the items of the input
              #         the 1-based index of the element in the input
       sin 90*#         equal to the required wave
     ?                  looping variable
     ?+sin 90*#         add the wave to the input

```
> 14 votes

# Answer
# Haskell, 26 bytes

```
zipWith(+)$cycle[1,0,-1,0]

```

Try it online! (runs all test cases)

Explanation:

```
zipWith(+)$cycle[1,0,-1,0]  -- anonymous tacit function
zipWith(+)                  -- pairwise addition between input list
          $cycle[1,0,-1,0]  -- and an infinitely-cycling "wave" list

```
> 13 votes

# Answer
# Mathematica, ~~26~~ ~~23~~ 22 bytes

```
Im[I^Range@Tr[1^#]]+#&

```

Try it online! (Mathics)

Note: The TIO link is for the 23-byte version, the 22-byte version is not Mathics-compatible.
> 10 votes

# Answer
## JavaScript (ES6), 28 bytes

```
a=>a.map((x,i)=>x-(i%4-1)%2)

```

The calculation goes like this:

```
i%4  -1  %2
0    -1  -1
1     0   0
2     1   1
3     2   0

```

The last bit taking advantage of the fact that in JS, a negative number when modulated will retain its negative sign (i.e. `-5 % 3 -> -2`, instead of `1` as it would be in Python).
> 10 votes

# Answer
# Python 2, 40 bytes

```
i=2
for x in input():print~-x+i%5%3;i*=2

```

Try it online!
> 9 votes

# Answer
# MATL, ~~11~~ 8 bytes

```
Jyn:^Yj+

```

Try it at **MATL Online!**

### Explanation

```
J     % Push 1j (imaginary unit)
      % STACK; 1j
y     % Implicit input. Duplicate from below
      % STACK: [-4 3 0 1 7 9 8 -2 11 -88], 1j, [-4 3 0 1 7 9 8 -2 11 -88]
n     % Number of elements
      % STACK: [-4 3 0 1 7 9 8 -2 11 -88], 1j, 10
:     % Range
      % STACK: [-4 3 0 1 7 9 8 -2 11 -88], 1j, [1 2 3 4 5 6 7 8 9 10]
^     % Power, element-wise
      % STACK: [-4 3 0 1 7 9 8 -2 11 -88], [1j -1 -1j 1 1j -1 -1j 1 1j -1]
Yj    % Imaginary part
      % STACK: [-4 3 0 1 7 9 8 -2 11 -88], [1 0 -1 0 1 0 -1 0 1 0]
+     % Add, element-wise. Implicit display
      % STACK: [-3 3 -1 1 8 9 7 -2 12 -88]

```
> 8 votes

# Answer
# , ~~29~~ 24 bytes

```
(l=scan())+Im(1i^seq(l))

```

Try it online!
> 3 votes

# Answer
# Jelly, 16 bytes

```
-1Jm2$$¦+2Jm4$$¦

```

Try it online!

heh I'm sure this is too long

# Edit

I know a 5 byte solution is possible but my wifi appears to be starting to cut me off so I'll golf this tomorrow. If someone posts the short Jelly solution before I can golf this, that's fine with me; I'll just keep this here for reference as to ~~how bad I am at Jelly lol~~ another way of doing it. I mean, I *could* just look at the link Phoenix posted in the comments, but since I'm still learning, I don't want to look at the solution until I've figured it out myself. This might cost me reputation but the learning is what I'm here for :)))
> 3 votes

# Answer
# Python 2, ~~50~~ 42 bytes

Saved 8 bytes thanks to @Sisyphus!

```
lambda l:map(sum,zip(l,[1,0,-1,0]*len(l)))

```

Try it online!

### 53 bytes

```
lambda l:[int(x+(1j**i).real)for i,x in enumerate(l)]

```

Try it online!
> 3 votes

# Answer
# J, 12 bytes

```
+1 0 _1 0$~#

```

Try it online!

Because J's shape operator `$` fills cyclically, when we shape it to the length `#` of the input, it does exactly what we want, and we can just add it to the input `]`
> 3 votes

# Answer
# Haskell, 26 bytes

*@Mego beat me to this solution*

```
zipWith(+)$cycle[1,0,-1,0]

```

Try it online!

This is what Haskell is great at. This declares a point-free function that zips the input with an infinite list.

# Haskell, 56 bytes

Here's a solution that uses complex numbers. Not very competitive because of the import but never the less pretty cool.

```
import Data.Complex
zipWith((+).realPart.((0:+1)^))[0..]

```

Try it online!
> 3 votes

# Answer
## C++, ~~93~~ ~~85~~ ~~83~~ 63 bytes

```
auto w=[](auto&i){for(int j=0;j<i.size();j+=2)i[j]+=j%4?-1:1;};

```

-8 bytes, thanks to this answer, i discovered that lambda parameters can be `auto` and you can pass with the correct parameter, it will work

-2 bytes thanks to Nevay

-2 bytes thanks to Zacharý

I removed the `vector` include. You will need to pass as argument to w a container that respect the following conditions :

* Have a method called `size` with no arguments
* Have overloaded the subscript operator

STL Containers that respect the following conditions are `array`, `vector`, `string`, `map`, `unordered_map`, and maybe others

If outputting by modifying arguments arguments is not allowed, then :

## C++, ~~112~~ 110 bytes

```
#include<vector>
std::vector<int>w(std::vector<int>i){for(int j=0;j<i.size();j+=2)i[j]+=(j%4)?-1:1;return i;}

```
> 3 votes

# Answer
# Mathematica, 19 bytes

```
i=1;#+Im[i*=I]&/@#&

```

### Explanation

```
i=1;#+Im[i*=I]&/@#&
i=1;                 (* set variable i to 1 *)
               /@#   (* iterate through the input: *)
    #+Im[i   ]&      (* add the imaginary component of i... *)
          *=I        (* multiplying i by the imaginary unit each iteration *)

```

Note: `i=1` appears outside of the function, which is okay per this meta consensus.
> 3 votes

# Answer
# Pari/GP, 30 bytes

```
a->[a[x]+imag(I^x)|x<-[1..#a]]

```

Try it online!
> 2 votes

# Answer
# Japt, ~~11~~ 10 bytes

Takes advantage of Japt's index wrapping.

```
Ë+[1TJT]gE

```

Test it

---

## Explanation

Implicit input of array `U`.

```
Ë

```

Map over the array.

```
+

```

To the current element add...

```
gE

```

The element at the current index (`E`)...

```
[1TJT]

```

In the array `[1,0,-1,0]`.
> 2 votes

# Answer
# Dyalog APL, 13 bytes

```
⊢+1 0 ¯1 0⍴⍨≢

```

Try it online!

**How?**

`1 0 ¯1 0` \- the array \[1, 0, -1, 0\]

`⍴⍨≢` \- reshape to the length of the input, cyclic

`⊢+` \- vectorized sum with the input
> 2 votes

# Answer
# Perl 6, ~~28~~ 22 bytes

~~{((1+0i,*×i...*)Z+$\_)».re}~~

```
(*Z-(i*i,*i...*))».re

```

Try it online!

`i*i, *i ... *` produces an infinite list of the numbers `-1, -i, 1, i` repeateded in a cycle. Those numbers are zipped with subtraction (`Z-`) with the input list (`*`), and then the real components of the resulting complex numbers are extracted (`».re`).
> 2 votes

# Answer
# Ruby, 38 bytes

```
->a{a.zip([1,0,-1,0].cycle).map &:sum}

```

Try it online!
> 2 votes

# Answer
# D, 56 bytes

```
void w(T)(T[]i){for(T j;j<i.length;j+=2)i[j]+=j%4?-1:1;}

```

Try it online!

This is a port of HatsuPointerKun's C++ answer, so don't forget about them!
> 2 votes

# Answer
# Actually, 11 bytes

```
;r⌠╦½*C≈⌡M¥

```

Try it online! (runs all test cases)

Explanation:

```
;r⌠╦½*C≈⌡M¥
;r           range(len(input))
  ⌠╦½*C≈⌡M   for each value in range:
   ╦½*C      cos(pi/2*value)
       ≈     floor to integer
          ¥  pairwise addition of the input and the new list

```
> 1 votes

# Answer
# Pyth, 11 bytes

```
.e+bss^.j)k

```

Try it online!
> 1 votes

# Answer
# CJam, 15 bytes

```
l~_,,[1TW0]f=.+

```

Try it online!
> 1 votes

# Answer
# 8th, ~~96~~ 63 bytes

**Code**

```
a:new swap ( swap 90 * deg>rad n:cos int + a:push ) a:each drop

```

This code leaves resulting array on TOS

**Usage and examples**

```
ok> [0,0,0,0,0] a:new swap ( swap 90 n:* deg>rad n:cos n:int n:+ a:push ) a:each drop .
[1,0,-1,0,1]

ok> [-4,3,0,1,7,9,8,-2,11,-88] a:new swap ( swap 90 * deg>rad n:cos int + a:push ) a:each drop .
[-3,3,-1,1,8,9,7,-2,12,-88]

```

**Explanation**

We use cos(x) in order get the right sequence \[1,0,-1,0\]. Each array element's index is multiplied by 90 degrees and then it is passed to cos() function to get the desired "wave factor" to be added to the corresponding item.

```
: f \ a -- a
  a:new    \ create output array
  swap     \ put input array on TOS
  \ array element's index is passed to cos in order to compute
  \ the "wave factor" to add to each item
  ( swap 90 n:* deg>rad n:cos n:int n:+
  a:push ) \ push new item into output array
  a:each
  drop     \ get rid of input array and leave ouput array on TOS
;

```
> 1 votes

# Answer
# Math.JS, 34 bytes

```
f(k)=k.map(j(x,y,z)=x+im(i^y[1]))

```

## Explained

```
f(k)=k.map(j(x,y,z)=x+im(i^y[1]))
f(k)=                               # Define a function f, which takes argument k.
     k.map(                     )   # Map k to a function
           j(x,y,z)=                # Function j. Takes arguments x, y, and z. Where x is the item, y is the index in the form [i], and z is the original list.
                      im(      )    # The imaginary component of...
                         i^y[1]     # i to the power of the index.
                    x+              # x +, which gives our wave.

```

Try it Online!
> 1 votes

# Answer
# C# (.NET Core), 50 bytes

```
n=>{for(int i=0;i<n.Length;i+=2)n[i]+=i%4<1?1:-1;}

```

Try it online!

Uses a simple lambda. Modifies the original array and returns the output through reference.
> 1 votes

# Answer
# 05AB1E, 16 bytes

```
vy3L2.SR0¸«Nè+})

```

Try it online!

---

`3L2.SR0¸«` is the shortest thing I can think of for `sin(x % 4)` in 05AB1E.
> 1 votes

# Answer
# Arturo, 33 bytes

```
$=>[i:0map&=>[&-((i%4)-1)%2'i+1]]

```

Try it

Port of ETHproductions' JavaScript answer.
> 0 votes

# Answer
# Zsh, 34 bytes

```
for i;echo $[++j%2*(j%4>2?-1:1)+i]

```

Try it online!
> 0 votes

# Answer
# Pyt, 9 bytes

```
ĐŁřπ*₂šƖ+

```

Try it online!

```
Đ            implicit input; Đuplicate
 Ł           get Łength
  ř          řangify
   π*₂       multiply by pi/2
      š      take šin
       Ɩ     cast to Ɩnteger
        +    add the two arrays element-wise

```
> 0 votes

---
Tags: code-golf, array
---


# Question
Title: Write a Rectangular Program that Outputs the Number of Times it was Rotated
The title says it all. Your goal is to write a program that forms a w×h rectangle of characters that can be rotated and re-run to output the number of 90° Counter-Clockwise (CCW) rotations that have been done.

For example, if the 3×2 program

```
abc
def

```

solved the problem, it would initially output 0, and successive rotations of 90° CCW

```
cf    fed    da
be    cba    eb
ad           fc

```

would output 1, 2, and 3 respectively.

Using comments makes this a trivial task is most languages. In Ruby for example, it can be done in a 7×7 rectangle:

```
###p###
### ###
###1###
p 0#2 p
###3###
### ###
###p###

```

The challenge is to do this **without** any sort of comments.

**Scoring**

Your score is w\*h, the area of your rectangle. Newlines are excluded. In other words, code-golf, newlines not counted.

The score for the Ruby example is 49 (though of course it is invalid since it has comments).

**Notes**

* Your code must really be rectangular with no missing characters at the end of lines.
* If you wish you may output other legal "mod 90°" values instead of 0 1 2 3. So 8 is fine instead of 0, and -1 is fine instead of 3, etc.
* The output may go to the console or into a file.
* Standard loopholes apply.

I hope this, my first question, really intrigues some people. Enjoy!

# Answer
# APL (1x3 = 3)

```
5!3

```

This solution uses the extra rule that any output that is correct mod 4 works.

In APL, `x!y` is the number of way to choose `x` elements from `y`, commonly known as `binom(y,x)` or `choose(y,x)`. Let's check that each rotation gives the right answer.

**0 rotations**

```
5!3

```

There's no way to choose 5 elements from 3, so we get 0, which is automatically printed.

**1 CCW rotation**

```
3
!
5

```

APL happily evaluates each line, getting the number `3`, the operator `!`, and then the number `5`, printing only the last of these (`5`), which is 1 mod 4.

**2 CCW rotations**

```
3!5

```

This is `binom(5,3)`, which is `(5*4*3*2*1)/(3*2*1)/(2*1) = 10`, which is 2 mod 4.

**3 CCW rotations**

```
5
!
3

```

As before, only the last-evaluated value of `3` is printer.

I don't actually know APL, so please tell me if I got any of the explanation wrong. I found it by trial and error as the first language on this site that:

1. Automatically prints the result of an expression
2. Given multiple lines of expressions, only outputs the last one
3. Has no issue with an operator standing alone on a line
4. Takes operators infix
5. Has a single-character arithmetic binary operator that is asymmetric (aRb != bRa), and flexible enough to return a variety of numbers.

For (5), I went down the list of APL dyadic functions. My first candidate operation was the integer division `/` of C and Python 2, but APL division `÷` gives floats. Exponentiation is tempting, but fails because `a` and `a^b` have the same parity but are gotten by consecutive rotations (unless `b=0`, but then `b^a=0`). Boolean operators like `<` give `0` and `1` 180 degrees apart, which doesn't work. Finally, I found the binomial operator `!` and tried numbers until I got some that work.

Thanks to Quincunx for his confidence that there exists a smaller solution than 2x2.
> 48 votes

# Answer
## Ruby, 7×9 (63)

```
 30;p
0||p=p
0|0;p;p
;p;p|p;
p=p ||0
;p   p;
2||p =p
 00;1
     p

```

A bit longer than the other solution, but at least this solution doesn't depend on any implicit printing or rule abuse. For all four rotations, the full code is parsed and other than some short-circuiting, all of it is executed. Surprisingly, there's absolutely no symmetry in the code

This solution relies on the fact that it's still possible to call the `p` function (which is used to print the numbers) even if a variable with the same name has already been defined. For example, something like `p p` calls the function `p` with the variable `p` as argument (thus, printing the value of `p`).

Explanation for some of the common expressions used in the code:

* `p`: As mentioned above, this is either a function call or a variable. When the variable is not defined, this calls the function `p` without arguments, which does nothing and returns `nil`.
* `p p`: Prints the variable `p`.
* `p|x`: When `p` is the function, this is identical to `nil|x`, which returns true/false depending on the value of `x`. If `p` is an integer, it's bitwise or. Either way, this statement has no side effect.
* `p=p||x`: Effectively the same as `p||=x` (conditional assignment) with the advantage of being syntactically valid and a no-op when reversed.

### Symmetric version (9×10 = 90)

```
    p

  0 * 0
  00100
  0||2* p
p *0||0
  00300
  0 * 0

    p

```

This is the shortest symmetric solution (C2 when ignoring the numbers to print) I could come up with.

### Test script

Here's a test script to verify the code above (the `#` at the line ends have been added so that the whitespace doesn't get stripped and are removed before execution):

```
rotate=->s{s.split($/).map{|i|i.chars.reverse}.transpose.map(&:join).join($/)}

s=<<EOD.gsub(?#,"")
 30;p  #
0||p=p #
0|0;p;p#
;p;p|p;#
p=p ||0#
;p   p;#
2||p =p#
 00;1  #
     p #
EOD

puts ">>> 0°"
eval s
puts ">>> 90°"
eval rotate[s]
puts ">>> 180°"
eval rotate[rotate[s]]
puts ">>> 270°"
eval rotate[rotate[rotate[s]]]

```
> 44 votes

# Answer
# Python - 23 x 23 = 529

Ok, this question has already a winner, but there is no Python solution, yet. So I thought about it - heavily! - and found a way to make the bulky `print` command working in any direction without producing errors when parsed from one of the other directions.

The breakthrough was the following line:

```
'"\'';forward_code;"';backward_code;""\'"''

```

While the `forward_code` is executed, the `backward_code` is part of a string and thus not printed. This is exactly the other way around when reading backwards.

So combined with two more directions and fine-tuned to get all quotes matching correctly I end up with the following solution:

```
''"''""''"''"''"'"''""'
"  ""                 "
"  \\                 "
'"\'';print 1;"'""\'"''
'"\''"';3 tnirp;""\'"''
"  ;""                "
"  p'                 "
'  r;                 '
'  i2                 '
"  n                  "
"  tt                 "
'   n                 '
'  4i                 '
"  ;r     .-=<>=-.    "
' \"p    /__----__\   '
"  ';'  |/ (')(') \|  "
"  ""    \   __   /   "
'  ""    .`--__--`.   '
"  \\   /    :|    \  "
'  ''  (_)   :|   (_) '
'  ""    |___:|____|  '
"  ''    |_________|  "
''"''""''"''"''"'"''""'

```

**Edit:** I found a way to deal with all that whitespace. ;)
> 34 votes

# Answer
# GolfScript, 4 (2x2)

```
43
12

```

Prints `4312` which is `0` (mod 4). The rotations print `3241` (1 mod 4), `2134` (2 mod 4), and `1423` (3 mod 4).

Prompted by:

> If you wish you may output other legal "mod 90°" values instead of 0 1 2 3. So 8 is fine instead of 0, and -1 is fine instead of 3, etc.

There are actually many sets of numbers for which this works. I found these with this Python program:

```
def f(a,b,c,d):
    return int("%i%i%i%i"%(a,b,c,d))
for a in range(10):
    for b in range(10):
        for c in range(10):
            for d in range(10):
                candidate = f(a,b,c,d) % 4 == 0
                candidate &= f(b,d,a,c) % 4 == 1
                candidate &= f(d,c,b,a) % 4 == 2
                candidate &= f(c,a,d,b) % 4 == 3
                if candidate:
                    print("%i, %i, %i, %i"%(a,b,c,d))

```

Although the program outputs `0`s (which probably wouldn't work), the valid solutions are of the form

```
ab
cd

```

Where `a∈{4,8}`, `b∈{3,7}`, `c∈{1,5,9}`, `d∈{2,6}`. IE `(a,b,c,d)∈{4,8}×{3,7}×{1,5,9}×{2,6}` which is 24 solutions.
> 33 votes

# Answer
# BASIC, 64

Won't win, but here it is anyway. (Tested in Chipmunk Basic)

```
?0:END:?
:::::::1
D:::::::
N::::::E
E::::::N
:::::::D
3:::::::
?:DNE:2?

```

Note: `?` is shorthand for `PRINT` in various dialects of BASIC. Although there are lots of syntax errors in the code, the `END` statement in the first line prevents them from being seen by the interpreter.
> 25 votes

# Answer
# Pyth, 9 characters (3x3)

```
0 1

3 2

```

In pyth, everything is printed by default, unless it is preceded by a space. Lines after the first line are for user input, and are not evaluated in this program.

Another way to get 9 characters:

```
"0"
3 1
"2"

```

---

# Pyth 1.0.5, 4 characters

While recent changes to pyth have made 2 digit numbers harder to generate (A change that I am considering reverting), older versions of Pyth have easy two digit number generation, which, combined with the implicit printing and the fact that all lines but the first are ignored, gives the following solution:

```
32
41

```

Prints 32,21,14,43.
> 21 votes

# Answer
# Befunge, 16

```
0.@1
@@@.
.@@@
3@.2

```

**Explanation:** Digits from `0` to `9` push the corresponding number onto the stack, `.` pops a value from the stack and prints it as an integer, and `@` ends the program.

(tested here)
> 18 votes

# Answer
# Piet, 49

I made a point only to use yellow and red colors, and to try and make it roughly symmetrical. When rotated, it prints 0, 1, 2 or 3. Exiting the program in Piet is hard, and takes up around half the space in the picture, unfortunately.
> 18 votes

# Answer
# GNU dc, 6 (3x2)

I think this is the shortest answer not to require the "mod 90°" rule-relaxation:

```
3z1
0p2

```

Outputs `0`, `1`, `2` or `3` for each rotation.

For the `0`, `2` and `3` rotations, the `p` simply pops and prints the last number literal to have been pushed to the stack. For the `1` rotation, the `z` pushes the current stack depth (1) to the stack, then the `p` pops and prints it.
> 16 votes

# Answer
# GolfScript, 9 (3x3)

```
0}1
} }
3}2

```

Sort of abusing the rules. The `}` happens to end the program if there is no matching `{`, and the contents of the stack are printed at program end.
> 10 votes

# Answer
## JavaScript, 4

```
03
12

```

When you execute this program (or a rotation of this program) in a javaScript console, only the last line is evaluated and echoed in the console.

So:

```
12 modulo 4 == 0
01 modulo 4 == 1
30 modulo 4 == 2
23 modulo 4 == 3

```

Here are all the similar 2x2 programs that work too:

```
03
12

03
16

03
52

03
56

03
92

03
96

07
12

07
16

07
52

07
56

07
92

07
96

43
12

43
16

43
52

43
56

43
92

43
96

47
12

47
16

47
52

47
56

47
92

47
96

83
12

83
16

83
52

83
56

83
92

83
96

87
12

87
16

87
52

87
56

87
92

87
96

```

In other terms,

```
ab
cd

```

where a is in \[0,4,8\], b is in \[3,7\], c is in \[1,5,9\], and d is in \[2,6\]
> 9 votes

# Answer
# CJam / GolfScript - 3\*3

```
2;3
;7;
1;0

```

The semicolon pops the previous number, thus only the bottom right corner is printed.
> 8 votes

# Answer
# Aheui, 8

```
바몽희뷸
뷷희몽반

```

Since Aheui does not have a letter that pushes 1 onto the stack, I decided to print 0, 5, 2, and 3.

Explanation: 바 and 반 push 0 and 2, respectively, onto the stack and moves the cursor right by one character. 뷸 and 뷷 push 5 and 3, respectively, onto the stack and moves the cursor down by two characters. 몽 pops and prints the number in the stack and moves the cursor up by one character. 희 terminates the program.
> 5 votes

# Answer
## JavaScript

(Entered in browser console, shell or another REPL, so result is printed)

```
1+2
-3-
4+5

```

Should work for any other language with expressions, non-significant newlines and automatic printing of the result.
> 5 votes

# Answer
# Matlab/Octave - ~~144~~ 100

## Golfed: 10 x 10 = 100

```
....d.....
....i.....
....s.....
... p2 ...
disp  1...
...3  psid
... 4p ...
.....s....
.....i....
.....d....

```

## Alternative solution: 15 x 15 = 225

```
.......d.......
.......i.......
.......s.......
...    p    ...
...         ...
...    4    ...
...    .    ...
disp 1...3 psid
...    .    ...
...    2    ...
...         ...
...    p    ...
.......s.......
.......i.......
.......d.......

```
> 5 votes

# Answer
## Perl 5x7 (35)

```
1+p+t+1
-print+
1+i+i+1
+tnirp+
1+t+p+1

```

A bit late to the party. The solitary `-` determines which number is printed.
> 5 votes

# Answer
# Befunge, 12 (6x2)

I Managed to come up with a slight improvement on the existing Befunge answer by making the most of Befunge's two-dimensional nature and having the code path run vertically in two of the orientations.

```
0.@.1v
v3.@.2

```

Try it online: Starting 0, Rotation 1, Rotation 2, Rotation 3.
> 4 votes

# Answer
# JavaScript, 3

```
2
1
4

```

It works... in base 7.

Base 9 version:

```
2
7
0

```

---

**Explanation**

When run interactively, e.g. from a debugging console, the value of the last statement/expression will be output.

*47* = *410**0* (mod *4*)
*4127* = *20510**1* (mod *4*)
*27* = *210**2* (mod *4*)
*2147* = *10910**3* (mod *4*)

Similar solutions could be found for any odd base.
> 3 votes

# Answer
# Marbelous, 7\*14 = 98

```
.. \/ \/ .. ..
.. 31 \\ 32 \/
\/ \\ \/ \\ \/
\/ 30 \\ 33 ..
.. .. \/ \/ ..

```
> 3 votes

# Answer
# brainfuck, 12x10 = 120

Outputs 0, 1, 2, and 3, respectively.

```
++         >
++++++++++++
++++++++++++
++++++++++++
++++++++++++
      .+++++
++++++++++++
++++++ +++++
++++++ +++++
++++++ +++++

```

Try it online!

One turn

Two turns

Three turns
> 3 votes

# Answer
# Argh!/Aargh! (4\*4=16)

What was that about using the right tool for the job? There are no comments (in the language in general).

The entire family of programs (generated in J: `((|.@:|:) ^: (i. 4)) >'hpqh';'q01p';'p32q';'hqph'` or `((|.@:|:) ^: (i. 4)) 4 4 $ 'hpqhq01pp32qhqph'`)

```
hpqh
q01p
p32q
hqph

```

rotated once:

```
hpqh
q12p
p03q
hqph

```

rotated twice:

```
hpqh
q23p
p10q
hqph

```

rotated three times:

```
hpqh
q30p
p21q
hqph

```

To explain this, it might be best to look at an "indented" version (That also works in all rotations):

```
hhpq h
  0  h
q   1p
p3   q
h  2
h qphh

```

This version shows that the program consists of 4 separate parts, one for each individual rotation.

* `h` \- set control flow left
* `p` \- print item in data/code raster below it
* `q` \- quit the program
> 2 votes

# Answer
# Floater \- 9×5=45

Prints 4, 1, 2, or 3 to console.

Note that 'Black' is a valid instruction (NOP), and is syntactic. Without it, it can't find the starting position. Thus, all positions in the rectangle are occupied.
> 2 votes

# Answer
# Triangular, 2x3 =\> 6

```
%%3
i%i

```

Try it online!

A "rectangular triangular program" - we certainly do live in a society.

The base version here prints the top value of the stack (initially 0), then the other two prints are missed due to triangular's execution order.

**Rotation 1**

```
i%
%%
i3

```

Increments the top value to 1, prints, misses the other two print commands.

**Rotation 2**

```
i%i
3%%

```

Increments twice, hits the last print command.

**Rotation 3**

```
3i
%%
%i

```

Pushes 3 onto the stack, hits a print statement, misses the other two.
> 2 votes

# Answer
# Pip, 2x2 = 4

```
tv
oi

```

Try it online!

All four letters are preinitialized variables; whichever one comes last in the program is autoprinted.

* No rotation: `i = 0`
* One rotation: `o = 1`
* Two rotations: `t = 10`
* Three rotations: `v = -1`
> 2 votes

# Answer
# Python, 18x18 = 324

Uses escaping and mixed quotation marks to change how each string is parsed after rotation. Triple quotes allow the literals to span multiple lines and take up less space.

```
"""p         '   "
   r         '   "
   i         '   "
   n'\""",)2(tnirp
'''t          '
   (          \
   3          "
   )          "
   ,          "
   '          ,
   '          )
   '          1
   \          (
   "          t"""
print(0),'''\"n
'   "         i
'   "         r
'   "         p'''

```

Test code (needs to be cleaned up) :

```
with open('./rotpy.py','r') as fh:
    l=list(fh)
    ll=max(len(x)for x in l)
    l=[x[:-1]+' '*(ll-len(x)) for x in l]

def r(l):
    return list(''.join(reversed(z)) for z in zip(*l))

for i in range(4):
    exec('\n'+'\n'.join(l))
    l=r(l)

```
> 2 votes

# Answer
# Element, 2x3 = 6

```
1*
`2
3

```

This is an improvement over the 3x3 naive solution, which has a ``` in the middle with a number on each side. The 0 case, shown above, is the most interesting, since the `*` is used to multiply the 3 by nothing to get 0. Other than that, it's not that complicated.

If you find the space awkward, you can replace it with pretty much any other character, excluding `[]{}`_`.

For reference, here are the other three rotations:

```
case 1
*2
1`3

case 2
 3
2`
*1

case 3
3`1
 2*

```
> 1 votes

# Answer
# Japt, 3 * 1 = 3 bytes

```
5zB

```

Try it online: as-is, rotated once, twice, thrice.

Outputs 0, 5, 2, 11 respectively.

The variable `B` holds the value 11, and `Number.z(other)` is floor division (everyone looked for apparently :p). For multi-line code, the last line is passed to output, which is simply a constant here.

---

## 2 * 2 = 4 bytes

```
2J
1T

```

Try it online: as-is, rotated once, twice, thrice.

Outputs 0, 21, 2, -1 respectively.

`T` holds 0, and `J` holds -1.

The trick is that, if two literals or variables are put side-by-side, a comma is inserted and the output is just the last one.

2 * 2 JS solution works in Japt too.
> 1 votes

# Answer
# MAWP, 2x2 = 4

```
0:
23

```

-2 characters from Bubbler.

The position of the `:` operator determines when things are output, so we can abuse that and position the numbers around it.

Bubbler's modification pops the existing 1 from the stack, saving two bytes. Try it!
> 1 votes

# Answer
# 05AB1E, 4 (2x2) bytes

```
YX
3¾

```

To-the-point approach.

Try it online or verify all four rotations.

**Explanation:**

* `Y` is a variable with default value \\$2\\$
* `X` is a variable with default value \\$1\\$
* `¾` is a counter variable with default value \\$0\\$

So in all four rotations they are all three pushed to the stack, and then output the last integer on the stack is output implicitly as result.

An alternative 2x2 is a port of the *@DLosc*'s Pip answer, where `T` = \\$10\\$ and `®` = \\$-1\\$:

```
TX
®¾

```

Try it online or verify all four rotations.
> 1 votes

# Answer
# Zsh, 36 (6x6)

```
 <<<0
3    <
<    <
<    <
<    1
 2<<<

```

Try it online!.

#### Alternative, (10x10):

```
printf 0 p
         r
3        i
         n
f        t
t        f
n
i        1
r
p 2 ftnirp

```

Exploits the fact that `printf` only prints the first word, if there are no quotes.
> 1 votes

# Answer
# Japt, 2\*2=4 bytes

Outputs `0`, `1`, `2` & `-1`.

```
ÄÄ
JT

```

Test it | Rotated: once, twice, or thrice

Outputs `0-3`.

```
ÄÄ
ÑV

```

Try it

I'm struggling to find anything in the spec that disallows trivial solutions of double, or even single, digit numbers.
> 1 votes

# Answer
# Chip, (2x5) 10

```
b~
+a
~t
e*
 f

```

`*` activates all neighbor elements: north, east, south and west (source)
`~` if not activated from the west, activates the east neighbor (NOT-gate) (never activated here)
`t` terminates execution after printing the current byte
`a` sets the bit `0x01` of the output
`b` sets the bit `0x02` of the output
`e` sets the bit `0x10` of the output
`f` sets the bit `0x20` of the output
`+` if activated by any neighbor, activate all other neighbors (wire)

Chip requires either the `-w` flag (to allow execution without input), or some input in order to run.

Prints `0`, `1`, `2`, or `3` in ASCII. If code points `0x00` to `0x03` are desired, remove the `e` and `f`, then move the space up to fill the gap.
> 0 votes

# Answer
# \>\<\> (Fish), 11 bytes

```
0v1
vnv
3v2

```

Try it

Starts in a corner, pushing whatever the rotated value is. Then gets sent in a infinite downwards loop which will soon crash since the stack is empty.
> 0 votes

# Answer
# Thunno, 4 bytes (2x2)

```
2y
3x

```

(The last one outputs `23` but that's ok because `23 % 4 = 3`)

Port of Kevin Cruijssen's 05AB1E answer.

`x` defaults to `0` and `y` defaults to `1`.
> 0 votes

# Answer
# TI-Basic, 2x2 = 4

```
03
12

```

This is the exact same as this answer, for the same reason.

### 3x3 = 9

```
2:3
:::
1:0

```
> 0 votes

# Answer
# Pyt, 9

```
2ĉ3
ĉĉĉ
1ĉ0

```

Try it online!

The key here is that `ĉ` clears the stack, so for every rotation, only the last number is implicitly printed.
> 0 votes

---
Tags: code-golf, source-layout
---


# Question
Title: Generate recursive "arrays" up to a certain depth
Given a positive integer `n`.

Generate a JSON array (can be a string, or your language's built-in JSON representation as long as we can get valid JSON, (your code does not need to include outputting the string, you can just use the built-in JSON representation)) containing two empty JSON arrays, then, add a set of 2 empty JSON arrays to each existing set of 2 empty JSON arrays up to `n` deep. `n` can be 0 or 1 indexed.

# Rules

1. The shortest code wins the challenge (as this is code-golf).
2. All output JSON must be RFC8259 compliant.

# Examples

```
Input: 0
Output: [[], []]
Input: 1
Output: [[[], []], [[], []]]
Input: 2
Output: [[[[], []], [[], []]], [[[], []], [[], []]]]

```

# Answer
> 3 votes
# Vyxal, 4 bytes

```
›(W:

```

Try it online! One-indexed. Returns a nested list.

```
›    # increment
 (   # repeat for n+1 times (n+1 is popped):
  W  #   wrap stack into single list (initially [])
   : #   duplicate
     # implicit output

```

---

### Vyxal `W`, 3 bytes

```
(W:

```

Try it online!

Here, it repeats `n` times, and before outputting implicitly, the `W` flag wraps the stack into a single list.

# Answer
> 6 votes
# APL (Dyalog Extended), ~~12~~ 6 bytes

−6 thanks to OP now allowing 1-indexing and results that *can* be converted to JSON, rather than the JSON itself.

Full program; prompts for 1-indexed `n` and prints APL nested array equivalent of the required JSON. Adding an print handler which just converts output to JSON shows the required result.

```
⍮⍨⍣⎕⊢⍬

```

Try it online!

empty list (`[]`)

`⍣⎕⊢` on that, apply the following function `n` (prompted-for) number of times:

`⍮⍨` pair up with itself

The print handler:

`Print←{``}` assign a function as follows:

`⎕JSON⍺` convert output array to JSON

`⎕←` print that

Setting up the JSON printing callback on output:

`⎕SE.` for the current session:

`onSessionPrint←` set the event handler for printing to

`Print` call the above handler function

# Answer
> 4 votes
# GNU sed, ~~36~~ 35 bytes

I believe numeric input is allowed to be in unary format for sed. For ex. `3` becomes `@@@` and `0` becomes the empty string (no @s). The nameless label `:` is supported by older versions of sed.

```
s:$:@[]:
:
s:@::
s:\[]:[&, &]:g
/@/b

```

Try it online with sed 4.2.2!

In each loop iteration one character is removed from the unary number as one depth is introduced in the array. A small trick is used in the first line, where the initialization is only `[]` (shorter than `[[], []]`), like a "-1 based indexing". As such the input number is incremented by one with the extra `@`. This helps also with not checking up front for the empty string (input 0).

**EDIT:** with 1-based indexing now allowed, the incrementing from first line isn't needed,thus saving one byte: `s:$:[]:` Thanks to Adám for the heads-up.

# Answer
> 3 votes
# JavaScript (Node.js), ~~25~~ ~~23~~ 22 bytes

*Saved 2 bytes thanks to Arnauld! Saved 1 byte by changing to 1-indexed.*

```
f=n=>n--?[a=f(n),a]:[]

```

Try it online! Arnauld's observation of testing for 1-indexed as `~n--` saves 1 byte over `n--+1`.

Returns an array of arrays, which, when printed, will output JSON compliant arrays.

If a string output is mandatory, then we have, using the same method:

# JavaScript (Node.js), ~~34~~ ~~32~~ ~~31~~ 29 bytes

*Saved 2 bytes thanks to Arnauld! Saved 2 bytes thanks to l4m2! Saved 1 byte by changing to 1-indexed.*

```
f=n=>`[${n--?[a=f(n),a]:[]}]`

```

Try it online!

# Answer
> 3 votes
# sclin, 15 bytes

```
[]"dup ,";1+ *#

```

Try it here! I've been thinking about having code that took input from the next line rather than the previous. Surprisingly useful, gonna have to use it more often...

For testing purposes:

```
[]"dup ,";1+ *# f>o
2

```

## Explanation

Prettified code:

```
[] ( dup , ) ; 1+ *#

```
* `[]` empty list
* `(...) ; 1+ *#` execute (next line) + 1 times...
    + `dup ,` duplicate and pair into list

# Answer
> 3 votes
# TI-Basic, 32 bytes

```
Prompt N
"[]
For(I,0,N
"["+Ans+","+Ans+"]
End
Ans

```

# Answer
> 2 votes
# Retina, 22 bytes

```
K`[]
"$+"+`\[]
[[],[]]

```

Try it online! No test suite due to the way the program uses history. Explanation:

```
K`[]

```

Replace the input with an empty array.

```
"$+"+`

```

Repeat `n` times...

```
\[]
[[],[]]

```

... replace each empty array with a pair of empty arrays.

Previous 0-indexed version was 27 bytes:

```
K`[[],[]]
"$+"+`\[]
[[],[]]

```

Try it online! No test suite due to the way the program uses history. Explanation: Starts with the first pair of empty arrays thus reducing the number of iterations needed by 1.

# Answer
> 2 votes
# \>\<\>, 58 bytes

```
e0i1+:?v"]["oo~.
3[r]40.\"["o:1-20
.","o:1-303[r]40
."]"o~

```

Try it

Offsetting the number by 1 would save 2 bytes, since I can skip the 1+.

## Explanation

Top row: Main function. Check if the recursion level is 0, if so print `[]` and return, else go down.

Second row: print `[`, then recurse.

Third row: print `,` then recurse

Print `]` and return.

# Answer
> 2 votes
# FunStack alpha, 23 bytes

```
Pair self iterate "" At

```

You can try it at Replit. Takes the depth (1-indexed) as a command-line argument and the program on stdin.

### Explanation

At the core of this solution is the following infinite sequence:

```
[]
[[],[]]
[[[],[]],[[],[]]]
...

```

We start with the empty list, and each subsequent element is two copies of the previous element wrapped in a list. `Pair self` does exactly that, and we get the desired infinite list by `iterate`ing that function starting from `""` (empty string / empty list).

This creates a bare value at the left end of the program, so it is appended to the program's argument list. Then `At` takes the first argument as an index into the second argument and returns the corresponding element.

# Answer
> 1 votes
# Charcoal, 11 bytes

```
Ｆ⊕Ｎ≔Ｅ²υυ⭆¹υ

```

Try it online! Link is to verbose version of code. Explanation: Port of Adám's APL answer.

```
Ｆ⊕Ｎ

```

Loop `n+1` times...

```
≔Ｅ²υυ

```

... replace the predefined empty list with a list of two copies of it.

```
⭆¹υ

```

Pretty-print the final list (needed because Charcoal doesn't normally output anything for empty lists).

# Answer
> 1 votes
# Python, 29 bytes

```
g=lambda n:n*[0]and[g(n-1)]*2

```

Attempt This Online!

1-indexed. Returns Python's native array representation.

# Python, 45 bytes

```
g=lambda n:n and f'[{g(n-1)},{g(n-1)}]'or'[]'

```

Attempt This Online!

Returns a string, also 1-indexed. I found three different 45-byte functions for this, so I chose the simplest.

# Answer
> 1 votes
# QuadR, 8+2=10 bytes

Takes `n` as 1-indexed argument on TIO.

```
.+
[&,&]

```

Initial input:

```
[]

```

Try it online!

`.+` match everything (any number of any characters)

`[&,&]` replace with open-bracket, match, comma, match, close-bracket

# Answer
> 1 votes
# 05AB1E, 5 bytes

```
¯IƒD‚

```

Try it online or verify all test cases.

**Explanation:**

```
¯      # Push an empty list: []
 Iƒ    # Loop the input+1 amount of times:
   D   #  Duplicate the current list
    ‚  #  Pair the two lists together
       # (after the loop, output the result implicitly)

```

# Answer
> 1 votes
# PHP, 64 bytes

```
for($a=[],$b=[&$a,&$a];$argn--;)$a=[$a,$a];echo json_encode($b);

```

Try it online!

I thought this solution by reference elegant enough to be posted, I wish we could use a reference to a variable while initializing it, but unfortunately it's not the case. Too bad for the output format, almost a third of the code is lost to formatting..

# Answer
> 1 votes
# , ~~57~~ 53 bytes

*Edit: saved 4 bytes by copying MarcMush's approach*

```
\(n){s="[]";for(i in 1:n)s=paste0("[",s,",",s,"]");s}

```

Returns JSON string.

Attempt This Online!

---

# , ~~41~~ 37 bytes

```
f=\(n,s={})`if`(n,f(n-1,list(s,s)),s)

```

Attempt This Online!

Returns R nested list, which can be converted into a json string.

# Answer
> 1 votes
# Julia 1.0, 21 bytes

```
!x=1:2(x>0).|>_->!~-x

```

Try it online!

returns a nested array

**Explanation**

* `a .|> f` applies `f` on each element of `a`
* when `x=0`, `1:0` is (kinda) an empty list, so the result is an empty list
* when `x>0`, `1:2` acts like a 2-element list, and each element of this list will be `!(x-1)`

# Answer
> 1 votes
# Raku, 21 bytes

```
{(@,{$_,$_}...*)[$_]}

```

Try it online!

# Answer
> 1 votes
# jq, 36 bytes

```
def n:try(.<0//(.-1|[n,n]))+[]//[];n

```

Try it online!

Thanks to ovs for the `try(A//C)+[]//B` hack!

Our recursive function has a base case of `-1`, which yields `[]`. Otherwise, our input is decremented, and `[n,n]` recurses into the function twice.

# Answer
> 1 votes
# Thunno, \\$7\log\_{256}(96)\approx\\$ 5.76 bytes

```
ls{KDZP

```

Attempt This Online!

Port of Kevin Cruijssen's 05AB1E answer.

#### Explanation

```
ls{KDZP  # Implicit input
ls       # Push an empty list and swap
  {K     # Repeat (input) times:
    DZP  #  Duplicate and pair
         # Implicit output

```

# Answer
> 0 votes
## Batch, 76 bytes

```
@set s=[]
@for /l %%i in (0,1,%1)do @call set s=%%s:[]=[[],[]]%%
@echo %s%

```

Explanation: Port of the 1-indexed version of my Retina answer, but looping from `0` to `n` to convert back to 0-indexed. `call set` is needed because otherwise the variable gets expanded before the `for` loop executes.

# Answer
> 0 votes
# Jelly, 9 bytes

```
’ßWƊR‘?;`

```

A recursive, monadic Link that accepts a non-negative integer (0-indexed) and yields the nested list. (Replace  with `¹` to use 1-indexed input.)

**Try it online!**

### How?

```
’ßWƊR‘?;` - Link: integer, n
      ?   - if...
     ‘    - ...condition: increment (i.e. n != -1?)
   Ɗ      - ...then: last three links as a monad - f(n):
’         -    decrement (n) -> n-1
 ß        -    call this Link with n-1
  W       -    wrap that in a list
    R     - ...else: range (n = -1) -> []
        ` - use as both arguments of:
       ;  -   concatenate

```

# Answer
> 0 votes
# Factor, 33 bytes

```
[ { } swap [ dup 2array ] times ]

```

Try it online!

---
Tags: code-golf, array, json
---


title: Products all the way down

text:
# Question
Title: Products all the way down
You are probably familiar with the Cartesian product. It takes two lists and creates a list of all pairs that can be made from an element of the first and an element from the second:

\\$ \left\[1,2\right\] \times \left\[3,4\right\] = \left\[(1,3),(1,4),(2,3),(2,4)\right\] \\$

Here the order of the result is such that the pairs whose first element is earlier in the first list come earlier in the result, and if the first elements come from the same element the pair whose second element comes first is earlier.

Now we can also have a generalized Cartesian product which takes 3 arguments, two lists and a function to combine pairs.

So for example if we wanted to find all ways to add an element of the first list to an element of the second list:

\\$ \mathrm{Cart} : \left((A,B) \rightarrow C, \[A\], \[B\]\right)\rightarrow\[C\]\\ \mathrm{Cart}\left(+,\[1,2\],\[3,4\]\right) = \[4,5,5,6\] \\$

This is the same as taking the regular Cartesian product and then adding up each pair.

Now with this generalized Cartesian product we are going to define the "product all the way down"

\\$ a\otimes b = \mathrm{Cart}\left(\otimes, a,b\right) \\$

This recursive definition is a little bit mind bending. \\$\otimes\\$ takes a ragged list containing nothing but lists all the way down and combines each pair of elements using itself.

Lets work through some examples. The simplest example is \\$\[\space\]\otimes\[\space\]\\$. Since the generalized Cartesian product of an empty list with anything is the empty list it doesn't matter that this is recursive the answer is just \\$\[\space\]\otimes\[\space\] = \[\space\]\\$. There are two elements to combine so there are no ways to combine two elements.

The next example is \\$\[\[\space\]\]\otimes\[\[\space\]\]\\$, here we have some elements. The regular Cartesian product of these is \\$\[(\[\space\],\[\space\])\]\\$, we already know how to combine \\$\[\space\]\\$ with \\$\[\space\]\\$ so we can do that. Our result is \\$\[\[\space\]\]\\$.

Ok Let's do \\$\[\[\space\],\[\[\space\]\]\]\otimes\[\[\[\space\]\]\]\\$. First we take the Cartesian product,

\\$ \[(\[\space\],\[\[\space\]\]),(\[\[\space\]\],\[\[\space\]\])\] \\$

Then we combine each with \\$\otimes\\$:

\\$ \begin{array}{ll} \[\[\space\]\otimes\[\[\space\]\],&\[\[\space\]\]\otimes\[\[\space\]\]\] \\ \[\[\space\],&\[\[\space\]\]\otimes\[\[\space\]\]\] \\ \[\[\space\],&\[\[\space\]\otimes\[\space\]\]\] \\ \[\[\space\],&\[\[\space\]\]\] \\ \end{array} \\$

## Task

Your task is to take two finite-depth ragged lists and return their "product all the way down".

Answers will be scored in bytes with the goal being to minimize the size of the source code.

## Test cases

If you are having difficulty understanding please ask rather than try to infer the rules from test cases.

```
[] [] -> []
[[]] [[]] -> [[]]
[[],[[]]] [[[]]] -> [[],[[]]]
[[[[]]]] [] -> []
[[],[[]],[]] [[],[[]]] -> [[],[],[],[[]],[],[]]

```

# Answer
# APL (Dyalog Unicode), 17 bytes

Anonymous infix lambda.

```
{0∊≢¨⍺⍵:⍬⋄,⍵∘.∇⍺}

```

Try it online!

`{``}` "dfn"; left argument is  and right argument is :

`0∊` Is zero a member of…
`≢¨` the length of each of…
`⍺⍵` the arguments?
`:⍬` If so, return the empty list.

Otherwise,…
`,` ravel (flatten)…
`⍵∘.∇⍺` the Cartesian self-product of the reversed arguments.
> 4 votes

# Answer
# Python, 42 bytes

```
f=lambda X,Y:[f(x,y)for x in X for y in Y]
```

Attempt This Online!

The obvious.
> 3 votes

# Answer
# Wolfram Language (Mathematica), 13 bytes

```
#0/@Tuples@#&

```

Try it online!

Takes input as a list of two ragged lists.
> 3 votes

# Answer
# Vyxal, 4 bytes

```
λΠvx

```

Try it Online!

Port of Jonathan Allan's Jelly answer.

#### Explanation

```
λ    # Start a lambda function
 Π   # Cartesian product
  v  # For each inner list:
   x #  Do a recursive call

```
> 2 votes

# Answer
# 05AB1E, ~~19~~ 11 bytes

```
"`â®δ.V"©.V

```

Input as a pair of ragged lists.

Try it online or verify all test cases.

**Explanation:**

```
"..."    # Recursive string as defined below
     ©   # Store this string in variable `®`
      .V # Execute it as 05AB1E code, using the (implicit) input as argument
         # (after which the result is output implicitly)

`        # Push both lists in the pair separated to the stack
 â       # Take the cartesian product of these two lists
   δ     # Map over each inner pair of lists:
  ® .V   # Execute `®` as 05AB1E code, doing a recursive call

```

If only 05AB1E had a recursive function builtin..
> 1 votes

# Answer
# Jelly, 4 bytes

```
Œpß€

```

A monadic link accepting a list of the two ragged lists that yields their product-all-the-way-down.

**Try it online!**
Or see the test-suite (The footer parses and reformats like the question for ease of comparison)

### How?

```
Œpß€ - Link, "f": list of lists (initially the two inputs), A:
Œp   - Cartesian product of A's items
   € - for each resulting list, a:
  ß  -   call this Link - i.e. f(a)

```
> 1 votes

# Answer
# Charcoal, 34 bytes

```
⊞υＡＦυ«≔⊟ιηＦ⊟ιＦＥη⟦κλ⟧«⊞ιλ⊞υλ»»⭆¹§υ⁰

```

Try it online! Link is to verbose version of code. Takes input as a list of two ragged lists. Explanation:

```
⊞υＡ

```

Push the list of two ragged lists to the predefined empty list.

```
Ｆυ«

```

Loop over all the lists of ragged lists.

```
≔⊟ιη

```

Remove the second ragged list from the list.

```
Ｆ⊟ιＦＥη⟦κλ⟧«

```

Remove the first ragged list from the list and loop over the Cartesian product of the lists.

```
⊞ιλ⊞υλ

```

Push each new list of two ragged lists to the ragged list being processed and also to the predefined empty list so that it will be "recursively" processed.

```
»»⭆¹§υ⁰

```

Pretty-print the resulting ragged list. (The default output for a ragged list is blank, so I don't have much choice here.)
> 1 votes

# Answer
# Thunno, \\$ 15 \log\_{256}(96) \approx \\$ 12.35 bytes

```
Y"yzSeYxAv"AxAv

```

Attempt This Online!

Port of Kevin Cruijssen's 05AB1E answer.

#### Explanation

```
Y"yzSeYxAv"AxAv  # Implicit input
Y                # Store it in y for later
 "yzSeYxAv"Ax    # Store the recursive string in x:
  yzS            #  Get the cartesian product of the elements of y
     e           #  Map:
      Y          #   Store the list in y
       xAv       #   And execute x as Thunno code
             Av  # Execute x as Thunno code
                 # Implicit output

```
> 1 votes

# Answer
# Ruby, 28 bytes

```
f=->a,b{a.product(b).map &f}

```

Try it online!

Recursive by definition.
> 0 votes

# Answer
# JavaScript, 33 bytes

```
f=A=>B=>A.flatMap(a=>B.map(f(a)))

```

Try it online!

Use as `f(A)(B)`, as permitted here.
> 0 votes

# Answer
# jq, 24 bytes

```
def f:[combinations|f];f

```

Try it online!
> 0 votes

---
Tags: code-golf, math, ragged-list
---


title: Even and Odd kinds

text:
# Question
Title: Even and Odd kinds
Let \\$n\\$ be some positive integer. We say that \\$n\\$ is of *even kind* if the prime factorisation of \\$n\\$ (counting duplicates) has an even number of integers. For example, \\$6 = 2 \times 3\\$ is of even kind. Likewise, we say \\$n\\$ is of *odd kind* of the prime factorisation of \\$n\\$ has an odd number of integers, such as \\$18 = 2 \times 3 \times 3\\$. Note that as the prime factorisation of \\$1\\$ contains \\$0\\$ primes, it is of *even kind*.

Let \\$E(n)\\$ be the count of positive integers of even kind less than or equal to \\$n\\$, and \\$O(n)\\$ be the count of positive integers of odd kind less than or equal to \\$n\\$. For example, for \\$n = 14\\$, we have

* \\$E(14) = 6\\$ (\\$1, 4, 6, 9, 10, 14\\$), and
* \\$O(14) = 8\\$ (\\$2, 3, 5, 7, 8, 11, 12, 13\\$)

---

You are to write a program which takes some positive integer \\$n \ge 1\\$ as input, and outputs the two values \\$E(n)\\$ and \\$O(n)\\$. You may input and output in any convenient method, and you may output the two outputs in any format that consistently presents the values (e.g. you cannot output one in unary and another in decimal), and that clearly distinguishes between the two (typically, has some kind of obvious delimiter).

This is a challenge, so the shortest code in bytes wins.

### Test cases

```
n -> [E(n), O(n)]
1 -> [1, 0]
2 -> [1, 1]
3 -> [1, 2]
4 -> [2, 2]
5 -> [2, 3]
6 -> [3, 3]
7 -> [3, 4]
8 -> [3, 5]
9 -> [4, 5]
10 -> [5, 5]
11 -> [5, 6]
12 -> [5, 7]
13 -> [5, 8]
14 -> [6, 8]
15 -> [7, 8]
16 -> [8, 8]
17 -> [8, 9]
18 -> [8, 10]
19 -> [8, 11]
20 -> [8, 12]

```

# Answer
# , 19 bytes

```
(-,])1#.2|1#@q:@+i.

```

Try it online!

* `1...+i.` 1 2 ... n
* `#@q:` Length `#` of prime factors `q:` of each
* `1#.2|` Sum of even lengths
* `(-,])` Input minus that sum `-` catted with `,` that sum `]`
> 6 votes

# Answer
# Jelly, 8 bytes

```
RÆE§ḂSṄạ

```

Try it online!

```
RÆE§ḂSṄạ
R         - Range [1, input]
 ÆE       - For each, get a list of the prime exponents
   §      - Sum each
    Ḃ     - Modulo each by 2
     S    - Sum
      Ṅ   - Print (with a trailing newline)
       ạ  - Get the absolute difference between this and the input (also implicitly printed)

```
> 5 votes

# Answer
# PARI/GP, 31 bytes

```
n->sum(i=1,n,I^(bigomega(i)%2))

```

Attempt This Online!

Outputs a complex number where the real part is \\$E(n)\\$ and the imaginary part is \\$O(n)\\$.
> 4 votes

# Answer
# JavaScript (ES6), 71 bytes

```
f=(n,a=[0,0])=>n?f(n-1,a,a[(g=_=>k>n?0:n%k?g(k++):1^g(n/=k))(k=2)]++):a

```

Try it online!

### Commented

```
f = (                 // f is a recursive function taking:
  n,                  //   n = input
  a = [0, 0]          //   a[] = output array
) =>                  //
n ?                   // if n is not equal to 0:
  f(                  //   do a recursive call:
    n - 1,            //     decrement n
    a,                //     pass a[]
    a[                //     update a[]:
      ( g =           //       g is a recursive function
        _ =>          //       which ignores its parameter
        k > n ?       //       if k is greater than n:
          0           //         stop the recursion
        :             //       else:
          n % k ?     //         if k is not a divisor of n:
            g(k++)    //           increment k and do a recursive call
          :           //         else:
            1 ^       //           invert the result
            g(n /= k) //           divide n by k and do a recursive call
      )(k = 2)        //       initial call to g, starting with k = 2
    ]++               //     increment a[0] or a[1], depending on the
                      //     parity of the number of prime divisors of n
  )                   //   end of recursive call
:                     // else:
  a                   //   return a[]

```
> 4 votes

# Answer
# 05AB1E, ~~8~~ 7 bytes

```
LÓOÉ1Ý¢

```

Try it online or verify all test cases.

**Explanation:**

-1 byte by realizing that: amount of prime factors of \\$x\\$ == sum(exponents of \\$x\\$'s prime factorization): see that they are the same here.

```
L        # Push a list in the range [1, (implicit) input]
 Ò       # Get the prime exponents of each inner integer
  O      # Sum each inner list together
   É     # Check for each sum whether it's odd
    1Ý   # Push pair [0,1]
      ¢  # Count the occurrences of 0 and 1 in the list
         # (after which the result is output implicitly)

```
> 4 votes

# Answer
# Desmos, ~~101~~ 97 bytes

```
f(K)=∑_{k=1}^Kmod([1,0]+∑_{n=2}^klog_n(gcd(n^{ceil(log_nk)},k))sign(∏_{a=3}^nmod(n,a-1)),2)

```

Output is the list \\$\[E(n),O(n)\]\\$. It will fail on larger values due to floating point inaccuracies, but I've tested values such as \\$1000\\$ and it gives the right output, so it's pretty much a nonissue.

Try It On Desmos!

Try It On Desmos! - Prettified

A shorter version of the above code technically works, but it fails for values greater than \\$15\\$ due to floating point errors (so it doesn't even pass all the test cases):

### ~~88~~ 84 bytes

```
f(K)=∑_{k=1}^Kmod([1,0]+∑_{n=2}^klog_n(gcd(n^k,k))sign(∏_{a=3}^nmod(n,a-1)),2)

```

Try It On Desmos!

Try It On Desmos! - Prettified
> 4 votes

# Answer
# Vyxal `o`, 8 bytes

```
ɾǐvL∷∑…ε

```

Try it Online!
> 3 votes

# Answer
# Ruby, ~~72~~ 66 bytes

-6 bytes thanks to Dingus

```
->n{[e=(1..n).map{|m|m.prime_division.sum{_2}}.count{_1%2<1},n-e]}

```

Attempt This Online!
> 3 votes

# Answer
# Vyxal, 8 bytes

```
'ǐ₂;L~ε"

```

Try it Online!

A flagless 8 byter that uses a method that is a little different to the other answer.

7 bytes using this approach with a flag:

## Vyxal `o`, 7 bytes

```
'ǐ₂;L…ε

```

Try it Online!
> 3 votes

# Answer
# Factor \+ `math.primes.factors`, ~~58~~ 50 bytes

```
[ dup [1,b] [ factors length odd? ] count tuck - ]

```

Try it online!

* `dup` Create an extra copy of the input.
* `[1,b]` Create a range from one to the input (inclusive).
* `[ ... ] count` Count the number of elements in the range for which `[ ... ]` returns true.
* `factors length odd?` Does it have an odd number of factors?
* `tuck -` Subtract the result from the input non-destructively. (Implicit multiple return)
> 3 votes

# Answer
# Japt, 12 bytes

Had to sacrifice 2 bytes to handle `1` :\

```
2Æõk è_Ê¤Ì¦X

```

Try it

```
2Æõk è_Ê¤Ì¦X     :Implicit input of integer U
2Æ               :Map each X in the range [0,2)
  õ              :  Range [1,U]
   k             :  Prime factors of each
     è           :  Count the elements that return true
      _          :  When passed through the following function
       Ê         :    Length
        ¤        :    To binary string
         Ì       :    Last character
          ¦X     :    Not equal to X?

```
> 3 votes

# Answer
# Mathematica, 40 bytes

```
Length/@PrimeOmega@Range@#~GroupBy~OddQ&

```

View it on Wolfram Cloud!

Output in the form `<|False->E(n),True->O(n)|>`.
> 2 votes

# Answer
# , 79 bytes

```
\(n)c(y<-sum(sapply(1:n,f<-\(n,p=2)sum(x<-!n%%p,if(n>1)f(n/p^x,p+!x))%%2)),n-y)

```

Attempt This Online!

Returns O(n), E(n).

Helper function `f` returns the number of prime factors, `f%%2` returns whether-or-not this is odd: `f<-\(n,p=2)sum(x<-!n%%p,if(n>1)f(n/p^x,p+!x))`
> 2 votes

# Answer
# Retina 0.8.2, 63 bytes

```
.+
$*
M!&`.+
+%`^(2*(1+))\2+$
2$1
22|¶

O`2?1
(1)+(21)*
$#1 $#2

```

Try it online! Link is to test suite that outputs the results for `1..n`. Explanation:

```
.+
$*

```

Convert to unary.

```
M!&`.+

```

List all the numbers from `n` down to `1`.

```
+%`^(2*(1+))\2+$
2$1

```

Count the number of prime factors of each number, using repeated `2`s as the count. This leaves a lone trailing `1` once all of the prime factors have been counted.

```
22|¶

```

Take the parity of the counts of prime factors, so that `1` means that it had an even number and `21` means that it had an odd number, and join all of the results together.

```
O`2?1

```

Sort the `1`s and `21`s separately to make them easier to count.

```
(1)+(21)*
$#1 $#2

```

Count the number of `1`s and `21`s.
> 2 votes

# Answer
# GeoGebra, 66 bytes

```
InputBox(n
a=Sum(Zip(Mod(Length(PrimeFactors(a)),2),a,1...n
ai+n-a

```

Try It On GeoGebra!

Output is in the form \\$E(n)+O(n)i\\$.
> 2 votes

# Answer
# \[Julia 1.1\], 92 bytes

```
using Primes
~N=(X=map(n->sum([b for (a,b)=factor(n)]),1:N);[sum(X.%2 .==0),sum(isodd.(X))])

```

Julia 1.0 appears to be supported by the package Primes.jl, but I haven't been able to import it successfully. Here is the output in Julia 1.1:

```
julia> VERSION
v"1.1.1"

julia> using Primes

julia> ~N=(X=map(n->sum([b for (a,b)=factor(n)]),1:N);[sum(X.%2 .==0),sum(isodd.(X))])
~ (generic function with 1 method)

julia> map(x -> println(lpad(x,2) * " -> $(~x)"), 1:20);
 1 -> [1, 0]
 2 -> [1, 1]
 3 -> [1, 2]
 4 -> [2, 2]
 5 -> [2, 3]
 6 -> [3, 3]
 7 -> [3, 4]
 8 -> [3, 5]
 9 -> [4, 5]
10 -> [5, 5]
11 -> [5, 6]
12 -> [5, 7]
13 -> [5, 8]
14 -> [6, 8]
15 -> [7, 8]
16 -> [8, 8]
17 -> [8, 9]
18 -> [8, 10]
19 -> [8, 11]
20 -> [8, 12]

```

This solution could be adapted without `Primes` in Julia 0.4, when `factor` was still part of base Julia.
> 2 votes

# Answer
# Pyth, 10 bytes

```
aBsm.&1lPh

```

Try it online!

Outputs `[O(n), E(n)]`.

### Explanation

```
aB            bifurcate the absolute difference of implicit eval(input()) and
  s           the sum of
   m          map over implicit range(eval(input()))
    .&1       modulo 2 (bitwise and 1)
       l      the length of
        P     the list of the prime factors of
         h    1 + implicit map lambda variable

```
> 2 votes

# Answer
# Brachylog, 15 bytes

```
⟦₁{ḋl%₂}ᵍlᵐĊ|;0

```

Try it online!

### Explanation

4 additional bytes needed at the end to deal with the special case of `1`.

```
⟦₁                  Range [1, ..., Input]
  {    }ᵍ           Group by:
   ḋl%₂                 Length of prime decomposition mod 2
         lᵐ         Map length
            Ċ|;0    Output must have 2 elements; otherwise (Input = 1), Output = [Input, 0]

```
> 1 votes

# Answer
# Charcoal, 40 bytes

```
Ｆ…·¹Ｎ«≔⁰θＷΦι¬﹪ι⁺²λ«≧÷⁺²⌊κι≦¬θ»⊞υθ»ＩＥ²№υι

```

Try it online! Link is to verbose version of code. Explanation:

```
Ｆ…·¹Ｎ«

```

Loop from `1` up to and including `n`.

```
≔⁰θ

```

Assume even kind.

```
ＷΦι¬﹪ι⁺²λ«

```

While the current value has any nontrivial factors: ...

```
≧÷⁺²⌊κι

```

... divide it by the lowest such factor, and...

```
≦¬θ

```

... flip between even and odd kind.

```
»⊞υθ

```

Save the kindness of the current value.

```
»ＩＥ²№υι

```

Output the counts of even and odd kindness.
> 1 votes

# Answer
# Ohm v2, 11 bytes

```
@€olé;ΣD³a«

```

Try it online!

Returns a list of `[E(n), O(n)]`. Note that Ohm v2 formats numbers a little weirdly when they are in a list, but they are definitely the right numbers.

## Explained

```
@€olé;ΣD³a«
@            # Push a range from 1 to the input to the stack
 €   ;       # To each item in the range from before:
  ol         # Get the length of the full prime factorization of the item
    é        # and then push whether the length is even
      ΣD     # Push two copies of the sum of that list - the first copy is how many numbers are E(n), and the second will be used to calculate how many numbers are O(n)
        ³a   # Get the absolute difference of the input and the E(n) count
          «  # Pair into a list

```
> 1 votes

# Answer
# Arturo, 52 bytes

```
$[n][x:∑map 1..n=>[%size factors.prime&2]@[n-x,x]]

```

Try it
> 1 votes

# Answer
# Thunno, \\$ 13 \log\_{256}(96) \approx \\$ 10.70 bytes

```
R1+Zh.S2%10dc

```

Attempt This Online! Port of Kevin Cruijssen's 05AB1E answer.

### Thunno, \\$ 16 \log\_{256}(96) \approx \\$ 13.17 bytes

```
DR1+Zh.S2%SDZKAD

```

Attempt This Online! Port of Steffan's Jelly answer.

#### Explanations

```
R1+Zh.S2%10dc  # Implicit input
R1+            # Push range(1, input + 1)
   Zh          # Prime factor exponents
     .S2%      # Sum mod 2 of each
         10dc  # Count 1s and 0s

```

```
DR1+Zh.S2%SDZKAD  # Implicit input
DR1+              # Duplicate and push range(1, input + 1)
    Zh            # Prime factor exponents
      .S2%        # Sum mod 2 of each
          SDZK    # Sum and print without popping
              AD  # Absolute difference with input

```
> 1 votes

---
Tags: code-golf, sequence, number-theory, primes
---


title: Infinitely many ℕ

text:
# Question
Title: Infinitely many ℕ
# Background:

A sequence of infinite naturals is a sequence that contains every natural number infinitely many times.

To clarify, **every number must be printed multiple times!**

# The Challenge:

Output a sequence of infinite naturals with the shortest code.

# Rules:

1. Each number must be separated by a (finite) amount of visible, whitespace or new line characters that aren't a digit.
2. The program cannot terminate (unless you somehow wrote all numbers).
3. Any way of writing such a sequence is acceptable.

# Examples:

```
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
...

```

`1, 1, 2, 1, 2, 3, 1, 2, 3, 4...`

Notice that we write all naturals from 1 to N for all N ∈ ℕ.

Feedback and edits to the question are welcome. Inspired by my Calculus exam.

# Answer
> 3 votes
## Arm Thumb (with libc calls), 34 bytes

Raw machine code

`f7ff fffe` is for libc calls which haven't been linked yet.

Needs to be loaded at an address that is **not** a multiple of 4, due to alignment requirements. Yes, it is counterintuitive, but it will make sense later.

```
2400 a707 3401 2501 0038 0029 f7ff fffe
3501 42a5 d9f8 200a f7ff fffe e7f2 7525
0020

```

Uncommented Assembly

```
        .thumb
        .globl main
        .thumb_func
main:
        movs    r4, #0
        adr     r7, str
.Lloop1:
        adds    r4, #1
        movs    r5, #1
.Lloop2:
        movs    r0, r7
        movs    r1, r5
        bl      printf
        adds    r5, #1
        cmp     r5, r4
        bls     .Lloop2
.Lloop2_end:
        movs    r0, #'\n'
        bl      putchar
        b       .Lloop1
str:
        .asciz "%u "

```

### Explanation

Equivalent C code:

```
#include <stdio.h>
#include <stdint.h>
int main(void)
{
    uint32_t N = 0;
    for (;;) {
        ++N;
        for (uint32_t num = 1; num <= N; num++) {
            printf("%u ", num);
        }
        putchar('\n');
    }
    // Unreachable
}

```

Since we are never returning from `main`, I say, "to hell with calling convention" and just overwrite the callee-saved registers with our local variables. They won't know the difference.

Specifically, I want r4 to be N (it is incremented before using), and r7 to be our printf string.

Unfortunately, we have an odd number of instructions, and `adr` can only load addresses that are 4 byte aligned, so we need to make `main` *not* be 4-byte aligned so the string *is* 4-byte aligned.

```
main:
        movs    r4, #0
        adr     r7, str

```

Begin printing the natural numbers. Increment N and start counting ℕ in r5.

```
.Lloop1:
        adds    r4, #1
        movs    r5, #1

```

`printf("%u ", ℕ)`

```
.Lloop2:
        movs    r0, r7
        movs    r1, r5
        bl      printf

```

Increment ℕ and loop while it is less than or equal to N.

```
        adds    r5, #1
        cmp     r5, r4
        bls     .Lloop2

```

After the second loop: `putchar('\n')`

```
.Lloop2_end:
        movs    r0, #'\n'
        bl      putchar

```

Jump back to the outer loop to increment N.

```
        b       .Lloop1

```

The printf string. This must be 4-byte aligned for `adr`, which we do with how we load `main`.

```
str:
        .asciz "%u "

```

# Answer
> 26 votes
# Scratch 3.0, ~~13~~ 20 blocks/~~121~~ 70 bytes

As SB Syntax:

```
define(n)(i
say(i
((n)+<(i)=(n)>)((1)+((i)*<(i)<(n

```

This says each term in the sequence. A delay can be added so that the numbers don't rapidly fire.

I have never seen scratch so abused. You call the *empty name* function with *empty parameters*. My goodness. Whatever saves bytes!

*-51 thanks to @att*

Try it on Scratch

## Explained

The main idea behind this program is that each "run" of natural numbers is printed until the value being printed is equal to the highest number of that run.

The first two lines of the function are pretty straightforward...define a function with parameters `n` (the upper limit of the current run of numbers) and `i` (the current number for printing), then output the value of `i`.

Then, we get to the fun part - the function call. The expression `n + (i = n)` determines if we need to move onto the next `n`: if `i` hasn't reached the upper limit, the expression evaluates as `n`. Otherwise, the expression is `n + 1`, giving us the next upper limit.

The expression `1 + (i * (i < n))` determines the next value of i. To properly understand this, consider the two different results `i < n` can evaluate to: if `i` is equal to `n` (that is, we have reached the upper limit of the current run and we need to consequently restart at 1), this will result in `(1 + (i * 0))`, which will always equal 1. However, if `i` is less than `n`, the expression will equal `(1 + (i * 1)) = (1 + i)` , which just happens to be the next value to print. Because there is no checks to see if execution should be halted, this goes on forever.

# Answer
> 19 votes
# Husk, 2 bytes

```
ḣN

```

Try it online!

First Husk answer! Also uses the sequence in the question

## How it works

```
ḣN - Main program
 N - The infinite list [1, 2, 3, ...]
ḣ  - Prefixes; [[1], [1, 2], [1, 2, 3], ...]

```

# Answer
> 15 votes
# 05AB1E, 2 bytes

```
∞L

```

Try it online! The footer formats the output like the example from the post.

pushes a list of all natural numbers, `L` takes the range `[1 .. n]` for each number.

# Answer
> 13 votes
# , ~~26~~ ~~25~~ 24 bytes

-1 byte thanks to Dominic van Essen

```
repeat cat(rpois(9,9)+1)

```

Try it online!

Outputs a random infinite sequence of integers, drawn from the \\$Poisson(9)\\$ distribution (+1 to avoid outputting any 0s). They are output in batches of 9 at a time, for more "efficiency". Any positive value of the mean would work; using a mean of 9 maximizes the variance for 1-character numbers.

All numbers appear infinitely often in the sense that for any integer \\$k\\$, the expected number of occurences of \\$k\\$ in the first \\$n\\$ realizations goes to \\$\infty\\$ as \\$n\to\infty\\$:

$$E\left\[\sum\_{i=1}^n\mathbb{I}\_{X\_i=k}\right\]\xrightarrow\[n\to\infty\]{}\infty.$$

The calls to `cat` mean that there integers within one batch of 9 are separated by spaces, but there is no separator between batches. The vast majority of 3- and 4-digit numbers in the output are due to this artefact, but there is a theoretical guarantee that such numbers (and larger numbers) will be output eventually, at least if we assume that the underlying random number generator is perfect.

---

For a larger variance, we can follow Giuseppe's suggestion for the same byte count:

```
repeat cat(1%/%runif(9))

```

Try it online!

This induces more `1`s and more large numbers (including some very large numbers thanks to the `cat` artefact). Again, number of occurrences of any integer goes to infinity when the size of the output goes to infinity.

---

Two other R answers come out shorter, using deterministic methods: Giuseppe's and Dominic van Essen's

# Answer
> 13 votes
# Python 2, 31 bytes

```
R=1,
while 1:print R;R+=len(R),

```

Try it online!

Thanks to @Danis for saving a byte here over `R+=R[-1]+1,`. This

Prints:

```
(1,)
(1, 1)
(1, 1, 2)
(1, 1, 2, 3)
(1, 1, 2, 3, 4)
(1, 1, 2, 3, 4, 5)
    ...

```

Accumulates a list of number from 1 to n (except 1 appears twice) each time appending the last element plus one.

**32 bytes**

```
R=[1]
for x in R:print R;R+=x+1,

```

Try it online!

---

# Python 2, 30 bytes (conjectured)

```
n=2
while 1:print~-2**n%n;n+=1

```

Try it online!

The sequence of \\$2^n \bmod n\\$ (A015910) is conjectured to take on all values \\$k \geq 0\\$ except \\$k=1\\$. I don't know if it's also conjectured that each value appears infinitely many times, but it seems consistent with known solutions for specific values.

We instead compute \\$(2^n-1) \bmod n\\$, which makes \\$0\\$ rather than \\$1\\$ be the only missing value (if the conjecture holds).

Looking at the output, you might think that \\$2\\$ is never output, but it in fact does appear first for \\$n=4700063497\\$ and for progressively higher values in A050259.

---

# Python 2, 33 bytes

```
R=[1]
for x in R:print x;R+=x+1,1

```

Try it online!

This is longer, but it's pretty nifty, printing the ABACABA sequence.

# Answer
> 10 votes
# Haskell, 17 bytes

```
[[1..x]|x<-[1..]]

```

Try it online!

Since the challenge seems to allow non-flat output, we can simply generate a list of the lists `[1],[1,2],[1,2,3,],...`, as suggested by @AZTECCO.

**Haskell, 19 bytes**

```
l=1:do x<-l;[x+1,1]

```

Try it online!

A recursively-defined infinite flat list with the ABACABA sequence `1,2,1,3,1,2,1,4,...` (A001511).

A same-length variant:

```
l=(:[1]).succ=<<0:l

```

Try it online!

**20 bytes**

```
l=do x<-[1..];[1..x]

```

Try it online!

Counting up `1,1,2,1,2,3,1,2,3,4,...`, but as a flat list.

# Answer
> 8 votes
# , 21 bytes

*(also near-simultaneously identified by Robin Ryder)*

```
while(T<-T+1)cat(T:0)

```

Try it online!

Similar to the example sequence, but each sub-series is reversed, and the initial value in each subseries is represented with an initial zero (so, `03` for 3, for instance).

If you don't like the initial zeros, then look at the previous version using `show` (below), or at Giuseppe's answer.

---

# , ~~23~~ 22 bytes

*Edit: -1 byte thanks to Robin Ryder*

```
while(T<-T+1)show(1:T)

```

Try it online!

Outputs the sequence used in the example, plus an additional infinite number of copies of the number `1`.
Each number is separated by either a space "" , a newline plus bracket, "`\n[`", or a bracket plus space "`[` ".

2-bytes golfier (at time of posting, at least...) than the other two  answers...

# Answer
> 7 votes
# Bash \+ GNU Coreutils, 20

```
seq -fseq\ %g inf|sh

```

Try it online! \- Times out after 60 seconds.

# Answer
> 7 votes
# Bash, 20 bytes

```
seq inf|xargs -l seq

```

Try it online!

# Answer
> 6 votes
# sed 4.2.2, 20

```
:;s/(1*).*/1\1 &/p;b

```

Try it online!

Output is in unary, as per this meta consensus.

# Answer
> 6 votes
# Befunge, 5 bytes

```
>1+?.

```

Try it online!

At each output, there is a 50% chance the current number will be printed and reset to 1, and a 50% chance that `2` will be printed and the current number will increase by some random odd number (following an exponential distribution). This can happen multiple times, so odd numbers can be outputted as well.

Every natural number has a nonzero probability of occurring, so it will eventually be printed infinitely many times.

### Explanation

```
>1+?.
>      # Go east.
 1+    # Initialize a counter to 1.
   ?   # Go in a random direction.
       # If the instruction pointer goes west:
  +    # Add the top two stack elements together.
       # If there is a 2 on top, this adds it to the counter.
       # If not, this does nothing.
 1     # Create a new 1 on the top of the stack.
>      # Go east.
 1+    # Add 1 to get 2, which remains on top of the counter.
   ?   # Repeat.

   ?   # If the IP goes east:
    .  # Print and delete the top of the stack.
>      # Go east.
 1+    # Add 1.
       # If there was a 2 that was printed and the counter remains, the 1 gets added to it.
       # If the counter was printed instead, this creates a new 1.
   ?   # Repeat.

   ?   # If the IP goes north or south, it wraps around to the ? instruction and repeats.

```

---

# Befunge-98, 14 bytes

```
]:.1-:0`j
]:+!

```

Try it online!

A determinstic solution, printing each range from 1 to `n` in descending order.

### Explanation

```
]           # Turn right (to the south) and go to the second line.

]:+!
]           # Turn right again (to the west).
   !        # Take the logical NOT of the secondary counter (which is now 0) to get 1.
  +         # Add the 1 to the main counter.
 :          # Duplicate the main counter to form a secondary counter.
]           # Turn right (to the north) and go to the first line.

]:.1-:0`j
]           # Turn right (to the east).
 :          # Duplicate the secondary counter.
  .         # Print and delete the duplicate.
   1-       # Subtract 1 from the secondary counter.
     0`     # Is the secondary counter greater than 0?
       j    # If so, jump over the ] instruction and repeat the first line.
]           # If not, turn right (to the south) and go to the second line.

```

# Answer
> 6 votes
# convey, 27 bytes

```
   >v
1","@"}
^+^<#-1
1+<<<

```

Try it online!

This counts down from successive numbers.

# Answer
> 5 votes
# Jelly, 4 bytes

```
‘RṄß

```

Try it online!

I think this outputs all numbers an infinite number of times, but because it's a different output format, I'm not 100% sure

## How it works

```
‘RṄß - Main link. Left argument is initially n = 0
‘    - Increment
 R   - Range
  Ṅ  - Print
   ß - Recursively run the main link

```

For `n = 0`, `‘RṄ` outputs `[1]`. We then recurse, using `n = [1]`. `‘RṄ` then outputs `[[1, 2]]`, and we recurse again, using `n = [[1, 2]]`, which outputs `[[[1, 2], [1, 2, 3]]]` etc.

# Answer
> 5 votes
# Octave, ~~29~~ 28 bytes

```
do disp(fix(1/rand)) until 0

```

**Try it online!**

This outputs a sequence \\$(x\_k)\\$ of independent, identically distributed random natural numbers. Each value \\$x\_k\\$ is obtained as \\$1/r\\$ rounded towards zero, where \\$r\\$ has a uniform distribution on the interval \\$(0,1)\\$.

For a given index \\$k\\$, and for any \\$n \in \mathbb N\\$, there is a nonzero probability that \\$x\_k=n\\$ (ignoring floating-point inaccuracies). Therefore, with probability \\$1\\$ every \\$n\\$ appears infinitely often in the sequence \\$(x\_k)\\$.

# Answer
> 5 votes
# , ~~25~~ 21 bytes

```
repeat T=print(T:0+1)

```

Try it online!

Prints `2..1, 3..1, 4..1` and so forth.

Thanks to Robin Ryder for -4 bytes.

This works because `print` invisibly returns its first argument.

# Answer
> 4 votes
# Wolfram Language (Mathematica), 25 bytes

```
Do[Print@n,{m,∞},{n,m}]

```

Try it online!

-1 byte @att

# Answer
> 4 votes
# C (gcc), 43 bytes

```
i;main(j){for(;;)printf("%d ",j=--j?:++i);}

```

Try it online!

# Answer
> 4 votes
# JavaScript (V8), 26 bytes

```
for(a=b='';;)write(a+=--b)

```

Try it online!

Character `-` used as a separator and the output starts with it, so I'm not really sure if this is acceptable.

# Answer
> 4 votes
# convey, 17 15 bytes

*-2 thanks to Jo King!*

```
>1\/v
:+<.+}
11

```

Try it online!

Previous version that used a 0-stream and incremented its indices by 1. Jo's variation uses a 1-stream that adds itself to its indices, thus shortening the last row.

Starting with the top left `0`, we push it to the left. `\` will push its length `1` downward, it will get incremented `+1` and then `length + 1` new 0s will be let through. So we generate `0`, `0 0`, `0 0 0`, …

Those list get then dumped in a sink `]` while their indices `\.` get incremented `+1` and written to the output `}`: `1`, `1 2`, `1 2 3`, …

# Answer
> 4 votes
# Regenerate `-a`, 14 bytes

```
(${$1+1} !1 )+

```

Attempt This Online!

The only choice for the regex to make here is how many times to repeat the `(`...`)+` loop. The first iteration will always print `1` , because the first alternative can't match, as `$1` hasn't been defined yet.

On subsequent iterations, `${$1+1}` does math on `$1`, treating its contents as a number. It ignores the trailing space, and adds 1 to it. This then becomes the new value for `$1`, etc.

The `!` short-circuiting alternation prevents the second alternative, i.e. `1` , from being taken once it becomes possible for the first alternative, `${$1+1}` , to match.

# Answer
> 3 votes
# C (gcc), ~~52~~ ~~49~~ 44 bytes

Saved 5 bytes thanks to AZTECCO!!!

```
f(i,j){for(j=1;printf("%d ",j--);)j=j?:++i;}

```

Try it online!

# Answer
> 3 votes
# Brachylog, 4 bytes

```
⟦₁ẉ⊥

```

Try it online!

```
  ẉ     Print with a newline
⟦₁      the range from 1 to something,
   ⊥    then try again.

```

# Answer
> 3 votes
# Perl 5, ~~22~~ 20 bytes

```
say while$_.=++$i.$"

```

Try it online!

# Answer
> 3 votes
# , 13 bytes

```
$:@,~[echo@#\

```

Try it online!

Outputs `1`, `1 2`, `1 2 3 4`, `1 2 3 4 5 6 7 8`, etc, with every number on its own line.

* `echo@#\` Output the prefix lengths of the current list, ie, `1..n` where n is the current list length. This is done as a side effect.
* `$:@,~` Append the list to itself `,~` and call the function recursively `$:@`.

# Answer
> 3 votes
# Java (JDK), 61 bytes

```
v->{for(int i,j=2;;j++)for(i=0;++i<j;)System.out.println(i);}

```

Try it online!

Edit: Thanks @user for shaving off a few bytes and helping me learn something today! Big thanks to @KevinCruijssen for -2 bytes.

# Answer
> 3 votes
# Charcoal, 8 bytes

```
Ｗ¹«Ｉ⊕ⅉＤ⸿

```

Try it online! Link is to verbose version of code. Works by repeatedly printing the next number to the canvas and then dumping the entire canvas.

2 bytes for a version that prints the \\$ n \\$th term of a sequence:

```
ＩΣ

```

Try it online! Explanation: Simply prints the digital sum of the input. Given any natural number \\$ n \\$, all the values of the form \\$ \frac { 10 ^ n - 1 } 9 10 ^ m \\$ have a digital sum of \\$ n \\$ for every \\$ m \\$, thus each natural number appears infinitely often.

# Answer
> 3 votes
# Rust, 54 bytes

```
(2..).for_each(|x|(1..x).for_each(|y|print!("{} ",y)))

```

Try it online

# Answer
> 3 votes
# Ruby, 17 bytes

```
loop{p *1..$.+=1}

```

Try it online!

# Answer
> 3 votes
# JavaScript (V8), 29 bytes

```
for(n=k=1;;)print(n=--n||k++)

```

Try it online!

# Answer
> 3 votes
# Factor, 32 bytes

```
1 [ dup bit-count . 1 + t ] loop

```

Try it online!

Loops over the positive integers and prints their bit count (the number of 1 bits, a.k.a. popcount) forever. Outputting nth term would be simply 9-bytes `bit-count`. (I checked that the function works with bigints.)

Uses the same logic as Neil's Charcoal answer that there are infinitely many numbers whose digit sum equals n, except that this one uses bits instead. More precisely, for any positive integer n, \\$2^m(2^n-1)\\$ for any non-negative integer m has exactly n bits on, so the sequence contains infinitely many n's for any n.

# Answer
> 3 votes
# JavaScript (Browser), 40 bytes

```
f=(x=1)=>setInterval(_=>alert(x,f(x+1)))

```

Not very competitive answer :(

# Answer
> 3 votes
# Rust \+ rand crate, 43 bytes

```
||loop{print!("{} ",rand::random::<u32>())}

```

Uses the rand crate to output random numbers, meaning every number is printed infinitely many times.

# Answer
> 3 votes
# Zsh, ~~29~~ .. 19 bytes

Solution by @AdamKatz: Try it Online!

```
for ((;++i;))seq $i

```

*19 bytes, port from bash : `s(){seq $[++n];s};s`
* *25 bytes (per @AdamKatz) : `for ((;++i;))echo {1..$i}`
* *25 bytes : `for ((;;i++))shuf -i 1-$i`
* *26 bytes (per @AdamKatz) : `for ((;;))echo {1..$[++i]}`
* *29 bytes : `for ((i=1;;))echo {1..$[i++]}`
* *I tried to use `/dev/random` for an alternative but it was a mess!*

# Answer
> 3 votes
# AutoHotkey, 36 bytes

```
Loop
Loop,%A_Index%
Send,%A_Index%`t

```

Output is via keyboard simulation so it will print in whatever the active window is.
Numbers are separated by tabs.

```
1   1   2   1   2   3   1   2   3   4   1   2   3   4   5   1   2   3   4   5   6   1   2   3   4   5   6   7   1   2   3   4   5   6   7   8   1   2   3   4   5   6   7   8   9   1   2   3   4   5   6   7   8   9   10  1   2   3   4   5   6   7   8   9   10  11  1   2   3   4   5   6   7   8   9   10  11  12  1   2   3   4   5   6   7   8   9   10  11  12  13  1   2   3   4   5   6   7   8   9   10  11  12  13  14  1   2   3   4   5   6   7   8   9   10  11  12  13  14  15  1   2   3   4   5   6   7   8   9   10  11  12  13  14  15  16  1   2   3   4   5   6   7   8   9   10  11  12  13  14  15  16  17  1   2   3   4   5   6   7   8   9   10  11  12  13  14  15  16  17  18

```

---

Alternatively - and not in compliance with the challenge spec - if you prefer your numbers to be spoken rather than printed:

```
Loop
Loop,%A_Index%
ComObjCreate("SAPI.SpVoice").Speak(A_Index)

```

# Answer
> 3 votes
# Julia, 27 bytes

```
f(n=1)=println.(1:n),f(n+1)

```

Try it online!

# Answer
> 3 votes
# Rust, 50 bytes

```
||for i in(1..).flat_map(|n|1..n){print!("{} ",i)}

```

Try it online!

I know there are a couple of rust answers already, but this one is deterministic and takes a different (and shorter) approach to the problem. explanation:

```
||for i in(1..).flat_map(|n|1..n){print!("{} ",i)} //anonymous function
          (1..)                                    //for evey n from 1..infinite
               .flat_map(|n|1..n)                  //map to range from 1..n and flatten
  for i in                       {print!("{} ",i)} //print with a trailing space

```

# Answer
> 2 votes
# JavaScript (V8), 34 bytes

*Saved 2 bytes thanks to @tsh*

```
for(n=k=0;;)print(n=n<k?n+1:++k/k)

```

Try it online!

Returning the n-th term would be **31 bytes**:

```
n=>(m=(8*n+1)**.5-1>>1)*~m/2-~n

```

Try it online!

# Answer
> 2 votes
# APL (Dyalog Unicode), ~~12~~ 11 bytes (SBCS)

*Saved 1 byte thanks to @ovs*

```
{∇1+⍴⎕←⍳⍵}1

```

Try it online!

This one also uses the sequence from the question.

# Answer
> 2 votes
# AWK, 34 bytes

```
{for(;;++i)for(j=0;j++<i;)print j}

```

Try it online!

# Answer
> 2 votes
# PHP, 30 bytes

```
<?for(;;)echo--$j?:$j=++$i,~_;

```

Try it online!

The numbers are separated by a no-break space (U+00A0).

# Answer
> 2 votes
# Stax, 5 bytes

```
VImRJ

```

Run and debug it

## Explanation

```
VImRJ
VIm   map 1..infinity to
   R  range 1..i
    J join with spaces
  m   print each iteration

```

# Answer
> 2 votes
# Icon, 46 bytes

```
procedure f()
i:=0;|1&write(1to(i+:=1))&\z
end

```

Try it online!

Of course `procedure` ... `end` block makes it very verbose.

Too bad `seq()` doesn't work with bigints - otherwise I could've saved some bytes with

```
procedure f()
|1&write(1to seq())&\z
end

```

# Answer
> 2 votes
# Wolfram Language (Mathematica), 31 bytes

```
Print@Floor[Sec@n^2]~Do~{n,∞}

```

Try it online!

Not quite as short as the other Mathematica answer, but implements a different and more mathematically interesting sequence, namely the integer part of \\$\sec^2n\\$; the fact that this includes every natural number infinitely often follows from the fact that the integers are uniformly distributed modulo \\$\pi\\$.

# Answer
> 2 votes
# Julia, ~~47~~ 46 bytes

Thanks to @user recommended to change `true` to `1>0`.

```
a=[1];while 1>0;println(a);push!(a,last(a)+1);end

```

output:

```
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]

```

# Python 3, 45 bytes

```
a=[1]
while 1:
    print(a)
    a+=[a[-1]+1]

```

# Answer
> 2 votes
# Burlesque, 6 bytes

```
,r1)ro

```

Try it online!

Explanation:

```
,       # Don't take implicit input from stdin
 r1     # Range from 1 to infinity
   )    # Map each value to
    ro  # Range from 1 to value

```

# Answer
> 2 votes
# Java (JDK), 54 bytes

```
A b;{b=(s,i)->{System.out.print(s+=i+++s);b.B(s,i);};}

```

Try it online!

Usually in lambda functions, this website doesn't include the "interface name =" part, but my answer was a declaration statement without the initialization, so I decided to include it. I couldn't find a rule about it.

My older, wrongly counted, **47 byte** solution: Try it online!

(forced) inputs: a String with any delimiter (" "), and 1, where Y is the class it's in, b is the name of the interface object, and B is the method in the interface being used.

# Answer
> 2 votes
## Bash, 21 bytes

```
s(){ seq $[++n];s;};s

```

```
1
1
2
1
2
3
…

```

Run the 21B version on Try It Online

This defines a function `s` that runs `seq NUMBER` where `NUMBER` starts at `1` and increments with each run, then it runs itself recursively. After the definition, we run `s`.

For the cost of 5B to specify `-s\`  (separator is a space character), it can be adapted to a one *answer* per line solution at 26 bytes:

```
s(){ seq -s\  $[++n];s;};s

```

```
1
1 2
1 2 3
…

```

Run the 26B version on Try It Online

# Answer
> 2 votes
# jq, 24 bytes

```
range(range(infinite))+1

```

Try it online! (requires the `-n` flag)

JQ is a stream-based language: every expression can return multiple values and when expressions are combined together the second one is flat-mapped over everything returned by the first. This makes it very easy to express infinite sequences.

`infinite` is a filter that ignores its input and returns a single infinite floating-point value.
`range(n)` is a filter that ignores its input and returns every positive integer smaller than `n`.
`+1` adds one to each value in the result.

By default if we run this program it will try to read from STDIN (because each filter needs to take an input, even if it is ignored). Therefore we pass the `-n` flag to tell the interpreter to pass a single `null` value as the input to the filter.

# Answer
> 2 votes
# PowerShell Core, 14 bytes

```
for(){1..++$i}

```

Try it online!

Will output the numbers of the sequence separated by a new line.

# Answer
> 2 votes
# Python 3, 36 bytes (including newline)

```
s=[1]
while 1:print(s);s+=[s[-1]+1]

```

Try it online!

# Answer
> 2 votes
# Vyxal, 5 bytes

```
{nɾṄ,

```

Try it Online! The `5` flag makes the online interpreter time out after 5 seconds.

Explanation:

```
{      # Open a(n infinite) while loop
 n     # Get the loop variable's value
  ɾ    # Push the range from 1 to n
   Ṅ   # Join by spaces (ɾ creates a list)
    ,  # Print

```

# Answer
> 2 votes
# Appleseed, 16 bytes

```
(q(_(map 1to(1to

```

Anonymous function that can be called with no arguments and returns an infinite nested list `((1) (1 2) (1 2 3) ...)`. Try it online!

### Explanation

```
(q           ; Anonymous function
 (_          ; that takes any number of arguments:
  (map 1to   ; Inclusive range from 1 to N for each N in
   (1to))))  ; numbers from 1 to infinity

```

# Answer
> 1 votes
# Scala, 23 bytes

```
Stream from 1 map(1 to)

```

Try it online

An infinite `Stream` of `IntRange`s. Uses the sequence from the question.

# Answer
> 1 votes
# Python 2, ~~24~~ 33 bytes

Added 9 bytes to fix an error kindly pointed out by caird coinheringaahing.

```
n=1
while 1:n+=1;print range(1,n)

```

Try it online!

# Answer
> 1 votes
# Retina 0.8.2, 11 bytes

```

_
}*M!&`_+

```

Try it online! Outputs in unary. Explanation: The first two lines cause the number of `_`s to increase on each pass, while the `M!&`_+` generates all suffixes, which ensures that all integers get printed. The `}` causes the entire script to repeat indefinitely. The `*` causes the suffixes to be printed and discarded, since otherwise Retina does not output until the program terminates.

18 bytes for a traditional decimal output. Each integer is printed in turn, and then for each integer all of the previous integers are printed again, so the final sequence is 1, 2, 1, 3, 2, 1, 4, 3 ...

```
{`^
_
*(M!&`_+
%`_

```

Try it online!

# Answer
> 1 votes
# Pyth, 4 bytes

```
f!pS

```

Try it online!

## Explanation

```
f!pS
      : lambda T:
   S  :    range(1, T)
  p   :    print and return the range
 !    :    logical negate the range
f     : Find first natural number input to function that returns a truthy value

```

# Answer
> 1 votes
# Raku, 18 bytes

```
.say for [\,] 1..*

```

Try it online!

`[\,] 1..*` generates the list of prefixes of the sequence of naturals. `.say for` just prints them.

# Answer
> 1 votes
# Nim, 47 bytes

```
var i=1
while true:
 for j in 1..i:echo j
 i+=1

```

Try it online! The footer makes it finite so the output can be observed.

Note that Nim doesn't have bigints, so this works only in theory (in accordance with our rules).

# Answer
> 1 votes
# Common Lisp, 56 bytes

```
(do((i 1(1+ i)))(())(dotimes(j i)(format t"~v^~a "j j)))

```

Nested loop solution using the `do` macro for the outer loop and the `dotimes` macro for the inner loop. `dotimes` starts with `0` so `format` includes a specifier that checks whether it's a `0`.

# Answer
> 1 votes
# AWK, 33 bytes

An approach different from @Noodle9's, that luckly uses one less byte.

```
{for(;;a[++i])for(j in a)print j}

```

Try it online!

```
{
for(;;a[++i])  # by only stating the array[element], that element is created in the array.
               # all not assigned variables starts at 0.
               # at first, i++ would return 0, and increment 1 to i;
               # but ++i increments 1 to i, and then return its new value.
  for(j in a)  # for every element existing in the array,
    print j    # prints the element j.
}

```

---

# AWK, 37 bytes

Prints numbers in one line.

```
{for(;;a[++i])for(j in a)printf j FS}

```

Try it online!

---

# AWK, 51 bytes

Prints numbers in a pyramid.

```
{for(;;a[++i])for(j in a)printf j+1 in a?j FS:j RS}

```

Try it online!

# Answer
> 1 votes
# sed in unary, 16 bytes

```
s/^/1\n1/p;h;G;D

```

Try it online!

Each unary natural is on its own line. Seems to increase logarithmically.

sed has two spaces: the default one is called the pattern space and is lost after processing the next of input; the other one is the hold space, which instead is retained throughout execution. Both start empty.

(sed cannot run without input, so this program is run with an empty line as input).

The idea is to have the largest number encountered so far on the first line, and then have the result of the previous iterations on the succeeding lines.

`s/^/1\n1/` replaces the beginning (symbolised with `^`, really just empty space) with `1` followed by a newline (`\n`) and another `1`. The `p` flag then prints the pattern space. The second `1` inserted increases the maximum number by 1, which was on the first line before the substitution, and now is on the second line.

`h` replaces the hold space with the contents of the pattern space, after which `G` appends the hold space to the pattern space, joining them by a newline. This is our method to retain the previous natural numbers encountered.

`D` deletes the first line (which in our case is always `1` thanks to the substitution made with the `s` command) and the newline after it. This effectively returns the largest number encountered so far back to the first line. Then `D` causes the program to be run from the beginning with what remains of the pattern space because the first line was not empty. Because the `s` command will always make sure the first line is not empty, the initial `1\n` effectively acts only for `D` to cause the program to loop indefinitely.

---

# sed 4.2.2, 15 bytes

```
:;s/^/1/p;h;G;t

```

Try it online!

sed 4.2.2 allows empty labels, ridding the need for `1\n` and `D`.

# Answer
> 1 votes
# Java (OpenJDK 8), 76 chars

```
void f(){for(int i=0,j;++i>0;out.println())for(j=0;j++<i;out.print(j+" "));}

```

Try it online!

Output (unlimited):

```
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
. . .

```

# Answer
> 1 votes
# Chapel, 51 bytes

```
var i=1;while(i){for j in 1..i do writeln(j);i+=1;}

```

Try it online!

# Answer
> 1 votes
# Batch, 127 bytes

```
@echo off
setlocal enabledelayedexpansion
set "s=1"
set k=1
for /L %%a in (0,0,0) do (echo !s! &set /a k=k+1 &set "s=!s! !k!")

```

# Answer
> 1 votes
# PowerShell, 20 bytes

```
for(){' '+(1..++$i)}

```

Try it online!

# Answer
> 1 votes
# Pyt, 7 bytes

```
1`⁺řĐƥł

```

Try it online!

Port of caird coinheringaahing's Jelly answer.

# Answer
> 1 votes
# Thunno, \\$ 9 \log\_{256}(96) \approx \\$ 7.41 bytes

```
[1+DR1+ZK

```

Attempt This Online!

13 chars for a better format: Attempt This Online!

#### Explanation

```
[1+DR1+ZK  # TOS is initially 0
[          # while True:
 1+        #  increment TOS
   DR1+    #  push range(1, TOS+1)
       ZK  #  pop and print

```

# Answer
> 1 votes
# Vyxal, 3 bytes

```
Þ∞K

```

Try it Online!

```
Þ∞ɾ

```

Try it Online!

#### Explanation

```
Þ∞  # Push an infinite list of positive integers:   [1, 2, 3, 4, 5, ...]
  K # Get the prefixes of this list                 [[1], [1, 2], [1, 2, 3], ...]
  ɾ # Inclusive one-range of each:                  [[1], [1, 2], [1, 2, 3], ...]

```

# Answer
> 0 votes
# Python, 76 bytes

```
def n():
 c=2
 while 1:
  yield from range(1,c)
  c+=1
for i in n():print(i)

```

Uses generators and `yield from` to chain infinite `range`s. You can call n directly for a generator.

---
Tags: code-golf, math, open-ended-function
---