Best shuffle: Difference between revisions
Content added Content deleted
m (→{{header|D}}) |
(→Tcl: Added implementation) |
||
Line 95: | Line 95: | ||
: (bestShuffle "a") |
: (bestShuffle "a") |
||
a a (1)</pre> |
a a (1)</pre> |
||
=={{header|Tcl}}== |
|||
{{tcllib|struct::list}} |
|||
<lang tcl>package require Tcl 8.5 |
|||
package require struct::list |
|||
# Simple metric function; assumes non-empty lists |
|||
proc count {l1 l2} { |
|||
foreach a $l1 b $l2 {incr total [string equal $a $b]} |
|||
return $total |
|||
} |
|||
# Find the best shuffling of the string |
|||
proc bestshuffle {str} { |
|||
set origin [split $str ""] |
|||
set best $origin |
|||
set score [llength $origin] |
|||
struct::list foreachperm p $origin { |
|||
if {$score > [set score [tcl::mathfunc::min $score [count $origin $p]]]} { |
|||
set best $p |
|||
} |
|||
} |
|||
set best [join $best ""] |
|||
return "$str,$best,($score)" |
|||
}</lang> |
|||
Demonstration: |
|||
<lang tcl>foreach sample {abracadabra seesaw elk grrrrrr up a} { |
|||
puts [bestshuffle $sample] |
|||
}</lang> |
|||
Output: |
|||
<pre> |
|||
abracadabra,baabacadrar,(0) |
|||
seesaw,assewe,(0) |
|||
elk,kel,(0) |
|||
grrrrrr,rgrrrrr,(5) |
|||
up,pu,(0) |
|||
a,a,(1) |
|||
</pre> |