集合的交集,并集,差集,对称差,相等
package work2;
import java.util.Arrays;
class Aggregate {
public int Naggregate[];
int Len, Size;
Aggregate() {
Naggregate = new int[0];
Size = 0;
Len = 0;
}
public void Extend() {
this.Naggregate = Arrays.copyOf(this.Naggregate, Size + 1);
Size += 1;
}
Aggregate(int a[]) {
Naggregate = new int[a.length];
for (int i = 0; i < a.length; i++) {
Naggregate[i] = a[i];
}
Size = a.length;
}
public Aggregate InterSection(Aggregate a) {
Aggregate c = new Aggregate();
for (int i = 0; i < this.Size; i++) {
for (int j = 0; j < a.Size; j++) {
if (this.Naggregate[i] == a.Naggregate[j]) {
c.Extend();
c.Naggregate[c.Len] = this.Naggregate[i];
c.Len++;
}
}
}
return c;
}//交集
public Aggregate DifferenceSet(Aggregate b) {
Aggregate c = new Aggregate();
int n = 0;
while (n < this.Size) {
int k = 0;
for (int i = 0; i < b.Size; i++) {
if (this.Naggregate[n] == b.Naggregate[i]) {
k++;
}
}
if (k == 0) {
c.Extend();
c.Naggregate[c.Len] = this.Naggregate[n];
c.Len++;
n++;
} else {
n++;
}
}
return c;
}//差集
public Aggregate Union(Aggregate a) {
Aggregate c = new Aggregate();
Aggregate d = this.DifferenceSet(a);
for (int i = 0; i < d.Size; i++) {
c.Extend();
c.Naggregate[c.Len] = d.Naggregate[i];
c.Len++;
}
for (int i = 0; i < a.Size; i++) {
c.Extend();
c.Naggregate[c.Len] = a.Naggregate[i];
c.Len++;
}
return c;
}//并集
public Aggregate SymmetricDifference(Aggregate a) {
Aggregate c = new Aggregate();
Aggregate d = this.DifferenceSet(a);
Aggregate e = a.DifferenceSet(this);
for (int i = 0; i < d.Size; i++) {
c.Extend();
c.Naggregate[c.Len] = d.Naggregate[i];
c.Len++;
}
for (int i = 0; i < e.Size; i++) {
c.Extend();
c.Naggregate[c.Len] = e.Naggregate[i];
c.Len++;
}
return c;
}//对称差
public boolean Equal(Aggregate a){
boolean m=false;
Aggregate n=this.InterSection(a);
if(this.Size==n.Size&&a.Size==n.Size)
m=true;
return m;
}//相等
}
public class Main {
public static void main(String[] args) {
int a[] = {1, 2, 9, 7, 4, 3, 5, 6};
int b[] = {1, 3, 6, 2, 5, 9, 7};
Aggregate e = new Aggregate(a);
Aggregate d = new Aggregate(b);
Aggregate NIS = e.InterSection(d);
Aggregate NDS = e.DifferenceSet(d);
Aggregate NU = e.Union(d);
Aggregate NSD = e.SymmetricDifference(d);
boolean NE=e.Equal(d);
System.out.println("交集:");
Nprint(NIS);
System.out.println("差集:");
Nprint(NDS);
System.out.println("并集:");
Nprint(NU);
System.out.println("对称差:");
Nprint(NSD);
System.out.println("是否相等:")
System.out.println(NE);
}
private static void Nprint(Aggregate f) {
for (int i = 0; i < f.Size; i++) {
System.out.println(f.Naggregate[i]);
}
}
}
注:学习摸索,不喜勿喷,欢迎指教!