package com.kevlindev.karnaugh;

import java.util.ArrayList;
import java.util.List;

public class MinTerm {
	private List<Integer> indexes = new ArrayList<Integer>();
	private List<TruthValue> bits = new ArrayList<TruthValue>();

	public MinTerm(int totalBits, int index) {
		this.indexes.add(index);

		for (int mask = 1 << (totalBits - 1); mask != 0; mask >>= 1) {
			TruthValue value = ((index & mask) == mask) ? TruthValue.TRUE : TruthValue.FALSE;

			this.bits.add(value);
		}
	}

	private MinTerm(List<Integer> indexes, List<TruthValue> bits) {
		this.indexes = indexes;
		this.bits = bits;
	}

	public int difference(MinTerm term) {
		int count = 0;

		for (int i = 0; i < bits.size(); i++) {
			if (bits.get(i) != term.bits.get(i)) {
				count++;
			}
		}

		return count;
	}

	/**
	 * Return the number of TRUE bit values in this minterm
	 * 
	 * @return
	 */
	public int getBitCount() {
		int count = 0;

		for (TruthValue value : bits) {
			if (value == TruthValue.TRUE) {
				count++;
			}
		}

		return count;
	}

	public List<TruthValue> getBits() {
		return bits;
	}

	public List<Integer> getIndexes() {
		return indexes;
	}

	public MinTerm merge(MinTerm term) {
		MinTerm result = null;
		int count = 0;
		List<TruthValue> mergedBits = new ArrayList<TruthValue>();

		for (int i = 0; i < bits.size(); i++) {
			if (bits.get(i) != term.bits.get(i)) {
				count++;

				if (count > 1) {
					break;
				}
				
				mergedBits.add(TruthValue.UNDEFINED);
			} else {
				mergedBits.add(bits.get(i));
			}
		}

		if (count < 2) {
			List<Integer> indexes = new ArrayList<Integer>();

			indexes.addAll(this.indexes);
			indexes.addAll(term.indexes);

			result = new MinTerm(indexes, mergedBits);
		}

		return result;
	}

	public String toString() {
		return "(" + Util.join(",", indexes) + "):" + Util.join("", bits);
	}
}

@@ -54,16 +54,46 @@
 ayList;%0A
+import java.util.Collections;%0A
 import j
@@ -107,16 +107,16 @@
 l.List;%0A
-
 %0Apublic 
@@ -808,16 +808,341 @@
 nt;%0A%09%7D%0A%0A
+%09@Override%0A%09public boolean equals(Object obj) %7B%0A%09%09boolean result = false;%0A%0A%09%09if (obj instanceof MinTerm) %7B%0A%09%09%09MinTerm other = (MinTerm) obj;%0A%0A%09%09%09result = indexes.equals(other.indexes) && bits.equals(other.bits);%0A%09%09%7D%0A%0A%09%09return result;%0A%09%7D%0A%0A%09@Override%0A%09public int hashCode() %7B%0A%09%09return indexes.hashCode() %5E bits.hashCode();%0A%09%7D%0A%0A
 %09/**%0A%09 *
@@ -1773,13 +1773,9 @@
 %09%09%7D%0A
-%09%09%09%09
 %0A
+
 %09%09%09%09
@@ -1973,16 +1973,16 @@
 dexes);%0A
-
 %09%09%09index
@@ -2007,16 +2007,47 @@
 exes);%0A%0A
+%09%09%09Collections.sort(indexes);%0A%0A
 %09%09%09resul

Add equals and hashCode to MinTerm so we can test equality and have them work properly in Sets