Triangles Challenge

brian_d_foy on 2005-01-28T18:06:44

I didn't see a Perl solution in the Triangles Challenge. Everyone there seems to love Lisp.

Can anyone defend Perl's honor?


Done!! :-)

cog on 2005-01-28T19:01:32

30 minutes, 37 lines :-)

Unfortunately, I now realized the contest is over, so I don't think I can submit my Perl solution... :-\

Re:Done!! :-)

cog on 2005-01-28T19:02:18

#!/usr/bin/perl
use warnings;
use strict;
use Math::Combinatorics;

my %points = (
        0 => [ 0 .. 10 ],
        1 => [ 0 .. 10 ],
        2 => [ 4, 6, 1, 3, 5, 0 ],
        3 => [ 5, 2, 1, 7, 9, 0 ],
        4 => [ 6, 2, 0, 7, 8, 1 ],
        5 => [ 0, 8, 10, 2, 1 ],
        6 => [ 10, 9, 1, 4, 2, 0 ],
        7 => [ 8, 9, 3, 4, 1, 0 ],
        8 => [ 10, 0, 5, 7, 4, 1 ],
        9 => [ 10, 6, 1, 0, 3, 7 ],
        10 => [ 0, 5, 8, 1, 6, 9 ],
);

my @lines = (
        [ 0, 5, 8, 10 ],
        [ 0, 3, 7, 9 ],
        [ 0, 2, 4, 6 ],
        [ 0, 1 ],
        [ 1, 6, 9, 10 ],
        [ 1, 4, 7, 8 ],
        [ 1, 2, 3, 5 ],
);

print "There are ", (scalar grep {is_triangle(@$_)} combine(3,0..10)), " triangles.\n";

sub is_triangle {
    (grep {$_ eq $_[1]} @{$points{$_[0]}}) &&
    (grep {$_ eq $_[2]} @{$points{$_[0]}}) &&
    (grep {$_ eq $_[2]} @{$points{$_[1]}}) &&
    ! grep { 3 == grep { $_ eq $_[0] or $_ eq $_[1] or $_ eq $_[2] } @$_ } @lines;
}

Re:Done!! :-)

Mr. Muskrat on 2005-01-29T03:59:56

Good job. It passes the second test shown on the page too.

#!/usr/bin/perl
use warnings;
use strict;
use Math::Combinatorics;

# I removed the points 0, 2, 4, 6 and the line from 0 6
# Resulting in the second example which has 15 triangles

my %points = (
        0 => [ 0, 1, 3, 5, 7 .. 10 ],
        1 => [ 0, 1, 3, 5, 7 .. 10 ],
        3 => [ 5, 1, 7, 9, 0 ],
        5 => [ 0, 8, 10, 1 ],
        7 => [ 8, 9, 3, 1, 0 ],
        8 => [ 10, 0, 5, 7, 1 ],
        9 => [ 10, 1, 0, 3, 7 ],
        10 => [ 0, 5, 8, 1, 9 ],
);

my @lines = (
        [ 0, 5, 8, 10 ],
        [ 0, 3, 7, 9 ],
        [ 0, 1 ],
        [ 1, 9, 10 ],
        [ 1, 7, 8 ],
        [ 1, 3, 5 ],
);

print "There are ", (scalar grep {is_triangle(@$_)} combine(3,0..10)), " triangles.\n";

sub is_triangle {
    (grep {$_ eq $_[1]} @{$points{$_[0]}}) &&
    (grep {$_ eq $_[2]} @{$points{$_[0]}}) &&
    (grep {$_ eq $_[2]} @{$points{$_[1]}}) &&
    ! grep { 3 == grep { $_ eq $_[0] or $_ eq $_[1] or $_ eq $_[2] } @$_ } @lines;
}

Re:Done!! :-)

cog on 2005-01-29T14:08:13

There was a second test? :-|