RabbitFarm
2022-12-18
Especially Frequent Even
The examples used here are from the weekly challenge problem statement and demonstrate the working solution.
Part 1
You are given a positive integer, $n > 0. Write a script to print the count of all special integers between 1 and $n.
Solution
use v5.36;
use boolean;
sub is_special{
my($x) = @_;
my %h;
my @digits = split(//, $x);
map{ $h{$_} = undef } @digits;
return keys %h == @digits;
}
MAIN:{
say q// . grep{ is_special($_) } 1 .. $ARGV[0];
}
Sample Run
$ perl perl/ch-1.pl 15
14
$ perl perl/ch-1.pl 35
32
Notes
The definition of a special integer for this problem is an integer whose digits are
unique. To determine this specialness we define is_special()
which splits any given
number into an array of digits. Each of the digits are added to a hash as the keys. If any
digits are not unique then they will not be duplicated as a hash key and the test will
return false.
Once is_special()
is set all we need to do is to map over the given range and count up
the results!
Part 2
You are given a list of numbers, @list. Write a script to find most frequent even numbers in the list. In case you get more than one even numbers then return the smallest even integer. For all other case, return -1.
Solution
use v5.36;
sub most_frequent_even{
my @list = @_;
@list = grep { $_ % 2 == 0 } @list;
return -1 if @list == 0;
my %frequencies;
map { $frequencies{$_}++ } @list;
my @sorted = sort { $frequencies{$b} <=> $frequencies{$a} } @list;
return $sorted[0] if $frequencies{$sorted[0]} != $frequencies{$sorted[1]};
my @tied = grep { $frequencies{$_} == $frequencies{$sorted[0]} } @list;
return (sort { $a <=> $b } @tied)[0];
}
MAIN:{
my @list;
@list = (1, 1, 2, 6, 2);
say most_frequent_even(@list);
@list = (1, 3, 5, 7);
say most_frequent_even(@list);
@list = (6, 4, 4, 6, 1);
say most_frequent_even(@list);
}
Sample Run
$ perl perl/ch-2.pl
2
-1
4
Notes
map and grep really do a lot to make this solution pretty succinct. First grep is used to extract just the even numbers. Then map is used to count up the frequencies. In the case of ties grep is used to identify the numbers with a tied frequency. The tied numbers are then sorted with the lowest one being returned, as specified.
References
posted at: 00:53 by: Adam Russell | path: /perl | permanent link to this entry