Reputation: 41
I'm trying to make a function that if there are any duplicated numbers in an array, then return 'false'.(I was working to make lotto program and it doesn't have any duplicated numbers.) I made a code to solve that, but the problem I have is that there goes an infinite loop in a main. The problem was that if I execute that 'check' function, there would be a possibility that 'a[1] == a[1]' will happen, then the code will fall into an infinite loop(it will continue to return only false). Then, my code will have an infinite loop. How can I fix my function appropriately?
#include <iostream>
#include <ctime>
#include <array>
#include <cstdlib>
using namespace std;
bool check(const int a[], int size, int num) {
for (int i{ 0 }; i < size - 1; i++) {
for (int j{ 1 }; j < size; ++j) {
if (a[i] == a[j]) {
return false;
}
}
}
return true;
}
int main() {
int lotto[6]{ 0 };
const int size = 6;
srand(static_cast<unsigned int>(time(0)));
for (int i{ 0 }; i < size; i++) {
int num = rand() % 45 + 1;
lotto[i] = num;
}
bool a{ false };
while (a != true) {
a = check(lotto, size, 1);
if (a == false) {
for (int i{ 0 }; i < size; i++) {
int new_num = rand() % 45 + 1;
lotto[i] = new_num;
}
}
else if (a == true)
break;
}
my_sort(lotto, size);
for (int j{ 0 }; j < size; j++) {
cout << lotto[j] << " ";
}
cout << endl;
return 0;
}
I had tried to solve my problem like this,
bool check(const int a[], int size, int num) {
for (int i{ 0 }; i < size - 1; i++) {
for (int j{ 1 }; j < size; ++j) {
if (i == 0) { int j = 1; }
if (i == 1) { int j = 2; }
if (i == 2) { int j = 3; }
if (i == 3) { int j = 4; }
if (i == 4) { int j = 5; }
if (i == 5) { int j = 6; }
if (a[i] == a[j]) {
return false;
}
}
}
return true;
}
but it still doesn't work :(. It would be my pleasure to teach me how to fix my 'check' function.
Upvotes: 0
Views: 201
Reputation: 21220
Your algorithm runs over all elements and compare each element with all the rest elements as long as you find two equal elements. However you always start the inner loop from value 1
and on the second iteration you will compare the second element with itself. That's where case a[1] == a[1]
comes from. To fix it you might write it like:
bool check(const int a[], int size, int num)
{
for (int i = 0; i < size - 1; i++) {
for (int j = i + 1; j < size; ++j) {
//-------^^^^^
if (a[i] == a[j]) {
return false;
}
}
}
return true;
}
An alternative solution might look like:
bool check(const int a[], int size, int num)
{
std::unordered_set<int> uniqueItems;
for (int j = 0; j < size; ++j)
{
auto res = uniqueItems.emplace(a[j]);
if (!res.second) {
// The item wasn't inserted as it's already in the set
return false;
}
}
return true;
}
Upvotes: 1