Recursive function

Hi.
I'm doing a programming project for school which involves a merge sort. I copied the code directly from a book, only the recursion isn't working. Throughout the year we've been doing work with recursion and it's been rather mean to me. My teacher has no clue what the problem is, but every time i try to make a recursive loop i have to jury rig it to work. For example, if i make a pathfinder, i have to tell it manually to backtrack after it finishes a "level" of recursion, rahter than just returning to the previous environment automatically. I've tried various IDEs (i use primarily Eclipse and Textpad) and nothing seems to work. Currently what i'm dealing with is as follows:
     public static void domergesort(board[] v, int st, int end)
          board[] tmp=new board[1];
          Vector vect=new Vector();
          if(st<end)
               int mid=(st+end)/2;
               System.out.println(end);
               domergesort(v,st,mid);
               System.out.println(end);
               domergesort(v,mid+1,end);
               merge(v,st,mid,end);
     }i put System.outs to see how far it gets through the code in the if-statement (cuz i knew it wasn't getting to merge()) and it didn't get past the first call of domergesort()
I'm guessing this problem is an extension of what i saw before: each time domergesort is called, the value for end is replaced by that of mid, and when end decreases to 0, the Java passes over the if statement, but when it backtracks a level, the value of end doesn't return to its previous value.
any ideas???

sorry.
solved my problem. turns out i was dumb and put the printing function inside the recursive loop so it tried to print the sorted list before it was done sorting, which is what screwed things up
but the thing about passing having to manually-reset things (like Vectors and arrays) is still up in the air

Similar Messages

  • Skipping to a specific place in a recursive function

    I wrote a recursive function that recurses Adding times, then calls go (). The entire function will call go () billions of times. When I call this function, I want to only run go () 5,000,000 times. It should run the first 5,000,000 go's if the Part variable is set to 1, the 2nd 5,000,000 go's if Part is 2, etc. The bolded code below is my attempt at implementing this. This code runs the correct 5,000,000-part pieces, but it takes too long because it is still recursing through every part, it's just not calling go () for the other ones. How can I only run the specific piece without recursing through all of the other ones?
    Add (int X, int Y, int Adding)
      int Tile;
      while (Y < 12)
        while (X < 16)
          if (aRoom [nRoom] [Y] [X] == 0)
            Changes [Adding - 1] [1] = X;
            Changes [Adding - 1] [2] = Y;
            for (Tile = 0; aTiles [nRoom] [Tile] [0] != 0; Tile++)
              if (aTiles [nRoom] [Tile] [1] > 0)
                aTiles [nRoom] [Tile] [1]--;
                aRoom [nRoom] [Y] [X] = aTiles [nRoom] [Tile] [0];
                Changes [Adding - 1] [0] = aTiles [nRoom] [Tile] [0];
                if (Adding > 1)
                  Add (X + 1, Y, Adding - 1);
                else
    PartTests++;
    if (Part == 0 || Part == Parts)
    go ();*}*
    if (PartTests == 5000000)
    Parts++;
    PartTests = 0;
                aTiles [nRoom] [Tile] [1]++;
            aRoom [nRoom] [Y] [X] = 0;
          X++;
        X = 0;
        Y++;
    }

    what go()?
    here's a cleaned up version of the code ( not a soln. ):
    Add( int X, int Y, int Adding )
         int Tile;
         while ( Y < 12 )
              while ( X < 16 )
                   if ( aRoom [nRoom][Y][X] == 0 )
                        Changes[Adding - 1][1] = X;
                        Changes[Adding - 1][2] = Y;
                        for ( Tile = 0; aTiles [nRoom][Tile][0] != 0; Tile++ )
                             if ( aTiles[nRoom][Tile][1] > 0 )
                                  aTiles[nRoom][Tile][1]--;
                                  aRoom[nRoom][Y][X] = aTiles [nRoom] [Tile] [0];
                                  Changes[Adding - 1][0] = aTiles[nRoom][Tile][0];
                                  if ( Adding > 1 )
                                       Add ( X + 1, Y, Adding-1 );
                                  else
                                       PartTests++;
                                       if ( Part == 0 || Part == Parts )
                                            go();
                                       if ( PartTests == 5000000 )
                                            Parts++;
                                            PartTests = 0;
                                  aTiles[nRoom][Tile][1]++;
                             } // end of if
                        } // end of for
                        aRoom[nRoom][Y][X] = 0;
                   } // end of if
                   X++;
              } // end of inner while
              X = 0;
              Y++;
         } // end of outer while
    }Edited by: scphan on Apr 4, 2009 1:13 PM

  • Problem with recursive function & Exception in thread "AWT-EventQueue-0"

    I hope that title doesn't put everyone off :)
    I have a recursive function that takes in a list of words, and a reference to my current best board. I am kludging the escape function +(tryWords.size() == 0 || mTotalBlankBlocks < 200)+ atm, but eventually it will escape based on whether the current bestBoard meets certain requirements. The function makes iterates through a list of words, and finds all the spaces that the word would fit into the puzzle: getValidSpacedPositions(currentWord); - it then iterates through each of these; placing a word, removing that word from the iterator and the relevant arrayLists and then recurses the function and tries to do the same with the next word etc.
    private void computeBoards(ArrayList<Word> tryWords, Board bestBoard) {
         if (tryWords.size() == 0 || mTotalBlankBlocks < 200)
              return;
         for(Iterator<Word> iter = tryWords.iterator(); iter.hasNext(); ){
              Word currentWord = new Word();
              currentWord = iter.next();
              ArrayList<Position> positions = new ArrayList<Position>();
              positions = getValidSpacedPositions(currentWord);
              if (positions.size() != 0)
                   iter.remove();
              System.out.println();
              int placedWordsIndex = tryWords.indexOf(currentWord);
              System.out.print(placedWordsIndex+". "+currentWord.getString()+" with "+positions.size()+" positions / ");
              for (Position position : positions) {
                   System.out.println("Pos:"+(positions.indexOf(position)+1)+" of "+positions.size()+"  "+position.getX()+","+position.getY()+","+position.getZ());
                   int blankBlocksLeft = placeWord(currentWord, position);
                   if(blankBlocksLeft != 0)
                        mPlacedWords.add(currentWord);
                        // TODO: Kludge! Fix this.
                        mUnplacedWords.remove(placedWordsIndex+1);
                        System.out.println("adding "+currentWord.getString()+" to added words list");
                        Board compareBoard = new Board(blankBlocksLeft, mPlacedWords.size());
                        if (compareBoard.getPercFilled() > bestBoard.getPercFilled())
                             bestBoard = new Board(blankBlocksLeft, mPlacedWords.size());
                        //**RECURSE**//
                        computeBoards(tryWords, bestBoard);
                        mUnplacedWords.add(currentWord);
                        removeWord(currentWord);
                        System.out.println("removing "+currentWord.getString()+" from added words list");
                   else
                        System.out.println("strange error, spaces are there but word cannot place");
              System.out.println("**FINISHED ITERATING POSITIONS");
         System.out.println("**FINISHED ITERATING TRYWORDS");
    }This all seems to work fine, but I add it in for completeness because I am not sure if I have done this right. The Exception occurs in the placeWord function which is called from the recursive loop, on the line bolded. For some reason the Arraylist Words seems to initialise with size 1 even though it is a null's when I look at it, (hence all the redundant code here) and I can't seem to test for null either, it seems to works fine for a while until the recursive funciton above has to back up a few iterations, then it crashes with the exception below.
         private int placeWord(Word word, Position originPosition) {
              ArrayList<Word> words = new ArrayList<Word>();
              switch (originPosition.getAxis().getCurrInChar()) {
              case 'x':
                   // TODO: This is returning ONE!!!s
                   words = mBlockCube[originPosition.getX()][originPosition.getY()][originPosition.getZ()].getWords();
                   int tempword1 = mBlockCube[originPosition.getX()][originPosition.getY()][originPosition.getZ()].getWords().size();
                   for (int i = 0; i < word.getLength(); i++) {
                        *if (words.get(0) == null)*
                             mBlockCube[originPosition.getX() + i][originPosition.getY()][originPosition.getZ()] = new Block(word, word.getChar(i));
                        else
                             mBlockCube[originPosition.getX() + i][originPosition.getY()][originPosition.getZ()].addWord(word);
                   break;
              case 'y':
                   words = mBlockCube[originPosition.getX()][originPosition.getY()][originPosition.getZ()].getWords();
                   int tempword2 = mBlockCube[originPosition.getX()][originPosition.getY()][originPosition.getZ()].getWords().size();
                   for (int i = 0; i < word.getLength(); i++) {
                        *if (words.get(0) == null)*
                             mBlockCube[originPosition.getX()][originPosition.getY() + i][originPosition.getZ()] = new Block(word, word.getChar(i));
                        else
                             mBlockCube[originPosition.getX()][originPosition.getY() + i][originPosition.getZ()].addWord(word);
                   break;
              case 'z':
                   words = mBlockCube[originPosition.getX()][originPosition.getY()][originPosition.getZ()].getWords();
                   int tempword3 = mBlockCube[originPosition.getX()][originPosition.getY()][originPosition.getZ()].getWords().size();
                   for (int i = 0; i < word.getLength(); i++) {
                        *if (words.get(0) == null)*
                             mBlockCube[originPosition.getX()][originPosition.getY()][originPosition.getZ() + i] = new Block(word, word.getChar(i));
                        else
                             mBlockCube[originPosition.getX()][originPosition.getY()][originPosition.getZ() + i].addWord(word);
                   break;
              mTotalBlankBlocks -= word.getLength();
              word.place(originPosition);
              String wordStr = new String(word.getWord());
              System.out.println("Word Placed: " + wordStr + " on Axis: " + originPosition.getAxis().getCurrInChar() + " at pos: "
                        + originPosition.getX() + "," + originPosition.getY() + "," + originPosition.getZ());
              return mTotalBlankBlocks;
    Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
         at java.util.ArrayList.RangeCheck(Unknown Source)
         at java.util.ArrayList.get(Unknown Source)
         at com.edzillion.crossword.GameCube.placeWord(GameCube.java:189)
         at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:740)
         at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
         at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
         at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
         at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
         at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
         at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
         at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
         at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
         at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
         at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
         at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
         at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
         at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
         at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
         at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
         at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
         at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
         at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
         at com.edzillion.crossword.GameCube.generateGameCube2(GameCube.java:667)
         at com.edzillion.crossword.GameCube.<init>(GameCube.java:42)
         at com.edzillion.crossword.Crossword.actionPerformed(Crossword.java:205)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    Any ideas? I've looked up this exception which didn't shed any light...                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    ArrayList<Word> words = new ArrayList<Word>();See the API Javadoc for ArrayList: this creates an empty ArrayList.
    if (words.get(0) == null)This tries to read the first element of the (still empty) array list -> throws IndexOutOFBoundsException
    If you want to stick to that logic (I am too lazy to proof-read your whole algorithm, but that should at least unblock you), you should first check whether the list actually contains at least one element:
    if (!words.isEmpty()) {...}

  • Is there any recursive function in DB2

    Hi all,
    Could you please tell me is there any recursive function in DB2 and if yes then please provide me a sample code.
    I want to write a function as below but it's giving me following error:
    >[Error] Script lines: 1-33 -
    ( DB2 SQL error: SQLCODE: -440, SQLSTATE: 42884, SQLERRMC: SCF_MC2;FUNCTION
    Message: No authorized routine named "SCF_MC2" of type "FUNCTION" having compatible arguments was found.
    Line: 11 )
    create FUNCTION scf_mc2 (@@certname varCHAR(20),@@assignee varCHAR(20),@@currentUser     varCHAR(20), @@javaLocale
    varCHAR(20) )RETURNS float
    LANGUAGE SQL
    READS SQL
    DATA format:
    BEGIN ATOMIC 
        declare @n_cost float;
        declare @n_cost1 float;
        set @n_cost1 =0.00;
    FOR @n_cost as
        select
        COALESCE ((CASE substr(ep.part_id,1,5) when 'cours' then tp2.scf_nc(ep.part_id,@@assignee,@@currentUser,@@javaLocale)  else
        tp2.scf_mc2(ep.part_id,@@assignee,@@currentUser,@@javaLocale) end ),0) cost
        from
        tpt_ext_ce_certification certi
        inner join tpt_ext_ce_track tr  on tr.certification_id = certi.id
        inner join tpt_ext_ce_group gr  ON gr.track_id = tr.id
        inner join tpt_ce_education_plan ep  ON ep.owner_id = gr.id
        WHERE
        tr.locale_id = @@javaLocale
        AND
        gr.locale_id = @@javaLocale
        AND
        certi.locale_id = @@javaLocale
        and
        substr(tr.flags,2,1) = '1'
        and
        certi.id=@@certname
    DO
    SET @n_cost1 = @n_cost+@n_cost1;
    END FOR;
    return @n_cost1;
    end format
    Regards
    Vishal

    Java is an object-oriented language, so you're not just searching for a method to do what you want, but for a Class, that provides that ability.
    And since you don't define what "the date that I want" means I can only guess.
    If you've got the date value in a String in some format, then you might look into the DateFormat or SimpleDateFormat classes.

  • Validation of recursive function call fails

    We want to use a call to a recursive function from a HTMLDB application. It should be used in a page region to generate a query string ("PL/SQL function body returning SQL query"). Everything works fine with a call to a non-recursive function. The recursive function also works fine when called from SQL+.
    After pressing "Apply changes" on "HTML DB Home>Builder - Application 148>Page Definition>Edit Page Region"-page I get the following error message after a long delay:
    Function returning SQL query: Query cannot be parsed within the Builder. If you believe your query is syntactically correct, check the ''generic columns'' checkbox below the region source to proceed without parsing
    (ORA-00600: internal error code, arguments: [kohdtf048], [], [], [], [], [], [], [])
    I assume that the validation routine follows the recursion until the memory limit is reached.
    Please give me a hint how to solve this problem.
    DB version: 10.1.0.2.0
    HTMLDB version: 1.5.0.00.33
    running on Win2000 server

    Since the original function is confidential, I have created a simple one showing the same behavior (and the same error). Termination does not depend on session state:
    Called function (to replace spaces with #):
    create or replace function MF_Test
         p_querystring     varchar2     
         return varchar2 is
         v_position integer;
    begin
         v_position:=instr(p_querystring,' ');
         if v_position=0 then     /* termination condition */
              return p_querystring;
         else
              return substr(p_querystring,1,v_position-1)||'#'||MF_Test(substr(p_querystring,v_position+1));
         end if;
    end MF_Test;
    calling function (from the page region, to generate a query string):
    declare
    q varchar2(500);
    begin
    q:='select * from hardware where model=''';
    q:=q||mf_test(:P3_SEARCH);
    q:=q||'''';
    end
    Validation seems not to terminate in case of recursive function calls.
    Thanks for your input.

  • Help with recursive function to print number patterns

    I'm sorry for having to ask for homework help - I'm badly stuck on this! Can someone give me a kick in the right direction with this?
    need a recursive function with a single positive int parameter n. the function should write (2^n - 1) integers and should be in the following pattern...
    n = 1, Output: 1
    n = 2, Output: 1 2 1
    n = 3, Output: 1 2 1 3 1 2 1
    n = 4, Output: 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
    n = 5, Output: 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
    function should valid for all positive integer values of n
    This was tagged as a 'short' problem...so it shouldnt take too much code...I am hung on on the following:
    *Do I keep track of the numbers printed, if so how?  I only have a single parameter to call with so I am confused as to how I could get an entire pattern without keeping track of the history
    *I had initially thought it would be necessary to cut it in half and do the 2nd half backwards (ie: for n=3, I would take care of the 1 2 1 - then 3 - then 1 2 1...but even then it seems like I could cut 1 2 1 in half the same way and therefor I should be able to do ALL of it in single parts...
    Can someone veer me in the right direction here? I'm really lost with this.

    This was tagged as a 'short' problem...so it shouldnt
    take too much code...Yeah, the method body could be done in a few lines.
    I am hung on on the following:
    *Do I keep track of the numbers printed, if so how?Not explicitly. Use the call stack. That is, use the fact that when you're recursing, the previous values of numbers are preserved in the previous method invocation.
    I only have a single parameter to call with so I am
    confused as to how I could get an entire pattern
    without keeping track of the historyYou don't have to store anything across method invocations.
    I had initially thought it would be necessary to cut
    it in half and do the 2nd half backwards (ie: for
    n=3, I would take care of the 1 2 1 - then 3 - then 1
    2 1...but even then it seems like I could cut 1 2 1
    in half the same way and therefor I should be able to
    do ALL of it in single parts...No, it's MUCH simpler than that. It's easier than yo uthink.
    Can someone veer me in the right direction here? I'm
    really lost with this.Try this simpler version of the problem:
    Write a recursive method that creates this output:
    n = 1: 1
    n = 2: 1 2
    n = 3: 1 2 3
    And try this simpler version:
    n = 1: 1
    n = 2: 2 1
    n = 3: 3 2 1

  • Calling Recursive function in a transaction

    Hello All
    I have a requirement calling Recursive function in Transaction.Means inside a transaction, i want to call the same transaction.Is it possible to do like this?
    Because when i am calling like this,transaction is running contineously without stop.
    Any help would be highly appreciated.
    Thanks,
    Manisha

    Manisha,
    take a look on this thread:
    Does xMII support recursive Business Logic Modules
    Hope Ricks solution can help you.
    Regards
    Pedro
    Edited by: Pedro Iglesias on Dec 19, 2008 9:56 AM

  • How to define recursive functions in JSP

    Hi,
    If anybody knows, how to to define recursive functions pls help. I am using an XML file for the creation of a tree menu. In order to display the menu, i have to use recursive functions...Also out.println throwing error in the function..
    Thanks,
    Philips

    I do not have my Java book at work with me today so you'll have to bear with me. The following routine assumes that you can get some sort of branch object from your tree menu object (also assuming you have something like this). Furthermore, it assumes that the branch object can return some sort of collection of all leaves and branches on a particular branch through a made-up getLeaves() method call.
    <%!
              public void displayLeaves(Branch branch)
                   Iterator branches = null;
                   branches = branch.getLeaves().getIterator();
                   Object leaf = null;
                   while( branches.hasMoreItems() )
                        leaf = branches.nextItem();
                        if(leaf instanceof branch)
                             displayLeaves((Branch) leaf);
                        else
                             out.println( ((Leaf)leaf).getValue() );
    %>This code fragment should be just the logic you need to expand a tree as JSP output. To invoke this method all you have to do is pass the root branch element to the method from within your JSP. Please let me know if you need additional info.

  • Function sequence error / Recursive functions error

    Hi! I've a little problem over here. I have an application (servlet) that makes recursive functions with DB access. This function contains a resultset that calls the same function again until no more data is found. The problem, is that I'm using JDBC-ODBC bridge (because this must work in SQL Server, Informix, Sybase, Access and Oracle), so I need to make commit of the connection in every resultset. If I make the commit inside the resultset, I got a "Function Sequence error" exception. Of course, I can't close every statement inside the resultset (or at least I don't know how). My code looks like this:
    public void myfunction(String odbc,String data1,String data2) throws SQLException,Exception{
         //this class, myclassDB, just return a established connection with the DB
         Connection connection = myclassDB.connect(odbc);
         Statement statement = connection.createStatement();
         ResultSet rs = statement.executeQuery("query");
         while(rs.next()){
              //do something with the information
              //make recursive
              connection.commit();
              myfunction(odbc,data1,data2);
         statement.close();
         connection.close();
    }Hope you can help me!
    Feel free to email me at [email protected]
    Regards!     

    I am not really sure what the question is but...
    Presuming that there isn't something wrong with your design (which recursive calls suggest) then you need to extract all of the data, close the resultset/statement then do the recursive calls. If you do processing first then you can still commit on the connection.

  • Help!! recursive function call

        *   The function which build the category tree
        public String categoryTree(Statement stat, boolean isMore, int id) {
            if(!isMore) {
                return "";
            else
               String sql = " select t_category_relation.category_relation_id, t_category_relation.level_in, " +
                            " t_category_item.category_item_id, t_category_item.category_name_jpn_NV from " +
                            " t_category_item, t_category_relation " +
                            " where " +
                            " t_category_item.category_item_id = t_category_relation.category_item_id and " +
                            " t_category_relation.parent_id = " + id + " and t_category_relation.parent_id<>0";
    //           return sql;
               try{
                   ResultSet res = stat.executeQuery(sql);
                   String spacer = "";
                   String input = "";
                   while(res.next()) {
                        int level = res.getInt(2);
                         id = res.getInt(1);
                         for(int i = 0; i < level; i ++) {
                            spacer +="   ";
                         input ="+ id: " +id + " NAME  " + res.getString(4) + "\n</td>\n<td align=center>\n<input type=checkbox value=" +String.valueOf(id) + " name=categoryid>\n</td>\n</tr>\n";
                         return "\t\t<TR>\n\t\t\t<TD>" + spacer + input + categoryTree(stat, true, id);
                   if(spacer.equals("")){
                        return input+categoryTree(stat, false, id);
                }catch(SQLException e) {
                        return "SQL Exception";
                return categoryTree(stat, false, id);
        }I am writing a menu generated base on a tree like relation ship that is store in a database. assume
    vegetable has two child and one of the child has another child and so forth.
    But I am getting a result like this:
    vegetable-->
    <1>childe
    <1.1>childe
    but missing <2>child
    because the while loop doesn't continous looping after the 1.1.
    please help me out
    thanx in advance

    >
    Re: help!! recursive function call
    Author: DrClap Aug 3, 2001 1:15 PM
    When you call the method recursively, the second call makes a second query to the database, before you have finished using the ResultSet from the first query. Since you are using the same Statement, executing the second query causes the first query to, um, disappear.
    The API documentation for java.sql.Statement says this: "Only one ResultSet object per Statement object can be open at any point in time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All statement execute methods implicitly close a statment's current ResultSet object if an open one exists."
    thanx for your reply!
        public String categoryTree(int id) {
               String sql = " select t_category_relation.category_relation_id, t_category_relation.level_in, " +
                            " t_category_item.category_item_id, t_category_item.category_name_jpn_NV from " +
                            " t_category_item, t_category_relation " +
                            " where " +
                            " t_category_item.category_item_id = t_category_relation.category_item_id and " +
                            " t_category_relation.parent_id = " + id;
               try{
                   Connection con = DataSourceUtil.getConnection("name");
                   Statement stat = con.createStatement();
                   ResultSet res = stat.executeQuery(sql);
                   String spacer = "";
                   String row = "";
                   while(res.next()) {
                        int level = res.getInt(2);
                         id = res.getInt(1);
                         for(int i = 0; i < level; i++) {
                            spacer +="   ";
                        row = " \t\t<tr>\n " +
                              " \t\t\t<td colspan='2'>" + spacer + " <a href=inventory_edit_product.jsp?categoryid=" + id +">" + res.getString(4) + "</a></td>\n" +
                              " \t\t</tr>\n ";
                         return (row + categoryTree(id));
                   con.close();
                }catch(SQLException e) {
                        return "<tr><td colspan=2>SQL Exception</td></tr>";
                return "";
        }New I think every recursive call will have it's own statement and resultSet but I am still getting same problem. The while loop stopped when calls reached first base case. Does anybody know why. I expect, assume that while loop will go next when a call reaches the base case which will return "".
    Thanx for help

  • Recursive function module for OM

    Hi all,
    I have to write a function module to retrieve the Org. Management hierarchy to a xml, the outcome should be like the results of transaction PPOSE.
    How to write a recursive function module to retrieve the data from tables HRP1001 and HRP1000 ?
    Thanks.

    Hi Macy,
    try using the delivered function module RH_STRUC_GET.
    Regards,
    Suresh Datti

  • Recursive Function Question

    I've used recursive functions with other programming
    languages but I seem to be having a problem using it with a UDF in
    a cfc file. I'm reading an XSD file, parsing the XSD and populating
    an array with the details of any import tags using XMLSearch,
    looping through the array and recursively calling the same UDF to
    process the child XSD file, so on an so forth. My issue happens
    when the UDF gets to the bottom of the recursive call and is going
    back up one level to loop to the next item in the array of the
    parent UDF call. When the code returns back it gives me an error
    saying "The element at position 2 cannot be found." After some
    trouble finding out what is happening, it seems the values
    contained in the array have been purged. In my experience with
    recursive functions, the values of any past calls will still be
    available in memory once the process returns back to it. I'm a
    litte green using UDFs but I would think it should work the same
    way. Is there an issue with the scope of the array variable I am
    using? I've attached my code. Any help is appreciated.
    Thanks!

    If I wanted to keep track of which XSD files I have already
    processed,
    would I be able to insert the file names into an array or
    list across
    recursive calls? Would I need to declare it within the
    cfcomponent tag
    before the cffunction tag? Thanks again.
    Yes you can. You would create an array an either the global
    THIS
    (unfortunately the default) or the more preferred VARIABLES
    scope. The
    this scope is public, the variables scope is private to the
    component.
    You can declare this global variable in the "pseudo
    constructor" space
    at the head of the component - which is the space between the
    opening
    <cfcomponent> tag and the first opening
    <cffunction> tag. You could
    also declare this global variable in another initialization
    style
    function that is called before your iteration function is
    called
    initially.
    You would then access and update the values in the global
    variable
    inside your iteration function just by calling it as
    this.aVariable or
    variables.aVariable.

  • How to collect returns from recursive function calls without a global var?

    Usually global variables shouldnt be used, I was told. Ok. But:
    How can I avoid using a global var when recursively using a function, when the function returns an object and when I want to have the collection of all these objects as the result?
    For example, I think of determine the users of a group including group nesting. I would write a function that adds the direct group members to a collection as a global var and call itself recusively if a member is another group. This recursively called function
    would do as well: Update the global var and if needed call itself.
    I'm afraid this is no good programming style. What algorithm would be better, prettier? Please dont focus on the example, it is a more general question of how to do.
    Thanks
    Walter

    I rarely needed to create/use recursive functions. Here's one example I did:
    function New-SBSeed {
    <#
    .Synopsis
    Function to create files for disk performance testing. Files will have random numbers as content.
    File name will have 'Seed' prefix and .txt extension.
    .Description
    Function will start with the smallest seed file of 10KB, and end with the Seed file specified in the -SeedSize parameter.
    Function will create seed files in order of magnitude starting with 10KB and ending with 'SeedSize'.
    Files will be created in the current folder.
    .Parameter SeedSize
    Size of the largest seed file generated. Accepted values are:
    10KB
    100KB
    1MB
    10MB
    100MB
    1GB
    10GB
    100GB
    1TB
    .Example
    New-SBSeed -SeedSize 10MB -Verbose
    This example creates seed files starting from the smallest seed 10KB to the seed size specified in the -SeedSize parameter 10MB.
    To see the output you can type in:
    Get-ChildItem -Path .\ -Filter *Seed*
    Sample output:
    Mode LastWriteTime Length Name
    -a--- 8/6/2014 8:26 AM 102544 Seed100KB.txt
    -a--- 8/6/2014 8:26 AM 10254 Seed10KB.txt
    -a--- 8/6/2014 8:39 AM 10254444 Seed10MB.txt
    -a--- 8/6/2014 8:26 AM 1025444 Seed1MB.txt
    .Link
    https://superwidgets.wordpress.com/category/powershell/
    .Notes
    Function by Sam Boutros
    v1.0 - 08/01/2014
    #>
    [CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact='Low')]
    Param(
    [Parameter(Mandatory=$true,
    ValueFromPipeLine=$true,
    ValueFromPipeLineByPropertyName=$true,
    Position=0)]
    [Alias('Seed')]
    [ValidateSet(10KB,100KB,1MB,10MB,100MB,1GB,10GB,100GB,1TB)]
    [Int64]$SeedSize
    $Acceptable = @(10KB,100KB,1MB,10MB,100MB,1GB,10GB,100GB,1TB)
    $Strings = @("10KB","100KB","1MB","10MB","100MB","1GB","10GB","100GB","1TB")
    for ($i=0; $i -lt $Acceptable.Count; $i++) {
    if ($SeedSize -eq $Acceptable[$i]) { $Seed = $i }
    $SeedName = "Seed" + $Strings[$Seed] + ".txt"
    if ($Acceptable[$Seed] -eq 10KB) { # Smallest seed starts from scratch
    $Duration = Measure-Command {
    do {Get-Random -Minimum 100000000 -Maximum 999999999 |
    out-file -Filepath $SeedName -append} while ((Get-Item $SeedName).length -lt $Acceptable[$Seed])
    } else { # Each subsequent seed depends on the prior one
    $PriorSeed = "Seed" + $Strings[$Seed-1] + ".txt"
    if ( -not (Test-Path $PriorSeed)) { New-SBSeed $Acceptable[$Seed-1] } # Recursive function :)
    $Duration = Measure-Command {
    $command = @'
    cmd.exe /C copy $PriorSeed+$PriorSeed+$PriorSeed+$PriorSeed+$PriorSeed+$PriorSeed+$PriorSeed+$PriorSeed+$PriorSeed+$PriorSeed $SeedName /y
    Invoke-Expression -Command:$command
    Get-Random -Minimum 100000000 -Maximum 999999999 | out-file -Filepath $SeedName -append
    Write-Verbose ("Created " + $Strings[$Seed] + " seed $SeedName file in " + $Duration.TotalSeconds + " seconds")
    This is part of the SBTools module and is used by the
    Test-SBDisk function. 
    Example use:
    New-SBSeed 10GB -Verbose
    Test-SBDisk is a multi-threaded function that puts IO load on target disk subsystem and can be used to simulate workloads from multiple machines hitting the same SAN at the same time, and measure disk IO and performance.
    Sam Boutros, Senior Consultant, Software Logic, KOP, PA http://superwidgets.wordpress.com (Please take a moment to Vote as Helpful and/or Mark as Answer, where applicable) _________________________________________________________________________________
    Powershell: Learn it before it's an emergency http://technet.microsoft.com/en-us/scriptcenter/powershell.aspx http://technet.microsoft.com/en-us/scriptcenter/dd793612.aspx

  • Recursive functions

    hi,
    A recursive function should produce a dynamic index and devolve that index when a value given by parameters is equal to the valçue from "sequence" column.
    CREATE OR REPLACE FUNCTION SOFT.ORDER_LINE(P_CODEMP IN NUMBER, P_NROF IN NUMBER, P_LINHAOF IN NUMBER,P_SEQUENCIA IN NUMBER, P_SEQ_LINE IN VARCHAR2,P_ORDEM IN VARCHAR2) RETURN VARCHAR2 IS
    CURSOR TAB IS SELECT SEQUENCIAPLANO,seq_linhas,tipo
                  FROM PRD_PLANEAMENTO
                  WHERE CODEMP=P_CODEMP AND
                        NROF=P_NROF AND
                        LINHAOF=P_LINHAOF AND
                        (P_SEQ_LINE is null and ( instr(Seq_Linhas,'.',-1)=0) or
                        P_SEQ_LINE = substr(Seq_Linhas,1,instr(Seq_Linhas,'.',-1)-1))
                  ORDER BY ORDEMSEQ;
    L_SEQ       PRD_PLANEAMENTO.SEQUENCIAPLANO%TYPE;
    l_seq_line  PRD_PLANEAMENTO.SEQ_linhas%TYPE;
    l_tipo      PRD_PLANEAMENTO.tipo%TYPE;
    LINE        NUMBER;
    TMPLINE     VARCHAR2(299);
    EXIST       NUMBER;
    BEGIN
      open Tab;
        loop
            fetch Tab into L_SEQ,l_seq_line,l_tipo;
            exit when Tab%notfound;
              LINE:= NVL(LINE,0) + 1;
              exist:=0;
              if (l_tipo='A') then
                BEGIN
                  SELECT COUNT(1)
                    INTO EXIST
                  FROM PRD_PLANEAMENTO
                  WHERE CODEMP=P_CODEMP AND
                        NROF=P_NROF AND
                        LINHAOF=P_LINHAOF AND
                        (L_SEQ_LINE = substr(Seq_Linhas,1,instr(Seq_Linhas,'.',-1)-1));
                EXCEPTION WHEN NO_DATA_FOUND THEN NULL;
                END;
              end if; 
              if p_ordem IS NULL then
                if l_seq=P_SEQUENCIA then
                   TMPLINE:=(to_char(line));
                end if;
                IF NVL(EXIST,0)>0 THEN     
                  TMPLINE:= (ORDER_LINE(P_CODEMP, P_NROF, P_LINHAOF,P_SEQUENCIA,l_SEQ_LINE,to_char(line)||'.'));
                END IF; 
              else
                if l_seq=P_SEQUENCIA then
                  TMPLINE:= (p_ordem||to_char(line));
                end if;
                IF NVL(EXIST,0)>0 THEN
                  TMPLINE:= (ORDER_LINE(P_CODEMP, P_NROF, P_LINHAOF,P_SEQUENCIA,l_SEQ_LINE,p_ordem||to_char(line)||'.'));
                END IF;
              end if;
        end loop;
        close Tab;
        return (TMPLINE); 
    END ORDER_LINE;
    The function devolves always "null" for the indices that have levels e.g. 3.1.5.1, except for the last level. How to deal with this situation? The objective is to devolve only that index and to break a recursive function - anybody has the idea how to do that?
    thank's
    jomar

    How do you get from your sample data to '1,2,3,4'? For example the two rows with ref_id = 1 have IDs 2 and 4.
    btw you can format code and output using [code] tags.

  • Recursive function selecting swing components

    I have a recursive function that is passed a container and a boolean value that represents whether the components is enabled or not. Every thing works as expected except it does not detect the JTextAreas. How can I check to see if the component (comp) is a JTextArea or not? Is there a better way to do this? The code is as follows:
    public void unlockComponents(Container container, boolean lock_value) {
    Container parent = container;
    for (int i = 0; i < parent.getComponentCount(); i++) {
    Component comp = parent.getComponent(i);
    if (comp instanceof JPanel) {
    Container subParent = (Container) comp;
    unlockComponents(subParent, lock_value);
    } else if (comp instanceof JLayeredPane) {
    Container subParent = (Container) comp;
    unlockComponents(subParent, lock_value);
    } else if (comp instanceof JScrollPane) {
    System.out.println("JSCROLLPANE");
    Container subParent = (Container) comp;
    unlockComponents(subParent, lock_value);
    } else if (comp instanceof JTextField) {
    JTextField component = (JTextField) comp;
    component.setEditable(lock_value);
    } else if (comp instanceof JTextArea) {
    JTextArea component = (JTextArea) comp;
    component.setEditable(lock_value);
    } else if (comp instanceof JCheckBox) {
    JCheckBox component = (JCheckBox) comp;
    component.setEnabled(lock_value);
    }

    Hmm.. this sounds somewhat familiar to me>> Is by any change the JPopupMenu showing out of the bounds of the frame of it's parent component? If so: Here lies your problem. Try to keep the popup within the frame.

  • REcursive function problem

    Hi all
    I need help in this recursive function
    The data in the merge_move_txn table is as follows:
    txn_id Source_tcid Target_tcid
    1 20 22
    2 22 32
    3 32 33
    4 49 54
    I need to get the target_tcid for a given source_tcid . If the target_tcid is also ther in source_tcid column i must get the target_tcid for it and so on..
    Eg: if the source_tcid i passed to this recursive function is 20 then i must get 33.
    because target of 20 is 22 , and target of 22 is 32 and target of 32 is 33.
    and 33 does not have any entry in source so i must pass 33.
    FUNCTION getTarget(tc_id MERGE_MOVE_TXN.source_tcid%TYPE)
    RETURN MERGE_MOVE_TXN.source_tcid%TYPE
    IS
    lv_count      NUMBER;
    lv_tar_tcid MERGE_MOVE_TXN.target_tcid%TYPE;
    BEGIN
          SELECT target_tcid INTO lv_tar_tcid
          FROM merge_move_txn
          WHERE source_tcid=tc_id
          AND ROWNUM=1;
          SELECT count(*) INTO lv_count
          FROM merge_move_txn
          WHERE source_tcid=lv_tar_tcid
          AND ROWNUM=1;
          IF(lv_count>0) THEN
            lv_tar_tcid:=getTarget(lv_tar_tcid);
          ELSE
            RETURN lv_tar_tcid;
          END IF;      
    END;But this code is giving error as "PL/SQL function returned without value"
    Why is this happening.
    Can you help me to correct this code?
    Thanks
    Glen

    IF(lv_count>0) THEN
    lv_tar_tcid:=getTarget(lv_tar_tcid);
    ELSE
    RETURN lv_tar_tcid;
    END IF;      
    IF(lv_count>0) THEN
       lv_tar_tcid:=getTarget(lv_tar_tcid);
    END IF;      
    RETURN lv_tar_tcid;                                                                                                                                                                                                                                                                                                                                                                                                                                   

Maybe you are looking for

  • Canvas Output to Broadcast via mini-DVI to Composite Video?

    Hello, I would like to send the output of my NTSC Canvas to my NTSC broadcast monitor via it's Composite input. I run FCP 6.0.3 on OS 10.5.3 and I was hoping I could make this connection via Apple's mini-DVI to Composite adapter. I seem to be all set

  • Posting of cross company transaction with different doc types

    Hi, The scenario is:- We have two companies X and Y. X makes a payment to Y with the following FI entries:- Company Code X Dr Vendor Y Cr Bank HDFC Company Code Y Dr Bank ICICI Cr Customer X Now this needs to be a cross company transaction where the

  • IPod Shuffle, headphones and speakers

    Will my Bose Acoustic Noise Cancelling headphones plug directly into an iPod Shuffle, or does this require the 3.5 mm stereo headphone minijack? If so is the minijack included with basic purchase? Also, is there a way to connect the Altec Lansing Orb

  • After system restore, can't access iTunes.

    Windows XP laptop. Window says file "itunes library.itl" cannot be read because it was created with a newer version of iTunes. Help!

  • Time taken

    I need to collect the CPU time taken to run some Java code. Is there a way that I can do this, and if so how do I do it? (in easy terms please!)