Exemplo n.º 1
0
        private static DesktopAplikacija.Entiteti.Put dijkstra(List <edge>[] v, DAL.Entiteti.Stanica pocetak, DAL.Entiteti.Stanica kraj, long velicina)
        {
            string s = string.Format("");

            bool[] visited = new bool[velicina];
            edge[] dd      = new edge[velicina];
            for (int i = 0; i < velicina; i++)
            {
                visited[i] = false;
                dd[i]      = new edge(-1, 0, 0);
            }

            SortedSet <edge> ss = new SortedSet <edge>();

            for (int i = 0; i < v[pocetak.SifraStanice].Count; i++)
            {
                ss.Add(new edge(v[pocetak.SifraStanice][i].c, v[pocetak.SifraStanice][i].v, pocetak.SifraStanice));
            }

            dd[pocetak.SifraStanice].v    = pocetak.SifraStanice;
            visited[pocetak.SifraStanice] = true;
            dd[pocetak.SifraStanice].c    = 0;
            edge tmp;

            while (ss.Count > 0)
            {
                tmp = ss.Min;
                ss.Remove(ss.Min);
                if (visited[tmp.v])
                {
                    continue;
                }

                dd[tmp.v].c    = tmp.c;
                visited[tmp.v] = true;
                dd[tmp.v].v    = tmp.parent;

                for (int i = 0; i < v[tmp.v].Count; i++)
                {
                    ss.Add(new edge(dd[tmp.v].c + v[tmp.v][i].c, v[tmp.v][i].v, tmp.v));
                }
            }

            if (dd[kraj.SifraStanice].c == -1)
            {
                return(new Entiteti.Put(-1, "Ne postoji put izmedju trazenih stanica!"));
            }

            long        tmp2 = kraj.SifraStanice;
            List <long> put  = new List <long>();

            put.Add(tmp2);
            while (tmp2 != pocetak.SifraStanice)
            {
                put.Add(dd[tmp2].v);
                tmp2 = dd[tmp2].v;
            }
            double tmpCijena;

            DAL.Entiteti.Stanica stanica1, stanica2;
            for (int i = put.Count - 1; i > 0; i--)
            {
                tmpCijena = 0;
                stanica1  = ks.getById(put[i]);
                stanica2  = ks.getById(put[i - 1]);
                foreach (edge ee in v[put[i]])
                {
                    if (ee.v == put[i - 1])
                    {
                        tmpCijena = ee.c;
                        break;
                    }
                }
                s += stanica1.Naziv + ", " + stanica1.Mjesto + " - " + stanica2.Naziv + ", " + stanica2.Mjesto + ": " + tmpCijena.ToString() + "KM\n";
            }

            return(new Entiteti.Put(dd[kraj.SifraStanice].c, s));
        }
Exemplo n.º 2
0
 public Transform fold(face f1, edge e1, face f2)
 {
     Plane p1, p2;
     Point3d cen = this.From;
     Vector3d v = this.To - this.From;
     p1 = new Plane(cen, v, f1.Normal);
     p2 = new Plane(cen, v, f2.Normal);
     return Transform.PlaneToPlane(p1, p2);
 }
Exemplo n.º 3
0
        bool b_f(object sender, EventArgs e, ref int [] d)
        {
            if (!G.isDir)
            {
                label2.Text = "Метод для орієнтованоо графа";
                return false;
            }
            int n = G.get_n(), m = G.get_m();

            int[] p = new int[n];
            edge[] ar_E;

            ar_E = new edge[m];

            for (int i = 0, n_in_edge = 0; i < n; ++i)
                for (int j = 0; j < n; ++j)
                    if (G.ar_sumiznist[i, j, 0] == 1 && n_in_edge < m)
                    {
                        ar_E[n_in_edge].a = i;
                        ar_E[n_in_edge].b = j;
                        ar_E[n_in_edge].cost = G.ar_sumiznist[i, j, 1];
                        ++n_in_edge;
                    }

            for (int i = 0; i < n; ++i)
            {
                p[i] = -1;
                d[i] = EPS;
            }

            d[choosen_vertex] = 0;
            int x = 0;
            for (int i=0; i < n; ++i)
            {
                x = -1;
                for (int j=0; j < m; ++j) // если реброс с - массой, и на парном месте в списке рёбер -  на него не смотреть

                    if (d[ar_E[j].a] < EPS)

                        if (d[ar_E[j].b] > d[ar_E[j].a] + ar_E[j].cost)
                        {
                            d[ar_E[j].b] = Math.Max(-EPS, d[ar_E[j].a] + ar_E[j].cost);
                            p[ar_E[j].b] = ar_E[j].a;
                            x = ar_E[j].b;
                        }
            }

            if (x == -1)
            {
                label2.Text = "No negative cycle from " + (choosen_vertex + 1).ToString();
                B_F = true;
                // кротчайший путь к вершинам
                Draw_Graph(sender, e);
                Gl.glColor3d(0, 1, 0);
                for (int i = 0; i < n; ++i)
                {

                    Gl.glRasterPos2f(G.ar_graph_point_position[i, 0] - 3 * devX, G.ar_graph_point_position[i, 1] + 13 * devY);
                    string text1 = "[ " + (d[i]).ToString() + " ]";

                    // в цикле foreach перебираем значения из массива text,
                    // который содержит значение строки для визуализации
                    foreach (char char_for_draw in text1)
                    {
                        // визуализируем символ c, с помощью функции glutBitmapCharacter, используя шрифт GLUT_BITMAP_9_BY_15.
                        Glut.glutBitmapCharacter(Glut.GLUT_BITMAP_9_BY_15, char_for_draw);
                    }
                }
                Gl.glFlush();
                AnT.Invalidate();
                return true;

            }
            else
            {
                int y = x;
                for (int i=0; i<n; ++i)
                    y = p[y];

                int[] path = new int[n];
                int n_in_p = 0;
                for (int cur=y; ; cur=p[cur])
                {
                    path[n_in_p++] = cur;
                    if (cur == y && n_in_p > 1)
                        break;
                }
                //reverse(path.begin(), path.end());
                int[] re_path = new int[n_in_p];
                string text = "";
                for (int k = 0; k < n_in_p; ++k)
                {
                    re_path[k] = path[n_in_p - k - 1];
                    text += (re_path[k] + 1).ToString();
                }

                label2.Text = "Negative cycle: ";
                textBox1.Text = text;
                B_F = false;
                return false;
            }
        }
