Skip to content

Instantly share code, notes, and snippets.

@iSWORD
Last active February 15, 2023 20:11
Show Gist options
  • Save iSWORD/13f715370e56703f6c973b6dd706bbbd to your computer and use it in GitHub Desktop.
Save iSWORD/13f715370e56703f6c973b6dd706bbbd to your computer and use it in GitHub Desktop.
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