# 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+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
• Yes. It returns the exact same thing as the input. On another note, what do we do about punctuation? Do we only operate on words consisting only of letters? – Thomas Eding Aug 3 '11 at 20:28
• @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

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 l=randomRIO(1,length l-2)>>=g.($l).splitAt g(a:b,c:d)=fmap(a:).s$c:b++d
g(a,b)=return$a++b  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 • The first solution should be removed as it does not fit the challenge criteria. The challenge description says "randomize". According to the meta, random cannot always have the same output. – mbomb007 Dec 6 '16 at 15:03 ## J, 2624 23 characters r=:{.,({~?~@#)&}.&}:,{:  • According to common code golf rules, you don't have to bind the phrase to a name. – FUZxxl Feb 14 '15 at 22:51 • #?# is one char shorter than?~@# – randomra Feb 15 '15 at 22:11 ### Ruby, 44 characters r=->w{w[h=1..-2]=[*w[h].chars].shuffle*"";w}  Works also for short words, i.e. words with one, two or three characters are returned unaltered. Edit: Using the array-splat idea of Ventero saves another char. • That's actually 44 characters. I eventually came up with the exact same answer by fine tuning my own - now I feel like a copy-cat after reading yours. – Aleksi Yrttiaho Aug 4 '11 at 8:24 • @user2316 Of course you are right. Thank you. – Howard Aug 4 '11 at 9:50 ## Ruby 1.9, 46 characters r=->w{w+[*w[1..-2].chars].shuffle*""+w[-1]}  • +1 This use of array-splat saved me also one char. Great idea. – Howard Aug 3 '11 at 16:46 • I don't know ruby - it fails on my ruby1.8, so I guess I need a never version? Does it work with input like 'I'? – user unknown Aug 4 '11 at 4:00 • @user: It says "Ruby 1.9" right there. ;) -- Ventero - One of the sensible requirements I forgot to mention is that it should not fail for word lengths 0 and 1. Sorry. – Tomalak Aug 4 '11 at 6:34 ## Golfscript As a "function" (named codeblock): 20 characters {1/(\)\{;9rand}$\}:r


When operating on the topmost element on the stack: 16 characters

