Search Results

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

Page 20/63 | < Previous Page | 16 17 18 19 20 21 22 23 24 25 26 27  | Next Page >

  • make tree in scheme

    - by ???
    (define (entry tree) (car tree)) (define (left-branch tree) (cadr tree)) (define (right-branch tree) (caddr tree)) (define (make-tree entry left right) (list entry left right)) (define (mktree order items_list) (cond ((= (length items_list) 1) (make-tree (car items_list) '() '())) (else (insert2 order (car items_list) (mktree order (cdr items_list)))))) (define (insert2 order x t) (cond ((null? t) (make-tree x '() '())) ((order x (entry t)) (make-tree (entry t) (insert2 order x (left-branch t)) (right-branch t))) ((order (entry t) x ) (make-tree (entry t) (left-branch t) (insert2 order x (right-branch t)))) (else t))) The result is: (mktree (lambda (x y) (< x y)) (list 7 3 5 1 9 11)) (11 (9 (1 () (5 (3 () ()) (7 () ()))) ()) ()) But I'm trying to get: (7 (3 (1 () ()) (5 () ())) (9 () (11 () ()))) Where is the problem?

    Read the article

  • PHP Recursive Function

    - by Tempname
    In my database I have a hierarchical flat table that returns data ordered by ParentID, ObjectID asc I am having a bit of an issue getting this recursive function to work properly. I get the first ParentChildChild but after that I get nothing else. Any help with this is greatly appreciated. Here is my testing code: $objectArr = array(); $objectData = DAOFactory::getTemplateObjectsDAO()->queryByTemplateID(1); for($i = 0; $i < count($objectData); $i++) { if(empty($objectData[$i]->parentID)) { echo $objectData[$i]->objectID; $objectArr[$i] = $objectData[$i]; $objectArr[$i]->children = array(); $objectArr[$i]->children = getChildren($objectData[$i]->objectID, $objectData); } } function getChildren($objectID, $data) { $childArr = array(); foreach($data as $object) { if($object->parentID == $objectID) { $childArr = $object; $childArr->children = array(); $childArr->children = getChildren($object->objectID, $data); } } return $childArr; } new dBug($objectData); This is the output that I am getting: Fullsize Link

    Read the article

  • trie reg exp parse step over char and continue

    - by forest.peterson
    Setup: 1) a string trie database formed from linked nodes and a vector array linking to the next node terminating in a leaf, 2) a recursive regular expression function that if A) char '*' continues down all paths until string length limit is reached, then continues down remaining string paths if valid, and B) char '?' continues down all paths for 1 char and then continues down remaining string paths if valid. 3) after reg expression the candidate strings are measured for edit distance against the 'try' string. Problem: the reg expression works fine for adding chars or swapping ? for a char but if the remaining string has an error then there is not a valid path to a terminating leaf; making the matching function redundant. I tried adding a 'step-over' ? char if the end of the node vector was reached and then followed every path of that node - allowing this step-over only once; resulted in a memory exception; I cannot find logically why it is accessing the vector out of range - bactracking? Questions: 1) how can the regular expression step over an invalid char and continue with the path? 2) why is swapping the 'sticking' char for '?' resulting in an overflow? Function: void Ontology::matchRegExpHelper(nodeT *w, string inWild, Set<string> &matchSet, string out, int level, int pos, int stepover) { if (inWild=="") { matchSet.add(out); } else { if (w->alpha.size() == pos) { int testLength = out.length() + inWild.length(); if (stepover == 0 && matchSet.size() == 0 && out.length() > 8 && testLength == tokenLength) {//candidate generator inWild[0] = '?'; matchRegExpHelper(w, inWild, matchSet, out, level, 0, stepover+1); } else return; //giveup on this path } if (inWild[0] == '?' || (inWild[0] == '*' && (out.length() + inWild.length() ) == level ) ) { //wild matchRegExpHelper(w->alpha[pos].next, inWild.substr(1), matchSet, out+w->alpha[pos].letter, level, 0, stepover);//follow path -> if ontology is full, treat '*' like a '?' } else if (inWild[0] == '*') matchRegExpHelper(w->alpha[pos].next, '*'+inWild.substr(1), matchSet, out+w->alpha[pos].letter, level, 0, stepover); //keep adding chars if (inWild[0] == w->alpha[pos].letter) //follow self matchRegExpHelper(w->alpha[pos].next, inWild.substr(1), matchSet, out+w->alpha[pos].letter, level, 0, stepover); //follow char matchRegExpHelper(w, inWild, matchSet, out, level, pos+1, stepover);//check next path } } Error Message: +str "Attempt to access index 1 in a vector of size 1." std::basic_string<char,std::char_traits<char>,std::allocator<char> > +err {msg="Attempt to access index 1 in a vector of size 1." } ErrorException Note: this function works fine for hundreds of test strings with '*' wilds if the extra stepover gate is not used Semi-Solved: I place a pos < w->alpha.size() condition on each path that calls w->alpha[pos]... - this prevented the backtrack calls from attempting to access the vector with an out of bounds index value. Still have other issues to work out - it loops infinitely adding the ? and backtracking to remove it, then repeat. But, moving forward now. Revised question: why during backtracking is the position index accumulating and/or not deincrementing - so at somepoint it calls w->alpha[pos]... with an invalid position that is either remaining from the next node or somehow incremented pos+1 when passing upward?

    Read the article

  • Can someone help with big O notation?

    - by Dann
    void printScientificNotation(double value, int powerOfTen) { if (value >= 1.0 && value < 10.0) { System.out.println(value + " x 10^" + powerOfTen); } else if (value < 1.0) { printScientificNotation(value * 10, powerOfTen - 1); } else // value >= 10.0 { printScientificNotation(value / 10, powerOfTen + 1); } } I understand how the method goes but I cannot figure out a way to represent the method. For example, if value was 0.00000009 or 9e-8, the method will call on printScientificNotation(value * 10, powerOfTen - 1); eight times and System.out.println(value + " x 10^" + powerOfTen); once. So the it is called recursively by the exponent for e. But how do I represent this by big O notation? Thanks!

    Read the article

  • What is the most efficient way to list all of the files in a directory (including sub-directories)?

    - by prometheus
    I am writing a servlet which will examine a directory on the server (external to the web container), and recursively search for certain files (by certain files, I mean files that are of a certain extension as well as a certain naming convention). Once these files are found, the servlet responds with a long list of all of the found files (including the full path to the files). My problem is that there are so many files and directories that my servlet goes extremely slow. I was wondering if there was a best practice or existing servlet for this type of problem? Would it be more efficient to simply compile the entire list of files and do the filtering via js/jquery on the client side?

    Read the article

  • Javascript recursive data structure definition

    - by Matt Bierner
    I need to define a data structure recursively in Javascript. Here is a simple example of a circular linked list: // List a very simplified example of what the actual (non list) code does. function List(f, r) { return function(){ return [f, r]; }; } var head = List('a', List('b', List('c', head))); When this is executed, head in List 'c' is resolved to undefined, not List 'a' as I need. List is an example function that returns a function (It is not an Javascript list that I can append to). I tried to wrap the definition of head is a self executing named function, but that blew the stack when head was resolved. What is the Javascript style solution that I am overlooking?

    Read the article

  • Deleting a node in a family tree

    - by user559142
    Hi, I'm trying to calclulate the best way to delete a node in a family tree. First, a little description of how the app works. My app makes the following assumption: Any node can only have one partner. That means that any child a single node has, it will also be the partner nodes child too. Therefore, step relations, divorces etc aren't compensated for. A node always has two parents - A mother and father cannot be added seperately. If the user doesn't know the details - the nodes attributes are set to a default value. Also any node can add parents, siblings, children to itself. Therefore in law relationships can be added. I have the following classes: FamilyMember String fName; String lName; String dob; String gender; FamilyMember mother, father, partner; ArrayListchildren; int index; int generation; void linkParents(); void linkPartner(); void addChild(); //gets & sets for fields Family ArrayListfamily; void addMember(); void removeMember(); FamilyMember getFamilyMember(index); ArrayListgetFamilyMembers(); FamilyTree Family family; void removeMember(); //need help void displayFamilyMembers(); void addFamilyMember(); void enterDetails(); void displayAncestors(); void displayDescendants(); void printDescendants(); FamilyMember findRootNode(); void sortGenerations(); void getRootGeneration(); I am having trouble with identifying the logic for removing a member. All other functions work fine. Has anyone developed a family tree app before who knows how to deal with removing various different nodes in the family "tree"? e.g. removing a leaf removing a leaf with partner (what if partner has parents etc) removing a parent It seems to be another recursive property but my head is swelling from over thought.

    Read the article

  • recursive program

    - by wilson88
    I am trying to make a recursive program that calculates interest per year.It prompts the user for the startup amount (1000), the interest rate (10%)and number of years(1).(in brackets are samples) Manually I realised that the interest comes from the formula YT(1 + R)----- interest for the first year which is 1100. 2nd year YT(1 + R/2 + R2/2) //R squared 2nd year YT(1 + R/3 + R2/3 + 3R3/) // R cubed How do I write a recursive program that will calculate the interest? Below is the function which I tried //Latest after editing double calculateInterest2(double start, double rate, int duration) { if (0 == duration) { return start; } else { return (1+rate) * calculateInterest2(start, rate, duration - 1); } }

    Read the article

  • Recursive Iterators

    - by soandos
    I am having some trouble making an iterator that can traverse the following type of data structure. I have a class called Expression, which has one data member, a List<object>. This list can have any number of children, and some of those children might be other Expression objects. I want to traverse this structure, and print out every non-list object (but I do want to print out the elements of the list of course), but before entering a list, I want to return "begin nest" and after I just exited a list, I want to return "end nest". I was able to do this if I ignored the class wherever possible, and just had List<object> objects with List<object> items if I wanted a subExpression, but I would rather do away with this, and instead have an Expressions as the sublists (it would make it easier to do operations on the object. I am aware that I could use extension methods on the List<object> but it would not be appropriate (who wants an Evaluate method on their list that takes no arguments?). The code that I used to generate the origonal iterator (that works) is: public IEnumerator GetEnumerator(){ return theIterator(expr).GetEnumerator(); } private IEnumerable theIterator(object root) { if ((root is List<object>)){ yield return " begin nest "; foreach (var item in (List<object>)root){ foreach (var item2 in theIterator(item)){ yield return item2; } } yield return " end nest "; } else yield return root; } A type swap of List<object> for expression did not work, and lead to a stackOverflow error. How should the iterator be implemented? Update: Here is the swapped code: public IEnumerator GetEnumerator() { return this.GetEnumerator(); } private IEnumerable theIterator(object root) { if ((root is Expression)) { yield return " begin nest "; foreach (var item in (Expression)root) { foreach (var item2 in theIterator(item)) yield return item2; } yield return " end nest "; } else yield return root; }

    Read the article

  • Getting a "for each" loop in Java to run in different order everytime

    - by R Stokes
    Hi, Basically my problem is that I'm trying to write a method that finds a random path in a graph of strings, which takes as it's parameters a start string, an integer length and a Vector of strings that will store the path. I'm attempting to do this by first adding the starting string to our blank vector, recursing through its neighbors until the vector's length (not including the start node) is the same as the integer length specified in the parameters. I've provided my code so far here: public Vector<String> findRandomPathFrom(String n, int len, Vector<String> randomPath){ randomPath.add(n); if (randomPath.size() == len + 1) return randomPath; for (String m : this.neighbours(n)){ if (!randomPath.contains(m) && findRandomPathFrom(m, len, randomPath) != null) return randomPath; } path.setSize(path.size() - 1); return null; } It seems to be working fine, returning a path with exactly the number of strings specified after the given start string. However, for any given starting string it generates the EXACT same path everytime, which kind of defeats the purpose of it being a random path generator. I'm guessing this problem is related to my "for each" loop, which loops through all the neighbouring strings of your current string. It seems to just be going with the first string in the neighbours vector every single time. Can anyone help me fix this problem so that it will choose a random neighbour instead of going in order? tl;dr - Any way of getting a "for each" loop in java to process a collection in a random order as oppoosed to start-to-finsih? Thanks in advance

    Read the article

  • Lambda recursive PHP functions.

    - by Kendall Hopkins
    Is it possible to have a PHP function that is both recursive and anonymous (lambda). This is my attempt to get it to work, but it doesn't pass in the function name. $factorial = function( $n ) use ( $factorial ) { if( $n == 1 ) return 1; return $factorial( $n - 1 ) * $n; }; print $factorial( 5 ); I'm also aware that this is a bad way to implement factorial, it's just an example.

    Read the article

  • recursively reverse linked list.

    - by Amanda
    I am implementing a function to recursively reverse a linked-list, but getting seg-fault. typedef struct _node { int data; struct _node *next; } Node, *NodeP; NodeP recursiveReverseList(NodeP first){ if(first == NULL) return NULL; if(first->next == NULL) return head; NodeP rest = recursiveReverseList(head->next); rest->next = first; first->next = NULL; return first; } Can you please help. P.S. The iterative version is working fine though. Its not homework. Just practicing C.

    Read the article

  • AngularJS recursive directive with a dynamic HTML template (bounty)

    - by Nazar Sobchuk
    I have a realy hard task here. I am working on an AngularJS web app, which is capable of sending different HTTP methods to our project's Restful Web Service and receiving responses in JSON. Basicaly it looks like this: You can create some REST resource from this application. Let's say an exam. To create an exam - you pick a resource from a list of available resources. This triggers a function, that sends a request to localhost:8080/STEP/api/explain/resorceName and gets a description for this resource. Description looks like this: http://jsonblob.com/534fc022e4b0bb44248d6460 After receiving a response - I start building input fields like follows (allFields - array of field objects for this resource, enumValues - enum values for resource's field if it's property isEnum = true): <div ng-repeat="field in allFields"> <div ng-show={{!field.isEnum}}> <p ng-show={{field.isRequired}}>{{field.name}}*: </p> <p ng-show={{!field.isRequired}}>{{field.name}}: </p> <input type="text" ng-model="updateEntityResource[field.name]" ng-change="getUpdateEntityAsText()" class="form-control" placeholder="{{parseClassName(field.type)}}"> </div> <div ng-show={{field.isEnum}}> <p ng-show={{field.isRequired}}>{{field.name}}*: </p> <p ng-show={{!field.isRequired}}>{{field.name}}: </p> <select ng-model="updateEntityResource[field.name]" ng-change="getUpdateEntityAsText()" class="form-control"> <option></option> <option ng-repeat="enumValue in field.enumValues" label={{enumValue.name}}>{{enumValue.ordinal}}</option> </select> </div> </div> Now, the problem. I need to create a recursive directive, which would be capable of generating fields in such maner as described above for every resource's field that has "restResourceName" not null. To get all it's fields you just send a request to localhost:8080/STEP/api/explain/restResourceName and get similar JSON response as shown above, which is then used to build HTML elements for inputing values into model. Does anyone know how this can be achieved using angular recursive directive? Every useful answer is highly appreciated and evaluated. The correct answer will get +50 or I will start a bounty, because I'm realy stuck with this for 2 days. If you need any additional info - let me know. Thank you.

    Read the article

  • Base Case in a recursive method

    - by Shaza
    Hey all, About my question, I'm asking a theoretical question here about Base case or the halting case in a recursive method, what's its standards? I mean, is it standard not to have body in it, just a return statement? Is it always like the following: If(input operation value) return sth; Do you have different thoughts about it??

    Read the article

  • How to detect the root recursive call?

    - by ahmadabdolkader
    Say we're writing a simple recursive function fib(n) that calculates the nth Fibonacci number. Now, we want the function to print that nth number. As the same function is being called repeatedly, there has to be a condition that allows only the root call to print. The question is: how to write this condition without passing any additional arguments, or using global/static variables. So, we're dealing with something like this: int fib(int n) { if(n <= 0) return 0; int fn = 1; if(n > 2) fn = fib(n-2) + fib(n-1); if(???) cout << fn << endl; return fn; } int main() { fib(5); return 0; } I thought that the root call differs from all children by returning to a different caller, namely the main method in this example. I wanted to know whether it is possible to use this property to write the condition and how. Update: please note that this is a contrived example that only serves to present the idea. This should be clear from the tags. I'm not looking for standard solutions. Thanks.

    Read the article

  • solving problems recursively in C

    - by Harry86
    Our professor gave us the following assignment: A "correct" series is one inwhich the sum of its members equals to the index of its first member. The program is supposed to find the length of the LONGEST "correct" series within a series of n numbers. for example: if the input series would be arr[4]={1, 1, 0, 0} the output (longest "correct" series) would be 3. arr[0]=1. 0!=1 therefore the longest series here is 0. arr[1]=1,and 1=1. but the follwing members also sum up to 1 as shown below: 1=arr[1]+arr[2]+arr[3] = 1+ 0 + 0, therefore the longest series here is 3. the output in this example is 3. That's what I got so far: int solve(int arr[], int index, int length,int sum_so_far) { int maxwith,maxwithout; if(index==length) return 0; maxwith = 1+ solve(arr,index+1,length,sum_so_far+arr[index]); maxwithout = solve(arr,index+1,length,arr[index+1]); if(sum_so_far+arr[index]==index) if(maxwith>maxwithout) return maxwith; return maxwithout; return 0; } int longestIndex(int arr[], int index,int length) { return solve(arr,0,length,0); } What am I doing wrong here? Thanks a lot for your time... Harry

    Read the article

  • Getting HIERARCHY_REQUEST_ERR when using Javascript to recursively generate a nested list

    - by Mark
    I have a method that is trying to take in a list. This list can contain data and other lists. The end goal is to try to convert something like this ["a", "b", ["c", "d"]] into <ol> <li> <b>a</a> </li> <li> <b>b</a> </li> <ol> <li> <b>c</a> </li> <li> <b>d</a> </li> </ol> </ol> The code is: function $(tagName) { return document.createElement(tagName); } //returns an html element representing data //data should be an array or some sort of value function tagMaker(data) { tag = null; if(data instanceof Array) { //data is an array, represent using <ol> tag = $("ol"); for(i=0; i<data.length; i++) { //construct one <li> for each item in the array listItem = $("li"); //get the html element representing this particular item in the array child = tagMaker(data[i]); //<li>*html for child*</li> listItem.appendChild(child); //add this item to the list tag.appendChild(listItem); } } else { //data is not an array, represent using <b>data</b> tag = $("b"); tag.innerHTML = data.toString(); } return tag; } Calling tagMaker throws HIERARCHY_REQUEST_ERR: DOM Exception 3, rather than generating a helpful HTML element object which I was planning to append to document.body.

    Read the article

  • How do I find the millionth number in the series: 2 3 4 6 9 13 19 28 42 63 ... ?

    - by HH
    It takes about minute to achieve 3000 in my comp but I need to know the millionth number in the series. The definition is recursive so I cannot see any shortcuts except to calculate everything before the millionth number. How can you fast calculate millionth number in the series? Series Def n_{i+1} = \floor{ 3/2 * n_{i} } and n_{0}=2. Interestingly, only one site list the series according to Google: this one. Too slow Bash code #!/bin/bash function series { n=$( echo "3/2*$n" | bc -l | tr '\n' ' ' | sed -e 's@\\@@g' -e 's@ @@g' ); # bc gives \ at very large numbers, sed-tr for it n=$( echo $n/1 | bc ) #DUMMY FLOOR func } n=2 nth=1 while [ true ]; #$nth -lt 500 ]; do series $n # n gets new value in the function through global value echo $nth $n nth=$( echo $nth + 1 | bc ) #n++ done

    Read the article

  • Recursively looping through a drive and replacing illegal characters

    - by yeahumok
    Hi I have to create an app that drills into a specific drive, reads all file names and replaces illegal SharePoint characters with underscores. The illegal characters I am referring to are: ~ # % & * {} / \ | : <> ? - "" Can someone provide either a link to code or code itself on how to do this? I am VERY new to C# and need all the help i can possibly get. I have researched code on recursively drilling through a drive but i am not sure how to put the character replace and the recursive looping together. Please help!

    Read the article

  • How can i optimize this recursive method

    - by Tirdyr
    Hi there. I'm trying to make a word puzzle game, and for that i'm using a recursive method to find all possible words in the given letters. The letters is in a 4x4 board. Like this: ABCD EFGH HIJK LMNO The recursive method is called inside this loop: for (int y = 0; y < width; y++) { for (int x = 0; x < height; x++) { myScabble.Search(letters, y, x, width, height, "", covered, t); } } letters is a 2D array of chars. y & x is ints that shows where in the board width & height is also int, that tells the dimensions of the board "" is the string we are trying to make (the word) covered is an array of bools, to check if we allready used that square. t is a List (wich contains all the words to check against). The recursive method that need optimizing: public void Search(char[,] letters, int y, int x, int width, int height, string build, bool[,] covered, List<aWord> tt) { // Dont get outside the bounds if (y >= width || y < 0 || x >= height || x < 0) { return; } // Dont deal with allrady covered squares if (covered[x, y]) { return; } // Get Letter char letter = letters[x, y]; // Append string pass = build + letter; // check if its a possibel word //List<aWord> t = myWords.aWord.Where(w => w.word.StartsWith(pass)).ToList(); List<aWord> t = tt.Where(w => w.word.StartsWith(pass)).ToList(); // check if the list is emphty if (t.Count < 10 && t.Count != 0) { //stop point } if (t.Count == 0) { return; } // Check if its a complete word. if (t[0].word == pass) { //check if its allrdy present in the _found dictinary if (!_found.ContainsKey(pass)) { //if not add the word to the dictionary _found.Add(pass, true); } } // Check to see if there is more than 1 more that matches string pass // ie. are there more words to find. if (t.Count > 1) { // make a copy of the covered array bool[,] cov = new bool[height, width]; for (int i = 0; i < width; i++) { for (int a = 0; a < height; a++) { cov[a, i] = covered[a, i]; } } // Set the current square as covered. cov[x, y] = true; // Continue in all 8 directions. Search(letters, y + 1, x, width, height, pass, cov, t); Search(letters, y, x + 1, width, height, pass, cov, t); Search(letters, y + 1, x + 1, width, height, pass, cov, t); Search(letters, y - 1, x, width, height, pass, cov, t); Search(letters, y, x - 1, width, height, pass, cov, t); Search(letters, y - 1, x - 1, width, height, pass, cov, t); Search(letters, y - 1, x + 1, width, height, pass, cov, t); Search(letters, y + 1, x - 1, width, height, pass, cov, t); } } The code works as i expected it to do, however it is very slow.. it takes about 2 mins to find the words. EDIT: i clarified that the letters array is 2D

    Read the article

  • passing back answers in prolog

    - by AhmadAssaf
    i have this code than runs perfectly .. returns a true .. when tracing the values are ok .. but its not returning back the answer .. it acts strangely when it ends and always return empty list .. uninstantiated variable .. test :- extend(4,12,[4,3,1,2],[[1,5],[3,4],[6]],_ExtendedBins). %printing basic information about the extend(NumBins,Capacity,RemainingNumbers,BinsSoFar,_ExtendedBins) :- getNumberofBins(BinsSoFar,NumberOfBins), msort(RemainingNumbers,SortedRemaining),nl, format("Current Number of Bins is :~w\n",[NumberOfBins]), format("Allowed Capacity is :~w\n",[Capacity]), format("maximum limit in bin is :~w\n",[NumBins]), format("Trying to fit :~w\n\n",[SortedRemaining]), format("Possible Solutions :\n\n"), fitElements(NumBins,NumberOfBins, Capacity,SortedRemaining,BinsSoFar,[]). %this is were the creation for possibilities will start %will check first if the number of bins allowed is less than then %we create a new list with all the possible combinations %after that we start matching to other bins with capacity constraint fitElements(NumBins,NumberOfBins, Capacity,RemainingNumbers,Bins,ExtendedBins) :- ( NumberOfBins < NumBins -> print('Creating new set: '); print('Sorry, Cannot create New Sets')), createNewList(Capacity,RemainingNumbers,Bins,ExtendedBins). createNewList(Capacity,RemainingNumbers,Bins,ExtendedBins) :- createNewList(Capacity,RemainingNumbers,Bins,[],ExtendedBins), print(ExtendedBins). createNewList(0,Bins,Bins,ExtendedBins,ExtendedBins). createNewList(_,[],_,ExtendedBins,ExtendedBins). createNewList(Capacity,[Element|Rest],Bins,Temp,ExtendedBins) :- conjunct_to_list(Element,ListedElement), append(ListedElement,Temp,NewList), sumlist(NewList,Sum), (Sum =< Capacity, append(ListedElement,ExtendedBins,Result); Capacity = 0), createNewList(Capacity,Rest,Bins,NewList,Result). fit(0,[],ExtendedBins,ExtendedBins). fit(Capacity,[Element|Rest],Bin,ExtendedBins) :- conjunct_to_list(Element,Listed), append(Listed,Bin,NewBin), sumlist(NewBin,Sum), (Sum =< Capacity -> fit(Capacity,Rest,NewBin,ExtendedBins); Capacity = 0, append(NewBin,ExtendedBins,NewExtendedBins), print(NewExtendedBins), fit(0,[],NewBin,ExtendedBins)). %get the number of bins provided getNumberofBins(List,NumberOfBins) :- getNumberofBins(List,0,NumberOfBins). getNumberofBins([],NumberOfBins,NumberOfBins). getNumberofBins([_List|Rest],TempCount,NumberOfBins) :- NewCount is TempCount + 1, %calculate the count getNumberofBins(Rest,NewCount,NumberOfBins). %recursive call %Convert set of terms into a list - used when needed to append conjunct_to_list((A,B), L) :- !, conjunct_to_list(A, L0), conjunct_to_list(B, L1), append(L0, L1, L). conjunct_to_list(A, [A]). Greatly appreciate the help

    Read the article

  • MySql stored procedure not found in PHP

    - by kaupov
    Hello, I have a trouble with MySql stored procedure that calls itself recursively using PHP (CakePHP). Calling it I receive following error: SQL Error: 1305: FUNCTION dbname.GetAdvertCounts does not exist The procedure itself is following: delimiter // DROP PROCEDURE IF EXISTS GetAdvertCounts// CREATE PROCEDURE GetAdvertCounts(IN category_id INT) BEGIN DECLARE no_more_sub_categories, advert_count INT DEFAULT 0; DECLARE sub_cat_id INT; DECLARE curr_sub_category CURSOR FOR SELECT id FROM categories WHERE parent_id = category_id; DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_sub_categories = 1; SELECT COUNT(*) INTO advert_count FROM adverts WHERE category_id = category_id; OPEN curr_sub_category; FETCH curr_sub_category INTO sub_cat_id; REPEAT SELECT advert_count + GetAdvertCounts(sub_cat_id) INTO advert_count; FETCH curr_sub_category INTO sub_cat_id; UNTIL no_more_sub_categories = 1 END REPEAT; CLOSE curr_sub_category; SELECT advert_count; END // delimiter ; If I remove or comment out the recursive call, the procedure is working. Any idea what I'm missing here? The categories are 2 level deep.

    Read the article

  • Python 3: Recursivley find if number is even

    - by pythonhack
    I am writing a program that must find if a number is even or not. It needs to follow this template. I can get it to find if a number is even or not recursively (call function and subtract 2, base case zero), but I am having a hard time following this template, based on how the isEven function is called in the main function. Any help would be greatly appreciated. Write a recursive function called isEven that finds whether a number is even or not: def isEven() #recursivley determine whether number is even or not def main(): number=int(input(“Enter a number : “)) if (isEven(number)): print(“Number is even”) else: print(“Number is not even”) main() Thank you! Appreciate it.

    Read the article

< Previous Page | 16 17 18 19 20 21 22 23 24 25 26 27  | Next Page >