1) 합의 법칙 - 사건 A 또는 사건 B가 일어날 경우의 수(합집합)
2) 곱의 법칙 - 사건 A와 사건 B가 동시에 일어날 경우의 수
public class Main{
public static void main(String[] args) {
//합의 법칙
//두 개의 주사위를 던졌을 때, 합이 3 또는 4의 배수일 경우의 수
//n(A) + n(B) - n(AnB) => 합집합
//두 개의 주사위 선언
int[] dice1 = {1,2,3,4,5,6};
int[] dice2 = {1,2,3,4,5,6};
//A 사건의 경우의 수, B 사건의 경우의 수
int nA = 0;
int nB = 0;
//사건 A와 B가 동시에 일어날 경우의 수(교집합)
int AandB = 0;
for (int item1 : dice1) {
for (int item2 : dice2) {
//합이 3의 배수일 경우의 수
if ((item1 + item2) % 3 == 0) {
nA++;
}
//합이 4의 배수일 경우의 수
if ((item1 + item2) % 4 == 0) {
nB++;
}
//3의 배수이면서 4의 배수일 경우의 수(12의 배수일 경우의 수)
if ((item1 + item2) % 12 == 0 ) {
nAandB += 1;
}
}
}
System.out.println("합의 법칙 - 기본 풀이");
System.out.println("Result : " + (nA + nB - AandB));
System.out.println("===구분선===");
//HashSet을 이용한 풀이
HashSet<ArrayList> result = new HashSet<>();
for (int itemA : dice1) {
for (int itemB : dice2) {
if ((itemA + itemB % 3 == 0) || (itemA + itemB % 4 == 0)) {
ArrayList list = new ArrayList(Arrays.asList(itemA,itemB));
result.add(list);
}
}
}
System.out.println("합의 법칙 - HashSet이용");
System.out.println("result : " + result);
System.out.println("result.size() : " + result.size());
System.out.println("===구분선===");
//곱의 법칙
//두 개의 주사위 a,b를 전졌을 때, a는 3의 배수, b는 4의 배수일 경우의 수
//n(A) * n(B) => 두 사건의 경우의 수의 곱
System.out.println("곱의 법칙");
nA = 0;
nB = 0;
for (int itemA : dice1) {
if(itemA % 3 == 0) {
nA +=1;
}
}
for (int itemB : dice2) {
if(itemA % 4 == 0) {
nB +=1;
}
}
System.out.println("Result : " + (nA*nB));
}
}
//결과값
합의 법칙 - 기본 풀이
Result : 20
===구분선===
합의 법칙 - HashSet이용
result : [[2, 1], [5, 4], [2, 2], [3, 3], [4, 4], [6, 6], [1, 2], [4, 5], [1, 3], [2, 4], [3, 5], [3, 6], [1, 5], [2, 6], [5, 1], [6, 2], [6, 3], [3, 1], [4, 2], [5, 3]]
result.size() : 20
===구분선===
곱의 법칙
Result : 2