我想创建两个数组,它们都不能有重复的值,如果可能,我会在同一循环中寻找答案。
for(int i=0;i<MAX;i++){//MAX=vector's number of values
scanf("%d", &vector[i]);//reads the number from the keyboard
while(j!=i){//Looks for each vector[i] if there is a vector[j], with j<i, with that value already. j starts at 0
if(vector[j]==vector[i]){
printf("\nWrite another number\n");
scanf("%d",&vector[i]);
j=0;
}
else
j++;
}
}
对于第二个循环,我寻找相同的结果,一组非重复的值,但具有随机数。
for(int i=0;i<MAX;i++){
vector[i]=(rand()%MAX-MIN+1)+MIN;
while(j!=i){
if(vector[j]==vector[i]){
vector[i]=(rand()%MAX-MIN+1)+MIN;;
j=0;
}
else
j++;
}
}
我一直试图提供一种在两个间隔之间生成随机数的方法,例如(2,10)U(12,20),因此,只要您发现重复的值,下一个随机数就不会包含它,但是我找不到任何方式可以做到这一点。
感谢您的帮助
要生成两个间隔的并集中的随机数,可以使用:
int n = rand() % (TOTAL_INTERVAL_MEMBERS-1) + LOWEST_INTERVAL_MEMBER;
if (n > MEMBERS_IN_LOWEST_VALUE_INTERVAL) n += INTERVAL_DIFFERENCE;
如果数字范围不太大,则可能要创建一个有效数字数组,并从中随机选择。