Exemplo n.º 4
0
            public bool Deduce(edge[] edges, bool[] known, Dictionary<string, unparsedFunctionDeclaration> unparsedDeclarationsByName, Dictionary<node, unparsedFunctionDeclaration> unparsedDeclarationsByNode, Action<edge> isCorrect, Action<edge> isFlipped, sourceAsChars source)
            {
                switch (Type)
                {
                    case nodeType.Declaration:
                        // Declarations have only outputs, and they are always in the correct orientation because they define it
                        foreach (var e in edges)
                        {
                            if (e != null && e.StartNode == this)
                                isCorrect(e);
                            if (e != null && e.EndNode == this)
                                isFlipped(e);
                        }
                        Edges = edges;
                        Connectors = edges.Select(e => e == null ? connectorType.None : connectorType.Output).ToArray();
                        return true;

                    case nodeType.Literal:
                        // Literals have only outputs
                        foreach (var e in edges)
                        {
                            if (e != null && e.StartNode == this)
                                isCorrect(e);
                            if (e != null && e.EndNode == this)
                                isFlipped(e);
                        }
                        Edges = edges;
                        Connectors = edges.Select(e => e == null ? connectorType.None : connectorType.Output).ToArray();
                        return true;

                    case nodeType.Call:
                        unparsedFunctionDeclaration func;
                        if (!unparsedDeclarationsByNode.TryGetValue(this, out func) && !unparsedDeclarationsByName.TryGetValue(GetContent(source), out func))
                            throw new ParseErrorException(new ParseError("Call to undefined function: {0}".Fmt(GetContent(source)), X, Y, source.SourceFile));
                        return deduceGiven(edges, known, isCorrect, isFlipped, func.Connectors.Count(fc => fc != connectorType.None), new[] { func.Connectors }, source,
                            "Incorrect number of connectors to call to function: {0}".Fmt(GetContent(source)),
                            "Incorrect orientation of connectors to call to function: {0}".Fmt(GetContent(source)));

                    case nodeType.TJunction:
                        return deduceGiven(edges, known, isCorrect, isFlipped, 3, _tJunctionConnConf, source,
                            "Incorrect number of connectors to T junction (this error indicates a bug in the parser; please report it).",
                            "Incorrect orientation of connectors to T junction (this error indicates a bug in the parser; please report it).");

                    case nodeType.CrossJunction:
                        return deduceGiven(edges, known, isCorrect, isFlipped, 4, _connConf, source,
                            "Incorrect number of connectors to cross junction (this error indicates a bug in the parser; please report it).",
                            "Incorrect orientation of connectors to cross junction (this error indicates a bug in the parser; please report it).");

                    case nodeType.LambdaExpression:
                        return deduceGiven(edges, known, isCorrect, isFlipped, 4, _connConf, source,
                            "Lambda expressions must have four connectors.",
                            "Lambda expressions must have two adjacent inputs and two adjacent outputs.");

                    case nodeType.LambdaInvocation:
                        return deduceGiven(edges, known, isCorrect, isFlipped, 4, _connConf, source,
                            "Lambda invocations must have four connectors.",
                            "Lambda invocations must have two adjacent inputs and two adjacent outputs.");

                    case nodeType.End:
                        return deduceGiven(edges, known, isCorrect, isFlipped, 1, _endConnConf, source,
                            "Incorrect number of connectors to end node (this error indicates a bug in the parser; please report it).",
                            "Incorrect orientation of connectors to end node (this error indicates a bug in the parser; please report it).");
                }
                throw new ParseErrorException(new ParseError("The parser encountered an internal error: unrecognised node type: {0}".Fmt(Type), X, Y, source.SourceFile));
            }
Exemplo n.º 5
0
        public Mesh Unfold(Mesh mesh)
        {
            List<face> Faces = new List<face>();
            List<edge> Edges = new List<edge>();

            mesh.Faces.ConvertQuadsToTriangles();
            mesh.UnifyNormals();
            mesh.Compact();
            Rhino.Geometry.Collections.MeshTopologyEdgeList el = mesh.TopologyEdges;
            Rhino.Geometry.Collections.MeshTopologyVertexList vs = mesh.TopologyVertices;
            mesh.FaceNormals.ComputeFaceNormals();
            //Print(mesh.FaceNormals.Count.ToString());
            //  Print(mesh.Vertices.Count.ToString());
            for (int i = 0; i < mesh.Faces.Count; i++)
            {
                face f1 = new face(
                  new Point3d(mesh.Vertices[mesh.Faces[i].A]),
                  new Point3d(mesh.Vertices[mesh.Faces[i].B]),
                  new Point3d(mesh.Vertices[mesh.Faces[i].C]),
                  mesh.FaceNormals[i]
                  );

                Faces.Add(f1);
            }
            for (int i = 0; i < el.Count; i++)
            {
                int[] faceid = el.GetConnectedFaces(i);

                edge e1 = new edge(vs[el.GetTopologyVertices(i).I], vs[el.GetTopologyVertices(i).J]);
                if (faceid.Length == 1)
                {
                    e1.Faces = new face[1];
                    e1.Faces[0] = Faces[faceid[0]];
                }
                else if (faceid.Length > 1)
                {
                    e1.Faces = new face[2];
                    e1.Faces[0] = Faces[faceid[0]];
                    e1.Faces[1] = Faces[faceid[1]];
                }
                e1.ID = i;
                Edges.Add(e1);
            }
            for (int i = 0; i < mesh.Faces.Count; i++)
            {
                int[] edgeid = el.GetEdgesForFace(i);
                face f1 = Faces[i];
                f1.edges[0] = Edges[edgeid[0]];
                f1.edges[1] = Edges[edgeid[1]];
                f1.edges[2] = Edges[edgeid[2]];
                f1.ID = i;
            }

            /* List<  Mesh> output2 = new List<  Mesh>();
             for (int i = 0; i < Faces.Count; i++)
             {
               output2.Add(Faces[i].DrawFace());
             }
             B = output2;
             */
            face f = Faces[0];
            f.AddTransform(Transform.PlaneToPlane(new Plane(f.Center(), f.Normal), Plane.WorldXY));

            FaceLoop(f);
            //Print(f.Pts[0].X.ToString() + "/" + f.Pts[0].Y.ToString() + "/" + f.Pts[0].Z.ToString());
            Mesh output = new Mesh();
            for (int i = 0; i < Faces.Count; i++)
            {
                output.Append(Faces[i].DrawFace());
            }
            return output;
        }
Exemplo n.º 6
0
 static bool EdgeNode(edge E, string N1, string N2)
 {
     return(E.N1 == N1 && E.N2 == N2 || E.N1 == N2 && E.N2 == N1);
 }
Exemplo n.º 7
0
 private void throwDisallowedDependency(edge latestOutput, edge disallowedDependency)
 {
     throw new ParseErrorException(
         new ParseError("Output cannot depend on a more-deeply nested lambda expression input.", latestOutput.EndX, latestOutput.EndY, _source.SourceFile),
         new ParseError("    — Lambda expression input is here.", disallowedDependency.StartX, disallowedDependency.StartY, _source.SourceFile)
     );
 }
Exemplo n.º 8
0
 public bool EqualTo(edge el)
 {
     if (this.From.Equals(el.From) && this.To.Equals(el.To)) return true;
     if (this.From.Equals(el.To) && this.To.Equals(el.From)) return true;
     return false;
 }
Exemplo n.º 9
0
 public tribox(point[] pts, edge[] els)
 {
     Cedges = new edge[6];
     Points = new point[4];
     Cedges[0] = els[0]; Cedges[1] = els[1]; Cedges[2] = els[2];
     Cedges[3] = els[3]; Cedges[4] = els[4]; Cedges[5] = els[5];
     Points[0] = pts[0]; Points[1] = pts[1]; Points[2] = pts[2]; Points[3] = pts[3];
 }
Exemplo n.º 10
0
 static void swap(edge[] arr, int index1, int index2)
 {
     edge temp = arr[index1];
     arr[index1] = arr[index2];
     arr[index2] = temp;
 }
