Order disjoint list items: Difference between revisions

jq
(→‎{{header|Julia}}: A new entry for Julia)
(jq)
Line 383:
X X Y | X -> [X, X, Y]</pre>
 
=={{header|jq}}==
{{works with|jq|1.4}}
 
Usage: <tt>M | disjoint_order(N)</tt>
<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
# in the input on the assumption that null is not initially in the input.
def indices:
. as $in
| reduce range(0; N|length) as $i
# state: [ array, indices ]
( [$in, []];
(.[0] | index(N[$i])) as $ix | .[0][$ix] = null | .[1] += [$ix])
| .[1];
 
. as $in
| (indices | sort) as $sorted
| reduce range(0; N|length) as $i ($in; .[$sorted[$i]] = N[$i] ) ;</lang>
 
'''Examples''':
 
(scrollable)
<div style="overflow:scroll; height:400px;">
<lang jq>["the", "cat", "sat", "on", "the", "mat"] | indices( ["mat", "cat"] )
#=> ["the","mat","sat","on","the","cat"]</lang>
 
<lang jq>["the", "cat", "sat", "on", "the", "mat"] | disjoint_order( ["cat", "mat"] )
#=> ["the","cat","sat","on","the","mat"]</lang>
 
<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"]</lang>
 
<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"]</lang>
 
<lang jq>["A", "B"] | disjoint_order( ["B"] )
#=> ["A","B"]</lang>
 
<lang jq>["A", "B"] | disjoint_order( ["B", "A"] )
#=> ["B","A"]</lang>
 
<lang jq>["A", "B", "B", "A"] | disjoint_order( ["B", "A"] )
#=> ["B","A","B","A"]</lang>
 
<lang jq>["X", "X", "Y"] | disjoint_order(["X"])
#=> [X, X, Y]</lang>
</div>
=={{header|Julia}}==
<tt>order_disjoint</tt> works by finding the indices of <tt>n</tt> in <tt>m</tt> and replacing the elements in <tt>m</tt> with those in <tt>n</tt> according to the sorted indices. When <tt>n</tt> either contains elements not in <tt>m</tt> or more copies of an element than exist in <tt>m</tt>, the function throws a <tt>DomainError</tt>.
2,459

edits