Pascal's triangle/Puzzle

From Rosetta Code
Pascal's triangle/Puzzle is a programming puzzle. It lays out a problem which Rosetta Code users are encouraged to solve, using languages and techniques they know. Multiple approaches are not discouraged, so long as the puzzle guidelines are followed. For other Puzzles, see Category:Puzzles.

This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers.

           [ 151]
          [  ][  ]
        [40][  ][  ]
      [  ][  ][  ][  ]
    [ X][11][ Y][ 4][ Z]

Each brick of the pyramid is the sum of the two bricks situated below it.
Of the three missing numbers at the base of the pyramid, the middle one is the sum of the other two (that is, Y = X + Z).

Write a program to find a solution to this puzzle.

Ada

The solution makes an upward run symbolically, though excluding Z. After that two blocks (1,1) and (3,1) being known yield a 2x2 linear system, from which X and Y are determined. Finally each block is revisited and printed. <lang ada>with Ada.Text_IO; use Ada.Text_IO;

procedure Pyramid_of_Numbers is

  B_X, B_Y, B_Z : Integer := 0; -- Unknown variables
  type Block_Value is record
     Known   : Integer := 0;
     X, Y, Z : Integer := 0;
  end record;
  X : constant Block_Value := (0, 1, 0, 0);
  Y : constant Block_Value := (0, 0, 1, 0);
  Z : constant Block_Value := (0, 0, 0, 1);
  procedure Add (L : in out Block_Value; R : Block_Value) is
  begin -- Symbolically adds one block to another
     L.Known := L.Known + R.Known;
     L.X := L.X + R.X - R.Z; -- Z is excluded as n(Y - X - Z) = 0
     L.Y := L.Y + R.Y + R.Z;
  end Add;
  procedure Add (L : in out Block_Value; R : Integer) is
  begin -- Symbolically adds a value to the block
     L.Known := L.Known + R;
  end Add;
  
  function Image (N : Block_Value) return String is
  begin -- The block value, when X,Y,Z are known
     return Integer'Image (N.Known + N.X * B_X + N.Y * B_Y + N.Z * B_Z);
  end Image;
  procedure Solve_2x2 (A11, A12, B1, A21, A22, B2 : Integer) is
  begin -- Don't care about things, supposing an integer solution exists
     if A22 = 0 then
        B_X := B2 / A21;
        B_Y := (B1 - A11*B_X) / A12;
     else
        B_X := (B1*A22 - B2*A12) / (A11*A22 - A21*A12);
        B_Y := (B1 - A11*B_X) / A12;
     end if;
     B_Z := B_Y - B_X;
  end Solve_2x2;
  
  B : array (1..5, 1..5) of Block_Value; -- The lower triangle contains blocks

begin

  -- The bottom blocks
  Add (B(5,1),X); Add (B(5,2),11); Add (B(5,3),Y); Add (B(5,4),4); Add (B(5,5),Z);
  -- Upward run
  for Row in reverse 1..4 loop
     for Column in 1..Row loop
        Add (B (Row, Column), B (Row + 1, Column));
        Add (B (Row, Column), B (Row + 1, Column + 1));
     end loop;
  end loop;
  
  -- Now have known blocks 40=(3,1), 151=(1,1) and Y=X+Z to determine X,Y,Z
  Solve_2x2
  (  B(1,1).X, B(1,1).Y, 151 - B(1,1).Known,
     B(3,1).X, B(3,1).Y,  40 - B(3,1).Known
  );
  -- Print the results
  for Row in 1..5 loop
     New_Line;
     for Column in 1..Row loop
        Put (Image (B(Row,Column)));
     end loop;
  end loop;

end Pyramid_of_Numbers; </lang> Sample output:


 151
 81 70
 40 41 29
 16 24 17 12
 5 11 13 4 8

ALGOL 68

Works with: ALGOL 68 version Standard - lu decomp and lu solve are from the ALGOL 68G/gsl library
Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9.i386

<lang algol>MODE

 FIELD = REAL,
 VEC = [0]REAL,
 MAT = [0,0]REAL;

MODE BRICK = UNION(INT, CHAR);

