Best shuffle: Difference between revisions

Content added Content deleted
(→‎Tcl: Added implementation)
m (→‎{{header|REXX}}: added REXX language.)
Line 95: Line 95:
: (bestShuffle "a")
: (bestShuffle "a")
a a (1)</pre>
a a (1)</pre>

=={{header|REXX}}==
<lang rexx>
/*REXX program to find best shuffle (of a character string). */

list='tree abracadabra seesaw elk grrrrrr up a'

/*find width of the longest word (prettify output).*/
L=0; do k=1 for words(list); L=max(L,length(word(list,k))); end; L=L+5

do j=1 for words(list) /*process the words in the list. */
$=word(list,j) /*the original word in the list. */
new=bestShuffle($) /*shufflized version of the word.*/
say 'original:' left($,L) 'new:' left(new,L) 'count:' countSame($,new)
end

exit


/*─────────────────────────────────────bestShuffle procedure────────────*/
bestShuffle: procedure; parse arg x 1 ox; Lx=length(x)
if Lx<3 then return reverse(x) /*fast track these puppies. */

do j=1 for Lx-1 /*first take care of replications*/
a=substr(x,j ,1)
b=substr(x,j+1,1)
if a\==b then iterate
_=verify(x,a); if _==0 then iterate /*switch 1st rep with some char. */
y=substr(x,_,1); x=overlay(a,x,_); x=overlay(y,x,j)
rx=reverse(x); _=verify(rx,a); if _==0 then iterate /*¬ enuf unique*/
y=substr(rx,_,1); _=lastpos(y,x) /*switch 2nd rep with later char.*/
x=overlay(a,x,_); x=overlay(y,x,j+1) /*OVERLAYs: a fast way to swap*/
end

do j=1 for Lx /*take care of same o'-same o's. */
a=substr(x, j,1)
b=substr(ox,j,1)
if a\==b then iterate
if j==Lx then x=left(x,j-2)a||substr(x,j-1,1) /*spec case of last*/
else x=left(x,j-1)substr(x,j+1,1)a || substr(x,j+2)
end

return x


/*─────────────────────────────────────countSame procedure──────────────*/
countSame: procedure; parse arg x,y; k=0
do j=1 for min(length(x),length(y))
k=k+(substr(x,j,1)==substr(y,j,1))
end
return k
</lang>
Output (with a freebie thrown in):
<pre style="height:20ex;overflow:scroll">
original: tree new: eert count: 0
original: abracadabra new: baaracadrab count: 0
original: seesaw new: eswase count: 0
original: elk new: lke count: 0
original: grrrrrr new: rrrrrrg count: 5
original: up new: pu count: 0
original: a new: a count: 1
</pre>


=={{header|Tcl}}==
=={{header|Tcl}}==