001package org.clafer.math; 002 003import java.util.Arrays; 004import java.util.HashSet; 005import java.util.Set; 006import org.clafer.domain.Domain; 007 008/** 009 * 010 * @author jimmy 011 */ 012public class SetEnvironment { 013 014 protected final Set<SubsetDomain> subsetDomains = new HashSet<>(); 015 protected final Set<Subset> subsets = new HashSet<>(); 016 protected final Set<Union> unions = new HashSet<>(); 017 018 public SetEnvironment subset(int sub, int sup) { 019 if (sub != sup) { 020 subsets.add(new Subset(sub, sup)); 021 } 022 return this; 023 } 024 025 public SetEnvironment subset(int sub, Domain domain) { 026 subsetDomains.add(new SubsetDomain(sub, domain)); 027 return this; 028 } 029 030 public SetEnvironment equal(int v1, int v2) { 031 subset(v1, v2); 032 subset(v2, v1); 033 return this; 034 } 035 036 public SetEnvironment union(int union, int[] operands) { 037 switch (operands.length) { 038 case 0: 039 throw new IllegalArgumentException(); 040 case 1: 041 equal(union, operands[0]); 042 default: 043 unions.add(new Union(union, operands)); 044 } 045 return this; 046 } 047 048 protected static class Union { 049 050 protected final int union; 051 protected final int[] operands; 052 053 protected Union(int union, int[] operands) { 054 this.union = union; 055 this.operands = operands.clone(); 056 Arrays.sort(this.operands); 057 } 058 059 @Override 060 public boolean equals(Object obj) { 061 if (obj instanceof Union) { 062 Union other = (Union) obj; 063 return union == other.union && Arrays.equals(operands, other.operands); 064 } 065 return false; 066 } 067 068 @Override 069 public int hashCode() { 070 return union ^ Arrays.hashCode(operands); 071 } 072 } 073 074 protected static class Subset { 075 076 protected final int sub; 077 protected final int sup; 078 079 protected Subset(int sub, int sup) { 080 this.sub = sub; 081 this.sup = sup; 082 } 083 084 @Override 085 public boolean equals(Object obj) { 086 if (obj instanceof Subset) { 087 Subset other = (Subset) obj; 088 return sub == other.sub && sup == other.sup; 089 } 090 return false; 091 } 092 093 @Override 094 public int hashCode() { 095 return sub ^ sup; 096 } 097 } 098 099 protected static class SubsetDomain { 100 101 protected final int sub; 102 protected final Domain sup; 103 104 protected SubsetDomain(int sub, Domain sup) { 105 this.sub = sub; 106 this.sup = sup; 107 } 108 109 @Override 110 public boolean equals(Object obj) { 111 if (obj instanceof SubsetDomain) { 112 SubsetDomain other = (SubsetDomain) obj; 113 return sub == other.sub && sup.equals(other.sup); 114 } 115 return false; 116 } 117 118 @Override 119 public int hashCode() { 120 return sub ^ sup.hashCode(); 121 } 122 } 123}