Order disjoint list items: Difference between revisions

m
m (→‎{{header|Wren}}: Minor tidy)
 
(22 intermediate revisions by 13 users not shown)
Line 1:
{{task|Sorting Algorithms}}
[[Category:Sorting]]
{{Sorting Algorithm}}
 
Given &nbsp; <code>M</code> &nbsp; as a list of items and another list &nbsp; <code>N</code> &nbsp; of items chosen from &nbsp; <code>M</code>, &nbsp; create &nbsp; <code>M'</code> &nbsp; as a list with the ''first'' occurrences of items from &nbsp; N &nbsp; sorted to be in one of the set of indices of their original occurrence in &nbsp; <code>M</code> &nbsp; but in the order given by their order in &nbsp; <code>N</code>.
Line 40 ⟶ 42:
* [[Sort disjoint sublist]]
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F order_disjoint_list_items(&data, items)
[Int] itemindices
L(item) Set(items)
V itemcount = items.count(item)
V lastindex = [-1]
L(i) 0 .< itemcount
lastindex.append(data.index(item, lastindex.last + 1))
itemindices [+]= lastindex[1..]
itemindices.sort()
L(index, item) zip(itemindices, items)
data[index] = item
 
F slist(s)
R Array(s).map(String)
 
F tostring(l)
R ‘'’l.join(‘ ’)‘'’
 
