Fitness for Shortest path using a genetic algorithm

Hi.
I have this problem:
I'm doing a program that has a map and two points. the map has wall that are not valid positions.
I have used a A* algorithm to calculate the shortest path and is working fine.
now i'm implementing a genetic algorithm to solve the problem but i'm not having sucess.
My genetic operator are directions (left, right, up and down).
I'm not being able to find a goodfitness function to solve the problem.
can someone tell me a god function or here I can found information about that?
I have been searching on google and I have not yet had sucess.
I have tryed two diferent fitness tecniques:
- add 1 for each step and if it finds a wall or gets out of the map add the maximum value (mapsize*mapsize).
- the other one is add the valid steps and if it finds a wall or gets out of the map add the number of necessary steps to gets to destination. the valid steps has a weight of 30% and the necessary steps has a weight of 70% (i have tryed to use diferent weight).
Can someone help me?
thanks

How about adapting your TSP code as follows. Your graph G(V, E) has two special vertices: v_s and v_d (start and destination). Let a candidate solution consist of a permutation of V\{v_s, v_d}u{v_m} where v_m is a new marker vertex whose purpose is to allow you to treat part of the candidate solution as irrelevant. Given candidate solution v_0 v_1 v_2 ... v_n v_m v_n+1 ... the weight is c(v_s, v_0) + c(v_0, v_1) + ... + c(v_n-1, v_n) where c(v_a, v_b) is the cost of the edge ab.

