RosettaCodeData/Task/Self-referential-sequence/Perl-6/self-referential-sequence.pl6

47 lines
1.4 KiB
Raku
Raw Permalink Normal View History

2013-04-10 23:57:08 -07:00
my @list;
my $longest = 0;
my %seen;
for 1 .. 1000000 -> $m {
next unless $m ~~ /0/; # seed must have a zero
my $j = join '', $m.comb.sort;
2016-12-05 22:15:40 +01:00
next if %seen{$j}:exists; # already tested a permutation
2013-04-10 23:57:08 -07:00
%seen{$j} = '';
2018-06-22 20:57:24 +00:00
my @seq = converging($m);
2013-04-10 23:57:08 -07:00
my %elems;
my $count;
for @seq[] -> $value { last if ++%elems{$value} == 2; $count++; };
if $longest == $count {
@list.push($m);
}
elsif $longest < $count {
$longest = $count;
@list = $m;
2018-06-22 20:57:24 +00:00
print "\b" x 20, "$count, $m"; # monitor progress
2013-04-10 23:57:08 -07:00
}
};
for @list -> $m {
2018-06-22 20:57:24 +00:00
say "\nSeed Value(s): ", my $seeds = ~permutations($m).unique.grep( { .substr(0,1) != 0 } );
my @seq = converging($m);
2013-04-10 23:57:08 -07:00
my %elems;
my $count;
for @seq[] -> $value { last if ++%elems{$value} == 2; $count++; };
say "\nIterations: ", $count;
say "\nSequence: (Only one shown per permutation group.)";
2018-06-22 20:57:24 +00:00
.say for |@seq[^$count], "\n";
2013-04-10 23:57:08 -07:00
}
sub converging ($seed) { return $seed, -> $l { join '', map { $_.value.elems~$_.key }, $l.comb.classify({$^b}).sort: {-$^c.key} } ... * }
sub permutations ($string, $sofar? = '' ) {
return $sofar unless $string.chars;
my @perms;
for ^$string.chars -> $idx {
my $this = $string.substr(0,$idx)~$string.substr($idx+1);
my $char = substr($string, $idx,1);
2016-12-05 22:15:40 +01:00
@perms.push( |permutations( $this, join '', $sofar, $char ) );
2013-04-10 23:57:08 -07:00
}
return @perms;
}