25
\$\begingroup\$

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.

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

69 Answers 69

17
\$\begingroup\$

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], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4]]
   (\AR)5
[[0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4]]
   \AR2
[[0], [0, 1]]
   \AR1
[[0]]
   \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], [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.

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

Python 3, 48 45 bytes

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

Hooray for side effects.

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

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.

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

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.

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

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[1];$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[1];$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.
\$\endgroup\$
  • 2
    \$\begingroup\$ 45 bytes: for($a=1;@$i<$n;$a.=" ".(@++$i+print"$a\n")); \$\endgroup\$ – Austin Mar 13 '15 at 8:14
  • \$\begingroup\$ @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) \$\endgroup\$ – Benoit Esnard Mar 13 '15 at 9:29
  • \$\begingroup\$ 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. \$\endgroup\$ – Austin Mar 13 '15 at 10:19
  • \$\begingroup\$ Indeed. Are you OK if I edit my answer to add your solution? \$\endgroup\$ – Benoit Esnard Mar 13 '15 at 10:24
  • 1
    \$\begingroup\$ for($a=1;$i++<$n=$_GET[n];$a.=" ".($i+print"$a\n")); --> try this (full code, using url parameter n with the number) \$\endgroup\$ – Ismael Miguel Mar 14 '15 at 22:32
5
\$\begingroup\$

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

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

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
\$\endgroup\$
  • 1
    \$\begingroup\$ An alternative 9: VQaYhNjdY. If only a returned the list, then something like VQjdaYhN would be 8. \$\endgroup\$ – Sp3000 Mar 12 '15 at 12:15
  • 2
    \$\begingroup\$ a briefly used to return the appended list. \$\endgroup\$ – Optimizer Mar 12 '15 at 12:47
  • \$\begingroup\$ I'm not familiar with Pyth, so could you elaborate why N+1+1-1? \$\endgroup\$ – seequ Mar 12 '15 at 20:30
  • 1
    \$\begingroup\$ @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)). \$\endgroup\$ – Jakube Mar 12 '15 at 21:12
  • \$\begingroup\$ Or even mhdhN, but that's a complete different approach. \$\endgroup\$ – Jakube Mar 12 '15 at 21:14
4
\$\begingroup\$

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)}
\$\endgroup\$
  • \$\begingroup\$ Where can I test this? I cant seem to find any ES6 playgrounds that accepts this \$\endgroup\$ – Kristoffer Sall-Storgaard Mar 12 '15 at 11:53
  • \$\begingroup\$ @KristofferSall-Storgaard Firefox supports ES6 be default. So Firefox Console. \$\endgroup\$ – Optimizer Mar 12 '15 at 13:42
4
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ You can save one by moving the b+=... into println(b+=...). \$\endgroup\$ – Geobits Mar 12 '15 at 13:15
3
\$\begingroup\$

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

Python 2 - 62 54 65 bytes

def f(n):
 for x in range(n):print' '.join(map(str,range(1,x+2)))
\$\endgroup\$
  • \$\begingroup\$ The number n should be given as input to the program, not initialized in a variable. \$\endgroup\$ – Zgarb Mar 12 '15 at 13:16
  • \$\begingroup\$ Thanks for the hint. Was not sure about that. \$\endgroup\$ – pepp Mar 12 '15 at 13:40
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ – Zgarb Mar 12 '15 at 13:45
  • \$\begingroup\$ So this would be right, right? \$\endgroup\$ – pepp Mar 12 '15 at 21:06
  • \$\begingroup\$ Looks good now! \$\endgroup\$ – Zgarb Mar 12 '15 at 21:50
3
\$\begingroup\$

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.
\$\endgroup\$
  • \$\begingroup\$ Now that's quite smart. +1 \$\endgroup\$ – seequ Mar 21 '15 at 20:37
  • \$\begingroup\$ This is more J-esque but doesn't it violate the rule about there being no trailing spaces on each line? \$\endgroup\$ – miles Jan 21 '17 at 9:16
  • \$\begingroup\$ @miles Indeed it does! Anything else would be very complicated. \$\endgroup\$ – FUZxxl Jan 21 '17 at 14:47
3
\$\begingroup\$

><> (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
\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ 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);}} \$\endgroup\$ – FatalSleep Mar 29 '15 at 9:47
  • 1
    \$\begingroup\$ Pretty nice trick, thanks! \$\endgroup\$ – A. Breust Mar 30 '15 at 8:12
  • \$\begingroup\$ 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. \$\endgroup\$ – FatalSleep Mar 30 '15 at 8:40
  • \$\begingroup\$ 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 \$\endgroup\$ – o79y Jan 22 '17 at 5:29
2
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – jimmy23013 Mar 12 '15 at 15:12
  • \$\begingroup\$ @user23013 OK,fixed! \$\endgroup\$ – Kasrâmvd Mar 12 '15 at 15:15
  • \$\begingroup\$ 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. \$\endgroup\$ – Sp3000 Mar 12 '15 at 16:17
  • \$\begingroup\$ @Sp3000 OK,thanks for attention! fixed!;) \$\endgroup\$ – Kasrâmvd Mar 12 '15 at 16:30
  • \$\begingroup\$ 72: def p(N):print'\n'.join(' '.join(map(str,range(1,i+2)))for i in range(N)) \$\endgroup\$ – seequ Mar 12 '15 at 16:37
2
\$\begingroup\$

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

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

Python

import string
N,s=int(input()),list(string.digits)
for i in range(1,N+1):
    print(' '.join(s[1:i+1]))
\$\endgroup\$
  • 1
    \$\begingroup\$ Doesn't this fail if N >= 10? \$\endgroup\$ – seequ Mar 12 '15 at 13:52
  • \$\begingroup\$ @Sieg Yes you're right. I just learning Python, was looking for way to convert list of int to list of strings. \$\endgroup\$ – bacchusbeale Mar 12 '15 at 17:20
  • \$\begingroup\$ 63 bytes: for i in range(int(input())):print(' '.join("123456789"[:i+1])) - Note that strings are treated as lists. \$\endgroup\$ – seequ Mar 12 '15 at 17:24
1
\$\begingroup\$

Golfscript 14

,{2+,1>' '*n}/

Expects the input number to be present on the stack.

Online example: link

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

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

Go, 93 81 78 93 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

\$\endgroup\$
  • \$\begingroup\$ 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 \$\endgroup\$ – Kristoffer Sall-Storgaard Mar 12 '15 at 14:15
  • \$\begingroup\$ The main problem I see is that it doesn't work for n>9. You can save a byte by changing != to >, though. \$\endgroup\$ – Geobits Mar 12 '15 at 14:49
  • \$\begingroup\$ @Bigtoes, fixed now, I dont know if I'm supposed to count the import statement though \$\endgroup\$ – Kristoffer Sall-Storgaard Mar 12 '15 at 15:04
  • \$\begingroup\$ I know they're counted for the languages I'm more familiar with, so most likely yes. Sucks, I know :) \$\endgroup\$ – Geobits Mar 12 '15 at 15:05
1
\$\begingroup\$

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

enter image description here

\$\endgroup\$
  • 1
    \$\begingroup\$ 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)) \$\endgroup\$ – edc65 Mar 13 '15 at 0:29
1
\$\begingroup\$

R, 28

for(i in 1:scan())print(1:i)
\$\endgroup\$
  • \$\begingroup\$ The output is incorrect for an input value of 0. Also, it's unclear whether the leading [1] on each line is in violation of the spec. \$\endgroup\$ – Alex A. Mar 13 '15 at 1:28
  • \$\begingroup\$ @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! \$\endgroup\$ – freekvd Mar 13 '15 at 20:10
  • \$\begingroup\$ 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.) \$\endgroup\$ – Alex A. Mar 13 '15 at 20:13
  • \$\begingroup\$ 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 [1] on each line. \$\endgroup\$ – Alex A. Mar 13 '15 at 21:28
1
\$\begingroup\$

TI-Basic, 28 bytes

Input N
For(I,1,N
randIntNoRep(1,N->L1
SortA(L1
Disp L1
End
\$\endgroup\$
  • 1
    \$\begingroup\$ This does not output as the format indicates; rather, the array is displayed, brackets and all, on the homescreen. \$\endgroup\$ – lirtosiast May 20 '15 at 1:03
1
\$\begingroup\$

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[999]="",*p=b+1;int c=0;for(;a--&&(sprintf(b,"%s %d",b,++c)&&puts(p)););}
\$\endgroup\$
  • \$\begingroup\$ puts(""); does nothing. You can use char b[999]="" instead of char b[999]={0} to save 1 character. \$\endgroup\$ – mch Mar 12 '15 at 16:14
  • 2
    \$\begingroup\$ puts(""); prints a newline character. \$\endgroup\$ – Felix Bytow Mar 12 '15 at 20:56
1
\$\begingroup\$

Perl: 34 characters

print"@$_\n"for map[1..$_],1..$_;

This code gets the input number supplied through the special variable $_.

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

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

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

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
\$\endgroup\$
  • \$\begingroup\$ Doing e=enumFromTo 1 saves 7 bytes. \$\endgroup\$ – Zgarb Mar 13 '15 at 8:40
  • \$\begingroup\$ @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 \$\endgroup\$ – nimi Mar 14 '15 at 1:47
1
\$\begingroup\$

Mathematica, 32

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

Scala, 73 65 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"))
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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