L(data, items) [(‘the cat sat on the mat’.split(‘ ’), (‘mat cat’).split(‘ ’)),
(‘the cat sat on the mat’.split(‘ ’), (‘cat mat’).split(‘ ’)),
(slist(‘ABCABCABC’), slist(‘CACA’)),
(slist(‘ABCABDABE’), slist(‘EADA’)),
(slist(‘AB’), slist(‘B’)),
(slist(‘AB’), slist(‘BA’)),
(slist(‘ABBA’), slist(‘BA’)),
(slist(‘’), slist(‘’)),
(slist(‘A’), slist(‘A’)),
(slist(‘AB’), slist(‘’)),
(slist(‘ABBA’), slist(‘AB’)),
(slist(‘ABAB’), slist(‘AB’)),
(slist(‘ABAB’), slist(‘BABA’)),
(slist(‘ABCCBA’), slist(‘ACAC’)),
(slist(‘ABCCBA’), slist(‘CACA’))]
print(‘Data M: #<24 Order N: #<9’.format(tostring(data), tostring(items)), end' ‘ ’)
order_disjoint_list_items(&data, items)
print(‘-> M' #.’.format(tostring(data)))</syntaxhighlight>
 
{{out}}
<pre>
Data M: 'the cat sat on the mat' Order N: 'mat cat' -> M' 'the mat sat on the cat'
Data M: 'the cat sat on the mat' Order N: 'cat mat' -> M' 'the cat sat on the mat'
Data M: 'A B C A B C A B C' Order N: 'C A C A' -> M' 'C B A C B A A B C'
Data M: 'A B C A B D A B E' Order N: 'E A D A' -> M' 'E B C A B D A B A'
Data M: 'A B' Order N: 'B' -> M' 'A B'
Data M: 'A B' Order N: 'B A' -> M' 'B A'
Data M: 'A B B A' Order N: 'B A' -> M' 'B A B A'
Data M: '' Order N: '' -> M' ''
Data M: 'A' Order N: 'A' -> M' 'A'
Data M: 'A B' Order N: '' -> M' 'A B'
Data M: 'A B B A' Order N: 'A B' -> M' 'A B B A'
Data M: 'A B A B' Order N: 'A B' -> M' 'A B A B'
Data M: 'A B A B' Order N: 'B A B A' -> M' 'B A B A'
Data M: 'A B C C B A' Order N: 'A C A C' -> M' 'A B C A B C'
Data M: 'A B C C B A' Order N: 'C A C A' -> M' 'C B A C B A'
</pre>
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">order(list a, b)
{
integer j;
Line 82 ⟶ 143:
 
0;
}</langsyntaxhighlight>
{{out}}
<pre>the cat sat on the mat | mat cat -> the mat sat on the cat
Line 93 ⟶ 154:
 
=={{header|AppleScript}}==
===Functional===
{{Trans|JavaScript}}
 
Accumulate a segmentation of M over a fold/reduce, and zip with N:
<langsyntaxhighlight AppleScriptlang="applescript">-- DISJOINT ORDER ---------------------------------------- DISJOINT ORDER --------------------
 
-- disjointOrder :: String -> String -> String
Line 104 ⟶ 166:
unwords(flatten(zip(segments(ms, ns), ns & "")))
end disjointOrder
 
 
-- segments :: [String] -> [String] -> [String]
Line 127 ⟶ 190:
 
 
-- TEST --------------------------------------------- TEST -------------------------
on run
script order
Line 136 ⟶ 199:
end |λ|
end script
arrowTable(map(order, [¬
Line 156 ⟶ 220:
 
 
-- GENERIC FUNCTIONS ----------------------------------- FORMATTING ----------------------
 
-- Formatting test results
 
-- arrowTable :: [[String]] -> String
Line 193 ⟶ 255:
transpose(map(leftAligned, transpose(rows)))))
end arrowTable
 
 
-------------------- GENERIC FUNCTIONS -------------------
 
-- concatMap :: (a -> [b]) -> [a] -> [b]
Line 204 ⟶ 269:
foldl(append, {}, map(f, xs))
end concatMap
 
 
-- deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a]
Line 218 ⟶ 284:
end if
end deleteBy
 
 
-- deleteFirst :: a -> [a] -> [a]
Line 229 ⟶ 296:
deleteBy(Eq, x, xs)
end deleteFirst
 
 
-- flatten :: Tree a -> [a]
Line 238 ⟶ 306:
end if
end flatten
 
 
-- foldl :: (a -> b -> a) -> a -> [b] -> a
Line 250 ⟶ 319:
end tell
end foldl
 
 
-- intercalate :: Text -> [Text] -> Text
Line 258 ⟶ 328:
return strJoined
end intercalate
 
 
-- justifyLeft :: Int -> Char -> Text -> Text
Line 267 ⟶ 338:
end if
end justifyLeft
 
 
-- map :: (a -> b) -> [a] -> [b]
Line 279 ⟶ 351:
end tell
end map
 
 
-- maximumBy :: (a -> a -> Ordering) -> [a] -> a
Line 295 ⟶ 368:
foldl(max, missing value, xs)
end maximumBy
 
 
-- minimum :: [a] -> a
Line 310 ⟶ 384:
foldl(min, missing value, xs)
end minimum
 
 
-- Lift 2nd class handler function into 1st class script wrapper
Line 322 ⟶ 397:
end if
end mReturn
 
 
-- Egyptian multiplication - progressively doubling a list, appending
Line 340 ⟶ 416:
return out & dbl
end replicate
 
 
-- transpose :: [[a]] -> [[a]]
Line 357 ⟶ 434:
map(column, item 1 of xss)
end transpose
 
 
-- uncons :: [a] -> Maybe (a, [a])
Line 366 ⟶ 444:
end if
end uncons
 
 
-- unwords :: [String] -> String
Line 377 ⟶ 456:
words of s
end |words|
 
 
-- zip :: [a] -> [b] -> [(a, b)]
Line 387 ⟶ 467:
map(pair, items 1 thru minimum([length of xs, length of ys]) of xs)
end zip</langsyntaxhighlight>
{{Out}}
<pre>the cat sat on the mat -> mat cat -> the mat sat on the cat
Line 396 ⟶ 476:
A B -> B A -> B A
A B B A -> B A -> B A B A </pre>
----
 
===Idiomatic===
 
<syntaxhighlight lang="applescript">(*
The task description talks about items in lists, but the examples are space-delimited substrings of strings.
The handler here deals with items in lists and leaves it to the calling code to sort out the rest.
*)
on odli(m, n)
-- Use shallow copies of the lists in case the calling process wants the passed originals to remain intact.
set m to m's items
set n_source to n's items
set n_check to n's items
repeat with i from 1 to (count m)
set thisItem to item i of m
if ({thisItem} is in n_check) then
set item i of m to beginning of n_source
set n_source to rest of n_source
if (n_source is {}) then exit repeat
repeat with j from 1 to (count n_check)
if (item j of n_check is thisItem) then
set item j of n_check to beginning of n_check
set n_check to rest of n_check
exit repeat
end if
end repeat
end if
end repeat
return m
end odli
 
-- Task code:
set textPairs to {{"the cat sat on the mat", "mat cat"}, {"the cat sat on the mat", "cat mat"}, ¬
{"A B C A B C A B C", "C A C A"}, {"A B C A B D A B E", "E A D A"}, ¬
{"A B", "B"}, {"A B", "B A"}, {"A B B A", "B A"}}
set output to {}
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to space
repeat with thisPair in textPairs
set {m, n} to thisPair
set spiel to "Data M: '" & m & "'\tOrder N: '" & n & "'\t--> '"
set end of output to spiel & odli(m's text items, n's text items) & "'"
end repeat
set AppleScript's text item delimiters to linefeed
set output to output as text
set AppleScript's text item delimiters to astid
return output</syntaxhighlight>
 
{{output}}
<syntaxhighlight lang="applescript">"Data M: 'the cat sat on the mat' Order N: 'mat cat' --> 'the mat sat on the cat'
Data M: 'the cat sat on the mat' Order N: 'cat mat' --> 'the cat sat on the mat'
Data M: 'A B C A B C A B C' Order N: 'C A C A' --> 'C B A C B A A B C'
Data M: 'A B C A B D A B E' Order N: 'E A D A' --> 'E B C A B D A B A'
Data M: 'A B' Order N: 'B' --> 'A B'
Data M: 'A B' Order N: 'B A' --> 'B A'
Data M: 'A B B A' Order N: 'B A' --> 'B A B A'"</syntaxhighlight>
 
Or with, say, lists instead of substrings:
 
<syntaxhighlight lang="applescript">set listOfLists1 to {{1, 2, 3, 4, 5}, {5, 4, 3, 2, 1}, {"aardvark", "duck-billed platypus", "banana"}}
set listOfLists2 to {{"aardvark", "duck-billed platypus", "banana"}, {1, 2, 3, 4, 5}}
return odli(listOfLists1, listOfLists2)</syntaxhighlight>
 
{{output}}
<syntaxhighlight lang="applescript">{{"aardvark", "duck-billed platypus", "banana"}, {5, 4, 3, 2, 1}, {1, 2, 3, 4, 5}}</syntaxhighlight>
 
=={{header|Arturo}}==
{{trans|Nim}}
<syntaxhighlight lang="rebol">orderDisjoint: function [m,n][
ms: split.words m
ns: split.words n
 
indexes: new []
 
loop ns 'item [
idx: index ms item
unless null? idx [
'indexes ++ idx
ms\[idx]: ""
]
]
sort 'indexes
 
loop.with:'i indexes 'idx ->
ms\[idx]: ns\[i]
return join.with:" " ms
]
 
process: function [a,b][
print [a "|" b "->" orderDisjoint a b]
]
 
process "the cat sat on the mat" "mat cat"
process "the cat sat on the mat" "cat mat"
process "A B C A B C A B C" "C A C A"
process "A B C A B D A B E" "E A D A"
process "A B" "B"
process "A B" "B A"
process "A B B A" "B A"</syntaxhighlight>
 
{{out}}
 
<pre>the cat sat on the mat | mat cat -> the mat sat on the cat
the cat sat on the mat | cat mat -> the cat sat on the mat
A B C A B C A B C | C A C A -> C B A C B A A B C
A B C A B D A B E | E A D A -> E B C A B D A B A
A B | B -> A B
A B | B A -> B A
A B B A | B A -> B A B A</pre>
 
=={{header|AutoHotkey}}==
{{works with|AutoHotkey 1.1}}
<langsyntaxhighlight AutoHotkeylang="autohotkey">Data := [ {M: "the cat sat on the mat", N: "mat cat"}
, {M: "the cat sat on the mat", N: "cat mat"}
, {M: "A B C A B C A B C", N: "C A C A"}
Line 419 ⟶ 611:
Result .= (ItemsN[A_LoopField]-- > 0 ? N.Remove(1) : A_LoopField) " "
return RTrim(Result)
}</langsyntaxhighlight>
{{Output}}
<pre>the cat sat on the mat :: mat cat -> the mat sat on the cat
Line 430 ⟶ 622:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( ( odli
= M N NN item A Z R
. !arg:(?M.?N)
Line 464 ⟶ 656:
& out$(\t odli$(!M.!N))
)
);</langsyntaxhighlight>
Output:
<pre>Data M: the cat sat on the mat Order N: mat cat the mat sat on the cat
Line 475 ⟶ 667:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <vector>
Line 542 ⟶ 734:
std::cin.get();
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 554 ⟶ 746:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun order-disjoint (data order)
(let ((order-b (make-hash-table :test 'equal)))
(loop :for n :in order :do (incf (gethash n order-b 0)))
Line 561 ⟶ 753:
(decf (gethash m order-b))
(pop order))
(t m)))))</langsyntaxhighlight>
{{out}}
<pre>CL-USER> (order-disjoint '(the cat sat on the mat) '(mat cat))
Line 581 ⟶ 773:
{{trans|Python}}
This version is not efficient.
<langsyntaxhighlight lang="d">import std.stdio, std.string, std.algorithm, std.array, std.range,
std.conv;
 
