Pascal's triangle: Difference between revisions

From Rosetta Code
Content added Content deleted
(→‎{{header|PHP}}: This code wasn't right. The example asks for ten rows and the code is two off. The 2nd number of the last row should be the function argument int. I have corrected the code.)
Line 1,021: Line 1,021:
1 7 15 23 23 15 7 1
1 7 15 23 23 15 7 1
</pre>
</pre>

=={{header|K}}==
<lang K> pascal:{(x-1){+':0,x,0}\1}

pascal 6
(1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1)</lang>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==

Revision as of 13:30, 20 November 2011

Task
Pascal's triangle
You are encouraged to solve this task according to the task description, using any language you may know.

Pascal's triangle is an interesting math concept. Its first few rows look like this:

   1
  1 1
 1 2 1
1 3 3 1

where each element of each row is either 1 or the sum of the two elements right above it. For example, the next row would be 1 (since the first element of each row doesn't have two elements above it), 4 (1 + 3), 6 (3 + 3), 4 (3 + 1), and 1 (since the last element of each row doesn't have two elements above it). Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.

Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1). This can be done either by summing elements from the previous rows or using a binary coefficient or combination function. Behavior for n <= 0 does not need to be uniform, but should be noted.

Ada

<lang ada>with Ada.Integer_Text_Io; use Ada.Integer_Text_Io; with Ada.Text_Io; use Ada.Text_Io;

procedure Pascals_Triangle is

  type Row is array(Positive range <>) of Integer;
  type Row_Access is access Row;
  type Triangle is array(Positive range <>) of Row_Access;
  function General_Triangle(Depth : Positive) return Triangle is
     Result : Triangle(1..Depth);
  begin
     for I in Result'range loop
        Result(I) := new Row(1..I);
        for J in 1..I loop
           if J = Result(I)'First or else J = Result(I)'Last then
              Result(I)(J) := 1;
           else
              Result(I)(J) := Result(I - 1)(J - 1) + Result(I - 1)(J);
           end if; 
        end loop;
     end loop;
     return Result;
  end General_Triangle;
  procedure Print(Item : Triangle) is
  begin
     for I in Item'range loop
        for J in 1..I loop
           Put(Item => Item(I)(J), Width => 3);
        end loop;
        New_Line;
     end loop;
  end Print;

begin

  Print(General_Triangle(7));

end Pascals_Triangle;</lang>

ALGOL 68

<lang algol68>PRIO MINLWB = 8, MAXUPB = 8; OP MINLWB = ([]INT a,b)INT: (LWB a<LWB b|LWB a|LWB b),

  MAXUPB = ([]INT a,b)INT: (UPB a>UPB b|UPB a|UPB b);

OP + = ([]INT a,b)[]INT:(

 [a MINLWB b:a MAXUPB b]INT out; FOR i FROM LWB out TO UPB out DO out[i]:= 0 OD;
 out[LWB a:UPB a] := a; FOR i FROM LWB b TO UPB b DO out[i]+:= b[i] OD;
 out

);

INT width = 4, stop = 9; FORMAT centre = $n((stop-UPB row+1)*width OVER 2)(q)$;

FLEX[1]INT row := 1; # example of rowing # FOR i WHILE

 printf((centre, $g(-width)$, row, $l$));
  1. WHILE # i < stop DO
 row := row[AT 1] + row[AT 2]

OD</lang> Output:

                    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

APL

Pascal' s triangle of order ⍵

<lang apl> {A←0,⍳⍵ ⋄ ⍉A∘.!A} </lang>

example

<lang apl> {A←0,⍳⍵ ⋄ ⍉A∘.!A} 3 </lang>

1 0 0 0
1 1 0 0
1 2 1 0
1 3 3 1

AutoHotkey

ahk forum: discussion <lang AutoHotkey>n := 8, p0 := "1"  ; 1+n rows of Pascal's triangle Loop %n% {

  p := "p" A_Index, %p% := v := 1, q := "p" A_Index-1
  Loop Parse, %q%, %A_Space%
     If (A_Index > 1)
        %p% .= " " v+A_LoopField, v := A_LoopField
  %p% .= " 1"

}

                        ; Triangular Formatted output

VarSetCapacity(tabs,n,Asc("`t")) t .= tabs "`t1" Loop %n% {

  t .= "`n" SubStr(tabs,A_Index)
  Loop Parse, p%A_Index%, %A_Space%
     t .= A_LoopField "`t`t"

} Gui Add, Text,, %t%  ; Show result in a GUI Gui Show Return

GuiClose:

 ExitApp</lang>


AWK

<lang awk>$ awk 'BEGIN{for(i=0;i<6;i++){c=1;r=c;for(j=0;j<i;j++){c*=(i-j)/(j+1);r=r" "c};print r}}' 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1</lang>

BASIC

Summing from Previous Rows

Works with: FreeBASIC

This implementation uses an array to store one row of the triangle. DIM initializes the array values to zero. For first row, "1" is then stored in the array. To calculate values for next row, the value in cell (i-1) is added to each cell (i). This summing is done from right to left so that it can be done on-place, without using a tmp buffer. Because of symmetry, the values can be displayed from left to right.

Space for max 5 digit numbers is reserved when formatting the display. The maximum size of triangle is 100 rows, but in practice it is limited by screen space. If the user enters value less than 1, the first row is still always displayed.

<lang freebasic>DIM i AS Integer DIM row AS Integer DIM nrows AS Integer DIM values(100) AS Integer

INPUT "Number of rows: "; nrows values(1) = 1 PRINT TAB((nrows)*3);" 1" FOR row = 2 TO nrows

   PRINT TAB((nrows-row)*3+1);
   FOR i = row TO 1 STEP -1
       values(i) = values(i) + values(i-1)
       PRINT USING "##### "; values(i);
   NEXT i
   PRINT

NEXT row</lang>

BBC BASIC

<lang bbcbasic> nrows% = 10

     colwidth% = 4
     @% = colwidth% : REM Set column width
     FOR row% = 1 TO nrows%
       PRINT SPC(colwidth%*(nrows% - row%)/2);
       acc% = 1
       FOR element% = 1 TO row%
         PRINT acc%;
         acc% = acc% * (row% - element%) / element% + 0.5
       NEXT
       PRINT
     NEXT row%</lang>

Output:

                     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
   1   9  36  84 126 126  84  36   9   1

C

Translation of: Fortran

<lang c>#include <stdio.h>

void pascaltriangle(unsigned int n) {

 unsigned int c, i, j, k;
 for(i=0; i < n; i++) {
   c = 1;
   for(j=1; j <= 2*(n-1-i); j++) printf(" ");
   for(k=0; k <= i; k++) {
     printf("%3d ", c);
     c = c * (i-k)/(k+1);
   }
   printf("\n");
 }

}

int main() {

 pascaltriangle(8);
 return 0;

}</lang>

Recursive

<lang c>#include <stdio.h>

  1. define D 32

int pascals(int *x, int *y, int d) { int i; for (i = 1; i < d; i++) printf("%d%c", y[i] = x[i - 1] + x[i], i < d - 1 ? ' ' : '\n');

return D > d ? pascals(y, x, d + 1) : 0; }

int main() { int x[D] = {0, 1, 0}, y[D] = {0}; return pascals(x, y, 0); }</lang>

C++

<lang cpp>#include <iostream>

  1. include <algorithm>
  2. include <vector>
  3. include <iterator>

void genPyrN(int rows) {

 if (rows < 0) return;
 // save the last row here
 std::vector<int> last(1, 1);
 std::cout << last[0] << std::endl;
 
 for (int i = 1; i <= rows; i++) {
   // work on the next row
   std::vector<int> thisRow;
   thisRow.reserve(i+1);
   thisRow.push_back(last.front()); // beginning of row
   std::transform(last.begin(), last.end()-1, last.begin()+1, std::back_inserter(thisRow), std::plus<int>()); // middle of row
   thisRow.push_back(last.back()); // end of row
   for (int j = 0; j <= i; j++)
     std::cout << thisRow[j] << " ";
   std::cout << std::endl;
   last.swap(thisRow);
 }

}</lang>

C#

Translation of: Fortran

Produces no output when n is less than or equal to zero.

<lang csharp>using System;

namespace RosettaCode {

   class PascalsTriangle {
       public void CreateTriangle(int n) {
           if (n > 0) {
               for (int i = 0; i < n; i++) {
                   int c = 1;
                   Console.Write(" ".PadLeft(2 * (n - 1 - i)));
                   for (int k = 0; k <= i; k++) {
                       Console.Write("{0}", c.ToString().PadLeft(3));
                       c = c * (i - k) / (k + 1);
                   }
                   Console.WriteLine();
               }
           }
       }
   }

}</lang>

Clojure

For n < 1, prints nothing, always returns nil. Copied from the Common Lisp implementation below, but with local functions and explicit tail-call-optimized recursion (recur). <lang lisp>(defn pascal [n]

 (let [newrow (fn newrow [lst ret]
                  (if lst
                      (recur (rest lst)
                             (conj ret (+ (first lst) (or (second lst) 0))))
                      ret))
       genrow (fn genrow [n lst]
                  (when (< 0 n)
                    (do (println lst)
                        (recur (dec n) (conj (newrow lst []) 1)))))]
   (genrow n [1])))

(pascal 4)</lang> And here's another version, using the partition function to produce the sequence of pairs in a row, which are summed and placed between two ones to produce the next row: <lang lisp> (defn nextrow [row]

 (vec (concat [1] (map #(apply + %) (partition 2 1 row)) [1] )))

(defn pascal [n]

 (assert (and (integer? n) (pos? n)))
 (let [triangle (take n (iterate nextrow [1]))]
   (doseq [row triangle]
     (println row))))

</lang> The assert form causes the pascal function to throw an exception unless the argument is (integral and) positive.

Here's a third version using the iterate function <lang lisp> (def pascal

 (iterate
   (fn [prev-row]
     (->>
       (concat (first prev-row) (partition 2 1 prev-row) (last prev-row))
       (map (partial apply +) ,,,)))
    [1]))

</lang>

Common Lisp

To evaluate, call (pascal n). For n < 1, it simply returns nil.

<lang lisp>(defun pascal (n)

  (genrow n '(1)))

(defun genrow (n l)

  (when (< 0 n)
      (print l)
      (genrow (1- n) (cons 1 (newrow l)))))

(defun newrow (l)

  (if (> 2 (length l))
     '(1)
     (cons (+ (car l) (cadr l)) (newrow (cdr l)))))</lang>

D

<lang d>int[][] pascalsTriangle(int rows) {

   auto tri = new int[][rows];
   foreach (r; 0 .. rows) {
       int v = 1;
       foreach (c; 0 .. r+1) {
           tri[r] ~= v;
           v = (v * (r - c)) / (c + 1);
       }
   }
   return tri;

}

void main() {

   auto t = pascalsTriangle(10);
   assert(t == [[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],
 [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]]);

}</lang> Functional style: <lang d>import std.stdio, std.algorithm, std.range;

auto pascal(int n) {

  auto p = 1;
  foreach (_; 1 .. n)
     p ~= array(map!q{a[0] + a[1]}(zip(p[$-1] ~ 0, 0 ~ p[$-1])));
  return p;

}

void main() {

   writeln(pascal(5));

}</lang> Output:

[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]

There is similarity between Pascal's triangle and Sierpinski triangle. Their difference are the initial line and the operation that act on the line element to produce next line. The following is a generic pascal's triangle implementation for positive number of lines output (n). <lang d>import std.stdio, std.string, std.format : fmx = format;

string Pascal(alias dg, T, T initValue)(int n) {

 string output;
 void append(T[] l) {
   output ~= repeat(" ", (n - l.length + 1)*2);
   foreach(e; l) output ~= fmx("%4s", fmx("%4s",e));
   output ~= "\n";
 }
 if(n > 0) {
   T[][] lines = initValue;
   append(lines[0]);
   for(int i = 1; i < n; i++) {
     lines ~= lines[i-1] ~ initValue; // length + 1
     for(int j = 1; j < lines[i-1].length; j++)
       lines[i][j] = dg(lines[i-1][j], lines[i-1][j-1]);
     append(lines[i]);
   }
 }
 return output;

}

string delegate(int n) GenericPascal(alias dg, T, T initValue)(){

 mixin Pascal!(dg, T, initValue);
 return &Pascal;

}

char xor(char a, char b) { return a == b ? '_' : '*'; }

void main() {

 auto pascal = GenericPascal!((int a, int b){return a + b;}, int, 1);
 auto sierpinski = GenericPascal!(xor, char, '*');
 foreach(i; [1,5,9])  writef(pascal(i));
 // an order 4 sierpinski triangle is a 2^4 lines generic
 // pascal triangle with xor operation
 foreach(i; [16]) writef(sierpinski(i));

}</lang> Output:

     1
             1
           1   1
         1   2   1
       1   3   3   1
     1   4   6   4   1
                     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
                                   *
                                 *   *
                               *   _   *
                             *   *   *   *
                           *   _   _   _   *
                         *   *   _   _   *   *
                       *   _   *   _   *   _   *
                     *   *   *   *   *   *   *   *
                   *   _   _   _   _   _   _   _   *
                 *   *   _   _   _   _   _   _   *   *
               *   _   *   _   _   _   _   _   *   _   *
             *   *   *   *   _   _   _   _   *   *   *   *
           *   _   _   _   *   _   _   _   *   _   _   _   *
         *   *   _   _   *   *   _   _   *   *   _   _   *   *
       *   _   *   _   *   _   *   _   *   _   *   _   *   _   *
     *   *   *   *   *   *   *   *   *   *   *   *   *   *   *   *

E

So as not to bother with text layout, this implementation generates a HTML fragment. It uses a single mutable array, appending one 1 and adding to each value the preceding value.

<lang e>def pascalsTriangle(n, out) {

   def row := [].diverge(int)

out.print("

") for y in 1..n { out.print("") row.push(1) def skip := n - y if (skip > 0) { out.print(``)
       }
       for x => v in row {
out.print(``)
       }
       for i in (1..!y).descending() {
           row[i] += row[i - 1]
       }
out.println("") } out.print("
$v

")

}</lang>

<lang e>def out := <file:triangle.html>.textWriter() try {

   pascalsTriangle(15, out)

} finally {

   out.close()

} makeCommand("yourFavoriteWebBrowser")("triangle.html")</lang>

Erlang

<lang erlang> -import(lists). -export([pascal/1]).

pascal(1)-> 1; pascal(N) ->

   L = pascal(N-1),
   [H|_] = L,
   [lists:zipwith(fun(X,Y)->X+Y end,[0]++H,H++[0])|L].

</lang>

Euphoria

Summing from Previous Rows

<lang Euphoria>sequence row row = {} for m = 1 to 10 do

   row = row & 1
   for n = length(row)-1 to 2 by -1 do
       row[n] += row[n-1]
   end for
   print(1,row)
   puts(1,'\n')

end for</lang>

Output:

{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}
{1,9,36,84,126,126,84,36,9,1}

F#

<lang fsharp>let rec nextrow l =

   match l with
   | []      -> []
   | h :: [] -> [1]
   | h :: t  -> h + t.Head :: nextrow t
  

let pascalTri n = List.scan(fun l i -> 1 :: nextrow l) [1] [1 .. n]

for row in pascalTri(10) do

   for i in row do
       printf "%s" (i.ToString() + ", ")
   printfn "%s" "\n"

</lang>

Factor

This implementation works by summing the previous line content. Result for n < 1 is the same as for n == 1.

<lang factor>USING: grouping kernel math sequences ;

(pascal) ( seq -- newseq )
   dup last 0 prefix 0 suffix 2 <clumps> [ sum ] map suffix ;
pascal ( n -- seq )
   1 - { { 1 } } swap [ (pascal) ] times ;</lang>

It works as:

<lang factor>5 pascal . { { 1 } { 1 1 } { 1 2 1 } { 1 3 3 1 } { 1 4 6 4 1 } }</lang>

Forth

<lang forth>: init ( n -- )

 here swap cells erase  1 here ! ;
.line ( n -- )
 cr here swap 0 do dup @ . cell+ loop drop ;
next ( n -- )
 here swap 1- cells here + do
   i @ i cell+ +!
 -1 cells +loop ;
pascal ( n -- )
     dup init   1  .line
 1 ?do i next i 1+ .line loop ;</lang>

This is a bit more efficient.

Translation of: C

<lang forth>: PascTriangle

 cr dup 0
 ?do
    1 over 1- i - 2* spaces i 1+ 0 ?do dup 4 .r j i - * i 1+ / loop cr drop
 loop drop

13 PascTriangle</lang>

Fortran

Works with: Fortran version 90 and later

Prints nothing for n<=0. Output formatting breaks down for n>20 <lang fortran>PROGRAM Pascals_Triangle

 CALL Print_Triangle(8)

END PROGRAM Pascals_Triangle

SUBROUTINE Print_Triangle(n)

 IMPLICIT NONE
 INTEGER, INTENT(IN) :: n
 INTEGER :: c, i, j, k, spaces
 DO i = 0, n-1
    c = 1
    spaces = 3 * (n - 1 - i)
    DO j = 1, spaces
       WRITE(*,"(A)", ADVANCE="NO") " "
    END DO
    DO k = 0, i
       WRITE(*,"(I6)", ADVANCE="NO") c
       c = c * (i - k) / (k + 1)
    END DO
    WRITE(*,*)
 END DO

END SUBROUTINE Print_Triangle</lang>

GAP

<lang gap>Pascal := function(n) local i, v; v := [1]; for i in [1 .. n] do Display(v); v := Concatenation([0], v) + Concatenation(v, [0]); od; end;

Pascal(9);

  1. [ 1 ]
  2. [ 1, 1 ]
  3. [ 1, 2, 1 ]
  4. [ 1, 3, 3, 1 ]
  5. [ 1, 4, 6, 4, 1 ]
  6. [ 1, 5, 10, 10, 5, 1 ]
  7. [ 1, 6, 15, 20, 15, 6, 1 ]
  8. [ 1, 7, 21, 35, 35, 21, 7, 1 ]
  9. [ 1, 8, 28, 56, 70, 56, 28, 8, 1 ]</lang>

Go

No output for n < 1. Otherwise, output formatted left justified. <lang go> package main

import "fmt"

func printTriangle(n int) {

   // degenerate cases
   if n <= 0 {
       return
   }
   fmt.Println(1)
   if n == 1 {
       return
   }
   // iterate over rows, zero based
   a := make([]int, (n+1)/2)
   a[0] = 1
   for row, middle := 1, 0; row < n; row++ {
       // generate new row
       even := row&1 == 0
       if even {
           a[middle+1] = a[middle] * 2
       }
       for i := middle; i > 0; i-- {
           a[i] += a[i-1]
       }
       // print row
       for i := 0; i <= middle; i++ {
           fmt.Print(a[i], " ")
       }
       if even {
           middle++
       }
       for i := middle; i >= 0; i-- {
           fmt.Print(a[i], " ")
       }
       fmt.Println("")
   }

}

func main() {

   printTriangle(4)

} </lang> Output:

1
1 1
1 2 1
1 3 3 1

Groovy

Recursive

In the spirit of the Haskell "think in whole lists" solution here is a list-driven, minimalist solution: <lang groovy>def pascal = { n -> (n <= 1) ? [1] : GroovyCollections.transpose([[0] + pascal(n - 1), pascal(n - 1) + [0]]).collect { it.sum() } }</lang> However, this solution is horribly inefficient (O(n**2)). It slowly grinds to a halt on a reasonably powerful PC after about line 25 of the triangle.

Test program: <lang groovy>def count = 15 (1..count).each { n ->

   printf ("%2d:", n); (0..(count-n)).each { print "    " }; pascal(n).each{ printf("%6d  ", it) }; println ""

}</lang>

Output:

 1:                                                                 1  
 2:                                                             1       1  
 3:                                                         1       2       1  
 4:                                                     1       3       3       1  
 5:                                                 1       4       6       4       1  
 6:                                             1       5      10      10       5       1  
 7:                                         1       6      15      20      15       6       1  
 8:                                     1       7      21      35      35      21       7       1  
 9:                                 1       8      28      56      70      56      28       8       1  
10:                             1       9      36      84     126     126      84      36       9       1  
11:                         1      10      45     120     210     252     210     120      45      10       1  
12:                     1      11      55     165     330     462     462     330     165      55      11       1  
13:                 1      12      66     220     495     792     924     792     495     220      66      12       1  
14:             1      13      78     286     715    1287    1716    1716    1287     715     286      78      13       1  
15:         1      14      91     364    1001    2002    3003    3432    3003    2002    1001     364      91      14       1  

GW-BASIC

<lang qbasic>10 INPUT "Number of rows? ",R 20 FOR I=0 TO R-1 30 C=1 40 FOR K=0 TO I 50 PRINT USING "####";C; 60 C=C*(I-K)/(K+1) 70 NEXT 80 PRINT 90 NEXT</lang>

Output:

Number of rows? 7
   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

Haskell

An approach using the "think in whole lists" principle: Each row in the triangle can be calculated from the previous row by adding a shifted version of itself to it, keeping the ones at the ends. The Prelude function zipWith can be used to add two lists, but it won't keep the old values when one list is shorter. So we need a similar function

<lang haskell>zapWith :: (a -> a -> a) -> [a] -> [a] -> [a] zapWith f xs [] = xs zapWith f [] ys = ys zapWith f (x:xs) (y:ys) = f x y : zapWith f xs ys</lang>

Now we can shift a list and add it to itself, extending it by keeping the ends:

<lang haskell>extendWith f [] = [] extendWith f xs@(x:ys) = x : zapWith f xs ys</lang>

And for the whole (infinite) triangle, we just iterate this operation, starting with the first row:

<lang haskell>pascal = iterate (extendWith (+)) [1]</lang>

For the first n rows, we just take the first n elements from this list, as in

<lang haskell>*Main> take 6 pascal [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1],[1,5,10,10,5,1]]</lang>

A shorter approach, plagiarized from [1] <lang haskell>-- generate next row from current row nextRow row = zipWith (+) ([0] ++ row) (row ++ [0])

-- returns the first n rows pascal = iterate nextRow [1]</lang>

HicEst

<lang HicEst> CALL Pascal(30)

SUBROUTINE Pascal(rows)

  CHARACTER fmt*6
  WRITE(Text=fmt, Format='"i", i5.5') 1+rows/4
  DO row = 0, rows-1
    n = 1
    DO k = 0, row
      col = rows*(rows-row+2*k)/4
      WRITE(Row=row+1, Column=col, F=fmt) n
      n = n * (row - k) / (k + 1)
    ENDDO
  ENDDO

END</lang>

Icon and Unicon

The code below is slightly modified from the library version of pascal which prints 0's to the full width of the carpet. It also presents the data as an isoceles triangle. <lang Icon>link math

procedure main(A) every n := !A do { # for each command line argument

  n := integer(\n) | &null
  pascal(n)
  }

end

procedure pascal(n) #: Pascal triangle

  /n := 16
  write("width=", n, " height=", n)	# carpet header
  fw := *(2 ^ n)+1
  every i := 0 to n - 1 do {
     writes(repl(" ",fw*(n-i)/2))
     every j := 0 to n - 1 do
        writes(center(binocoef(i, j),fw) | break)
     write()
     }

end</lang>

math provides binocoef math provides the original version of pascal

Sample output:

->pascal 1 4 8
width=1 height=1
 1 
width=4 height=4
       1 
     1  1 
    1  2  1 
  1  3  3  1 
width=8 height=8
                 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  
->

IDL

<lang IDL>Pro Pascal, n

n is the number of lines of the triangle to be displayed
r=[1]
print, r
 for i=0, (n-2) do begin
   pascalrow,r
 endfor

End

Pro PascalRow, r

 for i=0,(n_elements(r)-2) do begin 
   r[i]=r[i]+r[i+1]
 endfor

r= [1, r] print, r

End</lang>

J

<lang j>  !~/~ i.5 1 0 0 0 0 1 1 0 0 0 1 2 1 0 0 1 3 3 1 0 1 4 6 4 1</lang>

<lang j> ([: ":@-.&0"1 !~/~)@i. 5 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1</lang>

<lang j> (-@|. |."_1 [: ":@-.&0"1 !~/~)@i. 5

    1    
   1 1   
  1 2 1  
 1 3 3 1 
1 4 6 4 1</lang>

See the talk page for explanation of earlier version

Java

Summing from Previous Rows

Works with: Java version 1.5+

<lang java>import java.util.ArrayList; ...//class definition, etc. public static void genPyrN(int rows){ if(rows < 0) return; //save the last row here ArrayList<Integer> last = new ArrayList<Integer>(); last.add(1); System.out.println(last); for(int i= 1;i <= rows;++i){ //work on the next row ArrayList<Integer> thisRow= new ArrayList<Integer>(); thisRow.add(last.get(0)); //beginning for(int j= 1;j < i;++j){//loop the number of elements in this row //sum from the last row thisRow.add(last.get(j - 1) + last.get(j)); } thisRow.add(last.get(i)); //end last= thisRow;//save this row System.out.println(thisRow); } }</lang>

Combinations

This method is limited to 21 rows because of the limits of long. Calling pas with an argument of 22 or above will cause intermediate math to wrap around and give false answers. <lang java>public class Pas{ public static void main(String[] args){ //usage pas(20); }

public static void pas(int rows){ for(int i = 0; i < rows; i++){ for(int j = 0; j <= i; j++){ System.out.print(ncr(i, j) + " "); } System.out.println(); } }

public static long ncr(int n, int r){ return fact(n) / (fact(r) * fact(n - r)); }

public static long fact(int n){ long ans = 1; for(int i = 2; i <= n; i++){ ans *= i; } return ans; } }</lang>

JavaScript

Works with: SpiderMonkey
Works with: V8

<lang javascript>// Pascal's triangle object function pascalTriangle (rows) {

// Number of rows the triangle contains this.rows = rows;

// The 2D array holding the rows of the triangle this.triangle = new Array(); for (var r = 0; r < rows; r++) { this.triangle[r] = new Array(); for (var i = 0; i <= r; i++) { if (i == 0 || i == r) this.triangle[r][i] = 1; else this.triangle[r][i] = this.triangle[r-1][i-1]+this.triangle[r-1][i]; } }

// Method to print the triangle this.print = function(base) { if (!base) base = 10;

// Private method to calculate digits in number var digits = function(n,b) { var d = 0; while (n >= 1) { d++; n /= b; } return d; }

// Calculate max spaces needed var spacing = digits(this.triangle[this.rows-1][Math.round(this.rows/2)],base);

// Private method to add spacing between numbers var insertSpaces = function(s) { var buf = ""; while (s > 0) { s--; buf += " "; } return buf; }

// Print the triangle line by line for (var r = 0; r < this.triangle.length; r++) { var l = ""; for (var s = 0; s < Math.round(this.rows-1-r); s++) { l += insertSpaces(spacing); } for (var i = 0; i < this.triangle[r].length; i++) { if (i != 0) l += insertSpaces(spacing-Math.ceil(digits(this.triangle[r][i],base)/2)); l += this.triangle[r][i].toString(base); if (i < this.triangle[r].length-1) l += insertSpaces(spacing-Math.floor(digits(this.triangle[r][i],base)/2)); } print(l); } }

}

// Display 4 row triangle in base 10 var tri = new pascalTriangle(4); tri.print(); // Display 8 row triangle in base 16 tri = new pascalTriangle(8); tri.print(16);</lang> Output:

$ d8 pascal.js 
   1
  1 1
 1 2 1
1 3 3 1
              1
            1   1
          1   2   1
        1   3   3   1
      1   4   6   4   1
    1   5   a   a   5   1
  1   6   f   14  f   6   1
1   7   15  23  23  15  7   1

K

<lang K> pascal:{(x-1){+':0,x,0}\1}

  pascal 6

(1

1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1)</lang>

Liberty BASIC

<lang lb>input "How much rows would you like? "; n dim a$(n)

for i= 0 to n

      c = 1
      o$ =""
      for k =0 to i
            o$ =o$ ; c; " "
            c =c *(i-k)/(k+1)
      next k
      a$(i)=o$

next i

maxLen = len(a$(n)) for i= 0 to n

   print space$((maxLen-len(a$(i)))/2);a$(i)

next i

end</lang>

Locomotive Basic

<lang locobasic>10 CLS 20 INPUT "Number of rows? ", rows:GOSUB 40 30 END 40 FOR i=0 TO rows-1 50 c=1 60 FOR k=0 TO i 70 PRINT USING "####";c; 80 c=c*(i-k)/(k+1) 90 NEXT 100 PRINT 110 NEXT 120 RETURN</lang>

Output:

Number of rows? 7
   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

<lang logo>to pascal :n

 if :n = 1 [output [1]]
 localmake "a pascal :n-1
 output (sentence first :a (map "sum butfirst :a butlast :a) last :a)

end

for [i 1 10] [print pascal :i]</lang>

Lua

<lang lua> function nextrow(t)

 local ret = {}
 t[0], t[#t+1] = 0, 0
 for i = 1, #t do ret[i] = t[i-1] + t[i] end
 return ret

end

function triangle(n)

 t = {1}
 for i = 1, n do
   print(unpack(t))
   t = nextrow(t)
 end

end </lang>

Metafont

(The formatting starts to be less clear when numbers start to have more than two digits)

<lang metafont>vardef bincoeff(expr n, k) = save ?; ? := (1 for i=(max(k,n-k)+1) upto n: * i endfor )

    / (1 for i=2 upto min(k, n-k): * i endfor); ?

enddef;

def pascaltr expr c =

 string s_;
 for i := 0 upto (c-1):
   s_ := "" for k=0 upto (c-i): & "  " endfor;
   s_ := s_ for k=0 upto i: & decimal(bincoeff(i,k))
            & "  " if bincoeff(i,k)<9: & " " fi endfor;
   message s_;
 endfor

enddef;

pascaltr(4); end</lang>

Nial

Like J

(pascal.nial) <lang nial>factorial is recur [ 0 =, 1 first, pass, product, -1 +] combination is fork [ > [first, second], 0 first,

  / [factorial second, * [factorial - [second, first], factorial first] ]

] pascal is transpose each combination cart [pass, pass] tell</lang> Using it <lang nial>|loaddefs 'pascal.nial' |pascal 5</lang>

OCaml

<lang ocaml>(* generate next row from current row *) let next_row row =

 List.map2 (+) ([0] @ row) (row @ [0])

(* returns the first n rows *) let pascal n =

 let rec loop i row =
   if i = n then []
   else row :: loop (i+1) (next_row row)
 in loop 0 [1]</lang>

Octave

<lang octave>function pascaltriangle(h)

 for i = 0:h-1
   for k = 0:h-i
     printf("  ");
   endfor
   for j = 0:i
     printf("%3d ", bincoeff(i, j));
   endfor
   printf("\n");
 endfor

endfunction

pascaltriangle(4);</lang>

Oz

<lang oz>declare

 fun {NextLine Xs}
    {List.zip 0|Xs {Append Xs [0]}
     fun {$ Left Right}
        Left + Right
     end}
 end
 fun {Triangle N}
    {List.take {Iterate [1] NextLine} N}
 end
 fun lazy {Iterate I F}
    I|{Iterate {F I} F}
 end
 %% Only works nicely for N =< 5.
 proc {PrintTriangle T}
    N = {Length T}
 in
    for
       Line in T
       Indent in N-1..0;~1
    do
       for _ in 1..Indent do {System.printInfo " "} end
       for L in Line do {System.printInfo L#" "} end
       {System.printInfo "\n"}
    end
 end

in

 {PrintTriangle {Triangle 5}}</lang>

For n = 0, prints nothing. For negative n, throws an exception.

PARI/GP

<lang parigp>pascals_triangle(N)= { my(row=[],prevrow=[]); for(x=1,N,

   if(x>5,break(1));
        row=eval(Vec(Str(11^(x-1))));
        print(row));

prevrow=row; for(y=6,N,

  for(p=2,#prevrow,
        row[p]=prevrow[p-1]+prevrow[p]);
        row=concat(row,1);
        prevrow=row;
        print(row);
    );

}</lang>

Perl

<lang perl>sub pascal

  1. Prints out $n rows of Pascal's triangle. It returns undef for
  2. failure and 1 for success.
 {my $n = shift;
  $n < 1 and return undef;
  print "1\n";
  $n == 1 and return 1;
  my @last = (1);
  foreach my $row (1 .. $n - 1)
     {my @this = map {$last[$_] + $last[$_ + 1]} 0 .. $row - 2;
      @last = (1, @this, 1);
      print join(' ', @last), "\n";}
  return 1;}</lang>

Here is a shorter version using bignum, which is limited to the first 23 rows because of the algorithm used: <lang perl>use bignum; sub pascal { $_[0] ? unpack "A(A6)*", 1000001**$_[0] : 1 } print "@{[map -+-$_, pascal $_]}\n" for 0..22;</lang>

Perl 6

Translation of: Haskell

(the short version)

Works with: Rakudo version #23 "Lisbon"

Nonpositive inputs throw a multiple-dispatch error.

<lang perl6>multi pascal (1) { [1] } multi pascal (Int $n where (* > 1)) {

   my @rows = pascal $n - 1;
   @rows, [( 0, @(@rows[*-1]) ) >>+<< ( @(@rows[*-1]), 0 )];

}

say .perl for pascal 10;</lang>

Translation of: Perl

<lang perl6>sub pascal ($n)

  1. Prints out $n rows of Pascal's triangle.
 {$n < 1 and return Mu;
  say "1";
  $n == 1 and return 1;
  my @last = [1];
  for (1 .. $n - 1) -> $row
     {my @this = map (-> $a {@last[$a] + @last[$a + 1]}), 0 .. $row - 2;
      @last = (1, @this, 1);
      say join(' ', @last) ;}
  return 1;}

</lang>

one-liner

The following routine returns a lazy list of lines using the sequence operator (...). With a lazy result you need not tell the routine how many you want; you can just use a slice subscript to get the first N lines: <lang perl6>sub pascal { [1], -> @p { [0, @p Z+ @p, 0] } ... * }

.say for pascal[^10];</lang>

See http://perlgeek.de/blog-en/perl-6/pascal-triangle.writeback for a partial explanation of how this one-liner example works.

One problem with the routine above is that it might recalculate the sequence each time you call it. Slightly more idiomatic would be to define the sequence as a lazy constant, which gives the compiler more latitude in whether to cache or recalculate intermediate values. (A desperate garbage collector can trim an overly long lazy constant, since it can always be recreated later, assuming the programmer didn't lie about its constancy.) In that sense, this is a better translation of the Haskell too.

Works with: niecza version 2011.07

<lang perl6>constant Pascal = [1], -> @p { [0, @p Z+ @p, 0] } ... *;

.say for Pascal[^10];</lang> Output:

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
1 9 36 84 126 126 84 36 9 1

PHP

<lang php>function pascalsTriangle($num){ $c = 1; $triangle = Array(); for($i=0;$i<=$num;$i++){ $triangle[$i] = Array(); if(!isset($triangle[$i-1])){ $triangle[$i][] = $c; }else{ for($j=0;$j<count($triangle[$i-1])+1;$j++){ $triangle[$i][] = (isset($triangle[$i-1][$j-1]) && isset($triangle[$i-1][$j])) ? $triangle[$i-1][$j-1] + $triangle[$i-1][$j] : $c; } } } return $triangle; }

$tria = pascalsTriangle(8); foreach($tria as $val){ foreach($val as $value){ echo $value . ' '; } echo '
'; }</lang>

                                       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

PL/I

<lang PL/I> declare (t, u)(40) fixed binary; declare (i, n) fixed binary;

t,u = 0; get (n); if n <= 0 then return;

do n = 1 to n;

  u(1) = 1;
  do i = 1 to n;
     u(i+1) = t(i) + t(i+1);
  end;
  put skip edit ((u(i) do i = 1 to n)) (col(40-2*n), (n+1) f(4));
  t = u;

end; </lang>

<lang>

                                       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
                     1   9  36  84 126 126  84  36   9   1
                   1  10  45 120 210 252 210 120  45  10   1

</lang>

PicoLisp

Translation of: C

<lang PicoLisp>(de pascalTriangle (N)

  (for I N
     (space (* 2 (- N I)))
     (let C 1
        (for K I
           (prin (align 3 C) " ")
           (setq C (*/ C (- I K) K)) ) )
     (prinl) ) )</lang>

PowerShell

<lang powershell> $Infinity = 1 $NewNumbers = $null $Numbers = $null $Result = $null $Number = $null $Power = $args[0]

Write-Host $Power

For(

  $i=0;
  $i -lt $Infinity;
  $i++
  )
  {
   $Numbers = New-Object Object[] 1
   $Numbers[0] = $Power
  For(
     $k=0;
     $k -lt $NewNumbers.Length;
     $k++
     )
     {
      $Numbers = $Numbers + $NewNumbers[$k]
     }
  If(
    $i -eq 0
    )
    {
     $Numbers = $Numbers + $Power
    }
   $NewNumbers = New-Object Object[] 0
  Try
  {
  For(
     $j=0;
     $j -lt $Numbers.Length;
     $j++
     )
     {
      $Result = $Numbers[$j] + $Numbers[$j+1]
      $NewNumbers = $NewNumbers + $Result
     }
  }
  Catch [System.Management.Automation.RuntimeException]
  {
   Write-Warning "Value was too large for a Decimal. Script aborted."
   Break;
  }
  Foreach(
         $Number in $Numbers
         )
         {
         If(
           $Number.ToString() -eq "+unendlich"
           )
           {
            Write-Warning "Value was too large for a Decimal. Script aborted."
            Exit
           }
         }
   Write-Host $Numbers
   $Infinity++
  }

</lang>

Save the above code to a .ps1 script file and start it by calling its name and providing N.

PS C:\> & '.\Pascals Triangle.ps1' 1

----

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
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1
1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1
1 14 91 364 1001 2002 3003 3432 3003 2002 1001 364 91 14 1
1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1

Prolog

Difference-lists are used to make quick append. <lang Prolog>pascal(N) :- pascal(1, N, [1], [[1]|X]-X, L), maplist(my_format, L).

pascal(Max, Max, L, LC, LF) :- !, make_new_line(L, NL), append_dl(LC, [NL|X]-X, LF-[]).

pascal(N, Max, L, NC, LF) :- build_new_line(L, NL), append_dl(NC, [NL|X]-X, NC1), N1 is N+1, pascal(N1, Max, NL, NC1, LF).

build_new_line(L, R) :- build(L, 0, X-X, R).

build([], V, RC, RF) :- append_dl(RC, [V|Y]-Y, RF-[]).

build([H|T], V, RC, R) :- V1 is V+H, append_dl(RC, [V1|Y]-Y, RC1), build(T, H, RC1, R).

append_dl(X1-X2, X2-X3, X1-X3).

% to have a correct output ! my_format([H|T]) :- write(H), maplist(my_writef, T), nl.

my_writef(X) :- writef(' %5r', [X]). </lang>

Output : <lang Prolog> ?- pascal(15). 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 1 9 36 84 126 126 84 36 9 1 1 10 45 120 210 252 210 120 45 10 1 1 11 55 165 330 462 462 330 165 55 11 1 1 12 66 220 495 792 924 792 495 220 66 12 1 1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1 1 14 91 364 1001 2002 3003 3432 3003 2002 1001 364 91 14 1 1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1 true. </lang>

PureBasic

<lang PureBasic>Procedure pascaltriangle( n.i)

 For i=  0 To  n
      c = 1
      For k=0 To i
            Print(Str( c)+" ")
        c = c * (i-k)/(k+1);
       Next ;k
   PrintN(" "); nächste zeile
 Next ;i

EndProcedure

OpenConsole() Parameter.i = Val(ProgramParameter(0)) pascaltriangle(Parameter); Input()</lang>

Python

<lang python>def pascal(n):

  """Prints out n rows of Pascal's triangle.
  It returns False for failure and True for success."""
  row = [1]
  k = [0]
  for x in range(max(n,0)):
     print row
     row=[l+r for l,r in zip(row+k,k+row)]
  return n>=1</lang>

Or, by creating a scan function: <lang python>def scan(op, seq, it):

 a = []
 result = it
 a.append(it)
 for x in seq:
   result = op(result, x)
   a.append(result)
 return a

def pascal(n):

   def nextrow(row, x):
       return [l+r for l,r in zip(row+[0,],[0,]+row)]
   return scan(nextrow, range(n-1), [1,])

for row in pascal(4):

   print(row)</lang>

Qi

Translation of: Haskell

<lang Qi> (define iterate

 _ _ 0 -> []
 F V N -> [V|(iterate F (F V) (1- N))])

(define next-row

 R -> (MAPCAR + [0|R] (append R [0])))

(define pascal

 N -> (iterate next-row [1] N))

</lang>

R

Translation of: Octave

<lang R>pascalTriangle <- function(h) {

 for(i in 0:(h-1)) {
   s <- ""
   for(k in 0:(h-i)) s <- paste(s, "  ", sep="")
   for(j in 0:i) {
     s <- paste(s, sprintf("%3d ", choose(i, j)), sep="")
   }
   print(s)
 }

}</lang>

Here's an R version:

<lang R>pascalTriangle <- function(h) {

 lapply(0:h, function(i) choose(i, 0:i))

}</lang>

RapidQ

Summing from Previous Rows

Translation of: BASIC

The main difference to BASIC implementation is the output formatting. RapidQ does not support PRINT USING. Instead, function FORMAT$() is used. TAB() is not supported, so SPACE$() was used instead.

Another difference is that in RapidQ, DIM does not clear array values to zero. But if dimensioning is done with DEF..., you can give the initial values in curly braces. If less values are given than there are elements in the array, the remaining positions are initialized to zero. RapidQ does not require simple variables to be declared before use.

<lang rapidq>DEFINT values(100) = {0,1}

INPUT "Number of rows: "; nrows PRINT SPACE$((nrows)*3);" 1" FOR row = 2 TO nrows

   PRINT SPACE$((nrows-row)*3+1);
   FOR i = row TO 1 STEP -1
       values(i) = values(i) + values(i-1)
       PRINT FORMAT$("%5d ", values(i));
   NEXT i
   PRINT

NEXT row</lang>

Using binary coefficients

Translation of: BASIC

<lang rapidq>INPUT "Number of rows: "; nrows FOR row = 0 TO nrows-1

   c = 1
   PRINT SPACE$((nrows-row)*3);
   FOR i = 0 TO row
       PRINT FORMAT$("%5d ", c);
       c = c * (row - i) / (i+1)
   NEXT i
   PRINT

NEXT row</lang>

Retro

<lang Retro>2 elements i j

pascalTriangle
 cr dup
 [ dup !j 1 swap 1+ [ !i dup putn space @j @i - * @i 1+ / ] iter cr drop ] iter drop

13 pascalTriangle</lang>

REXX

<lang rexx> /*REXX program to display Pascal's triangle, neatly centered/formatted. */

arg n . if n== then call ser "no arguments were specified for Pascal's triangle"

if n<1 | \datatype(n,'W') then

             call ser "N for Pascal's triangle must be a positive integer"

a.=1 mx=!(n-1)/!(n%2)/!(n-1-n%2) /*MX =biggest number in triangle.*/ w=length(mx) /* W =width of biggest number. */ line.=1

 do row=1 for n
 prev=row-1
 a.row.1=1
   do j=2 to row-1
   jm1=j-1
   a.row.j=a.prev.jm1+a.prev.j
   line.row=line.row right(a.row.j,w)
   end
 if row\==1 then line.row=line.row right(1,w)    /*append the last "1".*/
 end

width=length(line.n) /*width of last line in triangle.*/

    do L=1 for n                      /*show lines in Pascal's triangle*/
    say center(line.L,width)
    end

exit

!:procedure;arg x;!=1;do j=2 to x;!=!*j;end;return ! /*calc. factorial*/ </lang> Output when the following was specified:

4

   1
  1 1
 1 2 1
1 3 3 1

Output when the following was specified:

11

                    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
  1   9  36  84 126 126  84  36   9   1
1  10  45 120 210 252 210 120  45  10   1

Output when the following was specified:

15

                                   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
            1    9   36   84  126  126   84   36    9    1
          1   10   45  120  210  252  210  120   45   10    1
       1   11   55  165  330  462  462  330  165   55   11    1
     1   12   66  220  495  792  924  792  495  220   66   12    1
  1   13   78  286  715 1287 1716 1716 1287  715  286   78   13    1
1   14   91  364 1001 2002 3003 3432 3003 2002 1001  364   91   14    1

Output when the following was specified:

22

                                                                         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
                                          1      9     36     84    126    126     84     36      9      1
                                      1     10     45    120    210    252    210    120     45     10      1
                                   1     11     55    165    330    462    462    330    165     55     11      1
                               1     12     66    220    495    792    924    792    495    220     66     12      1
                            1     13     78    286    715   1287   1716   1716   1287    715    286     78     13      1
                        1     14     91    364   1001   2002   3003   3432   3003   2002   1001    364     91     14      1
                     1     15    105    455   1365   3003   5005   6435   6435   5005   3003   1365    455    105     15      1
                 1     16    120    560   1820   4368   8008  11440  12870  11440   8008   4368   1820    560    120     16      1
              1     17    136    680   2380   6188  12376  19448  24310  24310  19448  12376   6188   2380    680    136     17      1
          1     18    153    816   3060   8568  18564  31824  43758  48620  43758  31824  18564   8568   3060    816    153     18      1
       1     19    171    969   3876  11628  27132  50388  75582  92378  92378  75582  50388  27132  11628   3876    969    171     19      1
   1     20    190   1140   4845  15504  38760  77520 125970 167960 184756 167960 125970  77520  38760  15504   4845   1140    190     20      1
1     21    210   1330   5985  20349  54264 116280 203490 293930 352716 352716 293930 203490 116280  54264  20349   5985   1330    210     21      1

Ruby

<lang ruby>def pascal(n = 1)

 return if n < 1
 # set up a new array of arrays with the first value
 p = 1
   
 # for n - 1 number of times,
 (n - 1).times do |i|
   # inject a new array starting with [1]
   p << p[i].inject([1]) do |result, elem|
     
     # if we've reached the end, tack on a 1.
     # else, tack on current elem + previous elem
     if p[i].length == result.length
       result << 1
     else
       result << elem + p[i][result.length]
     end
   end
 end
 
 # and return the triangle.
 p
 

end</lang>

Or for more or less a translation of the two line Haskell version (with inject being abused a bit I know):

<lang ruby>def next_row row ; ([0] + row).zip(row + [0]).collect {|l,r| l + r }; end

def pascal n ; ([nil] * n).inject([1]) {|x,y| y = next_row x } ; end</lang>

Scala

Simple recursive row definition: <lang scala> def tri(row:Int):List[Int] = { row match {

 case 1 => List(1)
 case n:Int => List(1) ::: ((tri(n-1) zip tri(n-1).tail) map {case (a,b) => a+b}) ::: List(1)
 }

} </lang> Funtion to pretty print n rows: <lang scala> def prettytri(n:Int) = (1 to n) foreach {i=>print(" "*(n-i)); tri(i) map (c=>print(c+" ")); println} prettytri(5) </lang> Outputs:

    1 
   1 1 
  1 2 1 
 1 3 3 1 
1 4 6 4 1 

Scheme

Works with: Scheme version RRS

<lang scheme>(define (next-row row)

 (map + (cons 0 row) (append row '(0))))

(define (triangle row rows)

 (if (= rows 0)
     '()
     (cons row (triangle (next-row row) (- rows 1)))))

(triangle (list 1) 5) </lang> Output: <lang>((1) (1 1) (1 2 1) (1 3 3 1) (1 4 6 4 1))</lang>

Seed7

<lang seed7>$ include "seed7_05.s7i";

const proc: main is func

 local
   var integer: numRows is 0;
   var array integer: values is [] (0, 1);
   var integer: row is 0;
   var integer: index is 0;
 begin
   write("Number of rows: ");
   readln(numRows);
   writeln("1" lpad succ(numRows) * 3);
   for row range 2 to numRows do
     write("" lpad (numRows - row) * 3);
     values &:= [] 0;
     for index range succ(row) downto 2 do
       values[index] +:= values[pred(index)];
       write(" " <& values[index] lpad 5);
     end for;
     writeln;
   end for;
 end func;</lang>

Tcl

Summing from Previous Rows

<lang tcl>proc pascal_iterative n {

   if {$n < 1} {error "undefined behaviour for n < 1"}
   set row [list 1]
   lappend rows $row    
   set i 1
   while {[incr i] <= $n} {
       set prev $row
       set row [list 1]
       for {set j 1} {$j < [llength $prev]} {incr j} {
           lappend row [expr {[lindex $prev [expr {$j - 1}]] + [lindex $prev $j]}]
       }
       lappend row 1
       lappend rows $row
   }
   return $rows

}

puts [join [pascal_iterative 6] \n]</lang>

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

Using binary coefficients

Translation of: BASIC

<lang tcl>proc pascal_coefficients n {

   if {$n < 1} {error "undefined behaviour for n < 1"}
   for {set i 0} {$i < $n} {incr i} {
       set c 1
       set row [list $c]
       for {set j 0} {$j < $i} {incr j} {
           set c [expr {$c * ($i - $j) / ($j + 1)}]
           lappend row $c
       }
       lappend rows $row
   }
   return $rows

}

puts [join [pascal_coefficients 6] \n]</lang>

Combinations

Translation of: Java

Thanks to Tcl 8.5's arbitrary precision integer arithmetic, this solution is not limited to a couple of dozen rows. Uses a caching factorial calculator to improve performance. <lang tcl>package require Tcl 8.5

proc pascal_combinations n {

   if {$n < 1} {error "undefined behaviour for n < 1"}
   for {set i 0} {$i < $n} {incr i} {
       set row [list]
       for {set j 0} {$j <= $i} {incr j} {
           lappend row [C $i $j]
       }
       lappend rows $row
   }
   return $rows

}

proc C {n k} {

   expr {[ifact $n] / ([ifact $k] * [ifact [expr {$n - $k}]])}

}

set fact_cache {1 1} proc ifact n {

   global fact_cache
   if {$n < [llength $fact_cache]} {
       return [lindex $fact_cache $n]
   }
   set i [expr {[llength $fact_cache] - 1}]
   set sum [lindex $fact_cache $i]
   while {$i < $n} {
       incr i
       set sum [expr {$sum * $i}]
       lappend fact_cache $sum
   }
   return $sum

}

puts [join [pascal_combinations 6] \n]</lang>

Comparing Performance

<lang tcl>set n 100 puts "calculate $n rows:" foreach proc {pascal_iterative pascal_coefficients pascal_combinations} {

   puts "$proc: [time [list $proc $n] 100]"

}</lang> outputs

calculate 100 rows:
pascal_iterative: 2800.14 microseconds per iteration
pascal_coefficients: 8760.98 microseconds per iteration
pascal_combinations: 38176.66 microseconds per iteration

Ursala

Zero maps to the empty list. Negatives are inexpressible. This solution uses a library function for binomial coefficients. <lang Ursala>#import std

  1. import nat

pascal = choose**ziDS+ iota*t+ iota+ successor</lang> This solution uses direct summation. The algorithm is to insert zero at the head of a list (initially the unit list <1>), zip it with its reversal, map the sum over the list of pairs, iterate n times, and return the trace. <lang Ursala>#import std

  1. import nat

pascal "n" = (next"n" sum*NiCixp) <1></lang> test program: <lang Ursala>#cast %nLL

example = pascal 10</lang> output:

<
   <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>,
   <1,9,36,84,126,126,84,36,9,1>>

Vedit macro language

Summing from Previous Rows

Translation of: BASIC

Vedit macro language does not have actual arrays (edit buffers are normally used for storing larger amounts of data). However, a numeric register can be used as index to access another numeric register. For example, if #99 contains value 2, then #@99 accesses contents of numeric register #2.

<lang vedit>#100 = Get_Num("Number of rows: ", STATLINE)

  1. 0=0; #1=1

Ins_Char(' ', COUNT, #100*3-2) Num_Ins(1) for (#99 = 2; #99 <= #100; #99++) {

   Ins_Char(' ', COUNT, (#100-#99)*3)
   #@99 = 0
   for (#98 = #99; #98 > 0; #98--) {

#97 = #98-1 #@98 += #@97 Num_Ins(#@98, COUNT, 6)

   }
   Ins_Newline

}</lang>

Using binary coefficients

Translation of: BASIC

<lang vedit>#1 = Get_Num("Number of rows: ", STATLINE) for (#2 = 0; #2 < #1; #2++) {

   #3 = 1
   Ins_Char(' ', COUNT, (#1-#2-1)*3)
   for (#4 = 0; #4 <= #2; #4++) {

Num_Ins(#3, COUNT, 6) #3 = #3 * (#2-#4) / (#4+1)

   }
   Ins_Newline

}</lang>