Skip to content

Instantly share code, notes, and snippets.

@srph
Created August 18, 2020 12:47
Show Gist options
  • Save srph/3be54edb2acc9aa60e45652881b3bd21 to your computer and use it in GitHub Desktop.
Save srph/3be54edb2acc9aa60e45652881b3bd21 to your computer and use it in GitHub Desktop.
JS: Get only a number twice
var integers = []
// Generate 10 integers
for (var i = 0; i < 10; i++) {
var number
do {
// Keep generating a random number if it's already in the array twice.
number = random(5)
} while(getCountInList(number) >= 2)
integers.push(number)
}
console.log(integers)
// Find how many of a given number is in the list
// Example: Find how many number 1 is in the list.
function getCountInList(number) {
return integers.filter(integer => integer === number).length
}
// Get random number from 0 to X.
function random(max) {
return Math.floor(Math.random() * Math.floor(max));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment