Heronian triangles: Difference between revisions

From Rosetta Code
Content added Content deleted
(J)
(jq)
Line 139: Line 139:
7 65 68 _ 210 140
7 65 68 _ 210 140
3 148 149 _ 210 300</lang>
3 148 149 _ 210 300</lang>

=={{header|jq}}==
{{works with|jq|1.4}}
<lang jq># input should be an array of the lengths of the sides
def hero:
(add/2) as $s
| ($s*($s - .[0])*($s - .[1])*($s - .[2])) as $a2
| if $a2 > 0 then ($a2 | sqrt) else 0 end;

def is_heronian:
hero as $h
| $h > 0 and ($h|floor) == $h;
def gcd3(x; y; z):
# subfunction expects [a,b] as input
def rgcd:
if .[1] == 0 then .[0]
else [.[1], .[0] % .[1]] | rgcd
end;
[ ([x,y] | rgcd), z ] | rgcd;
def task(maxside):
def rjust(width): tostring | " " * (width - length) + .;
[ range(1; maxside+1) as $c
| range(1; $c+1) as $b
| range(1; $b+1) as $a
| if ($a + $b) > $c and gcd3($a; $b; $c) == 1
then [$a,$b,$c] | if is_heronian then . else empty end
else empty
end ]

# sort by increasing area, perimeter, then sides
| sort_by( [ hero, add, .[2] ] )
| "The number of primitive Heronian triangles with sides up to \(maxside): \(length)",
"The first ten when ordered by increasing area, then perimeter, then maximum sides:",
" perimeter area",
(.[0:10][] | "\(rjust(11)) \(add | rjust(3)) \(hero | rjust(4))" ),
"All those with area 210, ordered as previously:",
" perimeter area",
( .[] | select( hero == 210 ) | "\(rjust(11)) \(add|rjust(3)) \(hero|rjust(4))" ) ;

task(200)</lang>
{{out}}
<lang sh>$ time jq -n -r -f heronian.jq
The number of primitive Heronian triangles with sides up to 200: 517
The first ten when ordered by increasing area, then perimeter, then maximum sides:
perimeter area
[3,4,5] 12 6
[5,5,6] 16 12
[5,5,8] 18 12
[4,13,15] 32 24
[5,12,13] 30 30
[9,10,17] 36 36
[3,25,26] 54 36
[7,15,20] 42 42
[10,13,13] 36 60
[8,15,17] 40 60
All those with area 210, ordered as previously:
perimeter area
[17,25,28] 70 210
[20,21,29] 70 210
[12,35,37] 84 210
[17,28,39] 84 210
[7,65,68] 140 210
[3,148,149] 300 210</lang>


=={{header|Perl}}==
=={{header|Perl}}==

Revision as of 08:52, 4 January 2015

Task
Heronian triangles
You are encouraged to solve this task according to the task description, using any language you may know.

Hero's formula for the area of a triangle given the length of its three sides a, b, and c is given by:

where s is half the perimeter of the triangle; that is,

Heronian triangles are triangles whose sides and area are all integers.

An example is the triangle with sides 3, 4, 5 whose area is 6 (and whose perimeter is 12).

Note that any triangle whose sides are all an integer multiple of 3,4,5; such as 6,8,10, will also be a heronian triangle.

Define a Primitive Heronian triangle as a heronian triangle where the greatest common divisor of all three sides is 1. this will exclude, for example triangle 6,8,10

The task is to:

  1. Create a named function/method/proceedure/... that implements Hero's formula.
  2. Use the function to generate all the primitive heronian triangles with sides <= 200.
  3. Show the count of how many triangles are found.
  4. Order the triangles by first increasing area, then by increasing perimeter, then by increasing maximum side lengths
  5. Show the first ten ordered triangles in a table of sides, perimeter, and area.
  6. Show a similar ordered table for those triangles with area = 210

Show all output here.

Note: when generating triangles it may help to restrict

D