Line 631 ⟶ 823:
orderDisjointArrayItems(a, b));
}
}</langsyntaxhighlight>
{{out}}
<pre>the cat sat on the mat | mat cat -> the mat sat on the cat
Line 650 ⟶ 842:
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(lib 'list) ;; for list-delete
 
Line 682 ⟶ 874:
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 698 ⟶ 890:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Order do
def disjoint(m,n) do
IO.write "#{Enum.join(m," ")} | #{Enum.join(n," ")} -> "
Line 736 ⟶ 928:
|> Enum.each(fn {m,n} ->
Order.disjoint(String.split(m),String.split(n))
end)</langsyntaxhighlight>
 
{{out}}
Line 751 ⟶ 943:
=={{header|Factor}}==
This solution is a tad bit whimsical (and a testament to the flexibility of the language that it allows something like this). <code>make-slots</code> replaces elements from ''M'' with <code>_</code> from the <code>fry</code> vocabulary according to the elements in ''N''. For example,
<langsyntaxhighlight lang="factor">qw{ the cat sat on the mat } qw{ mat cat } make-slots</langsyntaxhighlight>
produces <code>{ "the" _ "sat" "on" "the" _ }</code>. Then, <code>reorder</code> fries elements from ''N'' into the sequence. This is much like a regular fried quotation.
 
Line 758 ⟶ 950:
Finally, <code>input<sequence</code> is a smart combinator (a combinator that infers the stack effect of one or more of its inputs) that takes a sequence and a quotation and makes it so that from inside the quotation, you can think of sequence elements as though they were data stack objects. This is precisely what we want so that we can fry them.
 
<langsyntaxhighlight lang="factor">USING: assocs combinators combinators.smart effects formatting
fry kernel qw sequences ;
IN: rosetta-code.order-disjoint-list
Line 784 ⟶ 976:
{ qw{ A B B A } qw{ B A } }
}
[ show-reordering ] assoc-each</langsyntaxhighlight>
{{out}}
<pre>
Line 797 ⟶ 989:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 853 ⟶ 1,045:
}
 
}</langsyntaxhighlight>
{{out}}
<pre>
Line 865 ⟶ 1,057:
A B B A → B A » B A B A
</pre>
 
=={{header|Haskell}}==
<langsyntaxhighlight Haskelllang="haskell">import Data.List (mapAccumL, sort)
 
order
Line 898 ⟶ 1,091:
, ["A B", "B A"]
, ["A B B A", "B A"]
]</langsyntaxhighlight>
{{out}}
<pre>
Line 914 ⟶ 1,107:
{{Trans|JavaScript}}
 
<syntaxhighlight lang Haskell="haskell">import Control.ArrowMonad ((***)join)
import Data.Bifunctor (bimap)
import Prelude hiding (unlines, unwords, words, length)
import Data.List (delete, transpose)
import Data.Text hiding
( concat,
hiding (concat, zipWith, foldl, transpose, maximum)
foldl,
maximum,
transpose,
zipWith,
)
import Prelude hiding (length, unlines, unwords, words)
 
disjointOrder ::
:: Eq a =>
=> [a] -> [a] -> [a]
[a] ->
disjointOrder m n = concat $ zipWith (++) ms ns
[a]
disjointOrder m n = concat $ zipWith (<>) ms ns
where
ms = segments m n
ns = ((: []) <$> n) ++ [[]] -- asAs a list of lists, lengthened by 1
ns = ((: []) <$> n) <> [[]]
segments
segments :: Eq a
=>Eq [a] -=> [a] -> [[a]]
segments m n = _m ++ [_acca] ->
[a] ->
[[a]]
segments m n = _m <> [_acc]
where
(_m, _, _acc) = foldl split ([], n, []) m
split ::
:: Eq a =>
=> ([[a]], [a], [a]) -> a -> ([[a]], [a], [a])
a ->
([[a]], [a], [a])
split (ms, ns, acc) x
| x `elem` ns = (ms ++<> [acc], delete x ns, [])
| otherwise = (ms, ns, acc ++<> [x])
 
-- TEST ---------------------------------- TEST -------------------------
tests :: [(Text, Text)]
tests =
(packjoin ***bimap pack) <$>
<$> [ ("the cat sat on the mat", "mat cat"),
, ("the cat sat on the mat", "cat mat"),
, ("A B C A B C A B C", "C A C A"),
, ("A B C A B D A B E", "E A D A"),
, ("A B", "B"),
, ("A B", "B A"),
, ("A B B A", "B A")
]
 
table :: Text -> [[Text]] -> Text
table delim rows =
unlines $
intercalate delim <$>
<$> transpose
( ( \col ->
let width = (length $ maximum col)
in justifyLeft width ' ' <$> col) <$>
transpose rows )
<$> transpose rows
)
 
main :: IO ()
main =
(putStr . unpack) $
table (pack " -> ") $
unpack $
table (pack " ->( \(m, "n) $->
[ m,
(\(m, n) -> [m, n, unwords (disjointOrder (words m) (words n))]) <$> tests</lang>
n,
 
unwords (disjointOrder (words m) (words n))
]
)
<$> tests</syntaxhighlight>
{{Out}}
<pre>the cat sat on the mat -> mat cat -> the mat sat on the cat
Line 983 ⟶ 1,195:
Works in both languages. Assumes a single blank separates items:
 
<langsyntaxhighlight lang="unicon">procedure main(A)
every write(" -> ",odli("the cat sat on the mat","mat cat"))
every write(" -> ",odli("the cat sat on the mat","cat mat"))
Line 1,005 ⟶ 1,217:
}
return Mp
end</langsyntaxhighlight>
 
Output:
Line 1,024 ⟶ 1,236:
Implementation:
 
