Heronian triangles: Difference between revisions

+ D entry
(→‎{{header|Perl 6}}: Perl translation)
(+ D entry)
Line 29:
 
<small>'''Note''': when generating triangles it may help to restrict <math>a <= b <= c</math></small>
=={{header|D}}==
{{trans|Python}}
<lang d>import std.stdio, std.math, std.range, std.algorithm, std.numeric, std.traits, std.typecons;
 
double hero(in uint a, in uint b, in uint c) pure nothrow @safe @nogc {
immutable s = (a + b + c) / 2.0;
immutable a2 = s * (s - a) * (s - b) * (s - c);
return (a2 > 0) ? a2.sqrt : 0.0;
}
 
bool isHeronian(in uint a, in uint b, in uint c) pure nothrow @safe @nogc {
immutable h = hero(a, b, c);
return h > 0 && h.floor == h.ceil;
}
 
T gcd3(T)(in T x, in T y, in T z) pure nothrow @safe @nogc {
return gcd(gcd(x, y), z);
}
 
void main() /*@safe*/ {
enum uint maxSide = 200;
 
//auto h = cartesianProduct!3(iota(1, maxSide + 1))
auto r = iota(1, maxSide + 1);
auto h = cartesianProduct(r, r, r)
//.filter!({a, b, c} => ...
.filter!(t => t[0] <= t[1] && t[1] <= t[2] &&
t[0] + t[1] > t[2] &&
t[].gcd3 == 1 && t[].isHeronian)
.array;
 
// By increasing area, perimeter, then sides.
h.schwartzSort!(t => tuple(t[].hero, t[].only.sum, t.reverse));
 
writefln("Primitive Heronian triangles with sides up to %d: %d", maxSide, h.length);
"\nFirst ten when ordered by increasing area, then perimeter,then maximum sides:".writeln;
"Area Perimeter Sides".writeln;
immutable fmt = "%3s %8d %3dx%dx%d";
foreach (immutable t; h.take(10))
writefln(fmt, t[].hero, t[].only.sum, t[]);
 
"\nAll with area 210 subject to the previous ordering:".writeln;
"Area Perimeter Sides".writeln;
foreach (immutable t; h.filter!(t => t[].hero == 210))
writefln(fmt, t[].hero, t[].only.sum, t[]);
}</lang>
{{out}}
<pre>Primitive Heronian triangles with sides up to 200: 517
 
First ten when ordered by increasing area, then perimeter,then maximum sides:
Area Perimeter Sides
6 12 3x4x5
12 16 5x5x6
12 18 5x5x8
24 32 4x13x15
30 30 5x12x13
36 36 9x10x17
36 54 3x25x26
42 42 7x15x20
60 36 10x13x13
60 40 8x15x17
 
All with area 210 subject to the previous ordering:
Area Perimeter Sides
210 70 17x25x28
210 70 20x21x29
210 84 12x35x37
210 84 17x28x39
210 140 7x65x68
210 300 3x148x149</pre>
 
=={{header|Perl}}==
{{trans|Perl 6}}