#!/usr/bin/perl -w # # "Loop Abstraction Via Recursion" # # 060111 by liverpole # # Strict use strict; use warnings; # User-defined my @list = qw( 1 2 3 4 5 ); # Prototypes sub abstract_loop($$$); sub arbitrary_N_loops($;$$); sub show_results($$$); # Globals my $N; # The number of loops (which we want to abstract) my $total; # Total match attempts my $pvals = [ ]; # The list of values my $nmatch = 0; # Total matches # Subroutines sub match(@) { my ($plist) = @_; my $sum = 0; my $prod = 1; map { $prod *= $_; $sum += $_ } @$plist; my $div = ($prod / $sum); ($div == int($div)); } sub show_results($$$) { my ($nloops, $nmatch, $total) = @_; my $pct = ($total)? int(1000 * $nmatch / $total) / 10: 0; my $s = (1 == $nloops)? " ": "s"; printf "[%3d loop$s] ", $nloops; printf "Matches: %8d / %9d ", $nmatch, $total; printf "(%5.1f%%)\n", $pct; } # Main program # One loop $N = 1; $nmatch = $total = 0; foreach (@list) { push @$pvals, $_; # Add a new value to the list match($pvals) and ++$nmatch; # Check if it matches the criteria ++$total; # Add 1 to the total count pop @$pvals; # Remove the value at the end } show_results($N, $nmatch, $total);