두 배열의 요소가 동일한지 확인하는 C 프로그래밍 (순열 고려)

2024-07-27

순열을 고려하여 두 배열의 동일성을 검사하는 보다 효율적인 방법은 다음과 같습니다.

해시 테이블 사용

  • 각 배열의 각 요소를 해시 테이블에 키로 저장하고, 해당 키의 값을 증가시킵니다.
  • 두 배열을 모두 처리한 후, 해시 테이블의 모든 키-값 쌍을 비교합니다.
  • 모든 키-값 쌍이 동일하면 두 배열은 동일한 요소를 가지고 있는 것입니다.

예시 코드:

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

#define HASHTABLE_SIZE 100

typedef struct node {
    int key;
    int value;
} Node;

Node* hashtable[HASHTABLE_SIZE];

int hash(int key) {
    return key % HASHTABLE_SIZE;
}

void insert(int key) {
    int index = hash(key);
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->key = key;
    newNode->value = 1;

    if (hashtable[index] == NULL) {
        hashtable[index] = newNode;
    } else {
        Node* curr = hashtable[index];
        while (curr->next != NULL) {
            curr = curr->next;
        }
        curr->next = newNode;
    }
}

int compare(int a[], int b[], int n) {
    for (int i = 0; i < n; i++) {
        insert(a[i]);
    }

    for (int i = 0; i < n; i++) {
        int index = hash(b[i]);
        Node* curr = hashtable[index];

        while (curr != NULL) {
            if (curr->key == b[i]) {
                curr->value--;
                break;
            }
            curr = curr->next;
        }

        if (curr == NULL) {
            return 0;
        }
    }

    for (int i = 0; i < HASHTABLE_SIZE; i++) {
        Node* curr = hashtable[i];
        while (curr != NULL) {
            if (curr->value != 0) {
                return 0;
            }
            curr = curr->next;
        }
    }

    return 1;
}

int main() {
    int a[] = {1, 2, 3, 4, 5};
    int b[] = {5, 4, 3, 2, 1};
    int n = sizeof(a) / sizeof(a[0]);

    if (compare(a, b, n)) {
        printf("두 배열은 동일한 요소를 가지고 있습니다.\n");
    } else {
        printf("두 배열은 동일한 요소를 가지고 있지 않습니다.\n");
    }

    return 0;
}

정렬 후 비교

  • 두 배열을 오름차순으로 정렬합니다.
  • 정렬된 두 배열을 하나씩 비교합니다.
#include <stdio.h>
#include <stdlib.h>

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

void sort(int a[], int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
            if (a[i] > a[j]) {
                swap(&a[i], &a[j]);
            }
        }
    }
}

int compare(int a[], int b[], int n) {



예시 코드 (정렬 후 비교)

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

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

void sort(int a[], int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
            if (a[i] > a[j]) {
                swap(&a[i], &a[j]);
            }
        }
    }
}

int compare(int a[], int b[], int n) {
    sort(a, n);
    sort(b, n);

    for (int i = 0; i < n; i++) {
        if (a[i] != b[i]) {
            return 0;
        }
    }

    return 1;
}

int main() {
    int a[] = {1, 2, 3, 4, 5};
    int b[] = {5, 4, 3, 2, 1};
    int n = sizeof(a) / sizeof(a[0]);

    if (compare(a, b, n)) {
        printf("두 배열은 동일한 요소를 가지고 있습니다.\n");
    } else {
        printf("두 배열은 동일한 요소를 가지고 있지 않습니다.\n");
    }

    return 0;
}
  • 각 배열의 각 요소를 비트 배열로 변환합니다.
  • 두 비트 배열을 XOR 연산합니다.
#include <stdio.h>
#include <stdlib.h>

