I have difficult homework:
The list contains alphabetically all strings, which can form the letters A-K. The start of the list looks like this:
- ABCDEFGHIJK,
- ABCDEFGHIKJ,
- ABCDEFGHJIK,
- ABCDEFGHJKI, ...
The third string in the list is ABCDEFGHJIK. What is the list n's string?
I have made code to solve problem, but just to somewhere N value between 600 000 - 700 000. When I try to solve task with 700 000, I get 'Fatal error: Allowed memory size of 134217728 bytes exhausted'. And this is the trick of the task, automatic test number 11 is 1.6 million. So there must be a simpler algorithm, but I can not find it with search engine. So what would be algorithm? My code is:
<?php
$number = $_REQUEST['n'];
$lettering = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K");
$counter = $number;
$done = permute($lettering, $counter);
echo $done[$number-1]."<br>";
function permute($array, $counter) {
global $number;
if(1 === count($array))
return $array;
$result = array();
foreach($array as $key => $item)
foreach(permute(array_diff_key($array, array($key => $item)), $counter) as $p){
$result[] = $item.$p;
$counter--;
if($counter == 0) return $result;
}
return $result;
}