<langsyntaxhighlight Jlang="j">disjorder=:3 :0&.;:
:
clusters=. (</. i.@#) x
Line 1,032 ⟶ 1,244:
to=. ;need {.!._ each order{clusters
(from{x) to} x
)</langsyntaxhighlight>
 
Task examples:
 
<langsyntaxhighlight Jlang="j"> 'the cat sat on the mat' disjorder 'mat cat'
the mat sat on the cat
'the cat sat on the mat' disjorder 'cat mat'
Line 1,049 ⟶ 1,261:
B A
'A B B A' disjorder 'B A'
B A B A</langsyntaxhighlight>
 
=={{header|Java}}==
Doesn't handle the case when an item of N is not a member of M.
<langsyntaxhighlight lang="java">import java.util.Arrays;
import java.util.BitSet;
import org.apache.commons.lang3.ArrayUtils;
Line 1,102 ⟶ 1,314:
return m;
}
}</langsyntaxhighlight>
 
Output:
Line 1,121 ⟶ 1,333:
Accumulating a segmentation of M over a fold/reduce, and zipping with N:
 
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'"use strict'";
 
// ------------ ORDER DISJOINT LIST ITEMS ------------
// GENERIC FUNCTIONS
 
// disjointOrder :: [String] -> [String] -> [String]
const disjointOrder = ms =>
ns => zipWith(
a => b => [...a, b]
)(
segments(ms)(ns)
)(
ns.concat("")
)
.flat();
 
 
// segments :: [String] -> [String] -> [String]
const segments = ms =>
ns => {
const dct = ms.reduce((a, x) => {
const
wds = a.words,
found = wds.indexOf(x) !== -1;
 
return {
parts: [
...a.parts,
...(found ? [a.current] : [])
],
current: found ? [] : [...a.current, x],
words: found ? deleteFirst(x)(wds) : wds
};
}, {
words: ns,
parts: [],
current: []
});
 
return [...dct.parts, dct.current];
};
 
 
// ---------------------- TEST -----------------------
const main = () =>
transpose(transpose([{
M: "the cat sat on the mat",
N: "mat cat"
}, {
M: "the cat sat on the mat",
N: "cat mat"
}, {
M: "A B C A B C A B C",
N: "C A C A"
}, {
M: "A B C A B D A B E",
N: "E A D A"
}, {
M: "A B",
N: "B"
}, {
M: "A B",
N: "B A"
}, {
M: "A B B A",
N: "B A"
}].map(dct => [
dct.M, dct.N,
unwords(
disjointOrder(
words(dct.M)
)(
words(dct.N)
)
)
]))
.map(col => {
const
w = maximumBy(
comparing(x => x.length)
)(col).length;
 
return col.map(justifyLeft(w)(" "));
}))
.map(
([a, b, c]) => `${a} -> ${b} -> ${c}`
)
.join("\n");
 
 
// ---------------- GENERIC FUNCTIONS ----------------
 
// comparing :: (a -> b) -> (a -> a -> Ordering)
const comparing = f =>
// The ordering of f(x) and f(y) as a value
// drawn from {-1, 0, 1}, representing {LT, EQ, GT}.
x => y => {
const
a = f(x),
b = f(y);
 
return a < b ? -1 : (a > b ? 1 : 0);
};
 
// concatMap :: (a -> [b]) -> [a] -> [b]
const concatMap = (f, xs) => [].concat.apply([], xs.map(f));
 
// deleteFirst :: a -> [a] -> [a]
const deleteFirst = (x, xs) => {
const go = xs.length => 0Boolean(xs.length) ? (
x === xs[0] ? (
xs.slice(1)
) : [xs[0]].concat(deleteFirstgo(x, xs.slice(1)))
) : [];
 
// flatten :: Tree areturn -> [a]go;
};
const flatten = t => (t instanceof Array ? concatMap(flatten, t) : [t]);
 
 
// unwords :: [String] -> String
const unwords = xs => xs.join(' ');
// A space-separated string derived
// from a list of words.
xs.join(" ");
 
 
// words :: String -> [String]
const words = s => s.split(/\s+/);
// List of space-delimited sub-strings.
s.split(/\s+/u);
 
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
const zipWith = (f, xs, ys) => {
const ny = ys.length;
return (xs.length <= ny ? xs : xs.slice(0, ny))
.map((x, i) => f(x, ys[i]));
};
 
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
//------------------------------------------------------------------------
const zipWith = f =>
 
// A list constructed by zipping with a
// ORDER DISJOINT LIST ITEMS
// custom function, rather than with the
 
// default tuple constructor.
// disjointOrder :: [String] -> [String] -> [String]
const disjointOrder = (ms, ns)xs => ys => xs.map(
flatten (x, i) => f(x)(ys[i])
zipWith).slice(
0, Math.min(axs.length, b) => ays.concat(blength),
segments(ms, ns),
ns.concat('')
)
);
 
// ---------------- FORMATTING OUTPUT ----------------
// segments :: [String] -> [String] -> [String]
const segments = (ms, ns) => {
const dct = ms.reduce((a, x) => {
const wds = a.words,
blnFound = wds.indexOf(x) !== -1;
 
// justifyLeft :: Int -> Char -> String return-> {String
const justifyLeft = n =>
parts: a.parts.concat(blnFound ? [a.current] : []),
// The string s, followed by enough padding (with
current: blnFound ? [] : a.current.concat(x),
// the character c) to reach the string length n.
words: blnFound ? deleteFirst(x, wds) : wds,
c => s => };n > s.length ? (
} s.padEnd(n, {c)
) words: ns,s;
parts: [],
current: []
});
 
return dct.parts.concat([dct.current]);
};
 
// -----------------------------------------------------------------------
// FORMATTING TEST OUTPUT
 
// transpose :: [[a]] -> [[a]]
const transpose = xs =>
xs[0].map((_, iCol) => xs.map((row) => row[iCol]));
 
// maximumBy :: (a -> a -> Ordering) -> [a] -> a
const maximumBy = (f, xs) =>
xs.reduce((a, x) => a === undefinedBoolean(xs.length) ? x : (
fxs.slice(x, a1) > 0 ? x : a.reduce(
) (a, undefinedx); => 0 < f(x)(a) ? (
x
) : a,
xs[0]
)
) : undefined;
 
// 2 or more arguments
// curry :: Function -> Function
const curry = (f, ...args) => {
const intArgs = f.length,
go = xs =>
xs.length >= intArgs ? (
f.apply(null, xs)
) : function () {
return go(xs.concat([].slice.apply(arguments)));
};
return go([].slice.call(args, 1));
};
 
// justifyLefttranspose :: Int[[a]] -> Char -> Text -> Text[[a]]
const justifyLefttranspose = (n, cFiller, strText)rows =>
// The columns of a matrix of consistent row length,
n > strText.length ? (
// transposed into corresponding rows.
(strText + replicateS(n, cFiller))
Boolean(rows.length) ? rows[0].substrmap(0, n)
(_, i) :=> strText;rows.flatMap(
v => v[i]
)
) : [];
 