int main() {
    int a[] = {1, 2, 3, 4, 5};
    int b[] = {5, 4, 3, 2, 1};
    int n = sizeof(a) / sizeof(a[0]);

    int bitArray1[n];
    int bitArray2[n];

    for (int i = 0; i < n; i++) {
        bitArray1[i] = 1 << a[i];
        bitArray2[i] = 1 << b[i];
    }

    int result = 0;
    for (int i = 0; i < n; i++) {
        result ^= bitArray1[i] ^ bitArray2[i];
    }

    if (result == 0) {
        printf("두 배열은 동일한 요소를 가지고 있습니다.\n");
    } else {
        printf("두 배열은 동일한 요소를 가지고 있지 않습니다.\n");
    }

    return 0;
}

위의 코드는 3가지 방법으로 두 배열의 요소가 동일한지 확인하는 방법을 보여줍니다. 각 방법마다 장단점이 존재하며, 상황에 맞는 방법을 선택해야 합니다.

참고:

  • 위의 코드는 예시이며, 실제 상황에 맞게 수정해야 할 수도 있습니다.
  • 더 효율적인 방법이 존재할 수 있습니다.



두 배열의 요소가 동일한지 확인하는 대체 방법

큐 사용

  • 두 배열의 각 요소를 큐에 삽입합니다.
  • 큐가 비어질 때까지 큐에서 두 요소를 꺼내 비교합니다.
#include <stdio.h>
#include <stdlib.h>

#define QUEUE_SIZE 100

typedef struct node {
    int data;
    struct node* next;
} Node;

Node* front = NULL;
Node* rear = NULL;

void enqueue(int data) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->data = data;
    newNode->next = NULL;

    if (front == NULL) {
        front = rear = newNode;
    } else {
        rear->next = newNode;
        rear = newNode;
    }
}

int dequeue() {
    if (front == NULL) {
        return -1;
    }

    Node* temp = front;
    int data = temp->data;
    front = front->next;

    if (front == NULL) {
        rear = NULL;
    }

    free(temp);

    return data;
}

int compare(int a[], int b[], int n) {
    for (int i = 0; i < n; i++) {
        enqueue(a[i]);
    }

    for (int i = 0; i < n; i++) {
        int x = dequeue();
        int y = b[i];

        if (x != y) {
            return 0;
        }
    }

    return 1;
}

int main() {
    int a[] = {1, 2, 3, 4, 5};
    int b[] = {5, 4, 3, 2, 1};
    int n = sizeof(a) / sizeof(a[0]);

    if (compare(a, b, n)) {
        printf("두 배열은 동일한 요소를 가지고 있습니다.\n");
    } else {
        printf("두 배열은 동일한 요소를 가지고 있지 않습니다.\n");
    }

    return 0;
}
  • 두 배열의 각 요소를 맵의 키로 사용하고, 값을 1로 설정합니다.
  • 맵의 모든 키를 순회하면서 값을 비교합니다.
#include <stdio.h>
#include <stdlib.h>

#define MAP_SIZE 100

typedef struct node {
    int key;
    int value;
    struct node* next;
} Node;

Node* map[MAP_SIZE];

int hash(int key) {
    return key % MAP_SIZE;
}

void insert(int key) {
    int index = hash(key);
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->key = key;
    newNode->value = 1;

    if (map[index] == NULL) {
        map[index] = newNode;
    } else {
        Node* curr = map[index];
        while (curr->next != NULL) {
            curr = curr->next;
        }
        curr->next = newNode;
    }
}

