我这个程序的目标是让用户确定数组的大小并为他们选择的任何大小动态分配内存。一旦用户定义了数组的大小,不超过数组大小的随机数将被放置到所有分配的位置中。我遇到问题的地方是从数组中删除重复项并将其替换为未使用的值,
示例:
Please enter the size of the array:
User Input: 5
Output of code: 5, 3, 3, 1, 2
我需要它是这样的:
Please enter the size of the array:
User Input: 3
Output of program: 3, 1, 2
当前正在阅读 K.N. 的《C 编程 - 现代方法》国王(第二版)。
如果有人能指出我如何解决这个问题的正确方向,我将不胜感激。这是迄今为止我的代码。
#include <stdio.h>
#include <stdlib.h>
#define true 1
#define false 0
typedef int bool;
int main() {
int *UserData;
int TempPost;
int replace;
int UserInput;
int i;
int result;
bool digit_seen[UserInput];
int digit;
srand ((unsigned) time(NULL));
printf("Please enter the size of the array using a whole number: \n");
scanf("%d", &UserInput);
UserData = malloc(sizeof(int) * (UserInput ) +1);
for(i=0; i < UserInput; i ++) {
result = (( rand() % UserInput) + 1);
}
// check for duplicate values while putting values in array
while(UserInput>0){
digit = UserInput % UserInput;
if(digit_seen[digit])
break;
digit_seen[digit] = true;
UserInput /= UserInput;
if(UserInput > 0)
printf("Repeated digit \n");
else
printf("No repeated digit \n");
}
// Sorting the array using a Bubble sort
while(1){
replace = 0;
for (i=0; i<(UserInput - 1); i++){
if(UserData[i]>UserData[i+1]){
TempPost = UserData[i];
UserData[i] = UserData[i+1];
UserData[i+1] = TempPost;
replace = 1;
}
}
if(replace==0){
break;
}
}
printf("%d \n", result);
return 0;
}
最佳答案
这不是最有效的方法,但您可以在生成随机数时执行此操作。当您选择一个随机数时,请检查该数组之前的所有元素,看看它是否已被使用过。继续循环,直到选择一个未使用的号码。
for (i = 0; i < UserInput; i++) {
do {
result = ( rand() % UserInput) + 1;
} while (in_array(result, UserData, i-1));
UserData[i] = result;
}
int in_array(int val, int* array, int array_size) {
for (int i = 0; i < array_size; i++) {
if (array[i] == val) {
return 1;
}
}
return 0;
}
稍微更有效的方法是将数组初始化为0
。然后,不要选择随机数,而是选择一个随机索引来填充,然后重复此操作,直到选择包含 0
的索引。
UserData = calloc(UserInput, sizeof(int));
for (i = 1; i <= UserInput; i++) {
int index;
do {
index = rand() % UserInput;
} while (UserData[index] != 0)
UserData[index] = i;
}
关于c - 删除数组中的重复项并用未使用的值替换它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46332188/