in reply to (Efficiency Golf) Triangular numbers

I've pasted in the full program and its output. The strategy is to preselect the numbers to consider by populating arrays with only the triangular numbers which match the pattern of digits implied by 'THREE' and friends. Then I look for pairs of 5 and 3 digit numbers which can correspond to 'THREE' and 'TEN'. That leaves just two pairs, which speeds the search for 'ONE' and 'SIX' a lot.

This isn't very general or clever, just gets the job done.

Full Output:

There are 31 three digit triangular numbers There are 307 five digit triangular numbers There are 26 three digit ones which lack matching digits. There are 9 five digit ones matching the pattern 'THREE'. THREE: 17955 ONE: 435 SIX: 820 TEN: 153 Elapsed time: 0.02 0 0 0

Full Listing:

#!/usr/bin/perl -w # -*-Perl-*- use strict; sub triangular { use integer; my $n=shift; $n*($n+1)/2; } my @threedigit = map triangular($_), (int(sqrt(2*100))..int(sqrt(2*1000))); my @fivedigit = map triangular($_), (int(sqrt(2*10000))..int(sqrt(2*100000))); print "There are ".scalar @threedigit." three digit triangular numbers +\n"; print "There are ".scalar @fivedigit." five digit triangular numbers\n +"; my @threes; for (@threedigit){ $_ !~ m/(\d)\d*\1/g and push @threes,$_; } @threedigit = @threes; @threes = (); print "There are ".scalar @threedigit." three digit ones which lack ma +tching digits.\n"; my @fives; for (@fivedigit){ $_ =~ m/^\d*(\d)\1$/ and $_ !~ m/^\d*(\d)\d*\1\d+$/g and push @fives,$_;} @fivedigit = @fives; @fives = (); print "There are ".scalar @fivedigit." five digit ones matching the pa +ttern 'THREE'.\n"; my @THREE; my @TEN; # eliminate fives which dont give a TEN for (@fivedigit) { my $t5 = $_; my ($T,$H,$R,$E) = split //,$t5; my $N = "[^$T$H$R$E]"; for (@threedigit) { my $t3 = $_; my @t3 = split //, $t3; if ($t3 =~ m/$T$E$N/){ $N=$t3[2]; push @threes, $t3; push @fives, $t5; } } } # Now Brute Force my $size = $#fives; my %solution = ('THREE'=>[],'TEN'=>[],'ONE'=>[],'SIX'=>[]); my $idx; for $idx (0..$size) { my ($T,$H,$R,$E) = split //, $fives[$idx]; my ($XT,$XE,$N) = split //, $threes[$idx]; my $cc = "[^$T$H$R$E$N]"; for (@threedigit){ my $num = $_; if ($num =~ m/$cc$N$E/){ my $O = (split //, $num)[0]; my $cc="[^$T$H$R$E$N$O]"; for (@threedigit){ if ($_ =~ /$cc{3}/){ my ($S,$I,$X) = split //, $_; push @{$solution{'THREE'}}, $fives[$idx]; push @{$solution{'TEN'}}, $threes[$idx]; push @{$solution{'ONE'}}, $num; push @{$solution{'SIX'}}, $_; } } } } } # write out solution and timings for (keys %solution) { print "$_:\t",join("\t",@{$solution{$_}}),"\n"; } my @tim = times(); print "Elapsed time:\t",join "\t", @tim,"\n";

After Compline

Zaxo

In Section
Meditations