aboutsummaryrefslogtreecommitdiff
path: root/challenge-280/e-choroba/perl/ch-1.pl
blob: a05f90ec8128078730dd57f159a7063bed7fedb0 (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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/usr/bin/perl
use warnings;
use strict;
use experimental qw( signatures );

=head1 Two Interpretations

There are two interpretations that both fit to the examples given:

=over 4

=item 1.

The first character that appears for the second time is the answer.


=item 2.

The first character that appears for the second time B<and> doesn't appear any
more times is the answer.

=back

=cut

sub twice_appearance_1($str) {
    my %tally;
    for my $char (split //, $str) {
        return $char if 2 == ++$tally{$char};
    }
    return ""
}

sub twice_appearance_2($str) {
    my %tally;
    my @order;
    for my $char (split //, $str) {
        push @order, $char if 2 == ++$tally{$char};
    }
    for my $char (@order) {
        return $char if 2 == $tally{$char};
    }
    return ""
}

use Test::More tests => 2 * (3 + 2);

my @interpretation = qw( a d );

my $i = 0;
for my $twice_appearance(*twice_appearance_1{CODE}, *twice_appearance_2{CODE}) {
    is $twice_appearance->('acbddbca'), 'd', 'Example 1';
    is $twice_appearance->('abccd'), 'c', 'Example 2';
    is $twice_appearance->('abcdabbb'), 'a', 'Example 3';

    is $twice_appearance->('abcd'), "", 'Naught';
    is $twice_appearance->('abcdabcdabce'), $interpretation[$i++],
        "Interpretation $i";
}