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.

Similar Messages

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

  • 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

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

  • SD & FI BI functional Questions

    Hi Experts,
    I need to ask some questions to customer on SD & FI functional related questions for BI Analytical reports..
    Already cutomer implemented Data ware house Informatica with congnos reporting tool.
    right now they want to implement BI.
    please any one can share on what type functional questions could ask the customer.
    Advance Thanks,
    Bala.

    Hi,
    A few more pointers.
    Start with Reports. What the client is using. What he is expecting.
    If he got existing reports map the fields with Business Content BW Fields. Go to Business content and make a list of queries which are delivered from SAP. Explain them the KPI's. This should be good to start with. Also check the Tcodes they use.
    Look for DataSources that get data from theses Tcode's.
    Project Preparation (Initial stuff -- Do a conceptual review after this phase requirements gathering)
    Collect requirement thru interviews with Business teams /Core users / Information Leaders.
    Study & analyze KPI's (key figures) of Business process.
    Identify the measurement criteria's (Characteristics).
    Understand the Drill down requirements if any.
    Understand the Business process data flow if any.
    Identify the needs for data staging layers in BW – (i. e need for ODS if any)
    Understand the system landscape.
    Prepare Final Requirements Documents in the form of Functional Specifications containing:
    Report Owners, Data flow, KPI's, measurement criteria's, Report format along with drilldown requirements.
    Hope this helps.
    Thanks,
    JituK

  • 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

  • Sumifs function question

    Hi, Everyone, I have a function question of Sumifs, here a sample as follows,
    =SUMIFS(Budget :: E4:E14,Budget :: C4:C14,"=5003677000",Budget :: B4:B14,OR("=Transit","=Drawing cash")), according to the logic, I think like this, but it's wrong. So how to insert the OR function to the Sumifs function? May someone find the mistake in the function?
    Thank you.
    Alex

    I think you would actually do a sum of simifs, i.e. Sumif(....."Transit") + Sumif(....."Drawing Cash")
    Basically if you have two sumifs that differ in only one condition that would be treated like an OR in SQL, then make one Sumif for each unique set of  conditions and add them up
    Jason

  • OIC: Functional Question(11.5.10)

    Hi All,
    I would like to know answer for the following functional question in Oracle 11.5.10 Incentive Compensation Application(OIC). I would greatly appreciate if you anyone can reply for this.
    1. Question on Foreign currency exchange rates:
    We know that OIC cannot handle foreign currency exchange rates. Since all of our offer letters to the Sales guys are in local currency what we end up doing is picking an exchange rate on July 1st every year and converting them to US $. What I’m wondering is why couldn’t we just set them up in OIC in their local currency, without converting them?
    Is that possible? OIC can handle this?
    2. In OIC, Can I enter a DUMMY Acoount Executive (since we are not going to credit any single person in the Primary Account Executive role) that bookings could be credited to in order to ensure they roll up to the appropriate manager?
    a) Is that possible?
    b) Does this DUMMY Acoount Executive should be part of the HR Employee setups as well?, In OIC should we need to load the transaction for DUMMY Account
    Executive so that credit will get rolled up to approriate managers based on the Group hiearchy setups?
    Thanks,
    Johnson
    Edited by: user10413783 on Jun 23, 2009 4:06 PM

    Hi Johnson,
    2. In OIC, Can I enter a DUMMY Acoount Executive (since we are not going to credit any single person in the Primary Account Executive role) that bookings could be credited to in order to ensure they roll up to the appropriate manager?
    Yes
    b) Does this DUMMY Acoount Executive should be part of the HR Employee setups as well?, In OIC should we need to load the transaction for DUMMY Account
    Executive so that credit will get rolled up to approriate managers based on the Group hiearchy setups?
    You do not need to set up the dummy resource as employee. All you need is to create as OTHER type of resource and add that resource to group.
    Hope this helps.
    Thanks
    Srini

Maybe you are looking for