Help! Recursive function to print ncr
hi ,everyone
i am writing a program to print out the ncr of an array
ie gievn [1,2,3]
my outcome is expected to be
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
however my program output is
12 3
3 2
2 13
3 1
3 1 2
2 1
can somebody help me out to make my program to output the expected outcome
here is the code
import java.util.*;
public class ncrq
public static void main(String args[])
int[] value=new int[3];
value[0]=1;
value[1]=2;
value[2]=3;
printNcr(value);
public static void printNcr(int[] value)
if(value.length==0)
return;
else
int[] outcome=new int[value.length-1];
for(int i=0;i<value.length;i++)
System.out.print(value[i]+" ");
copyArray(value.length,outcome,value,i);
printNcr(outcome);
System.out.println();
public static void copyArray(int originalLength,int[] outcome,int[] income,int i)
int j=0;
for(int k=0;k<originalLength;k++)
if(k!=i)
outcome[j++]=income[k];
}
I would say to treat each character more like a symbol because that's how we handle such problems. Then write a method that tracks the position of each symbol / object and bumps it to antoher position and it'll do this for each object.
such as:
123
where 1 is obj a, 2 is obj b, and 3 is obj c.
Then pick on obj b and bump it to obj c's position and print the result, then bump it to obj a's position.
123 ---> 132 DONE focusing on obj a.
213 ---> 231 DOND focusing on obj b.
312 ---> 321 DOND focusing on obj c.
The number of bumps for each object will be determined by the original objects size, so a 3 digit number would have two bumps for each object and a 4 digit number (1234) would have 3 bumps per obj, etc....
A key part to this letting each obj stand in as a "leader" and having two bumps after it's assignment. Otherwise you'll recieve duplicate values.
So you would get (leaders are in bold): 1,2,3 ----> 1,3,2 ----> 2,1,3 -----> 2,3,1 -----> 3,1,2 ---->3,2,1
Similar Messages
-
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 -
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 -
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()) {...} -
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,
ManishaManisha,
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,
PhilipsI 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. -
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
WalterI 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 -
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
GlenIF(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; -
Recursive function to find the parents of a tree node
Hi,
I need help to write a recursive function to get the parents of a tree node upto the root.The major problem is , each node can have more than one parent.I have two methods ; one to get the immediate parents(getParents() will return me a vector) and the other to get the parents upto the root(will also return me a vector).
Thanks in advance,
nanduvslet me risk a dumb response ..
if there are multiple parents
why not just follow the first parent
back to the root
if everything starts at one root -
Finder can't continue recursive function
I'm trying to write a recursive function that returns a nested list representing the directory structure (including files) below a starting path. When I run my function, I get an error: "Applescript Error: Finder got an error: Can't continue getDirectoryStructure." This error appears at the first subfolder encountered.
This is one of those "spot my mistake" kind of posts, because I am completely lost. I don't see why it shouldn't be able to continue with my recursive function. Here's the code:
on getDirectoryStructure(startPath)
tell application "Finder"
set dirList to {}
set tempDirList to (get items of folder startPath)
repeat with curItem in tempDirList
if (class of curItem is folder) then
set end of dirList to getDirectoryStructure(startPath & ":" & name of curItem)
else
set end of dirList to curItem
end if
end repeat
end tell
return dirList
end getDirectoryStructure
getDirectoryStructure("Filibuster II:Users:ryos:Documents")I didn't realize I could display this a little better, I'm new to the list, and slowly getting it figured out.
This is a re-post of my previous message...
on script_title()
Filename : minimaldirtraversal.scpt (Script Debugger)
Author : Bill Hernandez
Version : 1.0.0
Updated : Saturday, December 16, 2006 ( 3:18 PM )
end script_title
-- ---------+---------+---------+------------------
on script_notes()
I took one of my directory traversal routines, and took a bunch of stuff
out of it, to create this for you...
Hope it helps,
Bill Hernandez
end script_notes
-- ---------+---------+---------+------------------
property gtimestart : ""
property gtimeend : ""
-- ---------+---------+---------+------------------
-- PROPERTIES REQUIRED FOR PROCESSING TRAVERSAL
-- ---------+---------+---------+------------------
property aFound : {}
property aIgnored : {}
property aFileTypes : {"TEXT"}
property aExtensions : {"txt", "text", "applescript", "html", "php"}
-- ---------+---------+---------+------------------
-- SYSTEM PATHS
-- ---------+---------+---------+------------------
property gdirpathhome : ""
property gdirpathdesktop : ""
property gdirpathdocs : ""
property gdirpathprefs : ""
property gdirpathtemp : ""
-- ---------+---------+---------+------------------
property gtextdelim : ":"
property g_Divider : "--------------------------------------------------" & return
-- ---------+---------+---------+------------------
property aErrors : {} -- list of errors
property gshow_errormessages : true -- set to false to prevent error messages from displaying
property gsend_error_messages_tolog : true
property g_continue : true -- use this instead of [if (not(g_abort)) then]
-- ---------+---------+---------+------------------
on run
set w_props to {contents:""}
--set w_id to my bb_CkWindowExists("Dummy Work Document", "", w_props) -- REMOVE THIS LINE, USED FOR TESTING
tell me
InitGlobals()
set which to "selectchoosefolder" -- aChoices -> { "selectcurrentdocument", "selectopendocuments", "selectchoosefolder"}
main(which) -- place your code in [main]
end tell
end run
-- ---------+---------+---------+------------------
on main(whichAction) -- This is the [main handler] called by [on run]
-- THIS IS A BASIC SHELL FOR ANY SCRIPT
my ProcessRequest(whichAction)
if (g_continue) then
set str to "" -- If this set to "", the following will be used "Would you like to continue processing now?"
-- REMOVE NEXT LINE, USED FOR TESTING
set str to str & "Found : ( " & (count items in aFound) & " ) files..." & return & "Time to process : " & (gtimeend - gtimestart) & " seconds..." & return & return
if (my ConfirmRequest(str)) then
repeat with thisItem in aFound
-- PROCESS EACH (FILE, WINDOW, or DOCUMENT) HERE
-- ******* DO THE WORK HERE
end repeat
end if
end if
set error_title to "Problem Found:" & return & "NOTIFY APPLE COMPUTER"
my error_HandleErrors(aErrors, error_title, gshow_errormessages, gsend_error_messages_tolog)
tell application "BBEdit" to activate
end main
-- ---------+---------+---------+------------------
on ProcessRequest(whichAction)
-- Having "if (whichAction..." here is redundant, instead of having it below, but makes it easier not having to repeat "set gtimestart..." several times
if (whichAction = "selectchoosefolder") then
set startFolder to my ChooseFolder("Select the folder where the files you want to combine are stored?")
end if
-- MAKE SURE "set gtimestart..." COMES AFTER "ChooseFolder(...)"
set gtimestart to (current date) -- REMOVE THIS LINE, USED FOR TESTING
if (g_continue) then
if (whichAction = "selectopendocuments") then
else if (whichAction = "selectchoosefolder") then
my processDirectory(startFolder)
else if (whichAction = "selectcurrentdocument") then
else
set aFound to {}
end if
end if
set gtimeend to (current date) -- REMOVE THIS LINE, USED FOR TESTING
end ProcessRequest
-- ---------+---------+---------+------------------
on InitGlobals()
set aErrors to {} -- list of errors
set gdirpathhome to (path to home folder from user domain as text)
set gdirpathdesktop to (path to desktop from user domain as text)
set gdirpathdocs to (path to documents folder from user domain as text)
set gdirpathprefs to (path to preferences folder from user domain as text)
set gdirpathtemp to (path to temporary items folder from user domain as text)
set g_continue to true
set aFound to {}
set aIgnored to {}
end InitGlobals
-- ---------+---------+---------+------------------
on ChooseFolder(s)
tell application "Finder"
activate
if (s = "") then
set str to "Select the folder you wish to traverse?"
else
set str to s
end if
try
return choose folder with prompt str
on error
set g_continue to false
tell application "BBEdit" to activate
end try
end tell
end ChooseFolder
-- ---------+---------+---------+------------------
on ConfirmRequest(s)
tell application "BBEdit"
activate
set b1 to "Go Ahead..."
set b2 to "Forget It!"
set str to s & "Would you like to continue processing now?"
set aResult to display dialog str buttons {b1, b2} default button {b1}
if ((button returned of aResult) = b1) then
return true
else
return false
end if
end tell
end ConfirmRequest
-- ---------+---------+---------+------------------
on date_GetFullDate(theDate)
set ds to date string of (theDate)
set TS to time string of (theDate)
tell application "Finder"
set TS to ((get characters 1 thru -7 of TS) & (get characters -3 thru -1 of TS)) as string
end tell
set FD to (ds & " (" & TS & ")")
return FD
end date_GetFullDate
-- ---------+---------+---------+------------------
on processDirectory(thisFolder)
tell application "Finder"
set aItems to (get every item of folder thisFolder)
end tell
repeat with I from 1 to the count of aItems
set thisItem to (item I of aItems as alias)
set itemInfo to info for thisItem
set itemName to (name of itemInfo)
if ((folder of itemInfo) is true) then
my processDirectory(thisItem) -- It is a FOLDER
else if ((visible of itemInfo is true) and (alias of itemInfo is false)) then
if (((file type) of itemInfo) is in aFileTypes) then
set aFound to aFound & thisItem -- It is a valid file
else if (((name extension) of itemInfo) is in aExtensions) then
set aFound to aFound & thisItem -- It is a valid file
else
set aIgnored to aIgnored & thisItem -- It is NOT a valid file
end if
else
set aIgnored to aIgnored & thisItem -- It is NOT a valid file
end if
end repeat
end processDirectory
-- ---------+---------+---------+------------------
on error_HandleErrors(aErrorList, header_str, display_error, send2log)
if (header_str = "") then
set myheaderstr to "Errors were encountered during script execution..."
else
set myheaderstr to header_str
end if
if ((count of aErrorList) > 0) then
set s to ""
repeat with my_error in aErrorList
set s to s & my_error & return & return
end repeat
set s to header_str & return & return & s
if (display_error) then
display dialog s buttons {"OK"} default button {"OK"} with icon stop giving up after 15
end if
if (send2log) then
-- NEED TO INCLUDE ROUTINE TO SEND ERRORS TO THE LOG
-- next line is normally enabled
-- my writetofile(s, gfilepathlog, true) -- { (true -> append_data), (false -> overwrite) }
end if
end if
end error_HandleErrors
-- ---------+---------+---------+------------------ -
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 -
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
VishalJava 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 serverSince 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.
Maybe you are looking for
-
How to get name from JButton?
Hey Is it possible to get the name from a clicked JButton in the actionPerformed so that if i have for example 2 JButtons i can do an if statement to do different things when a button is clicked? For example if button1 is clicked the screen writes "Y
-
Creating a PDF with automatic page turn after playing a movie
Is there anyway to create a pdf where pages get turned automatically after a movie has been played? Simply put, I need to create a slideshow with both movies and images, and with an automatic page turn every x seconds the movies might be either too s
-
Setting filenames for images sequences via scripting
Is there a good way to set the output filename for a sequence via scriping? When I explicitly set the filename and render location, the frame number is being appended to the end of the extension. (example: "filename.png002").
-
TAB in a string not diplayed!?
I am using Labview 5.1 and I want to show a header part of a file in a labview program. I display the information using a string variable. There are tabulators in the header string to separate the information. These tabulators are diplayed as \t if I
-
Hi all, I'm a new user and i need your help. I made a web site that uses applet. This web site is perfectly if i using it from a internet connection without a proxy. With proxy, instead, i have a big problem: applet does not work. This problem is pre