C의 2D 배열 안에 두 개의 동일한 열의 개별 요소를 표시하는 방법

IonC

내 임무는 두 개의 동일한 열을 찾고 각 요소를 2D 배열로 표시하는 것입니다. 그 후 동일한 열 중 하나를 오름차순으로 정렬하고 다른 하나는 내림차순으로 정렬해야합니다. 동일한 열을 찾기위한 코드를 작성했지만 발견 된 열의 개별 요소를 표시하는 데 많은 문제가 있습니다. show_columns()에서와 같이 함수 내부의 요소 를 열 형식 으로 표시하는 것을 선호합니다 declaration().

팁을 찾고

#include <stdio.h>
#include <stdbool.h>

void declaration(int a[100][100], int n) {
    int i, j;

    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            printf("a[%i][%i]=", i, j);
            scanf("%i", &a[i][j]);
        }
    }

    printf("\nThe matrix is : \n");
    for (i = 0; i < n; i++) {
        printf("\n");
        for (j = 0; j < n; j++) {
            printf("%d\t", a[i][j]);
       }
    }
    printf("\n\n");
}

bool columns(int rows, int cols, int i, int j, int a[rows][cols]) {
    for (int k = 0; k < rows; k++) {
        if (a[k][i] != a[k][j]) {
            return false;
        }
    }
    return true;
}

void show_columns(int rows, int cols, int a[rows][cols]) {
    for (int i = 0; i < cols; i++) {
        for (int j = i + 1; j < cols; j++) {
            if (columns(rows, cols, i, j, a)) {
                printf("\nThe columns %i si %i are identical\n", i, j);
            }
        }
    }
}

int main() {
    int a[100][100], n;
    int k;

    printf("Enter n:");
    scanf("%i", &n);

    int rows = n, cols = n;

    declaration(a, n);

    show_columns(rows, cols, a);

    return 0;
}
크레이그 에스티

누군가가 bool 함수에 의지하지 않고 배열에서 동일한 열을 찾는 데 도움을 줄 수 있다면 도움이 될 것입니다.

음, 가능할 수도 있지만 bool 함수가 핵심입니다 (예 : 두 개의 다른 열이 일치하면 true를 반환하는 함수).

그러나 모든 일치 항목을 찾으려면 다른 기능이 필요합니다. 고유 한 열 쌍을 반복하고 일치 함수를 호출하여 두 열이 일치하는지 확인해야합니다.

검색 인덱스와 최대 지오메트리를 추적하는 "반복자"구조체를 정의하는 데 도움이됩니다.


여기에 [완전히] 리팩토링 된 버전이 있습니다. 임의의 동일한 열이있는 임의 행렬을 생성하는 진단 테스트가 있습니다. 모든 열 쌍을 반복하고 일치하는 고유 한 열 번호를 인쇄합니다.

열을 정렬 하지 않습니다 . 이것은 독자를위한 연습 문제로 남겨졌습니다.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

unsigned int opt_R;
int opt_M;

typedef struct {
    int maxrow;                         // maximum number of rows
    int maxcol;                         // maximum number of columns
    int lcol;                           // starting left column
    int rcol;                           // starting right column
    int match;                          // 1=match
} search_t;

#define MAXROW      100
#define MAXCOL      100

int arrbig[MAXROW][MAXCOL];

// search_init -- initialize for full matrix search
void
search_init(search_t *srch,int maxrow,int maxcol)
{

    srch->maxrow = maxrow;
    srch->maxcol = maxcol;

    srch->lcol = 0;
    srch->rcol = 1;
}

// search_match -- decide if two given columns match
// RETURNS: 1=match
int
search_match(int lcol,int rcol,int maxrow,int arr[MAXROW][MAXCOL])
{
    int match = 0;

    for (int irow = 0;  irow < maxrow;  ++irow) {
        match = (arr[irow][lcol] == arr[irow][rcol]);
        if (! match)
            break;
    }

    return match;
}

// search_next -- advance to next search starting point
// RETURNS: 1=more to do
int
search_next(search_t *srch)
{
    int maxcol = srch->maxcol;

    srch->rcol += 1;

    if (srch->rcol >= maxcol) {
        srch->lcol += 1;
        srch->rcol = srch->lcol + 1;
    }

    return (srch->lcol < (maxcol - 1));
}

// search_find -- find next column pair that matches
int
search_find(search_t *srch,int arr[MAXROW][MAXCOL])
{
    int lcol = srch->lcol;
    int rcol = srch->rcol;
    int maxrow = srch->maxrow;
    int maxcol = srch->maxcol;
    int match = 0;

    while (lcol < (maxcol - 1)) {
        for (;  rcol < maxcol;  ++rcol) {
            match = search_match(lcol,rcol,maxrow,arr);
            if (match)
                break;
        }
        if (match)
            break;

        if (! search_next(srch))
            break;

        rcol = srch->rcol;
        lcol = srch->lcol;
    }

    srch->lcol = lcol;
    srch->rcol = rcol;
    srch->match = match;

    return match;
}

// dojoin -- ensure unique pairing
void
dojoin(const search_t *srch,int arr[MAXROW][MAXCOL])
{
    int lcol;
    int rcol;
    search_t *uniq;
    search_t uniqlist[opt_M];

    // make certain columns identical
    for (int iter = 0;  iter < opt_M;  ++iter) {
        while (1) {
            // get two different column numbers
            while (1) {
                lcol = rand() % srch->maxcol;
                rcol = rand() % srch->maxcol;
                if (lcol != rcol)
                    break;
            }

            // we want low/high
            if (lcol > rcol) {
                int tmp = lcol;
                lcol = rcol;
                rcol = tmp;
            }

            // have we set this before?
            int match = 0;
            for (int uniqidx = 0;  uniqidx < iter;  ++uniqidx) {
                uniq = &uniqlist[uniqidx];
                match = ((lcol == uniq->lcol) && (rcol == uniq->rcol));
                if (match)
                    break;
            }

            // got a _unique_ pair of column numbers
            if (! match) {
                uniq = &uniqlist[iter];
                uniq->lcol = lcol;
                uniq->rcol = rcol;
                break;
            }
        }

        // copy from one column to another
        for (int irow = 0;  irow < srch->maxrow;  ++irow)
            arr[irow][rcol] = arr[irow][lcol];

        printf("dojoin: EXPECTED %d,%d\n",lcol,rcol);
    }
}

// dotest -- perform test
void
dotest(int arr[MAXROW][MAXCOL])
{
    search_t srch;

    // NOTE: a smaller geometry can be used if desired
    search_init(&srch,MAXROW,MAXCOL);

    // create random matrix
    for (int irow = 0;  irow < srch.maxrow;  ++irow) {
        for (int icol = 0;  icol < srch.maxcol;  ++icol)
            arr[irow][icol] = rand();
    }

    // create columns that are the same
    dojoin(&srch,arr);

    // search entire matrix looking for matching columns
    for (int iter = 0;  iter < (opt_M * 2);  ++iter) {
        int match = search_find(&srch,arr);
        if (! match)
            break;

        printf("dotest: ACTUAL %d,%d\n",srch.lcol,srch.rcol);

        if (! search_next(&srch))
            break;
    }
}

int
main(int argc,char **argv)
{

    --argc;
    ++argv;

    for (;  argc > 0;  --argc, ++argv) {
        char *cp = *argv;
        if (*cp != '-')
            break;

        cp += 2;
        switch (cp[-1]) {
        case 'M':
            opt_M = (*cp != 0) ? atoi(cp) : (MAXCOL / 4);
            break;
        case 'R':
            opt_R = (*cp != 0) ? atoi(cp) : 1;
            break;
        }
    }

    // by printing the random seed value, and using -R on a subsequent program
    // invocation, we can make the result repeatable
    if (opt_R == 0)
        opt_R = time(NULL);
    printf("R: %u\n",opt_R);
    srand(opt_R);

    // set number of matching columns
    if (opt_M == 0)
        opt_M = 5;

    dotest(arrbig);

    return 0;
}

