我正在做一个井字棋(没有矩阵),我对此有疑问。
假设我在这里输入的是“5”:
printf(" 1 | 2 | 3 \n");
printf("___|___|___\n");
printf(" 4 | 5 | 6 \n");
printf("___|___|___\n");
printf(" 7 | 8 | 9 \n");
printf(" | | \n");
printf("\n");
我希望 A.I.选择一个随机框,不包括我输入的“5”。我正在做随机的事情:
srand ( time(NULL) );
int randIndex = rand() % 8;
if (movement == 5 && i == 0){
xslot[randIndex] = 'O';
steps = 1;
}
我不知道如何从这个随机选择中排除“5”。
这是我的数组:
char xslot[] = {'1', '2', '3', '4', '5', '6', '7', '8', '9'};
谢谢
编辑:完整代码:
main()
{
int movimento,passos;
bool passo1=false,passo2=false,passo3=false,passo4=false,passo5=false;
char oslot[9] = "O";
char xslot[] = {'1', '2', '3', '4', '5', '6', '7', '8', '9'};
srand ( time(NULL) );
printf("\n\n");
printf(" 1 | 2 | 3 \n");
printf("___|___|___\n");
printf(" 4 | 5 | 6 \n");
printf("___|___|___\n");
printf(" 7 | 8 | 9 \n");
printf(" | | \n");
printf("\n");
printf("Digite o numero do seu movimento:");
for(int i =0;i<5;i++){
scanf("%i",&movimento);
if (movimento == 1){
xslot[0] = 'X';
} else if (movimento == 2){
xslot[1] = 'X';
} else if (movimento == 3){
xslot[2] = 'X';
} else if (movimento == 4){
xslot[3] = 'X';
} else if (movimento == 5){
xslot[4] = 'X';
} else if (movimento == 6){
xslot[5] = 'X';
} else if (movimento == 7){
xslot[6] = 'X';
} else if (movimento == 8){
xslot[7] = 'X';
} else if (movimento == 9){
xslot[8] = 'X';
}
//INTELIGENCIA ARTIFICIAL
int randIndex = rand() % 8;
if (movimento == 5 && i == 0){
xslot[randIndex] = 'O';
passos = 1;
}
最佳答案
使用包含可用选择的数组,并在每次选择选择时“缩小”它:
size_t numSelections = 9;
int selections [] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
while (numSelections > 0) {
size_t const next = rand() % numSelections;
--numSelections;
// move selected selection out of valid array range
int const selection = selections [next];
selections [next] = selections [numSelections];
printf("Selected %d\n", selection);
}
每次选择一个值时,都会将其移出数组的有效范围,并将该值(未选择,但现在超出范围)移回到有效的数组范围内:
1 2 3 4|
;; select the 3, shrink valid range
1 2 3|4
;; move 3 out, bring 4 back in
1 2 4|x
在上面的示例中,选择是随机发生的,但您可以轻松修改它 - 例如 - 在随机选择和用户定向选择之间交替来实现您的游戏
关于c - 随机数组选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35444528/