Reputation: 1210
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.
If anyone got a nicer and better way to do this, please reply.
Upvotes: 1
Views: 209
Reputation: 10613
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.
If you want something for a more limited domain or a more targeted solution, then others have given you some good hints.
Upvotes: 0
Reputation: 178441
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
//....
Upvotes: 6
Reputation: 2041
Have they to be next to each other? Then You would only need a flag 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.
Upvotes: 0
Reputation: 58271
I would like to use switch-case as:
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
}
Upvotes: 3