다음은 -R1612382146. 동일한 열이 여러 개 있습니다.

R: 1612382146
dojoin: EXPECTED 12,99
dojoin: EXPECTED 2,74
dojoin: EXPECTED 18,91
dojoin: EXPECTED 18,34
dojoin: EXPECTED 64,93
dotest: ACTUAL 2,74
dotest: ACTUAL 12,99
dotest: ACTUAL 18,34
dotest: ACTUAL 18,91
dotest: ACTUAL 34,91
dotest: ACTUAL 64,93

다음은 더 많은 무작위 출력입니다.

R: 1612387497
dojoin: EXPECTED 35,72
dojoin: EXPECTED 72,82
dojoin: EXPECTED 60,93
dojoin: EXPECTED 34,45
dojoin: EXPECTED 79,90
dotest: ACTUAL 34,45
dotest: ACTUAL 35,72
dotest: ACTUAL 35,82
dotest: ACTUAL 60,93
dotest: ACTUAL 72,82
dotest: ACTUAL 79,90

R: 1612387500
dojoin: EXPECTED 14,68
dojoin: EXPECTED 60,80
dojoin: EXPECTED 22,84
dojoin: EXPECTED 11,15
dojoin: EXPECTED 1,52
dotest: ACTUAL 1,52
dotest: ACTUAL 11,15
dotest: ACTUAL 14,68
dotest: ACTUAL 22,84
dotest: ACTUAL 60,80

R: 1612387503
dojoin: EXPECTED 40,42
dojoin: EXPECTED 16,29
dojoin: EXPECTED 8,69
dojoin: EXPECTED 23,74
dojoin: EXPECTED 44,67
dotest: ACTUAL 8,69
dotest: ACTUAL 16,29
dotest: ACTUAL 23,74
dotest: ACTUAL 40,42
dotest: ACTUAL 44,67

R: 1612387506
dojoin: EXPECTED 20,32
dojoin: EXPECTED 36,59
dojoin: EXPECTED 9,36
dojoin: EXPECTED 20,48
dojoin: EXPECTED 38,48
dotest: ACTUAL 9,36
dotest: ACTUAL 20,32
dotest: ACTUAL 38,48

R: 1612387508
dojoin: EXPECTED 40,71
dojoin: EXPECTED 34,84
dojoin: EXPECTED 53,72
dojoin: EXPECTED 8,73
dojoin: EXPECTED 17,75
dotest: ACTUAL 8,73
dotest: ACTUAL 17,75
dotest: ACTUAL 34,84
dotest: ACTUAL 40,71
dotest: ACTUAL 53,72

최신 정보:

다음 struct은 별도의 배열 포인터 인수가 필요하지 않도록 모든 정보를에 넣는 버전입니다 .

다음과 같은 형식의 다차원 배열을 지원하기 위해 특별한 "배열 포인터"를 사용합니다.

int (*arr)[MAXCOL];

참조 : C 포인터 배열 / 포인터 배열 명확화

이렇게하면 임의 / 동적 배열 차원이있는 배열에 대한 올바른 인덱싱이 유지됩니다.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

unsigned int opt_R;
int opt_M;
int opt_W;
int opt_H;

typedef struct {
    int maxrow;                         // maximum number of rows
    int maxcol;                         // maximum number of columns
    int *arr;                           // array base

    int lcol;                           // starting/current left column
    int rcol;                           // starting/current right column

    int match;                          // 1=match
} search_t;

#define ARRDEF \
    int (*arr)[srch->maxcol] = (__typeof__(arr)) srch->arr

#define MAXROW      100
#define MAXCOL      100

// search_init -- initialize for full matrix search
void
search_reset(search_t *srch)
{

    srch->lcol = 0;
    srch->rcol = 1;
}

// search_init -- initialize for full matrix search
search_t *
search_init(int maxrow,int maxcol)
{
    search_t *srch;

    srch = calloc(1,sizeof(*srch));

    srch->maxrow = maxrow;
    srch->maxcol = maxcol;

    srch->arr = malloc(sizeof(*srch->arr) * maxrow * maxcol);

    search_reset(srch);

    return srch;
}

// search_free -- free up array
void
search_free(search_t *srch)
{

    free(srch->arr);
    free(srch);
}

// search_match -- decide if two given columns match
// RETURNS: 1=match
int
search_match(const search_t *srch)
{
    ARRDEF;
    int match = 0;
    int lcol = srch->lcol;
    int rcol = srch->rcol;

    for (int irow = 0;  irow < srch->maxrow;  ++irow) {
        match = (arr[irow][lcol] == arr[irow][rcol]);
        if (! match)
            break;
    }

    return match;
}

// search_next -- advance to next search starting point
// RETURNS: 1=more to do
int
search_next(search_t *srch)
{
    int maxcol = srch->maxcol;

    srch->rcol += 1;

    if (srch->rcol >= maxcol) {
        srch->lcol += 1;
        srch->rcol = srch->lcol + 1;
    }

    return (srch->lcol < (maxcol - 1));
}

// search_find -- find next column pair that matches
int
search_find(search_t *srch)
{
    int maxcol = srch->maxcol;
    int match = 0;

    while (srch->lcol < (maxcol - 1)) {
        for (;  srch->rcol < maxcol;  ++srch->rcol) {
            match = search_match(srch);
            if (match)
                break;
        }
        if (match)
            break;

        if (! search_next(srch))
            break;
    }

    srch->match = match;

    return match;
}

// dojoin -- ensure unique pairing
void
dojoin(const search_t *srch)
{
    ARRDEF;
    int lcol;
    int rcol;
    search_t *uniq;
    search_t uniqlist[opt_M];

    // make certain columns identical
    for (int iter = 0;  iter < opt_M;  ++iter) {
        while (1) {
            // get two different column numbers
            while (1) {
                lcol = rand() % srch->maxcol;
                rcol = rand() % srch->maxcol;
                if (lcol != rcol)
                    break;
            }

            // we want low/high
            if (lcol > rcol) {
                int tmp = lcol;
                lcol = rcol;
                rcol = tmp;
            }

            // have we set this before?
            int match = 0;
            for (int uniqidx = 0;  uniqidx < iter;  ++uniqidx) {
                uniq = &uniqlist[uniqidx];
                match = ((lcol == uniq->lcol) && (rcol == uniq->rcol));
                if (match)
                    break;
            }

            // got a _unique_ pair of column numbers
            if (! match) {
                uniq = &uniqlist[iter];
                uniq->lcol = lcol;
                uniq->rcol = rcol;
                break;
            }
        }

        // copy from one column to another
        for (int irow = 0;  irow < srch->maxrow;  ++irow)
            arr[irow][rcol] = arr[irow][lcol];

        printf("dojoin: EXPECTED %d,%d\n",lcol,rcol);
    }
}

// dofill -- fill matrix
void
dofill(const search_t *srch)
{
    ARRDEF;

    for (int irow = 0;  irow < srch->maxrow;  ++irow) {
        for (int icol = 0;  icol < srch->maxcol;  ++icol)
            arr[irow][icol] = rand();
    }
}

// dotest -- perform test
void
dotest(int maxrow,int maxcol)
{
    search_t *srch;

    // NOTE: a smaller geometry can be used if desired
    srch = search_init(maxrow,maxcol);

    // create random matrix
    dofill(srch);

    // create columns that are the same
    dojoin(srch);

    // search entire matrix looking for matching columns
    for (int iter = 0;  iter < (opt_M * 2);  ++iter) {
        int match = search_find(srch);
        if (! match)
            break;

        printf("dotest: ACTUAL %d,%d\n",srch->lcol,srch->rcol);

        if (! search_next(srch))
            break;
    }

    search_free(srch);
}

