root/examples/matrix.pl

Revision 17701, 2.1 kB (checked in by lwall, 16 months ago)

s:g/err/orelse/

  • Property svn:mime-type set to text/plain; charset=UTF-8
  • Property svn:eol-style set to native
Line 
1use v6-alpha;
2
3print "5x5 matrix in one line: " unless @*ARGS;
4my $matrix = @*ARGS[0] || =<>;
5$matrix ||= "abcdefghijklmnopqrstuvwxy";
6
7$matrix.chars == 25 or die "Matrix length MUST be 25 characters.\n";
8my @matrix  = [ '_' xx 7 ];
9push @matrix, [ '_', (split "", substr $matrix, 0, 5, ''), '_' ] while $matrix;
10push @matrix, [ '_' xx 7 ];
11my @adj;
12for 1..5 -> $y {
13    for 1..5 -> $x {
14        for -1..1 -> $dx {
15            for -1..1 -> $dy {
16                $dy or $dx or next;
17                @matrix[$y + $dy][$x + $dx] eq '_' and next;
18                push @adj[$y][$x], { x => ($x + $dx), y => ($y + $dy) };
19            }
20        }
21    }
22}
23
24
25sub build_re ($y, $x, $todo is copy, %had? is copy) {
26    %had{"$y/$x"} = 1;
27    my $r = @matrix[$y][$x] or die "y=$y,x=$x is empty";
28    --$todo or return $r;
29   
30    my @next; #= gather {
31        for @adj[$y][$x] -> $adj {
32            %had{"$adj<y>/$adj<x>"}++ and next;
33            #take build_re $adj<y>, $adj<x>, $todo, %had;
34            push @next, build_re $adj<y>, $adj<x>, $todo, %had;
35        }
36    #} or return $r;
37    @next or return $r;
38
39    return $todo == 1
40        ?? "$r\<[{ @next.join('') }]>?"
41        !! "$r\[{ @next.join('|') }]{ $todo < 4 ?? '?' !! '' }";
42}
43my @re;
44#say build_re 1, 1, 5;
45#say "done";
46#exit;
47
48#my $re = #rule {
49#    ^ [ <$(
50            for 1..5 -> $y {
51                for 1..5 -> $x {
52       push @re, build_re $y, $x, 6;
53                }
54            }
55#        }
56#    )> ] $
57#};
58
59my $re = join('|', @re);
60
61=foo
62
63my %scores = (
64  a => 1, b => 3, c => 3, d => 2, e => 1, f => 4, g => 2, h => 4, i => 1,
65  j => 8, k => 5, l => 1, m => 3, n => 1, o => 1, p => 3, q =>10, r => 1,
66  s => 1, t => 1, u => 1, v => 4, w => 4, x => 8, y => 4, z =>10
67);
68%scores.values >>*= 10;
69
70gather {
71    for slurp '/usr/share/dict/words' :chomp orelse die {
72        next if /<-[a-z]>/;
73        /$re/ and take { word => $_, score => %scores{ .letters }.sum };
74    }
75}
76==> sort [ { -.<score> }, { .<word>.length }, { .<word> } ];
77==> my @words;
78
79sayf 'MATRIX IS WORTH %d POINTS' <== sum @words>>[0];
80sayf '%3d %s' <== $_[1], $_[0] for @words;
Note: See TracBrowser for help on using the browser.