Pascal's triangle/Puzzle: Difference between revisions
m
→{{header|Wren}}: Minor tidy
m (→{{header|Phix}}: acutllay use that solveN(), syntax coloured, plus three alternatives) |
m (→{{header|Wren}}: Minor tidy) |
||
(12 intermediate revisions by 5 users not shown) | |||
Line 21:
{{trans|D}}
<
R x[row * (row + 1) I/ 2 + col]
Line 63:
L(j) 0..i
print(‘#4’.format(Int(0.5 + v[idx])), end' I j < i {‘ ’} E "\n")
idx++</
{{out}}
Line 87:
=={{header|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.
<
procedure Pyramid_of_Numbers is
Line 155:
end loop;
end loop;
end Pyramid_of_Numbers;</
{{Out}}
<pre>
Line 170:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
<!-- {{does not work with|ELLA ALGOL 68|Any (with appropriate job cards AND formatted transput statements removed) - tested with release 1.8.8d.fc9.i386 - ELLA has no FORMATted transput, and not }} -->
<
FIELD = REAL,
VEC = [0]REAL,
Line 265:
FOR var FROM 1 BY 2 TO 5 DO
printf(($5x$,$g$,puzzle[UPB puzzle][var],"=", real repr, solution[UPB puzzle][var]))
OD</
{{Out}}
<pre>
Line 278:
=={{header|AutoHotkey}}==
The main part is this:
<
Z := (2*N4 - 7*N3 - 8*N2 + 6*N1) / 7
X := (N3 - 2*N1 - Z) / 2
MsgBox,, Pascal's Triangle, %X%`n%Z%</
Message box shows:
<pre>5.000000
Line 288:
The GUI shows all values in the solved state.
<
; Pascal's triangle.ahk
; by wolf_II
Line 561:
; delete status bar text
Else SB_SetText("")
}</
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
REM Describe the puzzle as a set of simultaneous equations:
Line 603:
PRINT "X = " ; vector(8)
PRINT "Y = " ; vector(9)
PRINT "Z = " ; vector(10)</
{{Out}}
<pre>
Line 614:
This solution is based upon algebraic necessities, namely that a solution exists when (top - 4(a+b))/7 is integral. It also highlights the type difference between floating point numbers and integers in C.
<syntaxhighlight lang="c">
/* Pascal's pyramid solver
*
Line 654:
return 0;
}
</syntaxhighlight>
{{Out}}
<pre>
Line 664:
===Field equation solver===
Treating relations between cells as if they were differential equations, and apply negative feedback to each cell at every iteration step. This is how field equations with boundary conditions are solved numerically. It is, of course, not the optimal solution for this particular task.
<
#include <stdlib.h>
Line 736:
return 0;
}</
{{Out}}<pre>pass 1: 12
pass 2: 12
Line 752:
=={{header|C sharp|C#}}==
<
using System;
Line 939:
}
}
</syntaxhighlight>
{{out| Program Input and Output}}
<pre>
Line 1,008:
=={{header|C++}}==
{{trans|C}}
<
#include <iomanip>
Line 1,072:
return 0;
}</
=={{header|Clojure}}==
Line 1,078:
X and Z are the independent variables, so first work bottom up and determine the value of each cell in the form (n0 + n1*X + n2*Z).
We'll use a vector [n0 n1 n2] to represent each cell.
<
(defn plus [v1 v2] (vec (map + v1 v2)))
Line 1,086:
(defn above [row] (map #(apply plus %) (partition 2 1 row)))
(def rows (reverse (take 5 (iterate above bottom))))</
We know the integer value of cells c00 and c20 ( base-0 row then column numbers), so by subtracting these values we get two equations of the form 0=n0+n1*X+n2*Z.
<
(def c20 (get-in rows [2 0]))
(def eqn0 (minus c00 [151 0 0]))
(def eqn1 (minus c20 [ 40 0 0]))</
In this case, there are only two variables, so solving the system of linear equations is simple.
<
(assert (<= 1 m 2))
(let [n (- 3 m)
Line 1,104:
(let [x (solve 1), z (solve 2), y (+ x z)]
(println "x =" x ", y =" y ", z =" z))</
If you want to solve the whole pyramid, just add a call ''(show-pyramid x z)'' to the previous ''let'' form:
<
(defn show-pyramid [x z]
(doseq [row rows]
(println (map #(dot [1 x z] %) row)))</
=={{header|Craft Basic}}==
<syntaxhighlight lang="basic">let x = -1
do
let x = x + 1
let z = 0
do
let e = x + 11
let f = 11 + (x + z)
let g = (x + z) + 4
let h = 4 + z
if e + f = 40 then
let c = f + g
let d = g + h
let a = 40 + c
let b = c + d
let q = 0
if a + b = 151 then
let q = 1
endif
endif
if q = 0 then
let z = z + 1
endif
wait
loopwhile z < 20 and q = 0
if q = 0 then
let z = -1
endif
wait
loopuntil z >= 0
print "x = ", x
print "y = ", x + z
print "z = ", z</syntaxhighlight>
{{out| Output}}<pre>x = 5
y = 13
z = 8</pre>
=={{header|Curry}}==
{{Works with|PAKCS}}
<
import Constraint (allC, andC)
import Findall (findall)
Line 1,138 ⟶ 1,196:
, [ x, 11, y, 4, z]
]
main = findall $ solve . test</
{{Out}}
<pre>Execution time: 0 msec. / elapsed: 0 msec.
Line 1,145 ⟶ 1,203:
=={{header|D}}==
{{trans|C}}
<
void iterate(bool doPrint=true)(double[] v, double[] diff) @safe {
Line 1,205 ⟶ 1,263:
iterate(v, diff);
show(v);
}</
{{out}}
<pre>dev: 73410
Line 1,228 ⟶ 1,286:
=={{header|F_Sharp|F#}}==
<p>In a script, using the [http://numerics.mathdotnet.com/ Math.NET Numerics] library</p>
<
#load"Packages\MathNet.Numerics.FSharp\MathNet.Numerics.fsx"
Line 1,251 ⟶ 1,309:
let x = A.Solve(b)
printfn "x = %f, Y = %f, Z = %f" x.[8] x.[9] x.[10]</
{{out}}
<pre>x = 5.000000, Y = 13.000000, Z = 8.000000</pre>
Line 1,257 ⟶ 1,315:
=={{header|Factor}}==
{{works with|Factor|0.98}}
<
interpolate io kernel math math.ranges sequences ;
Line 1,269 ⟶ 1,327:
up first 151 = must-be-true ;
find-solution [I X = ${1}, Z = ${}I] nl</
{{out}}
<pre>
X = 5, Z = 8
</pre>
=={{header|FreeBASIC}}==
{{trans|PureBasic}}
<syntaxhighlight lang="freebasic">Function SolveForZ(x As Integer) As Integer
Dim As Integer a, b, c, d, e, f, g, h, z
For z = 0 To 20
e = x + 11
f = 11 + (x+z)
g = (x+z) + 4
h = 4 + z
If e + f = 40 Then
c = f + g
d = g + h
a = 40 + c
b = c + d
If a + b = 151 Then Return z
End If
Next z
Return -1
End Function
Dim As Integer x = -1, z = 0
Do
x = x + 1
z = SolveForZ(x)
Loop Until z >= 0
Print "X ="; x
Print "Y ="; x + z
Print "Z ="; z
Sleep
</syntaxhighlight>
{{out}}
<pre>X = 5
Y = 13
Z = 8</pre>
=={{header|Go}}==
This solution follows the way the problem might be solved with pencil and paper. It shows a possible data representation of the problem, uses the computer to do some arithmetic, and displays intermediate and final results.
<
import "fmt"
Line 1,410 ⟶ 1,505:
fmt.Println("y =", solveY(y))
fmt.Println("z =", solveZ(z))
}</
{{Out}}
<pre>
Line 1,433 ⟶ 1,528:
I assume the task is to solve any such puzzle, i.e. given some data
<
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:
<
coeff xys x = maybe 0 id $ lookup x xys
Line 1,465 ⟶ 1,560:
eqs = eqXYZ n ++ eqPyramid n h ++ eqConst n fields
h = length puzzle
n = length fields</
To solve the system, any linear algebra library will do (e.g [http://hackage.haskell.org/cgi-bin/hackage-scripts/package/hmatrix-0.2.0.0 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
<
normalize xs = [numerator (x * v) | x <- xs] where
v = fromInteger $ foldr1 lcm $ map denominator $ xs
Line 1,478 ⟶ 1,573:
answer = case solve 0 lr a of
Nothing - []
Just x - x : kernel lr</
will output one special solution and modifications that lead to more solutions, as in
<
[[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]]</
so for the second puzzle, not only X=1 Y=1 Z=0 is a solution,
Line 1,496 ⟶ 1,591:
Fixed points in the pyramid are 40 and 151, which I use to check a resulting pyramid for selection:
<
verb for the base of the pyramid:
<
the height of the pyramid:
<
=> 'chk', 'base' and 'ord' are the knowledge rules abstracted from the problem definition.
Line 1,510 ⟶ 1,605:
The J-sentence that solves the puzzle is:
<
<pre> 151 0 0 0 0
81 70 0 0 0
Line 1,519 ⟶ 1,614:
Get rid of zeros:
<
or
<
<pre> +-----------+
Line 1,539 ⟶ 1,634:
Generate 11 equations and 11 unknowns. Reuse code from Cramer's Rule.
<
import java.util.ArrayList;
import java.util.Arrays;
Line 1,653 ⟶ 1,748:
}
</syntaxhighlight>
{{out}}
Line 1,661 ⟶ 1,756:
Y = 13.00
Z = 8.00
</pre>
=={{header|jq}}==
{{works with|jq}}
'''Also works with gojq, the Go implementation of jq, and with fq.'''
In the spirit of the simplicity of Pascal Triangle's definition, the
first solution given in this entry works up from the bottom of the triangle using the
basic Pascal Triangle equation for each brick that is above two
others.
In the following, the value of the j-th brick in the i-th row is
denoted by rij if initially known (so r11 refers to the apex), and by
$Rij if initially unknown, so the variable "X" in the puzzle
could be denoted by $R51.
It is assumed that:
* all values in the triangle must be positive integers;
* the task is to solve for any given values of r11, r31, r52, r54;
* all solutions for the triple [X, Y, Z] should be found.
<syntaxhighlight lang=jq>
def solve(r11; r31; r52; r54):
range(1;r31 - 1) as $X
| range(1; r31 - 1) as $Y
| (($Y - $X) | select(. > 0)) as $Z
| (r52 + $X) as $R41
| (r52 + $Y) as $R42
| select($R41 + $R42 == r31)
| ($Y + r54) as $R43
| (r54 + $Z) as $R44
| ($R42 + $R43) as $R32
| ($R43 + $R44) as $R33
| (r31 + $R32) as $R21
| ($R32 + $R33) as $R22
| select($R21 + $R22 == r11)
| [$X, $Y, $Z];
solve(151; 40; 11; 4),
</syntaxhighlight>
{{output}}
<pre>
[5,13,8]
</pre>
===Algebraic solution===
As noted elsewhere on this page, elementary considerations show that
the apex (top) value and the value in the third row (mid) can be written as:
<pre>
top = 4(a+b) + 7(x+z)
mid = 2x + 2a + z
</pre>
where a and b are the known values at the base.
Using the jq program at [[Cramer%27s_rule#jq|Cramer's rule]], with the unknown vector being [x, z]:
<syntaxhighlight lang=jq>
include "rc-cramers-rule";
def solve(top; mid; a; b):
cramer(
[ [7, 7],
[2, 1]];
[top - 4*(a+b), mid-2*a]);
solve(151; 40; 11; 4)
</syntaxhighlight>
This gives the solution for [x,z] as:
{{output}}
<pre>
[5,8]
</pre>
=={{header|Julia}}==
{{trans|Kotlin}}
<
yd = round((top - 4 * (a + b)) / 7)
!isinteger(yd) && return 0, 0, 0
Line 1,678 ⟶ 1,840:
else
println("There is no solution.")
end</
{{out}}
Line 1,685 ⟶ 1,847:
=={{header|Kotlin}}==
{{trans|C}}
<
data class Solution(val x: Int, val y: Int, val z: Int)
Line 1,706 ⟶ 1,868:
else
println("There is no solutuon")
}</
{{out}}
Line 1,714 ⟶ 1,876:
=={{header|Maple}}==
<syntaxhighlight lang="maple">
sys := {22 + x + y = 40, 78 + 5*y + z = 151, x + z = y}:
solve(sys, {x,y,z});
</syntaxhighlight>
{{out}}<pre>
{x = 5, y = 13, z = 8}
Line 1,724 ⟶ 1,886:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
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:
<
d+e==b
e+f==c
Line 1,734 ⟶ 1,896:
n+Y==i
n+Z==j
X+Z==Y</
And we have the knowns
<
d->40
l->11
n->4</
Giving us 10 equations with 10 unknowns; i.e. solvable. So we can do so by:
<
knowns={a->151,d->40,l->11,n->4};
Solve[eqs/.knowns,{b,c,e,f,g,h,i,j,X,Y,Z}]</
gives back:
<
In pyramid form that would be:
<
81 70
40 41 29
16 24 17 12
5 11 13 4 8</
An alternative solution in Mathematica 10, constructing the triangle:
<
Solve[{triangle[3, 1] == 40, triangle[5, 1] == 151, y == x + z}, {x, y, z}]</
Three equations and three unknowns, which gives back:
<
=={{header|MiniZinc}}==
<syntaxhighlight lang="minizinc">
%Pascal's Triangle Puzzle. Nigel Galloway, February 17th., 2020
int: N11=151; constraint N11=N21+N22;
Line 1,775 ⟶ 1,937:
var 1..N11: Y=X+Z;
var 1..N11: Z;
</syntaxhighlight>
{{out}}
<pre>
Line 1,785 ⟶ 1,947:
=={{header|Nim}}==
{{trans|Ada}}
<
type
Line 1,844 ⟶ 2,006:
line.addSep(" ")
line.add toString(blocks[row][column], vars)
echo line</
{{out}}
<pre>151
Line 1,853 ⟶ 2,015:
=={{header|Oz}}==
<
functor
Line 1,921 ⟶ 2,083:
{Application.exit 0}
end</
=={{header|PARI/GP}}==
Line 1,931 ⟶ 2,093:
this helped me...
<
Pascals_triangle_puzzle(topvalue=151,leftsidevalue=40,bottomvalue1=11,bottomvalue2=4) = {
y=(topvalue-(4*(bottomvalue1+bottomvalue2)))/7;
Line 1,937 ⟶ 2,099:
z=y-x;
print(x","y","z); }
</syntaxhighlight>
I'm thinking of one to solve all puzzles regardless of size and positions. but the objective was to solve this puzzle.
=={{header|Perl}}==
<
my $rows = 5;
my @tri = map { [ map { {x=>0,z=>0,v=>0,rhs=>undef} } 1..$_ ] } 1..$rows;
Line 1,982 ⟶ 2,144:
my $y = $x+$z;
printf "x=%d, y=%d, z=%d\n", $x, $y, $z;
</syntaxhighlight>
{{out}}
<pre>Equations:
Line 1,993 ⟶ 2,155:
=={{header|Phix}}==
<!--<
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Pascal_triangle_Puzzle.exw
Line 2,129 ⟶ 2,291:
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pyramid</span><span style="color: #0000FF;">)</span>
<!--</
{{out}}
<pre>
Line 2,152 ⟶ 2,314:
A couple of other ways to use that solveN():
<!--<
<span style="color: #0000FF;">?</span><span style="color: #000000;">solveN</span><span style="color: #0000FF;">({{</span><span style="color: #000000;">18</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">73</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">}})</span> <span style="color: #000080;font-style:italic;">-- -- {5,13,8}</span>
Line 2,178 ⟶ 2,340:
-- })) -- {81,70,41,29,16,24,17,12,5,13,8}</span>
<span style="color: #0000FF;">})[-</span><span style="color: #000000;">3</span><span style="color: #0000FF;">..-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">])</span> <span style="color: #000080;font-style:italic;">-- {5,13,8}</span>
<!--</
And finally, a cheeky little two-liner that does the whole job
<!--<
<span style="color: #004080;">integer</span> <span style="color: #000000;">Y</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">151</span><span style="color: #0000FF;">-</span><span style="color: #000000;">4</span><span style="color: #0000FF;">*(</span><span style="color: #000000;">11</span><span style="color: #0000FF;">+</span><span style="color: #000000;">4</span><span style="color: #0000FF;">))/</span><span style="color: #000000;">7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">X</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">40</span><span style="color: #0000FF;">-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">*</span><span style="color: #000000;">11</span><span style="color: #0000FF;">-</span><span style="color: #000000;">Y</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">Z</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">Y</span><span style="color: #0000FF;">-</span><span style="color: #000000;">X</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Two-liner: x=%d, y=%d, z=%d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">X</span><span style="color: #0000FF;">,</span><span style="color: #000000;">Y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">Z</span><span style="color: #0000FF;">})</span>
<!--</
{{out}}
<pre>
Two-liner: x=5, y=13, z=8
</pre>
=={{header|Picat}}==
Below are three different approaches using constraint modelling (cp solver).
===Using lists to represent the triangle===
{{trans|Prolog}}
<syntaxhighlight lang="picat">import cp.
go =>
puzzle(T, X, Y,Z),
foreach(TT in T)
println(TT)
end,
println([x=X,y=Y,z=Z]),
nl,
fail, % are there any more solutions?
nl.
% Port of the Prolog solution
puzzle(Ts, X, Y, Z) :-
Ts = [ [151],
[_, _],
[40, _, _],
[_, _, _, _],
[X, 11, Y, 4, Z]],
Y #= X + Z,
triangle(Ts),
Vs = vars(Ts),
Vs :: 0..10000,
solve(Vs).
triangle([T|Ts]) :-
( Ts = [N|_] -> triangle_(T, N), triangle(Ts) ; true ).
triangle_([], _).
triangle_([T|Ts],[A,B|Rest]) :-
T #= A + B, triangle_(Ts, [B|Rest]).</syntaxhighlight>
{{out}}
<pre>[151]
[81,70]
[40,41,29]
[16,24,17,12]
[5,11,13,4,8]
[x = 5,y = 13,z = 8]</pre>
===Calculating the positions===
Here is a constraint model which calculates the positions in the triangle that should be added together.
<syntaxhighlight lang="picat">import cp.
puzzle2 =>
N = 5, % number of rows
Len = (N*(N+1)) div 2, % number of entries
% The triangle numbers for 1..N
T = [I*(I+1) div 2 : I in 1..N],
% The index of first number to use in addition
% create the indices of the numbers to add,
% i.e. Adds[I] + Adds[I+1]
Adds = new_list(T[N-1]),
Adds[1] := 2,
foreach(I in 2..T[N-1])
% "jump" of 2 when i-1 is a triangle number
if membchk(I-1,T) then
Adds[I] := Adds[I-1] + 2
else
Adds[I] := Adds[I-1] + 1
end
end,
% the pyramid
MaxVal = 10_000,
L = new_list(Len),
L :: 1..MaxVal,
% The clues.
L = [ 151,
_, _,
40, _, _,
_, _,_ , _ ,
X, 11, Y, 4, Z
],
% The sums
foreach(I in 1..T[N-1])
L[I] #= L[Adds[I]]+L[Adds[I]+1]
end,
% The extra constraint
Y #= X + Z,
solve(L),
println([x=X,y=Y,z=Z]),
fail, % check if there is another solution
nl.</syntaxhighlight>
{{out}}
<pre>[x = 5,y = 13,z = 8]</pre>
===Hard coded constraints===
<syntaxhighlight lang="picat">import cp.
puzzle3 =>
% 1
% 2 3
% 4 5 6
% 7 8 9 10
%11 12 13 14 15
X = new_list(15),
X :: 0..10_000,
X[1] #= X[2]+X[3],
X[2] #= X[4]+X[5],
X[3] #= X[5]+X[6],
X[4] #= X[7]+X[8],
X[5] #= X[8]+X[9],
X[6] #= X[9]+X[10],
X[7] #= X[11]+X[12],
X[8] #= X[12]+X[13],
X[9] #= X[13]+X[14],
X[10] #= X[14]+X[15],
X[13] #= X[11] + X[15], % Y=X+Z,
% The hints
X[1] #= 151,
X[4] #= 40,
X[12] #= 11,
X[14] #= 4,
solve(X),
println([x=X[11],y=X[13],z=X[15]]),
fail,
nl.</syntaxhighlight>
{{out}}
<pre>[x = 5,y = 13,z = 8]</pre>
=={{header|PicoLisp}}==
<
(^ @C (box 0))
(repeat)
Line 2,234 ⟶ 2,533:
(+ 4 @Z @H)
(+ @X @Z @Y)
T )</
{{Out}}
<pre>: (? (puzzle @X @Y @Z))
Line 2,240 ⟶ 2,539:
=={{header|Prolog}}==
<
puzzle(Ts, X, Y, Z) :-
Line 2,258 ⟶ 2,557:
% X = 5,
% Y = 13,
% Z = 8 ;</
=={{header|PureBasic}}==
Brute force solution.
<
; A.
; [ 151]
Line 2,292 ⟶ 2,591:
z=SolveForZ(x)
Until z>=0
MessageRequester(title$,"X="+Str(x)+#CRLF$+"Y="+Str(x+z)+#CRLF$+"Z="+Str(z))</
=={{header|Python}}==
{{works with|Python|2.4+}}
<
# [151]
# [ ] [ ]
Line 2,417 ⟶ 2,716:
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)</
{{Out}}
<pre>Constraint Equations:
Line 2,433 ⟶ 2,732:
http://www.fantascienza.net/leonardo/so/csp.zip
<
p = Problem()
Line 2,451 ⟶ 2,750:
p.addrule("Y == X + Z")
for sol in p.xsolutions():
print [sol[k] for k in "XYZ"]</
{{Out}}
Line 2,462 ⟶ 2,761:
We'll use a struct (cell v x z) to represent each cell,
where the value is (v + x*X + z*Z).
<syntaxhighlight lang="racket">
#lang racket/base
(require racket/list)
Line 2,477 ⟶ 2,776:
(- (cell-x cx) (cell-x cy))
(- (cell-z cx) (cell-z cy))))
</syntaxhighlight>
We first work bottom up and determine the value of each cell, starting from the bottom row.
<syntaxhighlight lang="racket">
(define (row-above row) (map cell-add (drop row 1) (drop-right row 1)))
Line 2,488 ⟶ 2,787:
(define row3 (row-above row2))
(define row4 (row-above row3))
</syntaxhighlight>
We know the value of two additional cells, so by subtracting these values we get two equations of the form 0=v+x*X+z*Z. In the usual notation we get x*X+z*Z=-v, so v has the wrong sign.
<syntaxhighlight lang="racket">
(define eqn40 (cell-sub (car row4) (cell 151 0 0)))
(define eqn20 (cell-sub (car row2) (cell 40 0 0)))
</syntaxhighlight>
To solve the 2 equation system, we will use the Cramer's rule.
<syntaxhighlight lang="racket">
(define (det2 eqnx eqny get-one get-oth)
(- (* (get-one eqnx) (get-oth eqny)) (* (get-one eqny) (get-oth eqnx))))
Line 2,505 ⟶ 2,804:
(/ (det2 eqnx eqny get-val get-oth)
(det2 eqnx eqny get-unk get-oth)))
</syntaxhighlight>
To get the correct values of X, Y and Z we must change their signs.
<syntaxhighlight lang="racket">
(define x (- (cramer2 eqn20 eqn40 cell-v cell-x cell-z)))
(define z (- (cramer2 eqn20 eqn40 cell-v cell-z cell-x)))
Line 2,515 ⟶ 2,814:
(displayln (list "Y" (+ x z)))
(displayln (list "Z" z))
</syntaxhighlight>
{{Out}}
Line 2,527 ⟶ 2,826:
(formerly Perl 6)
{{trans|Perl}}
<syntaxhighlight lang="raku"
my $rows = 5;
my @tri = (1..$rows).map: { [ { x => 0, z => 0, v => 0, rhs => Nil } xx $_ ] }
Line 2,569 ⟶ 2,868:
my $z = @eqn[1][2] / @eqn[1][1];
my $y = $x + $z;
say "x=$x, y=$y, z=$z";</
{{out}}
<pre>Equations:
Line 2,580 ⟶ 2,879:
=={{header|REXX}}==
This REXX version also displays a diagram of the puzzle.
<
/* ╔══════════════════════════════════════════════════╗
║ answer ║
Line 2,611 ⟶ 2,910:
end /*z*/
end /*y*/
end /*x*/ /*stick a fork in it, we're all done. */</
{{out|output|text= when using the default inputs:}}
<pre>
Line 2,633 ⟶ 2,932:
=={{header|Ruby}}==
uses [[Reduced row echelon form#Ruby]]
<
pyramid = [
Line 2,694 ⟶ 2,993:
end
puts
answer.each{|row| p row}</
{{out}}
Line 2,716 ⟶ 3,015:
=={{header|Scala}}==
<
val (x, y, z) = pascal(11, 4, 40, 151)
Line 2,727 ⟶ 3,026:
println(if (x != 0) s"Solution is: x = $x, y = $y, z = $z" else "There is no solution.")
}</
{{Out}}See it in running in your browser by [https://scalafiddle.io/sf/UJF14fw/0 (JavaScript)]
or by [https://scastie.scala-lang.org/l0AlwpSdR7i801Fq8CWHEQ Scastie (JVM)].
Line 2,733 ⟶ 3,032:
=={{header|Sidef}}==
{{trans|Raku}}
<
var rows = 5
var tri = rows.of {|i| (i+1).of { Hash(x => 0, z => 0, v => 0, rhs => nil) } }
Line 2,779 ⟶ 3,078:
var z = (eqn[1][2] / eqn[1][1])
var y = (x + z)
say "x=#{x}, y=#{y}, z=#{z}"</
{{out}}
<pre>
Line 2,792 ⟶ 3,091:
=={{header|SystemVerilog}}==
We can view this as a problem of generating a set of random numbers that satisfy the constraints. Because there is only one solution, the result isn't very random...
<
class Triangle;
Line 2,829 ⟶ 3,128:
Triangle answer = new;
endprogram</
<pre> [151]
[81][70]
Line 2,839 ⟶ 3,138:
=={{header|Tcl}}==
using code from [[Reduced row echelon form#Tcl]]
<
namespace path ::tcl::mathop
Line 2,906 ⟶ 3,205:
lappend solved $newrow
}
print_matrix $solved</
<pre>x=5.0
y=13.0
Line 2,919 ⟶ 3,218:
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
<
var isIntegral = Fn.new { |x, tol| x.fraction.abs <= tol }
Line 2,936 ⟶ 3,235:
} else {
System.print("There is no solution")
}</
{{out}}
Line 2,944 ⟶ 3,243:
=={{header|XPL0}}==
<
int I, P;
def Tab = $09;
Line 2,977 ⟶ 3,276:
];
];
]</
{{out}}
Line 2,990 ⟶ 3,289:
=={{header|zkl}}==
{{trans|Python}}
<
# [151]
# [ ] [ ]
Line 3,001 ⟶ 3,300:
L("X", 11, "Y", 4, "Z") );
addlConstraint:=Dictionary( "X",1, "Y",-1, "Z",1, "1",0 );
solvePyramid(p, addlConstraint);</
<
vl=vl.reverse();
constraints:=L(cnstr);
Line 3,084 ⟶ 3,383:
}
return(mtx);
}</
{{out}}
<pre>
|