There is a technique by which the list of (N+1) bit codes can be generated from (N)-bit codes.
- Take the list of N bit codes in the given order and call it List-N
- Reverse the above list (List-N), and name the new reflected list: Reflected-List-N
- Prefix each member of the original list (List-N) with 0 and call this new list 'A'
- Prefix each member of the new list (Reflected-List-N) with 1 and call this new list 'B'
- The list of codes with N+1 bits is the concatenation of Lists A and B.
A Demonstration of the above steps: Generating the list of 3-bit Mystery Codes from 2-Bit Mystery Codes
- 2-bit list of codes: 00, 01, 11, 10
- Reverse/Reflect the above list: 10, 11, 01, 00
- Prefix Old Entries with 0: 000, 001, 011, 010
- Prefix Reflected List with 1: 110, 111, 101, 100
- Concatenate the lists obtained in the last two steps: 000, 001, 011, 010, 110, 111, 101, 100
I found solution but when I enter 65 for example getting error
PHP Fatal error: Out of memory (allocated 538968064) (tried to allocate 20 bytes) in /home/pLR62k/prog.php on line 27
on Ideone http://ideone.com/HHRBoG
What Am I doing wrong?
<?php
function MysteryCodes($input){
$initArr=array(0,1);
if($input==1){
return $initArr;
}
else {
$list=array();
$list[0]=$initArr;
for ($i=1; $i<$input; $i++)
{
$prevIndex=$i-1;
$reflectedListN = array_reverse($list[$prevIndex]);
$listA=prefixR($list[$prevIndex], '0');
$listB=prefixR($reflectedListN, '1');
$list[$i]=array_merge($listA, $listB);
}
}
return array_slice($list[$input-1], -$input);
}
function prefixR($input, $prefix){
$result=array();
foreach($input as $value){
$result[]=$prefix.$value;
}
return $result;
}
fscanf(STDIN, "%d", $inp);
if($inp>=1 && $inp<=65){
$result=MysteryCodes($inp);
$output="";
foreach($result as $key=>$value)
$output.="$value\n";
fwrite(STDOUT, $output);
}