gpt4 book ai didi

计算并删除数组 c 中的重复项

转载 作者:太空宇宙 更新时间:2023-11-04 01:02:19 25 4
gpt4 key购买 nike

假设我有一个包含 [2,4,6,7, 7, 4,4] 的数组我想要一个可以迭代的程序,然后打印出如下内容:

Value:     Count:
2 1
4 3
6 1
7 2

我不希望它打印 ex 4 三次。到目前为止我得到了什么:

for (int i = 0; i < numberOfInts; i++)
{
dub[i] = 0;
for (int y = 0; y < numberOfInts; y++)
{
if (enarray[i] == enarray[y])
{

dub[i]++;
}
}

}

所以基本上我会根据所有元素检查数组中的每个元素,并且对于每个重复元素,我都会将一个元素添加到新数组 dub[] 的索引中。因此,如果我使用上面的示例数组运行此代码,然后将其打印出来,我将得到如下内容:1,3,1,2,2,3,3。这些数字非常令人困惑,因为我真的不知道它们属于哪个数字。特别是当我将数组中的数字随机化时。然后我必须删除数字,所以我只有一个。谁有更好的解决方案?

最佳答案

您可以遍历数组,同时检查每个元素是否已重复,在这种情况下您会增加它的计数(循环只检查头部值以节省处理时间)。这使您无需创建任何额外的缓冲区数组或结构即可完成所需的工作。

bool 'bl' 防止重复打印

int main() {

int arr[] = { 2, 4, 6, 7, 7, 4, 4 };
int size = (sizeof(arr) / sizeof(int));

printf("Value:\tCount\n");
for (int i = 0; i < size; i++) {
int count = 0, bl = 1; //or 'true' for print
//check elements ahead and increment count if repeated value is found
for (int j = i; j < size; j++) {
if (arr[i] == arr[j]) {
count++;
}
}
//check if it has been printed already
for (int j = i-1; j >= 0; j--) {
if (arr[i] == arr[j]) {
bl = 0; //print 'false'
}
}
if (bl) { printf("%d\t\t%d\n", arr[i], count); }
}

return 0;
}

关于计算并删除数组 c 中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33706724/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com