Hi everybody! Just doing one challenge again this week. Time limitations hold me back once again.
This week we're looking for the letters of a target word in a source word, and we're not allowed to use the same letter twice. Spoiler alert because it's only Wednesday and you still have the rest of the week to submit solutions if desired.
The easiest way to do this is with a dictionary hash initialized like so:
foreach (split //, $source) {$chars{$_}++}
Many people use map()
to do this, but I'm not a big fan of map in many cases because I feel it makes code less readable.
This gives us the number of occurrences of each letter in the original word.
Then we iterate through the target word and look for (and remove) the letters in the dictionary:
foreach (split //, $target) {
if ($chars{$_}) {
$chars{$_}--;
} else {
say 'false' and exit;
}
}
say 'true';
Obviously if the script did more than just this we'd need a success flag in there instead, but as it is we can just exit if we ever don't find the matching character in the dictionary.
Anyways, that's the solution for this week! I have a definite idea of how I'd solve the second challenge, I just don't have the time to implement it. I look forward to seeing the other solutions, because I'm sure they'll have more efficient ways to do it.
Top comments (0)