0

I'm trying to check if an array's values are in the correct order. For example if, I want to check if an array is in the order `{1,2,3,4,5,6,7} or even a different order such as{1,2,4,3,5,6,7}, {1,4,2,3,5,6,7}, (4,1,2,3,5,6,7},{1,2,3,5,4,6,7},{1,2,3,5,6,4,7},etc.

I had tried this and it didn't work:

int board[7]= {1,2,3,4,5,6,7};
if(board[] = {1,2,3,4,5,6,7})
    return true;

Is there a way to apply this concept?

3 Answers3

1

You'll have to go over the array. E.g.:

for (int i = 1; i < 7; ++i) {
    if (board[i] < board[i - 1]) {
        return false;
    }
}
return true;
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • my problem is that i dont only want to do this when it's in numerical order it could be any one of these {1,2,4,3,5,6,7}, {1,4,2,3,5,6,7}, (4,1,2,3,5,6,7},{1,2,3,5,4,6,7},{1,2,3,5,6,4,7}.etc – Deven Coleman Nov 30 '20 at 23:25
  • 1
    @DevenColeman please edit your question and explain what exactly you're trying to achieve. – Mureinik Nov 30 '20 at 23:26
  • 1
    @DevenColeman Ok, then the duplicate target seems correct. Please read that and edit the question if your question is different. – cigien Nov 30 '20 at 23:27
1

It appears you're looking for std::is_sorted:

return std::is_sorted(std::begin(board), std::end(board));
cigien
  • 57,834
  • 11
  • 73
  • 112
0

you can use std::equal from standard library

#include <iostream>
#include <algorithm>

int main()
{
    int tab1[] = {1,2,3,4,5,6,7,8,9};
    int tab2[] = {1,2,3,4,5,6,7,8,9};

    if( std::equal( std::begin(tab1), std::end(tab1), std::begin(tab2), std::end(tab2) ) )
    {
        std::cout << "tables are equal" << std::endl;
    }
    return 0;
}

If you use c++20, this code become cleaner:

#include <iostream>
#include <algorithm>

int main()
{
    int tab1[] = {1,2,3,4,5,6,7,8,9};
    int tab2[] = {1,2,3,4,5,6,7,8,9};

    if(std::ranges::equal( tab1, tab2))
    {
        std::cout << "tables are equal" << std::endl;
    }
    return 0;
}
WBurzynski
  • 21
  • 3