Exemplo n.º 11
0
        public static void Unwrap(double[,] image)//todo проверки выходов за диапазоны
        {
            int size0 = image.GetUpperBound(0);
            int size1 = image.GetUpperBound(1);

            pixel[,] pixels = new pixel[size0 + 1, size1 + 1];
            List <edge> edges = new List <edge>();

            for (int i = 1; i < size0; i++)
            {
                for (int j = 1; j < size1; j++)
                {
                    double H  = gamma(image[i, j - 1] - image[i, j]) - gamma(image[i, j] - image[i, j + 1]); //wrap(image[i,j-1]-image[i,j])-wrap(image[i,j]-image[i,j+1])
                    double V  = gamma(image[i - 1, j] - image[i, j]) - gamma(image[i, j] - image[i + 1, j]);
                    double D1 = gamma(image[i - 1, j - 1] - image[i, j]) - gamma(image[i, j] - image[i + 1, j + 1]);
                    double D2 = gamma(image[i - 1, j + 1] - image[i, j]) - gamma(image[i, j] - image[i + 1, j - 1]);
                    double R  = (H * H + V * V + D1 * D1 + D2 * D2);
                    pixels[i, j] = new pixel()
                    {
                        reliability = R, image = image, i = i, j = j
                    };
                }
            }

            for (int i = 0; i <= size0; i++)
            {
                int   j1    = 0;
                pixel temp1 = new pixel()
                {
                    reliability = 0, image = image, i = i, j = j1
                };
                pixels[i, j1] = temp1;
                int   j2    = size1;
                pixel temp2 = new pixel()
                {
                    reliability = 0, image = image, i = i, j = j2
                };
                pixels[i, j2] = temp2;
            }

            for (int j = 0; j <= size1; j++)
            {
                int   i1    = 0;
                pixel temp1 = new pixel()
                {
                    reliability = 0, image = image, i = i1, j = j
                };
                pixels[i1, j] = temp1;
                int   i2    = size0;
                pixel temp2 = new pixel()
                {
                    reliability = 0, image = image, i = i2, j = j
                };
                pixels[i2, j] = temp2;
            }

            {
                pixel  pixel1     = pixels[0, 0];
                pixel  pixel2     = pixels[0, 1];
                int    _increment = find_wrap(pixel1.image[pixel1.i, pixel1.j], pixel2.image[pixel2.i, pixel2.j]);
                double r          = pixel1.reliability + pixel2.reliability;
                //  if (r > 0)
                {
                    edge edge = new edge()
                    {
                        pixel1     = pixel1,
                        pixel2     = pixel2,
                        reaibility = r,
                        increment  = _increment
                    };
                    edges.Add(edge);
                }
            }


            {
                pixel  pixel1     = pixels[0, 0];
                pixel  pixel2     = pixels[1, 0];
                int    _increment = find_wrap(pixel1.image[pixel1.i, pixel1.j], pixel2.image[pixel2.i, pixel2.j]);
                double r          = pixel1.reliability + pixel2.reliability;
                //  if (r > 0)
                {
                    edge edge = new edge()
                    {
                        pixel1     = pixel1,
                        pixel2     = pixel2,
                        reaibility = r,
                        increment  = _increment
                    };
                    edges.Add(edge);
                }
            }

            for (int i = 1; i <= size0; i++)
            {
                for (int j = 1; j <= size1; j++)
                {
                    {
                        pixel  pixel1     = pixels[i - 1, j];
                        pixel  pixel2     = pixels[i, j];
                        int    _increment = find_wrap(pixel1.image[pixel1.i, pixel1.j], pixel2.image[pixel2.i, pixel2.j]);
                        double r          = pixel1.reliability + pixel2.reliability;
                        //  if (r > 0)
                        {
                            edge edge = new edge()
                            {
                                pixel1     = pixel1,
                                pixel2     = pixel2,
                                reaibility = r,
                                increment  = _increment
                            };
                            edges.Add(edge);
                        }
                    }

                    {
                        pixel  pixel1     = pixels[i, j - 1];
                        pixel  pixel2     = pixels[i, j];
                        int    _increment = find_wrap(pixel1.image[pixel1.i, pixel1.j], pixel2.image[pixel2.i, pixel2.j]);
                        double r          = pixel1.reliability + pixel2.reliability;
                        // if (r > 0)
                        {
                            edge edge = new edge()
                            {
                                pixel1     = pixel1,
                                pixel2     = pixel2,
                                reaibility = r,
                                increment  = _increment
                            };
                            edges.Add(edge);
                        }
                    }
                }
            }

            double val = ((double)edges.Count) / ((double)pixels.Length);

            edges.Sort(new edgeComparer());
            foreach (edge _edge in edges)
            {
                pixel PIXEL1 = _edge.pixel1;
                pixel PIXEL2 = _edge.pixel2;
                pixel group1;
                pixel group2;
                int   incremento;

                if (PIXEL2.head != PIXEL1.head)
                {
                    // PIXELM 2 is alone in its group
                    // merge this pixel with PIXELM 1 group and find the number of 2 pi to add
                    // to or subtract to unwrap it
                    if ((PIXEL2.next == null) && (PIXEL2.head == PIXEL2))
                    {
                        PIXEL1.head.last.next = PIXEL2;
                        PIXEL1.head.last      = PIXEL2;
                        (PIXEL1.head.number_of_pixels_in_group)++;
                        PIXEL2.head      = PIXEL1.head;
                        PIXEL2.increment = PIXEL1.increment - _edge.increment;
                    }

                    // PIXELM 1 is alone in its group
                    // merge this pixel with PIXELM 2 group and find the number of 2 pi to add
                    // to or subtract to unwrap it
                    else if ((PIXEL1.next == null) && (PIXEL1.head == PIXEL1))
                    {
                        PIXEL2.head.last.next = PIXEL1;
                        PIXEL2.head.last      = PIXEL1;
                        (PIXEL2.head.number_of_pixels_in_group)++;
                        PIXEL1.head      = PIXEL2.head;
                        PIXEL1.increment = PIXEL2.increment + _edge.increment;
                    }

                    // PIXELM 1 and PIXELM 2 both have groups
                    else
                    {
                        group1 = PIXEL1.head;
                        group2 = PIXEL2.head;
                        // if the no. of pixels in PIXELM 1 group is larger than the
                        // no. of pixels in PIXELM 2 group.  Merge PIXELM 2 group to
                        // PIXELM 1 group and find the number of wraps between PIXELM 2
                        // group and PIXELM 1 group to unwrap PIXELM 2 group with respect
                        // to PIXELM 1 group.  the no. of wraps will be added to PIXELM 2
                        // group in the future
                        if (group1.number_of_pixels_in_group >
                            group2.number_of_pixels_in_group)
                        {
                            // merge PIXELM 2 with PIXELM 1 group
                            group1.last.next = group2;
                            group1.last      = group2.last;
                            group1.number_of_pixels_in_group =
                                group1.number_of_pixels_in_group +
                                group2.number_of_pixels_in_group;
                            incremento =
                                PIXEL1.increment - _edge.increment - PIXEL2.increment;
                            // merge the other pixels in PIXELM 2 group to PIXELM 1 group
                            while (group2 != null)
                            {
                                group2.head       = group1;
                                group2.increment += incremento;
                                group2            = group2.next;
                            }
                        }

                        // if the no. of pixels in PIXELM 2 group is larger than the
                        // no. of pixels in PIXELM 1 group.  Merge PIXELM 1 group to
                        // PIXELM 2 group and find the number of wraps between PIXELM 2
                        // group and PIXELM 1 group to unwrap PIXELM 1 group with respect
                        // to PIXELM 2 group.  the no. of wraps will be added to PIXELM 1
                        // group in the future
                        else
                        {
                            // merge PIXELM 1 with PIXELM 2 group
                            group2.last.next = group1;
                            group2.last      = group1.last;
                            group2.number_of_pixels_in_group =
                                group2.number_of_pixels_in_group +
                                group1.number_of_pixels_in_group;
                            incremento =
                                PIXEL2.increment + _edge.increment - PIXEL1.increment;
                            // merge the other pixels in PIXELM 2 group to PIXELM 1 group
                            while (group1 != null)
                            {
                                group1.head       = group2;
                                group1.increment += incremento;
                                group1            = group1.next;
                            } // while
                        }     // else
                    }         // else
                }             // if
            }

            foreach (pixel pixel in pixels)
            {
                if (pixel.i == 0 && pixel.j == 0)
                {
                    int q = 0;
                }
                pixel.image[pixel.i, pixel.j] += TWOPI * ((double)pixel.increment);
            }
            //return result;
        }
        static void Main(string[] args)
        {
            //initializing the path to get the lines from the text file


            //creating an array of linkedlist - each item(i) in this array is a represention of the vertex i and the linkedlist nodes is what it is connected to
            // LinkedList<int>[] vertices = new LinkedList<int>[v];

            //initializing the vertices linkedlist array to have linkedlist as the items i.e v[i] is a linked list.


            int trials = 1;
            int min    = 2518;

            while (trials <= 1000444)
            {
                string   path  = @"C:\Users\joshu\Desktop\KragerAlgorithm";
                string[] lines = File.ReadAllLines(path);

                int no_of_edges = 0;
                int v           = lines.Length;

                int         ans   = 0;
                List <edge> edges = new List <edge>();
                //finding the edges and populating the edges of a vertice i.e vertices[i] (which is a node of linkedlist vertices)
                for (int i = 0; i < lines.Length; i++)
                {
                    FindVerticesinLine(lines[i], i);
                }

                //function to find the edges of a vertice(Vertices[i]) and adding it as a LinkedListNode
                void FindVerticesinLine(string s, int i)
                {
                    string num = "";

                    foreach (char c in s)
                    {
                        if (c != '\t')
                        {
                            num += c;
                            //Console.WriteLine("num is {0}",num);
                        }
                        else
                        {
                            if ((i + 1).ToString() != num)
                            {
                                int adj_ver = Convert.ToInt16(num);
                                //addEdge(vertices, i, adj_ver);
                                if (i < adj_ver)
                                {
                                    no_of_edges++;
                                    edge e = new edge();
                                    e.src = i;
                                    e.des = adj_ver - 1;
                                    edges.Add(e);
                                }
                                num = "";
                            }
                            else
                            {
                                num = "";
                            }
                        }
                    }
                }

                // no_of_edges = no_of_edges;
                //Console.WriteLine("no of edges is {0}", no_of_edges);



                VerticeRepresent[] verts = new VerticeRepresent[v];
                for (int i = 0; i < v; i++)
                {
                    verts[i]     = new VerticeRepresent();
                    verts[i].ver = i;
                }
                Random random = new Random();

                int no_of_vertices = v;

                while (no_of_vertices > 2)
                {
                    KragerAlgorithm();
                    //Console.WriteLine("no of vertices is {0}",no_of_vertices);
                    //Console.WriteLine("no of edges is {0}",no_of_edges);
                }

                void KragerAlgorithm()
                {
                    edge random_Edge     = edges[random.Next() % edges.Count];
                    int  src_random_Edge = GetVertice(random_Edge.src);
                    int  des_random_Edge = GetVertice(random_Edge.des);

                    //checking that i is not contracted
                    if (src_random_Edge != des_random_Edge)
                    {
                        //getting a random edge

                        verts[des_random_Edge].ver = src_random_Edge;
                        no_of_vertices--;
                    }
                }

                for (int i = 0; i < edges.Count; i++)
                {
                    if (GetVertice(edges[i].src) != GetVertice(edges[i].des))
                    {
                        ans++;
                    }
                }

                if (ans < min)
                {
                    min = ans;
                    using (StreamWriter sw = File.AppendText(@"C:\Users\joshu\Desktop\ans"))
                    {
                        sw.WriteLine(min);
                    }
                    Console.WriteLine(min);
                }

                int GetVertice(int edge_ver)
                {
                    while (edge_ver != verts[edge_ver].ver)
                    {
                        edge_ver = verts[edge_ver].ver;
                    }
                    return(edge_ver);
                }

                trials++;
            }


            Console.ReadKey();
        }