1/(\)\{;9rand}$\  • That's not a very good shuffle, but probably OK for this task. (That is, it'll "look random enough".) Still, at the cost of two more chars, you could get a much better shuffle by replacing 9 with 9.?. – Ilmari Karonen May 14 '12 at 20:55 • This fails for single-letter words, and I also don't think that the function should be allowed to return string, array of strings, string (as opposed to a single string). – Martin Ender Mar 27 '15 at 16:50 ## C++, 79 characters (with range check) string f(string s){if(s.size()>3)random_shuffle(&s,&s.end()[-1]);return s;}  ## C++, 81 65 characters (without range check) string f(string s){random_shuffle(&s,&s.end()[-1]);return s;}  Using pass by reference instead of returning the result shaves off another 10 characters from either solution. Full program, reading a string of words and shuffling converting them: #include <iostream> #include <algorithm> #include <cstdio> #include <ctime> #include <string> using namespace std; string f(string s){if(s.size()>3)random_shuffle(&s,&s.end()[-1]);return s;} int main() { std::srand(std::time(0)); std::string s; while(std::cin >> s) std::cout << f(s) << " "; std::cout << std::endl; }  Morale: don’t build what’s already there. Oh, and overflow checks are for wusses. • Nice, std::random_shuffle, that's a new one to me. btw I think you forgot #include<string> in your full code. – Scott Logan Aug 3 '11 at 15:48 • Something like that is what I had in mind originally. Unfortunately there is no built-in for shuffling a string in-place in JS. – Tomalak Aug 3 '11 at 15:59 • Fails for very short strings. – user unknown Aug 4 '11 at 4:02 • That's true, you're missing a length check (I did, as well). BTW @Arlen's answer is also worth a look. – Tomalak Aug 4 '11 at 6:43 • @userunknown That’s what I meant by “overflow checks are for wusses”. But to be fair, so do almost all other solutions. – Konrad Rudolph Aug 4 '11 at 7:02 Python, 86 characters import random as r def f(w):t=list(w[1:-1]);r.shuffle(t);return w+''.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+''.join(sample(w[1:-1]),len(w)-2)+w[-1]). – dr jimbob Mar 25 '12 at 16:39 # C (K&R) - 88 86 87 chars r(char*s){int m,j,l=strlen(s)-2,i=l;while(--i>0){j=rand()%l+1;m=s[j];s[j]=s;s=m;}}  There's no build-in swap or shuffle function in C, so I had to do it manually :( Sample Program with Ungolfed r(): #include <stdio.h> #include <string.h> #include <time.h> #include <stdlib.h> // ----------------------------------------------------------------------- r( char *s ) { int m, j, l=strlen(s)-2, i=l; while (--i>0) { j = rand() % l + 1; m = s[j]; s[j] = s; s = m; } } // ----------------------------------------------------------------------- int main() { char s[] = "anticipated"; srand( time(0) ); r( s ); puts( s ); return 0; }  EDIT: fixed the bug when s consists of less than 3 chars (thanks to user-uknown for noticing it! ) • In glibc, there is (was?) a non-standard library function strfry. – Mechanical snail Aug 3 '11 at 23:12 • funny experience, if I feed it with char s[] = "na"; // not anticipated – user unknown Aug 4 '11 at 3:30 • @user uknown: I just edited the code and fixed it, thanks for noticing the bug! (I just added >0 in the condition of the while loop, "costing me" two more, but needed, chars :) ) – Harry K. Aug 4 '11 at 7:53 • @Mechanical snail: I think strfy is still in glibc. – Harry K. Aug 4 '11 at 7:56 ## python, 87797593 92 chars (handling strings of length 0,1) from random import* f=lambda w:w if 4>len(w)else w+''.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+''.join(r.sample(j,len(j)))+w[-1] – arrdem 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 # C++, 111 97 chars std::string f(std::string s){for(int i=s.size()-1;i>1;std::swap(s[rand()%i+1],s[--i]));return s;}  Here is a full program for those who wish to test it: #include<string> #include<iostream> std::string f(std::string s){for(int i=s.size()-1;i>1;std::swap(s[rand()%i+1],s[--i]));return s;} int main(){ for(int i = 0; i<100; ++i) std::cout<<f("letters")<<std::endl; }  # Edit Realised there is no need to random both swap indexes, saved a variable and a few more characters. • Excellent. Most solutions fail on very small input. Yours not. – user unknown Aug 4 '11 at 4:06 # php (68 characters) $r=preg_replace('/^(\w)(\w+)(\w)$/e','$1.str_shuffle($2).$3',trim($w));  # shorter (60 characters) $r=preg_replace('/(.)(.+)(.)/e','$1.str_shuffle($2).$3',$w);

