Iteration into Recursion

Hi ..
can someone help me turn the iteration in the code below into recursion
// Note: phone number must be input in the form #######.
// Only the digits 2 through 9 are recognized.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.IllegalFormatException;
public class Phone
   private int phoneNumber[];
   // output letter combinations to file
   public void calculate( int phoneNumber )
      String letters[][] = { { " ", " ", " " },
         { " ", " ", " " }, { "A", "B", "C" }, { "D", "E", "F" },
         { "G", "H", "I" }, { "J", "K", "L" }, { "M", "N", "O" },
         { "P", "R", "S" }, { "T", "U", "V" }, { "W", "X", "Y" } };
      int digits[] = new int[ 7 ];
      for ( int i = 6; i >= 0; i-- )
         digits[ i ] = ( int )( phoneNumber % 10 );
         phoneNumber /= 10;
      } // end for
      Formatter output = null;
      try
         output = new Formatter( "phone.txt" );
      } // end try
      catch ( SecurityException securityException )
         System.err.println(
            "You do not have write access to this file." );
         System.exit( 1 );
      } // end catch
      catch ( FileNotFoundException fileNotFoundException )
         System.err.println( "Error creating file." );
         System.exit( 1 );
      } // end catch
      System.out.println( "Please wait..." );
      try
         int loop1; // loop counter for first digit of phone number
         int loop2; // loop counter for second digit of phone number
         int loop3; // loop counter for third digit of phone number
         int loop4; // loop counter for fourth digit of phone number
         int loop5; // loop counter for fifth digit of phone number
         int loop6; // loop counter for sixth digit of phone number
         int loop7; // loop counter for seventh digit of phone number
         // output all possible combinations
         for ( loop1 = 0; loop1 <= 2; loop1++ )
            for ( loop2 = 0; loop2 <= 2; loop2++ )
               for ( loop3 = 0; loop3 <= 2; loop3++ )
                  for ( loop4 = 0; loop4 <= 2; loop4++ )
                     for ( loop5 = 0; loop5 <= 2; loop5++ )
                        for ( loop6 = 0; loop6 <= 2; loop6++ )
                           for ( loop7 = 0; loop7 <= 2; loop7++ )
                              output.format( "%s%s%s%s%s%s%s\n",
                                 letters[ digits[ 0 ] ][ loop1 ],
                                 letters[ digits[ 1 ] ][ loop2 ],
                                 letters[ digits[ 2 ] ][ loop3 ],
                                 letters[ digits[ 3 ] ][ loop4 ],
                                 letters[ digits[ 4 ] ][ loop5 ],
                                 letters[ digits[ 5 ] ][ loop6 ],
                                 letters[ digits[ 6 ] ][ loop7 ] );
                           } // end for
                        } // end for
                     } // end for
                  } // end for
               } // end for
            } // end for
         } // end for
      } // end try
      catch ( IllegalFormatException illegalFormatException )
         System.err.println( "Error in format of output." );
         System.exit( 1 );
      } // end catch
      catch ( FormatterClosedException formatterClosedException )
         System.err.println(
            "Error sending output; File has been closed." );
         System.exit( 1 );
      } // end catch
      finally
         System.out.println( "Done." );
         if ( output != null )
            output.close(); // close output stream
      } // end finally
   } // end method calculate
} // end class Phone

Heila wrote:
I know a little about recursion .. and what's commen between them is that they have a base case and a caling for thesame method with the update needed. right?Yes, but what's important about that is that it means that to solve the problem over the whole set, you solve the same problem over parts of the set and then combine the results, which means, a) You have to understand how to define the algorithm in terms of itself, and b) you have to understand what the base case is. Do you know those parts for this problem?
As an example, factorial (N!) can be defined as:
N! = N * (N - 1)! if N > 1
N! = 1 if 0 <= N <= 1
Undefiend if N < 0
So we see that the "defining factorial in terms of itself" part is N * (N - 1)!, and that the base case is when N is 0 or 1.
Now, if you're going to define "find all sequences of N values" in terms of itself, how would you do that (without Java)?

