Print number triangle

Given a number N, output a NxN right angled triangle, where each row i is filled with numbers up to i.

Example

n = 0

(no output)

n = 4

1
1 2
1 2 3
1 2 3 4

n = 10

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

(no alignment needed)

n = N

1
1 2
1 2 3
.
.
.
1 2 3 4 .... N

There is no trailing space at the end of each line.

Least number of bytes wins, and standard loopholes are not allowed.

• Can the output be a nested list of numbers? – seequ Mar 12 '15 at 5:39
• What should be the behavior for n=0, and for n>9? – freekvd Mar 12 '15 at 18:55
• @Sieg Sure, as long as the output is correct. – Tan WS Mar 13 '15 at 0:57
• @freekvd for 0 there is no output, for n>9 no special formatting required – Tan WS Mar 13 '15 at 1:00
• Ah darn, you broke my submission. Fixing ASAP – seequ Mar 13 '15 at 5:54

Joe, 5 3 bytes (+2 or +3 for -t flag)

Well, apparently I didn't utilize the full potential of Joe. This was possible back when I first posted this.

\AR

Here, R gives the range from 0 to n, exclusive. Then \A takes successive prefixes of it (A is the identity function). Examples:

With -t flag (note: this is now the standard output even without the flag):

(\AR)5
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
\AR5
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
\AR2
0
0 1
\AR1
0
\AR0

Without it:

\AR5
[, [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4]]
(\AR)5
[, [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4]]
\AR2
[, [0, 1]]
\AR1
[]
\AR0
[]

The rules got changed a bit. My old code didn't behave correctly with N =0. Also, now output could be just a nested list, so -t can be dropped.

1R1+R

Now, Rn gives a range from 0 to n, exclusive. If given 0, it returns an empty list. 1+ adds 1 to every element of that range. 1R maps the values to ranges from 1 to x. Empty liats, when mapped, return empty lists.

Example output:

