Skip to content

Instantly share code, notes, and snippets.

@bfontaine
Forked from 140bytes/LICENSE.txt
Created July 6, 2012 21:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bfontaine/3062993 to your computer and use it in GitHub Desktop.
Save bfontaine/3062993 to your computer and use it in GitHub Desktop.
140byt.es -- shuffleArray (92B)

Here is a function to make a shuffled copy of an array, written with only 92 bytes.

function(
a, // the given array
b, // copy of a (placeholder)
i, // index (placeholder)
t // temporary variable (placeholder)
){
for(i in b=a.slice()) // for each i in [0, b.length[
// a is reused as an index
a=0|i*m.random(), // Math.floor random( [0, i[ )
t=b[a],b[a]=b[i],b[i]=t; // swap b[a] and b[i]
return b // return shuffled array
}
function(a,b,i,t){for(i in b=a.slice())a=0|i*Math.random(),t=b[a],b[a]=b[i],b[i]=t;return b}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright © 2011 Baptiste Fontaine bfontaine.net
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "shuffleArray",
"description": "return a shuffled version of an array using Fisher‑Yates algorithm.",
"keywords": [
"array",
"shuffle",
"random",
]
}
<!DOCTYPE html>
<title>shuffleArray</title>
<div>Expected value: <b>a list of shuffled numbers from 1 to 10</b>.</div>
<div>Actual value: <b id="ret"></b></div>
<script>
var myFunction = function(a,b,i,t){for(i in b=a.slice())a=0|i*Math.random(),t=b[a],b[a]=b[i],b[i]=t;return b}
document.getElementById( "ret" ).innerHTML = myFunction([1,2,3,4,5,6,7,8,9,10]);
</script>
@maettig
Copy link

maettig commented Jul 9, 2012

You don't need m since you are using Math only once. And you can write for(i in b=a.slice()). Also check this in-place shuffle using Fisher–Yates.

@bfontaine
Copy link
Author

Thanks, in my first version I was using Math twice, so I created m and forgot to remove it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment