Create random number different from the numbers inside an array [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have an array for example [2,8,5,6], and I want to generate a random number different from the numbers that are inside the array, and that this number is not greater than 100.
Many thanks friends

Using Set to avoid collisions
arr = [2, 8, 5, 6]
getRandom = (exclude, min = 0, max = 100) => {
let rand = Math.random() * 100 | 0
while (exclude.has(rand)) rand = min + Math.random() * max | 0
exclude.add(rand)
return rand
}
arr = new Set(arr)
console.log(getRandom(arr))
console.log(getRandom(arr))
console.log(getRandom(arr))
console.log(getRandom(arr))
console.log([...arr])

You could generate an array of the numbers up to the max that you want, then remove the ones that you don't want, and the pick a random element from the resulting array, for example:
const max = 100
const exclude = [2,8,5,6]
const randomIdx = Math.floor(Math.random() * (max + 1 - exclude.length))
const randomNum = [...Array(max + 1).keys()].filter(k => !exclude.includes(k))[randomIdx]
console.log(randomNum)

Related

How can I check if a number is already in an array? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
This is the array:
array = [1, 6, 9, 10 , 15, 18, 20];
And a random number is being generated from 1 to 20, with the following code:
var x = Math.floor((Math.random() * 20) + 1)
How could I check if the generated number is already in the array above? If it is, I want to generate a new value so it does not repeat one of the values in the array.
You can use array.includes(x)
var number;
do
{
number = Math.floor((Math.random() * 20) + 1) )
} while (array.includes(number))
Just be aware of unending loop, if you fill the array.
You can use Set Api for this too
The Set object lets you store unique values of any type, whether primitive values or object references.
read more here
in your case you can do something like this
let numbers = new Set(); // your collection
const generateNumber = () => Math.floor((Math.random() * 20) + 1)
// add new number to the set
function addNumber(value) {
numbers.add(value)
}
// generate random numbers
addNumber(generateNumber())
addNumber(generateNumber())
addNumber(generateNumber())
You can use indexOf() to check if the value is in array
and after that you can use comparisson to generate new number if the random number is the same as the previous
array = [1, 6, 9, 10 , 15, 18, 20]
var x = Math.floor((Math.random() * 20) + 1) )
if (array.indexOf(x) !== -1) {
//value exists in array
var x_old=x;
x = Math.floor((Math.random() * 20) + 1) )
while (x_old === x) {
x = Math.floor((Math.random() * 20) + 1) )
}
} else {
//Value doesn't exist in array
}
Check whether the number is already in the array, if so generate a new one.
let a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const generateRandomNumber = () => Math.floor((Math.random() * 20) + 1)
let temp = generateRandomNumber();
// console.log(temp)
while (a.includes(temp))
temp = generateRandomNumber()
a.push(temp);
console.log(a)
do {
var x = Math.floor((Math.random() * 20) + 1);
} while (array.indexOf(x) === -1)
This code should do it, but it will compute unneccesary things. So I prefer to choose just a random item from the array like this.
var x = array[Math.floor(Math.random() * array.length)];
A lot of people are talking about the include function. I don't prefer to use that because it is a modern function that is very lately supported.
You can also do this using the below recursive function. The below solution never logs the generated random number which is present in the array, instead it generates random number recursively until, the number not in the array is found!
var array1 = [1, 6, 9, 10 , 15, 18, 20];
var x = Math.floor((Math.random() * 20) + 1);
var xIncludesArray1 = array1.includes(x);
function arrFinder() {
if(!xIncludesArray1) { console.log(x)}
else { x = Math.floor((Math.random() * 20) + 1);
xIncludesArray1 = array1.includes(x);
arrFinder();}
};
arrFinder();

