HashSet을 통한 집합연산

wellsbabo·2023년 3월 22일
0

코드모음

목록 보기
3/3

HashSet 생성

HashSet set1 = new HashSet();

교집합

HashSet a = new HashSet(Arrays.asList(1, 2, 3, 4, 5));
HashSet b = new HashSet(Arrays.asList(2, 4, 6, 8, 10));
a.retainAll(b);//a의 값이 변한다

합집합

a = new HashSet(Arrays.asList(1, 2, 3, 4, 5));
b = new HashSet(Arrays.asList(2, 4, 6, 8, 10));
a.addAll(b);

차집합

a = new HashSet(Arrays.asList(1, 2, 3, 4, 5));
b = new HashSet(Arrays.asList(2, 4, 6, 8, 10));
a.removeAll(b);

합의 법칙

사건A 또는 사건B가 일어날 경우의 수
ex)두 개의 주사위를 던졌을 때 합이 3 또는 4의 배수일 경우의 수

int[] dice1 = {1, 2, 3, 4, 5, 6};
int[] dice2 = {1, 2, 3, 4, 5, 6};

HashSet<ArrayList> allCase = new HashSet<ArrayList>();
for (int item1: dice1) {
	for (int item2 : dice2) {
		if ((item1 + item2) % 3 == 0 || (item1 + item2) % 4 == 0) {
			ArrayList list = new ArrayList(Arrays.asList(item1, item2));
			allCase.add(list);
		}
	}
}
System.out.println("결과: " + allCase.size());

곱의 법칙

사건A와 사건B가 동시에 일어날 경우의 수
ex) 두 개의 주사위를 던졌을 때, a는 3의 배수, b는 4의 배수인 경우의 수

int[] dice1 = {1, 2, 3, 4, 5, 6};
int[] dice2 = {1, 2, 3, 4, 5, 6};

nA = 0;
nB = 0;

for (int item1: dice1) {
	if (item1 % 3 == 0) {
		nA++;
	}
}

for (int item2: dice2) {
	if (item2 % 4 == 0) {
		nB++;
	}
}
System.out.println("결과: " + (nA * nB));

0개의 댓글