public long TotalVertexWeight(QuantityVertex <T> vertex) { return(Bfs(vertex).Select(v => v.Quantity).Sum()); // var total = vertex.Quantity; // var next = new Queue<QuantityVertex<T>>(vertex.Neighbors); // while (next.Count > 0) // { // var v = next.Dequeue(); // total += v.Quantity; // v.Neighbors.ForEach(next.Enqueue); // } // return total; // return vertex.Quantity + vertex.Descendants.Cast<QuantityVertex<T>>().Select(v => v.Quantity).Sum(); }
private long FindCorrectValue(QuantityVertex <string> vertex) { var count = vertex.NeighborCount; if (count == 2) { return(vertex.Neighbors.Select(FindCorrectValue).Max()); } if (count < 2) { return(-1); } // Return branches grouped by weight var counts = vertex.NeighborEdges.With(edge => edge.Data + edge.OtherAs(vertex).SumBranches()) .GroupBy(pair => pair.Value) .Select(pairs => pairs.Keys().ToArray()) .ToArray(); if (counts.Length == 1 || counts.AllEqual(b => b.Length)) { return(-1); } // The single branch that is different from the others var offBranch = counts.Single(b => b.Length == 1)[0].OtherAs(vertex); // Find whether the wrong value is further up the chain var chosen = FindCorrectValue(offBranch); if (chosen != -1) { return(chosen); } // Compute the different between the wrong value and the correct values var regularEdge = counts.First(b => b.Length != 1)[0]; return(regularEdge.Data + regularEdge.OtherAs(vertex).SumBranches() - (offBranch.Quantity + offBranch.SumBranches()) + offBranch.Quantity); }