Task1
We are asked to find and count the number of similar words. Two words are similar if they consist of the same characters. This can be done with sorting the unique characters of a string and keep their count in a hash:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #!/usr/bin/env perl use strict; use warnings; use List::Util qw(uniq sum0); sub similar_words{ my ($count,%h) = (0); map{$h{join '',uniq sort split ''}++} @{$_[0]}; $count += ($_ * ($_-1)) / 2 foreach values %h; $count } printf "%d\n", similar_words(["aba","aabb","abcd","bac","aabc"]); printf "%d\n", similar_words(["aabb","ab","ba"]); printf "%d\n", similar_words(["nba","cba","dba"]); |
Task2
We are asked to sort an array based on the frequency of the items, and if the frequency of two items are the same, we have to sort them in decreasing order:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #!/usr/bin/env perl use strict; use warnings; sub frequency_sort{ my ($arr) = @_; my %h; $h{$_}++ foreach @$arr; sort{$h{$a} <=> $h{$b} || $b <=> $a} @$arr; } printf "(%s)\n", join ',', frequency_sort([1,1,2,2,2,3]); printf "(%s)\n", join ',', frequency_sort([2,3,1,3,2]); printf "(%s)\n", join ',', frequency_sort([-1,1,-6,4,5,-6,1,4,1]); |
No comments:
Post a Comment