FLEX[][]BRICK puzzle = (

          ( 151),
        ( " ", " "),
      (  40, " ", " "),
    ( " ", " ", " ", " "),
  ( "x",  11, "y",  4, "z")

);

PROC mat col = (INT row, col)INT: row*(row-1)OVER 2 + col; INT col x = mat col(5,1),

   col y = mat col(5,3),
   col z = mat col(5,5);

OP INIT = (REF VEC vec)VOID: FOR elem FROM LWB vec TO UPB vec DO vec[elem]:=0 OD; OP INIT = (REF MAT mat)VOID: FOR row FROM LWB mat TO UPB mat DO INIT mat[row,] OD;

OP / = (MAT a, MAT b)MAT:( # matrix division #

 [LWB b:UPB b]INT p ;
 INT sign;
 [,]FIELD lu = lu decomp(b, p, sign);
 [LWB a:UPB a, 1 LWB a:2 UPB a]FIELD out;
 FOR col FROM 2 LWB a TO 2 UPB a DO out[,col] := lu solve(b, lu, p, a[,col]) OD;
 out

);

OP / = (VEC a, MAT b)VEC: ( # vector division #

 [LWB a:UPB a,1]FIELD transpose a;
 transpose a[,1]:=a;
 (transpose a/b)[,LWB a]

);

INT upb mat = mat col(UPB puzzle, UPB puzzle); [upb mat, upb mat] REAL mat; INIT mat; [upb mat] REAL vec; INIT vec;

INT mat row := LWB mat; INT known row := UPB mat - UPB puzzle + 1;

  1. build the simultaneous equation to solve #

FOR row FROM LWB puzzle TO UPB puzzle DO

 FOR col FROM LWB puzzle[row] TO UPB puzzle[row] DO
   IF row < UPB puzzle THEN
     mat[mat row, mat col(row, col)] := 1;
     mat[mat row, mat col(row+1, col)] := -1;
     mat[mat row, mat col(row+1, col+1)] := -1;
     mat row +:= 1
   FI;
   CASE puzzle[row][col] IN
     (INT value):(
       mat[known row, mat col(row, col)] := 1;
       vec[known row] := value;
       known row +:= 1
     ),
     (CHAR variable):SKIP 
   ESAC
 OD

OD;

  1. finally add x - y + z = 0 #

mat[known row, col x] := 1; mat[known row, col y] := -1; mat[known row, col z] := 1;

FORMAT real repr = $g(-5,2)$;

CO # print details of the simultaneous equation being solved # FORMAT

 vec repr = $"("n(2 UPB mat-1)(f(real repr)", ")f(real repr)")"$,
 mat repr = $"("n(1 UPB mat-1)(f(vec repr)", "lx)f(vec repr)")"$;

printf(($"Vec: "l$,vec repr, vec, $l$)); printf(($"Mat: "l$,mat repr, mat, $l$)); END CO

  1. finally actually solve the equation #

VEC solution vec = vec/mat;

  1. and wrap up by printing the solution #

FLEX[UPB puzzle]FLEX[0]REAL solution; FOR row FROM LWB puzzle TO UPB puzzle DO

 solution[row] := LOC[row]REAL;
 FOR col FROM LWB puzzle[row] TO UPB puzzle[row] DO
   solution[row][col] := solution vec[mat col(row, col)]
 OD;
 printf(($n(UPB puzzle-row)(4x)$, $x"("f(real repr)")"$, solution[row], $l$))

OD;

FOR var FROM 1 BY 2 TO 5 DO

 printf(($5x$,$g$,puzzle[UPB puzzle][var],"=", real repr, solution[UPB puzzle][var]))

OD</lang> Output:

                 (151.0)
             (81.00) (70.00)
         (40.00) (41.00) (29.00)
     (16.00) (24.00) (17.00) (12.00)
 ( 5.00) (11.00) (13.00) ( 4.00) ( 8.00)
     x= 5.00     y=13.00     z= 8.00

Haskell

I assume the task is to solve any such puzzle, i.e. given some data

<lang haskell>

puzzle = [["151"],["",""],["40","",""],["","","",""],["X","11","Y","4","Z"]]

</lang>

one should calculate all possible values that fit. That just means solving a linear system of equations. We use the first three variables as placeholders for X, Y and Z. Then we can produce the matrix of equations:

<lang haskell>

triangle n = n * (n+1) `div` 2

coeff xys x = maybe 0 id $ lookup x xys

row n cs = [coeff cs k | k <- [1..n]]

eqXYZ n = [(0, 1:(-1):1:replicate n 0)]
 
eqPyramid n h = do
  a <- [1..h-1]
  x <- [triangle (a-1) + 1 .. triangle a]
  let y = x+a
  return $ (0, 0:0:0:row n [(x,-1),(y,1),(y+1,1)])

eqConst n fields = do
  (k,s) <- zip [1..] fields
  guard $ not $ null s
  return $ case s of
    "X" - (0, 1:0:0:row n [(k,-1)])
    "Y" - (0, 0:1:0:row n [(k,-1)])
    "Z" - (0, 0:0:1:row n [(k,-1)])
    _   - (fromInteger $ read s, 0:0:0:row n [(k,1)])

equations :: String - ([Rational], Rational)
equations puzzle = unzip eqs where
  fields = concat puzzle
  eqs = eqXYZ n ++ eqPyramid n h ++ eqConst n fields 
  h = length puzzle
  n = length fields 

</lang>

To solve the system, any linear algebra library will do (e.g hmatrix). For this example, we assume there are functions decompose for LR-decomposition, kernel to solve the homogenous system and solve to find a special solution for an imhomogenous system. Then

<lang haskell>

normalize :: [Rational] - [Integer]
normalize xs = [numerator (x * v) | x <- xs] where 
  v = fromInteger $ foldr1 lcm $ map denominator $ xs

run puzzle = map (normalize . drop 3) $ answer where
  (a, m) = equations puzzle
  lr = decompose 0 m
  answer = case solve 0 lr a of
    Nothing - []
    Just x  - x : kernel lr

</lang>

will output one special solution and modifications that lead to more solutions, as in

<lang haskell>

*Main run puzzle
151,81,70,40,41,29,16,24,17,12,5,11,13,4,8
*Main run [[""],["2",""],["X","Y","Z"]]
[[3,2,1,1,1,0],[3,0,3,-1,1,2]]

</lang>

so for the second puzzle, not only X=1 Y=1 Z=0 is a solution, but also X=1-1=0, Y=1+1=2 Z=0+2=2 etc.

Note that the program doesn't attempt to verify that the puzzle is in correct form.

J

Fixed points in the pyramid are 40 and 151, which I use to check a resulting pyramid for selection:

