A basic representation of a Graph.
Exemple #1
0
        public static void Main()
        {
            Graph<int> graph = new Graph<int>();
            graph.AddConnection(1, 2, 14, true);
            graph.AddConnection(1, 3, 10, true);
            graph.AddConnection(2, 4, 14, true);
            graph.AddConnection(1, 5, 18, true);
            graph.AddConnection(2, 6, 9, true);
            graph.AddConnection(3, 6, 10, true);
            graph.AddConnection(3, 4, 14, true);
            graph.AddConnection(7, 8, 9, false);
            graph.AddConnection(4, 7, 15, false);
            graph.AddConnection(4, 8, 11, true);
            graph.AddConnection(9, 10, 7, false);
            graph.AddConnection(1, 10, 10, true);
            graph.AddConnection(3, 9, 11, true);
            graph.AddConnection(8, 11, 8, false);
            graph.AddConnection(11, 12, 12, true);
            graph.AddConnection(9, 12, 17, true);
            graph.AddConnection(5, 10, 13, true);
            graph.AddConnection(6, 12, 15, true);
            graph.AddConnection(7, 13, 7, true);
            graph.AddConnection(8, 13, 10, true);
            graph.AddConnection(11, 13, 13, true);
            graph.AddConnection(7, 12, 12, true);
            graph.AddConnection(11, 14, 7, true);
            graph.AddConnection(12, 14, 10, false);

            List<Edge<int>> edges = graph.PrimeMinimumSpanningTree(1);
            Console.WriteLine("The edges of the minimum spanning tree from node 1 is:");
            foreach (var edje in edges)
            {
                Console.WriteLine(edje);
            }
        }
        private static Graph<int> InitializeGraph()
        {
            var graph = new Graph<int>();

            for (var i = 0; i < 6; i++)
            {
                graph.AddNode(i);
            }

            graph.AddConnection(1, 2, 1, true);
            graph.AddConnection(1, 4, 2, true);
            graph.AddConnection(2, 3, 3, true);
            graph.AddConnection(2, 5, 13, true);
            graph.AddConnection(3, 4, 4, true);
            graph.AddConnection(3, 6, 3, true);
            graph.AddConnection(4, 6, 16, true);
            graph.AddConnection(4, 7, 14, true);
            graph.AddConnection(5, 6, 12, true);
            graph.AddConnection(5, 8, 1, true);
            graph.AddConnection(5, 9, 13, true);
            graph.AddConnection(6, 7, 1, true);
            graph.AddConnection(6, 9, 1, true);

            return graph;
        }
        public void AllCharsTest()
        {
            RDMain inst = this.testInst;
            PrivateObject param0 = new PrivateObject(inst); // TODO: Initialize to an appropriate value
            RDMain_Accessor target = new RDMain_Accessor(param0); // TODO: Initialize to an appropriate value
            target.tokenBuffer = ".";

            target.CharClass();

            Graph verificationGraph = new Graph();

            BaseVertex start = verificationGraph.StartVertex;
            start.Accepting = false;
            StringBuilder allChar = new StringBuilder();
            for (int i = 32; i <= 126; i++)
            {
                allChar.Append((char)i);
            }
            string trans = allChar.ToString();
            BaseVertex end = verificationGraph.CreateNewVertex(true);
            start.AddConnection(end, trans);

            Graph generated = target.lineGraph;

            Assert.AreEqual<Graph>(verificationGraph, generated, "Graphs are not equal.  \nExpected:\n\n{0}\n\nReceived:\n\n{1}",
                verificationGraph.ToDOT("Expected"), generated.ToDOT("Generated"));
            Assert.AreEqual<int>(target.tokenBuffer.Length, target.tokenPosition, "Token position is not in correct location. Expected {0}, Actual {1}",
                1, target.tokenPosition);
        }
        private static void Main()
        {
            var cableGraph = new Graph<int>();
            var inputLines = int.Parse(Console.ReadLine());

            for (var i = 0; i < inputLines; i++)
            {
                var edgeInfo = Console.ReadLine().Split().Select(int.Parse).ToArray();
                cableGraph.AddConnection(edgeInfo[0], edgeInfo[1], edgeInfo[2], true); 
            }

            var resultTree = cableGraph.PrimeMinimumSpanningTree(1);
            Console.WriteLine(resultTree.Sum(edge => edge.Distance));
        }
