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

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.

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

  • Iterative signal processing algorithms in Labview

    Hi
    I am learning to program in Labview. I am trying to program an iterative algorithm in Labview and I am having difficultires. It is a short algorithm and thought that perhaps someone with Labview experience may be able to show me the way. Here I describe the algorithm:
    I have data in an I by K matrix A where i are the samples (rows) and k the variables (columns). For n number of runs, n = 1,2,...N need to compute u(subscript n) and r(subscript n) from A(subscript n-1). (Note that u is vector of length i and r is a vector of length k). Results are obatined for each run, n, iteratively by improving on estimates of u and r.
    First I need to select start values for u(subscript n) in the first iteration of the algorithm. These start values can be any one of the columns of A. Then I want to repeat the following steps (1 to 5) until convergence:
    (Note that ' represents transpositionof vector /matrix; ^ represents power)
    1. Improve estimate of r(subscript n) by:
    r(subscript n) = [u(subscript n)' u(subscript n)]^-1 u(subscript n)' A(subscript n-1)
    2. Scale length of r(subscript n) to 1.0 by:
    r(subscript n) = r(subscript n) [r(subscript n)' r(subscript n)]^0.5
    3. Improve estimate of u(subscript n) for this run by:
    u(subscript n) = A(subscript n-1) r(subscript n) [r(subscript n)' r(subscript n)]^-1
    4. Imprve estimate of tee(subscript n) by:
    tee(subscript n) = [u(subscript n)' u(subscript n)]
    5. check for convergence: if tee(subscript n) minus tee(subscript n) in the previous iteration is smaller than say e.g. 0.00001 times tee(subscript n), the method has converged for this run, if not, go to step 1.  
    The Substract the effect of this run:  A(subscript n) = A(subscript n -1) - u(subscript n) r(subscript n)'    and then go to the start for the next run.
    I have tried to do this with shift registers but the problems I am having aare to do with the start values for u and the iterative updating...
    I hope someone can help. I know that MAth script is probably the best way to do this but I don't yet have it and would like to do it in the block diagram with Labview vi for math.
    Cheers,

    for anyone trying to help me...i worked it out. Perseverance is certainly good!

  • 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

  • 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) ;
    }

  • What is difference between Iterator and Collection Wrapper?

    Hi all,
                  I dont understand the actual difference between Iterator and Collection Wrapper. I observed both are used for the same purpose. Could any one please let me know when to use Collection Wrapper and when to use Iterator??
    Thanks,
    Chinnu.

    L_Kiryl is right.
    Collections support global iteration (through collection->get_next( )) and local iteration (through iterator->get_next( )).
    Each collection has a focus object. Initially, the first object has the focus.
    Any global iteration moves the focus, which is published by the event FOCUS_CHANGED of the collection.
    If you want to iterate on the collection without moving the focus (and without triggering timeconsuming follow-up processes) you can use local iteration. To do so, request an iterator object from the collection and use this to iterate.
    And one more advantage of using iterator: it takes care of deleted entities. If you use global iteration then when you reach deleted entity it will be an exception. But there is no exception with iterator in the same situation.

  • Approximate operator and recursive call function in abap

    Dear expert,
    Please give me an example about Approximate operator and recursive call function in abap
    thanks so much

    Hi
    About Approximate operator, you can go to tcode 'ABAPDOCU', searching CO,CN,CA etc...each of them have example there.
    And recursive function,
    Say here is a FM,
    FUNCTION recursive_get_number.
    *import im_num type i.
    *export ex_num type i.
    ex_num = im_num + 1.
    IF ex_num GE 100.
       EXIT.
    ELSE.
       CALL FUNCTION recursive_get_number
            EXPORTING
               im_num = ex_num
            IMPORTING
               ex_num = ex_num.
    ENDIF.
    ENDFUNCTION.
    When you call this function from outside with importing parameter '1',  then will return you 100.
    regards,
    Archer.

  • Change the current row in an iterator and reflect the change on page

    Hi there,
    I have a jspx with a creation form created as usual draging and droping the data control. In same page, I inserted a commandButton which ActionListener executes a method in a managed bean called validate(). Through such a method what Im trying to do is to fill the form with data from specified entry of the database if certain condition is true. I know it is kinda twisted but unfortunately is the requirement for the page.
    So basically in "validate" method, if the condition I mentioned is reached, I do the following:
    // execute a Rollback (included in Page Definition) in order to cancel the previous auto-invoked "Create".
    FacesContext context = FacesContext.getCurrentInstance();
    Application app = context.getApplication();
    BindingContainer bindings =(BindingContainer)app.getVariableResolver().resolveVariable(context,"bindings");
    OperationBinding opBinding = bindings.getOperationBinding("Rollback");
    opBinding .execute();
    //get the iterator and asociated VO from the binding container
    ValueBinding vb = app.createValueBinding("#{bindings.AccountsVOIterator}");
    DCIteratorBinding dciter = (DCIteratorBinding) vb.getValue(FacesContext.getCurrentInstance());
    ViewObject view = dciter.getViewObject();
    //and set the current row with the specified entry I have mentioned above.
    Object keyValues[] = new Object[2];
    keyValues[0] = "1"; keyValues[1] = "98543";
    Row[] row = view.findByKey(new Key(keyValues),1);
    AccountsVpnVORowImpl client = (AccountsVpnVORowImpl)row[0];
    view.setCurrentRow(client);
    view.executeQuery();
    dciter.setCurrentRowWithKey(client.getKey().toStringFormat(true));
    dciter.executeQuery();
    opBinding = bindings.getOperationBinding("Execute");
    opBinding.execute();
    All this works perfectly when I debbug it but I cannot see the changes in the page(even refreshing browser). I need that when such a condition is met, the creation form turns into a modify-specific entry form, filling all fields with the specific data in order user can modify it, and all in the same page.
    Any clue?
    Thanks so much in advance for your time.

    Hi,
    I could see the problem with call to executeQuery and execute methods at the end of your method which re-sets the current row.
    Once you set the current row you should not call execute or executequery methods. Try removing those calls and also make sure that you have added partialTriggers property on the table is set to commandbutton id and partialSubmit property is set to true on commandButton to refresh the table partially on click of a button
    Sireesha

  • System cryptography: Use FIPS compliant cryptographic algorithms, including encryption, hashing and signing algorithms

    Hi,
    I have enabled FIPS compliant algorithms,including encryption, hashing and signing algorithms in (Windows server 2012 R2 ), after enabling. My SSIS package is not working and i am not able open my SSRS also.
    So can any one assist in this.
    Surendran.G
    Regards, Surendran.G

    Hi,
    in latest security recommendation guides it is no longer recommended to use this setting (because it breaks a lot of stuff...).
    http://blogs.technet.com/b/secguide/archive/2014/04/07/why-we-re-not-recommending-fips-mode-anymore.aspx
    Consider turning it off if  you do not have strict resuirements for it.
    otherwise, You will have to investigate you code. SQL server forums would be the appropirate place to get help in troublesooting your code.
    MCP/MCSA/MCTS/MCITP

  • How to clear rows from iterator and re-fetch fresh data from the table ?

    Hi,
    I am using JDev 11.1.1.2.0
    I have generated JPA Service Facade and by using it, I have created Data Control which finally I have dragged & dropped on my .jsff file.
    In viewObject, there is a method clearCache() to clear the viewObject data.
    Iterator has also one method clear() but when it invoked, ADF framework throws StackOverFlow error.
    So, I want to clear my iterator before calling executeQuery() method.
    How Can I clear it ?
    Because In my case if I run executeQuery() method on DCIteratorBinding, it is not getting updated with the lates value from DB table.
    So I want to clear all the rows from iterator and then want to call executeQuery() method to updated latest data from DB tables.
    I have also tried below peace of code to refresh iterator but still iterator getting updated with two same rows () while in DB it is proper.
    FacesContext fctx = FacesContext.getCurrentInstance();
    ValueBinding dcb =
    fctx.getApplication().createValueBinding("#{bindings}");
    DCBindingContainer iteratorbindings =
    (DCBindingContainer)dcb.getValue(fctx);
    DCIteratorBinding dciter =
    iteratorbindings.findIteratorBinding(<iteratorname>);
    dciter.releaseData();
    dciter.executeQuery();
    dciter.refresh(DCIteratorBinding.RANGESIZE_UNLIMITED);
    regards,
    devang

    Hi,
    Have you try to drag and drop to your refresh or query button an "Execute" operation from the Data Control Pallete?
    We are using JPA/ EJB Session Beans and that works for us.
    regards,
    pino

  • Hi,    In my view, all divide and conquer algorithms have Oefficiency doubt

    Hi,
    In my view, all divide and conquer algorithms have O(n log n) . But is there anyway to have a divide and conquer algorithm without the O(log n) factor?
    Do reply..
    Thanks

    ricardo_reli
    Welcome to the forum. Please don't post the same question more than once.
    I'm locking this thread now. The discussion can continue at
    [http://forums.sun.com/thread.jspa?threadID=5342725]
    db

  • Difference between af:iterator and af:foreach

    guys,
    whats the difference between af:iterator and af:foreach ?

    The documentation for af:iterator describes the differences:
    http://jdevadf.oracle.com/adf-richclient-demo/docs/tagdoc/af_iterator.html
    While the <af:forEach> will be sufficient for most user's needs, it does not work with a JSF DataModel, or CollectionModel. It also cannot be bound to EL expressions that use component-managed EL variables (such as the >"var" variable on an <af:table>). The <af:iterator> tag was created to address these issues. Thanks,
    Navaneeth

  • The demand of my application is that i can not replace for loop with a while loop.because i need fixed number of iterations and as far as i know fixed iterations could be only with possible with the for loop.

    the demand of my application is that i can not replace for loop with a while loop.because i need fixed number of iterations and as far as i know fixed iterations could be only with possible with the for loop.
    your recommended second option that i could add true/false case.
    this true/false case must be inside the for loop or outside the for loop?if this case is inside the for
    loop, how can i send stop command from outer while
    loop?
    more over do you have any example for this please?
    thanks"

    You can execute a fixed number of iterations using a while loop by comparing the iteration count to the number of iterations you want and wiring the output of that comparison (e.g. Less Than or Equal To) to the continue (or stop) terminal of your while loop. Which comparison you use depends on personal preference, where you wire the desired count and the interation count, and whether you're using the while loop as Continue if True or Stop if True.
    Ben gave you step-by-step instructions in response to your previous question. Look here for Ben's response.
    Ben's response looks pretty good and detailed to me. It certa
    inly deserved better than a 1-star rating.

  • Modifying existing recursive algorithm to an iterative version

    Hi,
    I find myself wanting to modify the algorithm below to an iterative version or possibly one thats tail recursive because I'm getting stack overflow errors with the input i present my program. Can someone help me break this down? I've tried several approaches, and I seem to get stuck each time, not being able to express what I want appropriately without using recursion.
            public void visitAll(HeapItem hi) {
                HeapItem refs[] = hi.getReferences();
                HeapItem item;
                int i;
                hi.visited = true;
                for (i = 0; i < refs.length; ++i) {
                    item = refs;
    if (item != null && !item.visited)
    visitAll(item);

    You should do something like this...
    public void visitAll(HeapItem hi) {
                HeapItem refs[] = hi.getReferences();
                HeapItem item;
                int i;
                if(refs.length == 0) return;
                hi.visited = true;
                for (i = 0; i < refs.length; ++i) {
                    item = refs;
    if (item != null && !item.visited)
    visitAll(item);

Maybe you are looking for

  • How do I set a PFI to High on a 6602 Board with DAQ Traditional

    Dear All, I am using LabVIEW 8.5 on 32-bit Windows XP with an NI 6602 DAQ board. In the past I've used DAQmx but for compatability with older software I need to do a few simple things using Traditional DAQ, which I have never used. Specifically I wou

  • How to implement drop down list in WDP Abap....very urgent...please help me

    Hi Gurus, I wanted to implement the drop down list button in the WDP Abap interactive form. Once the users clicks on the drop down button, an RFC should be called and display the details under the drop down button. Please give me the logic with code.

  • FS-CD Queries

    Hello I am new to FS-CD and have some queries which are : 1. Nominees are covered where? Will system be able to disburse check to them once the holder deceases? 2. Group Mediclaim Policy- Corporate/Person? How does it work in system? 3. Broker and Co

  • Automatic start of dbconsole during boot

    Is there an easy way to automatically start the dbconsole when a cluster node boots (unix) ? I don't mean putting "emctl start dbconsole" in a rc Skript. I would prefer an integration in clusterware.

  • Java.lang.reflect.InvocationTargetException on FCS Client start

    Hi, I've searched the Google and elsewhere but I haven't been able to find out about this error - java.lang.reflect.InvocationTargetException The client downloads and installs fine. Then when it starts, it asks for a certificate verification and then