Skip to content

Instantly share code, notes, and snippets.

@iSWORD
Last active Oct 26, 2020
Embed
What would you like to do?
Shuffle & Unshuffle an Array in JavaScript & Swift
// 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))
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)
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)
@iSWORD
Copy link
Author

iSWORD commented Jul 18, 2017

@iSWORD
Copy link
Author

iSWORD commented Sep 5, 2017

Swift implementation

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