><>, 51+3=54 47 bytes
:&v
?!\1-:&:&*}}r:
~\
!~>1+::n&:&%:a84*@@?$~o?
Try it online!
Input is expected on top of the stack at program start using the -v
flag. Output consists of non-aligned numbers separated by single spaces, and each line is separated by a single newline. Example output for N=5
:
1 2 3 4 5
11 12 13 14 15
21 22 23 24 25
16 17 18 19 20
6 7 8 9 10
... followed by a single newline. Program terminates with an error (something smells fishy...
), but that's on STDERR rather thatn STDOUT.
Explaination:
The first line simply stores a copy of N
in the register.
The second line builds up the offset for each output row by subtracting 1 from N
, multiplying this by N
, rotating it to the bottom of the stack and then reversing the entire stack. When the number on top of the stack reaches 0, the stack should look like this (example uses N=5
):
5 15 20 10 0 0
The third line discards the duplicate 0
from the top of the stack.
The fourth line increments the top of the stack and outputs a copy of it. This is then taken mod N
, and this is used to decide if a space or newline should be printed, and if the top of the stack should be discarded - if last number printed is x
, then x mod N == 0
indicates that the end of that output row has been reached. Execution ends when 1+
gets executed on an empty stack, throwing the termination error.
Previous version
This explicitly checked for an empty stack to end execution, and I was also including 3 bytes for the -v
flag usage.
:&v
?!\1-:&:&*}}r:
~\
!;>1+::n&:&%:a84*@@?$~o?!~l?
Try it online!
Are entries allowed to terminate with an error, as long as that error is not printed to STDOUT? – Sok – 2018-03-01T10:14:37.750
@Sok yes, that's allowed by default. – Martin Ender – 2018-03-01T10:17:51.053
1I guess the title is taken from the deleted question, but as it's not very searchable (to find for dupe etc.), can you change to a better one? – user202729 – 2018-03-01T11:59:29.347
1Since "the output format is flexible", may I output a one-dimensional array with the numbers ordered from line to line? (ex:
1 2 3 7 8 9 4 5 6
) Is the output format that flexible? – Olivier Grégoire – 2018-03-01T13:12:28.1304The APL solution is probably a single character of Old Persian cuneiform. – Mark – 2018-03-02T02:38:30.440