Last active
September 14, 2017 05:45
-
-
Save 92hackers/5406daaae8824df73250ac8a14335247 to your computer and use it in GitHub Desktop.
Randomly align items between a range of numbers, no duplicates.
This file contains 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
const random = require('lodash/random') | |
const swap = (arr, a, b) => { | |
const c = arr[a] | |
arr[a] = arr[b] | |
arr[b] = c | |
} | |
/** | |
* Generate random number between a range, no duplicate items, | |
* algorithm referenced from: | |
* https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle | |
* @param {Number} lower lower number | |
* @param {Number} upper upper number | |
*/ | |
const rangeRandom = (lower, upper) => { | |
const scrach = [] | |
for (let i = lower; i <= upper; i++) { | |
scrach.push(i) | |
} | |
const size = scrach.length | |
for (let i = 0; i < size - 2; i++) { | |
const j = random(i, size - 1) | |
swap(scrach, i, j) | |
} | |
return scrach | |
} | |
console.log(rangeRandom(1, 12)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment