简体   繁体   中英

How do I remove a certain element from my array just before the recursion?

So I'm trying to make a basic bomb wire cutting game where you get 4 randomly picked colors from an array of 6 possible colors, but I'm having trouble with getting it so there are no duplicate colors in the 4 random colors. I'm not sure how to remove already picked colors from the array. I think my logic is wrong.

const colors = ['Blue', 'Red', 'Yellow', 'White', 'Black', 'Green']
function getXRandomColors(colors, x, result) {
    if (x === 0) return result
    const randomIndex = Math.floor(Math.random() * colors.length)
    if (colors.includes(randomIndex)){
        colors = colors.filter(color => color !== randomIndex)}
    return getXRandomColors(colors, x - 1, [...result, colors[randomIndex]])
}
var fourRandomColors = getXRandomColors(colors, 4, [])
console.log('The wires are: ' + fourRandomColors);

I'd create a temporary variable set to the picked color, then removing that array entry at the randomIndex before continuing recursion.

const colors = ['Blue', 'Red', 'Yellow', 'White', 'Black', 'Green']
function getXRandomColors(colors, x, result) {
    if (x === 0) return result
    const randomIndex = Math.floor(Math.random() * colors.length)
    let pickedColor = colors[randomIndex];
    colors.splice(randomIndex, 1);
    return getXRandomColors(colors, x - 1, [...result, pickedColor])
}
var fourRandomColors = getXRandomColors(colors, 4, [])
console.log('The wires are: ' + fourRandomColors);

This way you are guaranteed there won't be any duplicates.

Couple things that are going wrong in your current example:

In your filter function

    colors = colors.filter(color => color !== randomIndex)}

The condition ( color !== randomIndex ) will always be true, because random index is a number and color is a string. What you'd want to do if you'd compare index is;

    colors = colors.filter((color, index) => index !== randomIndex)}

But even this won't have the desired result , since you're removing the random index from your array without storing it somewhere, this is how duplicates will show up in the first place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM