- #1
Jamin2112
- 986
- 12
I had an interview the other day and the lady was asking me about different ways to find whether there are any repeated elements in an array. At the end of the interview she told me to send her a code sample showing how to implement two of the ways we discussed. I thought that what I wrote was pretty straightforward, but I ended up not getting another interview (possibly for another reason). I'm wondering whether my code shows any indications that I'm a stylistic amateur or whether anything is downright wrong.
Code:
#include <algorithm>
#include <string>
#include <iostream>
using namespace std;
// This function returns true if the input array arr of length n, with values known to be in the
// range between floor and ceiling inclusive, contains any repeated elements.
bool contains_repeats(int* arr, int n, int floor, int ceiling) {
bool binaryMask[ceiling - floor + 1];
for (int i = 0; i < n; i++) {
if (binaryMask[ceiling - arr[i]]) {
return true;
} else {
binaryMask[ceiling - arr[i]] = 1;
}
}
return false;
}
// An overloading of the previous function uses quicksort and then checks whether any adjacent
// elements are equal.
bool contains_repeats(int* arr, int n) {
sort(arr, arr + n);
for (int i = 0; i < n - 1; i++) if (arr[i] == arr[i+1]) return true;
return false;
}
int main(int argc, char* argv[]) {
// Example of implemenation for the binary mask:
int numbers[] = {1, 3, 5, 1, 30, 4, 38, 94, 14, 41, 40, 69, 15, 11, 33, 3};
int low = 0;
int high = 100;
cout << "Are there any repeated elements?\n";
string answer = contains_repeats(numbers, sizeof(numbers)/sizeof(int), low, high) ? "Yes." : "No.";
cout << answer << endl;
// Example of implemenation using quicksort:
cout <<"Let's see if we get the same answer from the other procedure ...\n";
answer = contains_repeats(numbers, sizeof(numbers)/sizeof(int)) ? "Yes." : "No.";
cout << answer;
}