Find the missing permutation: Difference between revisions

Added Easylang
(Added Easylang)
(88 intermediate revisions by 30 users not shown)
Line 2:
 
<pre>
ABCD
ABCD
CABD
CABD
ACDB
ACDB
DACB
DACB
BCDA
BCDA
ACBD
ACBD
ADCB
ADCB
CDAB
CDAB
DABC
DABC
BCAD
BCAD
CADB
CADB
CDBA
CDBA
CBAD
CBAD
ABDC
ABDC
ADBC
ADBC
BDCA
BDCA
DCBA
DCBA
BACD
BACD
BADC
BADC
BDAC
BDAC
CBDA
CBDA
DBCA
DBCA
DCAB
DCAB
</pre>
 
Listed above are all of the permutations of the symbols &nbsp; '''A''', &nbsp; '''B''', &nbsp; '''C''', &nbsp; and &nbsp; '''D''', &nbsp; ''except'' &nbsp; for one permutation that's &nbsp; ''not'' &nbsp; listed.
Listed above are &nbsp; all-but-one &nbsp; of the permutations of the symbols &nbsp; '''A''', &nbsp; '''B''', &nbsp; '''C''', &nbsp; and &nbsp; '''D''', &nbsp; ''except'' &nbsp; for one permutation that's &nbsp; ''not'' &nbsp; listed.
 
 
Line 52 ⟶ 53:
* &nbsp; [[Permutations]])
<br><br>
 
=={{header|11l}}==
{{trans|C}}
 
<syntaxhighlight lang="11l">V perms = [‘ABCD’, ‘CABD’, ‘ACDB’, ‘DACB’, ‘BCDA’, ‘ACBD’, ‘ADCB’, ‘CDAB’,
‘DABC’, ‘BCAD’, ‘CADB’, ‘CDBA’, ‘CBAD’, ‘ABDC’, ‘ADBC’, ‘BDCA’,
‘DCBA’, ‘BACD’, ‘BADC’, ‘BDAC’, ‘CBDA’, ‘DBCA’, ‘DCAB’]
 
V missing = ‘’
L(i) 4
V cnt = [0] * 4
L(j) 0 .< perms.len
cnt[perms[j][i].code - ‘A’.code]++
L(j) 4
I cnt[j] != factorial(4-1)
missing ‘’= Char(code' ‘A’.code + j)
L.break
 
print(missing)</syntaxhighlight>
 
{{out}}
<pre>
DBAC
</pre>
 
=={{header|360 Assembly}}==
{{trans|BBC BASIC}}
Very compact version, thanks to the clever [[#Perl 6Raku|Perl 6Raku]] "xor" algorithm.
<langsyntaxhighlight lang="360asm">* Find the missing permutation - 19/10/2015
PERMMISX CSECT
USING PERMMISX,R15 set base register
Line 84 ⟶ 109:
MISS DC 4XL1'00',C' is missing' buffer
YREGS
END PERMMISX</langsyntaxhighlight>
{{out}}
<pre>DBAC is missing</pre>
 
=={{header|8080 Assembly}}==
<syntaxhighlight lang="asm">PRMLEN: equ 4 ; length of permutation string
puts: equ 9 ; CP/M print string
org 100h
lxi d,perms ; Start with first permutation
perm: lxi h,mperm ; Missing permutation
mvi b,PRMLEN ; Length of permutation
char: ldax d ; Load character
ora a ; Done?
jz done
xra m ; If not, XOR into missing permutation
mov m,a
inx h ; Increment pointers
inx d
dcr b ; Next character of current permutation
jnz char
jmp perm ; Next permutation
done: lxi d,msg ; Print the message and exit
mvi c,puts
jmp 5
msg: db 'Missing permutation: '
mperm: db 0,0,0,0,'$' ; placeholder
perms: db 'ABCD','CABD','ACDB','DACB','BCDA','ACBD','ADCB','CDAB'
db 'DABC','BCAD','CADB','CDBA','CBAD','ABDC','ADBC','BDCA'
db 'DCBA','BACD','BADC','BDAC','CBDA','DBCA','DCAB'
db 0 ; end marker </syntaxhighlight>
{{out}}
<pre>Missing permutation: DBAC</pre>
 
=={{header|8086 Assembly}}==
<syntaxhighlight lang="asm"> cpu 8086
org 100h
mov si,perms ; Start of permutations
xor bx,bx ; First word of permutation
xor dx,dx ; Second word of permutation
mov cx,23 ; There are 23 permutations given
perm: lodsw ; Load first word of permutation
xor bx,ax ; XOR with first word of missing
lodsw ; Load second word of permutation
xor dx,ax ; XOR with second word of missing
loop perm ; Get next permutation
mov [mperm],bx ; Store in placeholder
mov [mperm+2],dx
mov ah,9 ; Write output
mov dx,msg
int 21h
ret
msg: db 'Missing permutation: '
mperm: db 0,0,0,0,'$' ; Placeholder
perms: db 'ABCD','CABD','ACDB','DACB','BCDA','ACBD','ADCB','CDAB'
db 'DABC','BCAD','CADB','CDBA','CBAD','ABDC','ADBC','BDCA'
db 'DCBA','BACD','BADC','BDAC','CBDA','DBCA','DCAB'</syntaxhighlight>
{{out}}
<pre>Missing permutation: DBAC</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC Main()
DEFINE PTR="CARD"
DEFINE COUNT="23"
PTR ARRAY perm(COUNT)
CHAR ARRAY s,missing=[4 0 0 0 0]
BYTE i,j
 
perm(0)="ABCD" perm(1)="CABD"
perm(2)="ACDB" perm(3)="DACB"
perm(4)="BCDA" perm(5)="ACBD"
perm(6)="ADCB" perm(7)="CDAB"
perm(8)="DABC" perm(9)="BCAD"
perm(10)="CADB" perm(11)="CDBA"
perm(12)="CBAD" perm(13)="ABDC"
perm(14)="ADBC" perm(15)="BDCA"
perm(16)="DCBA" perm(17)="BACD"
perm(18)="BADC" perm(19)="BDAC"
perm(20)="CBDA" perm(21)="DBCA"
perm(22)="DCAB"
 
FOR i=0 TO COUNT-1
DO
s=perm(i)
FOR j=1 TO 4
DO
missing(j)==XOR s(j)
OD
OD
 
Print(missing)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Find_the_missing_permutation.png Screenshot from Atari 8-bit computer]
<pre>
DBAC
</pre>
 
=={{header|Ada}}==
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
procedure Missing_Permutations is
subtype Permutation_Character is Character range 'A' .. 'D';
Line 140 ⟶ 258:
Ada.Text_IO.Put_Line ("Missing Permutation:");
Put (Missing_Permutation);
end Missing_Permutations;</langsyntaxhighlight>
 
=={{header|Aime}}==
<syntaxhighlight lang="aime">void
paste(record r, index x, text p, integer a)
{
p = insert(p, -1, a);
x.delete(a);
if (~x) {
x.vcall(paste, -1, r, x, p);
} else {
r[p] = 0;
}
x[a] = 0;
}
 
integer
=={{header|AppleScript}}==
main(void)
{{Trans|JavaScript}} (ES6 Statistical approach)
{
record r;
list l;
index x;
 
l.bill(0, "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB",
"CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC",
"BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB");
 
x['A'] = x['B'] = x['C'] = x['D'] = 0;
Taking the third approach from the task description, and composing with functional primitives:
 
x.vcall(paste, -1, r, x, "");
<lang AppleScript>-- UNDER-REPRESENTED CHARACTER IN EACH OF 4 COLUMNS
 
l.ucall(r_delete, 1, r);
script missingChar
-- mean :: [Num] -> Num
on mean(xs)
script sum
on lambda(a, b)
a + b
end lambda
end script
foldl(sum, 0, xs) / (length of xs)
end mean
on lambda(xs)
set nMean to mean(xs)
script belowMean
on lambda(a, x, i)
if a is missing value then
if x < nMean then
character id (64 + i)
else
missing value
end if
else
a
end if
end lambda
end script
foldl(belowMean, missing value, xs)
end lambda
end script
 
o_(r.low, "\n");
-- Count of each character type in each character column
script colCounts
on lambda(xs)
script tally
on lambda(tuple, x)
set i to ord(x) - 64
set item i of tuple to (item i of tuple) + 1
tuple
end lambda
end script
foldl(tally, {0, 0, 0, 0}, xs)
end lambda
end script
 
return 0;
-- TEST
}</syntaxhighlight>
{{Out}}
<pre>DBAC</pre>
 
=={{header|ALGOL 68}}==
Uses the XOR algorithm of the Raku sample.
<syntaxhighlight lang="algol68">BEGIN # find the missing permutation in a list using the XOR method of the Raku sample #
# the list to find the missing permutation of #
[]STRING list = ( "ABCD", "CABD", "ACDB", "DACB", "BCDA"
, "ACBD", "ADCB", "CDAB", "DABC", "BCAD"
, "CADB", "CDBA", "CBAD", "ABDC", "ADBC"
, "BDCA", "DCBA", "BACD", "BADC", "BDAC"
, "CBDA", "DBCA", "DCAB"
);
# sets b to b XOR v and returns b #
PRIO XORAB = 1;
OP XORAB = ( REF BITS b, BITS v )REF BITS: b := b XOR v;
 
# loop through each character of each element of the list #
FOR c pos FROM LWB list[ LWB list ] TO UPB list[ LWB list ] DO
# loop through each element of the list #
BITS m := 16r0;
FOR l pos FROM LWB list TO UPB list DO
m XORAB BIN ABS list[ l pos ][ c pos ]
OD;
print( ( REPR ABS m ) )
OD
END</syntaxhighlight>
{{out}}
<pre>
DBAC
</pre>
 
=={{header|APL}}==
 
This is a function that takes a matrix where the rows are permutations,
and returns the missing permutation. It works by returning, for each column,
the letter that occurs least.
 
<syntaxhighlight lang="apl">missing ← ((⊂↓⍳¨⌊/) +⌿∘(⊢∘.=∪∘∊)) ⌷ ∪∘∊</syntaxhighlight>
 
{{out}}
 
<syntaxhighlight lang="apl"> perms←↑'ABCD' 'CABD' 'ACDB' 'DACB' 'BCDA' 'ACBD' 'ADCB' 'CDAB'
perms⍪←↑'DABC' 'BCAD' 'CADB' 'CDBA' 'CBAD' 'ABDC' 'ADBC' 'BDCA'
perms⍪←↑'DCBA' 'BACD' 'BADC' 'BDAC' 'CBDA' 'DBCA' 'DCAB'
missing perms
DBAC</syntaxhighlight>
 
=={{header|AppleScript}}==
{{Trans|JavaScript}}
{{Trans|Haskell}} (Statistical versions)
Taking the third approach from the task description, and composing with functional primitives:
 
Yosemite OS X onwards (uses NSString for sorting):
<syntaxhighlight lang="applescript">use framework "Foundation" -- ( sort )
 
--------------- RAREST LETTER IN EACH COLUMN -------------
on run
concat(map(composeList({¬
map(missingChar, map(colCounts head, ¬
transposeminimumBy(mapcomparing(curry(splitOn|length|)'s lambda(""), ¬
splitOn(spacegroup, ¬
"ABCD CABD ACDB DACB BCDA ACBD " &sort}), ¬
transpose(map(chars, ¬
|words|("ABCD CABD ACDB DACB BCDA ACBD " & ¬
"ADCB CDAB DABC BCAD CADB CDBA " & ¬
"CBAD ABDC ADBC BDCA DCBA BACD " & ¬
"BADC BDAC CBDA DBCA DCAB"))))) as text
--> "DBAC"
Line 215 ⟶ 368:
 
 
-------------------- GENERIC FUNCTIONS -------------------
 
-- chars :: String -> [String]
-- GENERIC FUNCTIONS
on chars(s)
characters of s
end chars
 
 
-- transpose :: [[a]] -> [[a]]
-- Ordering :: (-1 | 0 | 1)
on transpose(xss)
-- compare :: a -> a -> Ordering
script column
on lambdacompare(_a, iColb)
if a < b script rowthen
on lambda(xs)-1
else if a > b item iCol of xsthen
end lambda1
else
end script
0
end if
map(row, xss)
end lambdacompare
 
 
-- comparing :: (a -> b) -> (a -> a -> Ordering)
on comparing(f)
script
on |λ|(a, b)
tell mReturn(f) to compare(|λ|(a), |λ|(b))
end |λ|
end script
end comparing
map(column, item 1 of xss)
end transpose
 
 
-- curry :: (Script|Handler) -> Script
-- composeList :: [(a -> a)] -> (a -> a)
on curry(f)
on composeList(fs)
set mf to mReturn(f)
script
on lambda|λ|(ax)
script go
on lambda|λ|(bf, a)
mfmReturn(f)'s lambda|λ|(a, b)
end lambda|λ|
end script
end lambda foldr(go, x, fs)
end |λ|
end script
end currycomposeList
 
 
-- map :: (a -> b) -> [a] -> [b]
-- concat :: [[a]] -> [a]
on map(f, xs)
-- concat :: [String] -> String
on concat(xs)
set lng to length of xs
if 0 < lng and string is class of (item 1 of xs) then
set acc to ""
else
set acc to {}
end if
repeat with i from 1 to lng
set acc to acc & item i of xs
end repeat
acc
end concat
 
 
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lstv to lambda|λ|(v, item i of xs, i, xs)
end repeat
return lstv
end tell
end mapfoldl
 
 
-- foldl :: (a -> b -> a) -> a -> [b] -> a
-- foldr :: (b -> a -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
on foldr(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1lng to lng1 by -1
set v to lambda|λ|(v, item i of xs, v, i, xs)
end repeat
return v
end tell
end foldlfoldr
 
 
-- splitOn :: Text -> Text -> [Text]
-- group :: Eq a => [a] -> [[a]]
on splitOn(strDelim, strMain)
on group(xs)
set {dlm, my text item delimiters} to {my text item delimiters, strDelim}
script eq
set xs to text items of strMain
on |λ|(a, b)
a = b
end |λ|
end script
groupBy(eq, xs)
end group
 
 
-- groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
on groupBy(f, xs)
set mf to mReturn(f)
script enGroup
on |λ|(a, x)
if length of (active of a) > 0 then
set h to item 1 of active of a
else
set h to missing value
end if
if h is not missing value and mf's |λ|(h, x) then
{active:(active of a) & x, sofar:sofar of a}
else
{active:{x}, sofar:(sofar of a) & {active of a}}
end if
end |λ|
end script
if length of xs > 0 then
set dct to foldl(enGroup, {active:{item 1 of xs}, sofar:{}}, tail(xs))
if length of (active of dct) > 0 then
sofar of dct & {active of dct}
else
sofar of dct
end if
else
{}
end if
end groupBy
 
 
-- head :: [a] -> a
on head(xs)
if length of xs > 0 then
item 1 of xs
else
missing value
end if
end head
 
 
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return xsstrJoined
end splitOnintercalate
 
 
-- length :: [a] -> Int
on |length|(xs)
length of xs
end |length|
 
 
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
 
 
-- minimumBy :: (a -> a -> Ordering) -> [a] -> a
on minimumBy(f)
script
on |λ|(xs)
if length of xs < 1 then return missing value
tell mReturn(f)
set v to item 1 of xs
repeat with x in xs
if |λ|(x, v) < 0 then set v to x
end repeat
return v
end tell
end |λ|
end script
end minimumBy
 
-- ord :: Character -> Int
on ord(x)
id of x
end ord
 
-- Lift 2nd class handler function into 1st class script wrapper
Line 293 ⟶ 563:
else
script
property lambda|λ| : f
end script
end if
end mReturn</lang>
 
 
-- sort :: [a] -> [a]
on sort(xs)
((current application's NSArray's arrayWithArray:xs)'s ¬
sortedArrayUsingSelector:"compare:") as list
end sort
 
 
-- tail :: [a] -> [a]
on tail(xs)
if length of xs > 1 then
items 2 thru -1 of xs
else
{}
end if
end tail
 
 
-- transpose :: [[a]] -> [[a]]
on transpose(xss)
script column
on |λ|(_, iCol)
script row
on |λ|(xs)
item iCol of xs
end |λ|
end script
map(row, xss)
end |λ|
end script
map(column, item 1 of xss)
end transpose
 
 
-- words :: String -> [String]
on |words|(s)
words of s
end |words|</syntaxhighlight>
{{Out}}
<pre>"DBAC"</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">perms: [
"ABCD" "CABD" "ACDB" "DACB" "BCDA" "ACBD" "ADCB" "CDAB" "DABC"
"BCAD" "CADB" "CDBA" "CBAD" "ABDC" "ADBC" "BDCA" "DCBA" "BACD"
"BADC" "BDAC" "CBDA" "DBCA" "DCAB"
]
 
allPerms: map permutate split "ABCD" => join
 
print first difference allPerms perms</syntaxhighlight>
 
{{out}}
 
<pre>DBAC</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">IncompleteList := "ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB"
 
CompleteList := Perm( "ABCD" )
Line 331 ⟶ 657:
}
return substr(L, 1, -1)
}</langsyntaxhighlight>
 
=={{header|AWK}}==
Line 337 ⟶ 663:
This reads the list of permutations as standard input and outputs the missing one.
 
<langsyntaxhighlight lang="awk">{
split($1,a,"");
for (i=1;i<=4;++i) {
Line 355 ⟶ 681:
}
print s[1]s[2]s[3]s[4]
}</langsyntaxhighlight>
 
{{Out}}
Line 362 ⟶ 688:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> DIM perms$(22), miss&(4)
perms$() = "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", \
\ "CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", \
Line 373 ⟶ 699:
NEXT
PRINT $$^miss&(0) " is missing"
END</langsyntaxhighlight>
{{out}}
<pre>
Line 381 ⟶ 707:
=={{header|Burlesque}}==
 
<langsyntaxhighlight lang="burlesque">
ln"ABCD"r@\/\\
</syntaxhighlight>
</lang>
 
(Feed permutations via STDIN. Uses the naive method).
Line 390 ⟶ 716:
the letters with the lowest frequency:
 
<langsyntaxhighlight lang="burlesque">
ln)XXtp)><)F:)<]u[/v\[
</syntaxhighlight>
</lang>
 
=={{header|C}}==
<langsyntaxhighlight Clang="c">#include <stdio.h>
 
#define N 4
Line 427 ⟶ 753:
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>Missing: DBAC</pre>
 
=={{header|C++}}==
<lang Cpp>#include <algorithm>
#include <vector>
#include <set>
#include <iterator>
#include <iostream>
#include <string>
 
static const std::string GivenPermutations[] = {
"ABCD","CABD","ACDB","DACB",
"BCDA","ACBD","ADCB","CDAB",
"DABC","BCAD","CADB","CDBA",
"CBAD","ABDC","ADBC","BDCA",
"DCBA","BACD","BADC","BDAC",
"CBDA","DBCA","DCAB"
};
static const size_t NumGivenPermutations = sizeof(GivenPermutations) / sizeof(*GivenPermutations);
 
int main()
{
std::vector<std::string> permutations;
std::string initial = "ABCD";
permutations.push_back(initial);
 
while(true)
{
std::string p = permutations.back();
std::next_permutation(p.begin(), p.end());
if(p == permutations.front())
break;
permutations.push_back(p);
}
 
std::vector<std::string> missing;
std::set<std::string> given_permutations(GivenPermutations, GivenPermutations + NumGivenPermutations);
std::set_difference(permutations.begin(), permutations.end(), given_permutations.begin(),
given_permutations.end(), std::back_inserter(missing));
std::copy(missing.begin(), missing.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
return 0;
}</lang>
 
=={{header|C sharp|C#}}==
===By permutating===
{{works with|C sharp|C#|2+}}
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
 
Line 515 ⟶ 800:
}
}
}</langsyntaxhighlight>
===By xor-ing the values===
{{works with|C sharp|C#|3+}}
<langsyntaxhighlight lang="csharp">using System;
using System.Linq;
 
Line 536 ⟶ 821:
Console.WriteLine(string.Join("", values.Select(i => (char)i)));
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <algorithm>
#include <vector>
#include <set>
#include <iterator>
#include <iostream>
#include <string>
 
static const std::string GivenPermutations[] = {
"ABCD","CABD","ACDB","DACB",
"BCDA","ACBD","ADCB","CDAB",
"DABC","BCAD","CADB","CDBA",
"CBAD","ABDC","ADBC","BDCA",
"DCBA","BACD","BADC","BDAC",
"CBDA","DBCA","DCAB"
};
static const size_t NumGivenPermutations = sizeof(GivenPermutations) / sizeof(*GivenPermutations);
 
int main()
{
std::vector<std::string> permutations;
std::string initial = "ABCD";
permutations.push_back(initial);
 
while(true)
{
std::string p = permutations.back();
std::next_permutation(p.begin(), p.end());
if(p == permutations.front())
break;
permutations.push_back(p);
}
 
std::vector<std::string> missing;
std::set<std::string> given_permutations(GivenPermutations, GivenPermutations + NumGivenPermutations);
std::set_difference(permutations.begin(), permutations.end(), given_permutations.begin(),
given_permutations.end(), std::back_inserter(missing));
std::copy(missing.begin(), missing.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
return 0;
}</syntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">
(use 'clojure.math.combinatorics)
(use 'clojure.set)
Line 546 ⟶ 872:
(def s1 (apply hash-set (permutations "ABCD")))
(def missing (difference s1 given))
</syntaxhighlight>
</lang>
Here's a version based on the hint in the description. ''freqs'' is a sequence of letter frequency maps, one for each column. There should be 6 of each letter in each column, so we look for the one with 5.
<langsyntaxhighlight lang="clojure">(def abcds ["ABCD" "CABD" "ACDB" "DACB" "BCDA" "ACBD" "ADCB" "CDAB"
"DABC" "BCAD" "CADB" "CDBA" "CBAD" "ABDC" "ADBC" "BDCA"
"DCBA" "BACD" "BADC" "BDAC" "CBDA" "DBCA" "DCAB"])
Line 556 ⟶ 882:
(defn v->k [fqmap v] (->> fqmap (filter #(-> % second (= v))) ffirst))
 
(->> freqs (map #(v->k % 5)) (apply str) println)</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
 
<langsyntaxhighlight lang="coffeescript">
missing_permutation = (arr) ->
# Find the missing permutation in an array of N! - 1 permutations.
Line 596 ⟶ 922:
console.log missing_permutation(arr)
</syntaxhighlight>
</lang>
 
{{out}}
Line 605 ⟶ 931:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defparameter *permutations*
'("ABCD" "CABD" "ACDB" "DACB" "BCDA" "ACBD" "ADCB" "CDAB" "DABC" "BCAD" "CADB" "CDBA"
"CBAD" "ABDC" "ADBC" "BDCA" "DCBA" "BACD" "BADC" "BDAC" "CBDA" "DBCA" "DCAB"))
Line 618 ⟶ 944:
(cons (count letter occurs) letter))
letters))))))
(concatenate 'string (mapcar #'least-occurs (enum (length letters)))))))</langsyntaxhighlight>
{{out}}
<pre>ROSETTA> (missing-perm *permutations*)
Line 624 ⟶ 950:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.string, std.algorithm, std.range, std.conv;
 
Line 643 ⟶ 969:
 
// Version 2: xor all the ASCII values, the uneven one
// gets flushed out. Based on Perl 6Raku (via Go).
enum len = 4;
char[len] b = 0;
Line 666 ⟶ 992:
perms[0][maxCode - code].write;
}
}</langsyntaxhighlight>
{{out}}
<pre>DBAC
Line 672 ⟶ 998:
DBAC
DBAC</pre>
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Find_the_missing_permutation#Pascal Pascal].
 