// replicateS :: Int -> String -> String
const replicateS = (n, s) => {
let v = s,
o = '';
if (n < 1) return o;
while (n > 1) {
if (n & 1) o = o.concat(v);
n >>= 1;
v = v.concat(v);
}
return o.concat(v);
};
 
// MAIN ---
// -----------------------------------------------------------------------
return main();
 
})();</syntaxhighlight>
// TEST
return transpose(transpose([{
M: 'the cat sat on the mat',
N: 'mat cat'
}, {
M: 'the cat sat on the mat',
N: 'cat mat'
}, {
M: 'A B C A B C A B C',
N: 'C A C A'
}, {
M: 'A B C A B D A B E',
N: 'E A D A'
}, {
M: 'A B',
N: 'B'
}, {
M: 'A B',
N: 'B A'
}, {
M: 'A B B A',
N: 'B A'
}].map(dct => [
dct.M, dct.N,
unwords(disjointOrder(words(dct.M), words(dct.N)))
]))
.map(col => {
const width = maximumBy((a, b) => a.length > b.length, col)
.length;
return col.map(curry(justifyLeft)(width, ' '));
}))
.map(
([a, b, c]) => a + ' -> ' + b + ' -> ' + c
)
.join('\n');
})();</lang>
 
{{Out}}
Line 1,285 ⟶ 1,525:
 
Usage: <tt>M | disjoint_order(N)</tt>
<langsyntaxhighlight lang="jq">def disjoint_order(N):
# The helper function, indices, ensures that successive occurrences
# of a particular value in N are matched by successive occurrences
Line 1,299 ⟶ 1,539:
. as $in
| (indices | sort) as $sorted
| reduce range(0; N|length) as $i ($in; .[$sorted[$i]] = N[$i] ) ;</langsyntaxhighlight>
 
'''Examples''':
Line 1,305 ⟶ 1,545:
(scrollable)
<div style="overflow:scroll; height:400px;">
<langsyntaxhighlight lang="jq">["the", "cat", "sat", "on", "the", "mat"] | indices( ["mat", "cat"] )
#=> ["the","mat","sat","on","the","cat"]</langsyntaxhighlight>
 
<langsyntaxhighlight lang="jq">["the", "cat", "sat", "on", "the", "mat"] | disjoint_order( ["cat", "mat"] )
#=> ["the","cat","sat","on","the","mat"]</langsyntaxhighlight>
 
<langsyntaxhighlight lang="jq">["A", "B", "C", "A", "B", "C", "A", "B", "C"] | disjoint_order( ["C", "A", "C", "A"] )
#=> ["C","B","A","C","B","A","A","B","C"]</langsyntaxhighlight>
 
<langsyntaxhighlight lang="jq">["A", "B", "C", "A", "B", "D", "A", "B", "E"] | disjoint_order( ["E", "A", "D", "A"] )
#=> ["E","B","C","A","B","D","A","B","A"]</langsyntaxhighlight>
 
<langsyntaxhighlight lang="jq">["A", "B"] | disjoint_order( ["B"] )
#=> ["A","B"]</langsyntaxhighlight>
 
<langsyntaxhighlight lang="jq">["A", "B"] | disjoint_order( ["B", "A"] )
#=> ["B","A"]</langsyntaxhighlight>
 
<langsyntaxhighlight lang="jq">["A", "B", "B", "A"] | disjoint_order( ["B", "A"] )
#=> ["B","A","B","A"]</langsyntaxhighlight>
 
<langsyntaxhighlight lang="jq">["X", "X", "Y"] | disjoint_order(["X"])
#=> [X, X, Y]</langsyntaxhighlight>
</div>
 
Line 1,334 ⟶ 1,574:
 
'''Function'''
<syntaxhighlight lang="julia">
<lang Julia>
function order_disjoint{T<:AbstractArray}(m::T, n::T)
rlen = length(n)
Line 1,353 ⟶ 1,593:
return p
end
</syntaxhighlight>
</lang>
'''Main'''
<syntaxhighlight lang="julia">
<lang Julia>
testm = {["the", "cat", "sat", "on", "the", "mat"],
["the", "cat", "sat", "on", "the", "mat"],
Line 1,380 ⟶ 1,620:
println(" (", m, ", ", n, ") => ", p)
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,394 ⟶ 1,634:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
const val NULL = "\u0000"
Line 1,432 ⟶ 1,672:
for (i in 0 until m.size)
println("${m[i].padEnd(22)} -> ${n[i].padEnd(7)} -> ${orderDisjointList(m[i], n[i])}")
}</langsyntaxhighlight>
 
