[英]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. 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.
我不确定如何从阵列中删除已经选择的 colors。 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.我会创建一个临时变量设置为选择的颜色,然后在继续递归之前在
randomIndex
删除该数组条目。
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在你的过滤器 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.条件(
color !== randomIndex
)将始终为真,因为随机索引是一个数字,而颜色是一个字符串。 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.但即使这样也不会得到想要的结果,因为您要从数组中删除随机索引而不将其存储在某处,这就是重复项首先出现的方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.