Search Results

Search found 1553 results on 63 pages for 'tail recursion'.

Page 5/63 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Recursion Problem in PHP

    - by streetparade
    I need to create a valid xml from a given array(); My Method looks like this, protected function array2Xml($array) { $xml = ""; if(is_array($array)) { foreach($array as $key=>$value) { $xml .= "<$key>"; if(is_array($value)) { $xml .= $this->array2Xml($value); } $xml .= "</$key>"; } return $xml; } else { throw new Exception("in valid"); } } protected function createValidXMLfromArray($array,$node) { $xml = '<?xml version="1.0" encoding="ISO-8859-1"?>'; $xmlArray = $this->array2Xml($array); $xml .= "<$node>$xmlArray</$node>"; return $xml; } if i execute the above i just get keys with empty values; like <node> <name></name> </node> What i need is if i pass this array("name"=>"test","value"=>array("test1"=>33,"test2"=>40)); that it return this <node> <name>test</name> <value> <test1>33</test1> <test2>40</test2> </value> </node> Where is the error what did i wrong in the above recursion?

    Read the article

  • What is a Long Tail Keyword?

    Did you know that a long tail keyword will out convert a root keyword 9 times out of 10. In this article, I will discuss the reasons why the long tail is a better keyword to chase than the more common methods of chasing the root.

    Read the article

  • The Long Tail Keyword Phrase Phenomenon

    There's been much conversation and debate over whether to use short tail or long tail keyword phrases when working optimizing your articles and websites. I think a bit of both may be in order. Well let's first distinguish the difference and then we can talk about how we can apply them to our articles and/or website meta tags.

    Read the article

  • Winning With Long Tail Keywords - Become an Authority in Your Niche

    Most accomplished webmasters and SEO experts will mirror my words here. Winning in the long tail is essential to becoming an authority in your niche. Too often do webmasters go for the "frontal assault" when trying to win a niche, which more often than not results in their competition finding out about them, then pushing them out of the game with their strong list of long tail rankings. So, what can you do in order to dominate your niche and become an authority?

    Read the article

  • What is recursion? -- In plain english.

    - by Christopher Altman
    I hear this word everyday, but cannot give a meaningful, concise, or plain-english answer to what it is. Recursion is defined by the bastian of knowledge as: Recursion in computer science is a method where the solution to a problem depends on solutions to smaller instances of the same problem.1 The approach can be applied to many types of problems, and is one of the central ideas of computer science.[2] Source Is recursion simply something that repeats itself to get a solution? I am looking for a "Recursion for Dummies" definition, and maybe simple examples. My goal is to be able to understand and explain recursion in my own words. I do not like simply thinking I know the meaning of something because I hear it referenced daily, but have not paused to form my own understanding.

    Read the article

  • Is recursion preferred compare to iteration in multicore era?

    - by prM
    Or say, do multicore CPUs process recursion faster than iteration? Or it simply depends on how one language runs on the machine? like c executes function calls with large cost, comparing to doing simple iterations. I had this question because one day I told one of my friend that recursion isn't any amazing magic that can speed up programs, and he told me that with multicore CPUs recursion can be faster than iteration. EDIT: If we consider the most recursion-loved situation (data structure, function call), is it even possible for recursion to be faster?

    Read the article

  • Recursion in Java enums?

    - by davidrobles
    I've been trying for 3 hours and I just can't understand what is happening here. I have an enum 'Maze'. For some reason, when the method 'search' is called on this enum it's EXTREMELY slow (3 minutes to run). However, if I copy the same method to another class as a static method, and I call it from the enum 'Maze' it runs in one second! I don't understand why? is there any problem with recursive methods in Java enums?? What am I doing wrong? public enum Maze { A("A.txt"), B("B.txt"); // variables here... Maze(String fileName) { loadMap(fileName); nodeDistances = new int[nodes.size()][nodes.size()]; setNeighbors(); setDistances(); } ... more methods here ... private void setDistances() { nodeDistances = new int[nodes.size()][nodes.size()]; for (int i = 0; i < nodes.size(); i++) { setMax(nodeDistances[i]); // This works!!! TestMaze.search(nodes, nodeDistances[i], i, 0); // This DOESN'T WORK //search(nodes, nodeDistances[i], i, 0); } } public void setMax(int[] a) { for (int i=0; i<a.length; i++) { a[i] = Integer.MAX_VALUE; } } public void search(List<Node> allNodes, int[] distances, int curNodeIndex, int curDist) { if (curDist < distances[curNodeIndex]) { distances[curNodeIndex] = curDist; for (Node n : allNodes.get(curNodeIndex).getNeighbors()) { search(allNodes, distances, n.getNodeIndex(), curDist + 1); } } } } public class TestMaze { public static void search(List<Node> allNodes, int[] distances, int curNodeIndex, int curDist) { if (curDist < distances[curNodeIndex]) { distances[curNodeIndex] = curDist; for (Node n : allNodes.get(curNodeIndex).getNeighbors()) { search(allNodes, distances, n.getNodeIndex(), curDist + 1); } } } }

    Read the article

  • Python recursion , Sierpinski triangle with color at each depth

    - by ???? ???
    import turtle w=turtle.Screen() def Tri(t, order, size): if order==0: t.forward(size) t.left(120) t.forward(size) t.left(120) t.forward(size) t.left(120) else: t.pencolor('red') Tri(t, order-1, size/2, color-1) t.fd(size/2) t.pencolor('blue') Tri(t, order-1, size/2, color-1) t.fd(size/2) t.lt(120) t.fd(size) t.lt(120) t.fd(size/2) t.lt(120) t.pencolor('green') Tri(t, order-1, size/2,color-1) t.rt(120) t.fd(size/2) t.lt(120) can anyone help with this problem ? i want to a sierpinski triangle that have color at specific depth like this http://openbookproject.net/thinkcs/python/english3e/_images/sierpinski_color.png i dont know how to make the the triangle color change at specific depth

    Read the article

  • Dynamic Programming Recursion and a sprinkle of Memoization

    - by Auburnate
    I have this massive array of ints from 0-4 in this triangle. I am trying to learn dynamic programming with Ruby and would like some assistance in calculating the number of paths in the triangle that meet three criterion: You must start at one of the zero points in the row with 70 elements. Your path can be directly above you one row (if there is a number directly above) or one row up heading diagonal to the left. One of these options is always available The sum of the path you take to get to the zero on the first row must add up to 140. Example, start at the second zero in the bottom row. You can move directly up to the one or diagonal left to the 4. In either case, the number you arrive at must be added to the running count of all the numbers you have visited. From the 1 you can travel to a 2 (running sum = 3) directly above or to the 0 (running sum = 1) diagonal to the left. 0 41 302 2413 13024 024130 4130241 30241302 241302413 1302413024 02413024130 413024130241 3024130241302 24130241302413 130241302413024 0241302413024130 41302413024130241 302413024130241302 2413024130241302413 13024130241302413024 024130241302413024130 4130241302413024130241 30241302413024130241302 241302413024130241302413 1302413024130241302413024 02413024130241302413024130 413024130241302413024130241 3024130241302413024130241302 24130241302413024130241302413 130241302413024130241302413024 0241302413024130241302413024130 41302413024130241302413024130241 302413024130241302413024130241302 2413024130241302413024130241302413 13024130241302413024130241302413024 024130241302413024130241302413024130 4130241302413024130241302413024130241 30241302413024130241302413024130241302 241302413024130241302413024130241302413 1302413024130241302413024130241302413024 02413024130241302413024130241302413024130 413024130241302413024130241302413024130241 3024130241302413024130241302413024130241302 24130241302413024130241302413024130241302413 130241302413024130241302413024130241302413024 0241302413024130241302413024130241302413024130 41302413024130241302413024130241302413024130241 302413024130241302413024130241302413024130241302 2413024130241302413024130241302413024130241302413 13024130241302413024130241302413024130241302413024 024130241302413024130241302413024130241302413024130 4130241302413024130241302413024130241302413024130241 30241302413024130241302413024130241302413024130241302 241302413024130241302413024130241302413024130241302413 1302413024130241302413024130241302413024130241302413024 02413024130241302413024130241302413024130241302413024130 413024130241302413024130241302413024130241302413024130241 3024130241302413024130241302413024130241302413024130241302 24130241302413024130241302413024130241302413024130241302413 130241302413024130241302413024130241302413024130241302413024 0241302413024130241302413024130241302413024130241302413024130 41302413024130241302413024130241302413024130241302413024130241 302413024130241302413024130241302413024130241302413024130241302 2413024130241302413024130241302413024130241302413024130241302413 13024130241302413024130241302413024130241302413024130241302413024 024130241302413024130241302413024130241302413024130241302413024130 4130241302413024130241302413024130241302413024130241302413024130241 30241302413024130241302413024130241302413024130241302413024130241302 241302413024130241302413024130241302413024130241302413024130241302413 1302413024130241302413024130241302413024130241302413024130241302413024 02413024130241302413024130241302413024130241302413024130241302413024130

    Read the article

  • JavaScript recursion does not work properly

    - by misha-moroshko
    Hi, Could anyone say why the following recursive function does not work for me ? It should collect recursively all radio buttons in a given element. But, it does not found any for some reason !? Thanks !! <?xml version="1.0" encoding="Windows-1255"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script type="text/javascript"> function AllInputs(radioElement) { this.radioInputs = ((arguments.length == 1) ? [radioElement] : []); } AllInputs.prototype.toString = function() { return "[object AllInputs: radioInputs: " + this.radioInputs.length + "]"; } AllInputs.prototype.add = function(otherAllInputs) { this.radioInputs = this.radioInputs.concat(otherAllInputs.radioInputs); } function getAllInputsOfElement(element) { if (element.tagName.toLowerCase() == "input") { if (element.getAttribute("type").toLowerCase() == "radio") { return new AllInputs(element); } else { return new AllInputs(); } } else { var result = new AllInputs(); for (i = 0; i < element.children.length; i++) { result.add(getAllInputsOfElement(element.children[i])); } return result; } } function main() { alert(getAllInputsOfElement(document.getElementById("MyTable"))); } </script> </head> <body onload="main()"> <table id="MyTable"> <tr><td>Day</td></tr> <tr><td> <input type="radio" name="DayOfTheWeek" value="1" /><label>Monday</label> <input type="radio" name="DayOfTheWeek" value="2" /><label>Tuesday</label> <input type="radio" name="DayOfTheWeek" value="3" /><label>Wednesday</label> </td></tr> </table> </body> </html>

    Read the article

  • Using recursion to find paths in a 2D array

    - by rikkit
    Hi, I'm working on a project for my A level. It involves finding the maximum flow of a network, and I'm using javascript. I have a 2D array, with values in the array representing a distance between the two points. An example of the array: 0 2 2 0 0 0 1 2 0 0 0 2 0 0 0 0 I think I need to use a recursive technique to find a path; below is some pseudocode, assuming that the array is 4x4. a is (0,0), b is (3,3). function search(a,b) from a to b if element(i,j) != 0 then store value of element search(j,3) I was wondering if that was the right construction for a depth first search. Thanks for any help.

    Read the article

  • XSLT 1.0 help with recursion logic

    - by DashaLuna
    Hello guys, I'm having troubles with the logic and would apprecite any help/tips. I have <Deposits> elements and <Receipts> elements. However there isn't any identification what receipt was paid toward what deposit. I am trying to update the <Deposits> elements with the following attributes: @DueAmont - the amount that is still due to pay @Status - whether it's paid, outstanding (partly paid) or due @ReceiptDate - the latest receipt's date that was paid towards this deposit Every deposit could be paid with one or more receipts. It also could happen, that 1 receipt could cover one or more deposits. For example. If there are 3 deposits: 500 100 450 That are paid with the following receipts: 200 100 250 I want to get the following info: Deposit 1 is fully paid (status=paid, dueAmount=0, receiptNum=3. Deposit 2 is partly paid (status=outstanding, dueAmount=50, receiptNum=3. Deposit 3 is not paid (status=due, dueAmount=450, receiptNum=NAN. I've added comments in the code explaining what I'm trying to do. I am staring at this code for the 3rd day now non stop - can't see what I'm doing wrong. Please could anyone help me with it? :) Thanks! Set up: $deposits - All the available deposits $receiptsAsc - All the available receipts sorted by their @ActionDate Code: <!-- Accumulate all the deposits with @Status, @DueAmount and @ReceiptDate attributes Provide all deposits, receipts and start with 1st receipt --> <xsl:variable name="depositsClassified"> <xsl:call-template name="classifyDeposits"> <xsl:with-param name="depositsAll" select="$deposits"/> <xsl:with-param name="receiptsAll" select="$receiptsAsc"/> <xsl:with-param name="receiptCount" select="'1'"/> </xsl:call-template> </xsl:variable> <!-- Recursive function to associate deposits' total amounts with overall receipts paid to determine whether a deposit is due, outstanding or paid. Also determine what's the due amount and latest receipt towards the deposit for each deposit --> <xsl:template name="classifyDeposits"> <xsl:param name="depositsAll"/> <xsl:param name="receiptsAll"/> <xsl:param name="receiptCount"/> <!-- If there are deposits to proceed --> <xsl:if test="$depositsAll"> <!-- Get the 1st deposit --> <xsl:variable name="deposit" select="$depositsAll[1]"/> <!-- Calculate the sum of all receipts up to and including currenly considered --> <xsl:variable name="receiptSum"> <xsl:choose> <xsl:when test="$receiptsAll"> <xsl:value-of select="sum($receiptsAll[position() &lt;= $receiptCount]/@ReceiptAmount)"/> </xsl:when> <xsl:otherwise>0</xsl:otherwise> </xsl:choose> </xsl:variable> <!-- Difference between deposit amount and sum of the receipts calculated above --> <xsl:variable name="diff" select="$deposit/@DepositTotalAmount - $receiptSum"/> <xsl:choose> <!-- Deposit isn't paid fully and there are more receipts/payments exist. So consider the same deposit, but take next receipt into calculation as well --> <xsl:when test="($diff &gt; 0) and ($receiptCount &lt; count($receiptsAll))"> <xsl:call-template name="classifyDeposits"> <xsl:with-param name="depositsAll" select="$depositsAll"/> <xsl:with-param name="receiptsAll" select="$receiptsAll"/> <xsl:with-param name="receiptCount" select="$receiptCount + 1"/> </xsl:call-template> </xsl:when> <!-- Deposit is paid or we ran out of receipts --> <xsl:otherwise> <!-- process the deposit. Determine its status and then update corresponding attributes --> <xsl:apply-templates select="$deposit" mode="defineDeposit"> <xsl:with-param name="diff" select="$diff"/> <xsl:with-param name="receiptNum" select="$receiptCount"/> </xsl:apply-templates> <!-- Recursively call the template with the rest of deposits excluding the first. Before hand update the @ReceiptsAmount. For the receipts before current it is now 0, for the current is what left in the $diff, and simply copy over receipts after current one. --> <xsl:variable name="receiptsUpdatedRTF"> <xsl:for-each select="$receiptsAll"> <xsl:choose> <!-- these receipts was fully accounted for the current deposit. Make them 0 --> <xsl:when test="position() &lt; $receiptCount"> <xsl:copy> <xsl:copy-of select="./@*"/> <xsl:attribute name="ReceiptAmount">0</xsl:attribute> </xsl:copy> </xsl:when> <!-- this receipt was partly/fully(in case $diff=0) accounted for the current deposit. Make it whatever is in $diff --> <xsl:when test="position() = $receiptCount"> <xsl:copy> <xsl:copy-of select="./@*"/> <xsl:attribute name="ReceiptAmount"> <xsl:value-of select="format-number($diff, '#.00;#.00')"/> </xsl:attribute> </xsl:copy> </xsl:when> <!-- these receipts weren't yet considered - copy them over --> <xsl:otherwise> <xsl:copy-of select="."/> </xsl:otherwise> </xsl:choose> </xsl:for-each> </xsl:variable> <xsl:variable name="receiptsUpdated" select="msxsl:node-set($receiptsUpdatedRTF)/Receipts"/> <!-- Recursive call for the next deposit. Starting counting receipts from the current one. --> <xsl:call-template name="classifyDeposits"> <xsl:with-param name="depositsAll" select="$deposits[position() != 1]"/> <xsl:with-param name="receiptsAll" select="$receiptsUpdated"/> <xsl:with-param name="receiptCount" select="$receiptCount"/> </xsl:call-template> </xsl:otherwise> </xsl:choose> </xsl:if> </xsl:template> <!-- Determine deposit's status and due amount --> <xsl:template match="MultiDeposits" mode="defineDeposit"> <xsl:param name="diff"/> <xsl:param name="receiptNum"/> <xsl:choose> <xsl:when test="$diff &lt;= 0"> <xsl:apply-templates select="." mode="addAttrs"> <xsl:with-param name="status" select="'paid'"/> <xsl:with-param name="dueAmount" select="'0'"/> <xsl:with-param name="receiptNum" select="$receiptNum"/> </xsl:apply-templates> </xsl:when> <xsl:when test="$diff = ./@DepositTotalAmount"> <xsl:apply-templates select="." mode="addAttrs"> <xsl:with-param name="status" select="'due'"/> <xsl:with-param name="dueAmount" select="$diff"/> </xsl:apply-templates> </xsl:when> <xsl:when test="$diff &lt; ./@DepositTotalAmount"> <xsl:apply-templates select="." mode="addAttrs"> <xsl:with-param name="status" select="'outstanding'"/> <xsl:with-param name="dueAmount" select="$diff"/> <xsl:with-param name="receiptNum" select="$receiptNum"/> </xsl:apply-templates> </xsl:when> <xsl:otherwise/> </xsl:choose> </xsl:template> <!-- Add new attributes (@Status, @DueAmount and @ReceiptDate) to the deposit element --> <xsl:template match="MultiDeposits" mode="addAttrs"> <xsl:param name="status"/> <xsl:param name="dueAmount"/> <xsl:param name="receiptNum" select="''"/> <xsl:copy> <xsl:copy-of select="./@*"/> <xsl:attribute name="Status"><xsl:value-of select="$status"/></xsl:attribute> <xsl:attribute name="DueAmount"><xsl:value-of select="$dueAmount"/></xsl:attribute> <xsl:if test="$receiptNum != ''"> <xsl:attribute name="ReceiptDate"> <xsl:value-of select="$receiptsAsc[position() = $receiptNum]/@ActionDate"/> </xsl:attribute> </xsl:if> <xsl:copy-of select="./*"/> </xsl:copy> </xsl:template>

    Read the article

  • HQL recursion, how do I do this?

    - by niklassaers
    Hi guys, I have a tree structure where each Node has a parent and a Set<Node> children. Each Node has a String title, and I want to make a query where I select Set<String> titles, being the title of this node and of all parent nodes. How do I write this query? The query for a single title is this, but like I said, I'd like it expanded for the entire branch of parents. SELECT node.title FROM Node node WHERE node.id = :id Cheers Nik

    Read the article

  • Recursion causes exit to exit all JFrames (terminates app)

    - by Trizicus
    I have made an application that gives the user the option to open up a new spawn of the application entirely. When the user does so and closes the application the entire application terminates; not just the window. How should I go about recursively spawning an application and then when the user exits the JFrame spawn; killing just that JFrame and not the entire instance? Here is the relevant code: [...] JMenuItem newMenuItem = new JMenuItem ("New"); newMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new MainWindow(); } }); fileMenu.add(newMenuItem); [....] JMenuItem exit = new JMenuItem("Exit"); exit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }); fileMenu.add(exit); [...]

    Read the article

  • condition in recursion - best practise

    - by mo
    hi there! what's the best practise to break a loop? my ideas were: Child Find(Parent parent, object criteria) { Child child = null; foreach(Child wannabe in parent.Childs) { if (wannabe.Match(criteria)) { child = wannabe; break; } else { child = Find(wannabe, criteria); } } return child; } or Child Find(Parent parent, object criteria) { Child child = null; var conditionator = from c parent.Childs where child != null select c; foreach(Child wannabe in conditionator) { if (wannabe.Match(criteria)) { child = wannabe; } else { child = Find(wannabe, criteria); } } return child; } or Child Find(Parent parent, object criteria) { Child child = null; var enumerator = parent.Childs.GetEnumerator(); while(child != null && enumerator.MoveNext()) { if (enumerator.Current.Match(criteria)) { child = wannabe; } else { child = Find(wannabe, criteria); } } return child; } what do u think, any better ideas? i'm looking for the niciest solution :D mo

    Read the article

  • Recursion and Iteration

    - by Doug
    What is the difference? Are these the same? If not, can someone please give me an example? MW: Iteration - 1 : the action or a process of iterating or repeating: as a : a procedure in which repetition of a sequence of operations yields results successively closer to a desired result b : the repetition of a sequence of computer instructions a specified number of times or until a condition is met Recusion - 3 : a computer programming technique involving the use of a procedure, subroutine, function, or algorithm that calls itself one or more times until a specified condition is met at which time the rest of each repetition is processed from the last one called to the first

    Read the article

  • Fortran recursion segmentation faults

    - by ConnorG
    Hey all - I have to design and implement a Fortran routine to determine the size of clusters on a square lattice, and it seemed extremely convenient to code the subroutine recursively. However, whenever my lattice size grows beyond a certain value (around 200/side), the subroutine consistently segfaults. Here's my cluster-detection routine: RECURSIVE SUBROUTINE growCluster(lattice, adj, idx, area) INTEGER, INTENT(INOUT) :: lattice(:), area INTEGER, INTENT(IN) :: adj(:,:), idx lattice(idx) = -1 area = area + 1 IF (lattice(adj(1,idx)).GT.0) & CALL growCluster(lattice,adj,adj(1,idx),area) IF (lattice(adj(2,idx)).GT.0) & CALL growCluster(lattice,adj,adj(2,idx),area) IF (lattice(adj(3,idx)).GT.0) & CALL growCluster(lattice,adj,adj(3,idx),area) IF (lattice(adj(4,idx)).GT.0) & CALL growCluster(lattice,adj,adj(4,idx),area) END SUBROUTINE growCluster where adj(1,n) represents the north neighbor of site n, adj(2,n) represents the west and so on. What would cause the erratic segfault behavior? Is the cluster just "too huge" for large lattice sizes?

    Read the article

  • build a bst as an array using recursion?

    - by Jack B
    String[] dictionary = new String[dictSize]; //arrray of strings from dictionary String[] tree = new String[3*dictSize]; //array of tree void makeBST() { recMakeBST(0, dictionary.length-1); }//makeBST() int a=0; void recMakeBST(int low, int high) { if(high-low==0){ return; } else{ int mid=(high-low)/2; tree[a]=dictionary[mid]; a=a+1; recMakeBST(low, mid-1); a=a+1; recMakeBST(mid+1, high); } }

    Read the article

  • Basic Recursion, Check Balanced Parenthesis

    - by pws5068
    Greetings all, I've written software in the past that uses a stack to check for balanced equations, but now I'm asked to write a similar algorithm recursively to check for properly nested brackets and parenthesis. Good examples: () [] () ([]()[]) Bad examples: ( (] ([)] Suppose my function is called: isBalanced. Should each pass evaluate a smaller substring (until reaching a base case of 2 left)? Or, should I always evaluate the full string and move indices inward?

    Read the article

  • sorting using recursion

    - by user310587
    I have the following function to sort an array with even numbers in the front and odd numbers in the back. Is there a way to get it done without using any loops? //front is 0, back =array.length-1; arrangeArray (front, back); public static void arrangeArray (int front, int back) { if (front != back || front<back) { while (numbers [front]%2 == 0) front++; while (numbers[back]%2!=0) back--; if (front < back) { int oddnum = numbers [front]; numbers[front]= numbers[back]; numbers[back]=oddnum; arrangeArray (front+1, back-1); } } }

    Read the article

  • Using recursion an append in prolog

    - by Adrian
    Lets say that I would like to construct a list (L2) by appending elements of another list (L) one by one. The result should be exactly the same as the input. This task is silly, but it'll help me understand how to recurse through a list and remove certain elements. I have put together the following code: create(L, L2) :- (\+ (L == []) -> L=[H|T], append([H], create(T, L2), L2);[]). calling it by create([1,2,3,4], L2) returns L2 = [1|create([2,3,4], **)\. which is not a desired result.

    Read the article

  • Recursion Problems in Prolog

    - by Humble_Student
    I'm having some difficulties in prolog, I'm trying to write a predicate that will return all paths between two cities, although at the moment it returns the first path it finds on an infinite loop. Not sure where I'm going wrong but I've been trying to figure this out all day and I'm getting nowhere. Any help that could be offered would be appreciated. go:- repeat, f([],0,lon,spa,OP,OD), write(OP), write(OD), fail. city(lon). city(ath). city(spa). city(kol). path(lon,1,ath). path(ath,3,spa). path(spa,2,kol). path(lon,1,kol). joined(X,Y,D):- path(X,D,Y);path(Y,D,X). f(Ci_Vi,Di,De,De,PaO,Di):- append([De],Ci_Vi,PaO), !. f(Cities_Visited,Distance,Start,Destination,Output_Path,Output_Distance):- repeat, city(X), joined(Start,X,D), not_member(X,Cities_Visited), New_Distance is Distance + D, f([Start|Cities_Visited],New_Distance,X,Destination,Output_Path,Output_Distance). not_member(X,List):- member(X,List), !, fail. not_member(X,List). The output I'm expecting here is [spa,ath,lon]4 [spa,kol,lon]3. Once again, any help would be appreciated. Many thanks in advance.

    Read the article

  • Recursion Question : Revision

    - by stan
    My slides say that: A recursive call should always be on a smaller data structure than the current one There must be a non recursive option if the data structure is too small You need a wrapper method to make the recursive method accessible Just reading this from the slides makes no sense, especially seeing as it was a topic from before christmas! Could anyone try and clear up what it means please? Thank you

    Read the article

  • Using recursion to to trim a binary tree based on a given min and max value

    - by Justin
    As the title says, I have to trim a binary tree based on a given min and max value. Each node stores a value, and a left/right node. I may define private helper methods to solve this problem, but otherwise I may not call any other methods of the class nor create any data structures such as arrays, lists, etc. An example would look like this: overallRoot _____[50]____________________ / \ __________[38] _______________[90] / \ / _[14] [42] [54]_____ / \ \ [8] [20] [72] \ / \ [26] [61] [83] trim(52, 65); should return: overallRoot [54] \ [61] My attempted solution has three methods: public void trim(int min, int max) { rootFinder(overallRoot, min, max); } First recursive method finds the new root perfectly. private void rootFinder(IntTreeNode node, int min, int max) { if (node == null) return; if (overallRoot.data < min) { node = overallRoot = node.right; rootFinder(node, min, max); } else if (overallRoot.data > max) { node = overallRoot = node.left; rootFinder(node, min, max); } else cutter(overallRoot, min, max); } This second method should eliminate any further nodes not within the min/max, but it doesn't work as I would hope. private void cutter(IntTreeNode node, int min, int max) { if (node == null) return; if (node.data <= min) { node.left = null; } if (node.data >= max) { node.right = null; } if (node.data < min) { node = node.right; } if (node.data > max) { node = node.left; } cutter(node.left, min, max); cutter(node.right, min, max); } This returns: overallRoot [54]_____ \ [72] / [61] Any help is appreciated. Feel free to ask for further explanation as needed.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >