Le triangle de Pascal est généré en commençant par un 1 sur la première ligne. Sur les lignes suivantes, le nombre est déterminé par la somme des deux nombres situés directement au-dessus, à gauche et à droite.
Pour démontrer, voici les 5 premières lignes du triangle de Pascal:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Le défi
Étant donné une entrée n (à condition toutefois que cela soit plus pratique dans la langue de votre choix), générez les n premières lignes du triangle de Pascal. Vous pouvez supposer que n est un entier compris entre 1 et 25. Il doit y avoir un saut de ligne entre chaque ligne et un espace entre chaque nombre, mais en dehors de cela, vous pouvez le formater à votre guise.
C'est du code-golf , donc la solution la plus courte gagne.
Exemple I / O
> 1
1
> 9
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
code-golf
math
combinatorics
Peter Olson
la source
la source
Réponses:
J , 12 caractères
la source
i.5
renvoie les cinq premiers produits naturels. La ligne 2 ajoute{:
"Tail" (retour le dernier). La ligne 3 les combine avec!
"Out Of" (nombre de combinaisons). La ligne 4(!{:)i.5
est la même. en tenant compte du crochet. Il en(!:)
va de même pour une opération qui transforme les n premiers naturels en la nième ligne du triangle de Pascal. La ligne 5 l’applique à tous les préfixes (barres obliques inverses) de 0..4, mais J remplit les points inutilisés avec 0; l’opération est donc combinée (@
) avec l’opération de formatage de chaîne":
. Très cool J, upvoted.!
signifie factorial;!
nombre de combinaisons dyadiques . La finale@
in":@(!{:)\@i.
est juste là pour en faire un verbe autonome.Python, 56 octets
Exemple d'utilisation:
Produit:
la source
exec
éviter unefor
boucle.Python,
9491887063 caractèresla source
Mathematica: 36 (41?)
Mathematica a la
Binomial
fonction, mais cela enlève du plaisir à cela. Je propose:La ligne ci-dessus rendra un tableau fragmenté tel que:
Comme il s’agit d’un format de base dans Mathematica, j’ai pensé que ce serait acceptable, mais j’ai lu les règles à nouveau, je pense que ce n’est peut-être pas le cas. L’ajout
Grid@
produira une sortie parfaitement acceptable, pour un total de 41 caractères:n = 6
:la source
C, 522
Une réponse auto-démonstrative en C Ne pourrait pas être plus clair! Points bonus pour trouver le personnage supplémentaire.
la source
Golfscript (21 caractères)
Depuis qu'une explication a été demandée:
la source
Haskell,
9492Sortie:
Une version à 71 caractères qui n'imprime pas d'espace entre chaque numéro:
Sortie:
la source
mapM
place demapM_
.Scala,
81787270 caractères81 caractères: première tentative, copiée sans vergogne depuis la version Python :)
Exécutez-le en tant que script ou directement dans le REPL.
Couper à 70 caractères avec quelque chose de étonnamment lisible et idiomatique:
Ou
7270 caractères avec une méthode totalement différente:la source
Ruby:
514946 caractères(Code de 45 caractères + option de ligne de commande de 1 caractère)
Grâce à:
Échantillon échantillon:
Essayez-le en ligne!
la source
p.map!{|i|(v=n)+n=i}
.map
. Thank you.JavaScript (
90858381)Demo: http://jsfiddle.net/tcRCS/3/
NOTE: Doesn't work well in practice for about n > 30 because numbers overflow built-in integer data type and become floating-point numbers.
Edit 1: removed 5 characters by converting
while
tofor
and combining statementsEdit 2: move
s=
statement insidefor
and save 2 charsEdit 3: combine
s=1,j=1
initializer intos=j=1
and save 2 charsla source
s*(i-j)/j
, nots*((i-j)/j)
.(i-j)
before dividing byj
, then there is no need for floating point arithmetic because the results should always be an integer. If you do((i-j)/j)
first, this will result in decimal values which can be a source of error, and at the very least will require extra code for rounding/truncating. You don't begin to see this until you get to aboutn>11
, and you'll see decimal values in the output, i.e.,1 11 55 165 330 461.99999999999994 461.99999999999994...
R, 39 chars
R seems to be the very right tool for this task :-)
la source
n
is given? I corrected the code. Is this now OK?n
must be supplied from an external source at run time and the apparatus for capturing it is included in your program. Typically, that means by command line argument, or stdin, or file. By file is almost never used because it's invariably longer than the other two options.in Q (25 characters/20 with shorter version)
Shorter
Sample usage:
la source
t:{(x-1){0+':x,0}\1}
awk - 73 chars
fairly straightforward implementation:
sample run:
la source
Perl,
52, 49 charactersEdit: using
say
instead ofprint
la source
Perl,
4754 charactersIt takes a number from the command line, but doesn't perform any error checks.
Just realized it only works up to n=4. It was some old code I had on my hd.
This works though:
n has to be input into the script though, or it would be one character more.
la source
Keg, 40 bytes
Explained
la source
Perl, 77 Chars
Example input
Example output
la source
C,
132127 charactersla source
Pascal:
216192 characters(Not a real competitor, just an honorific presence.)
Sample run:
la source
MATL, 10 bytes
Language created after this challenge
Try it online!
la source
D
134128 charsoutput for 9 is
taking full advantage of "you may format it however you like"; there is a space between each number and a linebreak
edit repositioned the assignment to
l
to shave of some charsla source
Scala, 131 characters
Takes the input from the command line.
Output for n=10:
la source
0
s :-)?F♯ - 203 characters
My first attempt at a round of code golf, and first attempt at functional programming. There is probably some obvious way to shorten it I haven't quite figured out yet. It complies in VS2010s F♯ compiler (which has the effect of running #light by default unlike earlier versions), and also works in the F♯ interpreter. Accepts input via stdin. Wish there was a better way for the input/output though! Lots of characters!
la source
Why is there no accepted answer to this question?
VBA - 249 chars
la source
postscript - 59 chars (63 if you count
-dn=
to get the number of rows in)run with
to get
la source
Mathematica 35 chars
Here is the dull and lazy way of slicing Pascal's triangle:
la source
APL,
1915 charactersA bit late to the party, perhaps?
It doesn't beat the J entry, though.
This assumes that the index origin (
⎕IO
) is set to0
. Unfortunately, with an index origin of1
, we need2518 characters:There are two
⍨
s in the code to express my frustration.Demo:
Explanations
Short version:
⍳⍵
(with an index origin of 0) produces an array of the numbers from 0 to⍵-1
inclusive, where⍵
is the right argument to the function.⍳⍵+1
generates all numbers from 0 to⍵
{⍵!⍨⍳⍵+1}
generates⍵
choosek
for every elementk
in⍳⍵+1
. The⍨
(commute) operator swaps the arguments to a function around, such that the right hand argument becomes the left, and vice versa.{⍵!⍨⍳⍵+1}¨⍳⍵
passes each element in⍳⍵
using the¨
(each) operator. The result is a one dimensional array containing the first⍵
rows of the Pascal's Triangle.⍪
takes a one dimensional vector, and makes it a column rather than a row. Each row of the triangle is put on its own line.Long answer:
1-⍨
is placed before an⍳
to replicate an index origin of 0.0,⍳⍵
with an index origin of 1 replicates⍳⍵+1
with an index origin of 0.la source
Maple, 46
Usage:
la source
VBA,
16214210280 bytesSaved 22 bytes thanks to Taylor Scott.
This is an old question now but I saw a shorter solution for VBA.
This is meant to be run in the immediate window. Input is in cell
A1
of the active worksheet. Output is in the active worksheet starting atB2
and using however many cells are required based on the input. TheCOLUMN()>ROW()
check keeps the top right of the triangle blank. TheROW()=2
check makes the first value1
to initiate the triangle. I could have shifted the output down and dropped this check, but it introduces a lot of extraneous output before the actual triangle and I didn't feel that it was in the spirit of the challenge.I originally posted a much more complicated method that calculated every value based on its row and column. All this method does, though, is to use in-cell formulas. I start at
B2
so I can reference the row above it without#REF!
errors. Then, it copies and pastes the same formula over a block of cells n wide and n tall. The input and output forn=25
looks like this:la source
Function p(r)
toSub p(r)
since you have no function output value, removing the space fromdebug.? c(n,k);
and converting the multilineif-then-else
statement to a single line (If k Then c=c(n-1,k-1)*n/k Else c=1
) brings the byte-count down to130
by my countFor n=0 To...
can be condensed toFor n=0To...
bringing my version of the code toSub p(r):For n=0To r-1:For k=0To n:Debug.?c(n,k);:Next:Debug.?:Next:End Sub
Function c(n,k):If k Then c=1 Else c=c(n-1,k-1)*n/k
[char(10)]End Function
with a byte count of139
For n=0To[A1-1]:For k=0To n:?c(n,k);:Next:?:Next
Helper Function:Function c(n,k)
If k Then c=c(n-1,k-1)*n/k Else c=1
End Function
)B2
instead ofA1
is acceptable.05AB1E, 14 bytes
Try it online!
la source