1 ! Copyright (c) 2012 Anonymous
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: grouping kernel locals math math.ranges sequences ;
4 IN: rosetta-code.pascals-triangle
6 ! http://rosettacode.org/wiki/Pascal%27s_triangle
8 ! Pascal's triangle is an interesting math concept. Its first few rows look like this:
14 ! where each element of each row is either 1 or the sum of the
15 ! two elements right above it. For example, the next row would be
16 ! 1 (since the first element of each row doesn't have two elements
17 ! above it), 4 (1 + 3), 6 (3 + 3), 4 (3 + 1), and 1 (since the
18 ! last element of each row doesn't have two elements above it).
19 ! Each row n (starting with row 0 at the top) shows the
20 ! coefficients of the binomial expansion of (x + y)n.
22 ! Write a function that prints out the first n rows of the
23 ! triangle (with f(1) yielding the row consisting of only the
24 ! element 1). This can be done either by summing elements from the
25 ! previous rows or using a binary coefficient or combination
26 ! function. Behavior for n <= 0 does not need to be uniform, but
29 :: pascal-coefficients ( n -- seq )
31 dupd [ n swap - * ] [ /i ] bi swap
34 : (pascal) ( seq -- newseq )
35 dup last 0 prefix 0 suffix 2 <clumps> [ sum ] map suffix ;
38 1 - { { 1 } } swap [ (pascal) ] times ;