public BudgetService(GraphFactory graphFactory) {
this.graphFactory = graphFactory;
}
public Graph resolveBudget(Budget budget) {
Graph graph = createBudgetGraph(budget);
List<Vertex> positives = new LinkedList<Vertex>();
Map<Vertex, Integer> positivesDegree = new HashMap<Vertex, Integer>();
List<Vertex> negatives = new LinkedList<Vertex>();
Map<Vertex, Integer> negativesDegree = new HashMap<Vertex, Integer>();
for (Vertex v : graph.getVertexSet()) {
int degree = v.getDegree();
if (degree > 0) {
positives.add(v);
positivesDegree.put(v,degree);
} else {
negatives.add(v);
negativesDegree.put(v, degree);
}
}
BudgetGraphComparator comparator = new BudgetGraphComparator();
Graph solvedGraph = new AdjacencyMatrixDirectedGraph(graph.getVertexSet().size());
for( Vertex v : graph.getVertexSet()) {
solvedGraph.addVertex(v.getId());
}
while( (!positivesDegree.isEmpty()) && (!negativesDegree.isEmpty())) {
// on tri les deux listes de vertex
comparator.setTable(positivesDegree);
Collections.sort(positives, comparator);
comparator.setTable(negativesDegree);
Collections.sort(negatives, comparator);
Collections.reverse(negatives);
Vertex maxPosV = positives.get(0);
Vertex maxNegV = negatives.get(0);
int posDegree = positivesDegree.get(maxPosV);
int negDegree = negativesDegree.get(maxNegV);
if (posDegree + negDegree == 0) {
try {
solvedGraph.addEdge(maxPosV.getId(), maxNegV.getId(), posDegree);
positives.remove(maxPosV);
positivesDegree.remove(maxPosV);
negatives.remove(maxNegV);
negativesDegree.remove(maxNegV);
} catch (VertexNotFoundException e) {
// on ajoute le sommet manquant... un tour pour rien
solvedGraph.addVertex(e.getVertex());
}
}
else if (posDegree + negDegree > 0) {
try {
solvedGraph.addEdge(maxPosV.getId(), maxNegV.getId(), -negDegree);
positivesDegree.remove(maxPosV);
positivesDegree.put(maxPosV, posDegree + negDegree);
negatives.remove(maxNegV);
negativesDegree.remove(maxNegV);
} catch (VertexNotFoundException e) {
// on ajoute le sommet manquant... un tour pour rien
solvedGraph.addVertex(e.getVertex());
}
}
else {
try {
solvedGraph.addEdge(maxPosV.getId(), maxNegV.getId(), posDegree);
positivesDegree.remove(maxPosV);
positives.remove(maxPosV);
negativesDegree.remove(maxNegV);
negativesDegree.put(maxNegV, posDegree + negDegree);
} catch ( VertexNotFoundException e) {
// on ajoute le sommet manquant... un tour pour rien
solvedGraph.addVertex(e.getVertex());
}
}
}