Problem 24 clearly asks:
What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
If my initial string then is:
$str = "0123456789";
I interpret the request to mean: perform 1,000,000 permutations on $string.
for( $i = 0; $i < 1000000; $i++ ) {
$str = lexicographicPermute($str);
}
echo $str; // prints 2783915604, an incorrect answer.
However, if I only perform 999,999 permutations instead, then it returns the correct answer.
I’m still trying to wrap my head around why it is correct though.
What interpretation of the question would lead you to not perform 1,000,000 permutations?
You miss the fact that your original string (
$str = "0123456789") is actually a permutation too, and it should be counted as well. ) Consider this: what if you had written yourforlike this:… how many permutations you would have got? Two, of course: the original string and the result of
lexicographicPermute()invoked on it. )As a sidenote, I don’t think the direct approach (literally building those (million – 1) permutations) is the right way of solving this problem. Otherwise it wouldn’t have been so much of a problem for humans, no? )