# How to randomize letters in a word

According to some controversial story, the odrer of ltteres in a wrod deos not mttaer much for raednig, as lnog as the frist and lsat lteter macth with the orignial wrod.

So, for fun, what would be the shortest function to randomize letter order in a word while keeping the first and the last letter in place?

Here's my stab at it with JavaScript. All whitespace removed it's at 124 130 characters.

``````function r(w) {
var l=w.length-1;
return l<3?w:w[0]+w.slice(1,l).split("").sort(function(){return Math.random()-.5}).join("")+w[l];
}
``````

Shorter JavaScript always welcome.

• Edit: length check added. Function should not fail for short words.
-
Haskell, 4 characters: `r=id`. – Thomas Eding Aug 3 '11 at 20:01
@trinithis Huh? – Tomalak Aug 3 '11 at 20:11
@trinithis not sure what you talking about, but `id` is the identity function. I would still like to see Haskell solution to this problem in less than 100 characters. – Arlen Aug 4 '11 at 7:37
Should the specification be updated to require a uniform distribution of outcomes? This would disallow the 4 character Haskell solution. It would also disallow your example Javascript solution (shuffling by doing a sort like that is not uniform). – Thomas Eding Aug 4 '11 at 17:25
+1 for the first sentence: it actually took me a few seconds to realize it was spelled wrong XP – Nate Koppenhaver Aug 4 '11 at 18:33

# Mathematica 98 chars

Not the most economical code but fun to write.

`s` holds the input sentence (as a string).

``````Row[StringJoin @@@ (Characters@# /. {f_, m___, e_} :>
Flatten@{f, RandomSample@{m}, e} & /@ StringSplit@s), " "]
``````

