我怎样才能避免电脑选择相同的号码?
How could I avoid the pc to pick the same number?
如果我有这样的数组
int numbers[10] = {1,1,3,3,5,5,7,7,8,8};
我想随机抽取一个
i = numbers[rand()% 10];
对于这个例子,我怎样才能避免电脑多次选择相同的号码。因为就像你在数组中看到的一样,相同的数字重复了 2 次。所以我想,例如,数字 8 只选择两次,其他数字也一样。
我知道我可以做一些事情,比如将一个元素标记为“已删除”,例如,将其设置为 0,然后如果所选数字已被删除,您可以再次选择。但我不知道如何正确地做,所以如果这里有人能帮助我,我将不胜感激。
用数组+“交换和弹出”实现:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
static int pick_number(int *numbers, int max)
{
int index = rand() % max;
int result = numbers[index];
// Swap
numbers[index] = numbers[max-1];
return result;
}
int main(int argc, char *argv[])
{
srand(time(NULL));
int numbers[10] = {1,1,3,3,5,5,7,7,8,8};
for (int i = 10; i > 0; i--) {
printf("got: %d\n", pick_number(numbers, i));
}
return 0;
}
您可以生成随机数,使其等于尚未使用的元素数,并将未使用的元素移动到数组的前面。
#define SZ 10
int numbers[SZ] = {1,1,3,3,5,5,7,7,8,8};
for (int i = 0; i < SZ; ++i)
{
// Generate the random number in the range [0 .. UNUSED-ELEMENTS]
// First loop in range [0..9]
// Second loop in range [0..8]
// and so on
int r = rand() % (SZ-i);
int d = numbers[r];
printf("%d ", d);
// Overwrite the used element with an unused element, i.e. last unused,
// so that unused elements are always at the lowest array index
numbers[r] = numbers[SZ-i-1];
}
printf("\n");
如果我有这样的数组
int numbers[10] = {1,1,3,3,5,5,7,7,8,8};
我想随机抽取一个
i = numbers[rand()% 10];
对于这个例子,我怎样才能避免电脑多次选择相同的号码。因为就像你在数组中看到的一样,相同的数字重复了 2 次。所以我想,例如,数字 8 只选择两次,其他数字也一样。
我知道我可以做一些事情,比如将一个元素标记为“已删除”,例如,将其设置为 0,然后如果所选数字已被删除,您可以再次选择。但我不知道如何正确地做,所以如果这里有人能帮助我,我将不胜感激。
用数组+“交换和弹出”实现:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
static int pick_number(int *numbers, int max)
{
int index = rand() % max;
int result = numbers[index];
// Swap
numbers[index] = numbers[max-1];
return result;
}
int main(int argc, char *argv[])
{
srand(time(NULL));
int numbers[10] = {1,1,3,3,5,5,7,7,8,8};
for (int i = 10; i > 0; i--) {
printf("got: %d\n", pick_number(numbers, i));
}
return 0;
}
您可以生成随机数,使其等于尚未使用的元素数,并将未使用的元素移动到数组的前面。
#define SZ 10
int numbers[SZ] = {1,1,3,3,5,5,7,7,8,8};
for (int i = 0; i < SZ; ++i)
{
// Generate the random number in the range [0 .. UNUSED-ELEMENTS]
// First loop in range [0..9]
// Second loop in range [0..8]
// and so on
int r = rand() % (SZ-i);
int d = numbers[r];
printf("%d ", d);
// Overwrite the used element with an unused element, i.e. last unused,
// so that unused elements are always at the lowest array index
numbers[r] = numbers[SZ-i-1];
}
printf("\n");