Reputation: 1
I need to write a function that will compare two arrays, its for comparing a lottery ticket's numbers to the winning numbers, and it needs to return 1 for every number that matches and a 0 for every number that doesnt match. I use two arrays to store the numbers but i am having difficulties printing out the nonmatched ones correctly, this is the little program i wrote i cant figure out how to put the part that prints the 0 for a non matched element
int main() {
int i,j;
int flag=0;
int a[]={3,49,25,48,12,33};
int b[]={3,48,15,33,12,44};
for( i=0;i<6;i++){
for( j=0;j<6;j++){
if(a[i]==b[j]){
cout<<"1 "<<endl;
break;
}
else flag=1;
}
}
if(flag==1){
cout<<0;
}
return 0;
}
Upvotes: 0
Views: 2678
Reputation: 2684
This wont be the more efficient way to do it, but I hope that the following is an easy to understand solution, and that it serve you as a introduction to some useful tools in C++, which are for example the std::vector
containers, which you should learn:
#include <iostream>
#include <vector>
int main() {
std::vector<std::size_t> a={3,49,25,48,12,33};
std::vector<std::size_t> b={3,48,15,33,12,44};
std::size_t size (a.size());
std::vector<std::size_t> count_correct;
for( std::size_t i=0;i<size;i++) {
for( std::size_t j=0;j<size;j++){
if(a[i]==b[j]){
count_correct.push_back(1);
break;
}
}
}
for (std::size_t i(0); i<count_correct.size(); ++i) {
std::cout << "1" << std::endl;
}
std::size_t incorrect_times (size - count_correct.size());
for (std::size_t i(0); i<incorrect_times; ++i) {
std::cout << "0" << std::endl;
}
return 0;
}
Upvotes: 0
Reputation: 25526
Decide in the inner loop, if 0 or 1 has to be printed, but print out in outer loop:
for(i)
{
char c = '0';
for(j)
{
if(==)
{
c = '1';
break;
}
}
std::cout << c << ' ';
Upvotes: 1
Reputation: 409196
First of all you need to decide which of the number arrays is the "draw" and which is the "ticket". Better and more descriptive naming helps there.
Then you add a third bool
array, corresponding to the "ticket" array, and initialize all elements to false
. When you iterate over the number arrays, and the comparison is true
then you set the corresponding element of the bool
array to true
.
After the comparison, the bool
array will contain true
elements for each number of the "ticket" that matched a number of the "draw".
Disclaimer: This is only one of many possible solutions. It's maybe not the best, and maybe not exactly what you want.
Upvotes: 1