Exemplo n.º 13
0
        private DesktopAplikacija.Entiteti.Put dijkstra(List <edge>[] v, DAL.Entiteti.Stanica pocetak, DAL.Entiteti.Stanica kraj, long velicina)
        {
            string s = string.Format("");

            bool[] visited = new bool[velicina];
            edge[] dd      = new edge[velicina];
            for (int i = 0; i < velicina; i++)
            {
                visited[i] = false;
                dd[i]      = new edge();
            }

            SortedSet <edge> ss = new SortedSet <edge>();

            for (int i = 0; i < v[pocetak.SifraStanice].Count; i++)
            {
                ss.Add(new edge(v[pocetak.SifraStanice][i].c, v[pocetak.SifraStanice][i].v, pocetak.SifraStanice));
            }

            dd[pocetak.SifraStanice].v    = pocetak.SifraStanice;
            visited[pocetak.SifraStanice] = true;
            dd[pocetak.SifraStanice].c    = 0;
            edge tmp;

            while (ss.Count > 0)
            {
                tmp = ss.Min;
                ss.Remove(ss.Min);
                if (visited[tmp.v])
                {
                    continue;
                }

                dd[tmp.v].c    = tmp.c;
                visited[tmp.v] = true;
                dd[tmp.v].v    = tmp.parent;

                for (int i = 0; i < v[tmp.v].Count; i++)
                {
                    ss.Add(new edge(dd[tmp.v].c + v[tmp.v][i].c, v[tmp.v][i].v, tmp.v));
                }
            }
            long        tmp2 = kraj.SifraStanice;
            List <long> put  = new List <long>();

            put.Add(tmp2);
            while (tmp2 != pocetak.SifraStanice)
            {
                put.Add(dd[tmp2].v);
                tmp2 = dd[tmp2].v;
            }

            DAL.Entiteti.Stanica stanica1, stanica2;
            for (int i = put.Count - 1; i > 0; i--)
            {
                stanica1 = ks.getById(put[i]);
                stanica2 = ks.getById(put[i - 1]);
                s       += stanica1.Naziv + ", " + stanica1.Mjesto + " - " + stanica2.Naziv + ", " + stanica2.Mjesto + "\n";
            }

            return(new Entiteti.Put(dd[kraj.SifraStanice].c, s));
        }
Exemplo n.º 14
0
    private bool[] computeResults()
    {
        bool[] results = new bool[difficultyLevel];
        for (int i = 0; i < difficultyLevel; i++)
        {
            results[i] = false;
        }
        LinkedList <edge> ansInEdge = new LinkedList <edge>();

        for (int i = 0; i < difficultyLevel; i++)
        {
            if (ans[i].Count < 2)
            {
                continue;                                       //can't make edges with <2 vertices
            }
            //fill up ansInEdge
            while (ans[i].Count > 1)
            {
                int v1, v2;
                v1 = ans[i].First.Value;
                ans[i].RemoveFirst();
                v2 = ans[i].First.Value;
                ansInEdge.AddLast(new edge(v1, v2));
            }

            Debug.Log("# of Edges: " + ansInEdge.Count);

            edge[] arr1 = new edge[qnInEdges[i].Count];
            bool[] arr2 = new bool[arr1.Length];
            for (int j = 0; j < arr1.Length; j++)
            {
                arr2[j] = false;
            }

            qnInEdges[i].CopyTo(arr1, 0);

            bool hasIrrelevant = false;

            //compare ansInEdge w qnInEdge
            while (ansInEdge.Count > 0)
            {
                hasIrrelevant = true;
                for (int j = 0; j < arr1.Length; j++)
                {
                    if (arr1[j].isEqual(ansInEdge.First.Value))
                    {
                        arr2[j] = true;
                        ansInEdge.RemoveFirst();
                        hasIrrelevant = false;
                        break;
                    }
                }
                if (hasIrrelevant)
                {
                    break;
                }
            }

            bool checkArr2 = true;
            for (int k = 0; k < arr2.Length; k++)
            {
                if (!arr2[k])
                {
                    checkArr2 = false;
                    break;
                }
            }
            //1st condition - check if all edges are met
            //2nd condition - check if
            if (checkArr2 && !hasIrrelevant)
            {
                results[i] = true;
            }
        }
        return(results);
    }
