Search Results

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

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

  • C: sprintf and recursion

    - by Shinka
    In C, is it possible to use recursion within the sprintf function ? For some reason I get a segmentation fault when I do it: inline char *TreeNode_toString(const TreeNode *node) { char *out; if(TreeNode_isExternal(node)) // If the node has no children... { sprintf(out, "%s:%.2f", node->name, node->distance); } else // The node is strictly binary, so it will have two non-null children { char *l = TreeNode_toString(node->l); // l = left child char *r = TreeNode_toString(node->r); // r = right child sprintf(out, "(%s,%s):%.2f", l, r, node->distance); } return out; }

    Read the article

  • too much recursion

    - by Dänu
    Hey guys, I got an error in javascript and it won't get away. :-) In the little recursive thingy following, I want to replace a value inside a (nested) object. var testobj = { 'user': { 'name': 'Mario', 'password': 'itseme' } }; updateObject('emesti', 'password', testobj) function updateObject(_value, _property, _object) { for(var property in _object) { if(property == _property) { _object[property] = _value; } else if(objectSize(_object) > 0) { updateObject(_value, _property, _object[property]); } } return _object }; function objectSize(_object) { var size = 0, key; for (key in _object) { if (_object.hasOwnProperty(key)) size++; } return size; }; After running this, firefox throws the exception "too much recursion" on the line else if(objectSize(_object) > 0) { .

    Read the article

  • Recursion with Func

    - by David in Dakota
    Is it possible to do recursion with an Func delegate? I have the following, which doesn't compile because the name of the Func isn't in scope... Func<long, long, List<long>, IEnumerable<long>> GeneratePrimesRecursively = (number, upperBound, primeFactors) => { if (upperBound > number) { return new List<long>(); } else { if (!primeFactors.Any(factor => number % factor == 0)) primeFactors.Add(number); return GeneratePrimesRecursively(++number, upperBound, primeFactors); // breaks here. } };

    Read the article

  • Find 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

  • Jquery Too Much Recursion Error

    - by user367082
    Hi There. I hope someone could help me. I have this code: <script> $(document).ready(function() { spectrum(); function spectrum(){ $('#bottom-menu ul li.colored a').animate( { color: '#E7294F' }, 16000); spectrum2(); } function spectrum2(){ $('#bottom-menu ul li.colored a').animate( { color: '#3D423C' }, 16000); spectrum(); } }); </script> it's working but when I look at firebug it says that there's a Too Much Recursion error. I hope someone can tell me why. Thanks!

    Read the article

  • Counting vowels in a string using recursion

    - by Daniel Love Jr
    In my python class we are learning about recursion. I understand that it's when a function calls itself, however for this particular assignment I can't figure out how exactly to get my function to call it self to get the desired results. I need to simply count the vowels in the string given to the function. def recVowelCount(s): 'return the number of vowels in s using a recursive computation' vowelcount = 0 vowels = "aEiou".lower() if s[0] in vowels: vowelcount += 1 else: ??? I'm really not sure where to go with this, it's quite frustrating. I came up with this in the end, thanks to some insight from here. def recVowelCount(s): 'return the number of vowels in s using a recursive computation' vowels = "aeiouAEIOU" if s == "": return 0 elif s[0] in vowels: return 1 + recVowelCount(s[1:]) else: return 0 + recVowelCount(s[1:])

    Read the article

  • Recursion function not working properly

    - by jakecar
    I'm having quite a hard time figuring out what's going wrong here: class iterate(): def init(self): self.length=1 def iterated(self, n): if n==1: return self.length elif n%2==0: self.length+=1 self.iterated(n/2) elif n!=1: self.length+=1 self.iterated(3*n+1) For example, x=iterate() x.iterated(5) outputs None. It should output 6 because the length would look like this: 5 -- 16 -- 8 -- 4 -- 2 -- 1 After doing some debugging, I see that the self.length is returned properly but something goes wrong in the recursion. I'm not really sure. Thanks for any help.

    Read the article

  • How to avoid recursion in Java SecurityManager checkConnect?

    - by Zilupe
    I'm trying to take control of a Java code base that does lots of un-documented things. I'm using a custom SecurityManager to check permission requests. Specifically, my code is checking SocketPermission checks -- checkConnect. checkConnect is called when the application tries to resolve a host name to IP address and to connect to a specific IP address. The problem is that I don't know how to properly call host name resolution (InetAddress.getAddressByName) without falling into infinite recursion, because normally checkConnect is called even when I resolve the name from inside the SecurityManager.checkConnect. I have read on the web that I have to call the address resolution from a doPrivileged block, but no idea how. P.S. Is this possible without writing any policy files?

    Read the article

  • Java-Recursion: When does statements after a recursive method call executes

    - by Ruru Morlano
    When are statements after the method call itself going to execute? private void inorderHelper(TreeNode node) { if ( node==null ) return; inorderHelper(node.leftNode); System.out.printf("%d", node.data); inorderHelper(node.rigthNode); } All I can see is that the line of codes inorderHelper(node.leftNode) will continue to iterate until node == null and the method terminates immediately before node.data is printed. I think that I didn't get well recursion but all examples I can find doesn't have statements after the recursive call. All I want to know is when are statements like System.out.printf("%d",node.data) going to execute before the method return?

    Read the article

  • How does the recursion here work?

    - by David
    code 1: public static int fibonacci (int n){ if (n == 0 || n == 1) { return 1; } else { return fibonacci (n-1) + fibonacci (n-2); } } how can you use fibonacci if you haven't gotten done explaining what it is yet? I've been able to understand using recursion in other cases like this: code two: class two { public static void two (int n) { if (n>0) { System.out.println (n) ; two (n-1) ; } else { return ; } } public static void main (String[] arg) { two (12) ; } } In the case of code 2 though n will eventualy reach a point at which it doesnt satisfy n0 and the method will stop calling itself recursivly. in the case of code 2 though i don't see how it would be able to get itself from 1 if n=1 was the starting point to 2 and 3 and 5 and so on. Also i don't see how the line `return fibonacci (n-1) + fibonacci (n-2) would work since fibbonacci n-2 has to contain in some sense fibonacci n-1 in order to wrok but it isn't there yet. I know my question is worded poorly but looking at this is making my mind explode. the book i'm looking at says it will work. how does it work? `

    Read the article

  • java recursion on array

    - by user69514
    I have to create a program that finds all the possible ways of filling a board of size 3xN You place a domino which takes up 2 spaces to completely fill the board. So far, this is my thought process on how it should be done based on what the teacher has said as well as my own thoughts. Get input and check if its even or odd If it's odd, the board can't be filled all the way and the program ends If it's even, place a domino horizontally in the top right corner of the board Test if you can place a domino vertically in that spot. Repeat those two steps as many times as possible. The problem is I don't know how to code it to the point where you can remember the placements of each domino. I can get it to where it fills the board completely once and maybe twice, but nothing past that. I also know that I'm supposed to use recursion to figure this out fwiw. Here is the code I started on so far. There is also a main method and I have the initial even/odd check working fine. This is the part I have no idea on. public void recurDomino(int row, int column) { if (Board[2][x - 1] != false) { } else if(Board[1][x-1]!=false) { } else { for (int n=0; n < x - 1; n++) { Board[row][column] = true; Board[row][column+1] = true; column++; counter++; } recurDomino(1, 0); recurDomino(2, 0); } } Thank you for any help you guys can give me.

    Read the article

  • Reordering arguments using recursion (pro, cons, alternatives)

    - by polygenelubricants
    I find that I often make a recursive call just to reorder arguments. For example, here's my solution for endOther from codingbat.com: Given two strings, return true if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive"). Note: str.toLowerCase() returns the lowercase version of a string. public boolean endOther(String a, String b) { return a.length() < b.length() ? endOther(b, a) : a.toLowerCase().endsWith(b.toLowerCase()); } I'm very comfortable with recursions, but I can certainly understand why some perhaps would object to it. There are two obvious alternatives to this recursion technique: Swap a and b traditionally public boolean endOther(String a, String b) { if (a.length() < b.length()) { String t = a; a = b; b = t; } return a.toLowerCase().endsWith(b.toLowerCase()); } Not convenient in a language like Java that doesn't pass by reference Lots of code just to do a simple operation An extra if statement breaks the "flow" Repeat code public boolean endOther(String a, String b) { return (a.length() < b.length()) ? b.toLowerCase().endsWith(a.toLowerCase()) : a.toLowerCase().endsWith(b.toLowerCase()); } Explicit symmetry may be a nice thing (or not?) Bad idea unless the repeated code is very simple ...though in this case you can get rid of the ternary and just || the two expressions So my questions are: Is there a name for these 3 techniques? (Are there more?) Is there a name for what they achieve? (e.g. "parameter normalization", perhaps?) Are there official recommendations on which technique to use (when)? What are other pros/cons that I may have missed?

    Read the article

  • Project Euler (P14): recursion problems

    - by sean mcdaid
    Hi I'm doing the Collatz sequence problem in project Euler (problem 14). My code works with numbers below 100000 but with numbers bigger I get stack over-flow error. Is there a way I can re-factor the code to use tail recursion, or prevent the stack overflow. The code is below: import java.util.*; public class v4 { // use a HashMap to store computed number, and chain size static HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); public static void main(String[] args) { hm.put(1, 1); final int CEILING_MAX=Integer.parseInt(args[0]); int len=1; int max_count=1; int max_seed=1; for(int i=2; i<CEILING_MAX; i++) { len = seqCount(i); if(len > max_count) { max_count = len; max_seed = i; } } System.out.println(max_seed+"\t"+max_count); } // find the size of the hailstone sequence for N public static int seqCount(int n) { if(hm.get(n) != null) { return hm.get(n); } if(n ==1) { return 1; } else { int length = 1 + seqCount(nextSeq(n)); hm.put(n, length); return length; } } // Find the next element in the sequence public static int nextSeq(int n) { if(n%2 == 0) { return n/2; } else { return n*3+1; } } }

    Read the article

  • Java anagram recursion List<List<String>> only storing empty lists<Strings>

    - by Riff Rafffer
    Hi In this recursion method i am trying to find all anagrams and add it to a List but what happens when i run this code is it just returns alot of empty Lists. private List<List<String>> findAnagrams(LetterInventory words, ArrayList<String> anagram, int max, Map<String, LetterInventory> smallDict, int level, List<List<String>> result) { ArrayList<String> solvedWord = new ArrayList<String>(); LetterInventory shell; LetterInventory shell2; if (level < max || max == 0) { Iterator<String> it = smallDict.keySet().iterator(); while (it.hasNext()) { String k = it.next(); shell = new LetterInventory(k); shell2 = words; if (shell2.subtract(shell) != null) { anagram.add(k); shell2 = words.subtract(shell); if (shell2.isEmpty()) { //System.out.println(anagram.toString()); it prints off fine here result.add(anagram); // but doesnt add here } else findAnagrams(shell2, anagram, max, smallDict, level + 1, result); anagram.remove(anagram.size()-1); } } } return results; }

    Read the article

  • Array Recursion

    - by GeeYouAreYou
    I've got an assignment I can't figure out, any pointers will be much appreciated, it goes like so: There's a series of light bulbs represented as an array of true/false, there's a switch for every light bulb, by clicking it for any light bulb, you toggle it as well as 2 adjacent ones (1 from left & another 1 from right; if clicked switch's bulb on edge -- only 1 adjacent toggled of course). What is needed to accomplish is a method that accepts an array of a series of turned on/off light bulbs and another one representing another state of supposedly the 1st array after some switches have been clicked..! So recursion must be used to find out whether there's a combination of switch clicks that will transform array 1 to array 2. Here's the signature of the method: public static boolean disco(boolean[] init, boolean[] target) Will return true if array init can be transformed to target, false otherwise. Method must be static and not use any other static and global variables, only local. Example: boolean[] init = {true, false, true, false, true, false}; boolean[] target = {false, true, false, true, false, true}; For above 2 arrays, disco(init, target) will return true because toggling the 1st and 4th bulbs would yield the target state (remember adjacent bulbs being toggled as well). Any help much appreciated..!!

    Read the article

  • Resolve php endless recursion issue

    - by Matt
    Hey all, I'm currently running into an endless recursion situation. I'm implementing a message service that calls various object methods.. it's quite similar to observer pattern.. Here's whats going on: Dispatcher.php class Dispatcher { ... public function message($name, $method) { // Find the object based on the name $object = $this->findObjectByName($name); // Slight psuedocode.. for ease of example if($this->not_initialized($object)) $object = new $object(); // This is where it locks up. } return $object->$method(); ... } class A { function __construct() { $Dispatcher->message("B", "getName"); } public function getName() { return "Class A"; } } class B { function __construct() { // Assume $Dispatcher is the classes $Dispatcher->message("A", "getName"); } public function getName() { return "Class B"; } } It locks up when neither object is initialized. It just goes back and forth from message each other and no one can be initialized. I'm looking for some kind of queue implementation that will make messages wait for each other.. One where the return values still get set. I'm looking to have as little boilerplate code in class A and class B as possible Any help would be immensely helpful.. Thanks! Matt Mueller

    Read the article

  • SQL query recursion for a web-like structure

    - by MickeyD
    I have a table here, named "Foo". The data is set up something like this. ID TableReference DataId0 DataId1 DataId2 -- -------------- ------- ------- ------- 1 Prize 3 4 5 2 Prize 4 5 NULL 3 Cash 1 NULL NULL 4 Prize 8 NULL 12 5 Foo 2 3 NULL 6 Cash 8 1 10 7 Foo 5 1 2 Etc. The data is horribly set up, I know, but I didn't set it up that way. :) I'm only dealing with the after effect. I'm trying to come up with a way to essentially "flatten" the table; that is, to display all the data to a point where the table "Foo" does not reference itself. I'm trying to figure out a sql query that I can do to get there. Usually when I deal with recursion, I have (or can establish) parent IDs and set it up that way, but for this table there are seemingly multiple child and parent IDs creating a web-like structure instead of a hierarchy. So I'm at a loss where to even begin to write a sql query for something like this. Note: There is no infinite looping (where one Foo points to another Foo, which points back to the original Foo) from what I've found. Using t-sql. Thanks for any assistance, if at all possible.

    Read the article

  • Tail recursion and memoization with C#

    - by Jay
    I'm writing a function that finds the full path of a directory based on a database table of entries. Each record contains a key, the directory's name, and the key of the parent directory (it's the Directory table in an MSI if you're familiar). I had an iterative solution, but it started looking a little nasty. I thought I could write an elegant tail recursive solution, but I'm not sure anymore. I'll show you my code and then explain the issues I'm facing. Dictionary<string, string> m_directoryKeyToFullPathDictionary = new Dictionary<string, string>(); ... private string ExpandDirectoryKey(Database database, string directoryKey) { // check for terminating condition string fullPath; if (m_directoryKeyToFullPathDictionary.TryGetValue(directoryKey, out fullPath)) { return fullPath; } // inductive step Record record = ExecuteQuery(database, "SELECT DefaultDir, Directory_Parent FROM Directory where Directory.Directory='{0}'", directoryKey); // null check string directoryName = record.GetString("DefaultDir"); string parentDirectoryKey = record.GetString("Directory_Parent"); return Path.Combine(ExpandDirectoryKey(database, parentDirectoryKey), directoryName); } This is how the code looked when I realized I had a problem (with some minor validation/massaging removed). I want to use memoization to short circuit whenever possible, but that requires me to make a function call to the dictionary to store the output of the recursive ExpandDirectoryKey call. I realize that I also have a Path.Combine call there, but I think that can be circumvented with a ... + Path.DirectorySeparatorChar + .... I thought about using a helper method that would memoize the directory and return the value so that I could call it like this at the end of the function above: return MemoizeHelper( m_directoryKeyToFullPathDictionary, Path.Combine(ExpandDirectoryKey(database, parentDirectoryKey)), directoryName); But I feel like that's cheating and not going to be optimized as tail recursion. Any ideas? Should I be using a completely different strategy? This doesn't need to be a super efficient algorithm at all, I'm just really curious. I'm using .NET 4.0, btw. Thanks!

    Read the article

  • prolog recursion

    - by AhmadAssaf
    am making a function that will send me a list of all possible elemnts .. in each iteration its giving me the last answer .. but after the recursion am only getting the last answer back .. how can i make it give back every single answer .. thank you the problem is that am trying to find all possible distributions for a list into other lists .. the code test :- bp(3,12,[7, 3, 5, 4, 6, 4, 5, 2], Answer), format("Answer = ~w\n",[Answer]). bp(NB,C,OL,A):- addIn(C,OL,[[],[],[]],A); bp(NB,C,_,A). addIn(_,[],Result,Result). addIn(C,[Element|Rest],[F|R],Result):- member( Members , [F|R]), sumlist( Members, Sum), sumlist([Element],ElementLength), Cap is Sum + ElementLength, (Cap =< C, append([Element], Members,New), insert( Members, New, [F|R], PartialResult), addIn(C,Rest,PartialResult,Result)). by calling test .. am getting back all the list of possible answers .. now if i tried to do something that will fail like bp(3,11,[8,2,4,6,1,8,4],Answer). it will just enter a while loop .. more over if i changed the bp(NB,C,OL,A):- addIn(C,OL,[[],[],[]],A); bp(NB,C,_,A). to and instead of Or .. i get error : ERROR: is/2: Arguments are not sufficiently instantiated appreciate the help .. Thanks alot @hardmath

    Read the article

  • Finding duplicates in a list using recursion?

    - by user1760892
    I'm suppose to find if there is duplicates in a list and return true or false using recursion only (no loops). So if ArrayList of char is used, [a,b,c,d,e] should return false. [a,a,b,c,d] or [a,b,b,c,c,d] should return true. I've tried and tested different ways and it worked for some cases but not all. I changed my code around and this is what I have now. (Has problem at the last if statement) Can anyone give me some hints? Thanks. public static <T> boolean duplicate(List<T> list) throws NullPointerException { return duplicateHelper(list, list.get(0)); } public static <T> boolean duplicateHelper(List<T> list, T t){ if (list == null) throw new NullPointerException(); if(list.isEmpty()) return false; if(list.size() > 1){ if(t.equals(list.get(1))) return true; } if(list.size() == 1) return false; if(!duplicateHelper(list.subList(1,list.size()), t)){ return duplicate(list.subList(1,list.size())); } return false; }

    Read the article

  • 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 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

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