Similar Messages

  • SSMS 2012:FOR XML PATH Using XPath Node Tests-Columnn name 'test()' contains an invalid XML identifier as required by FOR XML?

    Hi all,
    I am learning XPATH and XQUERY from the Book "Pro T-SQL 2008 Programmer's Guide" written by Michael Coles, (published by apress). I copied the Code Listing 12-8 FOR XML PATH Using XPath Node Tests (listed below) and executed it in my
    SQL Server 2012 Management Studio:
    --Coles12_8.sql // saved in C:/Documemnts/SQL Server Management Studio
    -- Coles Listing 12-8 FOR XML PATH Using XPATH Node Tests
    -- Retrieving Name and E-mail Addresses with FOR XML PATH in AdvantureWorks
    -- 16 March 2015 0935 AM
    USE AdventureWorks;
    GO
    SELECT
    p.NameStyle AS "processing-instruction(nameStyle)",
    p.BusinessEntityID AS "Person/@ID",
    p.ModifiedDate AS "comment()",
    pp.PhoneNumber AS "test()",
    FirstName AS "Person/Name/First",
    MiddleName AS "Person/Name/Middle",
    LastName AS "Person/Name/Last",
    EmailAddress AS "Person/Email"
    FROM Person.Person p
    INNER JOIN Person.EmailAddress e
    ON p.BusinessEntityID = e.BusinessEntityID
    INNER JOIN Person.PersonPhone pp
    ON p.BusinessEntityID = pp.BusinessEntityID
    FOR XML PATH;
    I got the following error message:
    Msg 6850, Level 16, State 1, Line 2
    Column name 'test()' contains an invalid XML identifier as required by FOR XML; '('(0x0028) is the first character at fault.
    I have no ideas why I got this error message.  Please kindly help and advise me how to resolve this error.
    Thanks in advance,  Scott Chang

    Hi Michelle, Thanks for your nice response.
    I corrected the mistake and executed the revised code. It worked nicely.
    I just have one question to ask you about the appearance of the xml output of my Co;les12_8.sql:
    <row>
    <?nameStyle 0?>
    <Person ID="1" />
    <!--2003-02-08T00:00:00-->697-555-0142<Person><Name><First>Ken</First><Middle>J</Middle><Last>Sánchez</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    <?nameStyle 0?>
    <Person ID="2" />
    <!--2002-02-24T00:00:00-->819-555-0175<Person><Name><First>Terri</First><Middle>Lee</Middle><Last>Duffy</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    <?nameStyle 0?>
    <Person ID="3" />
    <!--2001-12-05T00:00:00-->212-555-0187<Person><Name><First>Roberto</First><Last>Tamburello</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    <?nameStyle 0?>
    <Person ID="4" />
    <!--2001-12-29T00:00:00-->612-555-0100<Person><Name><First>Rob</First><Last>Walters</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    <?nameStyle 0?>
    <Person ID="5" />
    <!--2002-01-30T00:00:00-->849-555-0139<Person><Name><First>Gail</First><Middle>A</Middle><Last>Erickson</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    <?nameStyle 0?>
    <Person ID="6" />
    <!--2002-02-17T00:00:00-->122-555-0189<Person><Name><First>Jossef</First><Middle>H</Middle><Last>Goldberg</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    <?nameStyle 0?>
    <Person ID="7" />
    <!--2003-03-05T00:00:00-->181-555-0156<Person><Name><First>Dylan</First><Middle>A</Middle><Last>Miller</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    <?nameStyle 0?>
    <Person ID="8" />
    <!--2003-01-23T00:00:00-->815-555-0138<Person><Name><First>Diane</First><Middle>L</Middle><Last>Margheim</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    <?nameStyle 0?>
    <Person ID="9" />
    <!--2003-02-10T00:00:00-->185-555-0186<Person><Name><First>Gigi</First><Middle>N</Middle><Last>Matthew</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    <?nameStyle 0?>
    <Person ID="10" />
    <!--2003-05-28T00:00:00-->330-555-2568<Person><Name><First>Michael</First><Last>Raheem</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    <?nameStyle 0?>
    <Person ID="11" />
    <!--2004-12-29T00:00:00-->719-555-0181<Person><Name><First>Ovidiu</First><Middle>V</Middle><Last>Cracium</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    I feel this xml output is not like the regular xml output.  Do you know why it is diffrent from the regular xml xml output?  Please comment on this matter.
    Thanks,
    Scott Chang
    What do you mean by regular xml document? Are you referring to fact that its missing a root element? if yes it can be added as below
    USE AdventureWorks;
    GO
    SELECT
    p.NameStyle AS "processing-instruction(nameStyle)",
    p.BusinessEntityID AS "Person/@ID",
    p.ModifiedDate AS "comment()",
    pp.PhoneNumber AS "text()",
    FirstName AS "Person/Name/First",
    MiddleName AS "Person/Name/Middle",
    LastName AS "Person/Name/Last",
    EmailAddress AS "Person/Email"
    FROM Person.Person p
    INNER JOIN Person.EmailAddress e
    ON p.BusinessEntityID = e.BusinessEntityID
    INNER JOIN Person.PersonPhone pp
    ON p.BusinessEntityID = pp.BusinessEntityID
    FOR XML PATH('ElementName'),ROOT('RootName');
    replace ElementName and RootName with whatever name you need to set for element as well as the root element
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • Aco  implemenataion for shortest paths.

    has anyone used ant colony optimization algorithm for finding shortest paths other than for the tsp? please i need some help and advice. thanks

    sorry for not being specific and the insubsequent reply. am just doing some research on aco, i want to try and implement it for best bath planning on a map/graph. I've been looking around for some example on such and noticed that this algorithm is mainly used for tsp problem which got me questioning the possibility of my task. I just want to know if it is definitely possible with aco as i will give it a go in this case. Implementing this algorthm successfully is the main challenge of my project so i cannot contemplate another algorithm option. Thanks for your time.

  • Computing of the shortest path using a custom cost function in Oracle NDM

    Hi to all,
    I have Oracle 10g R2, I'm working on Oracle Network Data Model. I created a Network (named ITALIA_NET) based on links table (named ITALIA_LINK$) and nodes table (named ITALIA_NODE$).
    Until now I computed the shortest path between two nodes using the 10gR2 NDM Java API, in particular I used the shortestPath() method.
    I know that this method computes the shortest path between two nodes on the base of the values of a field that can be the lenght OR the travel time of the links.
    What I wish to do is compute the shortest path between two nodes with a function that considers ( at the same time ) more parameters and on the base of them returns a path. For example, I want compute the shortest path taking into account these parameters for the links:
    travel times of links
    gradient links
    tortuosity links
    Infact, I have for each link the costs of: travel time (for example 3 minuts for cross the link), gradient (for example, the link has 2% of gradient) and tortuosity (for example, the link has two curves of 60° of angle).
    Do you have any idea how I can implement this?
    Are there other ways for reach this objective?
    I hope I explained well my objective.
    Thank you very much to all in advance.

    _1) If I convert the values of the other cost columns into the values of the primary cost column (time is ok), what is the formulation for do this conversion?_
    The modeling part is the most difficult part. I am not sure if there is a universal conversion formula between two different costs.
    One recommendation is to use time as your primary cost.
    For any other secondary costs, collect some data (or from some published statistics) on how these costs affect the travel time (based on the actual speeds wrt to gradients and tortuosity).
    I am not an expert on this. Maybe asking questions like,
    Q. how will a road of gradient = 10 deg affect the speed, uphill and downhill compared to the speed limit?
    Once you have a good estimates on the speeds, you can compute the travel times as the distance/length of the link is known. The same applies to tortuosity,
    Q. how will roads with 30/60/90 deg angles affect the travel speeds compared to the speed limit?
    Assuming you are using something like the speed limit as you normal travel speed to compute your travel time.
    _2) After conversion, how can I combine these columns?_
    Say if you have done the conversion part in Step 1, you have 3 costs,
    cost1, cost2, and cost3
    You can create a view on the link table with the combined link cost as (cost1+cost2+cost4) or
    you can create a new column that sums up the costs you want and use it as the link cost.
    hope it helps!
    jack

  • Graphs, finding shortest Path using BFS

    COuld some one give me some lead on how to go about finding shortest path between two nodes on a graph using BFS, Edges are labeled but not weighted. What kind of modification will be need to BFS for this?

    http://en.wikipedia.org/wiki/Breadth-first_search

  • Numbers not fit for Serious Business Use

    I run a small busieness with 8 users all using Macs (10.6.8) with 10.6.8 server.  Nothign dramatic, lots of small and medoum sized word procesing dicuments and spreadsheets.  We are long-time Mac users, I stayed with Appleworks for quite some time as we were used to it.  However over the last few years I have grown to like Numbers, and think it is quick and easy to produce very nice-looking output.
    So long as you don't do anything complicated or business critical - I have found out the hard way that it just isn't safe for grown-up use.  The reason I say this is baed on my experience with a spreadsheet I have written to record all jobs quoted out and analyse our performance.   The basic data table is about 400 rows x 50 columns.  There are a few dozen analysis sheets many with lots of instances of some quiet complex formulae,  Numbers is creaking at the seams, it takes 30 seconds just to open the file.  But my big problem is, it is very easy to get results that are just plain WRONG.  After many hours of debugging I finally discovered the reason.  As this spreadsheet has been developed there have been quite a lot of formatting changes, notable between "automatic", "text" and "date", and between "automatic", "text", "number" and currency", and (I assume) that asa result of this Numbers doesn't necessarily interpret data as being the format that you think it is.  Here's an example:
    The basic data recorded is jobs quoted out, including engineer, quote date, and amount.
    One of the tables shows an analysis of value quoted per engineer per month, using SUMIFS.  This matches data on engineer initials and date.
    The quote date is in a cell whsoe column is formatted as a date.
    The quote amount is in a cell whose column is formatted as currency.
    One engineer did a vewry big quote - and I noticed that thsi value was not showing up in the analysis table.
    I selected each column in turn and set the format of the colium, this did not make any diference.
    I cheecked (without changing anything) that the values for date and quote vaue were sensible -they were.
    Then I retyped the data for date and quote value.  I retyped exactly the same values that were there before.
    Bingo - now the analysis shows the correct amnounts.
    The conclusion is clearly that that the carrency and date values weren't matching the SUMIF as expected.  This is undeniable.
    It is a fact that retyping the data fixed it, one can speculate that the formatting of th cell had somehow become borked for some hiostorical reason, when new data was entered the format as forced to whatever the colium format was set to.  (we know from experience that even if you set the format for a column, individual cells in the colum can still have a different format if Numbers thinks this is what you intended)
    The problem is that, whatever the reason, Numbers gave me the wrong numerical result.  The raw data was displayed perfectly Ok with nothign at all to warn me of a problem.  The error was silent.  Therefore, I cannot trust what Numbers is telling me.  I cannot think of any way to check whether or not this sort of error is occuring...it was jut chance that I noticed on this occasion.
    In how many other placesis Numbers silently giving me the wrong answer?
    What about hundreds of other Numbers spreadsheets that I have used for quoting jobs - how do I know that these are numerically accurate?
    It is quite scary to have built up a big intellectual investment in Numbers, and then to discover that is is unreliable.
    Apple, of course, do not respond to feedback from me requesting a contact.
    Clearly no-one should be using Nukber for mission-critical applications.
    What are the alternatives?   I have avoided Excel for many tyears, ever since I lost a few days' work when it corrupted a file for me!  but these days Excel is so well established and in common use that I guess it can't be that bad any more.....can it?  And I suppose that it can;t have the same sort of errors that i find in Numbers.....peopple woudl have noticed by now, wouldn;t they??
    the real answer is that no one shoudl be using spreadsheets for busioness critical applciations - theyare just too dangerous, to difficult to get demonstrably right, too easy to break by accident.  When I can find time I am going to replace all the above with a Filemaker database. 
    Any thoughts or experiences from anyone else?
    Any chance of this post not getting deleted?

    Hi Luke,
    Chances of the post surviving or being deleted depend mostly on an interpretation of whether it fits the terms of use for Apple Support communities.
    I cheecked (without changing anything) that the values for date and quote vaue were sensible -they were.
    Then I retyped the data for date and quote value.  I retyped exactly the same values that were there before.
    Bingo - now the analysis shows the correct amnounts."
    I suspect that the previous change you mentioned may have altered the Date and Time value (the 'date value' you name) into something Numbers did not recognize as a Date and Time value when the column was reformatted to Date and Time, show date only. Retyping "exactly the same value as was there" displayed would remove any extraneous bits, permitting recognition as (the date part of) a Date and Time value, and allowing Numbers to recognize the row as one that should be included in the SUMIF. The case might be similar for the quote value in that row, although I think this would be less likely. If you changed both before checking the result of that change, there's little chance of discovering what caused the amount to be disregarded in the calculations.
    "There are a few dozen analysis sheets many with lots of instances of some quiet complex formulae,  Numbers is creaking at the seams, it takes 30 seconds just to open the file."
    Numbers is not speedy, particularly with quite complex formulas (and many of them). Part of the issue in Numbers '08 and '09 is that every change in a table triggers a recalculation of the whole table. That issue has been at least partially addressed in Numbers 3, where the recalculation appears to not extend to the full tableeach time there's a change, but to only th cells affected by the change.
    "...Excel is so well established and in common use that I guess it can't be that bad any more.....can it?"
    Excel has been "well established and in common use" for many years now. That alone, though, can't be relied upon as definitive evidence that "it can't be bad;" only that many copies of it have been sold and installed, many people use it, and files saved in a format it can open can be opened and read by many people. Whether it's "good" or "bad" (or should be described in more emphatic terms toward either end of this range) depends on the user, her purpose in using it, and how well that user feels it fits that purpose. (My personal take on it is that Excel does the jobs I've used it for well, but that I have used it infrequently enough that I have not learned where things (text size, data formatting, etc.) are found.
    But I'm not you, and my needs are not your needs. The standard advice applies: Use the tool that fits the job. That's fairly common advice in these discussions.
    Regards,
    Barry

  • Genetic algorithm for use within LabVIEW

    I want to use a genetic algorithm to optimise a control system.  I was going to use MatLab because I can write the GA with that, but I cannot get it running fast enough with my C-DAQ.  The alternative is to use LabView, but I could not write a GA VI.  Do you know of a GA for use in LabVIEW?

    Hi Jack@Newcastle,
    Take a look at the following example of Genetic Algorithm implemented in LabVIEW (https://decibel.ni.com/content/docs/DOC-13699).It should give you an idea how to write your own code.
    Regards,
    Edvin

  • Shortest path between two arbitrary point in the network

    Hi All,
    In oracle NDM, it's possible to find shortest path between two nodes (e.g. using SDO_NET_MEM.NETWORK_MANAGER.SHORTEST_PATH), but I need to find shortest path between 2 points which are on the network edges. I suppose I should use (Interface SubPath) in network java apis. However I want to do it via PLSQL api. Should I code it myself or there exists a function?
    Any help is appreciated.
    Edited by: Fa on Dec 15, 2011 2:51 AM

    pritamg wrote:
    I have to build an application in which the user will draw the graph by creating nodes and edges.and then the start node will be marked.Then the shortest paths to other nodes will be displayed.Give me any possible clue how to start.I am in deep deep trouble.I have to use Dijkstra's Algorithm.
    please help some one...pleaseDo you know Dijkstra's Algorithm for shortest path? I believe that one was also called the traveling salesman problem. You can easily Google to find out what it is.
    Did you listen to your instructor when he/she did his/her lectures on recursion and halting contitions? If not, then please go talk to him/her and read your book, the forum is not a place to try to learn a basic concept that you should have paid attention in class for the first time.
    If you have code and you have specific questions post them and we will be glad to help, but we are not here to develop your homework solutions for you, no matter how that may affect your future.

  • Shortest path issue

    Hey guys, first...Happy thanksgiving :)
    Ok, so I'm on my last assignment for my amazingly taught Data Structures class. I battled my way successfully through recursion, binary trees, redblack trees, 234 trees, B Trees, and heaps!...no issues at all!....but, now I have hit graphs. I understand the concept, but my latest assignment has me a bit frustrated..Im so close to finishing I can taste it!!....I just cant find the spoon..
    Here we go:
    We are given a graph on paper. It has circles (verteci) representing cities in the USA. These circles are connected by lines (edges) representing the distance between the cities. Also, the lines have arrows pointing the direction they may be traversed.
    We are to construct the graph in the computer, and then compute the shortest path from washington (Vertex 0) to every other city.
    I managed to construct the graph, and it will find the shortest path no problem. My only issue is that, it wants us to print the path it took, not just the destination and total distance....
    I have tried using a stack to push the verteci onto as theyre visited, but im not getting happy results.
    I should also mention, this code is taken out of the book with modifications by me so that it can add edges and verteci, and it now accepts String types for the vertex labels instead of characters.
    Here is my code
    PATH.JAVA (the important part)
    // path.java
    // demonstrates shortest path with weighted, directed graphs
    // to run this program: C>java PathApp
    import java.lang.*;
    import java.io.*;
    class DistPar               // distance and parent
    {                           // items stored in sPath array
        public int distance;    // distance from start to this vertex
        public int parentVert;  // current parent of this vertex
        public DistPar(int pv, int d)  // constructor
            distance = d;
            parentVert = pv;
    }  // end class DistPar
    class Vertex
        public String label;        // label (e.g. 'A')
        public boolean isInTree;
        public Vertex(String lab)   // constructor
            label = lab;
            isInTree = false;
    }  // end class Vertex
    class Graph
        private final int MAX_VERTS = 20;
        private final int INFINITY = 1000000;
        private Vertex vertexList[];    // list of vertices
        private int adjMat[][];         // adjacency matrix
        private int nVerts;             // current number of vertices
        private int nTree;              // number of verts in tree
        private DistPar sPath[];        // array for shortest-path data
        private int currentVert;        // current vertex
        private int startToCurrent;     // distance to currentVert
        private stack path_taken;       // stack to record path taken
        public Graph()                  // constructor
            vertexList = new Vertex[MAX_VERTS];
                                             // adjacency matrix
            adjMat = new int[MAX_VERTS][MAX_VERTS];
            nVerts = 0;
            nTree  = 0;
            for(int j=0; j<MAX_VERTS; j++)      // set adjacency
                for(int k=0; k<MAX_VERTS; k++)  //     matrix
                    adjMat[j][k] = INFINITY;    //     to infinity
            sPath = new DistPar[MAX_VERTS];     // shortest paths
            path_taken = new stack(MAX_VERTS);
        }  // end constructor
        public void addVertex(String lab)
            vertexList[nVerts++] = new Vertex(lab);
        public void addEdge(int start, int end, int weight)
            adjMat[start][end] = weight;  // (directed)
        public void path()                // find all shortest paths
            int startTree = 0;             // start at vertex 0
            vertexList[startTree].isInTree = true;
            nTree = 1;                     // put it in tree
          // transfer row of distances from adjMat to sPath
            for(int j=0; j<nVerts; j++)
                int tempDist = adjMat[startTree][j];
                sPath[j] = new DistPar(startTree, tempDist);
          // until all vertices are in the tree
            while(nTree < nVerts)
                int indexMin = getMin();    // get minimum from sPath
                int minDist = sPath[indexMin].distance;
                if(minDist == INFINITY)     // if all infinite
                {                        // or in tree,
                    System.out.println("There are unreachable vertices");
                    break;                   // sPath is complete
                else
                {                        // reset currentVert
                    currentVert = indexMin;  // to closest vert
                    startToCurrent = sPath[indexMin].distance;
                    // minimum distance from startTree is
                    // to currentVert, and is startToCurrent
                // put current vertex in tree
                vertexList[currentVert].isInTree = true;
                nTree++;
                path_taken.push(sPath[indexMin]);
                adjust_sPath();             // update sPath[] array
            }  // end while(nTree<nVerts)
            displayPaths();                // display sPath[] contents
            nTree = 0;                     // clear tree
            for(int j=0; j<nVerts; j++)
                vertexList[j].isInTree = false;
        }  // end path()
        public int getMin()               // get entry from sPath
        {                              //    with minimum distance
            int minDist = INFINITY;        // assume minimum
            int indexMin = 0;
            for(int j=1; j<nVerts; j++)    // for each vertex,
            {                           // if it's in tree and
                if( !vertexList[j].isInTree &&  // smaller than old one
                                   sPath[j].distance < minDist )
                    minDist = sPath[j].distance;
                    indexMin = j;            // update minimum
            }  // end for
            return indexMin;               // return index of minimum
         }  // end getMin()
        public void adjust_sPath()
          // adjust values in shortest-path array sPath
            int column = 1;                // skip starting vertex
            while(column < nVerts)         // go across columns
             // if this column's vertex already in tree, skip it
                if( vertexList[column].isInTree )
                    column++;
                    continue;
             // calculate distance for one sPath entry
                           // get edge from currentVert to column
                int currentToFringe = adjMat[currentVert][column];
                           // add distance from start
                int startToFringe = startToCurrent + currentToFringe;
                           // get distance of current sPath entry
                int sPathDist = sPath[column].distance;
             // compare distance from start with sPath entry
                if(startToFringe < sPathDist)   // if shorter,
                {                            // update sPath
                    sPath[column].parentVert = currentVert;
                    sPath[column].distance = startToFringe;
                column++;
             }  // end while(column < nVerts)
        }  // end adjust_sPath()
        public void displayPaths()
            for(int j=0; j<nVerts; j++) // display contents of sPath[]
                System.out.print(vertexList[j].label + "="); // B=
                if(sPath[j].distance == INFINITY)
                    System.out.print("inf");                  // inf
                else
                    System.out.print(sPath[j].distance);      // 50
                    String parent = vertexList[ sPath[j].parentVert ].label;
                    System.out.print(" (" + parent + ") ");       // (A)
            System.out.println("");
            System.out.println("PRINTING path_taken");
            DistPar thing = null;
            while((thing = path_taken.pop()) != null)
                System.out.println(" " + vertexList[thing.parentVert].label + " "+ thing.distance);
    }  // end class GraphSTACK.JAVA (my stack class)
    // stack.java
    // demonstrates stacks
    // to run this program: C>java StackApp
    class stack
        private int maxSize;        // size of stack array
        private DistPar[] stackArray;
        private int top;            // top of stack
        public stack(int s)         // constructor
            maxSize = s;             // set array size
            stackArray = new DistPar[maxSize];  // create array
            top = -1;                // no items yet
        public void push(DistPar j)    // put item on top of stack
            stackArray[++top] = j;     // increment top, insert item
        public DistPar pop()           // take item from top of stack
            return stackArray[top--];  // access item, decrement top
        public DistPar peek()          // peek at top of stack
            return stackArray[top];
        public boolean isEmpty()    // true if stack is empty
            return (top == -1);
        public boolean isFull()     // true if stack is full
            return (top == maxSize-1);
    }PATHAPP.JAVA (test program..builds the graph and calls path())
    class PathApp
        public static void main(String[] args)
            Graph theGraph = new Graph();
            theGraph.addVertex("Washington");
            theGraph.addVertex("Atlanta");
            theGraph.addVertex("Houston");
            theGraph.addVertex("Denver");
            theGraph.addVertex("Dallas");
            theGraph.addVertex("Chicago");
            theGraph.addVertex("Austin");
            theGraph.addEdge(0,1,600);
            theGraph.addEdge(1,0,600);
            theGraph.addEdge(0,4,1300);
            theGraph.addEdge(4,3,780);
            theGraph.addEdge(3,1,1400);
            theGraph.addEdge(1,2,800);
            theGraph.addEdge(2,1,800);
            theGraph.addEdge(4,5,900);
            theGraph.addEdge(4,6,200);
            theGraph.addEdge(6,4,200);
            theGraph.addEdge(6,2,160);
            theGraph.addEdge(3,5,1000);
            theGraph.addEdge(5,3,1000);
            System.out.println("Shortest Paths");
            theGraph.path();
            //theGraph.displayPaths();
            System.out.println();
    }Im mostly having trouble comprehending the Path.java file. A few friends and I stared at it for a few hours and couldnt get it to do what we wanted...
    path_taken is the stack I added in to try and push/pop the verteci as theyre traversed, but with what I stuck in right now, it still just prints the most recently visited vertex, and the sum of the distances.
    Any help is greatly appreciated!
    Thanks :)
    ----Arkhan

    If your graph is G(V, E), and you're trying to get to vertex v_end, then create a new graph G'(V', E') whereV' = (V x N) U {v_end'}
        (v_end' is a new object)
    E' = {((u, t), (v, t + f(u, v, t))) : (u, v) in E, t in N} U
         {((u, t), (u, t + 1)) : u in V, t in N} U
         {((v_end, t), v_end') : t in N}G' is infinite, so you'll need to use a lazy graph structure. Then just use Dijkstra from (v_start, 0) to v_end'.

  • Shortest Path

    I have this table:
    with t as (
      select 'A' source, 'B' destination, 7 meter from dual
      union all
      select 'A' source, 'C' destination, 9 meter from dual
      union all
      select 'A' source, 'F' destination, 14 meter from dual
      union all
      select 'B' source, 'C' destination, 10 meter from dual
      union all
      select 'B' source, 'D' destination, 15 meter from dual
      union all
      select 'C' source, 'D' destination, 11 meter from dual
      union all
      select 'C' source, 'F' destination, 2 meter from dual
      union all
      select 'D' source, 'E' destination, 6 meter from dual
      union all
      select 'E' source, 'F' destination, 9 meter from dual
    select * from t;How to know the shortest path from a source to a destination? Suppose, from A to F. Can we show the shortest path using SQL? tx in advance.

    Billy  Verreynne  wrote:
    I dislike what I consider blatant non-SQL features in SQL. Basic XML functionality is not an issue for me. But XQuery and modelling clauses - that I dislike.I can understand that.
    Note that for the particular case we're discussing here, if I were to implement it in 11.2, I'd surely choose the recursive factoring approach instead.
    I agree, most of these XML features may appear powerful and "cool" but also "evil" (as you would say) if they're not understood and used correctly.
    BTW, for the record, the XQuery expression I posted is rewritten using SQL internal functions, so not much left of XML functionalities after all (except the name perhaps?).
    So, I guess that makes it appears less evil ;)
    SQL> explain plan for
      2  select source
      3       , destination
      4       , meter
      5       , xmlcast(
      6           xmlquery('sum(for $i in ora:tokenize($s,";") return xs:integer($i))'
      7            passing path as "s"
      8            returning content
      9           ) as number
    10         ) as "SUM"
    11  from (
    12    select level, t.*, sys_connect_by_path(meter, ';') path
    13    from paths t
    14    where destination = 'F'
    15    connect by prior destination = source
    16    start with source = 'A'
    17  )
    18  order by "SUM"
    19  ;
    Explained.
    SQL> set pages 100
    SQL> set lines 140
    SQL> select * from table(dbms_xplan.display(format => 'ALL'));
    PLAN_TABLE_OUTPUT
    Plan hash value: 2102804061
    | Id  | Operation                                  | Name                  | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT                           |                       |     9 | 18189 |     4  (25)| 00:00:01 |
    |   1 |  SORT AGGREGATE                            |                       |     1 |     2 |         |     |
    |   2 |   COLLECTION ITERATOR PICKLER FETCH        | XQSEQUENCEFROMXMLTYPE |  8168 | 16336 |    29   (0)| 00:00:01 |
    |   3 |  SORT ORDER BY                             |                       |     9 | 18189 |     4  (25)| 00:00:01 |
    |   4 |   VIEW                                     |                       |     9 | 18189 |     4  (25)| 00:00:01 |
    |*  5 |    FILTER                                  |                       |       |       |         |     |
    |*  6 |     CONNECT BY NO FILTERING WITH START-WITH|                       |       |       |         |     |
    |   7 |      TABLE ACCESS FULL                     | PATHS                 |     9 |   171 |     3   (0)| 00:00:01 |
    Query Block Name / Object Alias (identified by operation id):
       1 - SEL$33CAA0FD
       2 - SEL$33CAA0FD / KOKBF$@SEL$AEEEB114
       3 - SEL$1
       4 - SEL$2        / from$_subquery$_001@SEL$1
       5 - SEL$2
       7 - SEL$3        / T@SEL$3
    Predicate Information (identified by operation id):
       5 - filter("DESTINATION"='F')
       6 - access("SOURCE"=PRIOR "DESTINATION")
           filter("SOURCE"='A')
    Column Projection Information (identified by operation id):
       1 - (#keys=0) SUM(SYS_XQ_ATOMCNVCHK(TO_NUMBER(SYS_XQ_UPKXML2SQL(VALUE(KOKBF$),2,1,0)),2,33))[22]
       2 - VALUE(A0)[40]
       3 - (#keys=1) CAST(TO_CHAR( (SELECT SUM(SYS_XQ_ATOMCNVCHK(TO_NUMBER(SYS_XQ_UPKXML2SQL(VALUE(KOKBF$),2,1,0
           )),2,33)) FROM TABLE() "KOKBF$")) AS number        )[22], "SOURCE"[CHARACTER,1],
           "DESTINATION"[CHARACTER,1], "METER"[NUMBER,22]
       4 - "SOURCE"[CHARACTER,1], "DESTINATION"[CHARACTER,1], "METER"[NUMBER,22], "PATH"[VARCHAR2,4000]
       5 - SYS_CONNECT_BY_PATH(TO_CHAR("METER"),';')[4000]
       6 - "SOURCE"[CHARACTER,1], "DESTINATION"[CHARACTER,1], STRDEF[1], STRDEF[1], STRDEF[22], STRDEF[1],
           STRDEF[1], STRDEF[22], PRIOR NULL[1], LEVEL[4], SYS_CONNECT_BY_PATH(TO_CHAR("METER"),';')[4000]
       7 - "SOURCE"[CHARACTER,1], "T"."DESTINATION"[CHARACTER,1], "T"."METER"[NUMBER,22]
    Note
       - dynamic sampling used for this statement (level=2)
    49 rows selected.

  • F4 help for file path in selection screen.

    Hi there,
    I defined one parameter p_path for file path using RLGRAP-FILENAME. I have not got F4 for this. How to solve this problem, can anybody pls help.
    Regards,
    Naseer.

    Hi,
    refer to the following code:
    AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_pc.
    DATA: it_tab TYPE filetable,
              wf_subrc TYPE i.
    DATA: wf_pcfile LIKE rlgrap-filename.
      DATA: wf_filter TYPE string,
            wf_dir TYPE string,
            wf_title TYPE string,
            wf_ext TYPE string.
    *  if p_ml = 'X'.                  "Manula Load - PC File
      wf_title = text-012.          "Window title
      wf_ext  = '.TXT'.           "Extension of the file
      wf_filter = 'Text Files (*.TXT)|*.TXT'.         "File Type
      wf_dir = wf_pcfile.           "Directory
    *Adds a GUI-Supported Feature
      CALL METHOD cl_gui_frontend_services=>file_open_dialog
        EXPORTING
          window_title      = wf_title
          default_extension = wf_ext
          file_filter       = wf_filter
          initial_directory = wf_dir
        CHANGING
          file_table        = it_tab
          rc                = wf_subrc.
    Hope this helps.
    <REMOVED BY MODERATOR>
    Regards,
    Sipra
    Edited by: Alvaro Tejada Galindo on Jan 31, 2008 9:48 AM

  • "for XML path "  Oracle equivalent of this SQL expression

    SELECT TheID,
    REPLACE(
    RTRIM(
    SELECT StudentID + ' '
    FROM StudentinSchoolLocation TL
    WHERE (LocationID = Results.LocationID)
    FOR XML PATH ('')
    ) AS StudentIDs,
    What is the equivalent of 'For XML path' used above
    The goal is to get a concatenated list of the group by columns. Like where ever the location is same , get the studentIds and make a comma seperated list of all ids for common location
    Works perfectly in SQL.
    Thank you

    Hi,
    user6287828 wrote:
    The goal is to get a concatenated list of the group by columns. Like where ever the location is same , get the studentIds and make a comma seperated list of all ids for common locationThat's called "String Aggregation"
    [AskTom.oracle.com|http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:2196162600402] shows several different ways to do it.
    I recommend the first one, the user-defined function STRAGG, which you can copy from that page.
    On Oracle 10 (and up) you may have a similar function, WM_CONCAT (owned by WMSYS), already installed.
    WM_CONCAT is not documented, so you may not want to use it in your Production applications.
    STRAGG is not so convenient if the order of items in the concatenated string is important.
    In that case, use XMLAGG or SYS_CONNECT_BY_PATH, as shown later in the asktom page.
    MODEL can also do ordered string aggregation.

  • Shortest Path Algorithm:

    Hi,
    I have about 20,000 (double) points and trying to find a shortest path between any two. I know that the best algorithm for doing that is Dijkstra's one. What is the best data structure for this? I read that usually heaps but the time it needs to sort the list is too long, maybe some one knows a better way? Maybe there is another algorithm that solves this problem? Please give me any suggestion about anything that I said above.
    Thank you in advance.

    I don't know no Dijkstra's algorithm for this problem. The only algorithm of Dijkstra for something like that that I know is to find the shortest path between two nodes in a weight network.
    I think that the lower bound for what you are trying to do is the same lower bound for sorting the points, so I think that the best you can do is to apply a good sorting algorithm (like quicksort, mergesort, heapsort or shellsort).
    The best data structure depends about how much info do you have previously about the number of points and memory that you have available. If you know that the max number of points that you'll work can be fit in the available memory, then the best data holder to use is an array (it's aways the fastest). If you'll see it as an array or as stack (for example) depends on the algorithm that you'll choose to sort the points.
    One last tip: if you choose using a List, prefer the ArrayList over LinkedList. LinkedList is slower than ArrayList for almost all kind of operations. If you'll work with a lot of elemts, do some testing before pick one of the two.
    Hope it helps,
    RGB

  • Shortest Path Algorithm with Djikstra

    Hi all,
    im developing a shortest path searching techniques by using Djikstra's algorithm. My search space is very huge and it is about 100,000 nodes or we can call it Vertex. I store all the nodes and weight of edges in MySql as follows:
    From | To | PathCost
    A B 2
    B A 2
    A D 9
    D A 9
    B C 7
    C B 7
    B E 5
    E B 5
    C D 5
    D C 9
    Whenever the class receive any request from someone who want to go from point A to point Z, it will load the data from mysql by using "Select * FROM table WHERE From='Variable' ", and declare it as new Vertex, and perform the search. The reason i load it from MySql everytime i receive a new request is because any new node can be added to database anytime.
    In a nut shell, im developing a system to search for a shortest path in real world, i represent buildings as a Vertex, and road as edges, any idea of what can i improve my current djikstra searching method or any new developement to reduce the running time to lowest??
    regards,
    howsen

    minimal spanning tree != shortest path...
    Mr. Pike is indeed correct. Consider this simple example. arrange a bunch of dots around the rim of a circle. Consider the distance between them to be just the standard measure of distance in the plane. Assume that the points are fairly evenly spaced, but not exactly evenly spaced.
    The minimal spanning tree, which you got by first joining the two closest points and then the next two, and then by joining more points to that structure, will end up looking like a letter C going around the circle and leaving a gap between the two points that were the furthest apart on the circle.
    Every point connects to every other point, possibly by passing through other points and it is minimal because it left out the widest gap.
    On the other hand, the quickest way to get from one tip of the C to the other tip is to go straight from the one to the other, not to walk all the way around the circle following a path that goes through every single other point in the system.
    Reducing a graph to a minimal spanning tree, gets you a single subgraph of the original grpah that has the least total distance. That, unfortunately, has nothing to do with telling you the fastest way to get from point A to point B traveling along the original graph.
    hence minimal spanning tree != shortest path...

  • Best shortest path algorithm ??

    Hi
    I am developing an application to guide a user from one point to another. I need to work out the shortest path between these two points.
    Is Dijkstra's algorithm the best to use? or should I be looking for a different one? I am looking for speed.
    Thanks

    Choosing a "single source shortest path" algorithm depends on if you are going to use a weighted or not weighted graph, if all weights are non-negative or negative etc. If negative -weight edges are allowed, Djikstra's algorithm can not be used. Instead you can use the Bellman-Ford algorithm.
    The running time of Djikstra's algorithm is lower than that of the Bellman-Ford algorithm. Runningtime for the Bellman-Ford algorithm is in general O(V^2E). Because Djikstra's algorithm always chooses the "closest" vertex (in a weigthed directed graph G=(V,E)) , we say it uses a greedy strategy. This strategy does not always yield optimal result. How fast the Djiktra algorithm is, depends how the min-priority queue is implemented. f.example: if you use the linear array implementation of the min-priority queue, the runningtime for Djikstra's algorithm is O(v^3) while a binary min-heap implementation of min-priority queue gives a runningtime of O(V E lg V).

Maybe you are looking for

  • PDF portfolio search not working in Reader for Linux

    I have a PDF portfolio with embedded index created using Acrobat 9.5.5 running on Windows 7. I can search this portfolio without any problem using the windows versions of Acrobat 9.5.5 or Reader 11.0.4, but when I try any of the same searches using R

  • IMovie '11 freezes while trying to generate iPhoto thumbnails

    So I need to move videos from iPhoto to iMovie '11. iMovie said I had to generate thumbnails before I could do that so I pressed ok. The pop-up window shows "generating thumbnails Processing Event: iPhoto Videos Time Remaning: " the window said it wo

  • Canon mp600r wifi and airport express

    I have 2 airport express. One is a routeur (because there are an imac and an ibook)and is connected to dsl on internet. The others airport express is used to enlarge the wi-fi access network in the house. i want to use the second airport express for

  • Changing oracle DB link from Public to Private

    Dear All, I would like to know what will be the impact of chaning a PUBLIC db link to PRIVATE db link. following is the scenario. In our Prod distributed environment, there are many Databases which need to talk to each other for which we have create

  • Doesn't load embedded tweets

    Since I reloaded, Firefox doesn't load embedded tweets from any site. All I get is a blue line that shows where the tweet should be. Any ideas? I run the ABP add on.