我正在尝试用 6 个不同字符中的 4 个填充数组,其中数组中的每个字符都不同。放入数组的字符基于 switch 语句。然后我想通过数组返回以确保我刚刚放置的字符不在数组中,如果是,我必须放入不同的字符。我该怎么做呢?我不想重新填充整个阵列,只是这一点。
这是我到目前为止的代码,包括评论:
-(void) fillarray{
for (int i=0; i<4; i++)
{
int randomNum = arc4random() % 6; // generates a random number
switch (randomNum) // based on the number generated, it choses what color will be placed into the slot
{
case 1:
colorarray[i] ='r';
break;
case 2:
colorarray[i] ='o';
break;
case 3:
colorarray[i] ='y';
break;
case 4:
colorarray[i] ='g';
break;
case 5:
colorarray[i] = 'b';
case 6:
colorarray[i] = 'p';
default:
break;
}
for (int j=0; j<4; j++) // runs through the array to ensure that the recently placed color does not match previous placed colors
{
while (j /= i)
if (colorarray[i]==colorarray[j]) // if the color is already in the array
//try again to place another color in this location
}