Stampa triangolo numerico


25

Dato un numero N, genera un triangolo NxN ad angolo retto, dove ogni riga iè riempita con numeri fino a i.

Esempio

n = 0

(nessuna uscita)

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

(nessun allineamento necessario)

n = N

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

Non c'è spazio finale alla fine di ogni riga.

Vince il numero minimo di byte e non sono consentite scappatoie standard.


L'output può essere un elenco nidificato di numeri?
Seequ,

Quale dovrebbe essere il comportamento per n = 0 e per n> 9?
freekvd

@Sieg Sicuro, purché l'output sia corretto.
Tan WS,

@freekvd per 0 non c'è output, per n> 9 non è richiesta una formattazione speciale
Tan WS

Ah dannazione, hai rotto la mia sottomissione. Riparazione al più presto
seequ

Risposte:


17

Joe , 5 3 byte (+2 o +3 per-t bandiera)

Beh, a quanto pare non ho sfruttato appieno il potenziale di Joe. Questo era possibile quando l'ho pubblicato per la prima volta.

\AR

Qui, Rfornisce l'intervallo da 0 a n, in esclusiva. Poi\A prende i successivi prefissi ( Aè la funzione identità). Esempi:

Con -tflag (nota: questo è ora l'output standard anche senza 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

Senza esso:

   \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
[]

Le regole sono state leggermente modificate. Il mio vecchio codice non si comportava correttamente con N = 0. Inoltre, ora l'output potrebbe essere solo un elenco nidificato, quindi -tpuò essere eliminato.

1R1+R

Ora, Rnfornisce un intervallo da 0 a n, esclusivo. Se dato 0, restituisce un elenco vuoto. 1+aggiunge 1 a ogni elemento di quell'intervallo.1Rmappa i valori a intervalli da 1 a x. I collegamenti vuoti, quando mappati, restituiscono elenchi vuoti.

Esempio di output:

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

Aggiornamento: ho appena notato qualcosa. La funzione mappa automaticamente per classificare 0 elementi. L'esempio seguente viene eseguito con -tflag.

   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

Vecchio: 5 byte (con la -tbandiera)

1R1R

Questa è una funzione anonima che accetta un numero, crea un elenco da 1 a N ( 1Rn) e mappa quei valori all'intervallo precedente, fornendo un intervallo da 1 a x per ogni elemento compreso tra 1 e N.

Il -tflag fornisce l'output come una tabella simile a J.

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

Nota: la lingua è molto nuova e non completa, ma l'ultima versione è stata rilasciata prima di questa sfida.


4
Quindi J non era abbastanza per avere un vantaggio sulle sfide basate su array? : D
Ottimizzatore

4
@Optimizer L'ottimizzazione è importante.
Seequ,

4
Improvvisamente, la mia risposta più votata è quella su cui ho trascorso il minor tempo. L'ingiustizia.
Seequ,

1
Immagino che Joe non sia il tuo Joe medio ...
Justin

10

Python 3, 48 45 byte

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

Evviva gli effetti collaterali.


2
Nido annidato. Ora è contorto.
Seequ,

È un trucco intelligente: mettere la funzione prima printdi eseguire la prints in ordine inverso.
xnor

8

APL, 5

⍪⍳¨⍳⎕

crea un vettore 1..n e per ogni elemento un altro vettore del genere.

Quindi ⍪ crea una colonna da tutti i vettori. Questo evita il problema con gli spazi vuoti finali.

Provalo su tryapl.org


Soluzione precedente:

{⎕←⍳⍵}¨⍳⎕

Crea un vettore 1..n

{⎕ ← ⍳⍵} è una funzione che genera per ogni (¨) elemento un vettore 1..n su una linea separata

Purtroppo questo non può essere provato su tryapl.org, perché ⎕ ← non funziona lì.


Non ci dovrebbero essere spazi finali in nessuna riga.
randomra,

ah grazie, mi è mancato quello. Correggerà presto
Moris Zucca il

Sapevo che APL sarebbe stata una soluzione
Conor O'Brien il

Oh Dio, cosa vedono i miei occhi
Codefun64,

6

J, 27 byte

J non è buono con output numerico non array. Questa funzione crea una stringa correttamente formattata dai numeri.

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

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

Provalo online qui.


Puoi anche usare ]\@i.per ottenere;@(<@,&LF@":@:>:@:]\@i.)
seequ

6

PHP, 53 byte

Modifica 2: Ismael Miguel ha suggerito di leggere dall'input invece di definire una funzione, quindi il punteggio ora è 53 byte per PHP:

for($a=1;@$i++<$n=$argv[1];$a.=" ".($i+print"$a\n"));

E ancora una volta, può essere migliorato se PHP è configurato per ignorare gli errori (52 byte):

for($a=1;$i++<$n=$argv[1];$a.=" ".($i+print"$a\n"));
for($a=1;$i++<$n=$_GET[n];$a.=" ".($i+print"$a\n"));

Modifica: Austin ha suggerito una versione di 60 byte nei commenti:

function f($n){for($a=1;@$i++<$n;$a.=" ".($i+print"$a\n"));}

Che può essere migliorato se non visualizziamo errori PHP (59 byte):

function f($n){for($a=1;$i++<$n;$a.=" ".($i+print"$a\n"));}

$amemorizza la riga successiva che verrà stampata e ogni volta che viene stampata uno spazio e il numero successivo ( printrestituisce sempre 1) vengono concatenati.


Funzioni ricorsive (65 byte):

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.

Funzione ricorsiva più breve, con segnalazione errori disabilitata (64 byte):

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

Funzione ricorsiva ancora più breve, con segnalazione errori disabilitata e una riga vuota prima dell'output reale (62 byte):

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

Solo per divertimenti, riprese non ricorsive:

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.

2
45 byte:for($a=1;@$i<$n;$a.=" ".(@++$i+print"$a\n"));
Austin,

@Austin: Ho letto in un commento che il codice deve essere una lettura completa del programma dall'input o una funzione. Trucco molto bello, può essere migliorato di un bit / byte: for($a=1;@$i++<$n;$a.=" ".($i+print"$a\n"));(44 byte)
Benoit Esnard

Ah ok, allora suppongo che lo faresti function f($n){for($a=1;@$i++<$n;$a.=" ".($i+print"$a\n"));}, che è di 60 byte.
Austin,

Infatti. Stai bene se modifico la mia risposta per aggiungere la tua soluzione?
Benoit Esnard,

1
for($a=1;$i++<$n=$_GET[n];$a.=" ".($i+print"$a\n"));-> prova questo (codice completo, usando il parametro url ncon il numero)
Ismael Miguel

5

CJam, 13 12 byte

ri{),:)S*N}/

Come funziona :

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";

Provalo online qui


4

Pyth, 9 byte

VQjdr1hhN

Pensavo davvero che questo potesse essere fatto più breve, ma non sembra così.

Provalo online .

            Q = input()
VQ          For N in [0, 1, ..., Q-1]:
    r1hhN       create list [1, ..., N+1+1-1]
  jd            print joined with spaces

1
Un'alternativa 9: VQaYhNjdY. Se solo arestituisse l'elenco, allora qualcosa del genere VQjdaYhNsarebbe 8.
Sp3000

2
ausato brevemente per restituire l'elenco allegato.
Ottimizzatore

Non ho familiarità con Pyth, quindi potresti spiegare perché N+1+1-1?
Seequ,

1
@Sieg rè la funzione dell'intervallo Python, quindi -1 ( r1Ncrea l'elenco [1, 2, ..., N-1]). Ma nell'iterazione ennesimo del ciclo, voglio la lista [1, 2, ..., N+1], quindi ho bisogno di aggiungere 2a N. r1hhNsi traduce direttamente in range(1, N+1+1). Un'altra possibilità sarebbe r1+N2( range(1, N+2)).
Jakube,

O addirittura mhdhN, ma questo è un approccio completamente diverso.
Jakube,

4

JavaScript (ES6) 49 52

Un compito così semplice, mi chiedo se questo può essere ridotto in JS (Aggiornamento: sì, usando la ricorsione)

Ricorsivo 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)}

Dove posso provarlo? Non riesco a trovare nessun parco giochi ES6 che lo accetti
Kristoffer Sall-Storgaard

@ KristofferSall-Storgaard Firefox supporta ES6 come impostazione predefinita. Quindi Firefox Console.
Ottimizzatore

4

Java, 85 84 byte

Questo è sorprendentemente breve in Java.

void a(int a){String b="";for(int c=0;c++<a;System.out.println(b+=(c>1?" ":"")+c));}

rientrato:

void a(int a){
    String b="";
    for(int c=0;
        c++<a;
        System.out.println(
                b+=(c>1?" ":"")+c
        ));
}

1 byte grazie a Bigtoes / Geobits


Puoi salvarne uno spostando b+=...in println(b+=...).
Geobits

3

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

3

Python 2 - 62 54 65 byte

def f(n):
 for x in range(n):print' '.join(map(str,range(1,x+2)))

Il numero ndeve essere fornito come input per il programma, non inizializzato in una variabile.
Zgarb,

Grazie per il suggerimento. Non ne ero sicuro.
pepp

2
Scusa, avrei dovuto essere più chiaro. Quello che intendevo dire è che devi effettivamente definire Nfacendo N=input()o qualcosa di simile, in modo che il tuo programma possa essere eseguito come tale. Ecco una discussione Meta sull'argomento.
Zgarb,

Quindi questo sarebbe giusto, vero?
pepp

Sembra buono ora!
Zgarb,

3

J, 9 caratteri

Come un tacito verbo monadico.

