将相关数组格式化为其他数组C [英] Formatting arrays in corelation to ther arrays C

查看:55
本文介绍了将相关数组格式化为其他数组C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个能够识别 Winning_order 数组整数是否在 Order1,Order2,Order3 中的函数.在 Order1 中,第一行 Winning_order 出现在 {1,2,3} 中,也出现在 order2 中.但是,在 Order3 中,没有一个元素与 Winning_order 的值相关,因此它不是有效的输出.

I am trying to make a function that is able to recognize if Winning_order arrays integers are within Order1,Order2,Order3. In Order1 the first row of Winning_order is present {1,2,3} as well as in order2. However in Order3 none of the elements correlate to the values of Winning_order so it is not a valid output.

int main(void)
{
  int Order1[5] = {1,2,3}
  int Order2[5] = {1,2,5,3}
  int Order3[5] = {1,2,5}
  int Winning_order[5][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}};
  
  return 0;
}

预期输出:

Order1
Order2

推荐答案

首先,正如@Jack Lilhammers指出的那样,如果我们可以假设我们了解您要完成的工作,那么您的预期输出是不正确的:您的问题本质上是检查如果数组是数组数组的元素.

Firstly, as @Jack Lilhammers pointed out, your expected output is incorrect if we can assume we understand what you are trying to accomplish: Your problem is essentially to check if an array is an element of an array-of-arrays.

可以这样实现:

#include <stdio.h>

int is_array_element(int rows, int columns, int arr1[rows][columns],
                     int arr2[columns]) {

    for(int i = 0; i < rows; i++) {
        for(int j = 0; j < columns; j++) {
            if(arr1[i][j] != arr2[j]) {
                break;
            }
            if(j == columns - 1) {
                return 1;
            }
        }
    }
    return 0;
}

int main(void) {

    /* as Order1 and Order3 have been declared as 5-arrays but are only
    initialized with 3 integers, the remaining two elements are zero and
    can (should) be ignored */
    int Order1[5] = {1, 2, 3};
    /* not clear how you wish to compare a 4-array with a 3-array and so
    the code will clip the last element */
    int Order2[5] = {1, 2, 5, 3};
    int Order3[5] = {1, 2, 5};

    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}
                              };
    
    if(is_array_element(8, 3, Winning_order, Order1)) {
        printf("Order1\n");  
    }
    if(is_array_element(8, 3, Winning_order, Order2)) {
        printf("Order2\n");  
    }
    if(is_array_element(8, 3, Winning_order, Order3)) {
        printf("Order3\n");  
    }
    return 0;
}

我们得到的输出是:

Order1

这篇关于将相关数组格式化为其他数组C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