유한 집합 {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} 으로 주어질 때, 배열로 주어진 이항연산이 결합법칙을 만족하는지 판별하는 함수를 작성하세요.
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));
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);
}
}
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
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("결합법칙 불성립")
풀이 작성
코딩도장은 프로그래밍 문제풀이를 통해서 코딩 실력을 수련(Practice)하는 곳입니다.