Exemplo n.º 15
0
    // Prims algorithm (Minimum spanning tree):
    IEnumerator prims(List <edge> vert)
    {
        print("Started - Prims Algorithm...");

        // Copy the vertices.
        List <edge>    edges    = vert;
        List <Vector3> vertices = new List <Vector3>();

        treeVertices = new List <Vector3>();
        treeEdges    = new List <edge>();

        for (int i = 0; i < edges.Count; i++)
        {
            if (!vertices.Contains(edges[i].start))
            {
                vertices.Add(edges[i].start);
            }
            else if (!vertices.Contains(edges[i].end))
            {
                vertices.Add(edges[i].end);
            }
        }

        int randomVertice = UnityEngine.Random.Range(0, vertices.Count);

        treeVertices.Add(vertices[randomVertice]);
        vertices.RemoveAt(randomVertice);

        while (vertices.Count > 0)
        {
            edge optEdge = null;

            foreach (edge e in edges)
            {
                if ((vertices.Contains(e.start) && !vertices.Contains(e.end)) ||
                    (vertices.Contains(e.end) && !vertices.Contains(e.start)))
                {
                    if (optEdge == null)
                    {
                        optEdge = e;
                    }
                    else if (optEdge.weight > e.weight)
                    {
                        optEdge = e;
                    }
                }
            }

            Vector3 vertex = new Vector3();

            if (vertices.Contains(optEdge.start))
            {
                vertex = optEdge.start;
            }
            else
            {
                vertex = optEdge.end;
            }

            vertices.Remove(vertex);
            treeVertices.Add(vertex);

            edges.Remove(optEdge);
            treeEdges.Add(optEdge);

            yield return(new WaitForSeconds(1.0f));
        }
        print("Finished - Prims algorithm.");

        Cam.GetComponent <cameraRender>().toggleDelaunay = false;
        Cam.GetComponent <cameraRender>().togglePrims    = true;

        StartCoroutine(generateHallways());
    }
Exemplo n.º 16
0
 public tribox(point[] pts)
 {
     Cedges = new edge[6];
     Points = new point[4];
     Points[0] = pts[0]; Points[1] = pts[1]; Points[2] = pts[2]; Points[3] = pts[3];
     Cedges[0] = new edge(pts[0], pts[1]);
     Cedges[1] = new edge(pts[0], pts[2]);
     Cedges[2] = new edge(pts[0], pts[3]);
     Cedges[3] = new edge(pts[1], pts[2]);
     Cedges[4] = new edge(pts[2], pts[3]);
     Cedges[5] = new edge(pts[3], pts[1]);
 }
Exemplo n.º 17
0
        static public void AddEdge(string Node1, string Node2, int EdgeVal)
        {
            edge temp = new edge(Node1, Node2, EdgeVal);

            Edges.Add(temp);
        }
Exemplo n.º 18
0
 public tribox(Point3f[] pts)
 {
     Cedges = new edge[6];
     Points = new point[4];
     Points[0] = new point(pts[0]); Points[1] = new point(pts[1]);
     Points[2] = new point(pts[2]); Points[3] = new point(pts[3]);
     Cedges[0] = new edge(Points[0], Points[1]);
     Cedges[1] = new edge(Points[0], Points[2]);
     Cedges[2] = new edge(Points[0], Points[3]);
     Cedges[3] = new edge(Points[1], Points[2]);
     Cedges[4] = new edge(Points[2], Points[3]);
     Cedges[5] = new edge(Points[3], Points[1]);
 }
        static void Main(string[] args)
        {
            /*********************************************************/
            const int DEBUGHIGH  = 3;
            const int DEBUGLOW   = 2;
            int       localdebug = DEBUGLOW;
            bool      localinput = false;
            string    inputFile  = "input2.txt";
            /*********************************************************/
            List <string> lines       = new List <string>();
            int           currentLine = 0;

            if (!localinput)
            {
                string tmpLine   = "";
                int    lineIndex = 0;
                while ((tmpLine = Console.ReadLine()) != null)
                {
                    lines.Insert(lineIndex++, tmpLine);
                }
            }
            else
            {
                string[] tmpLines = System.IO.File.ReadAllLines(inputFile);
                lines = new List <string>(tmpLines);
            }
            /*********************************************************/

            int testCases = Convert.ToInt32(lines[currentLine++]);

            for (int x = 0; x < testCases; x++)
            {
                int[]       firstInput  = Array.ConvertAll(lines[currentLine++].Split(' '), int.Parse);
                int         numberNodes = firstInput[0];
                int         numberEdges = firstInput[1];
                node[]      nodes       = new node[numberNodes];
                List <node> theQ        = new List <node>();

                for (int i = 0; i < numberNodes; i++)
                {
                    nodes[i]        = new node();
                    nodes[i].nodeId = i;
                }

                for (int i = 0; i < numberEdges; i++)
                {
                    int[] currentInput = Array.ConvertAll(lines[currentLine++].Split(' '), int.Parse);
                    bool  addEdge      = true;
                    edge  leftEdge     = new edge();
                    edge  rightEdge    = new edge();
                    leftEdge.edgeNumber  = currentInput[0] - 1;
                    leftEdge.edgeWeight  = currentInput[2];
                    rightEdge.edgeNumber = currentInput[1] - 1;
                    rightEdge.edgeWeight = currentInput[2];


                    edge tmpEdge = null;
                    if (nodes[rightEdge.edgeNumber] != null)
                    {
                        tmpEdge = nodes[rightEdge.edgeNumber].edges.Find(item => item.edgeNumber == leftEdge.edgeNumber);
                    }

                    if (nodes[leftEdge.edgeNumber] != null)
                    {
                        tmpEdge = nodes[leftEdge.edgeNumber].edges.Find(item => item.edgeNumber == rightEdge.edgeNumber);
                    }


                    if (tmpEdge != null && tmpEdge.edgeWeight < rightEdge.edgeWeight)
                    {
                        addEdge = false;
                    }

                    if (addEdge)
                    {
                        nodes[rightEdge.edgeNumber].edges.Add(leftEdge);
                        nodes[leftEdge.edgeNumber].edges.Add(rightEdge);
                    }
                }

                int sourceNode = Convert.ToInt32(lines[currentLine++]) - 1;

                nodes[sourceNode].searchData.distance = 0;
                theQ.Add(nodes[sourceNode]);



                while (theQ.Count() > 0)
                {
                    //get vertex with lowest calculated distance
                    node currentNode = theQ.Aggregate((item1, item2) => item1.searchData.distance < item2.searchData.distance ? item1:item2);
                    theQ.Remove(currentNode);


                    if (localdebug == DEBUGHIGH)
                    {
                        Console.WriteLine("SHOULD REMOVE: " + currentNode.nodeId);
                    }


                    for (int i = 0; i < currentNode.edges.Count(); i++)
                    {
                        int edgeNode = currentNode.edges[i].edgeNumber;

                        if (localdebug == DEBUGHIGH)
                        {
                            Console.WriteLine("*******************");
                            Console.WriteLine("current:" + currentNode.nodeId + ", edgeNode:" + edgeNode);
                        }
                        if (nodes[edgeNode].searchData.distance < currentNode.searchData.distance + currentNode.edges[i].edgeWeight)
                        {
                            if (localdebug == DEBUGHIGH)
                            {
                                Console.WriteLine(nodes[edgeNode].searchData.distance + " < " + (currentNode.searchData.distance + currentNode.edges[i].edgeWeight));
                            }
                        }
                        else
                        {
                            if (localdebug == DEBUGHIGH)
                            {
                                Console.WriteLine(nodes[edgeNode].searchData.distance + " > " + (currentNode.searchData.distance + currentNode.edges[i].edgeWeight));
                            }

                            nodes[edgeNode].searchData.distance = currentNode.searchData.distance + currentNode.edges[i].edgeWeight;
                        }
                        if (!nodes[edgeNode].visited && !theQ.Contains(nodes[edgeNode]))
                        {
                            theQ.Add(nodes[edgeNode]);
                            if (localdebug == DEBUGHIGH)
                            {
                                Console.WriteLine("Adding:" + edgeNode);
                            }
                        }
                    }



                    currentNode.visited = true;
                    if (localdebug == DEBUGHIGH)
                    {
                        Console.WriteLine("Visited:" + currentNode.nodeId);
                        Console.ReadKey();
                    }
                }

                List <string> output = new List <string>();
                for (int i = 0; i < numberNodes; i++)
                {
                    if (nodes[i] != null)
                    {
                        if (nodes[i].searchData.distance != 0)
                        {
                            if (nodes[i].searchData.distance == int.MaxValue)
                            {
                                output.Add("-1");
                            }
                            else
                            {
                                output.Add(nodes[i].searchData.distance.ToString());
                            }
                        }
                    }
                    else
                    {
                        output.Add("-1");
                    }
                }
                if (localdebug == DEBUGHIGH)
                {
                    Console.ReadKey();
                }

                Console.WriteLine(string.Join(" ", output.ToArray()));
            }
            if (localdebug >= DEBUGLOW)
            {
                Console.ReadKey();
            }
        }