=={{header|EasyLang}}==
<syntaxhighlight>
perms$[] = [ "ABCD" "CABD" "ACDB" "DACB" "BCDA" "ACBD" "ADCB" "CDAB" "DABC" "BCAD" "CADB" "CDBA" "CBAD" "ABDC" "ADBC" "BDCA" "DCBA" "BACD" "BADC" "BDAC" "CBDA" "DBCA" "DCAB" ]
n = len perms$[1]
len cnt[] n
#
nn = 1
for i to n - 1
nn *= i
.
for i to 4
for j to n
cnt[j] = 0
.
for s$ in perms$[]
cod = strcode substr s$ i 1 - 64
cnt[cod] += 1
.
for j to n
if cnt[j] <> nn
miss$ &= strchar (j + 64)
break 1
.
.
.
print miss$
</syntaxhighlight>
 
{{out}}
<pre>
DBAC
</pre>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="lisp">
;; use the obvious methos
(lib 'list) ; for (permutations) function
Line 689 ⟶ 1,050:
(set-substract (make-set all-perms) (make-set perms))
→ { DBAC }
</syntaxhighlight>
</lang>
 
 
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule RC do
def find_miss_perm(head, perms) do
all_permutations(head) -- perms
Line 711 ⟶ 1,070:
"CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"]
 
IO.inspect RC.find_miss_perm( hd(perms), perms )</langsyntaxhighlight>
 
{{out}}
Line 720 ⟶ 1,079:
=={{header|Erlang}}==
The obvious method. It seems fast enough (no waiting time).
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( find_missing_permutation ).
 
Line 737 ⟶ 1,096:
is_different( [_H] ) -> true;
is_different( [H | T] ) -> not lists:member(H, T) andalso is_different( T ).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 745 ⟶ 1,104:
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM MISSING
 
Line 779 ⟶ 1,138:
PRINT("Solution is: ";SOL$)
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>
Solution is: DBAC
</pre>
 
=={{header|Factor}}==
Permutations are read in via STDIN.
<syntaxhighlight lang="factor">USING: io math.combinatorics sequences sets ;
 
"ABCD" all-permutations lines diff first print</syntaxhighlight>
{{out}}
<pre>
DBAC
</pre>
 
=={{header|Forth}}==
'''Tested with:''' GForth, VFX Forth, SwiftForth, Win32 Forth. Should work with any ANS Forth system.
 
'''Method:''' Read the permutations in as hexadecimal numbers, exclusive ORing them together gives the answer.
(This solution assumes that none of the permutations is defined as a Forth word.)
<syntaxhighlight lang="forth"> hex
ABCD CABD xor ACDB xor DACB xor BCDA xor ACBD xor
ADCB xor CDAB xor DABC xor BCAD xor CADB xor CDBA xor
CBAD xor ABDC xor ADBC xor BDCA xor DCBA xor BACD xor
BADC xor BDAC xor CBDA xor DBCA xor DCAB xor
cr .( Missing permutation: ) u.
decimal</syntaxhighlight>
{{out}}
<pre>Missing permutation: DBAC ok</pre>
 
=={{header|Fortran}}==
'''Work-around''' to let it run properly with some bugged versions (e.g. 4.3.2) of gfortran: remove the ''parameter'' attribute to the array list.
<langsyntaxhighlight lang="fortran">program missing_permutation
 
implicit none
Line 802 ⟶ 1,186:
write (*, *)
 
end program missing_permutation</langsyntaxhighlight>
{{out}}
<pre>DBAC</pre>
 
=={{header|FreeBASIC}}==
===Simple count===
<syntaxhighlight lang="freebasic">' version 30-03-2017
' compile with: fbc -s console
 
Data "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD"
Data "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA"
Data "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD"
Data "BADC", "BDAC", "CBDA", "DBCA", "DCAB"
 
' ------=< MAIN >=------
 
Dim As ulong total(3, Asc("A") To Asc("D")) ' total(0 to 3, 65 to 68)
Dim As ULong i, j, n = 24 \ 4 ' n! \ n
Dim As String tmp
 
For i = 1 To 23
Read tmp
For j = 0 To 3
total(j, tmp[j]) += 1
Next
Next
 
tmp = Space(4)
For i = 0 To 3
For j = Asc("A") To Asc("D")
If total(i, j) <> n Then
tmp[i] = j
End If
Next
Next
 
Print "The missing permutation is : "; tmp
 
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End</syntaxhighlight>
{{out}}
<pre>The missing permutation is : DBAC</pre>
===Add the value's===
<syntaxhighlight lang="freebasic">' version 30-03-2017
' compile with: fbc -s console
 
Data "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD"
Data "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA"
Data "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD"
Data "BADC", "BDAC", "CBDA", "DBCA", "DCAB"
 
' ------=< MAIN >=------
 
Dim As ULong total(3) ' total(0 to 3)
Dim As ULong i, j, n = 24 \ 4 ' n! \ n
Dim As ULong total_val = (Asc("A") + Asc("B") + Asc("C") + Asc("D")) * n
Dim As String tmp
 
For i = 1 To 23
Read tmp
For j = 0 To 3
total(j) += tmp[j]
Next
Next
 
tmp = Space(4)
For i = 0 To 3
tmp[i] = total_val - total(i)
Next
 
Print "The missing permutation is : "; tmp
 
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End</syntaxhighlight>
<pre>output is same as the first version</pre>
===Using Xor===
<syntaxhighlight lang="freebasic">' version 30-03-2017
' compile with: fbc -s console
 
Data "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD"
Data "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA"
Data "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD"
Data "BADC", "BDAC", "CBDA", "DBCA", "DCAB"
 
' ------=< MAIN >=------
 
Dim As ULong i,j
Dim As String tmp, missing = chr(0, 0, 0, 0) ' or string(4, 0)
 
For i = 1 To 23
Read tmp
For j = 0 To 3
missing[j] Xor= tmp[j]
Next
Next
 
Print "The missing permutation is : "; missing
 
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End</syntaxhighlight>
<pre>Output is the same as the first version</pre>
 
=={{header|Frink}}==
<syntaxhighlight lang="frink">p = toSet[trim[splitLines["""ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB"""]]]
 
s = ["A","B","C","D"]
for n = s.lexicographicPermute[]
{
str = join["", n]
if ! p.contains[str]
println[str]
}</syntaxhighlight>
{{out}}
<pre>
DBAC
</pre>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># our deficient list
L :=
[ "ABCD", "CABD", "ACDB", "DACB", "BCDA",
Line 823 ⟶ 1,351:
# convert back to letters
s := "ABCD";
List(v, p -> List(p, i -> s[i]));</langsyntaxhighlight>
 
=={{header|Go}}==
Alternate method suggested by task description:
<langsyntaxhighlight lang="go">package main
 
import (
Line 872 ⟶ 1,401:
}
fmt.Println(string(b))
}</langsyntaxhighlight>
Xor method suggested by Perl 6Raku contributor:
<langsyntaxhighlight lang="go">func main() {
b := make([]byte, len(given[0]))
for _, p := range given {
Line 882 ⟶ 1,411:
}
fmt.Println(string(b))
}</langsyntaxhighlight>
{{out}} in either case:
<pre>
Line 890 ⟶ 1,419:
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">def fact = { n -> [1,(1..<(n+1)).inject(1) { prod, i -> prod * i }].max() }
def missingPerms
missingPerms = {List elts, List perms ->
Line 898 ⟶ 1,427:
: missingPerms(elts - e, ePerms).collect { [e] + it }
}.sum()
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">def e = 'ABCD' as List
def p = ['ABCD', 'CABD', 'ACDB', 'DACB', 'BCDA', 'ACBD', 'ADCB', 'CDAB', 'DABC', 'BCAD', 'CADB', 'CDBA',
'CBAD', 'ABDC', 'ADBC', 'BDCA', 'DCBA', 'BACD', 'BADC', 'BDAC', 'CBDA', 'DBCA', 'DCAB'].collect { it as List }
 
def mp = missingPerms(e, p)
mp.each { println it }</langsyntaxhighlight>
 
{{out}}
Line 912 ⟶ 1,441:
 
=={{header|Haskell}}==
====Difference between two lists====
{{works with|GHC|6.10+}}
{{works with|GHC|7.10.3}}
<lang haskell>import Data.List
<syntaxhighlight lang="haskell">import Data.List ((\\), permutations, nub)
import Control.Monad
import Control.ArrowMonad (join)
 
missingPerm :: Eq a => [[a]] -> [[a]]
:: Eq a
=> [[a]] -> [[a]]
missingPerm = (\\) =<< permutations . nub . join
 
deficientPermsList =:: ["ABCD","CABD","ACDB","DACB",String]
deficientPermsList =
"BCDA","ACBD","ADCB","CDAB",
[ "ABCD"
"DABC","BCAD","CADB","CDBA",
, "CABD"
"CBAD","ABDC","ADBC","BDCA",
, "ACDB"
"DCBA","BACD","BADC","BDAC",
, "DACB"
"CBDA","DBCA","DCAB"]
, "BCDA"
, "ACBD"
, "ADCB"
, "CDAB"
, "DABC"
, "BCAD"
, "CADB"
, "CDBA"
, "CBAD"
, "ABDC"
, "ADBC"
, "BDCA"
, "DCBA"
, "BACD"
, "BADC"
, "BDAC"
, "CBDA"
, "DBCA"
, "DCAB"
]
 
main =:: doIO ()
main = print $ missingPerm deficientPermsList</langsyntaxhighlight>
{{outOut}}
<pre>["DBAC"]</pre>
 
