Law of cosines - triples: Difference between revisions

(→‎{{header|Ruby}}: added extra credit)
Line 897:
 
For an angle of 60 degrees there are 18394 solutions.
</pre>
 
=={{header|Nim}}==
<lang nim>import strformat
import tables
 
# Generate tables at compile time. This eliminates the initialization at
# the expense of a bigger executable.
 
const square13 = block:
var tmp = newSeq[tuple[a, b: int]]()
for i in 1..13:
tmp.add((i * i, i))
toTable(tmp)
const square10000 = block:
var tmp = newSeq[tuple[a, b: int]]()
for i in 1..10000:
tmp.add((i * i, i))
toTable(tmp)
 
proc solve(angle, maxLen: int, allowSame: bool): seq[tuple[a, b, c: int]] =
result = newSeq[tuple[a, b, c: int]]()
for a in 1..maxLen:
for b in a..maxLen:
var lhs = a * a + b * b
if angle != 90:
case angle
of 60:
dec lhs, a * b
of 120:
inc lhs, a * b
else:
raise newException(IOError, "Angle must be 60, 90 or 120 degrees")
case maxLen
of 13:
var c = square13.getOrDefault(lhs)
if (not allowSame and a == b and b == c) or c == 0:
continue
result.add((a, b, c))
of 10000:
var c = square10000.getOrDefault(lhs)
if (not allowSame and a == b and b == c) or c == 0:
continue
result.add((a, b, c))
else:
raise newException(IOError, "Maximum length must be either 13 or 10000")
 
echo "For sides in the range [1, 13] where they can all be the same length:\n"
let angles = [90, 60, 120]
for angle in angles:
var solutions = solve(angle, 13, true)
echo fmt" For an angle of {angle} degrees there are {len(solutions)} solutions, to wit:"
write(stdout, " ")
for i in 0..<len(solutions):
write(stdout, fmt"{solutions[i]:25}")
if i mod 3 == 2:
write(stdout, "\n ")
write(stdout, "\n")
echo "\nFor sides in the range [1, 10000] where they cannot ALL be of the same length:\n"
var solutions = solve(60, 10000, false)
echo fmt" For an angle of 60 degrees there are {len(solutions)} solutions."</lang>
 
{{out}}
<pre>
For sides in the range [1, 13] where they can all be the same length:
 
For an angle of 90 degrees there are 3 solutions, to wit:
(a: 3, b: 4, c: 5) (a: 5, b: 12, c: 13) (a: 6, b: 8, c: 10)
For an angle of 60 degrees there are 15 solutions, to wit:
(a: 1, b: 1, c: 1) (a: 2, b: 2, c: 2) (a: 3, b: 3, c: 3)
(a: 3, b: 8, c: 7) (a: 4, b: 4, c: 4) (a: 5, b: 5, c: 5)
(a: 5, b: 8, c: 7) (a: 6, b: 6, c: 6) (a: 7, b: 7, c: 7)
(a: 8, b: 8, c: 8) (a: 9, b: 9, c: 9) (a: 10, b: 10, c: 10)
(a: 11, b: 11, c: 11) (a: 12, b: 12, c: 12) (a: 13, b: 13, c: 13)
For an angle of 120 degrees there are 2 solutions, to wit:
(a: 3, b: 5, c: 7) (a: 7, b: 8, c: 13)
 
For sides in the range [1, 10000] where they cannot ALL be of the same length:
 
For an angle of 60 degrees there are 18394 solutions.
</pre>
 
Anonymous user