Convert integers to string and then adding using recursion [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
Hi I am trying to solve a problem where the input for a function digital_root(n) will add the digits. I am not sure what I am doing wrong.
function digital_root(n) {
// ...
//1. separate n into array of digits
var nString = n.toString();
//[ '1', '2', '3', '4' ]
var numbersToAdd = [];
var total = 0;
for (var i = 0; i < nString.length; i++) {
numbersToAdd.push(+nString.charAt(i));
}
// result is [ 1, 2, 3, 4 ]
//2. add digits
for (var x = 0; x < numbersToAdd.length; x++) {
total += numbersToAdd[i];
//expected outputs
// total = 0 + numbersToAdd[0]--> 0+1--> total = 1
// total = 1 + numbersToAdd[1]-->1+2--> total = 3
// total = 3 + numbersToAdd[2]-->3+3--> total = 6
// total = 6 + numbersToAdd[3]-->6+3--> total = 9
}
return total;
}
console.log(digital_root(1234));
You need to use "x" instead of "i"
So changing
total += numbersToAdd[i];
to
total += numbersToAdd[x];
will fix an issue.
Also output should be 10 instead of 9, there is calculation mistake in your question

Convert array of numbers to string in Javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
How do I convert an array of numbers to a single string in Javascript?
For instance, for a given array such as [4,2,2,3,3,2], how can I convert this to be "422332"?
var arr = [4,2,2,3,3,2];
var stringFromArr = arr
.join('');
Make sure to follow all steps! Here's the easiest way to convert an array of numbers to a string:
var arr = [4, 2, 2, 3, 3, 2];
var string = arr
.filter(v => v != null)
.map(v => v * 1000)
.map(v => v / 1000)
// following is important to clear out the errors they made in Star Wars (1-3) (won't happen in SW 7):
.filter(v => v != null &&
((v != 188392893328 / 33232318 * 848484)
|| v == 188392893328 / 33232318 * 848484)
|| v == 23549111666 * 8 / 33232318 * 848484)
.map(v => v.toString())
.map(v => parseFloat(v))
.map(v => parseInt(v))
.join("");
console.log(string);
Now you can be sure! It's converted. Big time!

Get random number based on probability [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I was wondering to get a random number with two decimal places based on probability for example:
40% to get number from 1-10
20% to get number from 11-20
30% to get number from 21-30
10% to get number from 31-35
function Prob(){
var rnd = Math.random(),
rnd2 = Math.random();
if(rnd<0.4) return (1 + Math.floor(1000 * rnd2)/100);
else if(rnd<0.6) return (11 + Math.floor(1000 * rnd2)/100);
else if(rnd<0.9) return (21 + Math.floor(1000 * rnd2)/100);
else return (31 + Math.floor(500 * rnd2)/100);
}
You need two random numbers, so I calculate them at the start. I then use the if-else loops to cycle through your 40%, 20%, 30% and 10% (adding them up as I go). Note: Math.random returns a number between 0 and 1. Then for each catagory I use the SECOND random number to get in the range you have said - floor it to make sure it is an integer and add the starting number of each range. Note: the range of your last one is just 5.
I should explain, you must use two random numbers, otherwise the range of the second number would be dependent on which category you are in.
I have to do the 1000 * rnd2 in the floor and then divide by 100 outside to get the 2 decimal place you ask for.
Rewind's solution is great and specifically tailored to OP's quesiton. A more re-usable solution might be:
function getNumber(probabilities){
var rnd = Math.random();
var total = 0;
var hit;
for(var i = 0; i < probabilities.length; i++){
if(rnd > total && rnd < total + probabilities[i][0]){
hit = probabilities[i]
}
total += probabilities[i][0];
}
return Number((hit[1] + (Math.random() * (hit[2] - hit[1]))).toFixed(2));
}
var number = getNumber(
[
//chance, min, max
[0.4, 1, 10],
[0.2,11,20],
[0.3,21,30],
[0.1,31,35]
]
);
console.log(number);
The function will take an array with the probabilities, for each probability you specify the chance, the minimum value for that chance, the maximum value for that chance. It will return a number with two decimals.
https://jsfiddle.net/x237w5gv/
I guess this
var get1120 = _ => ~~(Math.random()*10)+11,
get2130 = _ => ~~(Math.random()*10)+21,
get3135 = _ => ~~(Math.random()*5)+31,
a = [get3135,get1120,get1120,get2130,get2130,get2130],
fun;
result = (fun = a[~~(Math.random()*10)]) ? fun() : ~~(Math.random()*10)+1;
console.log(result);
might do it;

How do I make a numerical array's increase amount smaller in each step? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I would like to make a numeric array which increases in every step.
[1,200,400,600,800,1000, .... , 10000]
But I need to make the amount by which it increases progressively smaller in every step. For example,
[1, 200, 300, 350, 325, 312.5, ....., 10000]
If anybody knows the solution, please give me some ideas.
Thank you.
Change the increment amount as you please...
var arr = [];
var i = 1;
var incrementAmt = 2000;
for(var j = 0; j < 1000; j++) {
var num = i + incrementAmt;
arr.push(num);
i = num;
i++;
incrementAmt = incrementAmt / 2; // cause incrementer to decrease each iteration
}
console.log(arr)

Categories

Resources