Best shuffle: Difference between revisions

→‎{{header|AutoHotkey}}: Introduce an inner loop to search for a good swap. Also, stop stacking multiple red boxes from wiki templates! One red box, with a specific message, is enough.
m (→‎{{header|OCaml}}: more explicit function name)
(→‎{{header|AutoHotkey}}: Introduce an inner loop to search for a good swap. Also, stop stacking multiple red boxes from wiki templates! One red box, with a specific message, is enough.)
Line 56:
 
=={{header|AutoHotkey}}==
{{incorrectincomplete|AutoHotkey|SeemsFinds toa bebest ashuffle, randombut rathernever thancalculates bestscore shufflenor gives correct output.}}
<lang AutoHotkey>MsgBox % Shuffle("Abracadabraabracadabra")
{{lines_too_long|AutoHotkey}}
MsgBox % Shuffle("Seesawseesaw")
{{output?|AutoHotkey}}
<lang AutoHotkey>MsgBox % Shuffle("Abracadabra")
MsgBox % Shuffle("Seesaw")
MsgBox % Shuffle("Abracadabra")
MsgBox % Shuffle("elk")
MsgBox % Shuffle("grrrrrr")
Line 69 ⟶ 66:
Shuffle(String)
{
Cord := String
Length := StrLen(String)
CharType := A_IsUnicode ? "UShort" : "UChar"
 
Loop, Parse, String ;for For each old character in the stringString...
{
Char1 := SubStr(Cord, A_Index, 1)
Random, CharIndex, 1, Length
If (Char1 <> A_LoopField) ; If new character already differs,
NumPut(Asc(SubStr(String,CharIndex,1)),String,(A_Index - 1) << !!A_IsUnicode,CharType) ;set the character at the current position
Continue ; do nothing.
NumPut(Asc(A_LoopField),String,(CharIndex - 1) << !!A_IsUnicode,CharType) ;set the character at the random position
 
Index1 := A_Index
OldChar1 := A_LoopField
Random, Index2, 1, Length ; Starting at some random index,
Loop, %Length% ; for each index...
{
If (Index1 <> Index2) ; Swap requires two different indexes.
{
Char2 := SubStr(Cord, Index2, 1)
OldChar2 := SubStr(String, Index2, 1)
 
; If after the swap, the two new characters would differ from
; the two old characters, then do the swap.
If (Char1 <> OldChar2) and (Char2 <> OldChar1)
{
; Swap Char1 and Char2 inside Cord.
NumPut(Asc(Char1), Cord, (Index2 - 1) << !!A_IsUnicode, CharType)
NumPut(Asc(Char2), Cord, (Index1 - 1) << !!A_IsUnicode, CharType)
Break
}
}
Index2 += 1 ; Get next index.
If (Index2 > Length) ; If after last index,
Index2 := 1 ; use first index.
}
}
Return Cord
}</lang>
 
Anonymous user