int
main(int argc,char **argv)
{

    --argc;
    ++argv;

    for (;  argc > 0;  --argc, ++argv) {
        char *cp = *argv;
        if (*cp != '-')
            break;

        cp += 2;
        switch (cp[-1]) {
        case 'M':
            opt_M = (*cp != 0) ? atoi(cp) : (MAXCOL / 4);
            break;

        case 'R':
            opt_R = (*cp != 0) ? atoi(cp) : 1;
            break;

        case 'H':
            opt_H = atoi(cp);
            break;

        case 'W':
            opt_W = atoi(cp);
            break;
        }
    }

    // by printing the random seed value, and using -R on a subsequent program
    // invocation, we can make the result repeatable
    if (opt_R == 0)
        opt_R = time(NULL);
    printf("R: %u\n",opt_R);
    srand(opt_R);

    // set number of matching columns
    if (opt_M == 0)
        opt_M = 5;

    if (opt_H == 0)
        opt_H = MAXROW;
    if (opt_W == 0)
        opt_W = MAXCOL;
    dotest(opt_H,opt_W);

    return 0;
}

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

개별 numpy 배열에서 동일한 값을 가진 numpy 배열의 요소를 그룹화하는 방법

분류에서Dev

한 열에 두 개의 개별 열의 최소 및 최대를 요약하는 방법

분류에서Dev

두 개의 2D 배열에서 개별 요소의 합을 계산하는 방법은 무엇입니까?

분류에서Dev

두 개의 개별 열의 데이터를 동일한 열에 표시하려는 경우

분류에서Dev

2 개의 1d 배열을 하나의 1d 배열로 변환하는 방법 (두 값 모두 하나의 요소 안에 있어야 함)

분류에서Dev

두 개의 배열에 각 요소를 숫자로 곱하는 방법 C ++

분류에서Dev

C ++에서 2D 동적 배열의 1 개 요소에 액세스하는 방법

분류에서Dev

두 개의 span 요소를 개별적으로 동일한 줄에 정렬하는 방법

분류에서Dev

2 개의 배열에서 고유 한 요소를 비교하는 방법

분류에서Dev

두 개의 개별 배열에서 두 개의 키 / 값 쌍으로 객체를 만드는 방법

분류에서Dev

배열의 각 요소를 개별적으로 표시하는 방법

분류에서Dev

Visual C # 두 개의 1D string [] 배열을 하나의 2D string [,] 배열로 병합하는 방법

분류에서Dev

2 개의 개별 객체 / 배열에 동일한 요소가 하나 있고 일치하는 요소가있는 경우 2 개의 객체를 하나의 배열로 연결하는 경우 비교하는 방법은 무엇입니까? 자바 스크립트

분류에서Dev

두 개의 다른 배열에서 동일한 요소를 일치시키는 $ or 연산

분류에서Dev

자바에서 2 개의 문자열 배열을 비교하고 두 배열에서 동일한 요소를 인쇄합니다.

분류에서Dev

2D 배열에 3 개의 동일한 값이 연속으로 있는지 확인하는 방법

분류에서Dev

JavaScript에서 두 개의 2D 배열에서 고유 한 값을 얻는 방법

분류에서Dev

두 개의 2d numpy 배열을 사전 할당 된 배열에 복사하는 방법

분류에서Dev

mysql-동일한 테이블과 열에서 2 개의 다른 요소 수를 합산하여 하나로 표시하는 방법은 무엇입니까?

분류에서Dev

반응 js에서 동일한 배열에 두 개 이상의 응답 데이터를 추가하는 방법

분류에서Dev

내부에 char 요소가있는 2D 배열의 크기를 두 배로 늘리는 방법

분류에서Dev

동일한 테이블에 두 개의 배열 표시

분류에서Dev

두 개의 PySpark 배열을 분해하고 동일한 위치에있는 요소를 유지합니다.

분류에서Dev

동일한 Tkinter Toplevel () 창에 두 개의 이미지를 표시하는 방법

분류에서Dev

