Today I have something really special, hope someone can help me.
I have this piece of code:
var names = [James, Robert, John, Michael, William, David];
var genNames = [];
var specialNames = ["James", "Michael", "David", "Robert"]; - (not implemented, genNames[] can't contain two or more of these names)
for (var i = 0; i < 4; i )
{
var idx = Math.floor(Math.random() * names .length);
genNames.push(names [idx]);
names.splice(idx, 1); - this preventing generation of two same names but specialNames is something else what I need and what I explained below.
}
Explanation of code:
This piece of code will generate 4 random names from the array named names[] and then they will be put into the new array genNames[]. I'm taking generated values in my code like this: ${genNames[0]}, ${genNames[1]}, ${genNames[2]}, ${genNames[3]}
But what's the problem?
After generating the result, there is the chance to contain two same names from names[] list as in specialNames[] list, it's a small chance in this example but I have many of values and some values which could not be generated twice like specialNames.
What I need?
If the generated names will contain two same names as in specialNames[] array, take one of them and replace (or just deny generation of two of these specialNames[]) with another name from the names[] array.
Simplified explanation:
Random generated names(genNames[]) from names[] array can't contain two or more specialNames.
Thanks for possible solutions/answers!
CodePudding user response:
You could use Set instead of a List. Sets are not containing duplicates. Is a duplicated added to a Set the number of elements inside the set will not change.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
CodePudding user response:
A good approach to avoid duplicate values while generating random indexes, is doing a while
loop that checks if the value relative to the random index generated is allowed or not, and keeps recalculating new indexes, until the corresponding value is an allowed value:
const generateNames = () => {
const names = ['James', 'Robert', 'John', 'Michael', 'William', 'David'];
const genNames = [];
const specialNames = ['James', 'Michael', 'David', 'Robert'];
for (let i = 0; i < 4; i ) {
let idx = Math.floor(Math.random() * names.length);
let name = names[idx];
// Check if `name` is a specialName AND if it's already present inside genNames array
while (specialNames.includes(name) && genNames.includes(name)) {
idx = Math.floor(Math.random() * names.length);
name = names[idx];
}
genNames.push(name);
setGenNames(genNames);
}};
Testing example: https://stackblitz.com/edit/react-sd7qlh