Best shuffle: Difference between revisions

jq
(jq)
Line 1,955:
up, pu, (0)
a, a, (1)</pre>
 
=={{header|jq}}==
{{works with|jq|1.5}}
The implementation in this section uses the deterministic "swap" algorithm found in other entries on this page.
 
<lang jq>def count(s): reduce s as $i (0;.+1);
 
def swap($i;$j):
.[$i] as $x | .[$i] = .[$j] | .[$j] = $x;
 
# Input: an array
# Output: a best shuffle
def bestShuffleArray:
. as $s
| reduce range(0; length) as $i (.;
. as $t
| (first(range(0; length)
| select( $i != . and
$t[$i] != $s[.] and
$s[$i] != $t[.] and
$t[$i] != $t[.])) as $j
| swap($i;$j))
// $t # fallback
);
 
# Award 1 for every spot which changed:
def score($base):
. as $in
| count( range(0;length)
| select($base[.] != $in[.]) );
 
# Input: a string
# Output: INPUT, BESTSHUFFLE, (NUMBER)
def bestShuffle:
. as $in
| explode
| . as $s
| bestShuffleArray
| "\($in), \(implode), (\( length - score($s) ))" ;</lang>
 
'''Examples:'''
<lang jq>"abracadabra", "seesaw", "elk", "grrrrrr", "up", "a", "antidisestablishmentarianism"
| bestShuffle</lang>
 
'''Invocation and Output'''
<pre>jq -nr -f best-shuffle.jq
abracadabra, baaracadabr, (0)
seesaw, esswea, (0)
elk, lke, (0)
grrrrrr, rgrrrrr, (5)
up, pu, (0)
a, a, (1)
antidisestablishmentarianism, maaaadisesitblishmenttrninis, (0)</pre>
 
=={{header|Kotlin}}==
2,487

edits