Created
August 18, 2020 12:47
-
-
Save srph/3be54edb2acc9aa60e45652881b3bd21 to your computer and use it in GitHub Desktop.
JS: Get only a number twice
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
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