int compare(int a[], int b[], int n) {
    for (int i = 0; i < n; i++) {
        insert(a[i]);
    }

    for (int i = 0; i < n; i++) {
        int index = hash(b[i]);
        Node* curr = map[index];

        while (curr != NULL) {
            if (curr->key == b[i]) {
                curr->value--;
                break;
            }
            curr = curr->next;
        }

        if (curr == NULL || curr->value != 0) {
            return 0;

arrays c permutation



자바 배열 출력하는 가장 간단한 방법

문제: 자바에서 배열을 출력하고 싶은데, 어떻게 해야 할지 막막하다면 이 가이드를 참고하세요.해결:자바에서 배열을 출력하는 가장 간단한 방법은 크게 두 가지가 있습니다.가장 기본적이고 직관적인 방법입니다. 배열의 각 요소를 순서대로 접근하여 출력합니다...


자바 배열에서 특정 값이 포함되어 있는지 확인하는 방법

문제: 자바에서 주어진 배열에 특정 값이 존재하는지 여부를 판단하고 싶습니다.해결 방법:자바에서는 배열 내의 값을 검색하는 다양한 방법이 있습니다. 각 방법은 상황에 따라 장단점이 있으므로, 문제에 맞는 적절한 방법을 선택하는 것이 중요합니다...


자바에서 배열 선언 및 초기화하기

자바에서 배열은 같은 자료형의 값들을 연속적으로 저장하기 위한 자료구조입니다. 마치 서랍장에 같은 종류의 물건을 칸별로 정리해 놓는 것과 비슷합니다. 각 서랍에 해당하는 자리를 인덱스라고 부르며, 이 인덱스를 통해 특정 값에 접근할 수 있습니다...


C/C++ 프로그래밍에서 #include <filename>과 #include "filename"의 차이점

1. #include <filename>각 컴파일러마다 정의된 표준 헤더 파일을 포함하는 데 사용됩니다.<filename> 안에 작성된 파일 이름은 컴파일러가 미리 정의된 경로 목록에서 검색됩니다. 이 목록은 일반적으로 운영 체제 및 컴파일러에 따라 다릅니다...


++i와 i++의 차이: C 언어의 전위 증감 연산자와 후위 증감 연산자

C 언어에서 ++i와 i++는 모두 변수 i의 값을 1 증가시키는 증감 연산자입니다. 하지만 언제 값이 증가하는지에 따라 전혀 다른 결과를 가져오기 때문에 명확하게 이해하는 것이 중요합니다.먼저 값을 증가시킨 후 해당 값을 반환합니다...



arrays c permutation

C 언어에서 배열의 크기를 구하는 방법

C 언어에서 배열의 크기를 구하는 가장 일반적인 방법은 sizeof 연산자를 사용하는 것입니다.전체 배열의 크기: sizeof(배열 이름)배열이 차지하는 전체 메모리 크기를 바이트 단위로 반환합니다.배열이 차지하는 전체 메모리 크기를 바이트 단위로 반환합니다


자바에서 두 개의 배열을 연결하는 방법

자바에서 두 개의 배열을 연결하여 하나의 새로운 배열을 만드는 방법은 여러 가지가 있습니다. 각 방법마다 장단점이 있으므로, 상황에 맞는 적절한 방법을 선택하는 것이 중요합니다.원리: 시스템 메서드를 이용하여 배열의 일부를 다른 배열로 복사합니다


Java에서 배열을 ArrayList로 변환하기

동적 크기: ArrayList는 필요에 따라 크기를 조절할 수 있어 배열처럼 미리 크기를 정해둘 필요가 없습니다. 데이터가 추가되거나 삭제될 때 유연하게 대처할 수 있습니다.다양한 메소드: ArrayList는 add


C# 배열에 값 추가하기: 자세한 설명

C# 배열은 동일한 데이터형의 값들을 순서대로 저장하는 자료구조입니다. 배열의 각 요소는 고유한 인덱스를 가지며, 이 인덱스를 통해 값에 접근하고 변경할 수 있습니다.배열 선언 예시:1. 배열 초기화 시 값 할당:배열을 선언하는 동시에 값을 할당할 수 있습니다


PHP에서 배열 요소 삭제하기: unset() 함수 활용

PHP에서 배열에서 특정 요소를 삭제하려면 unset() 함수를 사용합니다. unset() 함수는 변수나 배열 요소를 메모리에서 해제하는 데 사용되는 일반적인 함수이지만, 배열의 컨텍스트에서 사용하면 해당 요소를 삭제하는 효과를 가져옵니다