Exemple #5
0
        static void Main()
        {
            string epsilon = "0";
            Graph g = new Graph();

            //create vertices
            /*
            BaseVertex one = g.CreateNewVertex("0",false);
            BaseVertex two = g.CreateNewVertex("1",false);
            BaseVertex three = g.CreateNewVertex("2",false);
            */

            //BaseVertex four = g.CreateNewVertex("4",false);
            //BaseVertex five = g.CreateNewVertex("5",false);
            /*
            one.AddConnection(two, "a");

            two.AddConnection(two, "a");
            two.AddConnection(three, epsilon);

            three.AddConnection(three, "b");
            three.AddConnection(two, "a");
            three.AddConnection(one, "a");
            */

            BaseVertex v0 = g.CreateNewVertex("0", false);
            BaseVertex v1 = g.CreateNewVertex("1", true);
            BaseVertex v2 = g.CreateNewVertex("2", false);

            v0.AddConnection(v1, "a");

            v1.AddConnection(v1, "a");
            v1.AddConnection(v2, epsilon);

            v2.AddConnection(v2, "b");
            v2.AddConnection(v0, "a");
            v2.AddConnection(v1, "a");

            String nfaDOT = g.ToDOT("NFA");

            Converter c = new Converter(g,epsilon);

            //Console.WriteLine();
            c.convertToDFA(v0);
            //String dfaDOT = c.table.createGraph().ToDOT("DFA");
            //Console.WriteLine("Done");
            //Console.ReadLine();
        }
Exemple #6
0
        static void Main(string[] args)
        {
            Graph graph = new Graph();
            BaseVertex v1 = graph.CreateNewVertex("node1");
            BaseVertex v2 = graph.CreateNewVertex("node2");
            BaseVertex v3 = graph.CreateNewVertex("node3");
            BaseVertex v4 = graph.CreateNewVertex("node4");
            v1.Connections.Add(new Edge(v1, "", "a"));
            v1.Connections.Add(new Edge(v2, "", "a"));
            v1.Connections.Add(new Edge(v3, "", "a"));
            v1.Connections.Add(new Edge(v4, "", "a"));

            v1.Connections.Add(new Edge(v2, "", "b"));
            v1.Connections.Add(new Edge(v4, "", "b"));

            String s = graph.ToDOT("testgraph");
            Console.WriteLine(s);
        }
        public TransitionTable(Graph g, string epsilon)
        {
            columnNames = new ArrayList();
            rowNames = new ArrayList();
            epsilonTransition = epsilon;

            //create columNames ArrayList by iterating through every possible transition in the graph that is not an epsilon transition
            foreach (BaseVertex v in g.Vertices) {
                foreach (Edge e in v.Connections) {
                    if(!this.isInList(columnNames,e.Condition) && e.Condition != epsilonTransition){
                        columnNames.Add(e.Condition);
                    }
                }
            }

            //initialize and assign the width of the table
            table = new ArrayList[columnNames.Count];
            for (int i = 0; i < columnNames.Count;i++ ) {
                table[i] = new ArrayList(); // every array index is an arraylist, so those need to be initialized
            }
        }
