nkom
nkom

Reputation: 29

C: Check if a two-dimensional array is on descending order excluding 0

I need to check if a two-dimensional array is in descending order.

I wrote a soultion but not satisfied with it. Here is my working code:

bool sorted(void)
{
    int prev = board[0][0];
    int counter = 0;
    for (int i = 0; i < d; i++){
        for (int j = 0; j < d; j++){
            if (board[i][j] < prev){
                return false;
            }
            prev = board[i][j];
            counter++;
            if (counter == d * d - 1 ){
                return true;
            }
        }
    }
    return true;
}

I am looking for a way to use only conditionals, without a counter. Here is what I tried:

bool sorted(void)
{
    int prev = board[0][0];
    for (int i = 0; i < d; i++){
        for (int j = 0; j < d; j++){
            if (board[i][j] < prev && board[i][j] != 0){
                return false;
            }
            prev = board[i][j];
        }
    }
    return true;
}

This doesn't work. Assuming the array is sorted, without

 && board[i][j] != 0

as soon as the last element is checked, I get false, because 0 < 1.

I almost wrecked my head. Could you give some ideas, please? Thanks!

Upvotes: 0

Views: 71

Answers (2)

Bob__
Bob__

Reputation: 12779

You can solve your problem changing the initial value of prev:

#include <limits.h>                   // for INT_MIN

// ...

bool sorted(void)
{
    int prev = INT_MIN;               // <-- initialize with the lowest possible value
    for (int i = 0; i < d; i++){
        for (int j = 0; j < d; j++){
            if (board[i][j] < prev){
                return false;
            }
            prev = board[i][j];
        }
    }
    return true;
}

Upvotes: 1

darkknight
darkknight

Reputation: 216

Try the following:

bool sorted(void)
{
    int prev = board[0][0];
    for (int i = 0; i < d; i++){
        for (int j = 0; j < d; j++){
            if (board[i][j] < prev && board[i][j] != 0){
                return false;
            }
        }
       prev = board[i][j];
    }
return true;
}

Upvotes: 2

Related Questions