Exemplo n.º 20
0
        public double Solve(long pointCount, long[][] points)
        {
            double  cost  = 0;
            MinHeap edges = new MinHeap(pointCount * pointCount);

            for (int i = 0; i < pointCount - 1; i++)
            {
                for (int j = i + 1; j < pointCount; j++)
                {
                    edge edge = new edge();
                    edge.u    = i;
                    edge.v    = j;
                    edge.cost = Math.Pow(Math.Pow((points[i][0] - points[j][0]), 2) + Math.Pow((points[i][1] - points[j][1]), 2), 0.5);
                    edges.Add(edge);
                }
            }

            List <long> sets = new List <long>();

            for (int i = 0; i < pointCount; i++)
            {
                sets.Add(i);
            }
            int edgeNumber = 0;
            int size       = edges._size;

            for (int i = 0; i < size; i++)
            {
                if (edgeNumber == pointCount - 1)
                {
                    break;
                }
                edge edge = edges.Pop();
                if (sets[edge.u] != sets[edge.v])
                {
                    edgeNumber++;

                    cost += edge.cost;
                    long tmp = sets[edge.v];
                    for (int j = 0; j < pointCount; j++)
                    {
                        if (sets[j] == tmp)
                        {
                            sets[j] = sets[edge.u];
                        }
                    }
                }
            }

            /*List<Node> graph = new List<Node>();
             * List<edge> edges = new List<edge>();
             *
             * for (int i=0; i<pointCount; i++)
             * {
             *  graph.Add(new Node());
             *  graph[i].x = points[i][0];
             *  graph[i].y = points[i][1];
             *  graph[i].set = i;
             *
             * }
             *
             *
             * for (int i=0; i < pointCount-1; i++)
             * {
             *  for (int j=i+1; j < pointCount;j++)
             *  {
             *      edge edge = new edge();
             *      edge.u = graph[i];
             *      edge.v = graph[j];
             *      edge.cost = Math.Pow(Math.Pow((edge.u.x - edge.v.x), 2) + Math.Pow((edge.u.y - edge.v.y), 2), 0.5);
             *      edges.Add(edge);
             *  }
             * }
             * for (int i=0; i < edges.Count; i++)
             * {
             *  double min = double.MaxValue;
             *  int minIndex = int.MaxValue;
             *  for (int j=i; j < edges.Count; j++)
             *  {
             *      if (edges[j].cost < min)
             *      {
             *          minIndex = j;
             *          min = edges[j].cost;
             *      }
             *  }
             *  edge tmp = edges[i];
             *  edges[i] = edges[minIndex];
             *  edges[minIndex] = tmp;
             * }
             * double cost = 0;
             * int edgeNumber = 0;
             *
             * for(int i= 0; i<edges.Count; i++)
             * {
             *  if (edgeNumber == pointCount - 1)
             *      break;
             *  if (edges[i].u.set != edges[i].v.set)
             *  {
             *      edgeNumber++;
             *      edges[i].v.edges.Add(edges[i].u);
             *      edges[i].u.edges.Add(edges[i].v);
             *      cost += edges[i].cost;
             *      long tmp = edges[i].v.set;
             *      for (int j = 0; j < pointCount; j++)
             *      {
             *          if (graph[j].set == tmp)
             *              graph[j].set = edges[i].u.set;
             *      }
             *  }
             *
             * }*/
            return((double)((long)(cost * 1000000 + 0.5)) / 1000000);
        }