<lang j>chk=:40 151&-:@(2 4{{."1)</lang>

verb for the base of the pyramid:

<lang j>base=: [,11,+,4,]</lang>

the height of the pyramid:

<lang j>ord=:5</lang>

=> 'chk', 'base' and 'ord' are the knowledge rules abstracted from the problem definition.

The J-sentence that solves the puzzle is:

<lang j> |."2(#~chk"2) 2(+/\)^:(<ord)"1 base/"1>,{ ;~i:28</lang>

 151  0  0  0 0
  81 70  0  0 0
  40 41 29  0 0
  16 24 17 12 0
   5 11 13  4 8

Get rid of zeros:

<lang j>,.(1+i.5)<@{."0 1{.|."2(#~chk"2) 2(+/\)^:(<ord)"1 base/"1>,{ ;~i:28</lang> or <lang j>,.(<@{."0 1~1+i.@#){.|."2(#~chk"2) 2(+/\)^:(<ord)"1 base/"1>,{ ;~i:28</lang>

 +-----------+
 |151        |
 +-----------+
 |81 70      |
 +-----------+
 |40 41 29   |
 +-----------+
 |16 24 17 12|
 +-----------+
 |5 11 13 4 8|
 +-----------+

Mathematica

We assign a variable to each block starting on top with a, then on the second row b,c et cetera. k,m, and o are replaced by X, Y, and Z. We can write the following equations: <lang Mathematica>

b+c==a
d+e==b
e+f==c
g+h==d
h+i==e
i+j==f
l+X==g
l+Y==h
n+Y==i
n+Z==j
X+Z==Y

</lang> And we have the knowns <lang Mathematica>

a->151
d->40
l->11
n->4

</lang> Giving us 10 equations with 10 unknowns; i.e. solvable. So we can do so by: <lang Mathematica>

eqs={a==b+c,d+e==b,e+f==c,g+h==d,h+i==e,i+j==f,l+X==g,l+Y==h,n+Y==i,n+Z==j,Y==X+Z};
knowns={a->151,d->40,l->11,n->4};
Solve[eqs/.knowns,{b,c,e,f,g,h,i,j,X,Y,Z}]

</lang> gives back: <lang Mathematica>

{{b -> 81, c -> 70, e -> 41, f -> 29, g -> 16, h -> 24, i -> 17,  j -> 12, X -> 5, Y -> 13, Z -> 8}}

</lang> In pyramid form that would be: <lang Mathematica> 151 81 70 40 41 29 16 24 17 12 5 11 13 4 8 </lang>

Oz

<lang ocaml>%% to compile : ozc -x <file.oz> functor

import

 System Application FD Search

define

 proc{Quest Root Rules}
   proc{Limit Rc Ls}
     case Ls of nil then skip
     [] X|Xs then
       {Limit Rc Xs}
       case X of N#V then        
         Rc.N =: V
       [] N1#N2#N3 then
         Rc.N1 =: Rc.N2 + Rc.N3
       end
     end
   end
   proc {Pyramid R}  
     {FD.tuple solution 15 0#FD.sup R}  %% non-negative integers domain
 %%          01      , pyramid format
 %%        02  03
 %%      04  05  06
 %%    07  08  09  10
 %%  11  12  13  14  15    
     R.1 =: R.2 + R.3     %% constraints of Pyramid of numbers
     R.2 =: R.4 + R.5
     R.3 =: R.5 + R.6
     R.4 =: R.7 + R.8
     R.5 =: R.8 + R.9
     R.6 =: R.9 + R.10
     R.7 =: R.11 + R.12
     R.8 =: R.12 + R.13
     R.9 =: R.13 + R.14
     R.10 =: R.14 + R.15
     
     {Limit R Rules}      %% additional constraints
     
     {FD.distribute ff R}   
   end
 in
   {Search.base.one Pyramid Root} %% search for solution   
 end
 local 
   Root R    
 in
   {Quest Root [1#151 4#40 12#11 14#4 13#11#15]} %% supply additional constraint rules
   if {Length Root} >= 1 then
     R = Root.1
     {For 1 15 1 
       proc{$ I} 
         if {Member I [1 3 6 10]} then
           {System.printInfo R.I#'\n'} 
         else
           {System.printInfo R.I#' '}  
         end     
       end
     }
   else
     {System.showInfo 'No solution found.'}
   end
 end
 {Application.exit 0}

end</lang>

Prolog

<lang prolog>

- use_module(library(clpfd)).

puzzle( [[ 151],

         [U1],[U2],
       [40],[U3],[U4],
     [U5],[U6],[U7],[U8],
   [ X],[11],[ Y],[ 4],[ Z]], X,Y,Z  ) :-
151 #= U1 + U2, 40 #= U5 + U6,
U1 #= 40 + U3, U2 #= U3 + U4,
U3 #= U6 + U7, U4 #= U7 + U8,
U5 #=  X + 11, U6 #= 11 +  Y,
U7 #=  Y +  4, U8 #=  4 +  Z,
 Y #=  X +  Z,
Vars = [U1,U2,U3,U4,U5,U6,U7,U8,X,Y,Z],
Vars ins 0..sup, labeling([],Vars).

% ?- puzzle(_,X,Y,Z). % X = 5, % Y = 13, % Z = 8 ; </lang>

Python

Works with: Python version 2.4+

<lang python># Pyramid solver

  1. [151]
  2. [ ] [ ]
  3. [ 40] [ ] [ ]
  4. [ ] [ ] [ ] [ ]
  5. [ X ] [ 11] [ Y ] [ 4 ] [ Z ]
  6. X -Y + Z = 0

def combine( snl, snr ):

cl = {} if type(snl ) == type(1): cl['1'] = snl elif type(snl) == type('X'): cl[snl] = 1 else: cl.update( snl)

if type(snr ) == type(1): n = cl.get('1', 0) cl['1'] = n + snr elif type(snr) == type('X'): n = cl.get(snr, 0) cl[snr] = n + 1 else: for k,v in snr.items(): n = cl.get(k, 0) cl[k] = n+v return cl


def constrain(nsum, vn ): nn = {} nn.update(vn) n = nn.get('1', 0) nn['1'] = n - nsum return nn

def makeMatrix( constraints ): vmap = set() for c in constraints: vmap.update( c.keys()) vmap.remove('1') nvars = len(vmap) vmap = sorted(list(vmap)) # sort here so output is in sorted order mtx = [] for c in constraints: row = [] for vv in vmap: row.append(1.0* c.get(vv, 0)) row.append(-1.0*c.get('1',0)) mtx.append(row)

if len(constraints) == nvars: print 'System appears solvable' elif len(constraints) < nvars: print 'System is not solvable - needs more constraints.' return mtx, vmap


def SolvePyramid( vl, cnstr ):

vl.reverse() constraints = [cnstr] lvls = len(vl) for lvln in range(1,lvls): lvd = vl[lvln] for k in range(lvls - lvln): sn = lvd[k] ll = vl[lvln-1] vn = combine(ll[k], ll[k+1]) if sn is None: lvd[k] = vn else: constraints.append(constrain( sn, vn ))

print 'Constraint Equations:' for cstr in constraints: fset = ('%d*%s'%(v,k) for k,v in cstr.items() ) print ' + '.join(fset), ' = 0'

mtx,vmap = makeMatrix(constraints)

MtxSolve(mtx)

d = len(vmap) for j in range(d): print vmap[j],'=', mtx[j][d]


def MtxSolve(mtx): # Simple Matrix solver...

mDim = len(mtx) # dimension--- for j in range(mDim): rw0= mtx[j] f = 1.0/rw0[j] for k in range(j, mDim+1): rw0[k] = rw0[k] * f

for l in range(1+j,mDim): rwl = mtx[l] f = -rwl[j] for k in range(j, mDim+1): rwl[k] = rwl[k] + f * rw0[k]

# backsolve part --- for j1 in range(1,mDim): j = mDim - j1 rw0= mtx[j] for l in range(0, j): rwl = mtx[l] f = -rwl[j] rwl[j] = rwl[j] + f * rw0[j] rwl[mDim] = rwl[mDim] + f * rw0[mDim]

return mtx


p = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ] addlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 } SolvePyramid( p, addlConstraint) </lang> Output:

Constraint Equations:
-1*Y + 1*X + 0*1 + 1*Z  = 0
-18*1 + 1*X + 1*Y  = 0
-73*1 + 5*Y + 1*Z  = 0
System appears solvable
X = 5.0
Y = 13.0
Z = 8.0

The Pyramid solver is not restricted to solving for 3 variables, or just this particular pyramid.

Alternative solution using the csp module (based on code by Gustavo Niemeyerby): http://www.fantascienza.net/leonardo/so/csp.zip <lang python> from csp import Problem

p = Problem() pvars = "R2 R3 R5 R6 R7 R8 R9 R10 X Y Z".split()

  1. 0-151 is the possible finite range of the variables

p.addvars(pvars, xrange(152)) p.addrule("R7 == X + 11") p.addrule("R8 == Y + 11") p.addrule("R9 == Y + 4") p.addrule("R10 == Z + 4") p.addrule("R7 + R8 == 40") p.addrule("R5 == R8 + R9") p.addrule("R6 == R9 + R10") p.addrule("R2 == 40 + R5") p.addrule("R3 == R5 + R6") p.addrule("R2 + R3 == 151") for sol in p.xsolutions():

   print [sol[k] for k in "XYZ"]

</lang>

All possible solutions with X,Y,Z >= 0, found in about 17 seconds, with Psyco (X, Y, Z): <lang python> [4, 14, 3] [5, 13, 8] [6, 12, 13] [7, 11, 18] [8, 10, 23] [9, 9, 28] [10, 8, 33] [11, 7, 38] [12, 6, 43] [13, 5, 48] [14, 4, 53] [15, 3, 58] [16, 2, 63] [17, 1, 68] [18, 0, 73] </lang>

Ruby

uses Reduced row echelon form#Ruby <lang ruby>require 'rref'

pyramid = [

          [ 151],
         [nil,nil],
       [40,nil,nil],
     [nil,nil,nil,nil],
   ["x", 11,"y", 4,"z"]

] p pyramid equations = 1,-1,1,0 # y = x + z

def parse_equation(str)

 eqn = [0] * 4
 lhs, rhs = str.split("=")
 eqn[3] = rhs.to_i
 for term in lhs.split("+")
   case term
   when "x": eqn[0] += 1
   when "y": eqn[1] += 1
   when "z": eqn[2] += 1
   else      eqn[3] -= term.to_i
   end
 end
 eqn 

end

-2.downto(-5) do |row|

 pyramid[row].each_index do |col|
   val = pyramid[row][col]
   sum = "%s+%s" % [pyramid[row+1][col].to_s, pyramid[row+1][col+1].to_s]
   if val.nil?
     pyramid[row][col] = sum
   else
     equations << parse_equation(sum + "=#{val}")
   end
 end

end

reduced = convert_to(reduced_row_echelon_form(equations), :to_i)

for eqn in reduced

 if eqn[0] + eqn[1] + eqn[2] != 1
   fail "no unique solution! #{equations.inspect} ==> #{reduced.inspect}"
 elsif eqn[0] == 1: x = eqn[3]
 elsif eqn[1] == 1: y = eqn[3]
 elsif eqn[2] == 1: z = eqn[3]
 end

end

puts "x == #{x}" puts "y == #{y}" puts "z == #{z}"

answer = [] for row in pyramid

 answer << row.collect {|cell| eval cell.to_s}

end p answer</lang>

[[151], [nil, nil], [40, nil, nil], [nil, nil, nil, nil], ["x", 11, "y", 4, "z"]]
x == 5
y == 13
z == 8
[[151], [81, 70], [40, 41, 29], [16, 24, 17, 12], [5, 11, 13, 4, 8]]

Tcl

using code from Reduced row echelon form#Tcl <lang tcl>package require Tcl 8.5 namespace path ::tcl::mathop

set pyramid {

   {151.0 "" "" "" ""}
   {"" "" "" "" ""}
   {40.0 "" "" "" ""}
   {"" "" "" "" ""}
   {x 11.0 y 4.0 z}

}

set equations Template:1 -1 1 0

proc simplify {terms val} {

   set vars {0 0 0}
   set x 0
   set y 1
   set z 2
   foreach term $terms {
       switch -exact -- $term {
           x - y - z {
               lset vars [set $term] [+ 1 [lindex $vars [set $term]]]
           }
           default {
               set val [- $val $term]
           }
       }
   }
   return [concat $vars $val]

}

for {set row [+ [llength $pyramid] -2]} {$row >= 0} {incr row -1} {

   for {set cell 0} {$cell <= $row} {incr cell } {

set sum [concat [lindex $pyramid [+ 1 $row] $cell] [lindex $pyramid [+ 1 $row] [+ 1 $cell]]] if {[set val [lindex $pyramid $row $cell]] ne ""} {

           lappend equations [simplify $sum $val]

} else {

           lset pyramid $row $cell  $sum
       }
   }

}

set solution [toRREF $equations] foreach row $solution {

   lassign $row a b c d
   if {$a + $b + $c > 1} {
       error "problem does not have a unique solution"
   }
   if {$a} {set x $d}
   if {$b} {set y $d}
   if {$c} {set z $d}

} puts "x=$x" puts "y=$y" puts "z=$z"

foreach row $pyramid {

   set newrow {}
   foreach cell $row {
       if {$cell eq ""} {
           lappend newrow ""
       } else {
           lappend newrow [expr [join [string map [list x $x y $y z $z] $cell] +]]
       }
   }
   lappend solved $newrow

} print_matrix $solved</lang>

x=5.0
y=13.0
z=8.0
151.0                    
 81.0 70.0               
 40.0 41.0 29.0          
 16.0 24.0 17.0 12.0     
  5.0 11.0 13.0  4.0 8.0