I need a function to check if a number is repeated in a 3x3 multidimensional array for a college project.
Asked
Active
Viewed 110 times
-3
-
1Can you show the program you've already written, and explain how exactly your program doesn't work or doesn't produce the expected results? You have to show your work first; it must meet all requirements for a [mre]; and it must be a good-faith real attempt to implement your program and not a few token lines of code, before asking for help on stackoverflow.com. stackoverflow.com is a question and answer site *but we don't write code for other people*, here. For more information, see [ask] questions, take the [tour], and read the [help]. – Sam Varshavchik Dec 30 '20 at 15:52
1 Answers
0
A matrix is a fancy word for a 2D array, and a 2D array is a fancy word for an array (only longer). The naive approache would be to scan the array for each value and then see if there are duplicates in it, so for example something like (first "convert" your matrix to a 1D array)
for (int i = 0; i< arr.size(); i++) {
for (int j = i + 1; j < arr.size(); j++)
if (arr[i] == arr[j])
return true; // found duplicate.
The problem here, of course, is that the complexity is O(n^2).
We can do much better if we first sort the array (using merge) which will cost O(nlogn) and than the algorithm will be somwhat like this :
for (int i = 0; i < arr.size() - 1; i++)
if (arr[i] == arr[i+1])
return true;
Check here for more information.

Eminem
- 143
- 6