How to jumble a word

I’m trying to figure out how to jumble a given string. I’d assume you’d have to explode the string as follows:

set theWord to "jumble"
set theChars to (characters of theWord)
--returns: {"j", "u", "m", "b", "l", "e"}

but im stuck on how to randomly rearrange the letters. Could anyone help me with this?

This is an inelegant hack, but it works:

set theWord to "jumble"
set theChars to (characters of theWord)
set jumble_word to ""
repeat (count of items in theChars) times
	set replaced_letter to 0
	repeat until replaced_letter is 1
		set random_pick to (random number from 1 to count of items in theChars)
		if item random_pick of theChars is not "" then
			set jumble_word to jumble_word & item random_pick of theChars
			set item random_pick of theChars to ""
			set replaced_letter to 1
		end if
	end repeat
end repeat
display dialog jumble_word

I’d love to see some other examples though to help me improve my scripting.

Here’s my go at it:

set tWord to "jumble"
set jumbledWd to {}
set tChars to characters of tWord
repeat until (count jumbledWd) = (count tChars)
	set someChar to some item of tChars
	if someChar is not in jumbledWd then set jumbledWd's end to someChar
end repeat
jumbledWd as text --> "uljemb"

Hi Adam,

I like your version! It’s much cleaner.

However, I’m wondering, it doesn’t work with words that have the same letter more than once – jumble worked fine, but “radar” didn’t. It just seems to be stuck in a loop.

I remember seeing some shuffling code here a while ago, so I sought it out: Rand1point9 from Nigel Garvey. It seems to be a Fisher-Yates shuffle (aka Knuth shuffle), though I have not proven it is identical.

Note, however, I expect that that random basis of the some reference form is not good enough to be considered free of bias for even medium sized lists (like the 52 elements for a deck of cards).

If it’s just for words or short texts:

on jumbleText(txt)
	set chrs to txt's characters
	repeat with i from (count txt) to 2 by -1
		set r to (random number (i - 1)) + 1
		tell chrs to set {item i, item r} to {item r, item i}
	end repeat
	set astid to AppleScript's text item delimiters
	set AppleScript's text item delimiters to ""
	set jumbled to chrs as text
	set AppleScript's text item delimiters to astid
	return jumbled
end jumbleText


Thanks a lot guys! Some fantastic responses! Although I don’t have access to my computer at the moment im guessing you could do it with a shell script as well. I wonder which method would be the fastest?