遍历数组直到随机值不等于任何值
Iterating through an array until random value isn't equal to anything
首先,我对编程还很陌生,所以提前致歉。
这就是我想要做的:
1) 使用
将随机值生成到变量中
questionNr = Random.Range(0, nNodes);
2) 通过遍历其所有值将该变量与数组进行比较
for(var i=0; i<usedQuestionList.length(); i++){
if(questionNr == usedQuestionList[i]){
//stuff
}
}
3) 如果数组的任何值等于所述变量的值,则从头开始生成一个新的随机值并再次遍历数组。 pass/end 循环的唯一方法是当随机值不等于数组中的任何值时。
问题是,如果我执行这个简单的 for 循环,当条件不满足时,我无法返回并重新执行所有操作。
我很确定我只是接近了错误的逻辑,并且有一种我没有想到的简单方法可以做到这一点,这就是为什么我没有添加失败的任何代码的原因和while 循环尝试。感谢任何帮助,谢谢!
你可以设置一个标志,你可以在循环结束后检查,可能是这样的:
//A function that will take a number and check against the array
var loopRandomNumber = function(number){
//A flag to be used if match is found
var foundMatch = false;
//Your simple loop
for(var i=0; i<usedQuestionList.length(); i++){
//Checking if match
if(number == usedQuestionList[i]){
foundMatch = true; //Match found
break; // Jumps out of the for-loop to be a little faster
}
}
//Calling this function again with a new random number if match found
if(foundMatch){
loopRandomNumber(Random.Range(0, nNodes));
} else {
//Handle your condition for if no match was found here
}
}
loopRandomNumber(Random.Range(0, nNodes));
首先,我对编程还很陌生,所以提前致歉。
这就是我想要做的:
1) 使用
将随机值生成到变量中questionNr = Random.Range(0, nNodes);
2) 通过遍历其所有值将该变量与数组进行比较
for(var i=0; i<usedQuestionList.length(); i++){
if(questionNr == usedQuestionList[i]){
//stuff
}
}
3) 如果数组的任何值等于所述变量的值,则从头开始生成一个新的随机值并再次遍历数组。 pass/end 循环的唯一方法是当随机值不等于数组中的任何值时。
问题是,如果我执行这个简单的 for 循环,当条件不满足时,我无法返回并重新执行所有操作。
我很确定我只是接近了错误的逻辑,并且有一种我没有想到的简单方法可以做到这一点,这就是为什么我没有添加失败的任何代码的原因和while 循环尝试。感谢任何帮助,谢谢!
你可以设置一个标志,你可以在循环结束后检查,可能是这样的:
//A function that will take a number and check against the array
var loopRandomNumber = function(number){
//A flag to be used if match is found
var foundMatch = false;
//Your simple loop
for(var i=0; i<usedQuestionList.length(); i++){
//Checking if match
if(number == usedQuestionList[i]){
foundMatch = true; //Match found
break; // Jumps out of the for-loop to be a little faster
}
}
//Calling this function again with a new random number if match found
if(foundMatch){
loopRandomNumber(Random.Range(0, nNodes));
} else {
//Handle your condition for if no match was found here
}
}
loopRandomNumber(Random.Range(0, nNodes));