Finding a non-recursive algorithm

I had a project a year ago that was supposed to teach the class recursion. Already being familiar with the Java language, the project was simple.
The project was, you ahve a "cleaning robot" which cleans an entire room and then returns to the spot it originally was. The room was inputed as a txt file. Everytime you moved to a spot it was automatically cleaned
The Robot was given to you. The robot class hasthe following methods:
void move(Direction)   - moves in the direction you gave it.
boolean canMove(Direction)    -  returns true if the robot can move there without running into a wall
boolean hasBeen(Direction) - returns true if the robot has cleaned the spot that is in that directionThe Direction class was given to you. It is an enumerated type with the Directions FORWARD, BACWARD, LEFT, RIGHT.
now the Recursive algorithm is simple:
private void clean(Direction c, Direction r)
             move(c); //clean spot in direction
             for(Direction d : Direction.values()) //go every direction
                  if(canMove(d) && !haveBeen(d)) clean(d,reverse(d));
             move(r); //go back way we came
private Direction reverse(Direction d)
               switch(d)
                  case FORWARD:  d = Direction.BACKWARD; break;
                  case RIGHT:    d = Direction.LEFT;     break;
                  case BACKWARD: d = Direction.FORWARD;  break;
                  case LEFT:     d = Direction.RIGHT;    break;
             return d;     
public void start()
         clean(Direction.FORWARD, Direction.BACKWARD);
    }But I am curious how someone would go about implementing a NON recursive algorithm. I understand it would probably be around 2000 lines to implement it. I am not asking anyone to implement it, nor do I plan on it (well..I may one day if I am bored) I am only asking for mere curiosity how someone would go about implementing this non-recursively.
I have thought about it and thought about it, and the only thing I come up with is recursion. What are your thoughts?

then I think it'll work.Almost. Your algorithm is flawed in this section:
move(c);
      // After everything else, come back.
       backtrace.push(reverse(c));What happens when c is the reverse direction? You add to the stack the reverse of the reverse. This means you will continually go back and forth in an infinite loop. I took what you started with and worked it into a working solution:
