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

Similar Messages

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

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

  • How to modify existing concurrent program

    I want to edit and modify existing pl/sql concurrent program.
    what are the steps required to do this?

    Hi,
    Pls keep in mind that modifying standard programs is not advisable. You will get SPAU (http://help.sap.com/saphelp_nw2004s/helpdata/en/c8/61ec66e33611d1954b0000e82de14a/frameset.htm) when you upgrade your SAP system. Try to make an own version and include as much as possible from the standard program.
    Eddy

  • Modify existing Message

    Hi all,
    I need to change text/html part of message which I have in mail format. How to do this easily without loosing other parts of message?
    Or maybe you know some better way to create kind of simple proxy for SMTP which would add and replace some text in HTML part of email?
    So far I am reading message from plain stream of mail text representation (got it from Subethamail SMTP server) into JavaMail Message object. I had problem, when my changes to message were not reflected - I posted question on http://stackoverflow.com/questions/7674775/how-to-modify-existing-java-mail-mimemessage-body-parts/ and solved this one by calling message.saveChanges();
    The issue is that when I call message.saveChanges() headers seams to be lost - especially those around Content Type and Charset.
    My code looks like this:
    public void resend(InputStream data) throws Exception {
            Transport transport = mailSession.getTransport();
            MimeMessage message = new MimeMessage(mailSession, data);
            Object content = message.getContent();
            if (MimeMultipart.class.isAssignableFrom(content.getClass())) {
                MimeMultipart mimeMultipart = (MimeMultipart) content;
                for (int i = 0; i < mimeMultipart.getCount(); i++) {
                    MimeBodyPart bodyPart = (MimeBodyPart) mimeMultipart.getBodyPart(i);
                    if (bodyPart.getContentType().startsWith("text/plain")) {
                        String cnt = updateContent((String) bodyPart.getContent());
                        System.out.println("ContentType = " + bodyPart.getContentType());
                        System.out.println("Content = " + cnt);
                        String contentType = bodyPart.getContentType();
                        System.out.println("Updating content type to = " + contentType);
                        bodyPart.setContent(cnt, contentType);
                    } else if (bodyPart.getContentType().startsWith("text/html")) {
                        String cnt = updateContent((String) bodyPart.getContent());
                        System.out.println("ContentType = " + bodyPart.getContentType());
                        System.out.println("Content = " + cnt);
                        String contentType = bodyPart.getContentType();
                        System.out.println("Updating content type to = " + contentType);
                        bodyPart.setContent(cnt, contentType);
            } else {
                String cnt = updateContent((String) message.getContent());
                System.out.println("ContentType = " + message.getContentType());
                System.out.println("Content = " + cnt);
                String contentType = message.getContentType();
                System.out.println("Updating content type to = " + contentType);
                message.setContent(cnt, contentType);
            message.saveChanges();
    }Mark on Stackoverflow suggested that problem is in bodyPart.setContent(cnt, contentType); call...
    Hope that makes sense for you... and you will be able to help me...
    Thanks in advance
    Konrad
    Edited by: 890134 on 2011-10-07 08:29

    JavaMail wasn't really design to support "editing" of existing messages.
    That's caused some problems over the years and I've had to fix a number
    of bugs in this area. The current version (1.4.4) definitely works better
    than older versions, but I won't be surprised if there are still bugs.
    Even so, your code is making a number of invalid assumptions about the
    structure of messages. I would suggest looking at the msgshow.java
    demo program. It includes code that visits all the parts of a message.
    It should be straightforward to extend that code to detect the parts you
    want to modify and to change the content of those parts using the
    setContent (or setText) method.
    If it's still not working for you, provide more detail about what you're doing,
    including a same message. (Send the details to me at [email protected]
    if you prefer.)

  • Updates are not installing already exists, will modify existing instance.

    hi all
    I have  published updates via scup and seeing below message in update store log its  not updating old version what is this message means
    Update status from update (c2f61a88-730e-47af-8119-6e3b5a789764) already exists, will modify existing instance.
    ankith

    That just means that the client already scanned for compliance, scanned again now and found out that the state for that patch (installed, required, etc) has changed.
    Torsten Meringer | http://www.mssccmfaq.de

  • Create job and modify existing jobs in OM

    Dear all
    how to create job and modify existing jobs in OM?
    thanks
    Jeeva

    […] (as I understand it), pdf's are not a viable solution as these print jobs feature a very high resolution (1200 dpi).
    I would expect the output from Finale to be mostly in the form of font characters—so a PDF you create by printing-to-file should be resolution-independent. If you have +Adobe Acrobat+, that can be verified quite easily in Document Properties, which will list all embedded fonts, but you should also be able to tell by zooming ’way in with Preview: if the score still looks sharp when greatly enlarged (and the file takes up less than a few hundred kilobytes per page), you can be sure it will print well on any suitable device. (If you print-to-file as PostScript instead of PDF, the resulting document can be downloaded directly into any PS printer, but it will likely be several times larger than a PDF version.)

  • ERROR ITMS-9000:"Redundant Binary Upload. There already exists a binary upload with build version '1.1' for ipa '1.1'".

    ERROR ITMS-9000:"Redundant Binary Upload. There already exists a binary upload with build version '1.1' for ipa '1.1'".
    I need to change the build number, but not the version number. So I can upload a new build for same version to ITC. What step should I do in FB4.7?

    Hi mobisa,
    Can you try the solution in this post? ios - ERROR ITMS-9000: "Redundant Binary Upload. There already exists a binary upload with build version '1.0' for train…
    Thanks,
    Preran

  • Problem in modifying existing records in dbtab

    Hi Experts,
    I am doing a report where I have created two dbtab's , one for data getting saved and
    other for fetching data and modifying exsiting records..
    For eg - let ZABC be the table where I need to insert or update records and ZXYZ is the table where
    I need to fetch and modify existing records.
    Now my probelm is :
    In case of inserting new records (multiple records ) into my dbtab ( ZABC ) its working ,
    but modifying existing records in another dbtab (ZXYZ ) its not wroking !! plz advice !!
    If my select querry for modifying exsiting records is:
    SELECT *  FROM ZXYZ  INTO TABLE ITAB WHERE MATNR EQ S_MATNR.
    *****then its inserting a newline along with the existing records.
    but when my querry is,
    SELECT single *  FROM ZXYZ  WHERE MATNR EQ S_MATNR.
    then its modifying the existing records, but only the first record.
    Loop at itab.
    if sy-tabix  = 1.
    zabc-matnr = matnr.
    zabc-idnrk  = idnrk.
    zabc-budat = s_budat.
    zabc-menge = menge1.
    ZXYZ-menge = ZABC-Menge + MENGE1.
    ZXYZ-BALC  = ZXYZ-Menge   -   MENGE1.
    ELSEIF sy-tabix  = 2.
    zabc-matnr = matnr.
    zabc-idnrk  = idnrk.
    zabc-budat = s_budat.
    zabc-menge = menge2.
    ZXYZ-menge = ZABC-Menge + MENGE2.
    ZXYZ-BALC  = ZXYZ-Menge  -  MENGE2.
    ELSEIF sy-tabix  = 3.
    zabc-matnr = matnr.
    zabc-idnrk  = idnrk.
    zabc-budat = s_budat.
    zabc-menge = menge3.
    ZXYZ-menge = ZABC-Menge + MENGE3.
    ZXYZ-BALC  = ZXYZ-Menge   -  MENGE3.
    ENDIF.
    INSERT ZABC.
    IF SY-SUBRC EQ 0.
    MODIFY ZXYZ.
            IF SY-SUBRC = 0.
              MESSAGE : I002 WITH 'RECORD CREATED'.
                ENDIF.
    ENDIF.
    Please advice
    Karthik
    Edited by: Karthik R on Aug 24, 2009 9:42 PM

    Hi,
    This is because in the second case you are not selecting records into an internal table.
    As a result only the first record which satisfies the where condition is fetched.
    Check if the program goes into the loop when you write second select query.
    KR Jaideep,

  • How to modify existing code of SQVI report?

    Hi Expert,
       There is a SQVI report which has already been created but we need to change the one for new requirement.
    is there any way to modify existing code for new requirement?
    Can we edit in abap workbench?
    Thanks & Regards
    Savita

    Savita,
    You can not modify SQVI system generated code. You need to go to SAVI change mode and make modifications. If your requirement is a sort of additional fields or inserting come code into the program , then SQVI is not the choice. You need to use Infoset Queries (SQ03, SQ02, Sq01).
    KJogeswaraRao

  • How to modify existing enhancement?

    I have requirement which require to modify existing enhancement.
    What are the steps involved to modify enhancement?
    thanks

    Hi,
    Check
    https://www.sdn.sap.com/irj/sdn/nw-development?rid=/webcontent/uuid/2342e1f3-0b01-0010-a186-fdd404884050#section19
    http://help.sap.com/saphelp_nw04/helpdata/en/6b/3f6d016d0711d396a50004ac96334b/frameset.htm
    Edited by: Neenu Jose on Nov 18, 2008 7:48 AM

  • SPD 2010 won't overwrite existing workflow but creates a new version instead

    When editing then saving and publishing an existing SharePoint Designer workflow a new version of the workflow is created but the previous version is still available in the SharePoint list for a user to select and start manually.
    Example: The original workflow is named Email Notes. After editing and publishing there are now two workflows available: Email Notes and Email Notes (1). Future edits increment the number so now we have Email Notes, Email Notes (1), Email Notes (2) and so
    on. Any of these workflows can be started. It looks like SPD won’t overwrite the existing workflow. SPD only shows the original Email Notes workflow.
    The problem appeared after making the setting change: SharePoint Central Administration > Application Management > General Settings > Workflow settings > Workflow Task Notifications. I selected yes for "Allow external users to participate
    in workflow by sending them a copy of the document?"
    After noticing the effect it had on editing workflows I reverted to the default "No" but the problem persists.
    One wouldn’t think making that change would cause my current problem but I have confirmed the behavior on a test server with images from our live environment.
    Has anyone seen or heard of this before? I found one random post on a site where someone else had experienced the same thing.

    Hi,
    This is a known behaviour. When you publish the new version of the workflow, the previous version is still available because there might be some workflows executing in lists and libraries on this version. But you can remove the previous versions so that
    they are not available for the users to starts. Go to List/Library > Settings > Workflow Settings.
    You will see all the previously published versions of the workflow. Here it shows the version of the workflows with Allow, No New Instance or Remove options. By default, previous version workflow should change to "No new instance" so users cannot
    start this manually. If this does not happen then this workflow will be available for users to start as in your case. If no instances of previous version are running, then select remove, and click Ok. Hope it clarifies.
    Regards, Kapil ***Please mark answer as Helpful or Answered after consideration***

  • Modify existing rebate condition and exclusion

    Hi
    We are rebate agreements for customers. Currently I want to modify rebate condition in one of rebate agreement.
    Scenario: let us June 10th 2010 onwards, the rebate % is 3% for Profit center 'xxxx' & customer 'yyyy' instead of 1%. And 3% needs to accrued on billing docs going forward. How to set up this.
    I tried to modify existing rebate condition using VBo2 as follows: went into rebate agreement using VBo2, changed rebate % for condition record with effective from 06/11/2010 and Saved.  problem when I ran VBOF program, system posted reversal accrual for old rebate condition 1%. Old condition record validity from 01/01/2009 Valid to 12/31/2011.
    I have one more question. We want to set up rebate condition for all materials exclude some of them. we have thousands of materials for which we need to calculate rebates. but we want to exclude some materials in the rebate agreement. How to set up such exclus
    any ideas really appreciated
    thnx

    The key of your condition table (the one supporting your condition record in the agreement) is evidently Profit Center / Customer.  So for any combination of profit center and customer, you can maintain a rate and validity period. 
    You are attempting to maintain two separate records having the same key.  As you have experienced, the system does not allow it.
    The simple solution is to expire that rebate agreement and start a new one with the updated validity period and conditions.
    As for excluding certain materials, you need a more detailed key in your condition table.  Something else from the material master seems appropriateu2014Commission Group for example.  Maintain commissionable materials in group 01 and non-commissionable ones in group 02.  Then a key combination of Commission Group / Profit Center / Customer  would work well for you.
    Regards,
    Ken

  • Error :This database already exists and is not a supported version of MBAM.

    While installing MBAM 2.0 SP1 i get the following error ,screenshot is attached.
    This database already exists and is not a supported version of MBAM.
    System set-up
    Server 2012 on which SQL 2012 SP1 is installed.
    Adding MBAM Audit , recovery and compliance features.

    Change the name of the database to:-
    - For Recovery database - "MBAM Recovery and Hardware"
    - For Compliance Database - "MBAM Compliance Status"
    While installing the MBAM DB features and then try. Don't change the default names or use any custom name for DBs.
    Gaurav Ranjan

Maybe you are looking for

  • Request for Permission in facebook apps

    I want display Request for Permission my app facebook so this: http://facebook.xomcongnghe.com/YahooPermission.jpg but I do not do that it appears like this: my apps display thiss http://facebook.xomcongnghe.com/img2.png or http://facebook.xomcongngh

  • IViews in Flexible Performance Management

    Hello Experts, I trying to use the Flexible Appraisal with Enhancement Package 4, but I can not see the the following iViews under the path indicated on Portal: MSS (Manager Self-Service ==> Talent Management ==> Performance Management) ESS (Employee

  • Servlet error: Error loading filter 'ADFBindingFilter'

    I use JDeveloper 10g (9.0.5.2 build 1618) and deploy my application to standalone oc4j 10g. I got the following internal error when I access dataAction. So I could not show any page. Servlet error: Error loading filter 'ADFBindingFilter', filter-clas

  • Roll-out project implementation issue

    Dear colleagues, This issue might have already been turned up but couldn't find any related threads. We have created our template project, set up the structure, added project documentations (11MBs converted to PDF ), training materials, everything se

  • Problem after multiselection on table

    hi     i have a  table  IT_car_data  where i have to perform      multiselection in the table , and iam populated the       data in to the table from the itemlistbox , then i need       to perform multiselection on the table and send it to a structur