-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntSet.java
More file actions
115 lines (101 loc) · 2.63 KB
/
Copy pathIntSet.java
File metadata and controls
115 lines (101 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package set;
// int형 집합 클래스 만들기
public class IntSet {
private int max; // 집합의 최대 기수
private int num; // 집합의 요소 개수
private int[] set; // 집합 본체
// 생성자
public IntSet(int capacity) {
max = 0;
max = capacity;
try {
set = new int[max]; // 집합 배열 생성
} catch(OutOfMemoryError e) { // 배열의 생성 실패
max = 0;
}
}
// 집합의 최대 개수
public int capacity() {
return max;
}
// 집합의 요소 개수
public int size() {
return num;
}
// 집합에서 n을 검색합니다(index 반환)
public int indexOf(int n) {
for(int i=0; i<num; i++) {
if(set[i] == n)
return i; // 검색 성공
}
return -1; // 검색 실패
}
// 집합에 n이 있는지 없는지 확인
public boolean contains(int n) {
return (indexOf(n) != -1) ? true : false;
}
// 집합에 n을 추가합니다.
public boolean add(int n) {
if(num >= max || contains(n) == true)
return false; // 가득 찼거나 이미 n이 존재
else {
set[num++] = n; // 가장 마지막 자리에 추가
return true;
}
}
// 집합에서 n을 삭제
public boolean remove(int n) {
int idx; // n이 저장된 요소의 인덱스
if(num <= 0 || (idx = indexOf(n)) == -1)
return false; // 비어 있거나 이미 n이 존재
else {
set[idx] = set[--num]; // 마지막 요소를 삭제한 곳으로 옮긴다
return true;
}
}
// 집합 s에 복사
public void copyTo(IntSet s) {
int n = (s.max < num) ? s.max : num; // 복사할 요소 개수
for(int i=0; i<n; i++)
s.set[i] = set[i];
s.num = n;
}
// 집합 s를 복사
public void copyFrom(IntSet s) {
int n = (max < s.num)? max : s.num; // 복사할 요소 개수
for(int i=0; i<n; i++)
set[i] = s.set[i];
num = n;
}
// 집합 s와 같은지 확인
public boolean equalsTo(IntSet s) {
if(num != s.num) // 요소 개수와 같지 않으면
return false; // 집합도 같지 않는다
for(int i=0; i<num; i++) {
int j=0;
for( ; j<s.num; j++) {
if(set[i] == s.set[i])
break;
}
if(j == s.num) // set[i]는 s에 포함되지 않는다
return false;
}
return true;
}
// 집합 s1과 s2의 합집합을 복사
public void unionOf(IntSet s1, IntSet s2) {
copyFrom(s1); // 집합 s1을 복사
for(int i=0; i<s2.num; i++) { // 집합 s2의 요소를 추가
add(s2.set[i]);
}
}
// "{ a b c }"형식의 문자열로 표현을 바꿈
public String toString() {
StringBuffer temp = new StringBuffer("{ ");
for(int i=0; i<num; i++) {
temp.append(set[i] + " ");
}
temp.append("}");
return temp.toString();
}
}