{{out}}
Line 1,446 ⟶ 1,686:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">-- Split str on any space characters and return as a table
function split (str)
local t = {}
Line 1,487 ⟶ 1,727:
for _, example in pairs(testCases) do
print(table.concat(orderList(unpack(example)), " "))
end</langsyntaxhighlight>
{{out}}
<pre>the mat sat on the cat
Line 1,496 ⟶ 1,736:
B A
B A B A</pre>
=={{header|M2000 Interpreter}}==
===Simple===
<syntaxhighlight lang="m2000 interpreter">
Function Checkit$ {
Document Ret$
Flush
Data "the cat sat on the mat", "mat cat"
Data "the cat sat on the mat","cat mat"'
Data "A B C A B C A B C", "C A C A"
Data "A B C A B D A B E", "E A D A"
Data "A B", "B"
Data "A B", "B A"
Data "A B B A","B A"
Dim A$()
while not empty
read m$, n$
A$()=piece$(m$, " ")
Let w=piece$(n$, " ")
Let z=A$()
x=each(w)
while x
y=z#pos(array$(x))
if y>-1 then a$(y)=""
end while
p=0
x=each(w)
while x
while a$(p)<>"" : p++: end while
a$(p)=array$(x)
end while
ret$=m$+" | "+n$+" -> "+z#str$()+{
}
end while
=ret$
}
Report Checkit$()
Clipboard Checkit$()
</syntaxhighlight>
===Using a third array, sorted===
<syntaxhighlight lang="m2000 interpreter">
Function Checkit2$ {
Document Ret$
Flush
Data "the cat sat on the mat", "mat cat"
Data "the cat sat on the mat","cat mat"'
Data "A B C A B C A B C", "C A C A"
Data "A B C A B D A B E", "E A D A"
Data "A B", "B"
Data "A B", "B A"
Data "A B B A","B A"
Dim A$()
while not empty
read m$, n$
A$()=piece$(m$, " ")
Let w=piece$(n$, " ")
Let z=A$()
dim p(len(w))
x=each(w)
p=0
while x
y=z#pos(array$(x))
if y>-1 then a$(y)="": p(p)=y : p++
end while
u=p()#Sort()
x=each(u)
while x
a$(array(x))=w#val$(x^)
end while
ret$=m$+" | "+n$+" -> "+z#str$()+{
}
end while
=ret$
}
Report Checkit2$()
Clipboard Checkit2$()
</syntaxhighlight>
{{out}}
<pre>
the cat sat on the mat | mat cat -> the mat sat on the cat
the cat sat on the mat | cat mat -> the cat sat on the mat
A B C A B C A B C | C A C A -> C B A C B A A B C
A B C A B D A B E | E A D A -> E B C A B D A B A
A B | B -> A B
A B | B A -> B A
A B B A | B A -> B A B A
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">order[m_, n_] :=
ReplacePart[m,
MapThread[
Line 1,516 ⟶ 1,842:
Print[StringRiffle[order[{"A", "B"}, {"B"}]]];
Print[StringRiffle[order[{"A", "B"}, {"B", "A"}]]];
Print[StringRiffle[order[{"A", "B", "B", "A"}, {"B", "A"}]]];</langsyntaxhighlight>
{{out}}
<pre>the mat sat on the cat
Line 1,525 ⟶ 1,851:
B A
B A B A</pre>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import algorithm, strutils
 
 
proc orderDisjoint(m, n: string): string =
 
# Build the list of items.
var m = m.splitWhitespace()
let n = n.splitWhitespace()
 
# Find the indexes of items to replace.
var indexes: seq[int]
for item in n:
let idx = m.find(item)
if idx >= 0:
indexes.add idx
m[idx] = "" # Set to empty string for next searches.
indexes.sort()
 
# Do the replacements.
for i, idx in indexes:
m[idx] = n[i]
 
result = m.join(" ")
 
 
when isMainModule:
 
template process(a, b: string) =
echo a, " | ", b, " → ", orderDisjoint(a, b)
 
process("the cat sat on the mat", "mat cat")
process("the cat sat on the mat", "cat mat")
process("A B C A B C A B C", "C A C A")
process("A B C A B D A B E", "E A D A")
process("A B", "B")
process("A B", "B A")
process("A B B A", "B A")</syntaxhighlight>
 
{{out}}
<pre>the cat sat on the mat | mat cat → the mat sat on the cat
the cat sat on the mat | cat mat → the cat sat on the mat
A B C A B C A B C | C A C A → C B A C B A A B C
A B C A B D A B E | E A D A → E B C A B D A B A
A B | B → A B
A B | B A → B A
A B B A | B A → B A B A</pre>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub dsort {
my ($m, $n) = @_;
my %h;
Line 1,547 ⟶ 1,921:
my ($a, $b) = map([split], split '\|');
print "@$a | @$b -> @{[dsort($a, $b)]}\n";
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,559 ⟶ 1,933:
A B B A | B A -> B A B A
</pre>
 
=={{header|Perl 6}}==
{{works with|Rakudo|2018.03}}
<lang perl6>sub order-disjoint-list-items(\M, \N) {
my \bag = N.BagHash;
M.map: { bag{$_}-- ?? N.shift !! $_ }
}
 
# Testing:
 
for q:to/---/.comb(/ [\S+]+ % ' ' /).map({[.words]})
the cat sat on the mat mat cat
the cat sat on the mat cat mat
A B C A B C A B C C A C A
A B C A B D A B E E A D A
A B B
A B B A
A B B A B A
X X Y X
A X Y A
---
-> $m, $n { say "\n$m ==> $n\n", order-disjoint-list-items($m, $n) }</lang>
{{out}}
<pre>the cat sat on the mat ==> mat cat
the mat sat on the cat
 
the cat sat on the mat ==> cat mat
the cat sat on the mat
 
A B C A B C A B C ==> C A C A
C B A C B A A B C
 
A B C A B D A B E ==> E A D A
E B C A B D A B A
 
A B ==> B
A B
 
A B ==> B A
B A
 
A B B A ==> B A
B A B A
 
X X Y ==> X
X X Y
 
A X ==> Y A
Y X</pre>
 
=={{header|Phix}}==
{{Trans|Julia}}
Modified to support/skip missing elements
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function order_disjoint(sequence m, sequence n)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
integer rlen = length(n)
<span style="color: #008080;">function</span> <span style="color: #000000;">order_disjoint</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
sequence rdis = repeat(0,rlen)
<span style="color: #004080;">integer</span> <span style="color: #000000;">rlen</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
for i=1 to rlen do
<span style="color: #004080;">sequence</span> <span style="color: #000000;">rdis</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;">rlen</span><span style="color: #0000FF;">)</span>
object e = n[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: #000000;">rlen</span> <span style="color: #008080;">do</span>
integer j = find(e,m)
<span style="color: #004080;">object</span> <span style="color: #000000;">e</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
while j!=0 and find(j,rdis) do
<span style="color: #004080;">integer</span> <span style="color: #000000;">j</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">e</span><span style="color: #0000FF;">,</span><span style="color: #000000;">m</span><span style="color: #0000FF;">)</span>
j = find(e,m,j+1)
<span style="color: #008080;">while</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">and</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">j</span><span style="color: #0000FF;">,</span><span style="color: #000000;">rdis</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
end while
<span style="color: #000000;">j</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">e</span><span style="color: #0000FF;">,</span><span style="color: #000000;">m</span><span style="color: #0000FF;">,</span><span style="color: #000000;">j</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
rdis[i] = j
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
end for
<span style="color: #000000;">rdis</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: #000000;">j</span>
rdis = sort(rdis)
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
while rlen and rdis[1]=0 do
<span style="color: #000000;">rdis</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rdis</span><span style="color: #0000FF;">)</span>
rdis = rdis[2..$]
<span style="color: #008080;">while</span> <span style="color: #000000;">rlen</span> <span style="color: #008080;">and</span> <span style="color: #000000;">rdis</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">0</span> <span style="color: #008080;">do</span>
rlen -= 1
<span style="color: #000000;">rdis</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">rdis</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">..$]</span>
end while
<span style="color: #000000;">rlen</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">1</span>
for i=1 to rlen do
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
m[rdis[i]]=n[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: #000000;">rlen</span> <span style="color: #008080;">do</span>
end for
<span style="color: #000000;">m</span><span style="color: #0000FF;">[</span><span style="color: #000000;">rdis</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]]=</span><span style="color: #000000;">n</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
return join(m)
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end function
<span style="color: #008080;">return</span> <span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #000000;">m</span><span style="color: #0000FF;">)</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
sequence tests = {{"the cat sat on the mat","mat cat"},
{"the cat sat on the mat","cat mat"},
<span style="color: #004080;">sequence</span> <span style="color: #000000;">tests</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #008000;">"the cat sat on the mat"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"mat cat"</span><span style="color: #0000FF;">},</span>
{"A B C A B C A B C","C A C A"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"the cat sat on the mat"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"cat mat"</span><span style="color: #0000FF;">},</span>
{"A B C A B D A B E","E A D A"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"A B C A B C A B C"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"C A C A"</span><span style="color: #0000FF;">},</span>
{"A B","B"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"A B C A B D A B E"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"E A D A"</span><span style="color: #0000FF;">},</span>
{"A B","B A"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"A B"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"B"</span><span style="color: #0000FF;">},</span>
{"A B B A","B A"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"A B"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"B A"</span><span style="color: #0000FF;">},</span>
{"",""},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"A B B A"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"B A"</span><span style="color: #0000FF;">},</span>
{"A","A"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span><span style="color: #008000;">""</span><span style="color: #0000FF;">},</span>
{"A B",""},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"A"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"A"</span><span style="color: #0000FF;">},</span>
{"A B B A","A B"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"A B"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">""</span><span style="color: #0000FF;">},</span>
{"A B A B","A B"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"A B B A"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"A B"</span><span style="color: #0000FF;">},</span>
{"A B A B","B A B A"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"A B A B"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"A B"</span><span style="color: #0000FF;">},</span>
{"A B C C B A","A C A C"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"A B A B"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"B A B A"</span><span style="color: #0000FF;">},</span>
{"A B C C B A","C A C A"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"A B C C B A"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"A C A C"</span><span style="color: #0000FF;">},</span>
{"A X","Y A"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"A B C C B A"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"C A C A"</span><span style="color: #0000FF;">},</span>
{"A X","Y A X"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"A X"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Y A"</span><span style="color: #0000FF;">},</span>
{"A X","Y X A"}}
<span style="color: #0000FF;">{</span><span style="color: #008000;">"A X"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Y A X"</span><span style="color: #0000FF;">},</span>
 
<span style="color: #0000FF;">{</span><span style="color: #008000;">"A X"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Y X A"</span><span style="color: #0000FF;">}}</span>
for i=1 to length(tests) do
string {m,n} = tests[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;">tests</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
printf(1,"\"%s\",\"%s\" => \"%s\"\n",{m,n,order_disjoint(split(m),split(n))})
<span style="color: #004080;">string</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">m</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
end for </lang>
<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\",\"%s\" =&gt; \"%s\"\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">m</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">order_disjoint</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">split</span><span style="color: #0000FF;">(</span><span style="color: #000000;">m</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">split</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">))})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,680 ⟶ 2,008:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de orderDisjoint (M N)
(for S N
(and (memq S M) (set @ NIL)) )
(mapcar
'((S) (or S (pop 'N)))
M ) )</langsyntaxhighlight>
Test:
<langsyntaxhighlight PicoLisplang="picolisp">: (orderDisjoint '(the cat sat on the mat) '(mat cat))
-> (the mat sat on the cat)
 
