Keep It Simple, Stupid | |
PerlMonks |
Re: Simple Math Puzzle...by hv (Prior) |
on May 10, 2003 at 12:43 UTC ( [id://257121]=note: print w/replies, xml ) | Need Help?? |
One initial note: "10234" would be a better starting point than "12345". For the problem sub check_duplicates(), if you're going to write it that way you need to allow for the fact that you'll get 5 mandatory matches, when you compare digit-1 to digit-1 etc: you can allow for that by subtracting 5 from $flag. Another approach is to use indices to iterate over the arrays so that you can avoid comparing a digit against itself:
Another way to avoid it, since an equality check is symmetrical, is to iterate the inner loop only over the digits following the current outer digit:
But I'd rather use a simple regexp:
For check_prime(), note that a character class (/[2357]/) is more efficient than an alternation (/2|3|5|7/), but for counting the number of occurrences of a class of characters tr/// is faster still:
As a general efficiency rule, duplicated effort is a red flag: rather than let each check subroutine split the candidate to an array, you could do it once in the main loop and pass a reference to the resulting array as a second argument to the relevant check subroutines. Note also that you can gain time by ordering the check subroutines so that the ones most likely to fail or quickest to check appear earlier (at least if you also follow others' advice and short-circuit on the first failure) - in this respect, I'd check for duplicates first, but I'd also be inclined to avoid checking all of (for example) 44000 .. 44999 by checking for where the first duplicate occurs:
On another topic, you've done a good job of writing self-documenting code here, but I should mention that while I agree with other respondents about removing the use of $flag, I'd otherwise suggest renaming it - since it will have a true value if the candidate is not acceptable, I'd call it something like $bad or $fail and then finish the main loop with: Hugo
In Section
Meditations
|
|