Reputation: 53
I have entered 4 numbers into an array using
for (int i=0;i<4;i++)
{
cin >> choice[i];
}
I need to check whether i have entered numbers 1,3,4,6(in any order) into the array
eg:-
if choice[0] == 1 && choice[1] == 3 && choice[2] == 4 && choice[3] == 6
else if ........ 1,3,6,4
else if..........1,6,3,4
else if.......1,6,4,3
else if......1,4,6,3
else if......1,4,3,6
....
....
else if.....6,4,3,1
this type of checking makes my code too big.
Please help me with an alternative way
Upvotes: 0
Views: 132
Reputation: 217135
You may use something like:
std::vector<int> choice(4);
for (int i = 0; i < 4; ++i)
{
std::cin >> choice[i];
}
std::sort(std::begin(choice), std::end(choice));
if (choice == std::vector<int>{1, 3, 4, 6}) { // 1, 3, 4, 6 should be sorted.
// equal
}
Upvotes: 0
Reputation: 38919
Use std::is_permutation
:
int choice[4];
for (int i=0;i<4;i++)
{
cin >> choice[i];
}
std::cout << std::is_permutation(std::begin(choice), std::end(choice), std::vector<int>{1, 3, 4, 6}.begin()) << std::endl;
Upvotes: 5
Reputation: 12391
bool count1=false;
bool count2=false;
bool count3=false;
bool count4=false;
for (int i=0;i<4;i++)
{
cin >> choice[i];
if(choice[i]==1) count1==true;
else if(choice[i]==3) count2=true;
else if(choice[i]==4) count3=true;
else if(choice[i]==6) count4=true;
}
if(count1 && count2 && count3 && count4) cout<<endl<<"yes, it is!";
Upvotes: 3