Line 1,706 ⟶ 2,034:
 
: (orderDisjoint '(A B B A) '(B A))
-> (B A B A)</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function sublistsort($M, $N) {
$arr = $M.Split(' ')
Line 1,756 ⟶ 2,084:
sublistsort $M6 $N6
sublistsort $M7 $N7
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 1,771 ⟶ 2,099:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">from __future__ import print_function
 
def order_disjoint_list_items(data, items):
Line 1,807 ⟶ 2,135:
print('Data M: %-24r Order N: %-9r' % (tostring(data), tostring(items)), end=' ')
order_disjoint_list_items(data, items)
print("-> M' %r" % tostring(data))</langsyntaxhighlight>
 
{{out}}
Line 1,827 ⟶ 2,155:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket
(define disjorder
(match-lambda**
Line 1,863 ⟶ 2,191:
(report-disjorder '(A B A B) '(B A B A))
(report-disjorder '(A B C C B A) '(A C A C))
(report-disjorder '(A B C C B A) '(C A C A))</langsyntaxhighlight>
 
{{out}}
Line 1,881 ⟶ 2,209:
Data M: (A B C C B A) Order N: (A C A C) -> (A B C A B C)
Data M: (A B C C B A) Order N: (C A C A) -> (C B A C B A)</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2018.03}}
<syntaxhighlight lang="raku" line>sub order-disjoint-list-items(\M, \N) {
my \bag = N.BagHash;
M.map: { bag{$_}-- ?? N.shift !! $_ }
}
 
# Testing:
 
for q:to/---/.comb(/ [\S+]+ % ' ' /).map({[.words]})
the cat sat on the mat mat cat
the cat sat on the mat cat mat
A B C A B C A B C C A C A
A B C A B D A B E E A D A
A B B
A B B A
A B B A B A
X X Y X
A X Y A
---
-> $m, $n { say "\n$m ==> $n\n", order-disjoint-list-items($m, $n) }</syntaxhighlight>
{{out}}
<pre>the cat sat on the mat ==> mat cat
the mat sat on the cat
 
the cat sat on the mat ==> cat mat
the cat sat on the mat
 
A B C A B C A B C ==> C A C A
C B A C B A A B C
 
A B C A B D A B E ==> E A D A
E B C A B D A B A
 
A B ==> B
A B
 
A B ==> B A
B A
 
A B B A ==> B A
B A B A
 
X X Y ==> X
X X Y
 
A X ==> Y A
Y X</pre>
 
=={{header|REXX}}==
Note: &nbsp; items in &nbsp; <big>'''N'''</big> &nbsp; needn't be in &nbsp; <big>'''M'''</big>.
<langsyntaxhighlight lang="rexx">/*REXX program orders a disjoint list of M items with a list of N items. */
used = '0'x /*indicates that a word has been parsed*/
@. = /*placeholder indicates end─of─array, */
Line 1,929 ⟶ 2,307:
say @.j ' ────► ' space(mp) /*display new re─ordered text ──► term.*/
end /*j*/ /* [↑] end of processing for N words*/
/*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the internal default inputs:}}
<pre>
the cat sat on the mat | mat cat ───► the mat sat on the cat
Line 1,950 ⟶ 2,328:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def order_disjoint(m,n)
print "#{m} | #{n} -> "
m, n = m.split, n.split
Line 1,974 ⟶ 2,352:
['A B' , 'B A' ],
['A B B A' , 'B A' ]
].each {|m,n| order_disjoint(m,n)}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,985 ⟶ 2,363:
A B B A | B A -> B A B A
</pre>
===sprintf version===
<syntaxhighlight lang="ruby">ar = [
['the cat sat on the mat', 'mat cat'],
['the cat sat on the mat', 'cat mat'],
['A B C A B C A B C' , 'C A C A'],
['A B C A B D A B E' , 'E A D A'],
['A B' , 'B' ],
['A B' , 'B A' ],
['A B B A' , 'B A' ]
]
 
res = ar.map do |m,n|
mm = m.dup
nn = n.split
nn.each {|item| mm.sub!(item, "%s")} #sub! only subs the first match
mm % nn #"the %s sat on the %s" % [mat", "cat"] #does what you hope it does.
end
 
puts res
</syntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">def order[T](input: Seq[T], using: Seq[T], used: Seq[T] = Seq()): Seq[T] =
if (input.isEmpty || used.size >= using.size) input
else if (using diff used contains input.head)
using(used.size) +: order(input.tail, using, used :+ input.head)
else input.head +: order(input.tail, using, used)</langsyntaxhighlight>
'''Test:'''
<langsyntaxhighlight Scalalang="scala">val tests = List(
"the cat sat on the mat" -> "mat cat",
"the cat sat on the mat" -> "cat mat",
Line 2,006 ⟶ 2,404:
val done = order(input.split(" "), using.split(" "))
println(f"""Data M: $input%-24s Order N: $using%-9s -> Result M': ${done mkString " "}""")
}</langsyntaxhighlight>
{{out}}
<pre>Data M: the cat sat on the mat Order N: mat cat -> Result M': the mat sat on the cat
Line 2,018 ⟶ 2,416:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func dsort(m, n) {
var h = Hash()
n.each {|item| h{item} := 0 ++ }
Line 2,034 ⟶ 2,432:
EOT
var (a, b) = line.split('|').map{.words}...
say "#{a.to_sjoin(' ')} | #{b.to_sjoin(' ')} -> #{dsort(a.clone, b.clone).to_sjoin(' ')}"
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,049 ⟶ 2,447:
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">func disjointOrder<T: Hashable>(m: [T], n: [T]) -> [T] {
let replaceCounts = n.reduce(into: [T: Int](), { $0[$1, default: 0] += 1 })
let reduced = m.reduce(into: ([T](), n, replaceCounts), {cur, el in
Line 2,065 ⟶ 2,463:
print(disjointOrder(m: ["A", "B"], n: ["B"]))
print(disjointOrder(m: ["A", "B"], n: ["B", "A"]))
print(disjointOrder(m: ["A", "B", "B", "A"], n: ["B", "A"]))</langsyntaxhighlight>
 
{{out}}
Line 2,078 ⟶ 2,476:
=={{header|Tcl}}==
This is a simple version that assumes that ''all'' items in the order list are present in the list to be arranged:
<langsyntaxhighlight lang="tcl">proc orderDisjoint {theList theOrderList} {
foreach item $theOrderList {incr n($item)}
set is {}
Line 2,090 ⟶ 2,488:
foreach item $theOrderList i $is {lset theList $i $item}
return $theList
}</langsyntaxhighlight>
This is a more sophisticated version that handles items in the order list not being present in the list to be arranged:
<langsyntaxhighlight lang="tcl">proc orderDisjoint {theList theOrderList} {
foreach item $theOrderList {incr n($item)}
set is -
Line 2,109 ⟶ 2,507:
}
return $theList
}</langsyntaxhighlight>
Demonstration code (produces the same output from both implementations):
<langsyntaxhighlight lang="tcl">foreach {items order} {
"the cat sat on the mat" "mat cat"
"the cat sat on the mat" "cat mat"
Line 2,121 ⟶ 2,519:
} {
puts "'$items' with '$order' => '[orderDisjoint $items $order]'"
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,131 ⟶ 2,529:
'A B' with 'B A' => 'B A'
'A B B A' with 'B A' => 'B A B A'
</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./fmt" for Fmt
 
var NULL = "\0"
 
var orderDisjointList = Fn.new { |m, n|
var nList = n.split(" ")
// first replace the first occurrence of items of 'n' in 'm' with the NULL character
// which we can safely assume won't occur in 'm' naturally
for (item in nList) {
var ix = m.indexOf(item)
if (ix >= 0) {
var le = item.count
m = m[0...ix] + NULL + m[ix + le..-1]
}
}
// now successively replace the NULLs with items from nList
var mList = m.split(NULL)
var sb = ""
for (i in 0...nList.count) sb = sb + mList[i] + nList[i]
return sb + mList[-1]
}
 
var ma = [
"the cat sat on the mat",
"the cat sat on the mat",
"A B C A B C A B C",
"A B C A B D A B E",
"A B",
"A B",
"A B B A"
]
 
var na = [
"mat cat",
"cat mat",
"C A C A",
"E A D A",
"B",
"B A",
"B A"
]
 
for (i in 0...ma.count) {
Fmt.print("$-22s -> $-7s -> $s", ma[i], na[i], orderDisjointList.call(ma[i], na[i]))
}</syntaxhighlight>
 
{{out}}
<pre>
the cat sat on the mat -> mat cat -> the mat sat on the cat
the cat sat on the mat -> cat mat -> the cat sat on the mat
A B C A B C A B C -> C A C A -> C B A C B A A B C
A B C A B D A B E -> E A D A -> E B C A B D A B A
A B -> B -> A B
A B -> B A -> B A
A B B A -> B A -> B A B A
</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn disOrder(sm,sn){
M:=sm.split(" ");
N:=sn.split(" "); nc:=Walker.cycle(Utils.Helpers.listUnique(N));
Line 2,143 ⟶ 2,601:
else { nc.next(); w } // exhausted
}, String.fp(" ") )[1,*] // remove leading blank
}</langsyntaxhighlight>
A dictionary is used to hold count of the words in N, which is decremented as the words are used up.
A cycle of the words is consumed to track the replacement values.
It is assumed that there are no leading/trailing/consecutive spaces (easy to cover with a .filter()).
<langsyntaxhighlight lang="zkl">sets:=T(T("the cat sat on the mat","mat cat"),
T("the cat sat on the mat","cat mat"),
T("A B C A B C A B C","C A C A"),
Line 2,154 ⟶ 2,612:
foreach m,n in (sets){
m.println(" / ",n," --> ",disOrder(m,n));
}</langsyntaxhighlight>
{{out}}
<pre>
9,476

edits