Search Results

Search found 828 results on 34 pages for 'recursion'.

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

  • Recursion in the form of a Recursive Func&lt;T, T&gt;

    - by ToStringTheory
    I gotta admit, I am kind of surprised that I didn’t realize I could do this sooner.  I recently had a problem which required a recursive function call to come up with the answer.  After some time messing around with a recursive method, and creating an API that I was not happy with, I was able to create an API that I enjoy, and seems intuitive. Introduction To bring it to a simple example, consider the summation to n: A mathematically identical formula is: In a .NET function, this can be represented by a function: Func<int, int> summation = x => x*(x+1)/2 Calling summation with an input integer will yield the summation to that number: var sum10 = summation(4); //sum10 would be equal to 10 But what if I wanted to get a second level summation…  First some to n, and then use that argument as the input to the same function, to find the second level summation: So as an easy example, calculate the summation to 3, which yields 6.  Then calculate the summation to 6 which yields 21. Represented as a mathematical formula - So what if I wanted to represent this as .NET functions.  I can always do: //using the summation formula from above var sum3 = summation(3); //sets sum3 to 6 var sum3_2 = summation(sum3); //sets sum3 to 21 I could always create a while loop to perform the calculations too: Func<int, int> summation = x => x*(x+1)/2; //for the interests of a smaller example, using shorthand int sumResultTo = 3; int level = 2; while(level-- > 0) { sumResultTo = summation(sumResultTo); } //sumResultTo is equal to 21 now. Or express it as a for-loop, method calls, etc…  I really didn’t like any of the options that I tried.  Then it dawned on me – since I was using a Func<T, T> anyways, why not use the Func’s output from one call as the input as another directly. Some Code So, I decided that I wanted a recursion class.  Something that I would be generic and reusable in case I ever wanted to do something like this again. It is limited to only the Func<T1, T2> level of Func, and T1 must be the same as T2. The first thing in this class is a private field for the function: private readonly Func<T, T> _functionToRecurse; So, I since I want the function to be unchangeable, I have defined it as readonly.  Therefore my constructor looks like: public Recursion(Func<T, T> functionToRecurse) { if (functionToRecurse == null) { throw new ArgumentNullException("functionToRecurse", "The function to recurse can not be null"); } _functionToRecurse = functionToRecurse; } Simple enough.  If you have any questions, feel free to post them in the comments, and I will be sure to answer them. Next, I want enough. If be able to get the result of a function dependent on how many levels of recursion: private Func<T, T> GetXLevel(int level) { if (level < 1) { throw new ArgumentOutOfRangeException("level", level, "The level of recursion must be greater than 0"); } if (level == 1) return _functionToRecurse; return _GetXLevel(level - 1, _functionToRecurse); } So, if you pass in 1 for the level, you get just the Func<T,T> back.  If you say that you want to go deeper down the rabbit hole, it calls a method which accepts the level it is at, and the function which it needs to use to recurse further: private Func<T, T> _GetXLevel(int level, Func<T, T> prevFunc) { if (level == 1) return y => prevFunc(_functionToRecurse(y)); return _GetXLevel(level - 1, y => prevFunc(_functionToRecurse(y))); } That is really all that is needed for this class. If I exposed the GetXLevel function publicly, I could use that to get the function for a level, and pass in the argument..  But I wanted something better.  So, I used the ‘this’ array operator for the class: public Func<T,T> this[int level] { get { if (level < 1) { throw new ArgumentOutOfRangeException("level", level, "The level of recursion must be greater than 0"); } return this.GetXLevel(level); } } So, using the same example above of finding the second recursion of the summation of 3: var summator = new Recursion<int>(x => (x * (x + 1)) / 2); var sum_3_level2 = summator[2](3); //yields 21 You can even find just store the delegate to the second level summation, and use it multiple times: var summator = new Recursion<int>(x => (x * (x + 1)) / 2); var sum_level2 = summator[2]; var sum_3_level2 = sum_level2(3); //yields 21 var sum_4_level2 = sum_level2(4); //yields 55 var sum_5_level2 = sum_level2(5); //yields 120 Full Code Don’t think I was just going to hold off on the full file together and make you do the hard work…  Copy this into a new class file: public class Recursion<T> { private readonly Func<T, T> _functionToRecurse; public Recursion(Func<T, T> functionToRecurse) { if (functionToRecurse == null) { throw new ArgumentNullException("functionToRecurse", "The function to recurse can not be null"); } _functionToRecurse = functionToRecurse; } public Func<T,T> this[int level] { get { if (level < 1) { throw new ArgumentOutOfRangeException("level", level, "The level of recursion must be greater than 0"); } return this.GetXLevel(level); } } private Func<T, T> GetXLevel(int level) { if (level < 1) { throw new ArgumentOutOfRangeException("level", level, "The level of recursion must be greater than 0"); } if (level == 1) return _functionToRecurse; return _GetXLevel(level - 1, _functionToRecurse); } private Func<T, T> _GetXLevel(int level, Func<T, T> prevFunc) { if (level == 1) return y => prevFunc(_functionToRecurse(y)); return _GetXLevel(level - 1, y => prevFunc(_functionToRecurse(y))); } } Conclusion The great thing about this class, is that it can be used with any function with same input/output parameters.  I strived to find an implementation that I found clean and useful, and I finally settled on this.  If you have feedback – good or bad, I would love to hear it!

    Read the article

  • What is the relationship between recursion functions and memory stack?

    - by Eslam
    is there's a direct relationship between recursive functions and the memory stack, for more explanation consider that code: public static int triangle(int n) { System.out.println(“Entering: n = ” + n); if (n == 1) { System.out.println(“Returning 1”); return 1; } else { int temp = n + triangle(n - 1); System.out.println(“Returning“ + temp); return temp; } }? in this example where will the values 2,3,4,5 be stored until the function returns ? note that they will be returned in LIFO(LastInFirstOut) is these a special case of recursion that deals with the memory stack or they always goes together?

    Read the article

  • Can anyone help with java? Finding common nodes from two linked lists using recursion

    - by Dan
    I have to write a method that returns a linked list with all the nodes that are common to two linked lists using recursion, without loops. For example, first list is 2 - 5 - 7 - 10 second list is 2 - 4 - 8 - 10 the list that would be returned is 2 - 10 I am getting nowhere with this.. What I have been think of was to check each value of the first list with each value of the second list recursively but the second list would then be cut by one node everytime and I cannot compare the next value in the first list with the the second list. I hope this makes sense... Can anyone help?

    Read the article

  • Recursion with an Array; can't get the right value to return

    - by Matt
    Recursive Solution: Not working! Explanation: An integer, time, is passed into the function. It's then used to provide an end to the FOR statement (counter<time). The IF section (time == 0) provides a base case where the recursion should terminate, returning 0. The ELSE section is where the recursive call occurs: total is a private variable defined in the header file, elsewhere. It's initialized to 0 in a constructor, elsewhere. The function calls itself, recursively, adding productsAndSales[time-1][0] to total, again, and again, until the base call. Then the total is returned, and printed out later. Well, that's what I hoped for anyway. What I imagined would happen is that I would add up all the values in this one column of the array and the value would get returned, and printed out. Instead if returns 0. If I set the IF section to "return 1", I noticed that it returns powers of 2, for whatever value time is. EG: Time = 3, it returns 2*2 + 1. If time = 5, it returns 2*2*2*2 + 1. I don't understand why it's not returning the value I'm expecting. int CompanySales::calcTotals( int time ) { cout << setw( 4 ); if ( time == 0 ) { return 0; } else { return total += calcTotals( productsAndSales[ time-1 ][ 0 ]); } } Iterative Solution: Working! Explanation: An integer, time, is passed into the function. It's then used to provide an end to the FOR statement (counter<time). The FOR statement cycles through an array, adding all of the values in one column together. The value is then returned (and elsewhere in the program, printed out). Works perfectly. int CompanySales::calcTotals( int time ) { int total = 0; cout << setw( 4 ); for ( int counter = 0; counter < time; counter++ ) { total += productsAndSales[counter][0]; } return total0; }

    Read the article

  • Why isn't this infinite recursion? How does default variable initialization work in VB.NET?

    - by froadie
    I just made an interesting mistake in my code: Dim endColumn As Integer = startColumn + endColumn - 1 The code was actually supposed to be: Dim endColumn As Integer = startColumn + numColumns - 1 The interesting thing is, I would think that this code should be recursive and loop indefinitely, as the initialization of endColumn sort of calls itself. However, it seems that the code just treats the uninitialized variable as a 0 and so I get startColumn + 0 - 1. What is happening here behind the scenes? When does a variable get assigned a default value?

    Read the article

  • code doesnot delete specific extra files but deletes all, also no recursion for directory, help me t

    - by OM The Eternity
    I have to compare two folder structure and with reference of source folder I want to delete all the files/folders present in other destination folder which do not exist in reference source folder, how could i do this? $original = scan_dir_recursive('/var/www/html/copy2'); $mirror = scan_dir_recursive('/var/www/html/copy1'); function scan_dir_recursive($dir) { $all_paths = array(); $new_paths = scandir($dir); foreach ($new_paths as $path) { if ($path == '.' || $path == '..') { continue; } $path = $dir . DIRECTORY_SEPARATOR . $path; if (is_dir($path)) { $all_paths = array_merge($all_paths, scan_dir_recursive($path)); } else { $all_paths[] = $path; } } return $all_paths; } foreach($mirror as $mirr) { if($mirr != '.' && $mirr != '..') { if(!in_array($mirr, $original)) { unlink($mirr); // delete the file } } } The above code shows what i did.. Here My copy1 folder contains extra files than copy2 folders hence i need these extra files to be deleted. Below given output is are arrays of original Mirror and of difference of both.. Original Array ( [0] => /var/www/html/copy2/Copy (5) of New Text Document.txt [1] => /var/www/html/copy2/Copy of New Text Document.txt ) Mirror Array ( [0] => /var/www/html/copy1/Copy (2) of New Text Document.txt [1] => /var/www/html/copy1/Copy (3) of New Text Document.txt [2] => /var/www/html/copy1/Copy (5) of New Text Document.txt ) Difference Array ( [0] => /var/www/html/copy1/Copy (2) of New Text Document.txt [1] => /var/www/html/copy1/Copy (3) of New Text Document.txt [2] => /var/www/html/copy1/Copy (5) of New Text Document.txt ) when i iterate a loop to delete on difference array all files has to be deleted as per displayed output.. how can i rectify this.. the loop for deletion is given below. $dirs_to_delete = array(); foreach ($diff_path as $path) { if (is_dir($path)) { $dirs_to_delete[] = $path; } else { unlink($path); } } while ($dir = array_pop($dirs_to_delete)) { rmdir($dir); }

    Read the article

  • F# why my recursion is faster than Seq.exists?

    - by user38397
    I am pretty new to F#. I'm trying to understand how I can get a fast code in F#. For this, I tried to write two methods (IsPrime1 and IsPrime2) for benchmarking. My code is: // Learn more about F# at http://fsharp.net open System open System.Diagnostics #light let isDivisible n d = n % d = 0 let IsPrime1 n = Array.init (n-2) ((+) 2) |> Array.exists (isDivisible n) |> not let rec hasDivisor n d = match d with | x when x < n -> (n % x = 0) || (hasDivisor n (d+1)) | _ -> false let IsPrime2 n = hasDivisor n 2 |> not let SumOfPrimes max = [|2..max|] |> Array.filter IsPrime1 |> Array.sum let maxVal = 20000 let s = new Stopwatch() s.Start() let valOfSum = SumOfPrimes maxVal s.Stop() Console.WriteLine valOfSum Console.WriteLine("IsPrime1: {0}", s.ElapsedMilliseconds) ////////////////////////////////// s.Reset() s.Start() let SumOfPrimes2 max = [|2..max|] |> Array.filter IsPrime2 |> Array.sum let valOfSum2 = SumOfPrimes2 maxVal s.Stop() Console.WriteLine valOfSum2 Console.WriteLine("IsPrime2: {0}", s.ElapsedMilliseconds) Console.ReadKey() IsPrime1 takes 760 ms while IsPrime2 takes 260ms for the same result. What's going on here and how I can make my code even faster?

    Read the article

  • Is writing recursive functions hard for you?

    - by null
    I'm taking a computer science course now. I feel it is so hard compared to my polytechnic IT course. I can't understand recursive methods well. How do you manage to get your brain to understand it? When the recursive method returns back, my brain can not trace it nicely. Is there a better way to understand recursion? How do you start learning it? Is it normal that feel that it is very hard at then beginning? Look at the example, I'm very surprised how can I write this if it appears in exam. public class Permute { public static void main(String[] args) { new Permute().printPerms(3); } boolean[] used; int max; public void printPerms(int size) { used = new boolean[size]; max = size; for (int i = 0; i < size; i++) { used[i] = false; } perms(size, ""); } public void perms(int remaining, String res) { if (remaining == 0) { System.out.println(res); } else { for (int i = 0; i < max; i++) { if (!(used[i])) { used[i] = true; perms(remaining - 1, res + " " + i); used[i] = false; } } } } }

    Read the article

  • Equal Gifts Algorithm Problem

    - by 7Aces
    Problem Link - http://opc.iarcs.org.in/index.php/problems/EQGIFTS It is Lavanya's birthday and several families have been invited for the birthday party. As is customary, all of them have brought gifts for Lavanya as well as her brother Nikhil. Since their friends are all of the erudite kind, everyone has brought a pair of books. Unfortunately, the gift givers did not clearly indicate which book in the pair is for Lavanya and which one is for Nikhil. Now it is up to their father to divide up these books between them. He has decided that from each of these pairs, one book will go to Lavanya and one to Nikhil. Moreover, since Nikhil is quite a keen observer of the value of gifts, the books have to be divided in such a manner that the total value of the books for Lavanya is as close as possible to total value of the books for Nikhil. Since Lavanya and Nikhil are kids, no book that has been gifted will have a value higher than 300 Rupees... For the problem, I couldn't think of anything except recursion. The code I wrote is given below. But the problem is that the code is time-inefficient and gives TLE (Time Limit Exceeded) for 9 out of 10 test cases! What would be a better approach to the problem? Code - #include<cstdio> #include<climits> #include<algorithm> using namespace std; int n,g[150][2]; int diff(int a,int b,int f) { ++f; if(f==n) { if(a>b) { return a-b; } else { return b-a; } } return min(diff(a+g[f][0],b+g[f][1],f),diff(a+g[f][1],b+g[f][0],f)); } int main() { int i; scanf("%d",&n); for(i=0;i<n;++i) { scanf("%d%d",&g[i][0],&g[i][1]); } printf("%d",diff(g[0][0],g[0][1],0)); } Note - It is just a practice question, & is not part of a competition.

    Read the article

  • javascript complex recurrsion [on hold]

    - by Achilles
    Given Below is my data in data array. What i am doing in code below is that from that given data i have to construct json in a special format which i also gave below. //code start here var hierarchy={}; hierarchy.name="Hierarchy"; hierarchy.children=[{"name":"","children":[{"name":"","children":[]}]}]; var countryindex; var flagExist=false; var data = [ {country :"America", city:"Kansas", employe:'Jacob'}, {country :"Pakistan", city:"Lahore", employe:'tahir'}, {country :"Pakistan", city:"Islamabad", employe:'fakhar'} , {country :"Pakistan", city:"Lahore", employe:'bilal'}, {country :"India", city:"d", employe:'ali'} , {country :"Pakistan", city:"Karachi", employe:'eden'}, {country :"America", city:"Kansas", employe:'Jeen'} , {country :"India", city:"Banglore", employe:'PP'} , {country :"India", city:"Banglore", employe:'JJ'} , ]; for(var i=0;i<data.length;i++) { for(var j=0;j<hierarchy.children.length;j++) { //for checking country match if(hierarchy.children[j].name==data[i].country) { countryindex=j; flagExist=true; break; } } if(flagExist)//country match now no need to add new country just add city in it { var cityindex; var cityflag=false; //hierarchy.children[countryindex].children.push({"name":data[i].city,"children":[]}) //if(hierarchy.children[index].children!=undefined) for(var k=0;k< hierarchy.children[countryindex].children.length;k++) { //for checking city match if(hierarchy.children[countryindex].children[k].name==data[i].city) { // hierarchy.children[countryindex].children[k].children.push({"name":data[i].employe}) cityflag=true; cityindex=k; break; } } if(cityflag)//city match now add just empolye at that city index { hierarchy.children[countryindex].children[cityindex].children.push({"name":data[i].employe}); cityflag=false; } else//no city match so add new with employe also as this is new city so its emplye will be 1st { hierarchy.children[countryindex].children.push({"name":data[i].city,children:[{"name":data[i].employe}]}); //same as above //hierarchy.children[countryindex].children[length-1].children.push({"name":data[i].employe}); } flagExist=false; } else{ //no country match adding new country //with city also as this is new city of new country console.log("sparta"); hierarchy.children.push({"name":data[i].country,"children":[{"name":data[i].city,"children":[{"name":data[i].employe}]}]}); // hierarchy.children.children.push({"name":data[i].city,"children":[]}); } //console.log(hierarchy); } hierarchy.children.shift(); var j=JSON.stringify(hierarchy); //code ends here //here is the json which i seccessfully formed from the code { "name":"Hierarchy", "children":[ { "name":"America", "children":[ { "name":"Kansas", "children":[{"name":"Jacob"},{"name":"Jeen"}]}]}, { "name":"Pakistan", "children":[ { "name":"Lahore", "children": [ {"name":"tahir"},{"name":"bilal"}]}, { "name":"Islamabad", "children":[{"name":"fakhar"}]}, { "name":"Karachi", "children":[{"name":"eden"}]}]}, { "name":"India", "children": [ { "name":"d", "children": [ {"name":"ali"}]}, { "name":"Banglore", "children":[{"name":"PP"},{"name":"JJ"}]}]}]} Now the orignal problem is that currently i am solving this problem for data of array of three keys and i have to go for 3 nested loops now i want to optimize this solution so that if data array of object has more than 3 key say 5 {country :"America", state:"NewYork",city:"newYOrk",street:"elm", employe:'Jacob'}, or more than my solution will not work and i cannot decide before how many keys will come so i thought recursion may suit best here. But i am horrible in writing recurrsion and the case is also complex. Can some awesome programmer help me writing recurrsion or suggest some other solution.

    Read the article

  • Pathfinding results in false path costs that are too high

    - by user2144536
    I'm trying to implement pathfinding in a game I'm programming using this method. I'm implementing it with recursion but some of the values after the immediate circle of tiles around the player are way off. For some reason I cannot find the problem with it. This is a screen cap of the problem: The pathfinding values are displayed in the center of every tile. Clipped blocks are displayed with the value of 'c' because the values were too high and were covering up the next value. The red circle is the first value that is incorrect. The code below is the recursive method. //tileX is the coordinates of the current tile, val is the current pathfinding value, used[][] is a boolean //array to keep track of which tiles' values have already been assigned public void pathFind(int tileX, int tileY, int val, boolean[][] used) { //increment pathfinding value int curVal = val + 1; //set current tile to true if it hasn't been already used[tileX][tileY] = true; //booleans to know which tiles the recursive call needs to be used on boolean topLeftUsed = false, topUsed = false, topRightUsed = false, leftUsed = false, rightUsed = false, botomLeftUsed = false, botomUsed = false, botomRightUsed = false; //set value of top left tile if necessary if(tileX - 1 >= 0 && tileY - 1 >= 0) { //isClipped(int x, int y) returns true if the coordinates givin are in a tile that can't be walked through (IE walls) //occupied[][] is an array that keeps track of which tiles have an enemy in them // //if the tile is not clipped and not occupied set the pathfinding value if(isClipped((tileX - 1) * 50 + 25, (tileY - 1) * 50 + 25) == false && occupied[tileX - 1][tileY - 1] == false && !(used[tileX - 1][tileY - 1])) { pathFindingValues[tileX - 1][tileY - 1] = curVal; topLeftUsed = true; used[tileX - 1][tileY - 1] = true; } //if it is occupied set it to an arbitrary high number so enemies find alternate routes if the best is clogged if(occupied[tileX - 1][tileY - 1] == true) pathFindingValues[tileX - 1][tileY - 1] = 1000000000; //if it is clipped set it to an arbitrary higher number so enemies don't travel through walls if(isClipped((tileX - 1) * 50 + 25, (tileY - 1) * 50 + 25) == true) pathFindingValues[tileX - 1][tileY - 1] = 2000000000; } //top middle if(tileY - 1 >= 0 ) { if(isClipped(tileX * 50 + 25, (tileY - 1) * 50 + 25) == false && occupied[tileX][tileY - 1] == false && !(used[tileX][tileY - 1])) { pathFindingValues[tileX][tileY - 1] = curVal; topUsed = true; used[tileX][tileY - 1] = true; } if(occupied[tileX][tileY - 1] == true) pathFindingValues[tileX][tileY - 1] = 1000000000; if(isClipped(tileX * 50 + 25, (tileY - 1) * 50 + 25) == true) pathFindingValues[tileX][tileY - 1] = 2000000000; } //top right if(tileX + 1 <= used.length && tileY - 1 >= 0) { if(isClipped((tileX + 1) * 50 + 25, (tileY - 1) * 50 + 25) == false && occupied[tileX + 1][tileY - 1] == false && !(used[tileX + 1][tileY - 1])) { pathFindingValues[tileX + 1][tileY - 1] = curVal; topRightUsed = true; used[tileX + 1][tileY - 1] = true; } if(occupied[tileX + 1][tileY - 1] == true) pathFindingValues[tileX + 1][tileY - 1] = 1000000000; if(isClipped((tileX + 1) * 50 + 25, (tileY - 1) * 50 + 25) == true) pathFindingValues[tileX + 1][tileY - 1] = 2000000000; } //left if(tileX - 1 >= 0) { if(isClipped((tileX - 1) * 50 + 25, (tileY) * 50 + 25) == false && occupied[tileX - 1][tileY] == false && !(used[tileX - 1][tileY])) { pathFindingValues[tileX - 1][tileY] = curVal; leftUsed = true; used[tileX - 1][tileY] = true; } if(occupied[tileX - 1][tileY] == true) pathFindingValues[tileX - 1][tileY] = 1000000000; if(isClipped((tileX - 1) * 50 + 25, (tileY) * 50 + 25) == true) pathFindingValues[tileX - 1][tileY] = 2000000000; } //right if(tileX + 1 <= used.length) { if(isClipped((tileX + 1) * 50 + 25, (tileY) * 50 + 25) == false && occupied[tileX + 1][tileY] == false && !(used[tileX + 1][tileY])) { pathFindingValues[tileX + 1][tileY] = curVal; rightUsed = true; used[tileX + 1][tileY] = true; } if(occupied[tileX + 1][tileY] == true) pathFindingValues[tileX + 1][tileY] = 1000000000; if(isClipped((tileX + 1) * 50 + 25, (tileY) * 50 + 25) == true) pathFindingValues[tileX + 1][tileY] = 2000000000; } //botom left if(tileX - 1 >= 0 && tileY + 1 <= used[0].length) { if(isClipped((tileX - 1) * 50 + 25, (tileY + 1) * 50 + 25) == false && occupied[tileX - 1][tileY + 1] == false && !(used[tileX - 1][tileY + 1])) { pathFindingValues[tileX - 1][tileY + 1] = curVal; botomLeftUsed = true; used[tileX - 1][tileY + 1] = true; } if(occupied[tileX - 1][tileY + 1] == true) pathFindingValues[tileX - 1][tileY + 1] = 1000000000; if(isClipped((tileX - 1) * 50 + 25, (tileY + 1) * 50 + 25) == true) pathFindingValues[tileX - 1][tileY + 1] = 2000000000; } //botom middle if(tileY + 1 <= used[0].length) { if(isClipped((tileX) * 50 + 25, (tileY + 1) * 50 + 25) == false && occupied[tileX][tileY + 1] == false && !(used[tileX][tileY + 1])) { pathFindingValues[tileX][tileY + 1] = curVal; botomUsed = true; used[tileX][tileY + 1] = true; } if(occupied[tileX][tileY + 1] == true) pathFindingValues[tileX][tileY + 1] = 1000000000; if(isClipped((tileX) * 50 + 25, (tileY + 1) * 50 + 25) == true) pathFindingValues[tileX][tileY + 1] = 2000000000; } //botom right if(tileX + 1 <= used.length && tileY + 1 <= used[0].length) { if(isClipped((tileX + 1) * 50 + 25, (tileY + 1) * 50 + 25) == false && occupied[tileX + 1][tileY + 1] == false && !(used[tileX + 1][tileY + 1])) { pathFindingValues[tileX + 1][tileY + 1] = curVal; botomRightUsed = true; used[tileX + 1][tileY + 1] = true; } if(occupied[tileX + 1][tileY + 1] == true) pathFindingValues[tileX + 1][tileY + 1] = 1000000000; if(isClipped((tileX + 1) * 50 + 25, (tileY + 1) * 50 + 25) == true) pathFindingValues[tileX + 1][tileY + 1] = 2000000000; } //call the method on the tiles that need it if(tileX - 1 >= 0 && tileY - 1 >= 0 && topLeftUsed) pathFind(tileX - 1, tileY - 1, curVal, used); if(tileY - 1 >= 0 && topUsed) pathFind(tileX , tileY - 1, curVal, used); if(tileX + 1 <= used.length && tileY - 1 >= 0 && topRightUsed) pathFind(tileX + 1, tileY - 1, curVal, used); if(tileX - 1 >= 0 && leftUsed) pathFind(tileX - 1, tileY, curVal, used); if(tileX + 1 <= used.length && rightUsed) pathFind(tileX + 1, tileY, curVal, used); if(tileX - 1 >= 0 && tileY + 1 <= used[0].length && botomLeftUsed) pathFind(tileX - 1, tileY + 1, curVal, used); if(tileY + 1 <= used[0].length && botomUsed) pathFind(tileX, tileY + 1, curVal, used); if(tileX + 1 <= used.length && tileY + 1 <= used[0].length && botomRightUsed) pathFind(tileX + 1, tileY + 1, curVal, used); }

    Read the article

  • Having trouble with pathfinding

    - by user2144536
    I'm trying to implement pathfinding in a game I'm programming using this method. I'm implementing it with recursion but some of the values after the immediate circle of tiles around the player are way off. For some reason I cannot find the problem with it. This is a screen cap of the problem: The pathfinding values are displayed in the center of every tile. Clipped blocks are displayed with the value of 'c' because the values were too high and were covering up the next value. The red circle is the first value that is incorrect. The code below is the recursive method. //tileX is the coordinates of the current tile, val is the current pathfinding value, used[][] is a boolean //array to keep track of which tiles' values have already been assigned public void pathFind(int tileX, int tileY, int val, boolean[][] used) { //increment pathfinding value int curVal = val + 1; //set current tile to true if it hasn't been already used[tileX][tileY] = true; //booleans to know which tiles the recursive call needs to be used on boolean topLeftUsed = false, topUsed = false, topRightUsed = false, leftUsed = false, rightUsed = false, botomLeftUsed = false, botomUsed = false, botomRightUsed = false; //set value of top left tile if necessary if(tileX - 1 >= 0 && tileY - 1 >= 0) { //isClipped(int x, int y) returns true if the coordinates givin are in a tile that can't be walked through (IE walls) //occupied[][] is an array that keeps track of which tiles have an enemy in them // //if the tile is not clipped and not occupied set the pathfinding value if(isClipped((tileX - 1) * 50 + 25, (tileY - 1) * 50 + 25) == false && occupied[tileX - 1][tileY - 1] == false && !(used[tileX - 1][tileY - 1])) { pathFindingValues[tileX - 1][tileY - 1] = curVal; topLeftUsed = true; used[tileX - 1][tileY - 1] = true; } //if it is occupied set it to an arbitrary high number so enemies find alternate routes if the best is clogged if(occupied[tileX - 1][tileY - 1] == true) pathFindingValues[tileX - 1][tileY - 1] = 1000000000; //if it is clipped set it to an arbitrary higher number so enemies don't travel through walls if(isClipped((tileX - 1) * 50 + 25, (tileY - 1) * 50 + 25) == true) pathFindingValues[tileX - 1][tileY - 1] = 2000000000; } //top middle if(tileY - 1 >= 0 ) { if(isClipped(tileX * 50 + 25, (tileY - 1) * 50 + 25) == false && occupied[tileX][tileY - 1] == false && !(used[tileX][tileY - 1])) { pathFindingValues[tileX][tileY - 1] = curVal; topUsed = true; used[tileX][tileY - 1] = true; } if(occupied[tileX][tileY - 1] == true) pathFindingValues[tileX][tileY - 1] = 1000000000; if(isClipped(tileX * 50 + 25, (tileY - 1) * 50 + 25) == true) pathFindingValues[tileX][tileY - 1] = 2000000000; } //top right if(tileX + 1 <= used.length && tileY - 1 >= 0) { if(isClipped((tileX + 1) * 50 + 25, (tileY - 1) * 50 + 25) == false && occupied[tileX + 1][tileY - 1] == false && !(used[tileX + 1][tileY - 1])) { pathFindingValues[tileX + 1][tileY - 1] = curVal; topRightUsed = true; used[tileX + 1][tileY - 1] = true; } if(occupied[tileX + 1][tileY - 1] == true) pathFindingValues[tileX + 1][tileY - 1] = 1000000000; if(isClipped((tileX + 1) * 50 + 25, (tileY - 1) * 50 + 25) == true) pathFindingValues[tileX + 1][tileY - 1] = 2000000000; } //left if(tileX - 1 >= 0) { if(isClipped((tileX - 1) * 50 + 25, (tileY) * 50 + 25) == false && occupied[tileX - 1][tileY] == false && !(used[tileX - 1][tileY])) { pathFindingValues[tileX - 1][tileY] = curVal; leftUsed = true; used[tileX - 1][tileY] = true; } if(occupied[tileX - 1][tileY] == true) pathFindingValues[tileX - 1][tileY] = 1000000000; if(isClipped((tileX - 1) * 50 + 25, (tileY) * 50 + 25) == true) pathFindingValues[tileX - 1][tileY] = 2000000000; } //right if(tileX + 1 <= used.length) { if(isClipped((tileX + 1) * 50 + 25, (tileY) * 50 + 25) == false && occupied[tileX + 1][tileY] == false && !(used[tileX + 1][tileY])) { pathFindingValues[tileX + 1][tileY] = curVal; rightUsed = true; used[tileX + 1][tileY] = true; } if(occupied[tileX + 1][tileY] == true) pathFindingValues[tileX + 1][tileY] = 1000000000; if(isClipped((tileX + 1) * 50 + 25, (tileY) * 50 + 25) == true) pathFindingValues[tileX + 1][tileY] = 2000000000; } //botom left if(tileX - 1 >= 0 && tileY + 1 <= used[0].length) { if(isClipped((tileX - 1) * 50 + 25, (tileY + 1) * 50 + 25) == false && occupied[tileX - 1][tileY + 1] == false && !(used[tileX - 1][tileY + 1])) { pathFindingValues[tileX - 1][tileY + 1] = curVal; botomLeftUsed = true; used[tileX - 1][tileY + 1] = true; } if(occupied[tileX - 1][tileY + 1] == true) pathFindingValues[tileX - 1][tileY + 1] = 1000000000; if(isClipped((tileX - 1) * 50 + 25, (tileY + 1) * 50 + 25) == true) pathFindingValues[tileX - 1][tileY + 1] = 2000000000; } //botom middle if(tileY + 1 <= used[0].length) { if(isClipped((tileX) * 50 + 25, (tileY + 1) * 50 + 25) == false && occupied[tileX][tileY + 1] == false && !(used[tileX][tileY + 1])) { pathFindingValues[tileX][tileY + 1] = curVal; botomUsed = true; used[tileX][tileY + 1] = true; } if(occupied[tileX][tileY + 1] == true) pathFindingValues[tileX][tileY + 1] = 1000000000; if(isClipped((tileX) * 50 + 25, (tileY + 1) * 50 + 25) == true) pathFindingValues[tileX][tileY + 1] = 2000000000; } //botom right if(tileX + 1 <= used.length && tileY + 1 <= used[0].length) { if(isClipped((tileX + 1) * 50 + 25, (tileY + 1) * 50 + 25) == false && occupied[tileX + 1][tileY + 1] == false && !(used[tileX + 1][tileY + 1])) { pathFindingValues[tileX + 1][tileY + 1] = curVal; botomRightUsed = true; used[tileX + 1][tileY + 1] = true; } if(occupied[tileX + 1][tileY + 1] == true) pathFindingValues[tileX + 1][tileY + 1] = 1000000000; if(isClipped((tileX + 1) * 50 + 25, (tileY + 1) * 50 + 25) == true) pathFindingValues[tileX + 1][tileY + 1] = 2000000000; } //call the method on the tiles that need it if(tileX - 1 >= 0 && tileY - 1 >= 0 && topLeftUsed) pathFind(tileX - 1, tileY - 1, curVal, used); if(tileY - 1 >= 0 && topUsed) pathFind(tileX , tileY - 1, curVal, used); if(tileX + 1 <= used.length && tileY - 1 >= 0 && topRightUsed) pathFind(tileX + 1, tileY - 1, curVal, used); if(tileX - 1 >= 0 && leftUsed) pathFind(tileX - 1, tileY, curVal, used); if(tileX + 1 <= used.length && rightUsed) pathFind(tileX + 1, tileY, curVal, used); if(tileX - 1 >= 0 && tileY + 1 <= used[0].length && botomLeftUsed) pathFind(tileX - 1, tileY + 1, curVal, used); if(tileY + 1 <= used[0].length && botomUsed) pathFind(tileX, tileY + 1, curVal, used); if(tileX + 1 <= used.length && tileY + 1 <= used[0].length && botomRightUsed) pathFind(tileX + 1, tileY + 1, curVal, used); }

    Read the article

  • Change a Recursive function that has a for loop in it into an iterative function?

    - by Bill
    So I have this function that I'm trying to convert from a recursive algorithm to an iterative algorithm. I'm not even sure if I have the right subproblems but this seems to determined what I need in the correct way, but recursion can't be used you need to use dynamic programming so I need to change it to iterative bottom up or top down dynamic programming. The basic recursive function looks like this: Recursion(i,j) { if(i>j) return 0; else { //This finds the maximum value for all possible subproblems and returns that for this problem for(int x = i; x < j; x++) { if(some subsection i to x plus recursion(x+1,j) is > current max) max = some subsection i to x plus recursion(x+1,j) } } } This is the general idea, but since recursions typically don't have for loops in them I'm not sure exactly how I would convert this to iterative. Does anyone have any ideas?

    Read the article

  • Python: Pickling highly-recursive objects without using `setrecursionlimit`

    - by cool-RR
    I've been getting RuntimeError: maximum recursion depth exceeded when trying to pickle a highly-recursive tree object. Much like this asker here. He solved his problem by setting the recursion limit higher with sys.setrecursionlimit. But I don't want to do that: I think that's more of a workaround than a solution. Because I want to be able to pickle my trees even if they have 10,000 nodes in them. (It currently fails at around 200.) (Also, every platform's true recursion limit is different, and I would really like to avoid opening this can of worms.) Is there any way to solve this at the fundamental level? If only the pickle module would pickle using a loop instead of recursion, I wouldn't have had this problem. Maybe someone has an idea how I can cause something like this to happen, without rewriting the pickle module? Any other idea how I can solve this problem will be appreciated.

    Read the article

  • Deep recursion in WHM EasyApache software update causes out of memory

    - by Ernest
    I was trying to load some modules with EasyApache in a software update (WHM) cause I need to install Magento ecommerce. I did the first EasyApache update. However, one module I needed was not loaded. I loaded later but whenever I check Tomcat 5.5 in the profile builder I get: -- Begin opt 'Tomcat' -- -- Begin dryrun test 'Checking for v5' -- -- End dryrun test 'Checking for v5' -- -- Begin step 'Checking jdk' -- Deep recursion on subroutine "Cpanel::CPAN::Digest::MD5::File::_dir" at /usr/local/cpanel/Cpanel/CPAN/Digest/MD5/File.pm line 107. Out of memory! Out of memory! *** glibc detected *** realloc(): invalid next size: 0x09741188 *** Line 107 in question in the file.pm is the third one in this snippet: if(-d $full) { $hr->{ $short } = ''; _dir($full, $hr, $base, $type, $cc) or return; //line 107 } All my client sites are down and I don't know what to do to fix this.

    Read the article

  • Implement Negascout Algorithm with stack

    - by Dan
    I'm not familiar with how these stack exchange accounts work so if this is double posting I apologize. I asked the same thing on stackoverflow. I have added an AI routine to a game I am working on using the Negascout algorithm. It works great, but when I set a higher maximum depth it can take a few seconds to complete. The problem is it blocks the main thread, and the framework I am using does not have a way to deal with multi-threading properly across platforms. So I am trying to change this routine from recursively calling itself, to just managing a stack (vector) so that I can progress through the routine at a controlled pace and not lock up the application while the AI is thinking. I am getting hung up on the second recursive call in the loop. It relies on a returned value from the first call, so I don't know how to add these to a stack. My Working c++ Recursive Code: MoveScore abNegascout(vector<vector<char> > &board, int ply, int alpha, int beta, char piece) { if (ply==mMaxPly) { return MoveScore(evaluation.evaluateBoard(board, piece, oppPiece)); } int currentScore; int bestScore = -INFINITY; MoveCoord bestMove; int adaptiveBeta = beta; vector<MoveCoord> moveList = evaluation.genPriorityMoves(board, piece, findValidMove(board, piece, false)); if (moveList.empty()) { return MoveScore(bestScore); } bestMove = moveList[0]; for(int i=0;i<moveList.size();i++) { MoveCoord move = moveList[i]; vector<vector<char> > newBoard; newBoard.insert( newBoard.end(), board.begin(), board.end() ); effectMove(newBoard, piece, move.getRow(), move.getCol()); // First Call ****** MoveScore current = abNegascout(newBoard, ply+1, -adaptiveBeta, -max(alpha,bestScore), oppPiece); currentScore = - current.getScore(); if (currentScore>bestScore){ if (adaptiveBeta == beta || ply>=(mMaxPly-2)){ bestScore = currentScore; bestMove = move; }else { // Second Call ****** current = abNegascout(newBoard, ply+1, -beta, -currentScore, oppPiece); bestScore = - current.getScore(); bestMove = move; } if(bestScore>=beta){ return MoveScore(bestMove,bestScore); } adaptiveBeta = max(alpha, bestScore) + 1; } } return MoveScore(bestMove,bestScore); } If someone can please help by explaining how to get this to work with a simple stack. Example code would be much appreciated. While c++ would be perfect, any language that demonstrates how would be great. Thank You.

    Read the article

  • When there's no TCO, when to worry about blowing the stack?

    - by Cedric Martin
    Every single time there's a discussion about a new programming language targetting the JVM, there are inevitably people saying things like: "The JVM doesn't support tail-call optimization, so I predict lots of exploding stacks" There are thousands of variations on that theme. Now I know that some language, like Clojure for example, have a special recur construct that you can use. What I don't understand is: how serious is the lack of tail-call optimization? When should I worry about it? My main source of confusion probably comes from the fact that Java is one of the most succesful languages ever and quite a few of the JVM languages seems to be doing fairly well. How is that possible if the lack of TCO is really of any concern?

    Read the article

  • Stack Overflow Error

    - by dylanisawesome1
    I recently created a recursive cave algorithm, and would like to have more extensive caves, but get a stack overflow after re-cursing a couple times. Any advice? Here's my code: for(int i=0;i<100;i++) { int rand = new Random().nextInt(100); if(rand<=20) { if(curtile.bounds.y-40>500+new Random().nextInt(20)) digDirection(Direction.UP); } if(rand<=40 && rand>20) { if(curtile.bounds.y+40<m.height) digDirection(Direction.DOWN); } if(rand<=60 && rand>40) { if(curtile.bounds.x-40>0) digDirection(Direction.LEFT); } if(rand<=80 && rand>60) { if(curtile.bounds.x+40<m.width) digDirection(Direction.RIGHT); } } } public void digDirection(Direction d) { if(new Random().nextInt(100)<=10) { new Miner(curtile, map); // try { // Thread.sleep(2); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } //Tried this to avoid stack overflow. Didn't work. }

    Read the article

  • Can a recursive function have iterations/loops?

    - by Omega
    I've been studying about recursive functions, and apparently, they're functions that call themselves, and don't use iterations/loops (otherwise it wouldn't be a recursive function). However, while surfing the web for examples (the 8-queens-recursive problem), I found this function: private boolean placeQueen(int rows, int queens, int n) { boolean result = false; if (row < n) { while ((queens[row] < n - 1) && !result) { queens[row]++; if (verify(row,queens,n)) { ok = placeQueen(row + 1,queens,n); } } if (!result) { queens[row] = -1; } }else{ result = true; } return result; } There is a while loop involved. ... so I'm a bit lost now. Can I use loops or not?

    Read the article

  • Is this the right strategy to convert an in-level order binary tree to a doubly linked list?

    - by Ankit Soni
    So I recently came across this question - Make a function that converts a in-level-order binary tree into a doubly linked list. Apparently, it's a common interview question. This is the strategy I had - Simply do a pre-order traversal of the tree, and instead of returning a node, return a list of nodes, in the order in which you traverse them. i.e return a list, and append the current node to the list at each point. For the base case, return the node itself when you are at a leaf. so you would say left = recursive_function(node.left) right = recursive_function(node.right) return(left.append(node.data)).append(right);` Is this the right approach?

    Read the article

  • Searching for a key in a multi dimensional array and adding it to another array [migrated]

    - by Moha
    Let's say I have two multi dimensional arrays: array1 ( stuff1 = array ( data = 'abc' ) stuff2 = array ( something = '123' data = 'def' ) stuff3 = array ( stuff4 = array ( data = 'ghi' ) ) ) array2 ( stuff1 = array ( ) stuff3 = array ( anything = '456' ) ) What I want is to search the key 'data' in array1 and then insert the key and value to array2 regardless of the depth. So wherever key 'data' exists in array1 it gets added to array2 with the exact depth (and key names) as in array1 AND without modifying any other keys. How can I do this recursively?

    Read the article

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