-
-
Save jochemstoel/5df40d84f2519527add0a2e1d96500f0 to your computer and use it in GitHub Desktop.
Shuffle & Unshuffle an Array in JavaScript & Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Functions | |
let shuffle = (inArr, seed, unshuffle = false) => { | |
let outArr = Array.from(inArr), | |
len = inArr.length | |
let swap = (a, b) => [outArr[a], outArr[b]] = [outArr[b], outArr[a]] | |
for ( | |
var i = unshuffle ? len - 1 : 0; | |
unshuffle && i >= 0 || !unshuffle && i < len; | |
i += unshuffle ? -1 : 1 | |
) | |
swap(seed[i % seed.length] % len, i) | |
return outArr; | |
}, unshuffle = (inArr, seed) => shuffle(inArr, seed, true) | |
// Usage | |
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f"], | |
seed = [] | |
for (var i = 0; i < array.length / 2; i++) seed.push(Math.ceil(Math.random() * 10)) | |
console.log("Seed: " + seed) | |
console.log("Original array: " + array) | |
let shuffled = shuffle(array, seed) | |
console.log("Shuffled array: " + shuffled) | |
console.log("Unshuffled array: " + unshuffle(shuffled, seed)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
shuffle=(a,s,u)=>{o=a.concat(),l=a.length,w=(a,b)=>[o[a],o[b]]=[o[b],o[a]];for(i=u?l-1:0;u&&i>=0||!u&&i<l;i+=u?-1:1)w(s[i%s.length]%l,i);return o},unshuffle=(a,s)=>shuffle(a,s,1) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func shuffle (_ items: [Any], _ seed: [Int], _ unshuffle: Bool = false) -> [Any] { | |
var shItems = items | |
let iters = unshuffle ? Array((0..<items.count).reversed()) : Array(0..<items.count) | |
for i in iters { | |
let k = seed[i % seed.count] % items.count | |
(shItems[k], shItems[i]) = (shItems[i], shItems[k]) | |
} | |
return shItems | |
} | |
func unshuffle (_ items: [Any], _ seed: [Int]) -> [Any] { return shuffle(items, seed, true) } | |
let items = ["hello", "world", "foo", "bar"] | |
let seed = [5, 1, 7, 4] | |
let shuffled = shuffle(items, seed) | |
let unshuffled = unshuffle(shuffled, seed) | |
print(items) | |
print(shuffled) | |
print(unshuffled) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment