private static AdjacentMap GetWichtelAdjazentMap() { AdjacentMap adjacentMap = new AdjacentMap(); IEnumerable <string[]> lines = File.ReadAllLines("wichtel.txt").Select(a => a.Split(' ')); foreach (var line in lines) { string nodeLabe = line[0]; if (!adjacentMap.ContainsKey(nodeLabe)) { List <string> neighbors = new List <string>(); for (int i = 1; i < line.Length; i++) { if (!neighbors.Contains(line[i])) { neighbors.Add(line[i]); } } adjacentMap.Add(nodeLabe, neighbors); } } return(adjacentMap); }
private VertexReachabilityInfo CheckReachabilityIntern(AdjacentMap pGraph, int pMaxSteps, string pStartVertex, string pEndVertex) { bool isReachable = false; List <string> tempPath = new List <string>(); if (pMaxSteps == 0) { isReachable = pGraph[pStartVertex].Contains(pEndVertex) || pStartVertex.Equals(pEndVertex); } else { foreach (var nextVertex in pGraph.Keys) { VertexReachabilityInfo isReachablePath1 = CheckReachabilityIntern(pGraph, pMaxSteps - 1, pStartVertex, nextVertex); VertexReachabilityInfo isReachablePath2 = CheckReachabilityIntern(pGraph, pMaxSteps - 1, nextVertex, pEndVertex); isReachable = isReachablePath1.IsReachable && isReachablePath2.IsReachable; if (isReachable) { tempPath.Add(nextVertex); tempPath.AddRange(isReachablePath2.Path); break; } } } return(new VertexReachabilityInfo(isReachable, tempPath)); }
static void Main(string[] args) { AdjacentMap wichtelAdjazentMap = GetWichtelAdjazentMap(); Dictionary <String, Variable> variableStore = new Dictionary <string, Variable>(); Formula wichtel3Sat = IndependentSetReducer.ReduceTo3Sat(wichtelAdjazentMap, variableStore); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); var satisfiableInfo = new SatResolver().IsSatisfiable(wichtel3Sat); stopwatch.Stop(); Console.WriteLine($"{Console.Out.NewLine}Time elapsed: {stopwatch.Elapsed}"); bool[] maxSatisfiebleAssignment = SatUtil.GetMaxSatisfiebleAssignment(satisfiableInfo.SatisfiableAssignments); if (satisfiableInfo.IsSatisfiable && maxSatisfiebleAssignment.Count(a => a) > 0) { Console.WriteLine("\nResolved Wichtel Independet Set!"); for (int i = 0; i < satisfiableInfo.VariableList.Count; i++) { Console.WriteLine("Wichtel {0}: {1}", satisfiableInfo.VariableList[i].Name, maxSatisfiebleAssignment[i]); } } else { Console.WriteLine("\nCould not resolve Wichtel Independet Set!"); } Console.ReadLine(); }
public Formula ReduceVertexCoverToSat(AdjacentMap pUndirectedGraph, int pMinVertexCount) { Dictionary <string, Variable> variables = new Dictionary <string, Variable>(); foreach (var key in pUndirectedGraph.Keys) { for (int i = 1; i <= pMinVertexCount; i++) { variables.Add($"{key}|{i}", new Variable($"{key}|{i}")); } } Console.WriteLine("Created Variables"); foreach (var variable in variables) { Console.WriteLine(variable.Value.ToString()); } var formula = new Formula(); for (int i = 1; i <= pMinVertexCount; i++) { if (i > 1) { formula.Add(_and); } var atMostOneList = variables.Values.Where(v => v.Name.EndsWith($"|{i}")).ToList(); var atMostOneFormular = AtMostOne(atMostOneList); formula.AddRange(atMostOneFormular); } List <string> processedEdges = new List <string>(); foreach (var key in pUndirectedGraph.Keys) { foreach (var adjacent in pUndirectedGraph[key]) { if (!processedEdges.Contains($"{key}|{adjacent}") && !processedEdges.Contains($"{adjacent}|{key}")) { var atLeastOneList = new List <Variable>(); for (int i = 1; i <= pMinVertexCount; i++) { atLeastOneList.Add(variables[$"{key}|{i}"]); atLeastOneList.Add(variables[$"{adjacent}|{i}"]); } var atleastOneFormular = AtLeastOne(atLeastOneList); formula.Add(_and); formula.Add(atleastOneFormular); processedEdges.Add($"{key}|{adjacent}"); } } } return(formula); }
public static GeographyStrategyInfo FindStrategy(AdjacentMap pDirectedGraph, string pStartNode) { GeographyStrategyInfo geographyStrategyInfo = FindStrategy(pDirectedGraph, pStartNode, true); return(geographyStrategyInfo.FoundStrategy ? geographyStrategyInfo : new GeographyStrategyInfo(false, new List <List <string> >())); }
public List <String> ApproximateMinVertexCover(AdjacentMap pUndirectedGraph) { List <string> coveredVertice = new List <string>(); List <string> labedEdges = pUndirectedGraph.GetLabedEdges(); while (labedEdges.Count != 0) { int rndEdgeIndex = _rnd.Next() % labedEdges.Count; var labedEdge = labedEdges[rndEdgeIndex]; string[] vertexes = labedEdge.Split('|'); foreach (var vertex in vertexes) { if (!coveredVertice.Contains(vertex)) { coveredVertice.Add(vertex); } } foreach (string vertex2 in pUndirectedGraph[vertexes[0]]) { string edgeLable = $"{vertexes[0]}|{vertex2}"; string edgeLabeReverse = $"{vertex2}|{vertexes[0]}"; if (labedEdges.Contains(edgeLable)) { labedEdges.Remove(edgeLable); } else if (labedEdges.Contains(edgeLabeReverse)) { labedEdges.Remove(edgeLabeReverse); } } foreach (string vertex2 in pUndirectedGraph[vertexes[1]]) { string edgeLable = $"{vertexes[1]}|{vertex2}"; string edgeLabeReverse = $"{vertex2}|{vertexes[0]}"; if (labedEdges.Contains(edgeLable)) { labedEdges.Remove(edgeLable); } else if (labedEdges.Contains(edgeLabeReverse)) { labedEdges.Remove(edgeLabeReverse); } } } return(coveredVertice); }
static void Main(string[] args) { var undirectedGraph = new AdjacentMap { { "1", new List <string>() { "2", "3" } }, { "2", new List <string>() { "4", "1" } }, { "3", new List <string>() { "1", "5" } }, { "4", new List <string>() { "2", "5", "6" } }, { "5", new List <string>() { "3", "4", "6" } }, { "6", new List <string>() { "4", "5" } } }; VertexCoverResolver vertexCoverResolver = new VertexCoverResolver(); List <string> smallestVertexCover = undirectedGraph.Keys.ToList(); for (int i = 0; i < 20; i++) { var approximateMinVertexCover = vertexCoverResolver.ApproximateMinVertexCover(undirectedGraph); if (smallestVertexCover.Count > approximateMinVertexCover.Count) { smallestVertexCover = approximateMinVertexCover; } Console.WriteLine($"Found Vertex Cover: {string.Join(", ", approximateMinVertexCover)}"); } Console.WriteLine($"Found smallest Vertex Cover: {string.Join(", ", smallestVertexCover)}"); Console.ReadLine(); }
public static Formula ReduceTo3Sat(AdjacentMap pGraph, Dictionary <string, Variable> pVariableStore) { Formula formular = new Formula(); foreach (string key in pGraph.Keys) { Variable currentVertex; if (!pVariableStore.ContainsKey(key)) { currentVertex = new Variable(key); pVariableStore.Add(key, currentVertex); } else { currentVertex = pVariableStore[key]; } foreach (string adjazen in pGraph[key]) { Variable adjazenVertex; if (!pVariableStore.ContainsKey(adjazen)) { adjazenVertex = new Variable(adjazen); pVariableStore.Add(adjazen, adjazenVertex); } else { adjazenVertex = pVariableStore[adjazen]; } formular.Add(new Bracket() { Not, currentVertex, Or, Not, adjazenVertex }); formular.Add(And); } } formular.RemoveAt(formular.Count - 1); return(formular); }
public VertexReachabilityInfo CheckReachability(AdjacentMap pGraph, int pMaxSteps, string pStartVertex, string pEndVertex) { VertexReachabilityInfo checkReachabilityIntern = CheckReachabilityIntern(pGraph, pMaxSteps, pStartVertex, pEndVertex); if (checkReachabilityIntern.IsReachable) { if (checkReachabilityIntern.Path.Count > 0 && checkReachabilityIntern.Path[0] != pStartVertex) { checkReachabilityIntern.Path.Insert(0, pStartVertex); } if (checkReachabilityIntern.Path[checkReachabilityIntern.Path.Count - 1] != pEndVertex) { checkReachabilityIntern.Path.Add(pEndVertex); } } return(checkReachabilityIntern); }
static void Main(string[] args) { //var graph = new AdjacentMap() //{ // {"A", new List<string>() {"B"}}, // {"B", new List<string>() {"C"}}, // {"C", new List<string>() {"D"}}, // {"D", new List<string>() {"E"}} //}; //int steps = 5; // 2^steps //string startVertex = "A"; //string endVertex = "E"; var graph = new AdjacentMap { { "1", new List <string>() { "2", "3" } }, { "2", new List <string>() { "4" } }, { "3", new List <string>() { "9" } }, { "4", new List <string>() { "5", "7" } }, { "5", new List <string>() { "3", "7" } }, { "6", new List <string>() { "2", "7" } }, { "7", new List <string>() { "8", "9" } }, { "8", new List <string>() { "6", "9" } }, { "9", new List <string>() { } } }; int steps = 2; // 2^steps string startVertex = "1"; string endVertex = "5"; Console.WriteLine($"Check if vertex {endVertex} is reachable from vertex {startVertex}"); VertexReachabilityChecker vertexReachabilityChecker = new VertexReachabilityChecker(); Stopwatch stopwatch = new Stopwatch(); //2^0 = 1 var vertexReachabilityInfo = vertexReachabilityChecker.CheckReachability(graph, steps, startVertex, endVertex); stopwatch.Stop(); Console.WriteLine($"{Console.Out.NewLine}Time elapsed: {stopwatch.Elapsed}"); if (!vertexReachabilityInfo.IsReachable) { Console.WriteLine($"\nVertex {endVertex} is not reachable from vertex {startVertex}."); } else { Console.WriteLine($"\nVertex {endVertex} is reachable from vertex {startVertex}."); Console.WriteLine($"Path: {string.Join("->", vertexReachabilityInfo.Path)}"); } Console.Out.Flush(); Console.ReadLine(); }
public static Formula ReduceTo3Sat(AdjacentMap pGraph) { Dictionary <String, Variable> variableStore = new Dictionary <string, Variable>(); Operator and = new Operator(Operator.Types.And); Operator or = new Operator(Operator.Types.Or); Operator not = new Operator(Operator.Types.Not); var formula = new Formula(); var isFirst = true; foreach (var node in pGraph.Keys) { Variable red; if (!variableStore.ContainsKey($"{node}|Red")) { red = new Variable($"{node}|Red"); variableStore.Add($"{node}|Red", red); } else { red = variableStore[$"{node}|Red"]; } Variable blue; if (!variableStore.ContainsKey($"{node}|Blue")) { blue = new Variable($"{node}|Blue"); variableStore.Add($"{node}|Blue", blue); } else { blue = variableStore[$"{node}|Blue"]; } Variable green; if (!variableStore.ContainsKey($"{node}|Green")) { green = new Variable($"{node}|Green"); variableStore.Add($"{node}|Green", green); } else { green = variableStore[$"{node}|Green"]; } var nodeHasColor = new Bracket() { red, or, blue, or, green }; if (!isFirst) { formula.Add(and); } else { isFirst = false; } formula.Add(nodeHasColor); foreach (var adjazenzNode in pGraph[node]) { Variable adjazenRed; if (!variableStore.ContainsKey($"{adjazenzNode}|Red")) { adjazenRed = new Variable($"{adjazenzNode}|Red"); variableStore.Add($"{adjazenzNode}|Red", adjazenRed); } else { adjazenRed = variableStore[$"{adjazenzNode}|Red"]; } Variable adjazenBlue; if (!variableStore.ContainsKey($"{adjazenzNode}|Blue")) { adjazenBlue = new Variable($"{adjazenzNode}|Blue"); variableStore.Add($"{adjazenzNode}|Blue", adjazenBlue); } else { adjazenBlue = variableStore[$"{adjazenzNode}|Blue"]; } Variable adjazenGreen; if (!variableStore.ContainsKey($"{adjazenzNode}|Green")) { adjazenGreen = new Variable($"{adjazenzNode}|Green"); variableStore.Add($"{adjazenzNode}|Green", adjazenGreen); } else { adjazenGreen = variableStore[$"{adjazenzNode}|Green"]; } formula.Add(and); formula.Add(new Bracket() { not, red, or, not, adjazenRed }); formula.Add(and); formula.Add(new Bracket() { not, blue, or, not, adjazenBlue }); formula.Add(and); formula.Add(new Bracket() { not, green, or, not, adjazenGreen }); } } return(formula); }
static void Main(string[] args) { var undirectedGraph = new AdjacentMap { { "1", new List <string>() { "2", "7", "11" } }, { "2", new List <string>() { "1", "3", "11" } }, { "3", new List <string>() { "2", "4", "10" } }, { "4", new List <string>() { "3", "5", "9" } }, { "5", new List <string>() { "4", "6", "9" } }, { "6", new List <string>() { "5", "7", "8" } }, { "7", new List <string>() { "1", "6", "8" } }, { "8", new List <string>() { "6", "7", "12" } }, { "9", new List <string>() { "4", "5", "12" } }, { "10", new List <string>() { "3", "12", "11" } }, { "11", new List <string>() { "1", "2", "10" } }, { "12", new List <string>() { "8", "9", "10" } } }; int vertexCount = 7; //Cover(1, 5, 3) //var undirectedGraph = new AdjacentMap //{ // {"1", new List<string>() {"2", "4"}}, // {"2", new List<string>() { "1", "3", "5"}}, // {"3", new List<string>() {"2", "5", "6", "7"}}, // {"4", new List<string>() {"1"}}, // {"5", new List<string>() {"2", "3", "6"}}, // {"6", new List<string>() {"3", "5"}}, // {"7", new List<string>() {"3"}} //}; //int vertexCount = 3; // Cover (5,3) //var undirectedGraph = new AdjacentMap //{ // {"2", new List<string>() { "3", "5"}}, // {"3", new List<string>() {"2", "5", "6", "7"}}, // {"5", new List<string>() {"2", "3", "6"}}, // {"6", new List<string>() {"3", "5"}}, // {"7", new List<string>() {"3"}} //}; //int vertexCount = 2; var vertexCoverReducter = new VertexCoverReducer(); Formula formula = vertexCoverReducter.ReduceVertexCoverToSat(undirectedGraph, vertexCount); Console.WriteLine(formula.ToString()); Console.WriteLine(); Console.WriteLine(); SatResolver satResolver = new SatResolver(); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); var satisfiableInfo = satResolver.IsSatisfiable(formula); stopwatch.Stop(); Console.WriteLine($"{Console.Out.NewLine}Time elapsed: {stopwatch.Elapsed}"); bool[] maxSatisfiebleAssignment = SatUtil.GetMinSatisfiebleAssignment(satisfiableInfo.SatisfiableAssignments); if (satisfiableInfo.IsSatisfiable && maxSatisfiebleAssignment.Count(a => a) > 0) { Console.WriteLine("\nThe vertex cover problem is satisfiable!"); for (int i = 0; i < satisfiableInfo.VariableList.Count; i++) { Console.WriteLine("{0}:{1}", satisfiableInfo.VariableList[i].Name, maxSatisfiebleAssignment[i]); } } else { Console.WriteLine("\nThe vertex cover problem is not satisfiable!"); } Console.ReadLine(); }
static void Main(string[] args) { // Let GG = { <G, b> | P1 has a winning strategy for the generalized geography game played on graph G starting at node b }; // 1 -> 2 -> 4 -> 5 -> 3 -> 9 // 1 -> 2 -> 4 -> 5 -> 7 -> 9 var dGraph = new AdjacentMap { { "1", new List <string>() { "2", "3" } }, { "2", new List <string>() { "4" } }, { "3", new List <string>() { "9" } }, { "4", new List <string>() { "5", "7" } }, { "5", new List <string>() { "3", "7" } }, { "6", new List <string>() { "2", "7" } }, { "7", new List <string>() { "8", "9" } }, { "8", new List <string>() { "6", "9" } }, { "9", new List <string>() { } } }; // 1 -> 3 -> 5 -> 6 //var dGraph = new AdjacentMap //{ // {"1", new List<string>() {"2", "3"}}, // {"2", new List<string>() {"3", "4" ,"5"}}, // {"3", new List<string>() {"5"}}, // {"4", new List<string>() {"5", "7"}}, // {"5", new List<string>() {"6", "7", "8"}}, // {"6", new List<string>() {"3"}}, // {"7", new List<string>() {"8", "9"}}, // {"8", new List<string>() {"6", "9"}}, // {"9", new List<string>() {}} //}; // No Strategy //var dGraph = new AdjacentMap() //{ // {"1", new List<string>() {"2", "3"}}, // {"2", new List<string>() {"4"}}, // {"3", new List<string>() {"4"}}, // {"4", new List<string>() }, //}; Console.WriteLine($"Try to find a winning strategy for Player 1."); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); var strategyInfo = GeneralizedGeoStrategyFinder.FindStrategy(dGraph, "1"); stopwatch.Stop(); Console.WriteLine($"{Console.Out.NewLine}Time elapsed: {stopwatch.Elapsed}"); Console.WriteLine($"{Console.Out.NewLine}Player 1 found a winning strategy: {strategyInfo.FoundStrategy}"); foreach (List <string> strategy in strategyInfo.Strategies) { Console.WriteLine($"Strategy: {String.Join(" -> ", strategy)}"); } Console.ReadLine(); }
private static void Main(string[] args) { var graph = new AdjacentMap() { { "A", new List <string>() { "B", "F", "C", "E" } }, { "B", new List <string>() { "A", "C", "D", "F" } }, { "C", new List <string>() { "B", "D", "A", "E" } }, { "D", new List <string>() { "C", "E", "B", "F" } }, { "E", new List <string>() { "D", "F", "C", "A" } }, { "F", new List <string>() { "E", "A", "B", "D" } } }; Formula formula = ThreeColoringReducer.ReduceTo3Sat(graph); Console.WriteLine("Formula:"); Console.WriteLine(formula); var satResolver = new SatResolver(); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); var satisfiableInfo = satResolver.IsSatisfiable(formula); stopwatch.Stop(); Console.WriteLine($"{Console.Out.NewLine}Time elapsed: {stopwatch.Elapsed}"); bool[] maxSatisfiebleAssignment = SatUtil.GetMaxSatisfiebleAssignment(satisfiableInfo.SatisfiableAssignments); if (satisfiableInfo.IsSatisfiable && maxSatisfiebleAssignment.Count(a => a) > 0) { Console.WriteLine("\nThe graph is 3-colorable!"); for (int i = 0; i < satisfiableInfo.VariableList.Count; i++) { var nodeColorInfo = satisfiableInfo.VariableList[i].Name .Split("|", StringSplitOptions.RemoveEmptyEntries); Console.WriteLine("Node {0}|{1}:{2}", nodeColorInfo[0], nodeColorInfo[1], maxSatisfiebleAssignment[i]); } } else { Console.WriteLine("\nThe graph is not 3-colorable!"); } Console.Out.Flush(); Console.ReadLine(); }
private static GeographyStrategyInfo FindStrategy(AdjacentMap pDirectedGraph, string pStartNode, bool pPlayer1Round) { GeographyStrategyInfo strategyInfo; //1. Measure the out-degree of node nstart.If this degree is 0, then return reject, because there are no moves available for player one. int nodeOutDegree = pDirectedGraph[pStartNode].Count; if (nodeOutDegree == 0) { // no moves possible strategyInfo = new GeographyStrategyInfo(false, new List <List <string> >() { new List <string>() { pStartNode } }); } else { //2. Construct a list of all nodes reachable from nstart by one edge: n1, n2, ..., ni. List <string> nextReachableNodes = pDirectedGraph[pStartNode]; //3. Remove nstart and all edges connected to it from G to form G1. AdjacentMap graph1 = new AdjacentMap(pDirectedGraph); graph1.Remove(pStartNode); List <string> keys = new List <string>(graph1.Keys); foreach (string key in keys) { List <string> neighbors = graph1[key]; if (neighbors.Contains(pStartNode)) { List <string> newNeighbors = neighbors.ToList(); newNeighbors.Remove(pStartNode); graph1[key] = newNeighbors; } } //4. For each node nj in the list n1, ..., ni, call M(< G1, nj >). bool foundStrategy = true; List <List <string> > tempStrategies = new List <List <string> >(); foreach (string nextReachableNode in nextReachableNodes) { var currentNodeStrategyInfo = FindStrategy(graph1, nextReachableNode, !pPlayer1Round); foundStrategy = foundStrategy && currentNodeStrategyInfo.FoundStrategy; if (!currentNodeStrategyInfo.FoundStrategy && pPlayer1Round || currentNodeStrategyInfo.FoundStrategy && !pPlayer1Round) { tempStrategies.AddRange(currentNodeStrategyInfo.Strategies); } } foreach (var strategy in tempStrategies) { strategy.Insert(0, pStartNode); } //5. If all of these calls return accept, then no matter which decision P1 makes, P2 has a strategy to win, so return reject. Otherwise(if one of the calls returns reject) P1 has a choice that will deny any successful strategies for P2, so return accept. strategyInfo = new GeographyStrategyInfo(!foundStrategy, tempStrategies); } return(strategyInfo); }