Exemplo n.º 21
0
            private Tuple<FuncitonFunction.Node, edge[]> walk(edge edge, edge[] allowedDependencies, edge latestOutput)
            {
                Tuple<FuncitonFunction.Node, edge[]> tryNode;
                if (_edgesAlready.TryGetValue(edge, out tryNode))
                {
                    if (tryNode == null)
                        throw new ParseErrorException(new ParseError("The {0} has a cycle in it. It can never evaluate because it would always be an infinite loop.".Fmt(_function.Name == "" ? "main program" : "function " + _function.Name), edge.EndX, edge.EndY, _source.SourceFile));
                    var disallowedDependency = tryNode.Item2.FirstOrDefault(d => !allowedDependencies.Contains(d));
                    if (disallowedDependency != null)
                        throwDisallowedDependency(latestOutput, disallowedDependency);
                    return tryNode;
                }
                _edgesAlready[edge] = null;

                var node = edge.StartNode;
                var outputPosition = Enumerable.Range(0, 4).First(i => node.Edges[i] == edge && node.Connectors[i] == connectorType.Output);

                switch (node.Type)
                {
                    case nodeType.TJunction:
                        if (node.Connectors[0] == connectorType.Output)
                        {
                            // NAND
                            Helpers.Assert(node.Connectors[1] == connectorType.Input);
                            Helpers.Assert(node.Connectors[3] == connectorType.Input);
                            var left = walk(node.Edges[3], allowedDependencies, latestOutput);
                            var right = walk(node.Edges[1], allowedDependencies, latestOutput);
                            return _edgesAlready[edge] = new Tuple<FuncitonFunction.Node, edge[]>(
                                new FuncitonFunction.NandNode(_function, left.Item1, right.Item1),
                                left.Item2.ArrayUnion(right.Item2)
                            );
                        }
                        else
                        {
                            // splitter
                            Helpers.Assert(node.Connectors[0] == connectorType.Input);
                            Helpers.Assert(node.Connectors[1] == connectorType.Output);
                            Helpers.Assert(node.Connectors[3] == connectorType.Output);
                            if (node.Edges[0] == edge)
                                throw new ParseErrorException(new ParseError("This splitter is connected to itself. Such a construct is not allowed as it would always cause an infinite loop.", node.X, node.Y, _source.SourceFile));
                            return _edgesAlready[edge] = walk(node.Edges[0], allowedDependencies, latestOutput);
                        }

                    case nodeType.CrossJunction:
                        {
                            Helpers.Assert(node.Connectors[0] == connectorType.Input);
                            Helpers.Assert(node.Connectors[1] == connectorType.Output);
                            Helpers.Assert(node.Connectors[2] == connectorType.Output);
                            Helpers.Assert(node.Connectors[3] == connectorType.Input);
                            Helpers.Assert(node.Edges[1] == edge || node.Edges[2] == edge);

                            var left = walk(node.Edges[0], allowedDependencies, latestOutput);
                            var right = walk(node.Edges[3], allowedDependencies, latestOutput);
                            var newNode = node.Edges[1] == edge
                                ? (FuncitonFunction.Node) new FuncitonFunction.LessThanNode(_function, left.Item1, right.Item1)
                                : (FuncitonFunction.Node) new FuncitonFunction.ShiftLeftNode(_function, left.Item1, right.Item1);
                            return _edgesAlready[edge] = Tuple.Create(newNode, left.Item2.ArrayUnion(right.Item2));
                        }

                    case nodeType.Declaration:
                        return _edgesAlready[edge] = new Tuple<FuncitonFunction.Node, edge[]>(new FuncitonFunction.InputNode(_function, (int) edge.DirectionFromStartNode), edge.EmptyArray);

                    case nodeType.Call:
                        unparsedFunctionDeclaration decl;
                        if (!_unparsedFunctionsByNode.TryGetValue(node, out decl) && !_unparsedFunctionsByName.TryGetValue(node.GetContent(_source), out decl))
                            throw new ParseErrorException(new ParseError("Call to undefined function “{0}”.".Fmt(node.GetContent(_source)), node.X, node.Y, _source.SourceFile));

                        FuncitonFunction func;
                        if (!_parsedFunctions.TryGetValue(decl, out func))
                            func = decl.Parse(_unparsedFunctionsByName, _unparsedFunctionsByNode, _parsedFunctions);

                        // Try to optimise away no-op functions
                        int? inputPosition = func.GetInputForOutputIfNop(outputPosition);
                        Helpers.Assert(inputPosition == null || node.Connectors[inputPosition.Value] == connectorType.Input);
                        if (inputPosition != null)
                            return _edgesAlready[edge] = walk(node.Edges[inputPosition.Value], allowedDependencies, latestOutput);

                        if (!_callsAlready.ContainsKey(node))
                        {
                            var inputs = new FuncitonFunction.Node[4];
                            var dependencies = edge.EmptyArray;
                            for (int i = 0; i < 4; i++)
                            {
                                if (node.Connectors[i] != connectorType.Input)
                                    continue;
                                var result = walk(node.Edges[i], allowedDependencies, latestOutput);
                                inputs[i] = result.Item1;
                                dependencies = dependencies.ArrayUnion(result.Item2);
                            }
                            _callsAlready[node] = Tuple.Create(new FuncitonFunction.Call(func, inputs), dependencies);
                        }
                        return _edgesAlready[edge] = new Tuple<FuncitonFunction.Node, edge[]>(
                            new FuncitonFunction.CallOutputNode(_function, outputPosition, _callsAlready[node].Item1),
                            _callsAlready[node].Item2
                        );

                    case nodeType.Literal:
                        var content = Regex.Replace(node.GetContent(_source), @"\s*\n\s*", "").Trim().Replace('−', '-');
                        FuncitonFunction.Node newLiteralNode;
                        if (content.Length == 0)
                            newLiteralNode = new FuncitonFunction.StdInNode(_function);
                        else
                        {
                            BigInteger literal;
                            if (!BigInteger.TryParse(content, out literal))
                                throw new ParseErrorException(new ParseError("Literal does not represent a valid integer.", node.X, node.Y, _source.SourceFile));
                            newLiteralNode = new FuncitonFunction.LiteralNode(_function, literal);
                        }
                        return _edgesAlready[edge] = Tuple.Create(newLiteralNode, edge.EmptyArray);

                    case nodeType.LambdaInvocation:
                        if (!string.IsNullOrWhiteSpace(node.GetContent(_source)))
                            throw new ParseErrorException(new ParseError("Lambda invocation boxes must be empty.", node.X, node.Y, _source.SourceFile));

                        if (!_lambdasAlready.ContainsKey(node))
                        {
                            Helpers.Assert(node.Connectors[0] == connectorType.Input);
                            Helpers.Assert(node.Connectors[1] == connectorType.Output);
                            Helpers.Assert(node.Connectors[2] == connectorType.Output);
                            Helpers.Assert(node.Connectors[3] == connectorType.Input);
                            var lambdaGetter = walk(node.Edges[0], allowedDependencies, latestOutput);
                            var argument = walk(node.Edges[3], allowedDependencies, latestOutput);
                            _lambdasAlready[node] = new Tuple<FuncitonFunction.LambdaInvocation, edge[]>(
                                new FuncitonFunction.LambdaInvocation(argument.Item1, lambdaGetter.Item1),
                                lambdaGetter.Item2.ArrayUnion(argument.Item2));
                        }
                        return _edgesAlready[edge] = new Tuple<FuncitonFunction.Node, edge[]>(
                            new FuncitonFunction.LambdaInvocationOutputNode(_function, outputPosition, _lambdasAlready[node].Item1),
                            _lambdasAlready[node].Item2);

                    case nodeType.LambdaExpression:
                        if (!string.IsNullOrWhiteSpace(node.GetContent(_source)))
                            throw new ParseErrorException(new ParseError("Lambda expression boxes must be empty.", node.X, node.Y, _source.SourceFile));
                        Helpers.Assert(node.Connectors[0] == connectorType.Input);
                        Helpers.Assert(node.Connectors[1] == connectorType.Output);
                        Helpers.Assert(node.Connectors[2] == connectorType.Output);
                        Helpers.Assert(node.Connectors[3] == connectorType.Input);

                        switch (outputPosition)
                        {
                            case 1: // parameter
                                if (!allowedDependencies.Contains(edge))
                                    throwDisallowedDependency(latestOutput, edge);
                                if (!_lambdaParameters.ContainsKey(node))
                                    _lambdaParameters[node] = new FuncitonFunction.LambdaExpressionParameterNode(_function);
                                return _edgesAlready[edge] = new Tuple<FuncitonFunction.Node, FuncitonLanguage.edge[]>(_lambdaParameters[node], new[] { edge });

                            case 2: // lambdaGetter
                                // Need to put a skeleton instance into _edgesAlready because this node allows cycles
                                var clonedNode = new FuncitonFunction.LambdaExpressionNode(_function);
                                _edgesAlready[edge] = new Tuple<FuncitonFunction.Node, edge[]>(clonedNode, edge.EmptyArray);
                                // Walk the return values first so that they will create the lambda parameter node
                                var newAllowedDependencies = allowedDependencies.ArrayUnion(node.Edges[1]);
                                clonedNode.ReturnValue1 = walk(node.Edges[0], newAllowedDependencies, node.Edges[0]).Item1;
                                clonedNode.ReturnValue2 = walk(node.Edges[3], newAllowedDependencies, node.Edges[3]).Item1;
                                // If the lambda parameter is not in _lambdaParameters, it means we did not reach the lambda input and therefore the lambda
                                // ignores its input, so we can just pass a null node because it will never get evaluated anyway
                                clonedNode.Parameter = _lambdaParameters.Get(node, null);
                                return _edgesAlready[edge];

                            default:
                                throw new ParseErrorException(new ParseError("The parser encountered an internal error parsing a lambda expression.", node.X, node.Y, _source.SourceFile));
                        }

                    case nodeType.End:
                    case nodeType.Comment:
                    default:
                        throw new ParseErrorException(new ParseError("The parser encountered an internal error.", node.X, node.Y, _source.SourceFile));
                }
            }
Exemplo n.º 22
0
 public void add(edge e)
 {
     le.Add(e);
 }
Exemplo n.º 23
0
            private bool deduceGiven(edge[] edges, bool[] known, Action<edge> isCorrect, Action<edge> isFlipped, int expected, connectorType[][] connectors, sourceAsChars source, string connectorsError, string orientationError)
            {
                if (edges.Count(e => e != null) != expected)
                    throw new ParseErrorException(new ParseError(connectorsError, X, Y, source.SourceFile));

                var result = new List<deduceInfo>();
                foreach (var conn in connectors)
                {
                    for (int rot = 0; rot < 4; rot++)
                    {
                        var rotatedEdges = edges.Skip(rot).Concat(edges.Take(rot)).ToArray();
                        var rotatedKnowns = known.Skip(rot).Concat(known.Take(rot)).ToArray();
                        var valid = Enumerable.Range(0, 4).All(i =>
                                (rotatedEdges[i] == null && conn[i] == connectorType.None) ||
                                (!rotatedKnowns[i] && conn[i] != connectorType.None) ||
                                (rotatedKnowns[i] && rotatedEdges[i].StartNode == this && conn[i] == connectorType.Output) ||
                                (rotatedKnowns[i] && rotatedEdges[i].EndNode == this && conn[i] == connectorType.Input));
                        if (valid)
                            result.Add(new deduceInfo { Edges = rotatedEdges, Knowns = rotatedKnowns, Rotation = rot, Connectors = conn });
                    }
                }

                if (result.Count == 0)
                    throw new ParseErrorException(new ParseError(orientationError, X, Y, source.SourceFile));

                for (int i = 0; i < edges.Length; i++)
                {
                    var edge = edges[i];
                    if (edge == null || known[i])
                        continue;
                    var conns = result.Select(r => r.Connectors[(i + 4 - r.Rotation) % 4]).ToArray();
                    if (conns.Skip(1).All(c => c == conns[0]))
                    {
                        if (edge.StartNode == this && (int) edge.DirectionFromStartNode == i)
                            (conns[0] == connectorType.Output ? isCorrect : isFlipped)(edge);
                        else if (edge.EndNode == this && (int) edge.DirectionFromEndNode == i)
                            (conns[0] == connectorType.Input ? isCorrect : isFlipped)(edge);
                    }
                }

                Edges = result[0].Edges;
                Connectors = result[0].Connectors;
                return result.Count == 1;
            }
Exemplo n.º 24
0
        static polyhedron octahedron(Graphics g, PictureBox pb, int size)
        {
            point3d p1 = new point3d(-size / 2, 0, 0);
            point3d p2 = new point3d(0, 0, -size / 2);
            point3d p3 = new point3d(size / 2, 0, 0);
            point3d p4 = new point3d(0, 0, size / 2);
            point3d p5 = new point3d(0, size / 2, 0);
            point3d p6 = new point3d(0, -size / 2, 0);

            edge e1  = new edge(g, pb, ref p1, ref p2);
            edge e2  = new edge(g, pb, ref p2, ref p3);
            edge e3  = new edge(g, pb, ref p3, ref p4);
            edge e4  = new edge(g, pb, ref p1, ref p4);
            edge e5  = new edge(g, pb, ref p1, ref p5);
            edge e6  = new edge(g, pb, ref p2, ref p5);
            edge e7  = new edge(g, pb, ref p3, ref p5);
            edge e8  = new edge(g, pb, ref p4, ref p5);
            edge e9  = new edge(g, pb, ref p1, ref p6);
            edge e10 = new edge(g, pb, ref p2, ref p6);
            edge e11 = new edge(g, pb, ref p3, ref p6);
            edge e12 = new edge(g, pb, ref p4, ref p6);

            polygon plg1 = new polygon();

            plg1.add(e1);
            plg1.add(e6);
            plg1.add(e5);

            polygon plg2 = new polygon();

            plg2.add(e2);
            plg2.add(e7);
            plg2.add(e6);

            polygon plg3 = new polygon();

            plg3.add(e3);
            plg3.add(e7);
            plg3.add(e8);

            polygon plg4 = new polygon();

            plg4.add(e4);
            plg4.add(e8);
            plg4.add(e5);

            polygon plg5 = new polygon();

            plg5.add(e1);
            plg5.add(e9);
            plg5.add(e10);

            polygon plg6 = new polygon();

            plg6.add(e2);
            plg6.add(e10);
            plg6.add(e11);

            polygon plg7 = new polygon();

            plg7.add(e3);
            plg7.add(e11);
            plg7.add(e12);

            polygon plg8 = new polygon();

            plg1.add(e4);
            plg1.add(e9);
            plg1.add(e12);

            polyhedron res = new polyhedron();

            res.add(plg1);
            res.add(plg2);
            res.add(plg3);
            res.add(plg4);
            res.add(plg5);
            res.add(plg6);
            res.add(plg7);
            res.add(plg8);
            return(res);
        }
Exemplo n.º 25
0
 public bool EqualTo(edge el)
 {
     /*
      if (this.From.Equals(el.From) && this.To.Equals(el.To)) return true;
          if (this.From.Equals(el.To) && this.To.Equals(el.From)) return true;
          return false;
      */
     return el.ID == this.ID;
 }
Exemplo n.º 26
0
 private void addToSolution(edge e)
 {
     succ[e.node1].Add(e.node2);
     succ[e.node2].Add(e.node1);
     edgesUsed++;
 }
Exemplo n.º 27
0
        public Mesh Unfold(Mesh mesh)
        {
            List <face> Faces = new List <face>();
            List <edge> Edges = new List <edge>();

            mesh.Faces.ConvertQuadsToTriangles();
            mesh.UnifyNormals();
            mesh.Compact();
            Rhino.Geometry.Collections.MeshTopologyEdgeList   el = mesh.TopologyEdges;
            Rhino.Geometry.Collections.MeshTopologyVertexList vs = mesh.TopologyVertices;
            mesh.FaceNormals.ComputeFaceNormals();
            //Print(mesh.FaceNormals.Count.ToString());
            //  Print(mesh.Vertices.Count.ToString());
            for (int i = 0; i < mesh.Faces.Count; i++)
            {
                face f1 = new face(
                    new Point3d(mesh.Vertices[mesh.Faces[i].A]),
                    new Point3d(mesh.Vertices[mesh.Faces[i].B]),
                    new Point3d(mesh.Vertices[mesh.Faces[i].C]),
                    mesh.FaceNormals[i]
                    );

                Faces.Add(f1);
            }
            for (int i = 0; i < el.Count; i++)
            {
                int[] faceid = el.GetConnectedFaces(i);

                edge e1 = new edge(vs[el.GetTopologyVertices(i).I], vs[el.GetTopologyVertices(i).J]);
                if (faceid.Length == 1)
                {
                    e1.Faces    = new face[1];
                    e1.Faces[0] = Faces[faceid[0]];
                }
                else if (faceid.Length > 1)
                {
                    e1.Faces    = new face[2];
                    e1.Faces[0] = Faces[faceid[0]];
                    e1.Faces[1] = Faces[faceid[1]];
                }
                e1.ID = i;
                Edges.Add(e1);
            }
            for (int i = 0; i < mesh.Faces.Count; i++)
            {
                int[] edgeid = el.GetEdgesForFace(i);
                face  f1     = Faces[i];
                f1.edges[0] = Edges[edgeid[0]];
                f1.edges[1] = Edges[edgeid[1]];
                f1.edges[2] = Edges[edgeid[2]];
                f1.ID       = i;
            }


            /* List<  Mesh> output2 = new List<  Mesh>();
             * for (int i = 0; i < Faces.Count; i++)
             * {
             * output2.Add(Faces[i].DrawFace());
             * }
             * B = output2;
             */
            face f = Faces[0];

            f.AddTransform(Transform.PlaneToPlane(new Plane(f.Center(), -f.Normal), Plane.WorldXY));

            FaceLoop(f);
            //Print(f.Pts[0].X.ToString() + "/" + f.Pts[0].Y.ToString() + "/" + f.Pts[0].Z.ToString());
            Mesh output = new Mesh();

            for (int i = 0; i < Faces.Count; i++)
            {
                output.Append(Faces[i].DrawFace());
            }
            return(output);
        }
Exemplo n.º 28
0
        int so; // originating node

        #endregion Fields

        #region Constructors

        public edge()
        {
            so = 0; si = 0; next = NULL;
        }
Exemplo n.º 29
0
	void CalculateEdges(){
		
		edge tempEdge = new edge();
		for (int x = 0; x < cityMapBW.width; x++){
			for (int y = 0; y < cityMapBW.height; y++){
				if (cityMapBW.GetPixel(x,y).grayscale < 0.5f){
					if (cityMapBW.GetPixel(x-1,y).grayscale > 0.5f || 
					    cityMapBW.GetPixel(x+1,y).grayscale > 0.5f || 
					    cityMapBW.GetPixel(x,y-1).grayscale > 0.5f || 
					    cityMapBW.GetPixel(x,y+1).grayscale > 0.5f){
						//edgePos = new Vector3(x, 1f, y);
						tempEdge.edgeX = x;
						tempEdge.edgeY = y;
						edges.Add(tempEdge);
						RoadMap.SetPixel(tempEdge.edgeX, tempEdge.edgeY, Color.black);
						//edges.Add(cityMapBW.GetPixel(x,y).);
					}
				}
			}
		}

	}
Exemplo n.º 30
0
 (double adjustedTravelTime, double baseTravelTime) = CalculateWalkingTimeWithCongestion(edge, edgeOccupancies);