이 페이지는 코딩도장 데이터의 읽기 전용 정적 보관본입니다.

이항연산의 교환법칙, 결합법칙 판별

유한 집합 {0,1,....n-1} 위의 이항연산은 (nxn)-2차원 배열로 표시할 수 있습니다.

예컨대 i와 j의 연산값을 i * j = a[i][j] 로 주면 됩니다.

문제 1: (매우 쉬움) 특정한 2차원 (nxn)-배열로 주어진 연산이 교환법칙을 만족하는지 판별하는 함수를 작성하세요.

문제 2: (조금 어려움) 연산이 닫혀 있을 때 앞서 주어진 배열에 대하여 삼항 연산이 다음의 두가지 방법으로 정의될 수 있습니다. m_1(i,j,k) := (i*j)*k, m_2(i,j,k) := i*(j*k) 위의 두 삼항연산이 같은 경우 결합법칙이 성립한다고 합니다. 앞서 주어진 배열의 원소가 {0,1,...,n-1} 으로 주어질 때, 배열로 주어진 이항연산이 결합법칙을 만족하는지 판별하는 함수를 작성하세요.

2019/08/05 03:31

Sechi

곱셈이 닫혀 있으려면 -1, 0, 1 밖에 없지 않나요 - Noname, 2019/08/23 10:49
실수에 주어진 연산을 생각하면 그렇지만 문제에서는 아무런 유한집합에 주어진 이항연산에 대한 질문이라 그럴 필요가 없습니다. 문제에 나온 이항연산 *는 보통 생각하는 실수나 정수의 곱을 의미하지는 않습니다. - Sechi, 2019/08/25 20:09

5개의 풀이가 있습니다.

function validCommutativity(table){
    const n = table.length;

    for(let i=0; i<n; i++)
        for(let j=i+1; j<n; j++)
            if(table[i][j] !== table[j][i])
                return false

    return true
}

function validAssociative(table){
    const n = table.length;

    for(let i=0; i<n; i++)
        for(let j=0; j<n; j++)
            for(let k=0; k<n; k++)
                if(table[table[i][j]][k] !== table[i][table[j][k]])
                    return false

    return true
}

const foo = [
    [0, 0, 0, 0, 0],
    [0, 1, 1, 1, 1],
    [0, 1, 2, 2, 2],
    [0, 1, 2, 3, 3],
    [0, 1, 2, 3, 4],
]

console.log(validCommutativity(foo));
console.log(validAssociative(foo));

2019/08/28 22:08

Creator

package d238_commutative_associated;
public class CommutativeLaw {

    int op1(int a, int b) {
        return a*b;
    }

    public static void main(String[] args) {
        CommutativeLaw cl = new CommutativeLaw();
        int n=10;
        boolean result=true;
        int i, j;

        for(i=0; i<n; i++) {
            for(j=0; j<n; j++)
                if(cl.op1(i, j)!=cl.op1(j, i)) {
                    result=false;
                    break; //별 의미 없음.
                }
        }

        System.out.println(result);

    }
}
package d238_commutative_associated;
public class AssociatedLaw {

    int op2(int a, int b) {
        return a*b;
    }

    public static void main(String[] args) {
        AssociatedLaw al = new AssociatedLaw();
        int n=10;
        boolean result=true;
        int i, j, k;

        for(i=0; i<n; i++)
            for(j=0; j<n; j++)
                for (k=0; k<n; k++) {
                    if( al.op2( al.op2(i, j), k) != al.op2(i, al.op2(j, k) ) ) {
                        result=false;
                        break; //별 의미 없음.
                    }
                }

        System.out.println(result);

    }
}

2019/10/19 23:31

Katherine

a = [0:n]
b = [0:n]
c = [a,b]

for i in a:
    for j in b:
        if c[i][j] = c[j][i]: True
    else: False

흠 두번째는 좀 더 고민해봐야겠어요

2021/05/23 14:19

ss2663

dart

예외처리 포함

안 닫혀 있으면 그냥 false 리턴

typedef Matrix = List<List<int>>;

// avoid redundancy
bool isCommutative(Matrix matrix, int n) {
  for (int i = 0; i < n; i++) {
    for (int j = i + 1; j < n; j++) {
      if (matrix[i][j] != matrix[j][i]) {
        return false;
      }
    }
  }
  return true;
}

bool isAssociative(Matrix matrix, int n) {
  try {
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        for (int k = 0; k < n; k++) {
          if (matrix[matrix[i][j]][k] != matrix[i][matrix[j][k]]) {
            return false;
          }
        }
      }
    }    
  } on RangeError catch(e) {
    return false; // not closed for the operator
  }
  return true;
}

void main() {
  List<Matrix> testSet = [
    [],                                   // empty
    [[1], [2, 3]],                        // non-matrix
    [[1, 2, 3], [4, 5, 6]],               // non-square matrix
    [[0]],                                // *
    [[0, 0],[0, 1]],                      // *
    [[0, 1, 2],[1, 2, 3], [4, 5, 6]],     // +
    [[0, -1, -2],[1, 0, -1], [2, 1, 0]],  // -
    [[0, 0, 0],[0, 1, 2], [0, 2, 4]]      // *
  ];

  print("Commutative, Associative:");
  for (Matrix matrix in testSet) {    
    int n = matrix.length;
    if (matrix.isEmpty ||!matrix.fold(true, 
                       (lengthFixed, row) => lengthFixed && row.length == n)) {
      print('$matrix => Invalid: Square matrix is needed');
    } else {
      print('$matrix => ${isCommutative(matrix, n)}, ${isAssociative(matrix, n)}');
    }
  }  
}

실행결과

Commutative, Associative:
[] => Invalid: Square matrix is needed
[[1], [2, 3]] => Invalid: Square matrix is needed
[[1, 2, 3], [4, 5, 6]] => Invalid: Square matrix is needed
[[0]] => true, true
[[0, 0], [0, 1]] => true, true
[[0, 1, 2], [1, 2, 3], [4, 5, 6]] => false, false
[[0, -1, -2], [1, 0, -1], [2, 1, 0]] => false, false
[[0, 0, 0], [0, 1, 2], [0, 2, 4]] => true, false

2023/01/07 13:39

Noname

python 3.8

# 문제 1의 해
A = [[1,2,3], [4,5,6]]
B = [[5,6], [7,8], [9,0]]

def matrix_product(M1, M2):
    rows = len(M1)
    cols = len(M2[0])
    mids = len(M1[0])
    R = [[0 for _ in range(cols)] for _ in range(rows)]
    if cols == rows:
        for i in range(cols):
            for j in range(rows):
                for m in range(mids):
                    R[i][j] += M1[i][m]*M2[m][j]
        for i in range(len(R)):
            for j in range(len(R[0])):
                print(f"{R[i][j]:>3}", end=" ")
            print()
        return R
    else:
        return "can not product"

def are_matrices_equal(M1, M2):
    if len(M1) != len(M2) or len(M1[0]) != len(M2[0]):
        return False

    for i in range(len(M1)):
        for j in range(len(M1[0])):
            if M1[i][j] != M2[i][j]:
                return False
    return True

if matrix_product(A, B) == "곱셈불가" or \
        not are_matrices_equal(matrix_product(A, B), matrix_product(B, A)):
    print("교환법칙 불만족")
else:
    print("교환법칙 만족")

# 문제 2의 해
A = [[1,2], [3,4]]
B = [[5,6], [7,8]]
C = [[9,0], [1,2]]

# (A*B)*C = A*(B*C) ??
T1 = matrix_product(A, B)
Q1 = matrix_product(T1, C)
T2 = matrix_product(B, C)
Q2 = matrix_product(A, T2)

if are_matrices_equal(Q1, Q2):
    print("결합법칙 성립")
else:
    print("결합법칙 불성립")

2024/04/14 22:44

김맹준

46 22 109 64 46 22 109 64 29 40 51 39 54 69 9 18 27 교환법칙 불만족 19 22 43 50 193 44 437 100 51 12 71 16 193 44 437 100 결합법칙 성립 - 김맹준, 2024/04/14 22:45
출제자의 출제의도를 잘 이해했는지 모르겠네요. ㅎㅎ - 김맹준, 2024/04/14 22:46
목록으로