I want to create a function that will generate a random number between 0 to 9 which is not in the array.
My code so far:
var myArr = [0,2,3,4];
console.log("Arr: " + myArr);
function newNum(){
console.log("test");
for (var i = 0; i < 10; i++) {
var n = myArr.includes(i)
// I want to return n if it's not present in the array
}
return n;
}
newNum()
I want to return only 1 number. How do I do this?
Thanks.
6 Answers 6
What about this?
const invalidValues = [0,2,3,4];
const getRandomInt = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
const getValidRandomInt = (min, max) => {
while(true) {
let temp = getRandomInt(min,max)
if(!invalidValues.includes(temp)) {
return temp;
}
}
}
console.log(getValidRandomInt(0,10))
1 Comment
var myArr = [0,2,3,4];
function newNum(){
for (var i = 0; i < 10; i++) {
if (!myArr.includes(i)) {
return i;
}
}
// return -1 if all numbers present in array..
return -1;
}
newNum();
1 Comment
Generate the number within the range by using Math.random() then loop and check whether the number generated is in the array or not, if not in the array return the number:
function getRandomArbitrary(min, max, arr) {
arr = new Set(arr);
while(true){
let val = Math.floor(Math.random() * (max - min) + min);
if(!arr.has(val)){ return val;}
}
}
console.log(getRandomArbitrary(0, 10, [4,3,2]));
Comments
Answer:
Use Math.random() * (max - min) + min to get a number within a range.
You can wrap it with Math.floor to round down to an integer, or alternatively use a bitwise OR ( | ) for small numbers.
function newNum(n_arr) {
let r = () => Math.random()*9 | 0,
n = r();
while(n_arr.includes(n)) {
n = r();
}
return n;
}
Example:
var myArr = [0,2,3,4];
function newNum(n_arr){
let r = () => Math.random()*9 | 0,
n = r();
while(n_arr.includes(n)) {
n = r();
}
return n;
}
let result = newNum(myArr);
console.log(result);
Comments
var myArr= [0,2,5];
function randomNumber(myArr, n){
n ? n : 1;
var num = Math.random() * n;
if(myArr.indexOf( num ) !==-1 ) {
return randomNumber( myArr, n );
}
return num;
}
randomNumber(myArr, 10);
Comments
If you want to return the first number missing in the array, from your code above, you could just check if every value of i exists in the array and the moment that value doesn't exist, return it.
var myArr = [0,2,3,4]; // original array
function newNum(){
for (var i = 0; i < 10; i++) { // loop through i from 0-9
if (myArr.indexOf(i) === -1){ // check for the first missing number
return i; //return it
}
}
}
newNum()
Comments
Explore related questions
See similar questions with these tags.
includesreturns boolean, so you need to do something likeif(!myArr.includes(i)) return ithat's all you need inforloop, if it gets outside, there is no possible num between 0-9