For example, when `s = "This sentence is fairly easy to read.",

-

# J, 25

``````(]/:0,((2-~#)?1-~#),1-~#)
``````

Example:

``````      (]/:0,((2-~#)?1-~#),1-~#) 'order'
oedrr
(]/:0,((2-~#)?1-~#),1-~#) 'order'
oerdr
(]/:0,((2-~#)?1-~#),1-~#) 'order'
oderr
(]/:0,((2-~#)?1-~#),1-~#) 'order'
odrer
(]/:0,((2-~#)?1-~#),1-~#) 'order'
oerdr
(]/:0,((2-~#)?1-~#),1-~#) 'order'
oerdr
``````
-
 I can get down to 22 using the random shuffle verb on this page. – Gareth Aug 23 '12 at 12:02 Actually ignore my last comment, the top answer uses the method I would have used. – Gareth Aug 23 '12 at 13:00

## APL (Dyalog), 34 Charachters

Still trying to golf it a bit more, new to APL. Tips appreciated.

``````y←(⍴x←⍞)-2⋄x[1],x[1+⍳y][y?y],x[⍴x]
``````

Here is an attempt to explain it, I also simplified it a bit (no charachter improvement, though)

`⋄` is a statement separator, think of it as a new line.

That leaves us with 2 statements. `y←(⍴x←⍞)-2` and `x[1],x[1+⍳y][y?y],x[⍴x]`

APL works from right to left in statements, but follows parentesis still, so `(⍴x←⍞)` is executed first. `⍞` takes charachter input. `←` assigns that to `x` and `⍴` gives the length of `x`. Then the `-2` is executed, which subtracts 2 from the length of `x`. Finally, the length-2 is assigned to `y` and we move on to the next statement.

`x[⍴x]` takes the last character of `x`, think of it as `x[x.length]` (using the length as the index of the last character).

`,` is catenate.

So we concatenate the last character of `x` with `x[1+⍳y][y?y]` which takes the middle indices of `x` using `2+⍳y` and applies a randomization using `[y?y]`.

`⍳y` generates `1 2 3 ... y` and `1+` turns this into `2 3 4 ... y+1` which are the middle indices of x, for example, this returns `bcdef` from `abcdefg`.

`[y?y]` "deals" y values from 1 to y.

So, `x[1+⍳y][y?y]` grabs the middle of the word and randomizes it.

Finally, we concatenate the first charachter of `x` using `x[1],` to the rest of the string, and that is the output of the program.

Hopefully that was understandable...

-
 Oh dear God. (+1) -- Would you care to break it down for somebody who has no concept of APL? – Tomalak Aug 23 '12 at 5:43 Sure, give me a minute to update it – MrZander Aug 23 '12 at 5:49 No problem. If you can "golf it down" more do that first. – Tomalak Aug 23 '12 at 5:52 @Tomalak explained it as best as I could :) – MrZander Aug 23 '12 at 6:08 Brilliant, thank you. :) – Tomalak Aug 23 '12 at 6:15

C# w/Linq - 152 non-whitespace chars. It's terrible compared to other languages on char count, but elegant:

``````public string Shuf(string i)
{
return new String(i.Take(1)
.Concat(i.Skip(1).Take(i.Length-2).OrderBy(x=>Guid.NewGuid()))
.Concat(new[]{i.Last()})
.ToArray());
}
``````
-
 Why is the `toArray` necessary? – Tomalak Aug 3 '11 at 20:22 Because the product of these Linq methods is an `IEnumerable`, for which there isn't a built-in String constructor. It has to be converted to an explicit `char[]`. – KeithS Aug 3 '11 at 20:35 I see... Thanks! – Tomalak Aug 3 '11 at 20:38 there's no `Rand` class in C# - it's `Random`. Also, name the function `S` instead of `Shuf` to gain some chars. – w0lf May 15 '12 at 7:06 also, for a reason I haven't discovered yet, `x=>new Random().Next()` does not actually randomize the string. Try `_=>Guid.NewGuid()` - it's shorter and works – w0lf May 15 '12 at 7:11
show 1 more comment

I know this is an older puzzle, but I wanted to add my two cents from VBA: 128 177 151:

``````Sub o(s)
n=Left(s,1)
p=Len(s)-1
s=Right(s,p)
For i=1 To p-1
p=p-1
r=Int(p*Rnd()+1)
n=n & Mid(s,r,1)
s=Left(s,r-1) & Right(s,p-r+1)
Next
s=n & s
End Sub
``````

Example Usage:

``````a = "According"
o a ' a is assigned by the passing of the reference to the 'o' sub.
a = "to"
o a ' see above...
a = "some"
o a
a = "controversial"
o a
a = "story"
o a
``````

I was actually happily surprised to see it fare as well as it did against some of the other, more typical CG languages. After improving, this is still not the shortest, but I was happy to do it.

-
Does that keep the first and last letters in place and work with strings less than 3 characters long? – Tomalak Mar 19 '12 at 21:34
D'oh! First and last don't keep, but length is not a problem. I'll get back to you... – Gaffi Mar 19 '12 at 21:35
Fixed, @Tomalak. Thanks for catching that. – Gaffi Mar 20 '12 at 13:10

## MATLAB, 65 47 characters

``````r=@(s)s([3-min(end,2):1 randperm(end-2)+1 end])
``````

Works for strings of positive length, but fails on the empty string. Improved by using `end` as in jazzkingrt's solution.

This use of `end` can further improve jazzkingrt's solution by substituting `end` for `length(x)`. However, that solution doesn't handle strings of length one correctly. (I'm not allowed to comment, so I write here instead.)

-

## MATLAB (46 Characters)

``````f=@(x)[x(1) x(randperm(length(x)-2)+1) x(end)]
``````

Sample Usage:

``````>> f('elephant')

ans =

eplhnaet

>> f('imawesomebutyousuck')

ans =

iouesutuoeswbamycmk
``````

Works with words size two or greater.

-

## Q (42 Characters)

``````{(x[0]),((neg count 1_-1_x)?1_-1_x),-1#x}
``````

Sample Usage:

``````q){(x[0]),((neg count 1_-1_x)?1_-1_x),-1#x} "elephant"
"eeahlnpt"
q){(x[0]),((neg count 1_-1_x)?1_-1_x),-1#x} "ant"
"ant"
``````
-
 Doesn't work for single letter words, need to work on that. – sinedcm Mar 21 '12 at 17:52

# Q, 38 48

{((:)x),((-1(#:)a)?a:-1_1_x),last x}

Had to change it for words <=3 letters

``````{\$[3<(#)x;((*:)x),((-1*(#:)a)?a:-1_1_x),-1#x;x]}
``````
-
 You can get three less along the same vein: `{\$[3<(#)x;(1#x),((-1*(#)a)?a:-1_1_x),-1#x;x]}` – slackwear Mar 20 '12 at 21:03

JavaScript (132 characters):

``````function r(w){return w.substr(0,1)+w.substr(1,w.length-2).split('').sort(function(){return Math.random()-.5}).join('')+w.substr(-1)}
``````

You don't need to go through point by point. If provided a function which returns something where Math.round will return a random 0,1,-1, that will be sufficient (because of how sort works).

-
 That won't keep the first and last letters in place. – Tomalak Mar 18 '12 at 19:14 @Tomalak Now it will. – cwallenpoole Mar 20 '12 at 4:16 But it does not work anymore. – Tomalak Mar 20 '12 at 5:08

## R, 104 (126)

``````f=function(w){s=strsplit(w,"")[[1]];paste(c(s[1],sample(s[2:(length(s)-1)]),s[length(s)]),collapse="")}
``````

Usage:

``````for (i in 1:10) print(f("parola"))
[1] "plraoa"
[1] "prolaa"
[1] "praola"
[1] "parloa"
[1] "plaora"
[1] "palroa"
[1] "porlaa"
[1] "ploraa"
[1] "porlaa"
[1] "ploraa"
``````

the below function works with words with length less than 3:

``````f=function(w){s=strsplit(w,"")[[1]];ifelse(length(s)<3,w,paste(c(s[1],sample(s[2:(length(s)-1)]),s[length(s)]),collapse=""))}

f("pl")
[1] "pl"
f("a")
[1] "a"
``````
-
 Part of the task was not to move the first and last letters. – Tomalak Mar 18 '12 at 19:15 @Tomalak fixed! – Paolo Mar 19 '12 at 8:19 Does it work with words below the length of 3? – Tomalak Mar 19 '12 at 8:27 @Tomalak Now it should be ok! Thanks for the corrections! – Paolo Mar 19 '12 at 8:48

# Groovy, 75

``````r={w->w.size()<3?w:w[0]+w[1..-2].toList().sort{Math.random()}.join()+w[-1]}

assert r('a') == 'a'
assert r('it') == 'it'
assert r('cap') == 'cap'

for(x in 1..10) {
def w = r('Honorificabilitudinitatibus')
println w
assert w.size()==27 && w[0]=='H' && w[26]=='s'
}
``````
-

## Scala: 94

``````def r(w:String)=if(w.size<2)w else w(0)+util.Random.shuffle(w.tail.init.toSeq).mkString+w.last
``````

This is a riff on "user unknowns" answer. Since a String can be implicitly cast to a Seq of chars, we can leverage Seq methods to access the middle and end of the String.

-

# C#, 128

``````static string r(string w){var t="";while(w.Length>1){int n=new Random().Next(1,w.Length-1);t+=w[n];w=w.Remove(n,1);}return w+t;}
``````
-

## Perl - 76 chars

Pure Perl implementation that requires no external modules. Also correctly handles one-letter, two-letter word edge cases.

``````sub r{@a=split//,pop;@a>1?join'',@a[0,(sort{rand()<=>rand}1..\$#a-1),\$#a]:@a}
``````

### Usage

``````say r('stringified') for 1 .. 20;

# Example output

srfgiietnid
sgfnieiitrd
seiifgrtnid
siigrfeintd
sgiirntiefd
siigerniftd
sifiitgnred
sftrneiiigd
sfieirtngid
sfeitirgnid
sfiertnigid
sigteifrind
sgieftirnid
sieitfrnigd
stnigirfeid
sfietrniigd
siigfrenitd
stefrniiigd
setrfiniigd
sifgtiernid
``````

N.B. I'm not entirely convinced that the letter randomization still renders the word readable in the example above

-

# Python - 76 characters

``````import random as r
def f(w):m=list(w)[1:-1];r.shuffle(m);return w[0]+''.join(m)+w[-1]
``````
-
 George's userscript puts this at 85 characters. – dmckee♦ Sep 10 '11 at 0:14

The function trinithis proposed actually matches the specification:

``````s=id
``````

It returns the string unchanged, thus keeping the first and last characters in place and doing a permutation of all the other characters.

If someone is dissatisfied with the probability distribution of the permutations, here is a solution yielding a better distribution. It is obviously much more complex:

``````import Random
s(a:t@(b:c:d))=do{i<-randomRIO(0,length d);fmap(([a,t!!i]++).tail)\$s\$a:take i t++drop(i+1)t}
s l=return l
``````

An example of a program using this function:

``````main = getLine >>= s >>= putStrLn
``````
-
"dissatisfied with the probability distribution of the permutations" made me laugh. :) – Tomalak Aug 4 '11 at 16:44
@Rotsor how do you call that function? – Arlen Aug 4 '11 at 21:20
I've added an example to my post. – Rotsor Aug 4 '11 at 23:46
`fmap((a:t!!i:).tail)` – FUZxxl Aug 5 '11 at 22:00
@FUZxxl, no, sorry, I made the same mistake initially. Operator section does not work here because `:` is right-associative. I'd have to do `(a:).(t!!i:)`. – Rotsor Aug 5 '11 at 22:08

Python, 86 characters

``````import random as r
def f(w):t=list(w[1:-1]);r.shuffle(t);return w[0]+''.join(t)+w[-1]
``````

And here's an example of using it:

``````for x in ["ashley", "awesome", "apples"]:
print f(x)
``````

This is my first code golf exerise. After solving the problem I decided to look at the answers and it's no surprise mine answer isn't unique. This was fun though :o)

I did make one change after looking at the other responses and it was changing my import statement to use an alias. Great idea. ;o)

-
 And yet, your solution gets voted ahead of mine! :p – boothby Sep 12 '11 at 19:58 Fails on short strings; my python answer would be 75 chars if it failed on short strings (`from random import*\nf=lambda w:w[0]+''.join(sample(w[1:-1]),len(w)-2)+w[-1]`). – dr jimbob Mar 25 '12 at 16:39

## PowerShell, 93

``````filter x{if(\$_.length-lt3){\$_}else{\$_[0,-1]-join-join(\$_[1..(\$a=\$_.Length-2)]|random -c \$a)}}
``````

Look, double-jointed code!

-
 +1, that's very nice. – Tomalak Aug 5 '11 at 10:55 Way too long, sadly. – Joey Aug 5 '11 at 15:56 You can't beat Golfscript anyway. ;) It's way shorter than my JS solution; Powershell is pretty expressive. – Tomalak Aug 5 '11 at 16:47 This actually demonstrates plenty of things it doesn't handle well. Usually I aim for at least beating Python :-) – Joey Aug 6 '11 at 0:10