private void cleanAll() {
          //imitate the call stack
          Stack<Stack<Direction>> call = new Stack<Stack<Direction>>();
          //holds all the reverse directions     
         Stack<Direction> backtrack = new Stack<Direction>();
         //starting stack
         Stack<Direction> start = new Stack<Direction>();
         //load the starting stack
         for (Direction d : Direction.values())
              if(canMove(d) && !haveBeen(d))
                   start.push(d);
         call.push(start);
         while (!call.isEmpty()) {
              Stack<Direction> s = call.pop();
              while(!s.isEmpty()){
                   Direction c = s.pop();
                  move(c); //clean in this direction
                  backtrack.push(reverse(c)); //record the reverse
                  Stack<Direction> temp = new Stack<Direction>();
                  call.push(s); //stop the current path
                  //load the new stack
                  for (Direction d : Direction.values())
                     if (canMove(d) && !haveBeen(d))
                          temp.push(d);
                 if(!temp.isEmpty())   
                      s = temp; //make temp the current stack
         if(!backtrack.isEmpty())
              move(backtrack.pop());// After everything else, come back.
    }The problem with your solution is that you use 1 stack for the entire process. In this case, it does not differentiate between moves, so it doesn't KNOW what is a reverse. You need to seperate the reverse directions and treat the different in the special case. In order to do that, you need to know WHEN to reverse. Well you reverse when you have completed a cleaning "path".
My algorithm implements that "path" as another stack. And adds it to a stack of stacks. What this does is it allows me to know when to reverse. I pop off a stack from the call stack, and then after I am done with that stack I have to reverse, as shown in the code I posted.
Thank you so much for enhancing my knowledge of Stacks. You have helped emensely. I will be sure to tell my professor that i implemented a iterative solution in about 50 lines of code (extremely lower than the 2000 he hypothosized)

Similar Messages

  • N-ary Trees non-recursive traversal algorithms

    Hi,
    Non-recursive traversals are needed when you are unsure how big the tree's will be. So far all the algorithms I have seen either use their own internal stack
    or threading to climb back up the tree.
    Here's my attempt that seems to work but I would value so critical evaluation
    * An extension of the CommonAST that records the line and column
    * number.  The idea was taken from <a target="_top"
    * href="http://www.jguru.com/jguru/faq/view.jsp?EID=62654">Java Guru
    * FAQ: How can I include line numbers in automatically generated
    * ASTs?</a>.
    * @author Oliver Burn
    * @author lkuehne
    * @version 1.0
    * @see <a target="_top" href="http://www.antlr.org/">ANTLR Website</a>
    public class DetailAST
        public AST getFirstChild()
        public AST getNextSibling()
        public int getChildCount()
        public DetailAST getParent()
        public int getChildCount(int aType)
        public String getText()
    }This was cut back just to give you enough info
         public static AST getLeftMostChild(DetailAST ast) {
              DetailAST tempAst = ast.getFirstChild();
              while (tempAst.getFirstChild() != null) {
                   tempAst = tempAst.getFirstChild();
              return tempAst;
         public static void traverseASTInOrder(DetailAST root) {
              DetailAST current = getLeftMostChild(ast);
              processNode(current);
              while (current != root) {
                   if (current == current.getParent().getFirstChild()) {
                        processNode(current.getParent());
                   if (current.getNextSibling() != null) {
                        DetailAST sibling = current.getNextSibling();
                        if (sibling.getChildCount() != 0) {
                             current = (DetailAST) getLeftMostChild(sibling);
                             processNode(current);
                        } else {
                             current = sibling;
                             processNode(current);
                   } else {
                        current = current.getParent();
            // do stuff at inorder traversal
         public static void processNode(AST current) {
              System.out.println(current.getText());
         }for pre-order and post-order John Cowan put forward this algorithm
    http://lists.xml.org/archives/xml-dev/199811/msg00050.html
    traverse(Node node) {
        Node currentNode = node;
        while (currentNode != null) {
          visit(currentNode); //pre order
          // Move down to first child
          Node nextNode = currentNode.getFirstChild();
          if (nextNode != null) {
            currentNode = nextNode;
            continue;
          // No child nodes, so walk tree
          while (currentNode != null) {
            revisit(currentNode)     // post order
            // Move to sibling if possible.
            nextNode = currentNode.getNextSibling();
            if (nextNode != null) {
              currentNode = nextNode;
              break;
           // Move up
           if (currentNode = node)
          currentNode = null;
           else
          currentNode = currentNode.getParentNode();
      }Any comments, criticisms or suggestions ?
    regards
    David Scurrah

    Stack is recursion? As far as I know recursion is when
    function (method) calls itself. Just using some
    Collection, which java.util.Stack implements is not
    recursion.
    Regards
    PawelStacks are used to implement recursive algorithms. What happens in most languages when you make a function call? Each function has an "activation record" where it stores its local variables and parameters. This activation record is usually allocated on a stack. Thus for any recursive algorithm, there is a non-recursive algorithm that uses a stack.
    In the OP's case you don't need a stack because of the peculiarities of tree traversal when you have a pointer to the parent node. (Namely, no cycles and you can get back to where you've been) So the algorithms he gave should work fine.
    My only "criticism" would be that it may be more useful to implement these algorithms with the iterator pattern. So you would have a tree with some functions like:
    public class Tree{
        public TreeIterator inOrderIteraror();
        public TreeIterator preOrderIterator();
    }Where the TreeIterator would look like a java.util.Iterator, except maybe you want some additional utility methods in there or something.
    Other than that, non-recursive algorithms are defnitely the way to go.

  • Recursive algorithm to find maximum

    Hi there,
    I am looking for a recursive algorithm for finding the maximum and minimum values in a double array.
    I did find the code from this forum. It works upto the size of array=200 fine.. it however just waits and waits for larger size of the array.
    The code I am using is:
    public double maxRecursive(double [] array){
    if (array.length==1){
         return array[0];
    double [] next=new double[array.length-1];
    System.arraycopy(array,1,next,0,array.length-1);
    return Math.max(array[0],maxRecursive(next));
    Could anyone help me with a better algorithm? I feel the above code is a overhaul with arraycopy as well as the recursive calls.
    Thanks for all your help!
    JP

    try this exact code, and see the output (System.out.prints). That will explain you the logic.
    public double maxRecursive(double [] array, int pos) {
         if (array.length - 1==pos) {
              System.out.println("So, I read all the elements, Final Value is :"+array[pos]+"\n");
              return array[pos];
         double recMax = maxRecursive(array, pos+1);
         System.out.println("Now I am at "+pos+" Position !!!\n");
         System.out.println("Till now my maximum value is : "+recMax+"\n");
         if(array[pos] > recMax) {
              System.out.println("My previous element is "+array[pos]+" since it is greater than my max value, here onwards, this will be my max value\n");
              return array[pos];
         else {
              System.out.println("My Previous element is "+array[pos]+" since it is less than my max value, my max value will not change\n");
              return recMax;
    }Sudha

  • Let us discussion "non recursive with clause" usage

    I think there are 3 "non recursive with clause" usage.
    My question is do you know more "non recursive with clause" usage ?

    Another option is to use it to materialize remote data on the fly. Especially in combination with the materialize hint.
    I think I used this tecnique once, but can't find the proper example anymore. Very simplified it could looked like this:
    with fetchData as (Select /*+materialize */ * from myremoteTable@databaselink where status = 'CURRENT')
    select *
    from fetchdata r
    full outer join localData l on r.id = r.id
    where l.status = 'CURRENT'
    ;From 11g onwards: use the with clause to create better column names in larger select from dual combinations.
    Not sure with that results in a suitable use case.
    So instead of
    with orders as
    (select 1 id , 173 order#, 'John' customer, 'America' region from dual union all
      select 2 id , 170 order#, 'Paul' customer, 'UK' region from dual union all
      select 3 id , 240 order#, 'Hans' customer, 'Europe' region from dual union all
      select 4 id , 241 order#, 'Francois' customer, 'Europe' region from dual )
    select * from orders;you can now write
    with
    orders (id, order#, customer,region) as
    (select 1 , 173 , 'John' , 'America' from dual union all
      select 2 , 170 , 'Paul' , 'UK' from dual union all
      select 3 , 240 , 'Hans' , 'Europe' from dual union all
      select 4 , 241 , 'Francois' , 'Europe' from dual )
    select * from orders;THis makes it a little easier to create tase data useing some excel sheet I guess.

  • HT2534 i cant find the none option show in the step 11

    i cant find the none option show in the step 11

    http://support.apple.com/kb/ht2534
    You need to follow the steps in that article exactly, in particular:
    You must download and install a free app.
    To find a free app, navigate to the Top Charts column on the right side of the App Store window. Scroll down until you see the list of Free Apps. Select any app by clicking on it. Then click Free App underneath the app icon.
    In the pop-up window, click Create Apple ID.

  • What is the non-recursive stack based equivalent of this function?

    what is the non-recursive stack based equivalent of this function?
         static void _try (int n)
              int i; if (n==4) print(); else for (i=0; i<4; i++) if (is_free(i,n)) {
                   x[n] = i;
                   _try(n+1);
         }

    It goes infinite no output. Thanks though.
    public class CopyOfDamen { // x[i] = x coordinate of queen in row i.
         static int N = 4; static Stack stack = new Stack(); static int [] x = new int[8]; public static void main(String [] par) { _try(); }
         // prints field
         static void print ()
              int i,j;
              System.out.print ("+----------------+\n");
              for (i=0; i<8; i++) {
                   System.out.print ("|");
                   for (j=0; j<8; j++)
                        if (j==x) System.out.print ("<>"); else System.out.print (" ");
                   System.out.print ("|\n");
              System.out.print ("+----------------+\n\n");
         // tests, whether (ix, iy) is beaten by queens 0...(iy-1)
         static boolean is_free (int ix, int iy)
              int i;
              for (i=0; i<iy; i++)
                   if ((x[i]==ix) || (Math.abs(x[i]-ix)==Math.abs(i-iy))) return false;
              return true;
         // tries to place queen n on row n
         static void _try () {
              int i = 0, n = 0;
    call:
              for(;;) { // forever
                   if (n == N) {
                        print();
                   } else {
                        for (;i < N; i++) {
                             if (is_free(i,n)) {
                                  x[n] = i;
                                  System.out.print(x[n] + " ");
                                  n++;
                                  stack.push(i);
                                  i = 0;
                                  continue call; // call _try (but first save state and initiate new state)
                        } System.out.println();
                   // _try returns (check termination criterion and restore state)
                   n--;
                   if (n < 0) break; // terminate
                   i = stack.pop();
    } class Stack {
         int StackSize = 32, top = 0; int [] stack = new int[StackSize]; public Stack() {} void push(int x) { if (top < StackSize) stack[top++] = x; } int pop() { if (top >= 1) return stack[--top]; return -1; }

  • HT2534 but i didn't find the NONE option on the under the card name

    but i didn't find the NONE option on the under the card name

    It is a new account that you are trying to create and you selected a free app in the store and clicked on 'create Apple id' when 'buying' it ? I tried it earlier today and it still worked for me

  • HT2534 cannot find the none option in the payment type

    cannot find the none option in the payment type

    In this article, Creating an iTunes Store, App Store, iBookstore, and Mac App Store account without a credit card,
    click on this link: Creating an account on a computer and note the instruction that you must first purchase a free app in order to proceed through the steps of finding the None option.

  • HT2534 i cannot find the none option

    I cannot create an apple account without using a credit card. I cannot find the none option when it comes to the payment issue. Can somebody please help me?

    You are following the instructions on that page exactly for creating a new account (it won't work with an existing account) e.g. selecting a free app in the store and clicking on 'create Apple id' when 'buying' it ?

  • Non-recursion-based regex

    I'm doing some heavy duty very special case regexing. If fact I have to build them programatically as the actual regular expressions can grow to over 60,000 characters in length.
    I'm doing this in 1.3.1 and have tried a couple free/open source regex packages. As one might imagine, I get StackOverflowErrors very often in every package I've tried.
    If this is such a problem with regular expressions, it seems someone would have created a Java regexp package that doesn't rely so heavily on recursion. (In fact people have, in other languages, I just haven't found one in Java).
    Anyway, my first question is: is there a Java non-recursion-based regex package out there?
    I know I can increase the stack size, but to what?! I build my regexs on the fly, and the data they operate on is also generated on the fly.
    I think an OutOfMemoryError with a non-recursive implementation would be a lot less likely that a StackOverFlowError. ???
    It's Saturday (as you can see) and it looks more and more like I may have to write/port a regex package that fits the bill. This is really a pain.
    Another possibility is to use GNU Kawa (which implements proper tail recursion) to compile a Scheme regexp implementation into something I can use from Java. This seems really convoluted.
    Any ideas?

    Indeed, a 60,000 char regex is, to be blunt,
    ridiculous. There has to be another approach to
    whatever problem you are solving (is it biological in
    nature, perchance?). It's pattern recongition of structures of objects.
    My problem is that what I would REALLY like to do boils down to "regular expressions" over an 2-dimentional array of arbitrary objects, not characters.
    As a completely inane example: 3 Strings who's length is between 7 and 19 that don't start with "foo" or "bar", followed by any number of objects implementing Runnable but not Comparable.
    I started doing this from scratch, but I thought a faster way to get things done was to cheat.
    So I created a system to translate the objects I'm interested in to a "compact" String representation, right now it's about 32 characters long. I can specify properties I'm looking for with this representation, or specify I don't care with '.' values in the fields I don't care about. So for example a lowercase e in a particular index represents non-editable, uppercase means editable, '.' means I don't care. Some field/properties require multiple characters to represent them.
    Now the patterns I'm looking for are in a 2 dimensional array of objects.
    When you start multiplying hundreds of objects by hundreds of objects by 32 characters per object ... You get a pretty big regex.
    Another option I've started is custom, from scracth "Java Object Regular Expressions" or JOREs as I like to call them (I already started coding this and needed a package name).
    (Does anything like this already exist? I haven't found it.)
    Anyway, 60,000 is bordering on worst case scenarios. It could happen. 7000-ish is a more realistic average I'd expect, but it doesn't make worst cases go away.
    It seems even in many smaller cases I get a StackOverflowError, but there are probably more nested .{,}[^]+* type things in those to make them more complex.

  • Iterative and Recursive algorithms

    I am fairly new to Java and am currently looking into Data structures, algorithms etc...
    I have designed a very basic ADT (Abstract Data Type) class called Loan which contains the following private instance variables 'loanNo, copyNo, membershipNo, dateDueBack, totalFines'.
    Basically I am trying to devise an iterative and also a recursive algorithm for calculating fines for loans not returned over a given duration. For instance if I was to assume a fixed rate of say 1% for every day the book is overdue how would I go about writing the 2 algorithms.
    Both the algorithm and elements of the java code would be appreciated or any useful articles or websites that can help me to further my limited understanding of this topic.
    All help is greatly appreciated.

    I am very far from being an expert here, but:
    Two important things come to mind;
    1. Try to keep your calculations in one file/class it is tempting to have something like the following:
    class BookTypeA
      float calculateFine()
         loanRate = 2%;
         // stuff
    // and then in another file...
    class BookTypeB
      float calculateFine()
         loanRate = 0.5%;
         // stuff
    }Every time you update the algorithm for calculating the fines, you have to change both files, trust me, someone will notice if your calculations bend a penny one way or another.
    You solve this problem by having a Visitor, there is lots of stuff on the web about the Visitor pattern. Basically:
    class Calculator implements Visitor
       public int calculate( Book book  )
          //stuff here
    class BookTypeA extends Book
       void calculateFine(  Visitor v )
          v.visit( this );
    //main{}
    for(  Book bk : myBooks  )
        bk.calculateFine( calculator );
    // etc.2. Separate your calculations into discreet functions, notice the difference in the following two "calculators"...
    class Calculator
       float getFine( int daysoverdue )
          if(  !senior )
              float result = daysoverdue * 0.01f;
              result += ( int tax = result * 0.08f );
              result += ( previousFines );
              result -= ( float seniorsdiscount = result * 0.10f );
           //etc, etc.
    // The WAY BETTER version
    class Calculator
       float getFine( int daysoverdue )
          if(  !senior )
              float baseAmount = calculateBaseFines( daysoverdue );
              float taxAmount = calculateTax( baseAmount );
              float previousFines = addPreviousFines(  );
               float subTotal = baseAmount + taxAmount + previousFines;
              float seniorsDiscount = applySeniorsDiscount(  subTotal );
           //etc, etc.
          // one calculation per function
          float calculateTax(  float baseamount )
              taxRate = 0.08;
              return baseAmount * taxRate;
          // rest of the functions
    } In short be really explicit. Really clear. Chasing tax rates through program headers, global definitions, main classes is really rough. Put the tax rate right next to the calculation. Perform one calculation per function, stuff like this; int rate += ( amount * tax ) + zot; is impossible to debug.
    Hope that helps some.
    Andrew

  • True iterative algorithm/recursive algorithm

    Just confirming that the below is a true iterative algorithm
    public static double someMethod(int n, double t)
      if (n==0)   
        totalNo = n;  
      else  
        totalNo = number;    
        for (int i = 1; i < n; i++)       
          totalNo *= somePercentage;  
      return totalNo;
    }Recursive algorithms differ in the fact that they make a call to themselves. Is this true of any algorithm that makes a call to itself i.e. if an algorithm calls itself elsewhere in the algorithm it is always a recursive algorithm???
    Regards

    Not to be confused with dominition.You mean when Sue gets out her whip and stiletto
    heels?I think it refers to a control structure I once suggested. The traditional definition of recursion doesn't hold under concurrency! It's always implied that the caller waits for the recursive call to return. If it doesn't it's not true recursion. This happens when the recursive calls are spawned off in their own threads instead of beeing pushed onto a call stack.
    I called this dominition because I used the Domino Effect as an example. A domino piece starts to fall, gives the next piece a little push and then continues falling, and so on. I got a lot of flak for it because people couldn't accept to rethink the old definition of recursion and that I also had the nerve to invent a name for it. But the idea wasn't as novel as I first thought and it's also known as recursive parallelism or fork-join.
    Anyway dominition is interesting because by synchronizing the threads you can basically get pure iteration, pure recursion and everything in between. Also when multi-processor systems become more common there's room for new design patterns in wihich dominition probably will play a part.

  • Non recursive preorder traversal of binary tree

    hi,
    I am trying to implement a non-recursive traversal of binary tree. I already know the recursive one.
    I am trying to do it by using a Stack.
    I begin by Pushing the root of an element on to a stack, and then run a while loop in which i pop an element of the stack and get its children from right to left. and push it in the same order on to the stack. So during the next iteration of my while loop the top most element gets popped and its children and pushed on to the stack in the above manner.
    but when i pop an element from a stack its popped as an object so i dont know how to access its children.
    help me i am really stuck.

    Hi, I suppose you have something like this :
    class Stack {
      public void push( Object object ) throws ... { ... }
      public Object pop() throws ... { ... }
    class Element {
      Element elem;
      stack.push(elem);
      /* because pop() method return an object of type Object
      ** if you are sure that your stack only contains Element object
      ** then you need to cast (change the type of) what the pop() method
      ** returns in this way :
      elem = (Element)stack.pop();
      ...further reading on casting will be a good idea anyway.

  • Recursive node and Non Recursive node

    Hi,
    What is the difference between Recursive node and Non Recursive node ?
    Thanks,
    Teja

    Hi Teja
    Recursive node
    If you wish to represent a recursive data structure within the context, a recursive node is the correct node to use. The simplest example of recursive data within a hierarchical structure is a file system. A dictionary can contain either files or subdirectories. This definition is then repeated for each subdirectory level down the hierarchy.
    Within the context, a recursive node is a special node that has only two properties: name and repeatedNode. As with any context node, a recursive node must itself name, but the repeatedNode property is where the recursion is defined. This property holds a reference to some parent node and indicates that, at runtime, the location of the recursive node will be occupied by a node of the type indicated in the repeatedNode property.
    You should think of a recursive node as a design time placeholder used to indicate a node will be created at this location at runtime, and will be of the type named in the repeatedNode property.
    The node name identified by repeatedNode must lie on the direct path back to the context root node.
    When a recursive node is created at runtime it always created as a non-singleton node. This is a hard-coded feature and cannot be changed.
    Non recursive node is opposite to recursive node
    Regards
    Ruturaj

  • How to find first non zero value from the numeric value or string?

    Hiii, Every body
              I have one numeric indicator in which some valuse is coming with the decimal value, lets say 0.00013, now i want to find the first non-zero value from this numeric indicator, then what should i do to do so? i have converted it in the string, but i could not find any method to find first non-zero value from that string or either from the numeric indicator????
          Can you please help me, how to do it? i have attached the vi and write all the description inside.
    Thanks in Advance,
    Nisahnt
    Attachments:
    Find first nonzero.vi ‏20 KB

    Just convert it to an exponential string and take the first character .
    Message Edited by altenbach on 05-10-2006 08:00 AM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    FisrstNonzeroChar.png ‏3 KB
    FindFirstNonzeroCharacter.vi ‏20 KB

Maybe you are looking for

  • Date/time in LR 2.1 -- still not what I expect

    Date/time of images that I scanned and input the dates outside of Lightroom are now working better, but still not what I would call correct. If I use the Library Filter, the date selection is correct under "Date". This is the date that Lightroom call

  • Impdp import schema to different tablespace

    Hi, I have PRTDB1 schema in PRTDTS tablespace, I need encrypt this tablespace. and I have done this steps: 1. I created new encrypted PRTDTS_ENC tablespace. 2. I take export PRTDB1 schema. (expdp system/system schema=PRTDB1 directory=datapump dumpfil

  • Need Active Ingredient  table field & its calculation from batch chars

    Hi All, Creating a report where Active Ingredient(AI) table field is needed. Further per batch AI content need to be determined based on AI characteristics in batch & planned value of AI in material master for a material. Please help me in finding ou

  • Password Manager only works on some websites - Chrome

    I've recently started trying to use Password Manager again, but it only works with some websites, and none of the important ones for me (where security is most important, such as banking).  On these websites I see no functionality at all: no pop-ups,

  • Reg :  Trace DML Statements

    Dear all, i want to trace out the DML Statements that are executed in database 10g in a particular period of time and independent of sessions. any one tell me that how to write a script regards Naveen Message was edited by: Sivanaveen