aboutsummaryrefslogtreecommitdiff
path: root/challenge-260/dave-jacoby/perl/ch-2.pl
blob: 2d06d124aa91035c1b0d0b967336735306db1bf8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#!/usr/bin/env perl

use strict;
use warnings;
use experimental qw{ say postderef signatures state };

use Algorithm::Permute;
use List::Util qw{ first uniq };

my @examples = (qw{ CAT GOOGLE SECRET });

for my $example (@examples) {
    my $output = dictionary_rank($example);

    say <<"END";
    Input: \$word = '$example'
    Output: $output
END
}

sub dictionary_rank ($word) {
    my @word = split //, $word;
    my @list;
    my $iter = Algorithm::Permute->new( \@word );
    while ( my @p = $iter->next ) {
        push @list, join '', @p;
    }
    @list = uniq sort @list;

    # would normally worry about a not-there response, but
    # since the permutations are based on the word, the word
    # has to be in there.
    my $i = first { $word eq $list[$_] } 0 .. scalar @list;
    return $i + 1;
}