자바 : 파일을 두 개의 2D 문자열 배열로 선택적으로 스캔하는 방법

분류에서Dev

동일한 테이블에서 두 개의 개별 열을 계산하고이를 새 열로 합산하는 방법

분류에서Dev

두 개의 numpy 배열에서 일치하는 요소 제거

분류에서Dev

NSMutableArray 배열을 객관적인 C, iOS에서 두 개의 개별 배열 또는 두 개의 가변 배열로 나누는 방법

분류에서Dev

감소 배열 방법에 대한 두 개의 초기 값?

Related 관련 기사

  1. 1

    개별 numpy 배열에서 동일한 값을 가진 numpy 배열의 요소를 그룹화하는 방법

  2. 2

    한 열에 두 개의 개별 열의 최소 및 최대를 요약하는 방법

  3. 3

    두 개의 2D 배열에서 개별 요소의 합을 계산하는 방법은 무엇입니까?

  4. 4

    두 개의 개별 열의 데이터를 동일한 열에 표시하려는 경우

  5. 5

    2 개의 1d 배열을 하나의 1d 배열로 변환하는 방법 (두 값 모두 하나의 요소 안에 있어야 함)

  6. 6

    두 개의 배열에 각 요소를 숫자로 곱하는 방법 C ++

  7. 7

    C ++에서 2D 동적 배열의 1 개 요소에 액세스하는 방법

  8. 8

    두 개의 span 요소를 개별적으로 동일한 줄에 정렬하는 방법

  9. 9

    2 개의 배열에서 고유 한 요소를 비교하는 방법

  10. 10

    두 개의 개별 배열에서 두 개의 키 / 값 쌍으로 객체를 만드는 방법

  11. 11

    배열의 각 요소를 개별적으로 표시하는 방법

  12. 12

    Visual C # 두 개의 1D string [] 배열을 하나의 2D string [,] 배열로 병합하는 방법

  13. 13

    2 개의 개별 객체 / 배열에 동일한 요소가 하나 있고 일치하는 요소가있는 경우 2 개의 객체를 하나의 배열로 연결하는 경우 비교하는 방법은 무엇입니까? 자바 스크립트

  14. 14

    두 개의 다른 배열에서 동일한 요소를 일치시키는 $ or 연산

  15. 15

    자바에서 2 개의 문자열 배열을 비교하고 두 배열에서 동일한 요소를 인쇄합니다.

  16. 16

    2D 배열에 3 개의 동일한 값이 연속으로 있는지 확인하는 방법

  17. 17

    JavaScript에서 두 개의 2D 배열에서 고유 한 값을 얻는 방법

  18. 18

    두 개의 2d numpy 배열을 사전 할당 된 배열에 복사하는 방법

  19. 19

    mysql-동일한 테이블과 열에서 2 개의 다른 요소 수를 합산하여 하나로 표시하는 방법은 무엇입니까?

  20. 20

    반응 js에서 동일한 배열에 두 개 이상의 응답 데이터를 추가하는 방법

  21. 21

    내부에 char 요소가있는 2D 배열의 크기를 두 배로 늘리는 방법

  22. 22

    동일한 테이블에 두 개의 배열 표시

  23. 23

    두 개의 PySpark 배열을 분해하고 동일한 위치에있는 요소를 유지합니다.

  24. 24

    동일한 Tkinter Toplevel () 창에 두 개의 이미지를 표시하는 방법

  25. 25

    자바 : 파일을 두 개의 2D 문자열 배열로 선택적으로 스캔하는 방법

  26. 26

    동일한 테이블에서 두 개의 개별 열을 계산하고이를 새 열로 합산하는 방법

  27. 27

    두 개의 numpy 배열에서 일치하는 요소 제거

  28. 28

    NSMutableArray 배열을 객관적인 C, iOS에서 두 개의 개별 배열 또는 두 개의 가변 배열로 나누는 방법

  29. 29

    감소 배열 방법에 대한 두 개의 초기 값?

뜨겁다태그

보관