Exemple #8
0
        public static Graph ReadFromFile(String path)
        {
            Graph g = new Graph();
            List<BaseVertex> verts = new List<BaseVertex>();

            using (FileStream fs = new FileStream(path, FileMode.Open))
            {
                using (StreamReader sr = new StreamReader(fs))
                {
                    int length = Int32.Parse(sr.ReadLine());

                    for (int x = 0; x < length; x++)
                    {
                        String isAccepting = sr.ReadLine();
                        bool accepting = isAccepting == "Accepting";
                        verts.Add(new BaseVertex(x.ToString(), accepting));
                    }

                    for (int x = 0; x < length; x++)
                    {
                        for (int y = 0; y < length; y++)
                        {
                            String connections = sr.ReadLine();
                            String[] transitions = connections.Split(',');

                            if (transitions.Length > 0)
                            {
                                foreach (String transition in transitions)
                                {
                                    String text = transition.Trim();
                                    if (text.Length > 0)
                                        verts[x].AddConnection(verts[y], text);
                                }
                            }
                        }
                    }
                }
            }

            g.vertices = verts;
            g.StartVertex = verts[1];

            return g;
        }
        public Graph createGraph()
        {
            normalizeNames();

            Graph g = new Graph();

            BaseVertex[] verts = new BaseVertex[rowNames.Count];
            Dictionary<String, BaseVertex> vertexTable = new Dictionary<string,BaseVertex>();

            for (int x = 0; x < rowNames.Count; x++)
            {
                bool accepting = false;
                foreach (BaseVertex v in ((VertexSet)rowNames[x]).vertices)
                {
                    if (v.Accepting)
                        accepting = true;
                }
                BaseVertex vertex = g.CreateNewVertex(((VertexSet)rowNames[x]).ToDOTString(), accepting);
                vertexTable.Add(vertex.Name, vertex);
                verts[x] = vertex;
            }

            //iterate over vertices
            for (int i = 0; i < rowNames.Count; i++)
            {
                //iterate over alphabet
                for (int x = 0; x < columnNames.Count; x++)
                {
                    String toVertexName = ((VertexSet)table[x][i]).ToDOTString();
                    verts[i].AddConnection(vertexTable[toVertexName], columnNames[x].ToString());
                }
            }

            g.StartVertex = g.Vertices[1];

            return g;
        }
