For a function of the form.
bool contains_equal_rows(int height, int width, const int ar[height][width])
How do I find if a row is repeated? I can see how you can set a bool to true
if a row is repeated, but how do you avoid returning false
too early?
Problem description:
Write a function that gets a 2-d array of given dimensions of ints.
It returns true if the array contains two rows with exactly the same values in the same order, and returns false otherwise.bool contains_equal_rows( int height, int width, const int ar[height][width])
Examples:
On input
{{1,2,3,4}, {2,3,4,1}, {1,2,3,4}}
it returns true.
On input
{{1,2,3,4}, {2,3,4,5}, {3,4,5,6}}
it returns false.
On input
{{1,1,1,1}, {2,2,2,2}, {1,1,1,6}}
it returns false.
My attempt so far:
bool contains_equal_rows(int height, int width, const int array[height][width])
{
int w = width;
int h = height;
bool test = false;
bool matchedRow = false;
for(int m = 0; m < h; m++)
{
for(int n = 0; n < w; n++)
{
if( array[m][n] == array[m][n-1] )
{
test = true;
}
else
{
test = false;
}
}
if(test == true)
{
matchedRow = true;
}
}
return matchedRow;
}
The problem with my code is that I'm only comparing a row with the one before it, and can't figure out how to compare one row with all.
Expected results as shown in description.
You should start your outer loop from 1.
And in your inner loop compare array[0]
against array[m]
,
before entering into the inner most loop set test to false
as soon as test is true you can break out of both loops and return true.
You could add another for-loop:
For each row `i`:
For every other row `j`:
For each column `k` compare `array[i][k]` and `array[j][k]`
Something like this for example:
int w = width;
int h = height;
boolean test = false;
for(int i = 0; i < h; i++)
{
for(int j = i+1; j < h; j++) {
test = true;
for(int k = 0; k < w; k++)
{
if( array[i][k] != array[j][k] )
{
test = false;
}
}
if(test == true)
{
return true;
}
}
}
return false;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With