Search Results

Search found 1112 results on 45 pages for 'recursive'.

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

  • 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

  • Can Haskell's Parsec library be used to implement a recursive descent parser with backup?

    - by Thor Thurn
    I've been considering using Haskell's Parsec parsing library to parse a subset of Java as a recursive descent parser as an alternative to more traditional parser-generator solutions like Happy. Parsec seems very easy to use, and parse speed is definitely not a factor for me. I'm wondering, though, if it's possible to implement "backup" with Parsec, a technique which finds the correct production to use by trying each one in turn. For a simple example, consider the very start of the JLS Java grammar: Literal: IntegerLiteral FloatingPointLiteral I'd like a way to not have to figure out how I should order these two rules to get the parse to succeed. As it stands, a naive implementation like this: literal = do { x <- try (do { v <- integer; return (IntLiteral v)}) <|> (do { v <- float; return (FPLiteral v)}); return(Literal x) } Will not work... inputs like "15.2" will cause the integer parser to succeed first, and then the whole thing will choke on the "." symbol. In this case, of course, it's obvious that you can solve the problem by re-ordering the two productions. In the general case, though, finding things like this is going to be a nightmare, and it's very likely that I'll miss some cases. Ideally, I'd like a way to have Parsec figure out stuff like this for me. Is this possible, or am I simply trying to do too much with the library? The Parsec documentation claims that it can "parse context-sensitive, infinite look-ahead grammars", so it seems like something like I should be able to do something here.

    Read the article

  • Should not a tail-recursive function also be faster?

    - by Balint Erdi
    I have the following Clojure code to calculate a number with a certain "factorable" property. (what exactly the code does is secondary). (defn factor-9 ([] (let [digits (take 9 (iterate #(inc %) 1)) nums (map (fn [x] ,(Integer. (apply str x))) (permutations digits))] (some (fn [x] (and (factor-9 x) x)) nums))) ([n] (or (= 1 (count (str n))) (and (divisible-by-length n) (factor-9 (quot n 10)))))) Now, I'm into TCO and realize that Clojure can only provide tail-recursion if explicitly told so using the recur keyword. So I've rewritten the code to do that (replacing factor-9 with recur being the only difference): (defn factor-9 ([] (let [digits (take 9 (iterate #(inc %) 1)) nums (map (fn [x] ,(Integer. (apply str x))) (permutations digits))] (some (fn [x] (and (factor-9 x) x)) nums))) ([n] (or (= 1 (count (str n))) (and (divisible-by-length n) (recur (quot n 10)))))) To my knowledge, TCO has a double benefit. The first one is that it does not use the stack as heavily as a non tail-recursive call and thus does not blow it on larger recursions. The second, I think is that consequently it's faster since it can be converted to a loop. Now, I've made a very rough benchmark and have not seen any difference between the two implementations although. Am I wrong in my second assumption or does this have something to do with running on the JVM (which does not have automatic TCO) and recur using a trick to achieve it? Thank you.

    Read the article

  • Recursive breadth-first travel function in Java or C++?

    - by joejax
    Here is a java code for breadth-first travel: void breadthFirstNonRecursive(){ Queue<Node> queue = new java.util.LinkedList<Node>(); queue.offer(root); while(!queue.isEmpty()){ Node node = queue.poll(); visit(node); if (node.left != null) queue.offer(node.left); if (node.right != null) queue.offer(node.right); } } Is it possible to write a recursive function to do the same? At first, I thought this would be easy, so I came out with this: void breadthFirstRecursive(){ Queue<Node> q = new LinkedList<Node>(); breadthFirst(root, q); } void breadthFirst(Node node, Queue<Node> q){ if (node == null) return; q.offer(node); Node n = q.poll(); visit(n); if (n.left != null) breadthFirst(n.left, q); if (n.right != null) breadthFirst(n.right, q); } Then I found it doesn't work. It is actually does the same thing as this: void preOrder(Node node) { if (node == null) return; visit(node); preOrder(node.left); preOrder(node.right); } Has any one thought about this before?

    Read the article

  • How to change a recursive function for count files and catalogues?

    - by user661999
    <?php function scan_dir($dirname) { $file_count = 0 ; $dir_count = 0 ; $dir = opendir($dirname); while (($file = readdir($dir)) !== false) { if($file != "." && $file != "..") { if(is_file($dirname."/".$file)) ++$file_count; if(is_dir($dirname."/".$file)) { ++ $dir_count; scan_dir($dirname."/".$file); } } } closedir($dir); echo "There are $dir_count catalogues and $file_count files.<br>"; } $dirname = "/home/user/path"; scan_dir($dirname); ?> Hello, I have a recursive function for count files and catalogues. It returns result for each catalogue. But I need a common result. How to change the script? It returns : There are 0 catalogues and 3 files. There are 0 catalogues and 1 files. There are 2 catalogues and 14 files. I want: There are 2 catalogues and 18 files.

    Read the article

  • Apply rewrite rule for all but all the files (recursive) in a subdirectory?

    - by user784637
    I have an .htaccess file in the root of the website that looks like this RewriteRule ^some-blog-post-title/ http://website/read/flowers/a-new-title-for-this-post/ [R=301,L] RewriteRule ^some-blog-post-title2/ http://website/read/flowers/a-new-title-for-this-post2/ [R=301,L] <IfModule mod_rewrite.c> RewriteEngine On ## Redirects for all pages except for files in wp-content to website/read RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} !/wp-content RewriteRule ^(.*)$ http://website/read/$1 [L,QSA] #RewriteRule ^http://website/read [R=301,L] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> My intent is to redirect people to the new blog post location if they propose one of those special blog posts. If that's not the case then they should be redirected to http://website.com/read. Nothing from http://website.com/wp-content/* should be redirected. So far conditions 1 and 3 are being met. How can I meet condition 2?

    Read the article

  • Recursive N-way merge/diff algorithm for directory trees?

    - by BobMcGee
    What algorithms or Java libraries are available to do N-way, recursive diff/merge of directories? I need to be able to generate a list of folder trees that have many identical files, and have subdirectories with many similar files. I want to be able to use 2-way merge operations to quickly remove as much redundancy as possible. Goals: Find pairs of directories that have many similar files between them. Generate short list of directory pairs that can be synchronized with 2-way merge to eliminate duplicates Should operate recursively (there may be nested duplicates of higher-level directories) Run time and storage should be O(n log n) in numbers of directories and files Should be able to use an embedded DB or page to disk for processing more files than fit in memory (100,000+). Optional: generate an ancestry and change-set between folders Optional: sort the merge operations by how many duplicates they can elliminate I know how to use hashes to find duplicate files in roughly O(n) space, but I'm at a loss for how to go from this to finding partially overlapping sets between folders and their children. EDIT: some clarification The tricky part is the difference between "exact same" contents (otherwise hashing file hashes would work) and "similar" (which will not). Basically, I want to feed this algorithm at a set of directories and have it return a set of 2-way merge operations I can perform in order to reduce duplicates as much as possible with as few conflicts possible. It's effectively constructing an ancestry tree showing which folders are derived from each other. The end goal is to let me incorporate a bunch of different folders into one common tree. For example, I may have a folder holding programming projects, and then copy some of its contents to another computer to work on it. Then I might back up and intermediate version to flash drive. Except I may have 8 or 10 different versions, with slightly different organizational structures or folder names. I need to be able to merge them one step at a time, so I can chose how to incorporate changes at each step of the way. This is actually more or less what I intend to do with my utility (bring together a bunch of scattered backups from different points in time). I figure if I can do it right I may as well release it as a small open source util. I think the same tricks might be useful for comparing XML trees though.

    Read the article

  • Non recursive way to position a genogram in 2D points for x axis. Descendant are below

    - by Nassign
    I currently was tasked to make a genogram for a family consisting of siblings, parents with aunts and uncles with grandparents and greatgrandparents for only blood relatives. My current algorithm is using recursion. but I am wondering how to do it in non recursive way to make it more efficient. it is programmed in c# using graphics to draw on a bitmap. Current algorithm for calculating x position, the y position is by getting the generation number. public void StartCalculatePosition() { // Search the start node (The only node with targetFlg set to true) Person start = null; foreach (Person p in PersonDic.Values) { if (start == null) start = p; if (p.Targetflg) { start = p; break; } } CalcPositionRecurse(start); // Normalize the position (shift all values to positive value) // Get the minimum value (must be negative) // Then offset the position of all marriage and person with that to make it start from zero float minPosition = float.MaxValue; foreach (Person p in PersonDic.Values) { if (minPosition > p.Position) { minPosition = p.Position; } } if (minPosition < 0) { foreach (Person p in PersonDic.Values) { p.Position -= minPosition; } foreach (Marriage m in MarriageList) { m.ParentsPosition -= minPosition; m.ChildrenPosition -= minPosition; } } } /// <summary> /// Calculate position of genogram using recursion /// </summary> /// <param name="psn"></param> private void CalcPositionRecurse(Person psn) { // End the recursion if (psn.BirthMarriage == null || psn.BirthMarriage.Parents.Count == 0) { psn.Position = 0.0f; if (psn.BirthMarriage != null) { psn.BirthMarriage.ParentsPosition = 0.0f; psn.BirthMarriage.ChildrenPosition = 0.0f; } CalculateSiblingPosition(psn); return; } // Left recurse if (psn.Father != null) { CalcPositionRecurse(psn.Father); } // Right recurse if (psn.Mother != null) { CalcPositionRecurse(psn.Mother); } // Merge Position if (psn.Father != null && psn.Mother != null) { AdjustConflict(psn.Father, psn.Mother); // Position person in center of parent psn.Position = (psn.Father.Position + psn.Mother.Position) / 2; psn.BirthMarriage.ParentsPosition = psn.Position; psn.BirthMarriage.ChildrenPosition = psn.Position; } else { // Single mom or single dad if (psn.Father != null) { psn.Position = psn.Father.Position; psn.BirthMarriage.ParentsPosition = psn.Position; psn.BirthMarriage.ChildrenPosition = psn.Position; } else if (psn.Mother != null) { psn.Position = psn.Mother.Position; psn.BirthMarriage.ParentsPosition = psn.Position; psn.BirthMarriage.ChildrenPosition = psn.Position; } else { // Should not happen, checking in start of function } } // Arrange the siblings base on my position (left younger, right older) CalculateSiblingPosition(psn); } private float GetRightBoundaryAncestor(Person psn) { float rPos = psn.Position; // Get the rightmost position among siblings foreach (Person sibling in psn.Siblings) { if (sibling.Position > rPos) { rPos = sibling.Position; } } if (psn.Father != null) { float rFatherPos = GetRightBoundaryAncestor(psn.Father); if (rFatherPos > rPos) { rPos = rFatherPos; } } if (psn.Mother != null) { float rMotherPos = GetRightBoundaryAncestor(psn.Mother); if (rMotherPos > rPos) { rPos = rMotherPos; } } return rPos; } private float GetLeftBoundaryAncestor(Person psn) { float rPos = psn.Position; // Get the rightmost position among siblings foreach (Person sibling in psn.Siblings) { if (sibling.Position < rPos) { rPos = sibling.Position; } } if (psn.Father != null) { float rFatherPos = GetLeftBoundaryAncestor(psn.Father); if (rFatherPos < rPos) { rPos = rFatherPos; } } if (psn.Mother != null) { float rMotherPos = GetLeftBoundaryAncestor(psn.Mother); if (rMotherPos < rPos) { rPos = rMotherPos; } } return rPos; } /// <summary> /// Check if two parent group has conflict and compensate on the conflict /// </summary> /// <param name="leftGroup"></param> /// <param name="rightGroup"></param> public void AdjustConflict(Person leftGroup, Person rightGroup) { float leftMax = GetRightBoundaryAncestor(leftGroup); leftMax += 0.5f; float rightMin = GetLeftBoundaryAncestor(rightGroup); rightMin -= 0.5f; float diff = leftMax - rightMin; if (diff > 0.0f) { float moveHalf = Math.Abs(diff) / 2; RecurseMoveAncestor(leftGroup, 0 - moveHalf); RecurseMoveAncestor(rightGroup, moveHalf); } } /// <summary> /// Recursively move a person and all his/her ancestor /// </summary> /// <param name="psn"></param> /// <param name="moveUnit"></param> public void RecurseMoveAncestor(Person psn, float moveUnit) { psn.Position += moveUnit; foreach (Person siblings in psn.Siblings) { if (siblings.Id != psn.Id) { siblings.Position += moveUnit; } } if (psn.BirthMarriage != null) { psn.BirthMarriage.ChildrenPosition += moveUnit; psn.BirthMarriage.ParentsPosition += moveUnit; } if (psn.Father != null) { RecurseMoveAncestor(psn.Father, moveUnit); } if (psn.Mother != null) { RecurseMoveAncestor(psn.Mother, moveUnit); } } /// <summary> /// Calculate the position of the siblings /// </summary> /// <param name="psn"></param> /// <param name="anchor"></param> public void CalculateSiblingPosition(Person psn) { if (psn.Siblings.Count == 0) { return; } List<Person> sibling = psn.Siblings; int argidx; for (argidx = 0; argidx < sibling.Count; argidx++) { if (sibling[argidx].Id == psn.Id) { break; } } // Compute position for each brother that is younger that person int idx; for (idx = argidx - 1; idx >= 0; idx--) { sibling[idx].Position = sibling[idx + 1].Position - 1; } for (idx = argidx + 1; idx < sibling.Count; idx++) { sibling[idx].Position = sibling[idx - 1].Position + 1; } }

    Read the article

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