Week 370
My Solutions
Task 1 : Popular Word (By M. Anwar)
You are given a string paragraph and an array of the banned words. Write a script to return the most popular word that is not banned. It is guaranteed there is at least one word that is not banned and the answer is unique. The words in paragraph are case-insensitive and the answer should be in lowercase. The words can not contain punctuation symbols.
For frequency of words I immediately plan to use a hash. My only hangup on this one was when the input paragraph was not space separated but used punctuation marks instead. This could be more robust, but that's an abnormal input. I turn everything lowercase, check for spaces, strip out the punctuation marks, and put the word count in the hash %h. Then we ignore banned words.
sub strip($w) {
my $out;
for my $letter (split '', $w) {
$out .= $letter if ($letter =~ /\w/);
}
return $out;
}
sub proc($paragraph, @banned) {
say "Input: \$paragraph = $paragraph\n\t\@banned = @banned";
my @words;
if ($paragraph =~ /\s/) {
@words = split ' ', lc $paragraph;
} else {
my $word;
for my $letter (split '', lc $paragraph) {
if ($letter =~ /[a-zA-Z]/) {
$word .= $letter;
} else {
push @words, $word;
$word = "";
}
}
}
my %h;
foreach my $word (@words) {
$word = strip($word);
$h{$word}++;
}
my $max = 0;
my $max_word;
for my $w (keys %h) {
my $ban = 0;
for my $banned_word (@banned) {
if ($w eq $banned_word) {
$ban = 1;
last;
}
}
next if ($ban);
if ($max < $h{$w}) {
$max_word = $w;
$max = $h{$w};
}
}
say "Output: $max_word";
}
Task 2: Scramble String (By R. B-W)
You are given two strings $str1 and $str2 of the same length. Write a script to return true if $str2 is a scramble of $str1 otherwise return false. String B is a scramble of string A if A can be transformed into B by a single (recursive) scramble operation.
Mr. Roger Bell-West then goes on to explain what a scramble is.
- If the string consists of only one character, return the string.
- Divide the string X into two non-empty parts.
- Optionally, exchange the order of those parts.
- Optionally, scramble each of those parts.
- Concatenate the scrambled parts to return a single string.
When the task was first described, he had suggested choosing a random location for the split, and randomly deciding to perform the scrambles or swaps. I decided to embrace that approach.
I loop the scramble 10,000 times to increase the odds of success.
sub scramble($s) {
my $len = length($s);
if ($len == 1) {
return $s;
} else {
my $pt = 1 + ($len - 1) * rand();
my $a = substr $s, 0, $pt;
my $b = substr $s, $pt;
my $a_new = (int 2*rand() == 0) ? $a : scramble($a);
my $b_new = (int 2*rand() == 0) ? $b : scramble($b);
my $out = (int 2*rand() == 0) ? $a_new.$b_new : $b_new.$a_new;
}
}