====Character frequency in each column====
Another, more statistical, approach is to return the least common letter in each of the four columns. (If all permutations were present, letter frequencies would not vary).
 
<syntaxhighlight lang="haskell">import Data.List (minimumBy, group, sort, transpose)
import Data.Ord (comparing)
 
missingPerm
:: Ord a
=> [[a]] -> [a]
missingPerm = fmap (head . minimumBy (comparing length) . group . sort) . transpose
 
deficientPermsList :: [String]
deficientPermsList =
[ "ABCD"
, "CABD"
, "ACDB"
, "DACB"
, "BCDA"
, "ACBD"
, "ADCB"
, "CDAB"
, "DABC"
, "BCAD"
, "CADB"
, "CDBA"
, "CBAD"
, "ABDC"
, "ADBC"
, "BDCA"
, "DCBA"
, "BACD"
, "BADC"
, "BDAC"
, "CBDA"
, "DBCA"
, "DCAB"
]
 
main :: IO ()
main = print $ missingPerm deficientPermsList</syntaxhighlight>
{{Out}}
<pre>"DBAC"</pre>
 
====Folding XOR over the list of permutations====
Surfacing the missing bits:
{{Trans|JavaScript}}
{{Trans|Python}}
<syntaxhighlight lang="haskell">import Data.Char (chr, ord)
import Data.Bits (xor)
 
missingPerm :: [String] -> String
missingPerm = fmap chr . foldr (zipWith xor . fmap ord) [0, 0, 0, 0]
 
deficientPermsList :: [String]
deficientPermsList =
[ "ABCD"
, "CABD"
, "ACDB"
, "DACB"
, "BCDA"
, "ACBD"
, "ADCB"
, "CDAB"
, "DABC"
, "BCAD"
, "CADB"
, "CDBA"
, "CBAD"
, "ABDC"
, "ADBC"
, "BDCA"
, "DCBA"
, "BACD"
, "BADC"
, "BDAC"
, "CBDA"
, "DBCA"
, "DCAB"
]
 
main :: IO ()
main = putStrLn $ missingPerm deficientPermsList</syntaxhighlight>
{{Out}}
<pre>DBAC</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">link strings # for permutes
 
procedure main()
Line 944 ⟶ 1,580:
write("The difference is : ")
every write(!givens, " ")
end</langsyntaxhighlight>
 
The approach above generates a full set of permutations and calculates the difference. Changing the two commented lines to the three below will calculate on the fly and would be more efficient for larger data sets.
 
<langsyntaxhighlight Iconlang="icon">every x := permutes("ABCD") do # generate all permutations
if member(givens,x) then delete(givens,x) # remove givens as they are generated
else insert(givens,x) # add back any not given</langsyntaxhighlight>
 