Translation of: 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;
   // Sort by increasing area, perimeter, then sides.
   //auto h = cartesianProduct!3(iota(1, maxSide + 1))
   auto r = iota(1, maxSide + 1);
   const 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
             .schwartzSort!(t => tuple(t[].hero, t[].only.sum, t.reverse))
             .release;
   static void showTriangles(R)(R ts) @safe {
       "Area Perimeter Sides".writeln;
       foreach (immutable t; ts)
           writefln("%3s %8d %3dx%dx%d", t[].hero, t[].only.sum, t[]);
   }
   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;
   showTriangles(h.take(10));
   "\nAll with area 210 subject to the previous ordering:".writeln;
   showTriangles(h.filter!(t => t[].hero == 210));

}</lang>

Output:
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

J

Supporting implementation:

<lang J>a=:0&{"1 b=:1&{"1 c=:2&{"1 s=:(a+b+c)%2: A=:2 %: s*(s-a)*(s-b)*(s-c) P=:+/"1 isprimhero=:(0&~:*(=<.@+))@A*1=a+.b+.c

tri=: (/: A,.P,.{:"1) (#~ isprimhero)~./:"1~1+200 200 200#:i.200^3</lang>

Required examples:

<lang J> #tri 517

  10{.(,._,.A,.P) tri
3  4  5 _  6 12
5  5  6 _ 12 16
5  5  8 _ 12 18
4 13 15 _ 24 32
5 12 13 _ 30 30
9 10 17 _ 36 36
3 25 26 _ 36 54
7 15 20 _ 42 42

10 13 13 _ 60 36

8 15 17 _ 60 40
  (#~210=A) (,._,.A,.P) tri

17 25 28 _ 210 70 20 21 29 _ 210 70 12 35 37 _ 210 84 17 28 39 _ 210 84

7  65  68 _ 210 140
3 148 149 _ 210 300</lang>

jq

Works with: jq version 1.4

<lang jq># input should be an array of the lengths of the sides def hero:

 (add/2) as $s
 | ($s*($s - .[0])*($s - .[1])*($s - .[2])) as $a2
 | if $a2 > 0 then ($a2 | sqrt) else 0 end;

def is_heronian:

 hero as $h
 | $h > 0 and ($h|floor) == $h;

def gcd3(x; y; z):

 # subfunction expects [a,b] as input
 def rgcd:
   if .[1] == 0 then .[0]
   else [.[1], .[0] % .[1]] | rgcd
   end;
 [ ([x,y] | rgcd), z ] | rgcd;

def task(maxside):

 def rjust(width): tostring |  " " * (width - length) + .;
 
 [ range(1; maxside+1) as $c
   | range(1; $c+1) as $b
   | range(1; $b+1) as $a
   | if ($a + $b) > $c and gcd3($a; $b; $c) == 1
     then [$a,$b,$c] | if is_heronian then . else empty end
     else empty
     end ]
 # sort by increasing area, perimeter, then sides
 | sort_by( [ hero, add, .[2] ] )  
 | "The number of primitive Heronian triangles with sides up to \(maxside): \(length)",
   "The first ten when ordered by increasing area, then perimeter, then maximum sides:",
   "      perimeter area",
   (.[0:10][] | "\(rjust(11)) \(add | rjust(3)) \(hero | rjust(4))" ),
   "All those with area 210, ordered as previously:",
   "      perimeter area",
   ( .[] | select( hero == 210 ) | "\(rjust(11)) \(add|rjust(3)) \(hero|rjust(4))" ) ;

task(200)</lang>

Output:

<lang sh>$ time jq -n -r -f heronian.jq The number of primitive Heronian triangles with sides up to 200: 517 The first ten when ordered by increasing area, then perimeter, then maximum sides:

     perimeter area
   [3,4,5]  12    6
   [5,5,6]  16   12
   [5,5,8]  18   12
 [4,13,15]  32   24
 [5,12,13]  30   30
 [9,10,17]  36   36
 [3,25,26]  54   36
 [7,15,20]  42   42
[10,13,13]  36   60
 [8,15,17]  40   60

All those with area 210, ordered as previously:

     perimeter area
[17,25,28]  70  210
[20,21,29]  70  210
[12,35,37]  84  210
[17,28,39]  84  210
 [7,65,68] 140  210

[3,148,149] 300 210</lang>

Perl

Translation of: Perl 6

<lang perl>use strict; use warnings; use List::Util qw(max);

sub gcd { $_[1] == 0 ? $_[0] : gcd($_[1], $_[0] % $_[1]) }

sub hero {

   my ($a, $b, $c) = @_[0,1,2];
   my $s = ($a + $b + $c) / 2;
   sqrt $s*($s - $a)*($s - $b)*($s - $c);

}

sub heronian_area {

   my $hero = hero my ($a, $b, $c) = @_[0,1,2];
   sprintf("%.0f", $hero) eq $hero ? $hero : 0

}

sub primitive_heronian_area {

   my ($a, $b, $c) = @_[0,1,2];
   heronian_area($a, $b, $c) if 1 == gcd $a, gcd $b, $c;

}

sub show {

   print "   Area Perimeter   Sides\n";
   for (@_) {
       my ($area, $perim, $c, $b, $a) = @$_;

printf "%7d %9d %d×%d×%d\n", $area, $perim, $a, $b, $c;

   }

}

sub main {

   my $maxside = shift // 200;
   my $first = shift // 10;
   my $witharea = shift // 210;
   my @h;
   for my $c (1 .. $maxside) {

for my $b (1 .. $c) { for my $a ($c - $b + 1 .. $b) { if (my $area = primitive_heronian_area $a, $b, $c) { push @h, [$area, $a+$b+$c, $c, $b, $a]; } } }

   }
   @h = sort {

$a->[0] <=> $b->[0] or $a->[1] <=> $b->[1] or max(@$a[2,3,4]) <=> max(@$b[2,3,4])

   } @h;
   printf "Primitive Heronian triangles with sides up to %d: %d\n",
   $maxside,
   scalar @h;
   print "First:\n";
   show @h[0 .. $first - 1];
   print "Area $witharea:\n";
   show grep { $_->[0] == $witharea } @h;


}

&main();</lang>

Output:
Primitive Heronian triangles with sides up to 200: 517
First:
   Area Perimeter   Sides
      6        12    3×4×5
     12        16    5×5×6
     12        18    5×5×8
     24        32    4×13×15
     30        30    5×12×13
     36        36    9×10×17
     36        54    3×25×26
     42        42    7×15×20
     60        36    10×13×13
     60        40    8×15×17
Area 210:
   Area Perimeter   Sides
    210        70    17×25×28
    210        70    20×21×29
    210        84    12×35×37
    210        84    17×28×39
    210       140    7×65×68
    210       300    3×148×149

Perl 6

Works with: rakudo version 2015-01-03

<lang perl6>sub hero($a, $b, $c) {

   my $s = ($a + $b + $c) / 2;
   my $a2 = $s * ($s - $a) * ($s - $b) * ($s - $c);
   $a2.sqrt;

}

sub heronian-area($a, $b, $c) {

   $_ when Int given hero($a, $b, $c).narrow;

}

sub primitive-heronian-area($a, $b, $c) {

   heronian-area $a, $b, $c
       if 1 == [gcd] $a, $b, $c;

}

sub show {

   say "   Area Perimeter   Sides";
   for @_ -> [$area, $perim, $c, $b, $a] {

printf "%6d %6d %12s\n", $area, $perim, "$a×$b×$c";

   }

}

sub MAIN ($maxside = 200, $first = 10, $witharea = 210) {

   my \h = sort gather
       for 1 .. $maxside -> $c {
           for 1 .. $c -> $b {
               for $c - $b + 1 .. $b -> $a {
                   if primitive-heronian-area($a,$b,$c) -> $area {
                       take [$area, $a+$b+$c, $c, $b, $a];
                   }
               }
           }
       }
   say "Primitive Heronian triangles with sides up to $maxside: ", +h;
   say "\nFirst $first:";
   show h[^$first];
   say "\nArea $witharea:";
   show h.grep: *[0] == $witharea;

}</lang>

Output:
Primitive Heronian triangles with sides up to 200: 517

First 10:
   Area Perimeter   Sides
     6     12        3×4×5
    12     16        5×5×6
    12     18        5×5×8
    24     32      4×13×15
    30     30      5×12×13
    36     36      9×10×17
    36     54      3×25×26
    42     42      7×15×20
    60     36     10×13×13
    60     40      8×15×17

Area 210:
   Area Perimeter   Sides
   210     70     17×25×28
   210     70     20×21×29
   210     84     12×35×37
   210     84     17×28×39
   210    140      7×65×68
   210    300    3×148×149

Python

<lang python>from math import sqrt from fractions import gcd from itertools import product


def hero(a, b, c):

   s = (a + b + c) / 2
   a2 = s*(s-a)*(s-b)*(s-c)
   return sqrt(a2) if a2 > 0 else 0
   
   

def is_heronian(a, b, c):

   a = hero(a, b, c)
   return a > 0 and a.is_integer()
   

def gcd3(x, y, z):

   return gcd(gcd(x, y), z)


if __name__ == '__main__':

   maxside = 200
   h = [(a, b, c) for a,b,c in product(range(1, maxside + 1), repeat=3) 
        if a <= b <= c and a + b > c and gcd3(a, b, c) == 1 and is_heronian(a, b, c)]
   h.sort(key = lambda x: (hero(*x), sum(x), x[::-1]))   # By increasing area, perimeter, then sides
   print('Primitive Heronian triangles with sides up to %i:' % maxside, len(h))
   print('\nFirst ten when ordered by increasing area, then perimeter,then maximum sides:')
   print('\n'.join('  %14r perim: %3i area: %i' 
                   % (sides, sum(sides), hero(*sides)) for sides in h[:10]))
   print('\nAll with area 210 subject to the previous ordering:')
   print('\n'.join('  %14r perim: %3i area: %i' 
                   % (sides, sum(sides), hero(*sides)) for sides in h
                   if hero(*sides) == 210))</lang>
Output:
Primitive Heronian triangles with sides up to 200: 517

First ten when ordered by increasing area, then perimeter,then maximum sides:
       (3, 4, 5) perim:  12 area: 6
       (5, 5, 6) perim:  16 area: 12
       (5, 5, 8) perim:  18 area: 12
     (4, 13, 15) perim:  32 area: 24
     (5, 12, 13) perim:  30 area: 30
     (9, 10, 17) perim:  36 area: 36
     (3, 25, 26) perim:  54 area: 36
     (7, 15, 20) perim:  42 area: 42
    (10, 13, 13) perim:  36 area: 60
     (8, 15, 17) perim:  40 area: 60

All with area 210 subject to the previous ordering:
    (17, 25, 28) perim:  70 area: 210
    (20, 21, 29) perim:  70 area: 210
    (12, 35, 37) perim:  84 area: 210
    (17, 28, 39) perim:  84 area: 210
     (7, 65, 68) perim: 140 area: 210
   (3, 148, 149) perim: 300 area: 210

zkl

Translation of: Python

<lang zkl>fcn hero(a,b,c){ //--> area (float)

  s,a2:=(a + b + c).toFloat()/2, s*(s - a)*(s - b)*(s - c);
  (a2 > 0) and a2.sqrt() or 0.0

} fcn isHeronian(a,b,c){

  A:=hero(a,b,c);
  (A>0) and A.modf()[1].closeTo(0.0,1.0e-6) and A  //--> area or False

}</lang> <lang zkl>const MAX_SIDE=200; heros:=Sink(List); foreach a,b,c in ([1..MAX_SIDE],[a..MAX_SIDE],[b..MAX_SIDE]){

  if(a.gcd(b).gcd(c)==1 and (h:=isHeronian(a,b,c))) heros.write(T(h,a+b+c,a,b,c));

} // sort by increasing area, perimeter, then sides heros=heros.close().sort(fcn([(h1,p1,_,_,c1)],[(h2,p2,_,_,c2)]){

  if(h1!=h2) return(h1<h2);
  if(p1!=p2) return(p1<p2);
  c1<c2;

});

println("Primitive Heronian triangles with sides up to %d: ".fmt(MAX_SIDE),heros.len());

println("First ten when ordered by increasing area, then perimeter,then maximum sides:"); println("Area Perimeter Sides"); heros[0,10].pump(fcn(phabc){ "%3s %8d %3dx%dx%d".fmt(phabc.xplode()).println() });

println("\nAll with area 210 subject to the previous ordering:"); println("Area Perimeter Sides"); heros.filter(fcn([(h,_)]){ h==210 })

 .pump(fcn(phabc){ "%3s %8d %3dx%dx%d".fmt(phabc.xplode()).println() });</lang>
Output:
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