ege Selcuk
ege Selcuk

Reputation: 235

Checking for numbers within arrays in C

The function below is looking through Order1-3 and looks if any of the elements are within each of the 3 column values of each of the 8 rows inside Winning_order. So in this case Order1 values are within the first row of Winning_order so it comes out as true as well as Order2. However Order2 is not a valid output for the program, how can I modify the iterating function below so that it checks to be true. Order3 is meant to be a false as well since its not within Winning_order. The code has been gotten from the answer of this issue issue.

#include <stdio.h>

// Iterating function 
int match_arrays(int *arr1, int *arr2, int len)
{
  for (int i = 0; i < len; i++) {
    if (arr1[i] != arr2[i]) {
      return 0;
    }
  }
  return 1;
}

// Main function 
int main(void)
{
  int Order1[3] = {1,5,9};
  int Order2[4] = {1,2,5,3};
  int Order3[3] = {4,4,4};
  int Winning_order[8][3] = {{1,2,3}, {4,5,6}, {7,8,9},{1,4,7},{2,5,8},{3,6,9},{1,5,9},{3,5,7}};

  for (int i = 0; i < 5; i++) {
    if (match_arrays(Order1, Winning_order[i], 3)) {
      printf("Order1");
    }
    if (match_arrays(Order2, Winning_order[i], 3)) {
      printf("Order2");
    }
    if (match_arrays(Order3, Winning_order[i], 3)) {
      printf("Order3");
    }
  }
  return 0;
}

Expected Output

Order 1 Order 2

Upvotes: 1

Views: 73

Answers (1)

Mr. Chip
Mr. Chip

Reputation: 126

This matching method will output

Order2Order1

Could you explain some detail why Order2 will be true?

#include <stdio.h>

int match_arrays(int* arr_order, int* arr_win, int len_order, int len_win)
{
    int idx = 0;
    int err = 0;
    for (int i = 0; i < len_order; i++) {
        if (arr_order[i] != arr_win[idx]) {
            err++;
            if (err > len_order - len_win) {
                return 0;
            }
        } else {
            idx++;
            if (idx == len_win)
            {
                return 1;
            }
        }
    }
    return 1;
}

int main()
{

    int Order1[3] = {1, 5, 9};
    int Order2[4] = {1, 2, 5, 3};
    int Order3[3] = {4, 4, 4};
    int Winning_order[8][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {1, 4, 7}, {2, 5, 8}, {3, 6, 9}, {1, 5, 9}, {3, 5, 7}};

    for (int i = 0; i < 8; i++) {
        if (match_arrays(Order1, Winning_order[i], 3, 3)) {
            printf("Order1");
        }
        if (match_arrays(Order2, Winning_order[i], 4, 3)) {
            printf("Order2");
        }
        if (match_arrays(Order3, Winning_order[i], 3, 3)) {
            printf("Order3");
        }
    }
    return 0;

}

Upvotes: 1

Related Questions