A still more efficient version is:
<langsyntaxhighlight Iconlang="icon">link strings
procedure main()
Line 964 ⟶ 1,600:
if not member(givens, p) then write(p)
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 971 ⟶ 1,607:
=={{header|J}}==
'''Solution:'''
<langsyntaxhighlight Jlang="j">permutations=: A.~ i.@!@#
missingPerms=: -.~ permutations @ {.</langsyntaxhighlight>
'''Use:'''
<pre>data=: >;: 'ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA'
Line 984 ⟶ 1,620:
Or the above could be a single definition that works the same way:
 
<langsyntaxhighlight Jlang="j">missingPerms=: -.~ (A.~ i.@!@#) @ {. </langsyntaxhighlight>
 
Or the equivalent explicit (cf. tacit above) definition:
<langsyntaxhighlight Jlang="j">missingPerms=: monad define
item=. {. y
y -.~ item A.~ i.! #item
)</langsyntaxhighlight>
 
Or, the solution could be obtained without defining an independent program:
 
<langsyntaxhighlight Jlang="j"> data -.~ 'ABCD' A.~ i.!4
DBAC</langsyntaxhighlight>
 
Here, <code>'ABCD'</code> represents the values being permuted (their order does not matter), and <code>4</code> is how many of them we have.
Line 1,001 ⟶ 1,637:
Yet another alternative expression, which uses parentheses instead of the [http://www.jsoftware.com/help/dictionary/d220v.htm passive operator] (<code>~</code>), would be:
 
<langsyntaxhighlight Jlang="j"> ((i.!4) A. 'ABCD') -. data
DBAC</langsyntaxhighlight>
 
Of course the task suggests that the missing permutation can be found without generating all permutations. And of course that is doable:
 
<langsyntaxhighlight Jlang="j"> 'ABCD'{~,I.@(= <./)@(#/.~)@('ABCD' , ])"1 |:perms
DBAC</langsyntaxhighlight>
 
However, that's actually a false economy - not only does this approach take more code to implement (at least, in J) but we are already dealing with a data structure of approximately the size of all permutations. So what is being saved by this supposedly "more efficient" approach? Not much... (Still, perhaps this exercise is useful as an illustration of some kind of advertising concept?)
 
We could use parity, as suggested in the task hints:
<langsyntaxhighlight Jlang="j"> ,(~.#~2|(#/.~))"1|:data
DBAC</langsyntaxhighlight>
 
We could use arithmetic, as suggested in the task hints:
<langsyntaxhighlight Jlang="j"> ({.data){~|(->./)+/({.i.])data
DBAC</langsyntaxhighlight>
 
=={{header|Java}}==
Line 1,023 ⟶ 1,659:
Following needs: [[User:Margusmartsepp/Contributions/Java/Utils.java|Utils.java]]
 
<langsyntaxhighlight lang="java">import java.util.ArrayList;
 
import com.google.common.base.Joiner;
Line 1,042 ⟶ 1,678:
System.out.println(joiner.join(cs));
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,049 ⟶ 1,685:
Alternate version, based on checksumming each position:
 
<langsyntaxhighlight lang="java">public class FindMissingPermutation
{
public static void main(String[] args)
Line 1,072 ⟶ 1,708:
System.out.println("Missing permutation: " + missingPermutation.toString());
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 1,080 ⟶ 1,716:
 
The permute() function taken from http://snippets.dzone.com/posts/show/1032
<langsyntaxhighlight lang="javascript">permute = function(v, m){ //v1.0
for(var p = -1, j, k, f, r, l = v.length, q = 1, i = l + 1; --i; q *= i);
for(x = [new Array(l), new Array(l), new Array(l), new Array(l)], j = q, k = l + 1, i = -1;
Line 1,099 ⟶ 1,735:
 
missing = all.filter(function(elem) {return list.indexOf(elem) == -1});
print(missing); // ==> DBAC</langsyntaxhighlight>
 
====Functional====
 
<langsyntaxhighlight JavaScriptlang="javascript">(function (strList) {
 
// [a] -> [[a]]
Line 1,142 ⟶ 1,778:
'ABCD\nCABD\nACDB\nDACB\nBCDA\nACBD\nADCB\nCDAB\nDABC\nBCAD\nCADB\n\
CDBA\nCBAD\nABDC\nADBC\nBDCA\nDCBA\nBACD\nBADC\nBDAC\nCBDA\nDBCA\nDCAB'
);</langsyntaxhighlight>
 
{{Out}}
 
<langsyntaxhighlight JavaScriptlang="javascript">["DBAC"]</langsyntaxhighlight>
 
===ES6===
====Statistical====
=====Using a dictionary=====
 
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 1,166 ⟶ 1,802:
return transpose(xs.split(' ')
.map(x => x.split('')))
.map(col => col.reduce((a, x) => {( // char count inof each ofcharacter Nin columnseach ?column
returna[x] = (a[x] || 0) + 1,
a[x] = (a[x] || 0) + 1,
), a{}))
);
}, {}))
.map(dct => { // character with frequency below mean of distribution ?
let ks = Object.keys(dct),
Line 1,185 ⟶ 1,819:
 
// --> 'DBAC'
})();</langsyntaxhighlight>
 
{{Out}}
<pre>DBAC</pre>
 
 
=====Composing functional primitives=====
{{Trans|Haskell}}
<syntaxhighlight lang="javascript">(() => {
'use strict';
 
// MISSING PERMUTATION ---------------------------------------------------
 
// missingPermutation :: [String] -> String
const missingPermutation = xs =>
map(
// Rarest letter,
compose([
sort,
group,
curry(minimumBy)(comparing(length)),
head
]),
 
// in each column.
transpose(map(stringChars, xs))
)
.join('');
 
 
// GENERIC FUNCTIONAL PRIMITIVES -----------------------------------------
 
// transpose :: [[a]] -> [[a]]
const transpose = xs =>
xs[0].map((_, iCol) => xs.map(row => row[iCol]));
 
// sort :: Ord a => [a] -> [a]
const sort = xs => xs.sort();
 
// group :: Eq a => [a] -> [[a]]
const group = xs => groupBy((a, b) => a === b, xs);
 
// groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
const groupBy = (f, xs) => {
const dct = xs.slice(1)
.reduce((a, x) => {
const
h = a.active.length > 0 ? a.active[0] : undefined,
blnGroup = h !== undefined && f(h, x);
 
return {
active: blnGroup ? a.active.concat(x) : [x],
sofar: blnGroup ? a.sofar : a.sofar.concat([a.active])
};
}, {
active: xs.length > 0 ? [xs[0]] : [],
sofar: []
});
return dct.sofar.concat(dct.active.length > 0 ? [dct.active] : []);
};
 
// length :: [a] -> Int
const length = xs => xs.length;
 
// comparing :: (a -> b) -> (a -> a -> Ordering)
const comparing = f =>
(x, y) => {
const
a = f(x),
b = f(y);
return a < b ? -1 : a > b ? 1 : 0
};
 
// minimumBy :: (a -> a -> Ordering) -> [a] -> a
const minimumBy = (f, xs) =>
xs.reduce((a, x) => a === undefined ? x : (
f(x, a) < 0 ? x : a
), undefined);
 
// head :: [a] -> a
const head = xs => xs.length ? xs[0] : undefined;
 
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) => xs.map(f)
 
// compose :: [(a -> a)] -> (a -> a)
const compose = fs => x => fs.reduce((a, f) => f(a), x);
 
// curry :: ((a, b) -> c) -> a -> b -> c
const curry = f => a => b => f(a, b);
 
// stringChars :: String -> [Char]
const stringChars = s => s.split('');
 
 
// TEST ------------------------------------------------------------------
 
return missingPermutation(["ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD",
"ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC",
"BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"
]);
 
// -> "DBAC"
})();</syntaxhighlight>
{{Out}}
<pre>DBAC</pre>
 
====XOR====
Folding an xor operator over the list of character codes:
<syntaxhighlight lang="javascript">(() => {
'use strict';
 
// main :: IO ()
const main = () => {
const xs = [
'ABCD', 'CABD', 'ACDB', 'DACB', 'BCDA', 'ACBD',
'ADCB', 'CDAB', 'DABC', 'BCAD', 'CADB', 'CDBA',
'CBAD', 'ABDC', 'ADBC', 'BDCA', 'DCBA', 'BACD',
'BADC', 'BDAC', 'CBDA', 'DBCA', 'DCAB'
];
 
return xs.reduce(
(a, x) => zipWith(xor)(a)(codes(x)),
[0, 0, 0, 0]
).map(x => String.fromCodePoint(x)).join('')
};
 
// ---------------------- GENERIC ----------------------
 
// codes :: String -> [Int]
const codes = s =>
s.split('').map(c => c.codePointAt(0));
 
// xor :: Int -> Int -> Int
const xor = a =>
b => (a ^ b)
 
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
const zipWith = f =>
// A list constructed by zipping with a
// custom function, rather than with the
// default tuple constructor.
xs => ys => xs.slice(0).map(
(x, i) => f(x)(ys[i])
);
 
return main()
})();</syntaxhighlight>
{{Out}}
<pre>DBAC</pre>
Line 1,210 ⟶ 1,990:
If your version of jq has transpose/0, the definition given here
(which is the same as in [[Matrix_Transpose#jq]]) may be omitted.
<langsyntaxhighlight lang="jq">def transpose:
if (.[0] | length) == 0 then []
else [map(.[0])] + (map(.[1:]) | transpose)
Line 1,231 ⟶ 2,011:
# encode a string (e.g. "ABCD") as an array (e.g. [0,1,2,3]):
def encode_string: [explode[] - 65];</langsyntaxhighlight>
 
'''The task''':
<langsyntaxhighlight lang="jq">map(encode_string) | transpose | map(parities | decode) | join("")</langsyntaxhighlight>
 
{{Out}}
<langsyntaxhighlight lang="sh">$ jq -R . Find_the_missing_permutation.txt | jq -s -f Find_the_missing_permutation.jq
"DBAC"</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
<tt>find_missing_permutations</tt> accepts a list of strings and finds any permutations of the first string in the list that are missing from the list. If the list contains any strings that are not such permutations (including the first item), the function throws a <tt>DomainError</tt>. Duplicated permutations are silently ignored.
 
=== Obvious method ===
I chose to solve this task by permutation enumeration because Julia provides good native functions for creating and processing list permutations. Also, this function detects multiple missing permutations and tolerates duplicated items in the input list. The function will fail if the length of the strings exceeds 20. This failure occurs because the number of possible permutations then exceeds <tt>typemax(Int64)</tt>. But good luck with this sort of task when the strings approach such lengths.
Calculate all possible permutations and return the first not included in the array.
<syntaxhighlight lang="julia">using BenchmarkTools, Combinatorics
 
function missingperm(arr::Vector)
'''Function'''
allperms = String.(permutations(arr[1])) # revised for type safety
<lang Julia>
for perm in allperms
function find_missing_permutations{T<:String}(a::Array{T,1})
if perm ∉ arr return perm end
std = unique(sort(split(a[1], "")))
needsperm = trues(factorial(length(std)))
for s in a
b = split(s, "")
p = map(x->findfirst(std, x), b)
isperm(p) || throw(DomainError())
needsperm[nthperm(p)] = false
end
mperms = T[]
for i in findn(needsperm)[1]
push!(mperms, join(nthperm(std, i), ""))
end
return mperms
end
</lang>
 
arr = ["ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD",
'''Main'''
"CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC", "BDAC",
<lang Julia>
test = ["ABCD", "CABD", "ACDB", "DACBCBDA", "BCDADBCA", "ACBDDCAB",]
@show missingperm(arr)</syntaxhighlight>
"ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA",
"CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD",
"BADC", "BDAC", "CBDA", "DBCA", "DCAB"]
 
{{out}}
missperms = find_missing_permutations(test)
<pre>missingperm(arr) = "DBAC"</pre>
 
=== Alternative method 1 ===
print("The test list is:\n ")
{{trans|Python}}
i = 0
<syntaxhighlight lang="julia">function missingperm1(arr::Vector{<:AbstractString})
for s in test
print(s,missperm "= "string()
ifor +=pos in 1:length(arr[1])
i % s = 5Set()
i != 0 || print("\nfor perm in ")arr
c = perm[pos]
if c ∈ s pop!(s, c) else push!(s, c) end
end
missperm *= first(s)
end
return missperm
end
</syntaxhighlight>
i == 0 || println()
 
if length(missperms) > 0
=== Alternative method 2 ===
println("The following permutations are missing:")
{{trans|Raku}}
for s in missperms
<syntaxhighlight lang="julia">function missingperm2(arr::Vector)
println(" ", s)
len = length(arr[1])
xorval = zeros(UInt8, len)
for perm in [Vector{UInt8}(s) for s in arr], i in 1:len
xorval[i] ⊻= perm[i]
end
return String(xorval)
else
println("There are no missing permutations.")
end
</lang>
 
@show missingperm(arr)
{{out}}
@show missingperm1(arr)
@show missingperm2(arr)
 
@btime missingperm(arr)
@btime missingperm1(arr)
@btime missingperm2(arr)
</syntaxhighlight>{{out}}
<pre>
missingperm(arr) = "DBAC"
The test list is:
missingperm1(arr) = "DBAC"
ABCD CABD ACDB DACB BCDA
missingperm2(arr) = "DBAC"
ACBD ADCB CDAB DABC BCAD
6.460 μs (148 allocations: 8.55 KiB)
CADB CDBA CBAD ABDC ADBC
6.780 μs (24 allocations: 2.13 KiB)
BDCA DCBA BACD BADC BDAC
3.100 μs (50 allocations: 2.94 KiB)
CBDA DBCA DCAB
The following permutations are missing:
DBAC
</pre>
 
=={{header|K}}==
<langsyntaxhighlight Klang="k"> split:{1_'(&x=y)_ x:y,x}
 
g: ("ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB")
Line 1,328 ⟶ 2,110:
p2@&~p2 _lin p
"DBAC"</langsyntaxhighlight>
 
Alternative approach:
<langsyntaxhighlight Klang="k">
table:{b@<b:(x@*:'a),'#:'a:=x}
,/"ABCD"@&:'{5=(table p[;x])[;1]}'!4
"DBAC"</langsyntaxhighlight>
 
Third approach (where p is the given set of permutations):
<syntaxhighlight lang="k">
<lang K>
,/p2@&~(p2:{x@m@&n=(#?:)'m:!n#n:#x}[*p]) _lin p
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.1.2
 
fun <T> permute(input: List<T>): List<List<T>> {
if (input.size == 1) return listOf(input)
val perms = mutableListOf<List<T>>()
val toInsert = input[0]
for (perm in permute(input.drop(1))) {
for (i in 0..perm.size) {
val newPerm = perm.toMutableList()
newPerm.add(i, toInsert)
perms.add(newPerm)
}
}
return perms
}
 
fun <T> missingPerms(input: List<T>, perms: List<List<T>>) = permute(input) - perms
 
fun main(args: Array<String>) {
val input = listOf('A', 'B', 'C', 'D')
val strings = listOf(
"ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB",
"DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA",
"DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"
)
val perms = strings.map { it.toList() }
val missing = missingPerms(input, perms)
if (missing.size == 1)
print("The missing permutation is ${missing[0].joinToString("")}")
else {
println("There are ${missing.size} missing permutations, namely:\n")
for (perm in missing) println(perm.joinToString(""))
}
}</syntaxhighlight>
 
{{out}}
<pre>
The missing permutation is DBAC
</pre>
 
=={{header|Lua}}==
Using the popular Penlight extension module - https://luarocks.org/modules/steved/penlight
<langsyntaxhighlight Lualang="lua">local permute, tablex = require("pl.permute"), require("pl.tablex")
local permList, pStr = {
"ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB",
Line 1,352 ⟶ 2,175:
pStr = table.concat(perm)
if not tablex.find(permList, pStr) then print(pStr) end
end</langsyntaxhighlight>
{{out}}
<pre>DBAC</pre>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">lst := ["ABCD","CABD","ACDB","DACB","BCDA","ACBD","ADCB","CDAB","DABC","BCAD","CADB","CDBA","CBAD","ABDC","ADBC","BDCA","DCBA","BACD","BADC","BDAC","CBDA","DBCA","DCAB"]:
perm := table():
for letter in "ABCD" do
perm[letter] := 0:
end do:
for item in lst do
for letter in "ABCD" do
perm[letter] += StringTools:-FirstFromLeft(letter, item):
end do:
end do:
print(StringTools:-Join(ListTools:-Flatten([indices(perm)], 4)[sort(map(x->60-x, ListTools:-Flatten([entries(perm)],4)),'output=permutation')], "")):</syntaxhighlight>
{{Out|Output}}
<pre>"DBAC"</pre>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">ProvidedSet = {"ABCD" , "CABD" , "ACDB" , "DACB" , "BCDA" , "ACBD",
"ADCB" , "CDAB", "DABC", "BCAD" , "CADB", "CDBA" , "CBAD" , "ABDC",
"ADBC" , "BDCA", "DCBA" , "BACD", "BADC", "BDAC" , "CBDA", "DBCA", "DCAB"};
Line 1,364 ⟶ 2,202:
 
 
->{"DBAC"}</langsyntaxhighlight>
 
=={{header|MATLAB}}==
This solution is designed to work on a column vector of strings. This will not work with a cell array or row vector of strings.
 
<langsyntaxhighlight MATLABlang="matlab">function perm = findMissingPerms(list)
 
permsList = perms(list(1,:)); %Generate all permutations of the 4 letters
Line 1,395 ⟶ 2,233:
end %for
end %fingMissingPerms</langsyntaxhighlight>
 
{{out}}
<langsyntaxhighlight MATLABlang="matlab">>> list = ['ABCD';
'CABD';
'ACDB';
Line 1,452 ⟶ 2,290:
ans =
 
DBAC</langsyntaxhighlight>
 
=={{header|Nim}}==
{{trans|Python}}
<langsyntaxhighlight lang="nim">import strutils
 
proc missingPermutation(arr: openArray[string]): string =
result = ""
if arr.len == 0: return
if arr.len == 1: return arr[0][1] & arr[0][0]
 
for pos in 0 .. < arr[0].len:
var s: set[char] = {}
for permutation in arr:
Line 1,472 ⟶ 2,310:
 
const given = """ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA
CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB""".splitsplitWhiteSpace()
 
echo missingPermutation(given)</langsyntaxhighlight>
{{out}}
<pre>DBAC</pre>
Line 1,481 ⟶ 2,319:
 
some utility functions:
<langsyntaxhighlight lang="ocaml">(* insert x at all positions into li and return the list of results *)
let rec insert x = function
| [] -> [[x]]
Line 1,498 ⟶ 2,336:
(* convert a char list to a string *)
let string_of_chars cl =
String.concat "" (List.map (String.make 1) cl)</langsyntaxhighlight>
 
resolve the task:
 
<langsyntaxhighlight lang="ocaml">let deficient_perms = [
"ABCD";"CABD";"ACDB";"DACB";
"BCDA";"ACBD";"ADCB";"CDAB";
Line 1,517 ⟶ 2,355:
let results = List.filter (fun v -> not(List.mem v deficient_perms)) perms
 
let () = List.iter print_endline results</langsyntaxhighlight>
 
Alternate method : if we had all permutations,
Line 1,525 ⟶ 2,363:
of the number of occurences of each letter.
The following program works with permutations of at least 3 letters:
<langsyntaxhighlight lang="ocaml">let array_of_perm s =
let n = String.length s in
Array.init n (fun i -> int_of_char s.[i] - 65);;
Line 1,554 ⟶ 2,392:
 
find_missing deficient_perms;;
(* - : string = "DBAC" *)</langsyntaxhighlight>
 
=={{header|Octave}}==
<langsyntaxhighlight lang="octave">given = [ 'ABCD';'CABD';'ACDB';'DACB'; ...
'BCDA';'ACBD';'ADCB';'CDAB'; ...
'DABC';'BCAD';'CADB';'CDBA'; ...
Line 1,571 ⟶ 2,409:
bits(there) = 0;
missing = dec2base(find(bits)-1,'ABCD')
</syntaxhighlight>
</lang>
 
=={{header|Oz}}==
Using constraint programming for this problem may be a bit overkill...
<langsyntaxhighlight lang="oz">declare
GivenPermutations =
["ABCD" "CABD" "ACDB" "DACB" "BCDA" "ACBD" "ADCB" "CDAB" "DABC" "BCAD" "CADB" "CDBA"
Line 1,594 ⟶ 2,432:
{System.showInfo "Missing: "#P}
end
end</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">v=["ABCD","CABD","ACDB","DACB","BCDA","ACBD","ADCB","CDAB","DABC","BCAD","CADB","CDBA","CBAD","ABDC","ADBC","BDCA","DCBA","BACD","BADC","BDAC","CBDA","DBCA","DCAB"];
v=apply(u->permtonum(apply(n->n-64,Vec(Vecsmall(u)))),v);
t=numtoperm(4, binomial(4!,2)-sum(i=1,#v,v[i]));
Strchr(apply(n->n+64,t))</langsyntaxhighlight>
{{out}}
<pre>%1 = "DBAC"</pre>
 
=={{header|Pascal}}==
like [[c]], summation, and [[Perl 6Raku]] XORing
<langsyntaxhighlight lang="pascal">program MissPerm;
{$MODE DELPHI} //for result
 
Line 1,649 ⟶ 2,489:
For row := low(tcol) to High(tcol) do
IF SumElemCol[col,row]=fibN_1 then
result[col]:= chransichar(row+chOfs);
end;
 
Line 1,660 ⟶ 2,500:
For row := low(tmissPerm) to High(tmissPerm) do
For col := low(tcol) to High(tcol) do
result[col] := chransichar(ord(result[col]) XOR ord(Given_Permutations[row,col]));
end;
 
Line 1,666 ⟶ 2,506:
writeln(CountOccurences,' is missing');
writeln(CheckXOR,' is missing');
end.</langsyntaxhighlight>{{out}}<pre>DBAC is missing
DBAC is missing</pre>
 
Line 1,674 ⟶ 2,514:
the first missing rotation is the target.
 
<langsyntaxhighlight Perllang="perl">sub check_perm {
my %hash; @hash{@_} = ();
for my $s (@_) { exists $hash{$_} or return $_
Line 1,683 ⟶ 2,523:
@perms = qw(ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA
CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB);
print check_perm(@perms), "\n";</langsyntaxhighlight>
 
{{out}}
<pre>DBAC</pre>
 
===Alternates===
=={{header|Perl 6}}==
All cases take permutation list on STDIN or as filename on command line
<lang perl6>my @givens = <ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA
<br><br>
CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB>;
If the string XOR was of all the permutations, the result would be a string of nulls "\0",
 
since one is missing, it is the result of XOR of all the rest :)
my @perms = <A B C D>.permutations.map: *.join;
<syntaxhighlight lang="perl">print eval join '^', map "'$_'", <>;</syntaxhighlight>
 
or if you don't like eval...
.say when none(@givens) for @perms;</lang>
<syntaxhighlight lang="perl">$\ ^= $_ while <>;
{{out}}<pre>DBAC</pre>
print '';</syntaxhighlight>
Of course, all of these solutions are working way too hard,
whenEvery youpermutation canhas a "reverse", just xortake all reverses and remove the bits,"normals".
<syntaxhighlight lang="perl">local $_ = join '', <>;
and the missing one will just pop right out:
my %h = map { $_, '' } reverse =~ /\w+/g;
<lang perl6>say [~^] @givens;</lang>
delete @h{ /\w+/g };
{{out}}<pre>DBAC</pre>
print %h, "\n";</syntaxhighlight>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>constant perms = {"ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB",
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
"DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA",
<span style="color: #008080;">constant</span> <span style="color: #000000;">perms</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"ABCD"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"CABD"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"ACDB"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"DACB"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"BCDA"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"ACBD"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"ADCB"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"CDAB"</span><span style="color: #0000FF;">,</span>
"DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"}
<span style="color: #008000;">"DABC"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"BCAD"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"CADB"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"CDBA"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"CBAD"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"ABDC"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"ADBC"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"BDCA"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"DCBA"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"BACD"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"BADC"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"BDAC"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"CBDA"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"DBCA"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"DCAB"</span><span style="color: #0000FF;">}</span>
-- 1: sum of letters
sequence r = repeat(0,4)
<span style="color: #000080;font-style:italic;">-- 1: sum of letters</span>
for i=1 to length(perms) do
<span style="color: #004080;">sequence</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span>
r = sq_add(r,perms[i])
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">perms</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
end for
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sq_add</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">,</span><span style="color: #000000;">perms</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
r = sq_sub(max(r)+'A',r)
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
puts(1,r&'\n')
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sq_sub</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">max</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">)+</span><span style="color: #008000;">'A'</span><span style="color: #0000FF;">,</span><span style="color: #000000;">r</span><span style="color: #0000FF;">)</span>
-- based on the notion that missing = sum(full)-sum(partial) would be true,
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">r</span><span style="color: #0000FF;">})</span>
-- and that sum(full) would be like {M,M,M,M} rather than a mix of numbers.
<span style="color: #000080;font-style:italic;">-- based on the notion that missing = sum(full)-sum(partial) would be true,
-- the final step is equivalent to eg {1528,1530,1531,1529}
-- and that sum(full) would be like {M,M,M,M} rather than a mix of numbers.
-- max-r[i] -> { 3, 1, 0, 2}
-- the final step is equivalent to chars ->eg { D1528, B1530, A1531,1529} C}
-- max-r[i] -&gt; { 3, 1, 0, 2}
-- (but obviously both done in one line)
-- to chars -&gt; { D, B, A, C}
 
-- (but obviously both done in one line)
-- 2: the xor trick
r = repeat(0,4)
-- 2: the xor trick</span>
for i=1 to length(perms) do
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span>
r = sq_xor_bits(r,perms[i])
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">perms</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
end for
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sq_xor_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">,</span><span style="color: #000000;">perms</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
puts(1,r&'\n')
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
-- (relies on the missing chars being present an odd number of times, non-missing chars an even number of times)
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">r</span><span style="color: #0000FF;">})</span>
 
<span style="color: #000080;font-style:italic;">-- (relies on the missing chars being present an odd number of times, non-missing chars an even number of times)
-- 3: find least frequent letters
r = " "
-- 3: find least frequent letters</span>
for i=1 to length(r) do
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">" "</span>
sequence count = repeat(0,4)
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
for j=1 to length(perms) do
<span style="color: #004080;">sequence</span> <span style="color: #000000;">count</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span>
count[perms[j][i]-'A'+1] += 1
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">perms</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
end for
<span style="color: #004080;">integer</span> <span style="color: #000000;">cdx</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">perms</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">][</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]-</span><span style="color: #008000;">'A'</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span>
r[i] = smallest(count,1)+'A'-1
<span style="color: #000000;">count</span><span style="color: #0000FF;">[</span><span style="color: #000000;">cdx</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
puts(1,r&'\n')
<span style="color: #000000;">r</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">smallest</span><span style="color: #0000FF;">(</span><span style="color: #000000;">count</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)+</span><span style="color: #008000;">'A'</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span>
-- (relies on the assumption that a full set would have each letter occurring the same number of times in each position)
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
-- (smallest(count,1) returns the index position of the smallest, rather than it's value)
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">r</span><span style="color: #0000FF;">})</span>
 
<span style="color: #000080;font-style:italic;">-- (relies on the assumption that a full set would have each letter occurring the same number of times in each position)
-- 4: test all permutations
-- (smallest(count,1) returns the index position of the smallest, rather than it's value)
for i=1 to factorial(4) do
r = permute(i,"ABCD")
-- 4: test all permutations</span>
if not find(r,perms) then exit end if
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">factorial</span><span style="color: #0000FF;">(</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
end for
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">permute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"ABCD"</span><span style="color: #0000FF;">)</span>
puts(1,r&'\n')
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">,</span><span style="color: #000000;">perms</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
-- (relies on brute force(!) - but this is the only method that could be made to cope with >1 omission)</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">r</span><span style="color: #0000FF;">})</span>
<span style="color: #000080;font-style:italic;">-- (relies on brute force(!) - but this is the only method that could be made to cope with &gt;1 omission)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,758 ⟶ 2,603:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
$finalres = Array();
function permut($arr,$result=array()){
Line 1,778 ⟶ 2,623:
permut($given);
print_r(array_diff($finalres,$givenPerms)); // Array ( [20] => DBAC )
</syntaxhighlight>
</lang>
 
=={{header|Picat}}==
Here are several approaches, including constraint modelling, sets (ordset), and permutations.
 
All assume that the variables P1 and/or Perms has been defined:
<syntaxhighlight lang="picat"> P1 = ["ABCD","CABD","ACDB","DACB","BCDA","ACBD",
"ADCB","CDAB","DABC","BCAD","CADB","CDBA",
"CBAD","ABDC","ADBC","BDCA","DCBA","BACD",
"BADC","BDAC","CBDA","DBCA","DCAB"],
Perms = permutations("ABCD"),
% ...
</syntaxhighlight>
 
===Very imperative===
<syntaxhighlight lang="picat"> % ...
Missing = _,
foreach(P in Perms, Missing = _)
Found = false,
foreach(T in P1)
if P == T then
Found := true
end
end,
if not Found then
Missing := P
end
end,
println(missing1=Missing).</syntaxhighlight>
 
===Somewhat less imperative===
<syntaxhighlight lang="picat"> % ...
Missing2 = _,
foreach(P in Perms, Missing2 = _)
if not member(P,P1) then
Missing2 := P
end
end,
println(missing2=Missing2).</syntaxhighlight>
 
===Using findall===
<syntaxhighlight lang="picat"> % ...
println(missing3=difference(Perms,P1)).
 
difference(Xs,Ys) = findall(X,(member(X,Xs),not(member(X,Ys)))).</syntaxhighlight>
 
===findall approach as a one-liner===
<syntaxhighlight lang="picat"> % ...
println(missing4=findall(X,(member(X,Perms),not(member(X,P1))))).</syntaxhighlight>
 
===Using ordsets===
The module <code>ordsets</code> must be imported,
<syntaxhighlight lang="picat">import ordsets.
% ...
println(missing5=subtract(new_ordset(Perms),new_ordset(P1))).</syntaxhighlight>
 
===List comprehension===
List comprehension with <code>membchk/1</code> for the check)
<syntaxhighlight lang="picat"> % ...
println(missing6=[P:P in Perms,not membchk(P,P1)])</syntaxhighlight>
 
===Using maps===
<syntaxhighlight lang="picat"> % ...
Map = new_map(),
foreach(P in P1) Map.put(P,1) end,
println(missing7=[P: P in Perms, not Map.has_key(P)]).</syntaxhighlight>
 
==="Merge sort" variants===
"Merge sort" variants, using sorted lists. <code>zip/2</code> requires that the length of the two lists are the same, hence the "dummy".
<syntaxhighlight lang="picat"> % ...
PermsSorted = Perms.sort(),
P1Sorted = P1.sort(),
Found2 = false,
foreach({P,PP} in zip(PermsSorted,P1Sorted ++ ["DUMMY"]), Found2 = false)
if P != PP then
println(missing8=P),
Found2 := true
end
end,
 
A = [cond(P == PP,1,0) : {P,PP} in zip(PermsSorted,P1Sorted ++ ["DUMMY"])],
println(missing9=[PermsSorted[I] : I in 1..PermsSorted.length, A[I] = 0].first()),
 
% shorter
println(missing10=[P:{P,PP} in zip(PermsSorted,P1Sorted ++ ["DUMMY"]), P != PP].first()),</syntaxhighlight>
 
===Constraint modelling===
The <code>cp</code> module must be imported.
<syntaxhighlight lang="picat">import cp.
 
% ...
ABCD = new_map(['A'=1,'B'=2,'C'=3,'D'=4]),
 
% convert to integers (for the table constraint)
P1Table = [ [ABCD.get(C,0) : C in P].to_array() : P in P1],
Missing3 = new_list(4), Missing3 :: 1..4,
all_different(Missing3),
table_notin({Missing3[1],Missing3[2],Missing3[3],Missing3[4]},P1Table),
solve(Missing3),
ABCD2 = "ABCD",
println(missing11=[ABCD2[I] : I in Missing3]).</syntaxhighlight>
 
===Matrix approach===
<syntaxhighlight lang="picat"> % ...
PermsLen = Perms.length,
P1Len = P1.length,
A2 = new_array(PermsLen,P1Len), bind_vars(A2,0),
foreach(I in 1..PermsLen, J in 1..P1Len, Perms[I] = P1[J])
A2[I,J] := 1
end,
println(missing12=[Perms[I] : I in 1..PermsLen, sum([A2[I,J] : J in 1..P1Len])=0]).</syntaxhighlight>
 
===Xor variant===
{{trans|Raku}}
<syntaxhighlight lang="picat"> % ...
println(missing13=to_fstring("%X",reduce(^,[parse_term("0x"++P):P in P1]))).</syntaxhighlight>
 
===Count occurrences===
Count the character with the least occurrence (=5) for each positions (1..4). Some variants.
{{trans|K}}
<syntaxhighlight lang="picat"> % ...
println(missing14=[[O:O=5 in Occ]:Occ in [occurrences([P[I]:P in P1]):I in 1..4]]),
 
% variant using sorting the occurrences
println(missing15a=[C:C=_ in [sort2(Occ).first():Occ in [occurrences([P[I]:P in P1]):I in 1..4]]]),
 
% transpose instead of array index
println(missing15b=[C:C=_ in [sort2(O).first():T in transpose(P1),O=occurrences(T)]]),
 
% extract the values with first
println(missing15c=[sort2(O).first():T in transpose(P1),O=occurrences(T)].map(first)),
 
println(missing15d=[sort2(O).first().first():T in transpose(P1),O=occurrences(T)]),
 
println(missing15e=[S[1,1]:T in transpose(P1),S=sort2(occurrences(T))]).
 
% return a map with the elements and the number of occurrences
occurrences(List) = Map =>
Map = new_map(),
foreach(E in List)
Map.put(E, cond(Map.has_key(E),Map.get(E)+1,1))
end,
Perms2 = Perms,
foreach(P in P1) Perms2 := delete(Perms2,P) end,
println(missing16=Perms2),
 
nl.
 
% sort a map according to values
sort2(Map) = [K=V:_=(K=V) in sort([V=(K=V): K=V in Map])]
</syntaxhighlight>
 
Running all these snippets:
{{out}}
<pre>
missing1 = DBAC
missing2 = DBAC
missing3 = [DBAC]
missing4 = [DBAC]
missing5 = [DBAC]
missing6 = [DBAC]
missing7 = [DBAC]
missing8 = DBAC
missing9 = DBAC
missing10 = DBAC
missing11 = DBAC
missing12 = [DBAC]
missing13 = DBAC
missing14 = [D,B,A,C]
missing15a = DBAC
missing15b = DBAC
missing15c = DBAC
missing15d = DBAC
missing15e = DBAC
missing16 = [DBAC]</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(setq *PermList
(mapcar chop
(quote
Line 1,795 ⟶ 2,815:
(rot L) )
(unless (member Lst *PermList) # Check
(prinl Lst) ) ) ) )</langsyntaxhighlight>
{{out}}
<pre>DBAC</pre>
Line 1,802 ⟶ 2,822:
 
{{works with|PowerShell|4.0}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
function permutation ($array) {
function generate($n, $array, $A) {
Line 1,859 ⟶ 2,879:
)
$perm | where{-not $find.Contains($_)}
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 1,866 ⟶ 2,886:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure in_List(in.s)
Define.i i, j
Define.s a
Line 1,904 ⟶ 2,924:
Data.s "DABC","BCAD","CADB","CDBA","CBAD","ABDC","ADBC","BDCA"
Data.s "DCBA","BACD","BADC","BDAC","CBDA","DBCA","DCAB"
EndDataSection</langsyntaxhighlight>
 
Based on the [[Permutations#PureBasic|Permutations]] task,
the solution could be:
<langsyntaxhighlight PureBasiclang="purebasic">If OpenConsole()
NewList a.s()
findPermutations(a(), "ABCD", 4)
Line 1,922 ⟶ 2,942:
Print(#CRLF$ + "Press ENTER to exit"): Input()
EndIf</langsyntaxhighlight>
 
=={{header|Python}}==
===Python: Calculate difference when compared to all permutations===
{{works with|Python|2.6+}}
<langsyntaxhighlight lang="python">from itertools import permutations
 
given = '''ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA
Line 1,934 ⟶ 2,954:
allPerms = [''.join(x) for x in permutations(given[0])]
 
missing = list(set(allPerms) - set(given)) # ['DBAC']</langsyntaxhighlight>
 
===Python:Counting lowest frequency character at each position===
Line 1,940 ⟶ 2,960:
i.e. it never needs to generate the full set of expected permutations.
 
<langsyntaxhighlight lang="python">
def missing_permutation(arr):
"Find the missing permutation in an array of N! - 1 permutations."
Line 1,971 ⟶ 2,991:
print missing_permutation(given)
</syntaxhighlight>
</lang>
 
===Python:Counting lowest frequency character at each position: functional===
Uses the same method as explained directly above,
but calculated in a more functional manner:
<langsyntaxhighlight lang="python">>>> from collections import Counter
>>> given = '''ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA
CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB'''.split()
>>> ''.join(Counter(x).most_common()[-1][0] for x in zip(*given))
'DBAC'
>>> </langsyntaxhighlight>
 
;Explanation
Line 1,990 ⟶ 3,010:
created by the call to <code>most_common()</code>
is the least common character.
<langsyntaxhighlight lang="python">>>> from pprint import pprint as pp
>>> pp(list(zip(*given)), width=120)
[('A', 'C', 'A', 'D', 'B', 'A', 'A', 'C', 'D', 'B', 'C', 'C', 'C', 'A', 'A', 'B', 'D', 'B', 'B', 'B', 'C', 'D', 'D'),
Line 2,007 ⟶ 3,027:
>>> ''.join([Counter(x).most_common()[-1][0] for x in zip(*given)])
'DBAC'
>>> </langsyntaxhighlight>
 
===Python:Folding XOR over the set of strings===
Surfacing the missing bits:
{{Trans|JavaScript}}
<syntaxhighlight lang="python">'''Find the missing permutation'''
 
from functools import reduce
from operator import xor
 
 
print(''.join([
chr(i) for i in reduce(
lambda a, s: map(
xor,
a,
[ord(c) for c in list(s)]
), [
'ABCD', 'CABD', 'ACDB', 'DACB',
'BCDA', 'ACBD', 'ADCB', 'CDAB',
'DABC', 'BCAD', 'CADB', 'CDBA',
'CBAD', 'ABDC', 'ADBC', 'BDCA',
'DCBA', 'BACD', 'BADC', 'BDAC',
'CBDA', 'DBCA', 'DCAB'
],
[0, 0, 0, 0]
)
]))</syntaxhighlight>
{{Out}}
<pre>DBAC</pre>
 
=={{header|Quackery}}==
 
Credit to [[#Raku|Raku]] for the method, and noting that the strings are valid hexadecimal numbers.
 
<syntaxhighlight lang="quackery"> $ "ABCD CABD ACDB DACB BCDA ACBD
ADCB CDAB DABC BCAD CADB CDBA
CBAD ABDC ADBC BDCA DCBA BACD
BADC BDAC CBDA DBCA DCAB" nest$
16 base put
[] swap
witheach [ $->n drop join ]
0 swap witheach ^
number$ echo$
base release</syntaxhighlight>
 
{{out}}
 
<pre>DBAC</pre>
 
=={{header|R}}==
This uses the "combinat" package, which is a standard R package:
<syntaxhighlight lang="text">
library(combinat)
 
Line 2,024 ⟶ 3,092:
 
setdiff(perms3, incomplete)
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,032 ⟶ 3,100:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 2,068 ⟶ 3,136:
c))
;; -> '(D B A C)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>my @givens = <ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA
CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB>;
 
my @perms = <A B C D>.permutations.map: *.join;
 
.say when none(@givens) for @perms;</syntaxhighlight>
{{out}}<pre>DBAC</pre>
Of course, all of these solutions are working way too hard,
when you can just xor all the bits,
and the missing one will just pop right out:
<syntaxhighlight lang="raku" line>say [~^] <ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA
CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB>;</syntaxhighlight>
{{out}}<pre>DBAC</pre>
 
=={{header|RapidQ}}==
<syntaxhighlight lang="vb">
<lang vb>
Dim PList as QStringList
PList.addItems "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB"
Line 2,096 ⟶ 3,180:
showmessage MPerm
'= DBAC
</syntaxhighlight>
</lang>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX pgm finds one or more missing permutations from an internal list & displays them.*/
list = 'ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA',
"DCBA BACD BADC BDAC CBDA DBCA DCAB" 'CBAD ABDC ADBC/*list BDCAthat DCBAis BACDmissing BADCone BDAC CBDA DBCA DCAB'permutation.*/
@.= /* [↓] needs to be as long as THINGS.*/
@abcU = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' /*an uppercase (Latin/Roman) alphabet. */
things = 4 /*number of unique letters to be used. */
bunch = 4 /*number letters to be used at a time. */
do j=1 for things /* [↓] only get a portion of alphabet.*/
$.j= substr(@abcU, j, 1) /*extract just one letter from alphabet*/
end /*j*/ /* [↑] build a letter array for speed.*/
call permSet 1 /*invoke PERMSET subroutine recursively*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
permSet: procedure expose $. @. bunch list things; parse arg ? /*calls self recursively.*/
if ?>bunch then do; _=
do m=1 for bunch /*build a permutation. */
_= _ || @.m /*add permutation──►list.*/
end /*m*/
/* [↓] is in the list? */
Line 2,122 ⟶ 3,206:
else do x=1 for things /*build a permutation. */
do k=1 for ?-1
if @.k==$.x then iterate x /*was permutation built? */
end /*k*/
@.?= $.x /*define as being built. */
call permSet ?+1 /*call subr.self recursively. */
end /*x*/
return</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
'''output'''
<pre>
DBAC is missing from the list.
Line 2,134 ⟶ 3,218:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
list = "ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB"
Line 2,148 ⟶ 3,232:
next
next
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,156 ⟶ 3,240:
=={{header|Ruby}}==
{{works with|Ruby|2.0+}}
<langsyntaxhighlight lang="ruby">given = %w{
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA
CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB
Line 2,163 ⟶ 3,247:
all = given[0].chars.permutation.collect(&:join)
puts "missing: #{all - given}"</langsyntaxhighlight>
{{out}}
<pre>
Line 2,170 ⟶ 3,254:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">list$ = "ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB"
 
for a = asc("A") to asc("D")
Line 2,185 ⟶ 3,269:
next c
next b
next a</langsyntaxhighlight>
{{out}}
<pre>DBAC missing</pre>
 
=={{header|Rust}}==
{{trans|Go}}
Xor method suggested by Raku contributor:
<syntaxhighlight lang="rust">const GIVEN_PERMUTATIONS: [&str; 23] = [
"ABCD",
"CABD",
"ACDB",
"DACB",
"BCDA",
"ACBD",
"ADCB",
"CDAB",
"DABC",
"BCAD",
"CADB",
"CDBA",
"CBAD",
"ABDC",
"ADBC",
"BDCA",
"DCBA",
"BACD",
"BADC",
"BDAC",
"CBDA",
"DBCA",
"DCAB"
];
 
fn main() {
 
const PERMUTATION_LEN: usize = GIVEN_PERMUTATIONS[0].len();
let mut bytes_result: [u8; PERMUTATION_LEN] = [0; PERMUTATION_LEN];
 
for permutation in &GIVEN_PERMUTATIONS {
for (i, val) in permutation.bytes().enumerate() {
bytes_result[i] ^= val;
}
}
println!("{}", std::str::from_utf8(&bytes_result).unwrap());
}
 
</syntaxhighlight>
{{out}}
<pre>
DBAC
</pre>
 
=={{header|Scala}}==
{{libheader|Scala}}
{{works with|Scala|2.8}}
<langsyntaxhighlight lang="scala">def fat(n: Int) = (2 to n).foldLeft(1)(_*_)
def perm[A](x: Int, a: Seq[A]): Seq[A] = if (x == 0) a else {
val n = a.size
Line 2,231 ⟶ 3,363:
DBCA
DCAB""".stripMargin.split("\n")
println(findMissingPerm(perms(0), perms))</langsyntaxhighlight>
 
===Scala 2.9.x===
{{works with|Scala|2.9.1}}
<langsyntaxhighlight Scalalang="scala">println("missing perms: "+("ABCD".permutations.toSet
--"ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB".stripMargin.split(" ").toSet))</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
const func string: missingPermutation (in array string: perms) is func
Line 2,271 ⟶ 3,403:
"ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC",
"BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB")));
end func;</langsyntaxhighlight>
 
{{out}}
Line 2,280 ⟶ 3,412:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func check_perm(arr) {
(var hash = Hash.new().@{arr} = @[1]*arr.len;
hash.set_keys(arr...)
arr.each { |s|
s.len.times {
var t = (s.substr(1) + s.substr(0, 1));
hash.has_key(t) || return t;
} * s.len
}
}
 
var perms = %w(ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA
CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB);
 
say check_perm(perms);</langsyntaxhighlight>
{{out}}
<pre>
DBAC
</pre>
 
=={{header|TI-83 BASIC}}==
<syntaxhighlight lang="ti83b">"ABCDCABDACDBDACBBCDAACBDADCBCDABDABCBCADCADBCDBACBADABDCADBCBDCADCBABACDBADCBDACCBDADBCADCAB"→Str0
"ABCD"→Str1
length(Str0)→L
[[0,0,0,0][0,0,0,0][0,0,0,0][0,0,0,0]]→[A]
 
For(I,1,L,4)
For(J,1,4,1)
sub(Str0,I+J-1,1)→Str2
For(K,1,4,1)
sub(Str1,K,1)→Str3
If Str2=Str3
Then
[A](J,K)+1→[A](J,K)
End
End
End
End
 
Matr►list([A],1,L₁)
min(L₁)→M
 
" "→Str4
 
For(I,1,4,1)
For(J,1,4,1)
If [A](I,J)=M
Then
Str4+sub(Str1,J,1)→Str4
End
End
End
sub(Str4,2,4)→Str4
Disp "MISSING"
Disp Str4</syntaxhighlight>
 
=={{header|Tcl}}==
{{tcllib|struct::list}}
<langsyntaxhighlight lang="tcl">
package require struct::list
 
Line 2,315 ⟶ 3,484:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Ursala}}==
Line 2,321 ⟶ 3,490:
and needn't be reinvented, but its definition is shown here in the interest of
comparison with other solutions.
<langsyntaxhighlight Ursalalang="ursala">permutations = ~&itB^?a\~&aNC *=ahPfatPRD refer ^C/~&a ~&ar&& ~&arh2falrtPXPRD</langsyntaxhighlight>
The <code>~&j</code> operator computes set differences.
<langsyntaxhighlight Ursalalang="ursala">#import std
#show+
 
Line 2,351 ⟶ 3,520:
CBDA
DBCA
DCAB]-</langsyntaxhighlight>
{{out}}
<pre>
Line 2,359 ⟶ 3,528:
=={{header|VBScript}}==
Uses the 3rd method approach by adding the columns.
<syntaxhighlight lang="vb">
<lang vb>
arrp = Array("ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD",_
"ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA",_
Line 2,384 ⟶ 3,553:
 
WScript.StdOut.WriteLine missing
</syntaxhighlight>
</lang>
 
{{Out}}
<pre>DBAC</pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">
fn main() {
list := ('ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB
CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB')
elem := ['A', 'B', 'C', 'D']
if find_missed_pmt_1(list, elem) !='' {println('${find_missed_pmt_1(list, elem)} is missing')}
else {println('Warning: nothing found')}
if find_missed_pmt_2(list, elem) !='' {println('${find_missed_pmt_2(list, elem)} is missing')}
else {println('Warning: nothing found')}
if find_missed_pmt_3(list, elem) !='' {println('${find_missed_pmt_3(list, elem)} is missing')}
else {println('Warning: nothing found')}
}
 
fn find_missed_pmt_1(list string, elem []string) string {
mut result := ''
for avals in elem {
for bvals in elem {
for cvals in elem {
for dvals in elem {
result = avals + bvals + cvals + dvals
if avals != bvals
&& avals != cvals
&& avals != dvals
&& bvals != cvals
&& bvals != dvals
&& cvals != dvals {
if list.replace_each(['\n','','\t','']).split(' ').any(it == result) == false {return result}
}
}
}
}
}
return result
}
 
fn find_missed_pmt_2(list string, elem []string) string {
list_arr := list.replace_each(['\n','','\t','']).split(' ')
mut es := []u8{len: elem.len}
mut aa := map[u8]int{}
mut result :=''
for idx, _ in es {
aa = map[u8]int{}
for vals in list_arr {
aa[vals[idx]]++
}
for chr, count in aa {
if count & 1 == 1 {
result += chr.ascii_str()
break
}
}
}
return result
}
 
fn find_missed_pmt_3(list string, elem []string) string {
list_arr := list.replace_each(['\n','','\t','']).split(' ')
mut miss_1_arr, mut miss_2_arr, mut miss_3_arr, mut miss_4_arr := []u8{}, []u8{}, []u8{}, []u8{}
mut res1, mut res2, mut res3, mut res4 := '', '', '', ''
for group in list_arr {
for chr in group[0].ascii_str() {miss_1_arr << chr}
for chr in group[1].ascii_str() {miss_2_arr << chr}
for chr in group[2].ascii_str() {miss_3_arr << chr}
for chr in group[3].ascii_str() {miss_4_arr << chr}
}
for chr in elem {
if miss_1_arr.bytestr().count(chr) < 6 {res1 = chr}
if miss_2_arr.bytestr().count(chr) < 6 {res2 = chr}
if miss_3_arr.bytestr().count(chr) < 6 {res3 = chr}
if miss_4_arr.bytestr().count(chr) < 6 {res4 = chr}
}
return res1 + res2 + res3 + res4
}
</syntaxhighlight>
 
{{out}}
<pre>
DBAC is missing
DBAC is missing
DBAC is missing
</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-set}}
{{libheader|Wren-perm}}
<syntaxhighlight lang="wren">import "./set" for Set
import "./perm" for Perm
 
var missingPerms = Fn.new { |input, perms|
var s1 = Set.new()
s1.addAll(perms)
var perms2 = Perm.list(input).map { |p| p.join() }
var s2 = Set.new()
s2.addAll(perms2)
return s2.except(s1).toList
}
var input = ["A", "B", "C", "D"]
var perms = [
"ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB",
"DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA",
"DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"
]
var missing = missingPerms.call(input, perms)
if (missing.count == 1) {
System.print("The missing permutation is %(missing[0])")
} else {
System.print("There are %(missing.count) missing permutations, namely:\n")
System.print(missing)
}</syntaxhighlight>
 
{{out}}
<pre>
The missing permutation is DBAC
</pre>
 
=={{header|XPL0}}==
Line 2,393 ⟶ 3,681:
missperm <missperm.txt
 
<langsyntaxhighlight XPL0lang="xpl0">code HexIn=26, HexOut=27;
int P, I;
[P:= 0;
for I:= 1 to 24-1 do P:= P xor HexIn(1);
HexOut(0, P);
]</langsyntaxhighlight>
 
{{out}}
Line 2,407 ⟶ 3,695:
=={{header|zkl}}==
Since I just did the "generate the permutations" task, I'm going to use it to do the brute force solution.
<langsyntaxhighlight lang="zkl">var data=L("ABCD","CABD","ACDB","DACB","BCDA","ACBD","ADCB","CDAB",
"DABC","BCAD","CADB","CDBA","CBAD","ABDC","ADBC","BDCA",
"DCBA","BACD","BADC","BDAC","CBDA","DBCA","DCAB");
Utils.Helpers.permute(["A".."D"]).apply("concat").copy().remove(data.xplode());</langsyntaxhighlight>
Copy creates a read/write list from a read only list.
xplode() pushes all elements of data as parameters to remove.
Line 2,419 ⟶ 3,707:
 
=={{header|ZX Spectrum Basic}}==
<langsyntaxhighlight lang="zxbasic">10 LET l$="ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB"
20 LET length=LEN l$
30 FOR a= CODE "A" TO CODE "D"
Line 2,432 ⟶ 3,720:
120 NEXT i
130 PRINT x$;" is missing"
140 NEXT d: NEXT c: NEXT b: NEXT a</langsyntaxhighlight>
2,078

edits