【发布时间】:2018-10-04 04:19:15
【问题描述】:
我正在为嵌入式板编程以点亮 4 个 LED(共 8 个)。 我想随机化那些被点亮的,然后重复这个过程。 基本上,通过从一组设置数字(LED 位值)中复制值,使它们随机化,然后将它们插入另一个数组。第二个阵列需要唯一的值(即相同的 4 个 LED,但采用唯一的随机模式)。我需要复制这 x 次,因此是主 while 循环。
目前,我在第二个数组中得到重复的数字。我相信这是因为嵌套的 for 循环没有正确中断。我尝试过 break,使 for 循环计数器 (i/j) 成为最大值(这会导致无限循环),甚至 goto。
到目前为止无济于事。任何有关解决此问题的更好方法的更正或建议表示感谢!
int main() {
srand(time(NULL)); //Set seed random number
int ledORIGINAL[4] = { 2,4,6,8 }; //Array of defined numbers to use
int led[4] = { 0,0,0,0 }; //Empty array (set to 0's)
int rIndex=0, ledIndex=0, loop=0; //Index variables
bool originalNum = false; //Boolean flag to find original number
while (loop < 2) { //Set how many random arrays you need
while (ledIndex < 4) { //Repeat util all 4 array slots filled
rIndex = rand() % 4; //Get a random index number
if (led[ledIndex] == 0) { //If the array slot is empty
for (int i = 0; i < 4; i++) { //Nested for loops to check number is not already in array
for(int j=0; j<4; j++){
if (led[i] != ledORIGINAL[j]) {
originalNum = true;
}
else {
originalNum = false; //Boolean flag set to false, no need to search further
//i= 4; //Set i to 4 to break outer loop
//j = 4; //Set j to 4 to break inner loop
break;
//goto PLACE;
}
}
}
//PLACE:
if (originalNum) {
led[ledIndex] = ledORIGINAL[rIndex];
ledIndex++;
}
}
}
for (int i = 0; i < 4; i++) {
std::cout << led[i];
led[i] = 0;
}
ledIndex = 0;
loop++;
}
}
【问题讨论】:
-
只需创建一个长度为 8 的数组,其中包含 4 个 0 和 4 个 1。然后Fisher-Yates shuffle 选择要点亮的 LED。
-
我需要保留这些数字,以便稍后移动它们,而不是使用实际位
-
是什么阻止了您对数组进行 FY 洗牌,即为此目的使用已知算法?
-
您声称发布的代码是 C,但是,它包含:
std::cout << led[i];这是一个 C++ 语句。 -
关于:`break;`这只会退出内部
for()循环,而不是外部for()循环