## Ruby 1.9, 43 characters

r=w[0]+[*w[1..-2].chars].shuffle.join+w[-1]

Does not yet work for 1 character length Strings (duplicates that character), and fails for empty String.

-

## python, 87797593 92 chars (handling strings of length 0,1)

``````from random import*
f=lambda w:w if 4>len(w)else w[0]+''.join(sample(w[1:-1],len(w)-2))+w[-1]
``````

EDIT: Originally thought it was supposed to split string words (which it did at 128 chars; now at 87 chars does requirement). Argh, my bad at reading comprehension.

EDIT 2: Change from def to lambda function from def to save 6 chars. Assuming sample is already imported to the namespace (`from random import sample`) could bring this down to ~60).

EDIT 3: "len(w[1:-1])" (12 chars) to "len(w)-2" (8 chars) per gnibbler's nice suggestion.

EDIT 4: JBernando saved one char (had considered `from random import *` and saw it was equivalent -- not realizing the space in `import *` is unnecessary).; user unknown added 19 chars `w if len(w)<4 else` to handle 0 and 1 char strings correctly.

EDIT 5: Saved another char per boothby's code golf trick. `if len(w)<4 else` to `if 4>len(w)else`.

-
However, the question only defined the input as a word, not a string of words. :) – Ben Richards Aug 3 '11 at 17:10
@sidran32: Thanks, my bad. I had just noticed (upon rereading) and then saw your comment; deleted -- edited -- and undeleted. – dr jimbob Aug 3 '11 at 17:19
Idea - you can trim 3 chars by doing this.... def f(w):j=w[1:-1]; return w[0]+''.join(r.sample(j,len(j)))+w[-1] – rmckenzie Aug 3 '11 at 20:12
@rmckenzie: Good idea. However, right before I saw your comment right after I trimmed it to lambda function (saving 6 chars), so I can no longer do your method of defining intermediate vars. – dr jimbob Aug 3 '11 at 20:20
`len(w)-2` instead of `len(w[1:-1])`? – gnibbler Aug 3 '11 at 23:29