Exemple #10
0
        /// <summary>
        /// Parse a line in the character class definition and token definition file
        /// </summary>
        /// <param name="line"></param>
        private Tuple<String, Graph> parseLine(string line)
        {
            line = line.Trim();

            if (line.Length == 0)
                return null;

            //switch parsing modes when we find a header for a new section
            if (line.Substring(0, 2) == "%%")
            {
                if (parsingMode == ParsingMode.None)
                    parsingMode = ParsingMode.CharacterClasses;
                else if (parsingMode == ParsingMode.CharacterClasses)
                    parsingMode = ParsingMode.TokenDefinitions;

                //skip to next line after getting rid of the comment line
                return null;
            }

            if(line.Substring(0,1) == "$")
            {
                //get char class name
                int index = 1;
                while(line[index] != ' ' && line[index] != '\t')
                {
                    index++;
                }
                string charClassName = line.Substring(1, index-1);

                //get char class definition text
                String charClassDef = line.Substring(index).Trim();

                //try parsing character class definition
                lineGraph = new Graph();
                tokenBuffer = charClassDef;
                tokenPosition = 0;

                Regexp();

                //insert name/NFA into the correct dictionary depending on if we are parsing character classes or token definitions
                if(parsingMode == ParsingMode.CharacterClasses)
                {
                    characterClasses.Add(charClassName, lineGraph);
                }
                else if(parsingMode == ParsingMode.TokenDefinitions)
                {
                    tokenDefinitions.Add(charClassName, lineGraph);
                }

                return new Tuple<string, Graph>(charClassName, lineGraph);
            }
            return null;
        }
        public void FullAlphaNumRangeTest()
        {
            RDMain inst = this.testInst;
            PrivateObject param0 = new PrivateObject(inst); // TODO: Initialize to an appropriate value
            RDMain_Accessor target = new RDMain_Accessor(param0); // TODO: Initialize to an appropriate value
            target.tokenBuffer = "[a-zA-Z0-9]";

            target.CharClass();

            Graph verificationGraph = new Graph();

            BaseVertex start = verificationGraph.StartVertex;
            start.Accepting = false;

            BaseVertex newV = verificationGraph.CreateNewVertex(true);
            start.AddConnection(newV, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");

            Graph generated = target.lineGraph;

            Assert.AreEqual<Graph>(verificationGraph, generated, "Graphs are not equal.  \nExpected:\n\n{0}\n\nReceived:\n\n{1}",
                verificationGraph.ToDOT("Expected"), generated.ToDOT("Generated"));
            Assert.AreEqual<int>(target.tokenBuffer.Length, target.tokenPosition, "Token position is not in correct location. Expected {0}, Actual {1}",
                1, target.tokenPosition);
        }
        public void DefinedCharClassExclusionTest()
        {
            RDMain inst = this.testInst;
            PrivateObject param0 = new PrivateObject(inst); // TODO: Initialize to an appropriate value
            RDMain_Accessor target = new RDMain_Accessor(param0); // TODO: Initialize to an appropriate value
            target.tokenBuffer = "[^0] IN $DIGIT";
            target.characterClasses["DIGIT"] = new Graph();
            BaseVertex v = target.characterClasses["DIGIT"].CreateNewVertex(true);
            target.characterClasses["DIGIT"].StartVertex.Accepting = false;
            target.characterClasses["DIGIT"].StartVertex.AddConnection(v, "0123456789");

            target.Regexp();

            Graph verificationGraph = new Graph();

            BaseVertex start = verificationGraph.StartVertex;
            start.Accepting = false;
            BaseVertex end = verificationGraph.CreateNewVertex(true);
            start.AddConnection(end, "123456789");

            Graph generated = target.lineGraph;

            Assert.AreEqual<Graph>(verificationGraph, generated, "Graphs are not equal.  \nExpected:\n\n{0}\n\nReceived:\n\n{1}",
                verificationGraph.ToDOT("Expected"), generated.ToDOT("Generated"));
            Assert.AreEqual<int>(target.tokenBuffer.Length, target.tokenPosition, "Token position is not in correct location. Expected {0}, Actual {1}",
                1, target.tokenPosition);
        }
 private void RexpPrime()
 {
     if (tokenPosition >= tokenBuffer.Length)
         return;
     if (tokenBuffer[tokenPosition] == '|')
     {
         tokenPosition++;
         Graph oldGraph = lineGraph;
         int oldPosition = tokenPosition;
         lineGraph = new Graph();
         Rexp1();
         RexpPrime();
         if (oldPosition == tokenPosition)
         {
             throw new SyntaxError("Union Operator not followed by any expressions");
         }
         else
         {
             oldGraph.CombineGraphs(lineGraph, true);
             lineGraph = oldGraph;
         }
     }
 }
 private void Rexp2()
 {
     if (tokenPosition >= tokenBuffer.Length)
         return;
     if (tokenBuffer[tokenPosition] == '(')
     {
         tokenPosition++;
         parenCounter++;
         Graph oldGraph = lineGraph;
         lineGraph = new Graph();
         Rexp();
         if (tokenPosition >= tokenBuffer.Length)
             throw new SyntaxError("Not enough closing parentheses.");
         if (tokenBuffer[tokenPosition] != ')')
         {
             throw new SyntaxError("Lexical Error. Failed to close a ) grouping");
         }
         tokenPosition++;
         parenCounter--;
         Rexp2Tail();
         oldGraph.CombineGraphs(this.lineGraph);
         this.lineGraph = oldGraph;
     }
     else if (RE_CHAR())
     {
         if (tokenPosition >= tokenBuffer.Length)
             return;
         Rexp2Tail();
     }
     else
     {
         Rexp3();
     }
 }
Exemple #15
0
        public Graph doParse()
        {
            Dictionary<String, Graph> nfas = new Dictionary<string, Graph>();
            foreach (string line in lines)
            {
                Tuple<String, Graph> g = parseLine(line);
            }

            Graph giantNFA = new Graph();
            giantNFA.StartVertex.Accepting = false;

            foreach (KeyValuePair<String, Graph> pair in tokenDefinitions)
            {
                giantNFA.CombineGraphs(pair.Value, false);
            }

            return giantNFA;
        }
Exemple #16
0
        /// <summary>
        /// Combines two graphs. Uses this as the base and adds the passed one to the end.
        /// </summary>
        /// <param name="that">Graph -> The graph to tack onto this one.</param>
        public void CombineGraphs(Graph that)
        {
            List<BaseVertex> ends = this.Accepting;

            that.start.Name = "start" + (this.vertices.Count + that.Vertices.Count);

            //Make sure to put vertices from the other graph into this one.
            foreach (BaseVertex v in that.Vertices)
            {
                this.vertices.Add(v);
                v.Name = "" + vertices.Count;
            }
            foreach (BaseVertex temp in ends)
            {
                temp.AddConnection(that.start, "");
                temp.Accepting = false;
            }
        }
Exemple #17
0
        public void CombineGraphs(Graph that, bool spacewaster)
        {
            that.start.Name = "start" + (this.vertices.Count + that.Vertices.Count);

            //Make sure to put vertices from the other graph into this one.
            foreach (BaseVertex v in that.Vertices)
            {
                this.vertices.Add(v);
                v.Name = "" + vertices.Count;
            }
            BaseVertex temp = this.start;
            temp.AddConnection(that.start, "");
        }
        public void SimpleBracketZeroTest()
        {
            RDMain inst = this.testInst;
            PrivateObject param0 = new PrivateObject(inst); // TODO: Initialize to an appropriate value
            RDMain_Accessor target = new RDMain_Accessor(param0); // TODO: Initialize to an appropriate value
            target.tokenBuffer = "[0]";

            target.CharClass();

            Graph verificationGraph = new Graph();

            BaseVertex start = verificationGraph.StartVertex;
            start.Accepting = false;

            BaseVertex newV = verificationGraph.CreateNewVertex(true);
            start.AddConnection(newV, "0");

            Graph generated = target.lineGraph;

            Assert.AreEqual<Graph>(verificationGraph, generated, "Graphs are not equal.  \nExpected:\n\n{0}\n\nReceived:\n\n{1}",
                verificationGraph.ToDOT("Expected"), generated.ToDOT("Generated"));
            Assert.AreEqual<int>(target.tokenBuffer.Length, target.tokenPosition, "Token position is not in correct location. Expected {0}, Actual {1}",
                1, target.tokenPosition);
        }
Exemple #19
0
        private static void TestInputFile(String path, Graph dfa, Dictionary<string, string> options)
        {
            try
            {
                using (FileStream fs = new FileStream(path, FileMode.Open))
                {
                    using (StreamReader sr = new StreamReader(fs))
                    {
                        String line = sr.ReadLine();

                        String[] inputTokens = line.Split(' ', '\t', '\n', '\r');

                        foreach (String inputToken in inputTokens)
                        {
                            if (inputToken.Trim().Length > 0)
                            {
                                if (dfa.AcceptsToken(inputToken))
                                    Console.WriteLine(inputToken + " was accepted.");
                                else
                                    Console.WriteLine(inputToken + " was rejected.");
                            }
                        }

                    }
                }
            }
            catch (FileNotFoundException err)
            {
                Console.Error.WriteLine("Couldn't open input for reading.");
                Environment.Exit(1);
            }
        }
Exemple #20
0
 public Graph MergeIntoGiantNFA()
 {
     Graph g = new Graph();
     return g;
 }