((${$2+1}|1)( $2){$2-1}( ${$4+1}{1-$4/$~1}| ${$2+1}{1-$2/$~1}){$~1-$2+1}\n){$~1}
Takes the argument from the command-line. Try it here!
Explanation
(Spaces are replaced with underscores to improve visibility.)
Each line is generated in three parts. Top-level structure:
( ) Group 1: a line of output
(...) Group 2: the first digit
(...){...} Group 3: repetitions of the first digit
(...){...} Group 4: count up to N
\n Add a newline
{$~1} Repeat, generating N lines
Group 2, the first digit on each line:
( )
${$2+1} Add 1 to the previous value of group 2
| Or, if group 2 has not been previously matched...
1 Use 1
Group 3, the rest of the digits on the line that are identical to the first number:
(_$2) The most recent value of group 2 (with a space in front of it)
{$2-1} repeated (group 2) - 1 times
Group 4, the remaining numbers on the line, starting with (group 2) + 1 and counting up to N:
( ${$4+1}{1-$4/$~1}| ${$2+1}{1-$2/$~1}){$~1-$2+1}
( )
_ Space
${$4+1} Previous value of group 4, plus 1
{ } Repeat the value this many times:
$4/$~1 1 if group 4 == N, 0 otherwise
1- Subtract from 1: 1 -> 0 and 0 -> 1
So if the new value would have been N+1,
it instead becomes empty string
| If the previous value of group 4 was not
a number, the arithmetic fails, and we
instead use...
_ Space
${$2+1} Last value of group 2, plus 1
{1-$2/$~1} Repeat 0 times if group 2 == N
{ } Repeat the above
$~1-$2+1 N - (group 2) + 1 times
Worked example
Suppose the input is 3.
Line 1:
- Group 2: not previously matched, so
1
- Group 3:
1
repeated 1-1
= 0 times, so empty string
- Group 4 is repeated
3-1+1
= 3 times:
- Group 4 not previously matched, so
followed by 2
repeated 1-1/3
= 1 time (the division is integer division)
- Previous value of group 4 is
2
, so
followed by 3
repeated 1-2/3
= 1 time
- Previous value of group 4 is
3
, so
followed by 4
repeated 1-3/3
= 0 times
Result: 1 2 3
Line 2:
- Group 2: previous value is
1
, so 2
- Group 3:
2
repeated 2-1
= 1 time
- Group 4 is repeated
3-2+1
= 2 times:
- Previous value of group 4 is
, which is not a number, so
followed by 3
repeated 1-2/3
= 1 time
- Previous value of group 4 is
3
, so
followed by 4
repeated 1-3/3
= 0 times
Result: 2 2 3
Line 3:
- Group 2: previous value is
2
, so 3
- Group 3:
3
repeated 3-1
= 2 times
- Group 4 is repeated
3-3+1
= 1 time:
- Previous value of group 4 is
, which is not a number, so
followed by 4
repeated 1-3/3
= 0 times
Result: 3 3 3