1 /* 2 * Copyright 2006 - 2012 Christina Bohk and Roland Ewald 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package p3j.simulation.assignments.exhaustive; 17 18 import java.util.ArrayList; 19 import java.util.Collections; 20 import java.util.HashSet; 21 import java.util.List; 22 import java.util.Set; 23 24 /** 25 * This class provides all data structures and methods required to enumerate a 26 * set of {@link Assignment} instances step-by-step. Ensures no assignment is 27 * added twice. 28 * 29 * @author Christina Bohk 30 * @author Roland Ewald 31 * 32 */ 33 public class AssignmentEnumerator { 34 35 /** Sorted list with most probably assignment combinations in front. */ 36 private final List<Assignment> assignmentQueue = new ArrayList<Assignment>(); 37 38 /** The set of assignment IDs. */ 39 private final java.util.Set<String> idSet = new HashSet<String>(); 40 41 /** 42 * Instantiates a new assignment enumerator. Puts first assignment in the 43 * queue. 44 * 45 * @param assignment 46 * the first assignment 47 */ 48 AssignmentEnumerator(Assignment assignment) { 49 addToQueue(assignment); 50 } 51 52 /** 53 * Instantiates a new assignment enumerator. 54 */ 55 AssignmentEnumerator() { 56 } 57 58 /** 59 * Adds the assignment to the queue if it has not been added before. 60 * 61 * @param assignment 62 * the assignment 63 */ 64 private void addToQueue(Assignment assignment) { 65 if (idSet.contains(assignment.getID())) { 66 return; 67 } 68 assignmentQueue.add(assignment); 69 idSet.add(assignment.getID()); 70 } 71 72 /** 73 * Checks if is empty. 74 * 75 * @return true, if is empty 76 */ 77 public boolean isEmpty() { 78 return assignmentQueue.isEmpty(); 79 } 80 81 /** 82 * Removes the most probable assignment. 83 * 84 * @return the most probable assignment, null if there is none 85 */ 86 public Assignment removeMostProbable() { 87 return isEmpty() ? null : assignmentQueue.remove(0); 88 } 89 90 /** 91 * Gets the most probable assignment. 92 * 93 * @return the most probable assignment 94 */ 95 public Assignment getMostProbable() { 96 return assignmentQueue.get(0); 97 } 98 99 /** 100 * Adds a set of assignments. 101 * 102 * @param assignments 103 * the assignments 104 */ 105 public void add(Set<Assignment> assignments) { 106 for (Assignment assignment : assignments) { 107 addToQueue(assignment); 108 } 109 Collections.sort(assignmentQueue); 110 } 111 112 }