• +1 Very nice. :) You could drop the trim(), actually, and in the regex you can remove the anchors and use . instead of \w. – Tomalak Aug 3 '11 at 20:20
• @Tomalak Suggested I try rewriting this solution in Perl. Including his suggestions, I got this: use List::Util 'shuffle';sub r{$_=~m/(.)(.+)(.)/;$1.join('',shuffle split//,$2).$3;} That's 87 characters. Without the use line, it's 62 characters. – Ben Richards Aug 3 '11 at 21:52
• Can you provide a demo of this working? Because I can't... – Steve Robbins Sep 23 '11 at 22:33

## Perl - 96 (or 71) characters 84 (or 59) characters

This is what I came up with in Perl. Went through a few different ways to do it but this seemed shortest from what I can think of so far, at 97 characters.

use List::Util 'shuffle';sub r{($b,@w)=split//,$_;$e=pop(@w);return$b.join('',shuffle@w).$e;}  Though, if you cut out the 'use' line (which I guess is valid, since others excluded #include lines in their C programs) I can cut it down further to 71 characters: sub r{($b,@w)=split//,$_;$e=pop(@w);return$b.join('',shuffle@w).$e;}


EDIT It was suggested that I try doing this implementing @tobius' method. This way I got it down to 84 characters, or by removing the use line, 59 characters:

use List::Util 'shuffle';sub r{$_=~m/(.)(.+)(.)/;$1.join'',shuffle split//,$2.$3}

• shortened your Version down to 87: use List::Util 'shuffle';sub r{($b,@w)=split//,$_;$e=pop@w;join'',$b,(shuffle@w),$e} – mbx Aug 3 '11 at 18:52 • @sidran32 Can you implement Perl a variant of @tobius' answer, just for comparison? – Tomalak Aug 3 '11 at 20:19 • @Tomalak Sure, I'll try it out. – Ben Richards Aug 3 '11 at 21:39 • shortened your regex version down by 3 characters: use List::Util 'shuffle';sub r{$_=~m/(.)(.+)(.)/;$1.join'',shuffle split//,$2.$3} – mbx Aug 4 '11 at 9:26 • Nice. I'm too used to using a heaping helping of parenthesis for clarity. Bad habit when golfing. :P – Ben Richards Aug 4 '11 at 18:11 ## Ruby, 77 75 characters def r(s);f=s.size-2;1.upto(f){|i|x=rand(f)+1;t=s[i];s[i]=s[x];s[x]=t};s;end  My Scala solution in a slightly less verbose language. I'm not a Ruby expert by any means, so there's probably room for improvement. • Wow. Works with 'I', as your scala solution. – user unknown Aug 4 '11 at 3:35 Ruby 1.9, 77 48 46 44 chars r=->w{w[h=1..-2]=[*w[h].chars].shuffle*"";w}  Disclaimer: I tuned this based on the highest ranked answer - noticed the exact same answer later on. You can check the history that I have kept true to my original idea but changed from ruby 1.8 to ruby 1.9 for short lambdas and shuffle. If empty words are allowed then 56 54 chars r=->w{w.empty?||w[h=1..-2]=[*w[h].chars].shuffle*"";w}  • Nobody expects the spanish 'I'. – user unknown Aug 4 '11 at 4:07 • Attempted to handle cases with 0 or 1 letters as well – Aleksi Yrttiaho Aug 4 '11 at 8:14 # Python 3, 9493 91 characters Using a different technique. Might also work in Python 2. from random import* s=lambda x:x+''.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 https://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. • I know I am so so so late here, but can x[0:-1] become x[:-1]? – Zacharý Jul 20 '17 at 13:22 ## JavaScript - 118 122 chars Shorter JavaScript - 118 characters with no white space. Uses approximately the same algorithm as the OP, but with less chaining. I tried a lot of recursion, and I tried some iteration, but they all tend to get bogged down in some way or another. function s(w) { w = w.split(''); var a = w.shift(), z = w.pop(); return z?a + (w.sort(function() { return Math.random() - .5}).join('')) + z:a; }  • Does not pass the 'I'-test. – user unknown Aug 4 '11 at 3:31 • @Ryan Using return z?a+...+z:w; as an implicit length check would be in order. The silent assumption was that the function would receive only "valid" words. – Tomalak Aug 4 '11 at 7:06 • Good point, except that w has been modified, so I have to use a in the else of the ternary. Edited, and up to 122 chars. – Ryan Kinal Aug 4 '11 at 11:57 • @Ryan: I believe a would be wrong for two-letter input. :-\ Damn next time I will line out requirements more carefully. – Tomalak Aug 4 '11 at 16:40 • I don't think it would, actually. z will only be undefined if the word is one letter (or less). – Ryan Kinal Aug 4 '11 at 17:02 ## D, 62 chars import std.random;void s(char[] s){randomShuffle(s[1..$-1]);}


okay I cheated with a normal char array instead of a real string (which is immutable char[] so no in-place shuffling)

edit with a length check it requires 14 more

import std.random;void s(char[] s){if(s.length>1)randomShuffle(s[1..$-1]);}  • And it returns what for an input like 'I'? – user unknown Aug 4 '11 at 3:23 • It would be fairer (= better comparable) to return the result. – Konrad Rudolph Aug 4 '11 at 10:46 • @user a range error. @ konrad that would require return s; and char[] return type 11 more chars – ratchet freak Aug 4 '11 at 13:09 • @ratchet Could you post the entire program, please? BTW, I don't understand why you are counting import std.random;, and not just the function. – Arlen Aug 4 '11 at 20:11 • I'm guessing you could save 1 byte by using omitting the space in char[] s (to make it char[]s), but I haven't used D in years. – Tim Čas Dec 12 '16 at 21:42 ## php 5.3 (60 chars) $r=!$w?:$w.str_shuffle(substr($w,1,-1)).substr($w,-1);


Improved to 56 chars and no longer requires version 5.3:

$r=substr_replace($w,str_shuffle(substr($w,1,-1)),1,-1);  • +1 nice alternative to the other PHP answer. Not shorter, but no regex is a plus. – Tomalak Aug 4 '11 at 17:30 • Updated with a shorter solution that doesn't require version 5.3 – migimaru Aug 4 '11 at 18:12 • The old version is not correct: returns true for short strings. – Titus Sep 12 '16 at 19:15 Perl - 111 characters (without using any library function) sub r{($f,@w)=split//,shift;$l=pop@w;while(@w){if(rand(9)>1){push@w,shift@w}else{push@t,pop@w}}join'',$f,@t,$l}  $in="randomizethis";
$out = &r($in);
print "\nout: $out"; sub r{($f,@w)=split//,shift;$l=pop@w;while(@w){if(rand(9)>1){push@w,shift@w}else{push@t,pop@w}}join'',$f,@t,$l}  # Python It's 90 89 112 characters of python! ## Edit 1: as a function this time! (thanks gnibbler) ## Edit 2: now handles short words (thanks user unknown) import random as r def q(s): a=list(s) b=a[1:-1] r.shuffle(b) if len(s)<4: return s return a+''.join(b)+a[-1]  • even less if you follow the spec and write a function :) – gnibbler Aug 3 '11 at 23:08 • ah, pity shuffle doesn't work on strings – gnibbler Aug 3 '11 at 23:28 • The random module is like me at a nightclub... we both just sort of shuffle in place! :) – Andbdrew Aug 3 '11 at 23:38 • Doesn't work for input like 'I'; return 'II'. – user unknown Aug 4 '11 at 3:24 • thanks! it now handles short words, but is slightly longer :) – Andbdrew Aug 4 '11 at 12:55 ## Scala, 135 139142156 characters def r(s:String)={var(x,o,t,f)=(0,s.toArray,' ',s.size-2) for(i<-1 to f){t=o(i) x=util.Random.nextInt(f)+1 o(i)=o(x) o(x)=t} o.mkString}  -7: removed ':String' (return type can be inferred) -7: removed 'return ' (last expression is the return value) -3: factored s.size-2 out -4: toCharArray -> toArray • Works with 'I' and 'Verwürfel' without fancy Python characters. :) However, my solution using 'shuffle' is a bit shorter. – user unknown Aug 4 '11 at 3:49 • @user unknown Thanks for the edits :-) – Gareth Aug 4 '11 at 17:27 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)  # 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 ## Ruby 1.9, 43 characters r=w+[*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 - 76 characters import random as r def f(w):m=list(w)[1:-1];r.shuffle(m);return w+''.join(m)+w[-1]  ## R, 104 (126) f=function(w){s=strsplit(w,"")[];paste(c(s,sample(s[2:(length(s)-1)]),s[length(s)]),collapse="")}  Usage: for (i in 1:10) print(f("parola"))  "plraoa"  "prolaa"  "praola"  "parloa"  "plaora"  "palroa"  "porlaa"  "ploraa"  "porlaa"  "ploraa"  the below function works with words with length less than 3: f=function(w){s=strsplit(w,"")[];ifelse(length(s)<3,w,paste(c(s,sample(s[2:(length(s)-1)]),s[length(s)]),collapse=""))} f("pl")  "pl" f("a")  "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 ## Python, 102 characters def f(x):t=list(x)[1:-1];k='';exec'k+=t.pop(id(7)%len(t));'*len(t);return[x,x+k+x[-1]][len(x)>1]  No imports! Works for words 1 character and above. This is my first golf entry and I was inspired by BlueEyedBeast's entry from Shortest code to produce non-deterministic output for the idea of using id(Object). Explanation: It makes a list of letters from the input excluding the first and last, and repeatedly pops from this list and appends to a new one until empty. The index it pops from is id(7) % len(list we're popping from). Since id(7) is the memory address of the object 7, it is essentially random. So now we have a list of randomly scrambled letters from the center of the original input. All we do now is append the first and last letters of the original output accordingly and we got the output we want: (first letter)+(scrambled middle)+(last letter). # R, 9592 91 characters f=function(w,a=el(strsplit(w,'')),b=length(a))cat(a,sample(a[c(1,b)],b-2),a[b],sep="")  Makes use of R's lazy evaluation to compute a and b as function parameters, saving space with re-use later on. Also unlike other R answer this works for all words >1 char long. Example below: > f("hippopotamus") hpuoopaitmps > f("dog") dog > f("az") az  Edit: Replaced unlist() with [[]] Replaced [] with el() # 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 • Wow, D being competitive. I think randomShuffle(s[1..$-1]) can be s[1..\$-1].randomShuffle IIRC (unless that's in a D version older than this post) – Zacharý Jul 20 '17 at 13:24

# 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 ffunction patterns, changed the shuffle function to accept only two parameters, changed lists:delete for --[], swapped a lists:reverse call for a lists:last