简体   繁体   English

比较数组中的三个数字

[英]comparing three numbers in an array

im looking for nice and clean way to see if there are three equal numbers in an array. 我正在寻找一种干净的方法来查看数组中是否有三个相等的数字。

Right now i have this: 现在我有这个:

for (int i = 0; i < nr ; i++)
{
    if(a[i] == 1){one++;}
    else if(a[i] == 2){two++;}
    else if(a[i] == 3){three++;}
    else if(a[i] == 4){four++;}
    else if(a[i] == 5){five++;}
    else if(a[i] == 6){six++;}
}

if(one >= 3){
    printf("Tre tal finns i ettor, 3p\n");
}else if(two >= 3){
    printf("Tre tal finns i tvår, 6p\n");
}else if(three >= 3){
    printf("Tre tal finns i treor, 9p\n");
}else if(four >= 3){
    printf("Tre tal finns i fyror, 12p\n");
}else if(five >= 3){
    printf("Tre tal finns i femmor, 15p\n");
}else if(six >= 3){
    printf("Tre tal finns i sexor, 18p\n");
}

Where a (integer) is an array of 5 elements(containing elemets 1-6) and "nr" is an variable to keep track for the arrays length. 其中(整数)是一个由5个元素组成的数组(包含元素1-6),而“ nr”是一个变量,用于跟踪数组的长度。

If anyone got a nicer and better way to do this, please reply. 如果有人有更好更好的方法,请回复。

Generalize it for a histogram , and basically do the first step of counting sort : 将其归纳为直方图 ,并基本上进行计数排序的第一步:

int histogram[n]; //variable length array are fine in c99, if using older c - malloc
for (int i = 0; i < n; i++) histogram[i] = 0; //init
for (i = 0; i < nr; i++)
   histogram[a[i]]++;
for (i = 0; i < n; i++)
   if (histogram[i] >= 3) //found it
//....    

I would like to use switch-case as: 我想将switch-case用作:

switch((a[i]){
 case 1: one++;
         break;
 case 2: two++;
         break;
 case 3: three++;
         break;
 case 4: four++;
         break;
 case 5: five++;
         break;
 case 6: six++;
         break;
 //default: if you want to add 
}

Have they to be next to each other? 他们必须彼此相邻吗? Then You would only need a flag var. 然后,您只需要标记var。

Indeed, if It doesn't care to You if You've more than a number repeated but just know them exist, it'll be better. 确实,如果您不希望重复的数目多于一个,但只知道它们存在,那会更好。

If you want a truly general solution then sort your input array; 如果您想要一个真正通用的解决方案,则对输入数组进行排序; once sorted, finding all instances where a number appears more than n times, for whatever n you want, becomes trivial. 一旦排序,找到一个数字出现n次以上的所有实例,无论您想要什么n ,都变得微不足道。

If you want something for a more limited domain or a more targeted solution, then others have given you some good hints. 如果您想为更有限的领域或更具针对性的解决方案提供帮助,那么其他人给了您一些很好的提示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM