Search Results

Search found 1157 results on 47 pages for 'recursive descent'.

Page 14/47 | < Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >

  • How to write a recursive function that returns a linked list of nodes, when given a binary tree of n

    - by Jian Lin
    I was once asked of this in an interview: How to write a recursive function that returns a linked list of nodes, when given a binary tree of nodes? (flattening the data) For some reason, I tend to need more than 3 to 5 minutes to solve any recursive problem. Usually, 15 to 20 minutes will be more like it. How could we attack this problem, such as a very systematic way of reaching a solution, so that they can be solved in 3 to 5 minute time frame?

    Read the article

  • Where should I initialize variables for an OO Recursive Descent Parse Tree?

    - by Vasto
    I'd like to preface this by stating that this is for a class, so please don't solve this for me. One of my labs for my cse class is creating an interpreter for a BNF that was provided. I understand most of the concepts, but I'm trying to build up my tree and I'm unsure where to initialize values. I've tried in both the constructor, and in the methods but Eclipse's debugger still only shows the left branch, even though it runs through completely. Here is my main procedure so you can get an idea of how I'm calling the methods. public class Parser { public static void main(String[] args) throws IOException { FileTokenizer instance = FileTokenizer.Instance(); FileTokenizer.main(args); Prog prog = new Prog(); prog.ParseProg(); prog.PrintProg(); prog.ExecProg(); } Now here is My Prog class: public class Prog { private DeclSeq ds; private StmtSeq ss; Prog() { ds = new DeclSeq(); ss = new StmtSeq(); } public void ParseProg() { FileTokenizer instance = FileTokenizer.Instance(); instance.skipToken(); //Skips program (1) // ds = new DeclSeq(); ds.ParseDS(); instance.skipToken(); //Skips begin (2) // ss = new StmtSeq(); ss.ParseSS(); instance.skipToken(); } I've tried having Prog() { ds = null; ss = null; } public void ParseProg() { FileTokenizer instance = FileTokenizer.Instance(); instance.skipToken(); //Skips program (1) ds = new DeclSeq(); ds.ParseDS(); ... But it gave me the same error. I need the parse tree built up so I can do a pretty print and an execute command, but like I said, I only get the left branch. Any help would be appreciated. Explanations why are even more so appreciated. Thank you, Vasto

    Read the article

  • What is the proper way to create a recursive entity in the Entity Framework?

    - by Orion Adrian
    I'm currently using VS 2010 RC, and I'm trying to create a model that contains a recursive self-referencing entity. Currently when I import the entity from the model I get an error indicating that the parent property cannot be part of the association because it's set to 'Computed' or 'Identity', though I'm not sure why it does it that way. I've been hand-editing the file to get around that error, but then the model simply doesn't work. What is the proper way to get recursive entities to work in the Entity Framework. CREATE TABLE [dbo].[Appointments]( [AppointmentId] [int] IDENTITY(1,1) NOT NULL, [Description] [nvarchar](1024) NULL, [Start] [datetime] NOT NULL, [End] [datetime] NOT NULL, [Username] [varchar](50) NOT NULL, [RecurrenceRule] [nvarchar](1024) NULL, [RecurrenceState] [varchar](20) NULL, [RecurrenceParentId] [int] NULL, [Annotations] [nvarchar](50) NULL, [Application] [nvarchar](100) NOT NULL, CONSTRAINT [PK_Appointments] PRIMARY KEY CLUSTERED ( [AppointmentId] ASC ) ) GO ALTER TABLE [dbo].[Appointments] WITH CHECK ADD CONSTRAINT [FK_Appointments_ParentAppointments] FOREIGN KEY([RecurrenceParentId]) REFERENCES [dbo].[Appointments] ([AppointmentId]) GO ALTER TABLE [dbo].[Appointments] CHECK CONSTRAINT [FK_Appointments_ParentAppointments] GO

    Read the article

  • Can you make a PHP function recursive without repeating it's name?

    - by alex
    It's always bugged me a recursive function needs to name itself, when a instantiated class can use $this and a static method can use self etc. Is there a similar way to do this in a recursive function without naming it again (just to cut down on maintenance)? Obviously I could use call_user_func or the __FUNCTION__ constant but I would prefer something less ugly. Update Thanks for your answers. I might stick to including the function name for simple functions, and make take the other approaches for anything more complicated.

    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

  • How can I make a recursive version of my iterative method?

    - by user247679
    Greetings. I am trying to write a recursive function in Java that prints the numbers one through n. (n being the parameter that you send the function.) An iterative solution is pretty straightforward: public static void printNumbers(int n){ for(int i = 1; i <= n; i++){ System.out.println(i); i++; } As a novice programmer, I'm having troubles figuring out how a recursive version of this method would work. Any bright ideas? Thanks for reading my problem!

    Read the article

  • Java - StackOverflow Error on recursive 2D boolean array method that shouldn't happen.

    - by David W.
    Hey everyone, I'm working on a runnable java applet that has a fill feature much like the fill method in drawing programs such as Microsoft Paint. This is how my filling method works: 1.) The applet gets the color that the user clicked on using .getRGB 2.) The applet creates a 2D boolean array of all the pixels in the window, with the value "true" if that pixel is the same color as the color clicked on or "false" if not. The point of this step is to keep the .getRGB method out of the recursive method to hopefully prevent this error. 3.) The applet recursively searches the 2D array of booleans where the user clicked, recording each adjacent point that is "true" in an ArrayList. The method then changes each point it records to false and continues. 4.) The applet paints every point stored in the ArrayList to a user selected color. All of the above steps work PERFECTLY if the user clicks within a small area, where only a few thousand pixels or so have their color changed. If the user selects a large area however (such as about 360,000 / the size of the applet window), the applet gets to the recursive stage and then outputs this error: Exception in thread "AWT-EventQueue-1" java.lang.StackOverflowError at java.util.ArrayList.add(ArrayList.java:351) at paint.recursiveSearch(paint.java:185) at paint.recursiveSearch(paint.java:190) at paint.recursiveSearch(paint.java:190) at paint.recursiveSearch(paint.java:190) at paint.recursiveSearch(paint.java:190) at paint.recursiveSearch(paint.java:190) at paint.recursiveSearch(paint.java:190) (continues for a few pages) Here is my recursive code: public void recursiveSearch(boolean [][] list, Point p){ if(isValid(p)){ if(list[(int)p.y][(int)p.x]){ fillPoints.add(p); list[(int)p.y][(int)p.x] = false; recursiveSearch(list, new Point(p.x-1,p.y));//Checks to the left recursiveSearch(list, new Point(p.x,p.y-1));//Checks above recursiveSearch(list, new Point(p.x+1,p.y));//Checks to the right recursiveSearch(list, new Point(p.x,p.y+1));//Checks below } } } Is there any way I can work around an error like this? I know that the loop will never go on forever, it just could take a lot of time. Thanks in advance.

    Read the article

  • How can I implement a tail-recursive list append?

    - by martingw
    A simple append function like this (in F#): let rec app s t = match s with | [] -> t | (x::ss) -> x :: (app ss t) will crash when s becomes big, since the function is not tail recursive. I noticed that F#'s standard append function does not crash with big lists, so it must be implemented differently. So I wondered: How does a tail recursive definition of append look like? I came up with something like this: let rec comb s t = match s with | [] -> t | (x::ss) -> comb ss (x::t) let app2 s t = comb (List.rev s) t which works, but looks rather odd. Is there a more elegant definition?

    Read the article

  • Global variable in a recursive function how to keep it at zero?

    - by Grammin
    So if I have a recursive function with a global variable var_: int var_; void foo() { if(var_ == 3) return; else var_++; foo(); } and then I have a function that calls foo() so: void bar() { foo(); return; } what is the best way to set var_ =0 everytime foo is called thats not from within itself. I know I could just do: void bar() { var_ =0; foo(); return; } but I'm using the recursive function a lot and I don't want to call foo and forget to set var_=0 at a later date. Does anyone have any suggestions on how to solve this? Thanks, Josh

    Read the article

  • How to deal with recursive dependencies between static libraries using the binutils linker?

    - by Jack Lloyd
    I'm porting an existing system from Windows to Linux. The build is structured with multiple static libraries. I ran into a linking error where a symbol (defined in libA) could not be found in an object from libB. The linker line looked like g++ test_obj.o -lA -lB -o test The problem of course being that by the time the linker finds it needs the symbol from libA, it has already passed it by, and does not rescan, so it simply errors out even though the symbol is there for the taking. My initial idea was of course to simply swap the link (to -lB -lA) so that libA is scanned afterwards, and any symbols missing from libB that are in libA are picked up. But then I find there is actually a recursive dependency between libA and libB! I'm assuming the Visual C++ linker handles this in some way (does it rescan by default?). Ways of dealing with this I've considered: Use shared objects. Unfortunately this is undesirable from the perspective of requiring PIC compliation (this is performance sensitive code and losing %ebx to hold the GOT would really hurt), and shared objects aren't needed. Build one mega ar of all of the objects, avoiding the problem. Restructure the code to avoid the recursive dependency (which is obviously the Right Thing to do, but I'm trying to do this port with minimal changes). Do you have other ideas to deal with this? Is there some way I can convince the binutils linker to perform rescans of libraries it has already looked at when it is missing a symbol?

    Read the article

  • Recursive function for copy of multilevel folder is not working.

    - by OM The Eternity
    Recursive function for copy of multilevel folder is not working. I have a code to copy all the mulitilevel folder to new folder. But in between I feel there is problem of proper path recognition, see the code below.. <?php $source = '/var/www/html/pranav_test'; $destination = '/var/www/html/parth'; copy_recursive_dirs($source, $destination); function copy_recursive_dirs($dirsource, $dirdest) { // recursive function to copy // all subdirectories and contents: if(is_dir($dirsource)) { $dir_handle=opendir($dirsource); } if(!is_dir($dirdest)) { mkdir($dirdest, 0777); } while($file=readdir($dir_handle)) {/*echo "<pre>"; print_r($file);*/ if($file!="." && $file!="..") { if(!is_dir($dirsource.DIRECTORY_SEPARATOR.$file)) { copy ($dirsource.DIRECTORY_SEPARATOR.$file, $dirdest.DIRECTORY_SEPARATOR.$dirsource.DIRECTORY_SEPARATOR.$file); } else{ copy_recursive_dirs($dirsource.DIRECTORY_SEPARATOR.$file, $dirdest); } } } closedir($dir_handle); return true; } ?> from the above code the if loop has a copy function as per requirement, but the path applied for destination here is not proper, I have tried with basename function as well.. but it didnt got the expected result.. below is the if loop i am talking about with comment describing the output... if(!is_dir($dirsource.DIRECTORY_SEPARATOR.$file)) { $basefile = basename($dirsource.DIRECTORY_SEPARATOR.$file);//it gives the file name echo "Pranav<br>".$dirdest.DIRECTORY_SEPARATOR.$dirsource.DIRECTORY_SEPARATOR.$file;//it outputs for example "/var/www/html/parth//var/www/html/pranav_test/media/system/js/caption.js" which is not correct.. copy ($dirsource.DIRECTORY_SEPARATOR.$file, $dirdest.DIRECTORY_SEPARATOR.$dirsource.DIRECTORY_SEPARATOR.$file); } as shown above the i cannot get the files and folders copied to expected path.. please guide me to place proper path in the function....

    Read the article

  • Private Java class properties mysteriously reset between method calls....

    - by Michael Jones
    I have a very odd problem. A class property is mysteriously reset between method calls. The following code is executed so the constructor is called, then the parseConfiguration method is called. Finally, processData is called. The parseConfiguration method sets the "recursive" property to "true". However, as soon as it enters "processData", "recursive" becomes "false". This problem isn't isolated to a single class -- I have several examples of this in my code. How can this possibly be happening? I've tried initialising properties when they're declared outside any methods, I've tried initialising them in constructors... nothing works. The only complication I can think of here is that this class is invoked by an object that runs in a thread -- but here is one instance per thread, so surely no chance that threads are interfering. I've tried setting both methods to "synchronized", but this still happens. Please help! /** * This class or its superclasses are NOT threaded and don't extend Thread */ public class DirectoryAcquirer extends Manipulator { /** * @var Whether to recursively scan directories */ private boolean recursive = false; /** * Constructor */ public DirectoryAcquirer() { } /** * Constructor that initialises the configuration * * @param config * @throws InvalidConfigurationException */ public DirectoryAcquirer(HierarchicalConfiguration config) throws InvalidConfigurationException { super(config); } @Override protected void parseConfiguration() throws InvalidConfigurationException { // set whether to recurse into directories or not if (this.config.containsKey("recursive")) { // this.recursive gets set to "true" here this.recursive = this.config.getBoolean("recursive"); } } @Override public EntityCollection processData(EntityCollection data) { // here this.recursive is "false" this.logger.debug("processData: Entered method"); } }

    Read the article

  • Scheme. Tail recursive ?

    - by n00b
    Hi guys, any tail-recursive version for the below mentioned pseudocode ? Thanks ! (define (min list) (cond ((null? list '()) ((null? (cdr list)) (car list)) (#t (let ((a (car list)) (b (min (cdr list))) ) (if (< b a) b a) ) ) ) )

    Read the article

  • Back-to-back ajax long poll without a recursive callback function.

    - by Teddy
    I'm trying to make long poll ajax calls, back to back. The problem with the current way I'm doing it is that I make each successive call from the callback function of the previous call. Is this a problem? Firebug doesn't show any of my ajax calls as completed, even thought the data is returned and the callback is executed. The recursive structure seems inefficient. Any ideas?

    Read the article

  • Sequential numbering from recursive function? e.g. 2, 2.1, 2.1.1, 2.2, 2.2.1

    - by Pete
    I have a recursive function reading a "table of contents" of documents from a database. I would like to print numbering with the document that reflects where the item is in the tree, e.g. First item, 1.1 Child of first item, 1.1.1 Child of child of first item, 1.2 Child of first item, Second item, 2.1 Child of second item, etc. Rather stumped about this at the moment - help please?

    Read the article

  • If a jQuery function calls itself in its completion callback, is that a recursive danger to the stac

    - by NXT
    Hi, I'm writing a little jQuery component that animates in response to button presses and also should go automatically as well. I was just wondering if this function recursive or not, I can't quite work it out. function animate_next_internal() { $('#sc_thumbnails').animate( { top: '-=106' }, 500, function() { animate_next_internal(); } ); } My actual function is more complicated to allow for stops and starts, this is just a simplified example.

    Read the article

  • how Can we get the output format to CSV instead of HTML in Alfresco using webscripts?

    - by pavan123
    how Can we change the output format to CSV instead of HTML in Alfresco using webscripts? below are the my corresponding FTL and Webscript files recursive.get.html.ftl <#macro recurse_macro node depth> <#if node.isContainer> <tr> <td> ${node.properties.name} </td> <td></td> </tr> <#list node.children as child> <#if child.isContainer> <@recurse_macro node=child depth=depth+1/> <#list child.children as child2> <#if child2.isDocument> <tr><td></td><td>${child2.properties.name}</td></tr> </#if> </#list> </#if> </#list> </#if> </#macro> Recursive Listing of Spaces & Documents: Space Document recursive.get.desc.xml <webscript> <shortname>recurcive</shortname> <description>Recursive</description> <url>/sample/recursive/{recursive}</url> <format default="html">extension</format> <authentication>guest</authentication> </webscript> and html output is Recursive Listing of Spaces & Documents: Space Document Company Home Data Dictionary Space Templates Software Engineering Project Documentation Drafts Pending Approval Published Samples system-overview.html Discussions UI Design Presentations Quality Assurance Presentation Templates doc_info.ftl localizable.ftl my_docs.ftl my_spaces.ftl my_summary.ftl translatable.ftl recent_docs.ftl general_example.ftl my_docs_inline.ftl show_audit.ftl readme.ftl Email Templates notify_user_email.ftl invite_user_email.ftl RSS Templates RSS_2.0_recent_docs.ftl Saved Searches admin Scripts backup.js example test script.js backup and log.js append copyright.js alfresco docs.js test return value.js Web Scripts org alfresco sample blogsearch.get.js blogsearch.get.atom.ftl blogsearch.get.desc.xml blogsearch.get.html.ftl blogsearch.get.html.400.ftl blogsearch.get.atom.400.ftl categorysearch.get.js categorysearch.get.atom.ftl categorysearch.get.desc.xml categorysearch.get.html.ftl categorysearch.get.html.404.ftl categorysearch.get.atom.404.ftl folder.get.js folder.get.atom.ftl folder.get.desc.xml folder.get.html.ftl avmstores.get.desc.xml avmstores.get.html.ftl avmbrowse.get.js avmbrowse.get.desc.xml avmbrowse.get.html.ftl recursive.get.desc.xml recursive.get.html.ftl sgs.get.desc.xml sgs.get.csv.ftl sample1.get.desc.xml sample1.get.csv.ftl first.get.desc.xml first.get.text.ftl rag.get.html.ftl rag.get.desc.xml new1.get.desc.xml new1.get.html.ftl excel.get.html.ftl excel.get.desc.xml sgs1.get.desc.xml one.get.html.ftl one.get.desc.xml one.get.js readme.html Web Scripts Extensions readme.html Guest Home Alfresco-Tutorial.pdf User Homes isabel Users Home

    Read the article

  • emacs delete directory recursively?

    - by Stephen
    I was searching through for a way to copy/delete directory trees... dired seems to have dired-copy-file-recursive (though sans documentation) and a search on 'recursive' also returns: tramp-handle-dired-recursive-delete-directory is a compiled Lisp function in `tramp.el'. (tramp-handle-dired-recursive-delete-directory FILENAME) Recursively delete the directory given. This is like `dired-recursive-delete-directory' for Tramp files. But I can't find dired-recursive-delete-directory anywhere! Anyone know what's going on? Thanks ~

    Read the article

  • Help with Perl Regex Recursive Replace One Liner? Replace MySQL comments '--' with '#'

    - by NJTechie
    I have various SQL files with '--' comments and we migrated to the latest version of MySQL and it hates these comments. I want to replace -- with #. I am looking for a recursive, inplace replace one-liner. This is what I have : perl -p -i -e 's/--/# /g' `fgrep -- -- * ` A sample .sql file : use myDB; --did you get an error I get the following error : Unrecognized switch: --did (-h will show valid options). p.s : fgrep skipping 2 dashes was just discussed here if you are interested. Any help is appreciated.

    Read the article

  • ManyToManyField error when having recursive structure. How to solve it?

    - by luc
    Hello, I have the following table in the model with a recursive structure (a page can have children pages) class DynamicPage(models.Model): name = models.CharField("Titre",max_length=200) parent = models.ForeignKey('self',null=True,blank=True) I want to create another table with manytomany relation with this one: class UserMessage(models.Model): name = models.CharField("Nom", max_length=100) page = models.ManyToManyField(DynamicPage) The generated SQL creates the following constraint: ALTER TABLE `website_dynamicpage` ADD CONSTRAINT `parent_id_refs_id_29c58e1b` FOREIGN KEY (`parent_id`) REFERENCES `website_dynamicpage` (`id`); I would like to have the ManyToMany with the page itself (the id) and not with the parent field. How to modify the model to make the constraint using the id and not the parent? Thanks in advance

    Read the article

  • Recursive MySQL function call eats up too much memory and dies.

    - by kylex
    I have the following recursive function which works... up until a point. Then the script asks for more memory once the queries exceed about 100, and when I add more memory, the script typically just dies (I end up with a white screen on my browser). public function returnPArray($parent=0,$depth=0,$orderBy = 'showOrder ASC'){ $query = mysql_query("SELECT *, UNIX_TIMESTAMP(lastDate) AS whenTime FROM these_pages WHERE parent = '".$parent."' AND deleted = 'N' ORDER BY ".$orderBy.""); $rows = mysql_num_rows($query); while($row = mysql_fetch_assoc($query)){ // This uses my class and places the content in an array. MyClass::$_navArray[] = array( 'id' => $row['id'], 'parent' => $row['parent'] ); MyClass::returnPArray($row['id'],($depth+1)); } $i++; } Can anyone help me make this query less resource intensive?

    Read the article

  • jQuery: is there a way to make a recursive child selector?

    - by gsquare567
    instead of checking only the immediate children of an element, i would like to recursively check all children of the element. specifically, something like $("#survey11Form>input[type=text]:visible").val(); with the html: <form id="survey11Form" name="survey11Form" action="#" method="post"> <div id="survey11Div"> <fieldset> <legend>TEST'TEST"TEST</legend> <div class="label"> <label test="" title="TEST'TEST" for="answer15"> TEST'TEST"TEST </label></div> <div class="fieldWrapper text required"> <div style="width: 146px;" class="cellValue"> <input type="text" title="TEST'TEST" value="" id="survey11answer15" name="survey11answer15"> should give me the value of that input. the jquery i've come up with does not. any ideas as to what would work in this situation (and all recursive situations)? thanks!

    Read the article

  • I'm having trouble with using std::stack to retrieve the values from a recursive function.

    - by Peter Stewart
    Thanks to the help I received in this post: http://stackoverflow.com/questions/2761918/how-do-i-use-this-in-a-member-function I have a nice, concise recursive function to traverse a tree in postfix order: void Node::postfix() { if (left != __nullptr) { left->postfix(); } if (right != __nullptr) { right->postfix(); } cout<<cargo<<"\n"; return; }; Now I need to evaluate the values and operators as they are returned. My problem is how to retrieve them. I tried the std::stack: #include <stack> stack <char*> s; void Node::postfix() { if (left != __nullptr) { left->postfix(); } if (right != __nullptr) { right->postfix(); } s.push(cargo); return; }; but when I tried to access it in main() while (!s.empty()) { cout<<s.top<<"\n"; s.pop; } I got the error: 'std::stack<_Ty::top': function call missing argument list; use '&std::stack<_Ty::top' to create a pointer to member' I'm stuck. Another question to follow shortly.

    Read the article

< Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >