perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 329 - Task 1: Counter Integers

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-329/#TASK1
 3 #
 4 # Task 1: Counter Integers
 5 # ========================
 6 #
 7 # You are given a string containing only lower case English letters and digits.
 8 #
 9 # Write a script to replace every non-digit character with a space and then
10 # return all the distinct integers left.
11 #
12 ## Example 1
13 ##
14 ## Input: $str = "the1weekly2challenge2"
15 ## Output: 1, 2
16 ##
17 ## 2 is appeared twice, so we count it one only.
18 #
19 #
20 ## Example 2
21 ##
22 ## Input: $str = "go21od1lu5c7k"
23 ## Output: 21, 1, 5, 7
24 #
25 #
26 ## Example 3
27 ##
28 ## Input: $str = "4p3e2r1l"
29 ## Output: 4, 3, 2, 1
30 #
31 ############################################################
32 ##
33 ## discussion
34 ##
35 ############################################################
36 #
37 # This one is fairly simple:
38 # - replace all non-digits by whitespace
39 # - remove leading or trailing whitespace
40 # - split string at whitespaces into individual integers
41 # - for each integer, put it into the result array unless it's
42 #   already there
43 
44 use v5.36;
45 
46 counter_integers("the1weekly2challenge2");
47 counter_integers("go21od1lu5c7k");
48 counter_integers("4p3e2r1l");
49 
50 sub counter_integers($str) {
51     say "Input: \"$str\"";
52     $str =~ s/[^\d]/ /g;
53     $str =~ s/^\s+//;
54     $str =~ s/\s+$//;
55     my @integers = split /\s+/, $str;
56     my @result = ();
57     my $seen = {};
58     foreach my $integer (@integers) {
59         push @result, $integer unless $seen->{$integer};
60         $seen->{$integer} = 1;
61     }
62     say "Output: " . join(", ", @result);
63 }
64