How to create an array containing non-repeating numbers? [duplicate] - javascript

This question already has answers here:
Generate unique random numbers between 1 and 100
(32 answers)
Closed 2 years ago.
this is my first question here.
I need to generate an array containing 16 random numbers and that's my solution:
var arr = [];
for (var i = 0; i < 16; i++) {
arr.push(Math.floor(Math.random() * 100) + 1);
}
The problem is that in this way it is possible that there are repeated numbers. Is there someone who can help me? Thanks in advance.

The shortest approach is to use a Set and check the wanted size of it.
let numbers = new Set,
result;
while (numbers.size < 16) numbers.add(Math.floor(Math.random() * 100) + 1);
result = [...numbers];
console.log(...result);

Use a while loop
const MAX_NUMBER = 16;
const arr = [];
do {
const randomNumber = Math.floor(Math.random() * 100) + 1
// Push if the array does not contain it
if (!arr.includes(randomNumber)) {
arr.push(randomNumber);
}
} while (arr.length < MAX_NUMBER);
console.log(arr)

Related

How do I successfully push 50 randomly generated numbers into an array? [duplicate]

This question already has answers here:
How do I build a loop in JavaScript? [closed]
(4 answers)
Closed 4 years ago.
I have written a function that generates different numbers each time it is called. Now I want it to genarate say 50 different numbers and then push it into an array. How do I go about it? This is the code below:
function generateRandomNumbers() {
let randomArray = [];
let digits = Math.floor(Math.random() * 900000000) + 100000000;
digits = `0${digits}`;
// Last task is to push 50 random digits into the array;
return randomArray;
}
console.log(generateRandomNumbers());
You need to do something like this:
function generateRandomNumbers(howMany) {
let arr = [];
for(let i = 0; i <= howMany; i++)
{
let digits = Math.floor(Math.random() * 900000000) + 100000000;
digits = `0${digits}`;
arr.push(digits);
}
return arr;
}
let randomArray = generateRandomNumbers(50);
console.log(randomArray);

How to generate random numbers without including a set number? [duplicate]

This question already has answers here:
Unique (non-repeating) random numbers in O(1)?
(22 answers)
Closed 4 years ago.
I'm just trying to generate 8 random numbers from 1 to 25. My issue is that I already have a variable and its value is 14, with that being said my question is how to generate random numbers from 1 to 25 and if one them is equal to 14 then replace it with another random number? at the end, I want to have 8 random numbers in my array and I don't want to include 14 in it. Can anyone tell me what I'm missing or how to make this more accurate? and sometimes I only end up with 7 elements in my array, does anyone knows why?
Here's my code:
var arr = [];
var currentvar = 14;
for(var i = 0 ; i < 9; i++){
var num = Math.floor(Math.random()*25) + 1;
if(num === currentvar){
num = Math.floor(Math.random()*25) + 1;
}else{
arr.push(num);
}
}
console.log(arr);
Study the logic you've implemented more closely. You go through the loop exactly 9 times (not 8), and you have mutually exclusive outcomes for each iteration due to an if...else control flow.
Either you reassign num if it's equal to currentvar (which you should do correctly by removing var from the second assignment), or you add it to the array, never both in one iteration. That's what else means, and you probably want a do...while loop to assign num until it is not equal to currentvar.
var arr = [];
var currentvar = 14;
var num;
for (var i = 0; i < 8; i++) {
do {
num = Math.floor(Math.random() * 25) + 1;
} while (num === currentvar);
arr.push(num);
}
console.log(arr);
Alternatively, if you want to keep your if...else statement, you can decrement the loop counter i instead to repeat the loop an extra time when num === currentvar:
var arr = [];
var currentvar = 14;
for (var i = 0; i < 8; i++) {
var num = Math.floor(Math.random() * 25) + 1;
if (num === currentvar) {
i--;
} else {
arr.push(num);
}
}
console.log(arr);

How to create random string in Javascript? [duplicate]

