Find the missing permutation: Difference between revisions

Content added Content deleted
m (rearranged the placement of the permutation list, added bullet points for the three methods, added whitespace and highlighting to the task's preamble, added a ;Related task: (bold) header, changed verb tense.)
(moved PHP below perl, addded Phix)
Line 1,445: Line 1,445:
DBAC is missing</pre>
DBAC is missing</pre>


=={{header|PHP}}==
<lang php><?php
$finalres = Array();
function permut($arr,$result=array()){
global $finalres;
if(empty($arr)){
$finalres[] = implode("",$result);
}else{
foreach($arr as $key => $val){
$newArr = $arr;
$newres = $result;
$newres[] = $val;
unset($newArr[$key]);
permut($newArr,$newres);
}
}
}
$givenPerms = Array("ABCD","CABD","ACDB","DACB","BCDA","ACBD","ADCB","CDAB","DABC","BCAD","CADB","CDBA","CBAD","ABDC","ADBC","BDCA","DCBA","BACD","BADC","BDAC","CBDA","DBCA","DCAB");
$given = Array("A","B","C","D");
permut($given);
print_r(array_diff($finalres,$givenPerms)); // Array ( [20] => DBAC )
</lang>
=={{header|Perl}}==
=={{header|Perl}}==


Line 1,499: Line 1,477:
<lang perl6>say [~^] @givens;</lang>
<lang perl6>say [~^] @givens;</lang>
{{out}}<pre>DBAC</pre>
{{out}}<pre>DBAC</pre>

=={{header|Phix}}==
<lang Phix>constant perms = {"ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB",
"DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA",
"DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"}
-- 1: sum of letters
sequence r = repeat(0,4)
for i=1 to length(perms) do
r = sq_add(r,perms[i])
end for
r = sq_sub(max(r)+'A',r)
puts(1,r&'\n')
-- the final step is equivalent to eg {1528,1530,1531,1529}
-- max-r[i] -> { 3, 1, 0, 2}
-- to chars -> { D, B, A, C}
-- (but obviously all done in one step)

-- 2: the xor trick
r = repeat(0,4)
for i=1 to length(perms) do
r = sq_xor_bits(r,perms[i])
end for
puts(1,r&'\n')

-- 3: find least frequent letters
r = " "
for i=1 to length(r) do
sequence count = repeat(0,4)
for j=1 to length(perms) do
count[perms[j][i]-'A'+1] += 1
end for
r[i] = smallest(count,1)+'A'-1
end for
puts(1,r&'\n')

-- 4: test all permutations
for i=1 to factorial(4) do
r = permute(i,"ABCD")
if not find(r,perms) then exit end if
end for
puts(1,r&'\n')</lang>
{{out}}
<pre>
DBAC
DBAC
DBAC
DBAC
</pre>

=={{header|PHP}}==
<lang php><?php
$finalres = Array();
function permut($arr,$result=array()){
global $finalres;
if(empty($arr)){
$finalres[] = implode("",$result);
}else{
foreach($arr as $key => $val){
$newArr = $arr;
$newres = $result;
$newres[] = $val;
unset($newArr[$key]);
permut($newArr,$newres);
}
}
}
$givenPerms = Array("ABCD","CABD","ACDB","DACB","BCDA","ACBD","ADCB","CDAB","DABC","BCAD","CADB","CDBA","CBAD","ABDC","ADBC","BDCA","DCBA","BACD","BADC","BDAC","CBDA","DBCA","DCAB");
$given = Array("A","B","C","D");
permut($given);
print_r(array_diff($finalres,$givenPerms)); // Array ( [20] => DBAC )
</lang>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==