For both of these challenges, even though the requirement is matching two values, my solutions will work with two or more values.
While there is probably a Math:: function that generates the factors of a given number, I'm of the belief that it defeats the point of the weekly challenge. I tend to only use List::Util functions, which is part of Perl core.
This is a relatively straight forward task. I create a loop from 1 to the minimum of the supplied values (any value greater than this won't be a factor of the minimum number). I then add that number to the result if the division of all inputs by the number results in no remainder.
» ./ch-1.pl 12 18 1, 2, 3, 6 » ./ch-1.pl 18 23 1
I'm really looking forward to seeing the solutions to this task by other Team PWC members. I'm not sure my solution is the best one, but it works. Let me also sing the praises of the map function. The best thing since sliced bread.
I start by short circuiting the code to return
0 if the length of the target is not the length of the other strings. No solution would be possible in this scenario.
The approach that I took was having any array of arrays called
@remaining. Each row represents the remaining letters available from each string. It starts with one row representing all the strings.
I then work through each letter of the target string. Using the map function, I take the first letter off any string that starts with that letter.
For example, in the first example ('XY X XXY'),
@remaining starts with
(('XY', 'X')). After the first run,
(('Y', 'X'), ('XY', '')) as both strings start with an 'X'. The second iteration would result in
(('Y', ''), ('Y', '')) removing the second 'X'. The final run would result with
(('', ''), ('', '')) removing the Y in the last character.
If at any point remaining has no values, we return
0. Once we have exhausted all letters, we know their is a solution, so return
» ./ch-2.pl XY X XXY 1 » ./ch-2.pl XXY XXZ XXXXZY 1 » ./ch-2.pl YX X XXY 0