This question already has answers here:
javascript password generator
(34 answers)
Generate random string/characters in JavaScript
(93 answers)
Closed 5 years ago.
I would like to create random strings. But I am not get a right way. any one can help me please?
my try :
var anysize = 3;//the size of string
var charset = "abcdefghijklmnopqrstuvwxyz"; //from where to create
console.log( Math.random( charset ) * anysize ); //getting bad result
Is it possible to correct me? or any other elegant way to fix this?
Thanks in advance.
You should use .length property of your string of possible characters(charset).
Also, use Math.floor method in order to get integer positions of your chars array.
You can get a random item from charset string using its array index:
charset[Math.floor(Math.random() * charset.length)]
var anysize = 3;//the size of string
var charset = "abcdefghijklmnopqrstuvwxyz"; //from where to create
result="";
for( var i=0; i < anysize; i++ )
result += charset[Math.floor(Math.random() * charset.length)];
console.log(result);
function randomString(anysize, charset) {
var res = '';
while (anysize--) res += charset[Math.random() * charset.length | 0];
return res;
}
Something like that
You could get the n-index char of string charset and append to a new string many times as you need, see following please:
var anysize = 3;//the size of string
var charset = "abcdefghijklmnopqrstuvwxyz"; //from where to create
var i=0, ret='';
while(i++<anysize)
ret += charset.charAt(Math.random() * charset.length)
console.log(ret);
The first thing you will want to do is create a helper function that can grab a random value from an array.
getRandomValue(array) {
const min = 0; // an integer
const max = array.length; // guaranteed to be an integer
/*
Math.random() will return a random number [0, 1) Notice here that it does not include 1 itself
So basically it is from 0 to .9999999999999999
We multiply this random number by the difference between max and min (max - min). Here our min is always 0.
so now we are basically getting a value from 0 to just less than array.length
BUT we then call Math.floor on this function which returns the given number rounded down to the nearest integer
So Math.floor(Math.random() * (max - min)) returns 0 to array.length - 1
This gives us a random index in the array
*/
const randomIndex = Math.floor(Math.random() * (max - min)) + min;
// then we grab the item that is located at that random index and return it
return array[randomIndex];
}
You could use this helper function with no regard for changing the length of the string, like this:
var randomString = getRandomValue(charset) + getRandomValue(charset) + getRandomValue(charset);
However, you may want to create another function that contains a loop based on how long you want the random string to be:
function getRandomString(charset, length) {
var result = '';
for (var i = 0; i <= length; i++) {
result += getRandomValue(charset);
}
return result;
}
And that function would be used like this
var randomString = getRandomString(charset, 3);

How do i split an integer and all the digits produced to create a new number? [duplicate]

This question already has answers here:
JavaScript Number Split into individual digits
(30 answers)
Closed 6 years ago.
For instance, if i have the number 4444. I need it to do 4+4+4+4=16.
i want to get the result of 16. I tried changing the number to a string and got the array. But i don't know how to add it after. I searched it up but the other examples were too complicated for my level.
Working Example
var n = 4444;
var a = n.toString().split('').map(Number).reduce(function(a, b) {
return a + b;
});
Turn number to string
Split it
Map over array to return Numbers
Reduce to get total
or with a loop:
var sum = 0;
var string = n.toString();
for (var i = 0; i < string.length; i++) {
sum = sum + Number(string[i]);
}

Having Issue On Generating Random Numbers More Than Random Rage Number

I need to generate 30 Random Numbers between 1 to 20. I am using this code but this is making conflict since the loop number is bigger than the Random range (I guess!)
var arr1 = [];
for (var i = 0; i < 30;) {
var ran = Math.floor(Math.random() * 20) + 1;
if ( arr1.indexOf(ran) == -1)
arr1[i++] = ran;
}
can you please let me know why this is happening and how I can prevent this to create 30 random numbers?
Thanks
I created a fiddle here , have a look
https://jsbin.com/kagixi/edit?html,js,output
In first case, we are updating values by iterating over all the indices.
var list = new Array(30).fill(0);
list.forEach(function(d, index){
list[index] = Math.floor(Math.random() * 20) + 1;
});
console.log(list);
Another way of doing this is to initialize array just to loop and then simply create a new array with same length or replace the existing one as I did in this example.
var list2 = new Array(30).fill(0);
list2 = list2.map(function(){
return Math.floor(Math.random() * 20) + 1;
});
You miss the third argument on your for statement.
Try this:
var arr1 = [];
for (var i = 0; i < 30; i++) {
arr1[i] = Math.floor(Math.random() * 20) + 1;
}
Your code creates an infinite loop.
Your random numbers are between 1 and 20 but you want 30 of them in your array. The check for duplicates in the line if ( arr1.indexOf(ran) == -1) is guaranteed to return false after 20 iterations, creating an infinite loop.

Categories

Resources