1R1+R0
[]
1R1+R5
[, [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]

Update: I just noticed something. The function automatically maps to rank 0 elements. The following example is run with -t flag.

1R1+R3 5 8
1
1 2
1 2 3

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

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

Old: 5 bytes (with the -t flag)

1R1R

This is an anonymous function which takes in a number, creates a list from 1 to N (1Rn) and maps those values to the preceding range, giving a range from 1 to x for each item of range 1 to N.

The -t flag gives output as a J-like table.

1R1R5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Note : the language is very new and not complete, but the latest version was released before this challenge.

• So J was not enough for having an advantage on array based challenges ? :D – Optimizer Mar 12 '15 at 5:51
• @Optimizer Optimizing is important. – seequ Mar 12 '15 at 5:57
• Suddenly, my most voted answer is the one I spent the least time on. The injustice. – seequ Mar 12 '15 at 18:52
• I guess Joe is not your average Joe... – Justin Mar 14 '15 at 18:43

Python 3, 48 45 bytes

f=lambda n:n and[f(n-1),print(*range(1,n+1))]

Hooray for side effects.

• Nested nothingness. Now that's twisted. – seequ Mar 12 '15 at 20:26
• That's a nifty trick: putting the function before the print to execute the prints in reverse order. – xnor Mar 13 '15 at 21:49

APL, 5

⍪⍳¨⍳⎕

creates a vector 1..n and for each element another such vector.

Then ⍪ makes a column out of all vectors. This avoids the problem with trailing blanks.

Try it on tryapl.org

Older solution:

{⎕←⍳⍵}¨⍳⎕

Creates a vector 1..n

{⎕←⍳⍵} is a function that outputs for each (¨) element a vector 1..n on a separate line

This one can't be tried on tryapl.org unfortunately, because ⎕← doesn't work there.

• There should be no trailing spaces in any line. – randomra Mar 12 '15 at 9:04
• ah thank you, i missed that one. Will correct soon – Moris Zucca Mar 12 '15 at 9:14
• I knew APL would be a solution – Conor O'Brien Sep 30 '15 at 21:33
• Oh God, what are my eyes seeing – Codefun64 Oct 3 '15 at 18:44

J, 27 bytes

J is not good with non-array numeric output. This function creates a properly formatted string from the numbers.

;@(<@,&LF@":@:>:@:i.@>:@i.)

(;@(<@,&LF@":@:>:@:i.@>:@i.)) 4
1
1 2
1 2 3
1 2 3 4

Try it online here.

• You could also use ]\@i. to get ;@(<@,&LF@":@:>:@:]\@i.) – seequ Mar 21 '15 at 11:32

PHP, 53 Bytes

Edit 2: Ismael Miguel suggested reading from input instead of defining a function, so the score is now 53 bytes for PHP:

for($a=1;@$i++<$n=$argv;$a.=" ".($i+print"$a\n")); And once again, it can be improved if PHP is configured to ignore errors (52 bytes): for($a=1;$i++<$n=$argv;$a.=" ".($i+print"$a\n"));
for($a=1;$i++<$n=$_GET[n];$a.=" ".($i+print"$a\n")); Edit: Austin suggested a 60 bytes version in the comments: function f($n){for($a=1;@$i++<$n;$a.=" ".($i+print"$a\n"));}

Which can be improved if we doesn't display PHP errors (59 bytes):

function f($n){for($a=1;$i++<$n;$a.=" ".($i+print"$a\n"));}$a stores the next line that will be printed, and each time it's printed a space and the next number (print always returns 1) are concatened to it.

Recursive functions (65 bytes):

function f($n){$n>1&&f($n-1);echo implode(' ',range(1,$n))."\n";}
function f($n){$n>1&&f($n-1);for(;@$i++<$n;)echo$i,' ';echo"\n";}   // Using @ to hide notices.

Shorter recursive function, with error reporting disabled (64 bytes):

function f($n){$n>1&&f($n-1);for(;$i++<$n;)echo$i,' ';echo"\n";}

Even shorter recursive function, with error reporting disabled and an empty line before real output (62 bytes):

function f($n){$n&&f($n-1);for(;$i++<$n;)echo$i,' ';echo"\n";}

Just for fun, non-recursive fucntions:

function f($n){for($i=0;$i<$n;print implode(' ',range(1,++$i))."\n");} // 70 bytes function f($n){for(;@$i<$n;print implode(' ',range(1,@++$i))."\n");} // 68 bytes, hiding notices. function f($n){for(;$i<$n;print implode(' ',range(1,++$i))."\n");} // 66 bytes, error reporting disabled. • 45 bytes: for($a=1;@$i<$n;$a.=" ".(@++$i+print"$a\n")); – Austin Mar 13 '15 at 8:14 • @Austin: I've read in a comment that the code must be either a full program reading from input, or a function. Very nice trick, it can be improved by a bit / byte: for($a=1;@$i++<$n;$a.=" ".($i+print"$a\n")); (44 bytes) – Benoit Esnard Mar 13 '15 at 9:29 • Ah ok, then I suppose you would do function f($n){for($a=1;@$i++<$n;$a.=" ".($i+print"$a\n"));}, which is 60 bytes. – Austin Mar 13 '15 at 10:19
• Indeed. Are you OK if I edit my answer to add your solution? – Benoit Esnard Mar 13 '15 at 10:24
• for($a=1;$i++<$n=$_GET[n];$a.=" ".($i+print"$a\n")); --> try this (full code, using url parameter n with the number) – Ismael Miguel Mar 14 '15 at 22:32 CJam, 13 12 bytes ri{),:)S*N}/ How it works: ri{ }/ "Run the block input number of times with iteration index from 0 to N-1"; ) "Increment the iteration index (making it 1 to N)"; , "Get an array of 0 to iteration index"; :) "Increment each of the above array members by 1"; S* "Join all above array numbers with space"; N "Add a new line. After all iterations, things are automatically printed"; Try it online here Pyth, 9 bytes VQjdr1hhN Really thought that this can be done shorter, but it doesn't seem so. Try it online. Q = input() VQ For N in [0, 1, ..., Q-1]: r1hhN create list [1, ..., N+1+1-1] jd print joined with spaces • An alternative 9: VQaYhNjdY. If only a returned the list, then something like VQjdaYhN would be 8. – Sp3000 Mar 12 '15 at 12:15 • a briefly used to return the appended list. – Optimizer Mar 12 '15 at 12:47 • I'm not familiar with Pyth, so could you elaborate why N+1+1-1? – seequ Mar 12 '15 at 20:30 • @Sieg r is the Python-range function, therefore the -1 (r1N creates the list [1, 2, ..., N-1]). But in the Nth iteration of the loop, I want the list [1, 2, ..., N+1], therefore I need to add 2 to N. r1hhN translates directly to range(1, N+1+1). Another possibility would be r1+N2 (range(1, N+2)). – Jakube Mar 12 '15 at 21:12 • Or even mhdhN, but that's a complete different approach. – Jakube Mar 12 '15 at 21:14 JavaScript (ES6) 49 52 Such a simple task, I wonder if this can be made shorter in JS (Update: yes, using recursion) Recursive 49 f=n=>alert((r=w=>n-i++?w+'\n'+r(w+' '+i):w)(i=1)) Iteraive 52 f=n=>{for(o=r=i=1;i++<n;o+='\n'+r)r+=' '+i;alert(o)} • Where can I test this? I cant seem to find any ES6 playgrounds that accepts this – Kristoffer Sall-Storgaard Mar 12 '15 at 11:53 • @KristofferSall-Storgaard Firefox supports ES6 be default. So Firefox Console. – Optimizer Mar 12 '15 at 13:42 Java, 85 84 bytes This is surprisingly short in Java. void a(int a){String b="";for(int c=0;c++<a;System.out.println(b+=(c>1?" ":"")+c));} Indented: void a(int a){ String b=""; for(int c=0; c++<a; System.out.println( b+=(c>1?" ":"")+c )); } 1 byte thanks to Bigtoes/Geobits • You can save one by moving the b+=... into println(b+=...). – Geobits Mar 12 '15 at 13:15 Prolog - 119 h(N):-setof(X,(between(1,N,K),setof(Y,between(1,K,Y),X)),[L]),k(L),nl,fail. k([A|B]):-write(A),(B=[];write(" "),k(B)). Python 2 - 62 54 65 bytes def f(n): for x in range(n):print' '.join(map(str,range(1,x+2))) • The number n should be given as input to the program, not initialized in a variable. – Zgarb Mar 12 '15 at 13:16 • Thanks for the hint. Was not sure about that. – pepp Mar 12 '15 at 13:40 • Sorry, I should have been clearer. What I meant is that you must actually define N by doing N=input() or something similar, so that your program can be run as such. Here is a Meta discussion on the topic. – Zgarb Mar 12 '15 at 13:45 • So this would be right, right? – pepp Mar 12 '15 at 21:06 • Looks good now! – Zgarb Mar 12 '15 at 21:50 J, 9 characters As a tacit, monadic verb. [:":\1+i. • i. y – the numbers from 0 to y - 1. • 1 + i. y – the numbers from 1 to y. • ": y – the vector y represented as a string. • ":\ y – each prefix of y represented as a string. • ":\ 1 + i. y – each prefix of the numbers from 1 to y represented as a matrix of characters. • Now that's quite smart. +1 – seequ Mar 21 '15 at 20:37 • This is more J-esque but doesn't it violate the rule about there being no trailing spaces on each line? – miles Jan 21 '17 at 9:16 • @miles Indeed it does! Anything else would be very complicated. – FUZxxl Jan 21 '17 at 14:47 ><> (Fish), 40 37 + 3 = 40 bytes &1>:&:&)?;1\ (?v:n" "o1+>}:{:@ ao\~1+ Once again, ><> does decently well at another number printing exercise. Run with the -v flag for input, e.g. py -3 fish.py -v 4 Explanation & Put n in register 1 Push 1 (call this "i") [outer loop] :&:&)? If i > n... ; Halt 1 Else push 1 (call this "j") [inner loop] }:{:@(? If j > i... ~1+ao Pop j, print newline, increment i and go to start of outer loop :n" "o1+ Else print j, print a space, increment j and go to start of inner loop C (with no loops, yeah!) - 72 bytes b(n,c){if(n){b(n-1,32);printf("%d%c",n,c);}}r(n){if(n){r(n-1);b(n,10);}} This creates a function r(n) that can be used this way: main(){ r(5); } See it in action, here on tutorialspoint.com It requires a very few tricks easily explained. I think it can be greatly improved. • Actually it's 75 bytes, not 74. However, you can cut it down to 72 bytes by replacing ' ' with 32 and '\n' with 10: b(n,c){if(n){b(n-1,32);printf("%d%c",n,c);}}r(n){if(n){r(n-1);b(n,10);}} – FatalSleep Mar 29 '15 at 9:47 • Pretty nice trick, thanks! – A. Breust Mar 30 '15 at 8:12 • Thanks! I did my best to one up you in the C category, but I couldn't make anything shorter! So I decided to shorten yours instead. – FatalSleep Mar 30 '15 at 8:40 • 64 bytes b(n,c){n&&b(n-1,32)^printf("%d%c",n,c);}r(n){n&&r(n-1)^b(n,10);} Wandbox – o79y Jan 22 '17 at 5:29 Python 2 - 72 >>> def p(N):print'\n'.join(' '.join(map(str,range(1,i+2)))for i in range(N)) ... >>> p(5) 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 • For answers on this site, you should write a complete program or function. And you should print the result to stdout, or return them from a function. N should be read from input or taken as a function parameter, not predefined as a variable. – jimmy23013 Mar 12 '15 at 15:12 • @user23013 OK,fixed! – Kasramvd Mar 12 '15 at 15:15 • The function definition needs to be included in the byte count, so I don't think this is 61. It's probably in your best interest to call the function something short, like p. On another note, you can remove two spaces - one between print and '\n' and the other between ))) and for. – Sp3000 Mar 12 '15 at 16:17 • @Sp3000 OK,thanks for attention! fixed!;) – Kasramvd Mar 12 '15 at 16:30 • 72: def p(N):print'\n'.join(' '.join(map(str,range(1,i+2)))for i in range(N)) – seequ Mar 12 '15 at 16:37 Perl, 28 Reads the parameter from stdin. @x=1..$_,print"@x
"for 1..<>

From the command line:

perl -E'$,=$";say 1..$_ for 1..<>' but I don't now how to count that (probably between 25 and 29). Python import string N,s=int(input()),list(string.digits) for i in range(1,N+1): print(' '.join(s[1:i+1])) • Doesn't this fail if N >= 10? – seequ Mar 12 '15 at 13:52 • @Sieg Yes you're right. I just learning Python, was looking for way to convert list of int to list of strings. – bacchusbeale Mar 12 '15 at 17:20 • 63 bytes: for i in range(int(input())):print(' '.join("123456789"[:i+1])) - Note that strings are treated as lists. – seequ Mar 12 '15 at 17:24 Golfscript 14 ,{2+,1>' '*n}/ Expects the input number to be present on the stack. Online example: link Clip, 16 Jm[ijkw,1iwS},1n Explanation J .- join with newlines -. m[i },1n .- map numbers from 1 to numeric value of input -. jkw wS .- join with spaces -. ,1i .- numbers from 1 to index -. Go, 93817893 90 bytes func r(n int)(s string){s=string(n+48);if n!=1{s=r(n-1)+" "+s};println(s);return} Current ungolfed func r(n int) (s string) { // Convert n to a string, we do not have to initialize s since // we hijacked the return value. // Numbers in the ascii table starts at 48 s = string(n | 48) // Unless we are on our last iteration, we need previous iterations, // a space and our current iteration if n != 1 { // Collect the result of previous iteration for output s = r(n-1) + " " + s } println(s) // We can use a naked return since we specified the // name of our return value in the function signature return } If we need to handle N > 9 we can use the following at 78 bytes, however it requires importing the fmt package. func r(n int)(s string){s=Sprint(n);if n!=1{s=r(n-1)+" "+s};Println(s);return} If we include the import statement I'm now back at my initial 93 92 90 bytes import."fmt";func r(n int)(s string){s=Sprint(n);if n>1{s=r(n-1)+" "+s};Println(s);return} Test it online here: http://play.golang.org/p/BWLQ9R6ilw The version with fmt is here: http://play.golang.org/p/hQEkLvpiqt • I'm not sure how I feel about the string cast, but any attempts to turn it into a byte array just makes it longer – Kristoffer Sall-Storgaard Mar 12 '15 at 14:15 • The main problem I see is that it doesn't work for n>9. You can save a byte by changing != to >, though. – Geobits Mar 12 '15 at 14:49 • @Bigtoes, fixed now, I dont know if I'm supposed to count the import statement though – Kristoffer Sall-Storgaard Mar 12 '15 at 15:04 • I know they're counted for the languages I'm more familiar with, so most likely yes. Sucks, I know :) – Geobits Mar 12 '15 at 15:05 ZX / Sinclair BASIC - 39 bytes ZX Basic uses 1 byte per keyword (all the uppercase words), so helps to keep the byte size down a bit... 1 INPUT n:FOR i=1 TO n:FOR j=1 TO i:PRINT j;" ";:NEXT j:PRINT:NEXT i Using n = 8 • Nice. But ZX basic uses 6 more hidden bytes for each numeric literal (a common trick was VAL("1") (6 bytes as VAL is 1) insted of 1 (7 bytes)) – edc65 Mar 13 '15 at 0:29 R, 28 for(i in 1:scan())print(1:i) • The output is incorrect for an input value of 0. Also, it's unclear whether the leading  on each line is in violation of the spec. – Alex A. Mar 13 '15 at 1:28 • @AlexA. if you look closely at the question you'll see my comment asking what behavior should be for n=0. But thanks for pointing me in the right direction! – freekvd Mar 13 '15 at 20:10 • I saw the comment. The thing is that this doesn't print nothing for 0, it prints 1; 1 0. (Pretend ; is a line break.) – Alex A. Mar 13 '15 at 20:13 • You might want to also consider using cat(1:i,"\n"). Even though it's slightly longer than print(1:i), it doesn't include a leading  on each line. – Alex A. Mar 13 '15 at 21:28 TI-Basic, 28 bytes Input N For(I,1,N randIntNoRep(1,N->L1 SortA(L1 Disp L1 End • This does not output as the format indicates; rather, the array is displayed, brackets and all, on the homescreen. – lirtosiast May 20 '15 at 1:03 C, 89 characters // 90 characters f(int n){int a=1,b;for(;n--;++a){for(b=0;b<a;++b)printf("%c%d",(!!b)*' ',b+1);puts("");}} To eliminate confusion about puts("");. This simply prints a newline character (as seen here): Notice that puts not only differs from fputs in that it uses stdout as destination, but it also appends a newline character at the end automatically (which fputs does not). I got it slightly shorter with @TheBestOne's java algorithm: // 89 characters f(int a){char b="",*p=b+1;int c=0;for(;a--&&(sprintf(b,"%s %d",b,++c)&&puts(p)););} • puts(""); does nothing. You can use char b="" instead of char b={0} to save 1 character. – mch Mar 12 '15 at 16:14 • puts(""); prints a newline character. – Felix Bytow Mar 12 '15 at 20:56 Perl: 34 characters print"@$_\n"for map[1..$_],1..$_;

This code gets the input number supplied through the special variable $_. • Most brackets are redundant here: print"@$_\n"for map[1..$_],1..$_ also works. – nutki Mar 13 '15 at 10:26
• I adjusted the code. – Felix Bytow Mar 13 '15 at 11:06

C# - 94 bytes

Written as an anonymous function that returns a string, which doesn't seem to be disallowed by the spec.

n=>String.Join("\n\n",Enumerable.Range(1,n).Select(l=>String.Join(" ",Enumerable.Range(1,l))))

Here's an ungolfed version (comments are read in BDCA order):

n =>
String.Join("\n\n",                    //...then join it together with newlines.
Enumerable.Range(1, n).Select(l => //For each l from 1 to n, ...
String.Join(" ",              //...and join it with spaces, ...
Enumerable.Range(1, l)    //...get the range from 1 to l, ...

Bash+coreutils, 26 bytes

seq \$1|sed "x;G;s/\n/ /;h"
• seq simply generates the numbers 1 to n
• sed saves the entire output for a given line in the hold space, and then appends the next line to it.

Haskell, 62 57 bytes

e=enumFromTo 1
f=putStr.unlines.map(unwords.map show.e).e

Point-free style. Usage example:

Prelude> f 5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
• Doing e=enumFromTo 1 saves 7 bytes. – Zgarb Mar 13 '15 at 8:40
• @Zgarb: Thanks, but if I swap out enumFromTo 1, I have to give the main function a name, too, so it's 5 bytes. Without the name it would be a let construct: let e=enumFromTo 1 in (putStr.unlines.map(unwords.map show.e).e) 5 – nimi Mar 14 '15 at 1:47

Mathematica, 32

Print@Row[Range@i," "]~Do~{i,#}&
• How about TableForm[Range/@Range@#]&? – Martin Ender Mar 21 '15 at 15:13
• Shorter: Grid[Range/@Range@#]& – alephalpha Mar 21 '15 at 15:22
• And it even looks better. :) (I keep forgetting about Grid.) – Martin Ender Mar 21 '15 at 15:23
• But I'm not sure if there is no trailing space at the end of each line. – alephalpha Mar 21 '15 at 15:24
• Oh good point. :( – Martin Ender Mar 21 '15 at 15:25

Scala, 7365 62 bytes

(n:Int)=>print(1 to n map(1 to _ mkString " ") mkString "\n")

Ungolfed

def printNumberTriangle(n: Int): Unit = {
def rowString(m: Int): String = 1.to(m).mkString(" ")
print(1.to(n).map(rowString).mkString("\n"))
}