Similar Messages

  • 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.

  • Dominition - neither iteration nor recursion?

    The below thread is about how to print "Hello World" 100 times without the use of iteration or recursion.
    http://forum.java.sun.com/thread.jsp?forum=31&thread=351868
    One solution is of course to use "straight" code. Just excecute 100 print statements one after the other.
    But I think there is another solution. I've called it dominition because it resembles the domino effect. You give the first domino block a push and then they fall one after the other. It's a new control structure which is neither iteration nor recursion. This is how it looks like in code.
    public class Print extends Thread {
        private int n;
        Print (int n) {
            this.n = n;
        public void run() {
            System.out.println("Hello World");
            if (n<100)
                new Print(n+1).start();
    }It looks like recursion but I'd say it's not. The instantiation of the new Print within Print isn't completed when the call returns and this disqualifies it as a recursive call, both in the mathematical and in the programming sense.
    I'd say the call within Print to itself is a dominition call, not a recursive call! What do you say?

    import java.util.*;
    public class HelloWorld100 {
      public static int i = 0 ;
      public static void main ( String[] argv ) {
        TimerTask tt = new TimerTask() {
          public void run ( ) {
            if ( i++ >= 100 ) System.exit(0) ;
            System.out.println("Hello World: " + i) ;
        Timer t = new Timer() ;
        t.schedule(tt, 0, 1) ;
    }

  • 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

  • Do the custom rollup member formulas work recursively for parent child dimension?

    Hi
    We have custom rollup set up for Account dimension which is parent child.
    It seems to work fine when the custom member formula refers to a base account member i.e. if the formula for MemberKey4 is (MemberKey1 + MemberKey2) then it shows the sum of the underlying members 1 and 2.
    But if the formula for MemberKey10 is (MemberKey3 + MemberKey4) then it should evaluate the value for MemberKey4 first and then add to it value for MemberKey3 to come up with final number for MemberKey10.
    Do the custom rollup work fine with the recursive calculations? Is this recursion limited to some level?
    Thanks
    Shailesh

    Hi Jorg,
    Thanks for your input.
    Actually the hierarhcy is more determined by the parent child relationship. So we cannot move the members as per the formula. And further the formulas are not always additive, there are divisions and multiplactions happening also.
    Further the calculated members (account members) are used in different places, the usage level of calculated members could be 3 in some cases i.e. MemberKey15 = (calculated using MemberKey10 = (calculated using MemberKey7 = (Calculated using MemberKey4 = (calculated using base members)))). Now inserting the base members in place of a calcuated member becomes more of string manipulation.
    And on the top of above complexity, the formulas are not static and they are more user defined, they may change between time periods, which forces us to write a dynamic procedure to translate the 'business formula' into SSAS formula. We expect the custom rollup to work as expected (i.e. if the formula contains a calculation involving the calculated member, it should resolve that first and so on) and we have written generic procedure to replace the Account Code in the 'business formula' with the accont key value with the account hierarchy char string.
    In the link http://doc.ddart.net/mssql/sql2000/html/olapdmad/agmdxadvanced_6jn7.htm for AS2000, it talks about the calculation pass deapth, it says:
    .......If a cube has custom rollup formulas or custom rollup operators, a second calculation pass is performed to handle the computations needed to calculate these features.......
    Now from the above, it is obvious that the OLAP engine will automatically go into recursion if the formula contains a cacluated member and it knows that the calculated member has to be resolved first before calculating the final formula result. The above article also talks about 'Calculation Pass Number' property in the AdvanceCube Editor (AS2000), which can be set to the value depending on the expected number of passes required in a given scenario. I don't find such an equivalent peoperty for SSAS 2005.
    Would anybody please throw some more ideas / insights on this issue?
    Jorg, thanks  again for your input...
    Shailesh

  • How to get rid of StackOverflowError in recursion!!

    Hello everyone,
    I am getting the StackOverflowError in my program when I do recursion. One of my function calculates the regions in an Image using the 8-based connectivity principles. I tried it on small example image grids of size less than 47 and it workd (I did it with small sizes to debug the program!) Now, when I found it works, I tried it for jpegs of sizes 384x256 and it simply crashes in recursion.
    My function caluclated the region for a single pixel, goes into recursion for its neightbouring 8 pixels,and so on... the program stack begins to unwind only at the end when all the pixels are considered, thus laying heaps of function records on top of the stack till it all "should" eventually disappear.
    I even tried something like this
    java -Xmx128m fuzzynmoments.java on my Windows machine but to no avail.
    I would REALLY appreciate ANY help.
    Please reply with your suggestions at the earliest.
    Thank you,
    Sandeep

    Recursion is bad, mmkay?
    Unless you can grow the stack in someway (I'm not familiar with the parameters for javac), it's pretty much a lost cause.

  • Scroll for an af:iterator component

    Hi,
    I have an af:iterator into an af:menu component with the rows attribute set to -1. How can i display the af:iterator list into a scrollable component with a fixed height?
    By default the component displays all its items and introduces a vertical scroll to the page, not to the component itself.
    Thank you

    Hi,
    I want to keep my af:iterator component bound to an af:menu. If I introduce a panel group layout inside the af:menu and inside the panel group my af:iterator, when I press the menu component it is rendered firstly the panel group layout empty with the specific height and then the menu items from the af:iterator.
    Thanks.

  • Recursive Infix to Postfix algorithm (Shunting-yard algorithm)

    Hi, I have to write a Infix to Postfix algorithm in a recursive form. I have an idea of how to do it iteratively using a Stack, but recursively I'm having some trouble. Could anybody offer some help or hints on how to get started?

    Well, I could write the iterative version along the lines of this:
    Scanner inScan = new Scanner(System.in);
    String exp;
    StringBuffer postfix = new StringBuffer();
    Stack stk = new Stack<Character>();
    System.out.println("Enter an arithmetic expression: ");
    exp = inScan.nextLine();
    for(int i = 0; i<exp.length(); i++)
        char ch = exp.charAt(i);
        if(ch<='F' && ch>='A')
            stk.push(ch);
        else{
           switch(ch)
              case '+':       \\what to do if ch is a + operator
              case '*':        \\what to do if ch is a * operator
              case '(':        \\what to do if ch is a (
              // and so on for each operator or paranthesis, i know what to do with each operator
    }That's not the full program obviously and may have some mistakes, but I'm confident I know how to do it iteratively. Recursively is the problem. What kind of base case could I use for my recursive method? And do I need more than one recursive method?

  • Please help me fill in the blank

    Our own �innovative� Chunk Sort algorithm is designed for sorting arrays that consist of a few presorted chunks. The idea is to find the next chunk and merge it with the already sorted beginning segment of the array. We will implement this algorithm iteratively, without recursion.
         Fill in the blanks in the following merge method:
    * Precondition: 0 <= m <= n
    * m == 0 or a[0] <= ... <= a[m-1]
    * n == m or a[m] <= ... <= a[n-1]
    * Postcondition: the values a[0] .. a[n-1] are arranged
    * in the ascending order
    private static void merge(int a[], int m, int n)
    // If any of the two segments is empty, do nothing:
    int i = 0, j = m; // starting indices into the two segments
    // Allocate a temporary array temp to hold n elements
    int k = 0; // starting index into the temporary array
    while (i < m && j < n)
    if ( ______________________ )
    else
    k++;
    // Copy remaining elements:
    while (i < m)
    k++;
    while (j < n)
    k++;
    // Copy temp back to a:
    for ( _____________________________________ )

    Your teacher needs to teach you to Teach
    Yourself[b]. People can't always tell you the answer
    to everything. There comes a time in life when you
    just have to break down and fire up that brain cell.
    Not quite, you need at least two neurones to make a synapse. Unless, we talking about extrapyramidal pathways. Then termination on peripheral skeletal muscle is what is going on. Certainly, that is required in this case as the OP doesn't appear motivated enough to pick up a book.

  • Permutations of non-sequential string in C

    Hi,
    I'm just learning C now and am trying to get my head around this permutation pickle I'm in.  I can pretty simply write code that will give all permutations of N number of letters from A-z.  E.g., if N = 4, it will print out AAAA AAAB .... zzzz. This is pretty simple iteratively or recursively with a counter.
    now, however, I want to enter in a string that does not neccessary contain letters in sequence, and find all the possible relevant permutations of that string.  E.g. I input a string of BEHP, and  I want to find all the permutations of this combination.  I don't want BBBB, BBBE, etc., I want BEHP, BHPE, BPHE, etc. 
    I think my current approach is severely limited by the counter method, as it's giving permutations that are just not relevant.
    Also, can someone please confirm the maths on this.  If I have a string of 3 letters, ABC, the number of possible combinations is 3! right? 3 factorial?
    Thanks

    I don't know C, but have a couple of logic-based suggestions.  I believe you are right in your permutations calculation of 3!.  To solve your problem of combinations, could you do something like put each character into an array (which is ordered by index) and then use a similar technique to the one you used for the other set of letters but base it on the index number?

  • Oraxsl command line utility - xslt transform difficulty

    I am having trouble understanding the documentation for the ORAXSL command line utility interface, as follows:
    I have two sheets [XSLT transformation sheets], token.xsl and loop.xsl, which I am trying to transform into a single xsl sheet using ORAXSL command line.
    token.xsl transforms a string of comma-separated values into single tokens (<value> elements, each of them contains one value).
    loop.xsl expands special iteration elements (<loop:for> and <loop:while>) into recursive template calls.
    Used together, I can parse a node containing comma separated values into an xml document with each value in its own node.

    Hi
    This is very simple (to the best of my knowledge)
    sqlplus userid/password@hoststring @pl_sql_file_name.ext [arg1] [arg2] [arg3]
    sqlplus - to invoke oracle
    userid - is the login id into oracle db
    password - is the password
    hoststring - is the ORACLE_SID
    pl_sql_file_name.ext - is the pl_sql file you wish to run
    arg1, arg2, arg3 - the arguments that you may be refering in the pl_sql script. arg1 refers to &1 in your script and arg2 refers to &2 in your script and arg3 refers to &3 in your script.
    Have fun!
    Good Luck
    null

  • What is Continuations? what is the advantage of Continuations?

    http://www.cs.cornell.edu/courses/cs3110/2012sp/recitations/rec26-cps/rec26.html
    what is Continuations? what is the advantage of Continuations when compare with iterative and recursive?
    if i stop running the program, can Continuations style help to run at the last running point?
    computing nightmare

    Tail recursion is when a recursive call is the last piece of evaluation done.  So
    let rec len l =
    match l with
    | [] -> 0
    | x:xs -> 1 + len xs
    is recursive, but not tail recursive, because there's still the addition to do after the recursion returns, whereas here
    let len l =
    let rec len' l n =
    match l with
    | [] -> n
    | x: xs -> len' xs n+1
    len' l 0
    len' is tail-recursive.
    As there's nothing to left do in the current call when the recursive call is made, then the compiler can optimize the code to re-use the stack frame.
    This is the simplest way to provide for unbounded repetition of an action with immutable state, passing updated state into the recursive call.
    Tree-like structures, on the other hand have a left descent then a right descent and you can't make both the tail, because you have to return from one to do the other.  So that's where continuation passing moving the accumulation from the stack to the
    heap can ameliorate the problem.

  • 'unbounded' java factorial question

    during a recent job interview I was given a java assessment test and asked to write a code fragment to calculate factorials.
    The tech lead then walked through the code with me and questioned how I would write the fragment
    'unbounded' by an int, long or double type.
    He mentioned the phrase 'max value' somewhere, but I don't understand the solution he was looking for.
    do any java gurus understand the question? can you provide a code fragment that meets this requirement?
    I've seen the typical code samples using an int type as the input number.
    Thanks in advance for your help.

    user13537476 wrote:
    during a recent job interview I was given a java assessment test and asked to write a code fragment to calculate factorials.
    The tech lead then walked through the code with me and questioned how I would write the fragment
    'unbounded' by an int, long or double type.
    He mentioned the phrase 'max value' somewhere, but I don't understand the solution he was looking for.He was probably asking what you would do if the result were bigger than Integer.MAX_VALUE, Long.MAX_VALUE, etc. Factorial grows very fast, so even a modest input can have a result that's too large to fit in those types.
    do any java gurus understand the question? can you provide a code fragment that meets this requirement?I can't speak to what the interviewer was looking for, but if it were me, I'd use BigInteger.
    I've seen the typical code samples using an int type as the input number.That would be sufficient to show the general approach, whether iterative or recursive, but it will only work for small values. If I recall, 12! is the largest factorial value that will fit into an int. You can use the same approach with BigInteger.

  • When I open a new window, the spinner does not stop, or the window open

    I have a MBP 3 yrs. old, running Snow Lep. When I open a new window, the spinner in the address bar spins and window does not open unless I click on the X and stop the spinner. Some times this doesn't work either. It just hangs up trying to open the next window.

    The given are very little details about your problem so please elaborate. 
    2. on each page load you have to verify whether the session variable. if "IsLoggedIn" exists and its value is "true" then you can show the requested page otherwise redirect to login page.
    if(Session["IsLoggedIn"] == null || Session["IsLoggedIn"] != "true")
    Response.Redirect("login.aspx");
    Better way: use a master page. In the load_page event, check the session. Thus, you wouldn't need to write the method to check in every page, just in the master page.
    Noam B.
    Do not Forget to Vote as Answer/Helpful, please. It encourages us to help you...
    Masterpage is a better idea.
    But The login page shouldn't use MasterPage OR need to have logic to check before redirecting to login page if you are already in Login page.
    Otherwise you will get into Recursive Redirection error.
    hope this helps.

  • Problem in generic value copier class / reflection and generic classes

    Hello experts,
    I try to archive the following and am struggling for quite some time now. Can someone please give an assessment if this is possible:
    I am trying to write a generic data copy method. It searches for all (parameterless) getter methods in the source object that have a corresponding setter method (with same name but prefixed by "set" instead of "get" and with exactly one parameter) in the destination object.
    For each pair I found I do the following: If the param of the setter type (T2) is assignable from the return type of the getter (T1), I just assign the value. If the types are not compatible, I want to instantiate a new instance of T2, assign it via the setter, and invoke copyData recursively on the object I get from the getter (as source) and the newly created instance (as destination). The assumption is here, that the occurring source and destination objects are incompatible but have matching getter and setter names and at the leaves of the object tree, the types of the getters and setters are compatible so that the recursion ends.
    The core of the problem I am struggling with is the step where I instantiate the new destination object. If T2 is a non-generic type, this is straightforward. However, imagine T1 and T2 are parametrized collections: T1 is List<T3> and T2 is List<T4>. Then I need special handling of the collection. I can easily iterate over the elements of the source List and get the types of the elements, but I can not instantiate only a generic version of the destinatino List. Further I cannot create elements of T4 and add it to the list of T2 and go into recursion, since the information that the inner type of the destination list is T4 is not available at run-time.
    public class Source {
       T1 getA();
       setA(T1 x);
    public class Dest {
       T2 getA();
       setA(T2 x);
    public class BeanDataCopier {
       public static void copyData(Object source, Object destination) {
          for (Method getterMethod : sourceGetterMethods) {
             ... // find matching getter and setter names
             Class sourceParamT = [class of return value of the getter];
             Class destParamT = [class of single param of the setter];
             // special handling for collections -  I could use some help here
             // if types are not compatible
             Object destParam = destination.getClass().newInstance();
             Object sourceParam = source.[invoke getter method];
             copyData(sourceParam, destParam);
    // usage of the method
    Souce s = new Source(); // this is an example, I do not know the type of s at copying time
    Dest d = new Dest(); // the same is true for d
    // initialize s in a complicated way (actually JAX-B does this)
    // copy values of s to d
    BeanDataCopier.copyData(s, d);
    // now d should have copied values from s Can you provide me with any alternative approaches to implement this "duck typing" behaviour on copying properties?
    Best regards,
    Patrik
    PS: You might have guessed my overall use case: I am sending an object tree over a web service. On the server side, the web service operation has a deeply nested object structure as the return type. On the client side, these resulting object tree has instances not of the original classes, but of client classes generated by axis. The original and generated classes are of different types but have the identically named getter and setter methods (which again have incompatible parameter types that however have consistent names). On the client side, I want to simply create an object of the original class and have the values of the client object (including the whole object tree) copied into it.
    Edited by: Patrik_Spiess on Sep 3, 2008 5:09 AM

    As I understand your use case this is already supported by Axis with beanMapping [http://ws.apache.org/axis/java/user-guide.html#EncodingYourBeansTheBeanSerializer]
    - Roy

Maybe you are looking for