}
rows.add(new SimpleEntry<Integer, Integer>(i, sum));
}
- for (int i = 0; i < m; i++) {
+ for (int i = 0; i < m; i++)
cols.add(new SimpleEntry<Integer, Integer>(i, col_sums[i]));
- }
- //Sort the lists so the rows and columns with the least amount of positive compatibilities
+
+ //Sort the lists so the rows and columns with the least amount of positive compatibilities are up front
Comparator<SimpleEntry<Integer, Integer>> comp = new Comparator<SimpleEntry<Integer, Integer>>() {
@Override
public int compare(SimpleEntry<Integer, Integer> a, SimpleEntry<Integer, Integer> b) {
* 2. Find the match with the lowest sum and still positive compatibility for that row or column
* 3. Select smallest from those indices
*/
- SimpleEntry<Integer, Integer> MINIMUM = new SimpleEntry<Integer, Integer>(-1, Integer.MAX_VALUE);
while (!(rows.isEmpty() || cols.isEmpty())) {
//1. Find the row or column with the lowest sum(least available matches)
SimpleEntry<Integer, Integer> row_l = rows.peekFirst();
//Remove the current lowest row sum
rows.remove(row_l);
//3. Find smallest column that has compatibility 1
- SimpleEntry<Integer, Integer> smallest = MINIMUM;
- for (SimpleEntry<Integer, Integer> e : cols) {
- if (e.getValue() < smallest.getValue() && compatibility[row_l.getKey()][e.getKey()] == 1) {
- smallest = e;
- }
- }
+ SimpleEntry<Integer, Integer> min = new SimpleEntry<Integer, Integer>(-1, Integer.MAX_VALUE);
+ for (SimpleEntry<Integer, Integer> e : cols)
+ if (e.getValue() < min.getValue() && compatibility[row_l.getKey()][e.getKey()] == 1)
+ min = e;
//No pets left that have a positive compatibility
- if (smallest.getKey() == -1) {
- continue;
+ if (min.getKey() != -1) {
+ cols.remove(min);
+ result[row_l.getKey()] = min.getKey();
}
- cols.remove(smallest);
- result[row_l.getKey()] = smallest.getKey();
//2. The column is the lowest
} else {
//Remove the current lowest column sum
cols.remove(col_l);
//3. Find smallest row that has compatibility 1
- SimpleEntry<Integer, Integer> smallest = MINIMUM;
- for (SimpleEntry<Integer, Integer> e : rows) {
- if (e.getValue() < smallest.getValue() && compatibility[e.getKey()][col_l.getKey()] == 1) {
- smallest = e;
- }
- }
- //No pets left that have a positive compatibility
- if (smallest.getKey() == -1) {
- continue;
+ SimpleEntry<Integer, Integer> min = new SimpleEntry<Integer, Integer>(-1, Integer.MAX_VALUE);
+ for (SimpleEntry<Integer, Integer> e : rows)
+ if (e.getValue() < min.getValue() && compatibility[e.getKey()][col_l.getKey()] == 1)
+ min = e;
+ //If there is a pet left, remove it and assign it
+ if (min.getKey() != -1) {
+ rows.remove(min);
+ result[min.getKey()] = col_l.getKey();
}
- rows.remove(smallest);
- result[smallest.getKey()] = col_l.getKey();
}
}
return result;