[:":\1+i.
  • i. y- i numeri da 0a y - 1.
  • 1 + i. y- i numeri da 1a y.
  • ": y- il vettore yrappresentato come una stringa.
  • ":\ y- ogni prefisso di yrappresentato come una stringa.
  • ":\ 1 + i. y- ciascun prefisso dei numeri da 1a yrappresentato come una matrice di caratteri.

Ora è abbastanza intelligente. +1
seequ

Questo è più J-esque ma non viola la regola che non ci siano spazi finali su ogni riga?
miglia

@miles In effetti lo fa! Qualsiasi altra cosa sarebbe molto complicata.
FUZxxl,

3

> <> (Pesce) , 40 37 + 3 = 40 byte

&1>:&:&)?;1\
(?v:n" "o1+>}:{:@
ao\~1+

Ancora una volta,> <> si comporta abbastanza bene in un altro esercizio di stampa numerica. Esegui con il -vflag per l'input, ad es

py -3 fish.py -v 4

Spiegazione

&               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

3

C (senza loop, sì!) - 72 byte

b(n,c){if(n){b(n-1,32);printf("%d%c",n,c);}}r(n){if(n){r(n-1);b(n,10);}}

Questo crea una funzione r(n)che può essere utilizzata in questo modo:

main(){ r(5); }

Guardalo in azione, qui su tutorialspoint.com

Richiede pochissimi trucchi facilmente spiegabili. Penso che possa essere notevolmente migliorato.


1
In realtà sono 75 byte, non 74. Tuttavia, puoi b(n,c){if(n){b(n-1,32);printf("%d%c",n,c);}}r(n){if(n){r(n-1);b(n,10);}}
ridurlo

1
Un bel trucco, grazie!
A. Breust,

Grazie! Ho fatto del mio meglio per sceglierti nella categoria C, ma non potevo accorciare nulla! Quindi ho deciso di accorciare il tuo.
FatalSleep

64 byte b(n,c){n&&b(n-1,32)^printf("%d%c",n,c);}r(n){n&&r(n-1)^b(n,10);} Wandbox
o79y

2

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

Per le risposte su questo sito, è necessario scrivere un programma o una funzione completi. E dovresti stampare il risultato su stdout o restituirli da una funzione. N dovrebbe essere letto dall'input o preso come parametro di funzione, non predefinito come variabile.
jimmy23013,

@ user23013 OK, risolto!
Kasramvd,

La definizione della funzione deve essere inclusa nel conteggio dei byte, quindi non credo che sia 61. Probabilmente è nel tuo interesse chiamare la funzione in modo breve, come p. In un'altra nota, è possibile rimuovere due spazi: uno tra printe '\n'e l'altro tra )))e for.
Sp3000,

@ Sp3000 OK, grazie per l'attenzione! risolto !;)
Kasramvd

72:def p(N):print'\n'.join(' '.join(map(str,range(1,i+2)))for i in range(N))
seequ,

2

Perl, 28 anni

Legge il parametro da stdin.

@x=1..$_,print"@x
"for 1..<>

Dalla riga di comando:

perl -E'$,=$";say 1..$_ for 1..<>'

ma ora non so come contarlo (probabilmente tra 25 e 29).


1

Pitone

import string
N,s=int(input()),list(string.digits)
for i in range(1,N+1):
    print(' '.join(s[1:i+1]))

1
Questo non fallisce se N> = 10?
Seequ,

@Sieg Sì hai ragione. Stavo solo imparando Python, cercavo un modo per convertire un elenco di int in un elenco di stringhe.
bacchusbeale,

63 bytes: for i in range(int(input())):print(' '.join("123456789"[:i+1])) - Note that strings are treated as lists.
seequ


1

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

1

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


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

The main problem I see is that it doesn't work for n>9. You can save a byte by changing != to >, though.
Geobits

@Bigtoes, fixed now, I dont know if I'm supposed to count the import statement though
Kristoffer Sall-Storgaard

I know they're counted for the languages I'm more familiar with, so most likely yes. Sucks, I know :)
Geobits

1

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


1
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

1

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 [1] on each line is in violation of the spec.
Alex A.

@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

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.

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.
Alex A.

1

TI-Basic, 28 bytes

Input N
For(I,1,N
randIntNoRep(1,N->L1
SortA(L1
Disp L1
End

1
This does not output as the format indicates; rather, the array is displayed, brackets and all, on the homescreen.
lirtosiast

1

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)););}

puts(""); does nothing. You can use char b[999]="" instead of char b[999]={0} to save 1 character.
mch

2
puts(""); prints a newline character.
Felix Bytow

1

Perl: 34 characters

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

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


1
Most brackets are redundant here: print"@$_\n"for map[1..$_],1..$_ also works.
nutki

I adjusted the code.
Felix Bytow

1

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

1

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.

1

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

@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


1

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"))
}
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.