Search Results

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

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

  • Recursion in prepared statements

    - by Rob
    I've been using PDO and preparing all my statements primarily for security reasons. However, I have a part of my code that does execute the same statement many times with different parameters, and I thought this would be where the prepared statements really shine. But they actually break the code... The basic logic of the code is this. function someFunction($something) { global $pdo; $array = array(); static $handle = null; if (!$handle) { $handle = $pdo->prepare("A STATEMENT WITH :a_param"); } $handle->bindValue(":a_param", $something); if ($handle->execute()) { while ($row = $handle->fetch()) { $array[] = someFunction($row['blah']); } } return $array; } It looked fine to me, but it was missing out a lot of rows. Eventually I realised that the statement handle was being changed (executed with different param), which means the call to fetch in the while loop will only ever work once, then the function calls itself again, and the result set is changed. So I am wondering what's the best way of using PDO prepared statements in a recursive way. One way could be to use fetchAll(), but it says in the manual that has a substantial overhead. The whole point of this is to make it more efficient. The other thing I could do is not reuse a static handle, and instead make a new one every time. I believe that since the query string is the same, internally the MySQL driver will be using a prepared statement anyway, so there is just the small overhead of creating a new handle on each recursive call. Personally I think that defeats the point. Or is there some way of rewriting this?

    Read the article

  • Sudoku Recursion Issue (Java)

    - by SkylineAddict
    I'm having an issue with creating a random Sudoku grid. I tried modifying a recursive pattern that I used to solve the puzzle. The puzzle itself is a two dimensional integer array. This is what I have (By the way, the method doesn't only randomize the first row. I had an idea to randomize the first row, then just decided to do the whole grid): public boolean randomizeFirstRow(int row, int col){ Random rGen = new Random(); if(row == 9){ return true; } else{ boolean res; for(int ndx = rGen.nextInt() + 1; ndx <= 9;){ //Input values into the boxes sGrid[row][col] = ndx; //Then test to see if the value is valid if(this.isRowValid(row, sGrid) && this.isColumnValid(col, sGrid) && this.isQuadrantValid(row, col, sGrid)){ // grid valid, move to the next cell if(col + 1 < 9){ res = randomizeFirstRow(row, col+1); } else{ res = randomizeFirstRow( row+1, 0); } //If the value inputed is valid, restart loop if(res == true){ return true; } } } } //If no value can be put in, set value to 0 to prevent program counting to 9 setGridValue(row, col, 0); //Return to previous method in stack return false; } This results in an ArrayIndexOutOfBoundsException with a ridiculously high or low number (+- 100,000). I've tried to see how far it goes into the method, and it never goes beyond this line: if(this.isRowValid(row, sGrid) && this.isColumnValid(col, sGrid) && this.isQuadrantValid(row, col, sGrid)) I don't understand how the array index goes so high. Can anyone help me out?

    Read the article

  • Recursion inside while loop, How does it work ?

    - by M.H
    Can you please tell me how does this java code work? : public class Main { public static void main (String[] args) { Strangemethod(5); } public static void Strangemethod(int len) { while(len > 1){ System.out.println(len-1); Strangemethod(len - 1); } } } I tried to debug it and follow the code step by step but I didn't understand it.

    Read the article

  • Recursion in assembly?

    - by Davis
    I'm trying to get a better grasp of assembly, and I am a little confused about how to recursively call functions when I have to deal with registers, popping/pushing, etc. I am embedding x86 assembly in C++. Here I am trying to make a method which given an array of integers will build a linked list containing these integers in the order they appear in the array. I am doing this by calling a recursive function: insertElem (struct elem *head, struct elem *newElem, int data) -head: head of the list -data: the number that will be inserted at the end of a list -newElem: points to the location in memory where I will store the new element (data field) My problem is that I keep overwriting the registers instead of a typical linked list. For example, if I give it an array {2,3,1,8,3,9} my linked-list will return the first element (head) and only the last element, because the elements keep overwriting each other after head is no longer null. So here my linked list looks something like: 2--9 instead of 2--3--1--8--3--9 I feel like I don't have a grasp on how to organize and handle the registers. newElem is in EBX and just keeps getting rewritten. Thanks in advance!

    Read the article

  • Create a triangle out of stars using only recursion

    - by Ramblingwood
    I need to to write a method that is called like printTriangle(5);. We need to create an iterative method and a recursive method (without ANY iteration). The output needs to look like this: * ** *** **** ***** This code works with the iterative but I can't adapt it to be recursive. public void printTriangle (int count) { int line = 1; while(line <= count) { for(int x = 1; x <= line; x++) { System.out.print("*"); } System.out.print("\n"); line++; } } I should not that you cannot use any class level variables or any external methods. Thanks.

    Read the article

  • LL(8) and left-recursion

    - by Peregring-lk
    I want to understand the relation between LL/LR grammars and the left-recursion problem (for any question I know parcially the answer, but I ask them as I don't know nothing, because I am a little confused now, and prefer complete answers) I'm happy with sintetized or short and direct answers (or just links solving it unambiguously): What type of language isn't LL(8) languages? LL(K) and LL(8) have problems with left-recursion? Or only LL(k) parsers? LALR(1) parser have troubles with left or right recursion? What type of troubles? Only in terms of the LL/LALR comparision. What is better, Bison (LALR(1)) or Boost.Spirit (LL(8))? (Let's suppose other features of them are irrelevant in this question) Why GCC use a (hand-made) LL(8) parser? Only for the "handling-error" problem?

    Read the article

  • Recursion Interview Questions [closed]

    - by halivingston
    Given a string, "ABC", print all permutations Given a dollar bill, fill out possible ways it can summed up using .25, .10, .5, etc. Given a phone number (123-456), print out all it's word counter parters like (ADG-XYZ) A B C D E F G H I J K L M N O P In the above 2D matrix, print all possible words (just literally all words, and sure we could check if it's exists in a dictionary). The base case is I think here is that reaching the same i, j positions. Any others you can think of?

    Read the article

  • Recursion through a directory tree in PHP

    - by phphelpplz
    I have a set of folders that has a depth of at least 4 or 5 levels. I'm looking to recurse through the directory tree as deep as it goes, and iterate over every file. I've gotten the code to go down into the first sets of subdirectories, but no deeper, and I'm not sure why. Any ideas? $count = 0; $dir = "/Applications/MAMP/htdocs/idahohotsprings.com"; function recurseDirs($main, $count){ $dir = "/Applications/MAMP/htdocs/idahohotsprings.com"; $dirHandle = opendir($main); echo "here"; while($file = readdir($dirHandle)){ if(is_dir($file) && $file != '.' && $file != '..'){ echo "isdir"; recurseDirs($file); } else{ $count++; echo "$count: filename: $file in $dir/$main \n<br />"; } } } recurseDirs($dir, $count); ?

    Read the article

  • Python recursion with list returns None

    - by newman
    def foo(a): a.append(1) if len(a) > 10: print a return a else: foo(a) Why this recursive function returns None (see transcript below)? I can't quite understand what I am doing wrong. In [263]: x = [] In [264]: y = foo(x) [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] In [265]: print y None

    Read the article

  • ruby inject recursion?

    - by Matt Humphrey
    the goal is to start with ['a','b','c'] and end up with {'a'={'b'={'c'={}}}} so, getting my bearings, i did this: ruby-1.8.7-p174 ['a','b','c'].inject({}){|h,v| h.update(v = {})} = {"a"={}, "b"={}, "c"={}} and then figured, if i actually pass on the result hash, it will recurse and nest, but: ruby-1.8.7-p174 ['a','b','c'].inject({}){|h,v| h.update(v = {}); h[v]} = {} why is this? any idea how to achieve the desired result in an elegant one-liner?

    Read the article

  • Javascript Recursion

    - by rpophessagr
    I have an ajax call and would like to recall it once I finish parsing and animating the result into the page. And that's where I'm getting stuck. I was able to recall the function, but it seems to not take into account the delays in the animation. i.e. The console keeps outputting the values at a wild pace. I thought setInterval might help with the interval being the sum of the length of my delays, but I can't get that to work... function loadEm(){ var result=new Array(); $.getJSON("jsonCall.php",function(results){ $.each(results, function(i, res){ rand = (Math.floor(Math.random()*11)*1000)+2000; fullRand += rand; console.log(fullRand); $("tr:first").delay(rand).queue(function(next) { doStuff(res); next(); }); }); var int=self.setInterval("loadEm()",fullRand); }); } });

    Read the article

  • Java Recursion Triangle Standing on Tip

    - by user1629075
    I was wondering how to create triangle out of asterisks on its tip rather than on its base. I have the code for making it stand on its base: public static String printTriangle (int count) { if( count <= 0 ) return ""; String p = printTriangle(count - 1); p = p + "*"; System.out.print(p); System.out.print("\n"); return p; } But then I'm stuck on how to have the greatest number of stars on the top, and then the next least, and so on. I was thinking something along the terms of having (count - p) to have the input of rows be subtracted from the amount of decrease, but then i was confused by this idea because p is string. EDIT: I tried changing the position of printTriangle(count - 1) using my original method without iterations and got 1 star per each line; how can I fix this? public class triangles { public static void main(String[] args) { printTriangle(5); } public static String printTriangle (int count) { if( count <= 0 ) return ""; String p = ""; p = p + "*"; System.out.print(p); System.out.print("\n"); p = printTriangle(count - 1); return p; } }

    Read the article

  • Python list recursion type error

    - by Jacob J Callahan
    I can't seem to figure out why the following code is giving me a TypeError: 'type' object is not iterable pastebin: http://pastebin.com/VFZYY4v0 def genList(self): #recursively generates a sorted list of child node values numList = [] if self.leftChild != 'none': numList.extend(self.leftChild.genList()) #error numList.extend(list((self.Value,))) if self.rightChild != 'none': numList.extend(self.rightChild.genList()) #error return numList code that adds child nodes (works correctly) def addChild(self, child): #add a child node. working if child.Value < self.Value: if self.leftChild == 'none': self.leftChild = child child.parent = self else: self.leftChild.addChild(child) elif child.Value > self.Value: if self.rightChild == 'none': self.rightChild = child child.parent = self else: self.rightChild.addChild(child) Any help would be appreciated. Full interpreter session: >>> import BinTreeNode as BTN >>> node1 = BTN.BinaryTreeNode(5) >>> node2 = BTN.BinaryTreeNode(2) >>> node3 = BTN.BinaryTreeNode(12) >>> node3 = BTN.BinaryTreeNode(16) >>> node4 = BTN.BinaryTreeNode(4) >>> node5 = BTN.BinaryTreeNode(13) >>> node1.addChild(node2) >>> node1.addChild(node3) >>> node1.addChild(node4) >>> node1.addChild(node5) >>> node4.genList() <class 'list'> >>> node1.genList() Traceback (most recent call last): File "<interactive input>", line 1, in <module> File "C:...\python\BinTreeNode.py", line 47, in genList numList.extend(self.leftChild.genList()) #error File "C:...\python\BinTreeNode.py", line 52, in genList TypeError: 'type' object is not iterable

    Read the article

  • Recursion: using values passed in parameters

    - by Tom Lilletveit
    I got this line of code that pops a int of the array saves it to int element then removes it from array. then in the return statement return CountCriticalVotes(rest, blockIndex + element); it ads it to the blockIndex variable and if it reaches 10 before the array is empty it returns 1. But my problem is this, I do not want it to add up all the values in the array in the parameter, but only add one then revert the parameter value back to it´s original state, then add a new, revert etc... How would i do this? int NumCriticalVotes :: CountCriticalVotes(Vector<int> & blocks, int blockIndex) { if (blockIndex >= 10) { return 1; } if (blocks.isEmpty()) { return 0; } else { int element = blocks.get(0); Vector<int> rest = blocks; rest.remove(0); return CountCriticalVotes(rest, blockIndex + element);

    Read the article

  • Removing Left Recursion in ANTLR

    - by prosseek
    As is explained in http://stackoverflow.com/questions/2652060/removing-left-recursion , there are two ways to remove the left recursion. Modify the original grammar to remove the left recursion using some procedure Write the grammar originally not to have the left recursion What people normally use for removing (not having) the left recursion with ANTLR? I've used flex/bison for parser, but I need to use ANTLR. The only thing I'm concerned about using ANTLR (or LL parser in genearal) is left recursion removal. In practical sense, how serious of removing left recursion in ANTLR? Is this a showstopper in using ANTLR? Or, nobody cares about it in ANTLR community? I like the idea of AST generation of ANTLR. In terms of getting AST quick and easy way, which method (out of the 2 removing left recursion methods) is preferable?

    Read the article

  • SQL SERVER – Backing Up and Recovering the Tail End of a Transaction Log – Notes from the Field #042

    - by Pinal Dave
    [Notes from Pinal]: The biggest challenge which people face is not taking backup, but the biggest challenge is to restore a backup successfully. I have seen so many different examples where users have failed to restore their database because they made some mistake while they take backup and were not aware of the same. Tail Log backup was such an issue in earlier version of SQL Server but in the latest version of SQL Server, Microsoft team has fixed the confusion with additional information on the backup and restore screen itself. Now they have additional information, there are a few more people confused as they have no clue about this. Previously they did not find this as a issue and now they are finding tail log as a new learning. Linchpin People are database coaches and wellness experts for a data driven world. In this 42nd episode of the Notes from the Fields series database expert Tim Radney (partner at Linchpin People) explains in a very simple words, Backing Up and Recovering the Tail End of a Transaction Log. Many times when restoring a database over an existing database SQL Server will warn you about needing to make a tail end of the log backup. This might be your reminder that you have to choose to overwrite the database or could be your reminder that you are about to write over and lose any transactions since the last transaction log backup. You might be asking yourself “What is the tail end of the transaction log”. The tail end of the transaction log is simply any committed transactions that have occurred since the last transaction log backup. This is a very crucial part of a recovery strategy if you are lucky enough to be able to capture this part of the log. Most organizations have chosen to accept some amount of data loss. You might be shaking your head at this statement however if your organization is taking transaction logs backup every 15 minutes, then your potential risk of data loss is up to 15 minutes. Depending on the extent of the issue causing you to have to perform a restore, you may or may not have access to the transaction log (LDF) to be able to back up those vital transactions. For example, if the storage array or disk that holds your transaction log file becomes corrupt or damaged then you wouldn’t be able to recover the tail end of the log. If you do have access to the physical log file then you can still back up the tail end of the log. In 2013 I presented a session at the PASS Summit called “The Ultimate Tail Log Backup and Restore” and have been invited back this year to present it again. During this session I demonstrate how you can back up the tail end of the log even after the data file becomes corrupt. In my demonstration I set my database offline and then delete the data file (MDF). The database can’t become more corrupt than that. I attempt to bring the database back online to change the state to RECOVERY PENDING and then backup the tail end of the log. I can do this by specifying WITH NO_TRUNCATE. Using NO_TRUNCATE is equivalent to specifying both COPY_ONLY and CONTINUE_AFTER_ERROR. It as its name says, does not try to truncate the log. This is a great demo however how could I achieve backing up the tail end of the log if the failure destroys my entire instance of SQL and all I had was the LDF file? During my demonstration I also demonstrate that I can attach the log file to a database on another instance and then back up the tail end of the log. If I am performing proper backups then my most recent full, differential and log files should be on a server other than the one that crashed. I am able to achieve this task by creating new database with the same name as the failed database. I then set the database offline, delete my data file and overwrite the log with my good log file. I attempt to bring the database back online and then backup the log with NO_TRUNCATE just like in the first example. I encourage each of you to view my blog post and watch the video demonstration on how to perform these tasks. I really hope that none of you ever have to perform this in production, however it is a really good idea to know how to do this just in case. It really isn’t a matter of “IF” you will have to perform a restore of a production system but more of a “WHEN”. Being able to recover the tail end of the log in these sever cases could be the difference of having to notify all your business customers of data loss or not. If you want me to take a look at your server and its settings, or if your server is facing any issue we can Fix Your SQL Server. Note: Tim has also written an excellent book on SQL Backup and Recovery, a must have for everyone. Reference: Pinal Dave (http://blog.sqlauthority.com)Filed under: Notes from the Field, PostADay, SQL, SQL Authority, SQL Performance, SQL Query, SQL Server, SQL Tips and Tricks, T SQL

    Read the article

  • Is recursion really bad?

    - by dotneteer
    After my previous post about the stack space, it appears that there is perception from the feedback that recursion is bad and we should avoid deep recursion. After writing a compiler, I know that the modern computer and compiler are complex enough and one cannot automatically assume that a hand crafted code would out-perform the compiler optimization. The only way is to do some prototype to find out. So why recursive code may not perform as well? Compilers place frames on a stack. In additional to arguments and local variables, compiles also need to place frame and program pointers on the frame, resulting in overheads. So why hand-crafted code may not performance as well? The stack used by a compiler is a simpler data structure and can grow and shrink cleanly. To replace recursion with out own stack, our stack is allocated in the heap that is far more complicated to manage. There could be overhead as well if the compiler needs to mark objects for garbage collection. Compiler also needs to worry about the memory fragmentation. Then there is additional complexity: CPUs have registers and multiple levels of cache. Register access is a few times faster than in-CPU cache access and is a few 10s times than on-board memory access. So it is up to the OS and compiler to maximize the use of register and in-CPU cache. For my particular problem, I did an experiment to rewrite my c# version of recursive code with a loop and stack approach. So here are the outcomes of the two approaches:   Recursive call Loop and Stack Lines of code for the algorithm 17 46 Speed Baseline 3% faster Readability Clean Far more complex So at the end, I was able to achieve 3% better performance with other drawbacks. My message is never assuming your sophisticated approach would automatically work out better than a simpler approach with a modern computer and compiler. Gage carefully before committing to a more complex approach.

    Read the article

  • Stack Trace Logger [migrated]

    - by Chris Okyen
    I need to write a parent Java class that classes using recursion can extend. The parent class will be be able to realize whenever the call stack changes ( you enter a method, temporarily leave it to go to another method call, or you are are finsihed with the method ) and then print it out. I want it to print on the console, but clear the console as well every time so it shows the stack horizantaly so you can see the height of each stack to see what popped off and what popped on... Also print out if a baseline was reached for recursive functions. First. How can I using the StackTraceElements and Thread classes to detect automatically whenever the stack has popped or pushed an element on without calling it manually? Second, how would I do the clearing thing? For instance , if I had the code: public class recursion(int i) { private static void recursion(int i) { if( i < 10) System.out.println('A'); else { recursion(i / 10 ); System.out.println('B'); } } public static void main(String[] argv) { recursion(102); } } It would need to print out the stack when entering main(), when entering recursion(102) from main(), when it enters recursion(102 / 10), which is recursion(10), from recursion(102), when it enters recursion(10 / 10), which is recursion(1) from recursion(10). Print out a message out when it reaches the baseline recursion(1).. then print out the stacks of reversed revisitation of function recursion(10), recursion(102) and main(). finally print out we are exiting main().

    Read the article

  • Understanding Long Tail Keywords For SEO

    Long tail keywords are typically two or more words (a phrase) that you type into a search engine like Google when you are searching for a product, service, the answer to a question or any kind of research you might find necessary. And if you're not at the top of the search engines (preferably in one of the first 3 positions), your chances of making money online decrease substantially.

    Read the article

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