# Python 3, 9493 91 characters

Using a different technique. Might also work in Python 2.

``````from random import*
s=lambda x:x[0]+''.join(sample(x[1:-1],len(x)-2))+x[-1]if x[0:-1]else x
``````

The `... if x[0:-1] else x` gives `x` if its length is 1 (otherwise it would be duplicated). The function thereby works for strings of length 0 and 1.

The `sample()` is from http://stackoverflow.com/questions/2668312/shuffle-string-in-python/2668366#2668366.

Since it's one expression, we can use a `lambda` (eliminating `return`, `def`, and a pair of parentheses).

Edit: `from random import*` to save 1 character, after the other Python submission.

-

# Erlang, 188172 132 chars

``````f([H|C=[_|_]])->T=[lists:last(C)],[H|s(C--T,T)];f(X)->X. s([],N)->N;s(D,N)->E=[lists:nth(random:uniform(length(D)),D)],s(D--E,E++N).
``````

I'm still learning Erlang so any tips on making this shorter are appreciated.

full code(string_shuffle module):

``````-module(string_shuffle).
-export([f/1]).

f([H|C=[_|_]])->
T=[lists:last(C)],
[H|s(C--T,T)];f(X)->X.
f(X)->X.

s([],N)->N;
s(D,N)->
E=[lists:nth(random:uniform(length(D)),D)],
s(D--E,E++N).
``````

## Edit

Took the shuffle part out as a seperate function which no longer requires the head and tail of the list to be passed around.

## Edit 2

Restructured to remove one of the `f`function patterns, changed the shuffle function to accept only two parameters, changed `lists:delete` for `--[]`, swapped a `lists:reverse` call for a `lists:last`

-

## Javascript, 202 characters

``````function r(s){var s=s.split(""),h=[-1],n=s.length-1,t,i;h[-1]=s[0];for(i=0;++i<n;){do{t=Math.random()}while(t in h);h[t]=s[i];h[i]=t;}h.sort();for(i=0;i<n;++i)h[i]=h[h[i]];return n?h.join("")+s[n]:s[0]}
``````

This solution has an unbiased distribution.

### Algorithm:

Split input string into an array `s`. Consider another array `h` that is doubly used as a dictionary. For each letter in `s` at index 0 < `i` < `s.length-1`, assign a unique random number to `h` at `i`. Also map the random number in the range [0, 1) in `h` to the letter. The first and last letters are handled specially. Before assigning the random numbers as described above, do the analogous thing for the first letter, but hard code the number as -1 (guaranteed to be less than the smallest random number generated, which can be 0). Ignore the last letter for now. Sort `h`. Map `h`'s random value to the corresponding letter. Join the array into a string and tack on the last letter. Special case for 1 character input, where we return the first character (we still crunch `h` because the logic is shorter that way).

-
 `for(i=1;i `for(i=0;++i
show 1 more comment

## Java, 194 charcters

``````String r(String s){String[]c=s.split("");if(c.length>2)java.util.Collections.shuffle(java.util.Arrays.asList(c).subList(2,c.length-1));return(""+java.util.Arrays.asList(c)).replaceAll("\\W","");}
``````

If you can assume `java.util.*` is imported, then you can shave off a fair amount of characters. Might be able to squeeze in a `List` variable to save a few more. If the class the `r` function is implemented in derives from `java.util.Arrays`, then even more characters can be saved.

-
 && isn't much shorter than `if`; try it without asList and without 'replaceAll'. `[, L, l, o, a]` and `[Ljava.lang.String;@addbf1` might be with you. – user unknown Aug 4 '11 at 4:25 `&&` requires both sides to be boolean expressions, and `shuffle` has return type `void`. As for storing the `asList` into `c`, the types are incompatable. I could store it in a `java.util.List`, but that is lengthy right there. – Thomas Eding Aug 4 '11 at 16:18 @trinithis Yeah I just tried with `&&` and came to the same conclusion. So I deleted my comment. – Tomalak Aug 4 '11 at 16:37 One can do `import static java.util.Arrays.*`, which is just another import instead of deriving from `java.util.Arrays`, which is kind of clumsy. – Rotsor Aug 5 '11 at 1:06

# C++11: - 68 66 chars

``````auto f=[&](){if(s.size()>2)random_shuffle(s.begin()+1,s.end()-1);};
``````

full program:

``````#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main(int argc, char* argv[]){

string s = "SomestrinG";
auto f=[&](){if(s.size()>2)random_shuffle(s.begin()+1,s.end()-1);};

f();
cout << s << endl;
return 0;
}
``````
-
 Is hard coding in the input string legal? – Thomas Eding Aug 4 '11 at 21:38 @trinithis I thought we were only concerned with the function itself. The program only shows how to use the function. Regardless, not hard coding the input would not make a difference in this case; just add `string s; cin >> s;` – Arlen Aug 4 '11 at 21:55

# D: 55 characters

``````void f(T)(T s){if(s.length>2)randomShuffle(s[1..\$-1]);};
``````

full program:

``````import std.stdio, std.random, std.conv;

void f(T)(T s){if(s.length>2)randomShuffle(s[1..\$-1]);};

void main(){

char[] s = to!(char[])("SomestrinG");

f(s);
writeln(s);
}
``````
-
I think the `else s` part is missing? – Tomalak Aug 5 '11 at 4:28
@Tomalak No, it's not, because there is no need for it. If the string is of length 2 or less, then we leave it alone. Also, `randomShuffle()` is in-place. – Arlen Aug 5 '11 at 5:07

# FSharp, ~207 177

Count includes whitespace since its significant for f#

``````let f w=
let r=System.Random()
let e = Seq.length w
(w|>Seq.mapi(fun i l->if i=0||i=e-1 then i,l else r.Next(1,e-1),l)|>Seq.sortBy fst|>Seq.map snd|>List.ofSeq).ToString()
``````

Run with:

``````printfn "%s" (f "apples")
``````
-

Python, 86 chars

Slnicig is safe, so no bnouds ckhnceig is neeacrssy. Wkros on all leghtns.

``````from random import*
def f(x):x=list(x);t=x[1:-1];shuffle(t);x[1:-1]=t;return''.join(x)
``````
-

``````import Random
import Data.List
r l=fmap(f l.g l)newStdGen
f l n=map snd\$head\$filter(\l->map fst l==n)\$permutations\$zip[0..]l
g l=take(n+2).(0:).(++[n+1]).take n.nub.randomRs(1,n)where n=length l-2
``````

Hacked this into existence while Rotsor was making his post. This will cover all possible permutations, and I believe it does so uniformly.

The function `r` is the function that the user uses.

The algorithm is fairly straightforward. It generates a random list of unique numbers from 1 to n-2. Then it tacks on 0 to the front and n-1 to the end of the list. The `take(n+2)` is there to handle the case where the input is a single character (or an empty string for that matter). Then it searches for the corresponding permutation and returns that.

The list is generated by generating an infinite list of random numbers from 1 to n-2. Then it picks out the first occurance of each number in that range.

-
 I've been puzzled why this program always produces the same result until I've realised that one needs to call `newStdGen` upon each independent call to `r`. – Rotsor Aug 4 '11 at 17:52 Run it outside of ghci. Make a main function, such as `main = getLine >>= r >>= putStrLn`. Then compile it and execute or use runhaskell. This will solve the problem. That or exit ghci every time and restart it after every call to `r`. – Thomas Eding Aug 4 '11 at 18:17 I was testing the distribution by doing `replicateM 500 \$ r "12345"`, which returned 500 identical results, so running it outside of ghci makes no difference. – Rotsor Aug 4 '11 at 18:34 Actually I think you should replace `getStdGen` with `newStdGen` in your solution, so it behaves in a way most (?) would expect. – Rotsor Aug 4 '11 at 18:40 I see. Fixed it. Thankfully, the character count is the same :D – Thomas Eding Aug 4 '11 at 19:11