Recursion... please help!

How can I develope a code that understands the Fibonacci-system? Say the answer that's gonna show on the console is fab(10)=89...
All I know is is
fab(0) = 0
fab(1) = 1
fab(2) = 1 = 0+1
fab(3) = 2 = 1+1
fab(4) = 3 = 1+2 and so on...

Just out of curiousity since you said that recursion
is a bad way to get the Fibonacci numbers... Can we
for instance use loop instead? But how? Here's a recursive and an iterative version. When n is like 40 the recursive takes seconds while the iterative isn't even measurable. 40 iterations in a while-loop and a few additions/assignments is nothing. Never use recursion when there's an obvious iterative alternative,
public static long fib1(int n) { // recursive
   return n<=2 ? 1 : fib1(n-1) + fib1(n-2); 
public static long fib2(int n) { // iterative
   long prev=1;
   long fib=1;
   while (--n > 1) {
      long t = fib;
      fib = fib + prev;
      prev = t;
   return fib;
}

Similar Messages

  • Please Help - Permutations using recursion..

    Please some body help me in generating permutaions using recursion..exact guidelines are as follows..
    Producing consecutive permutations.Need to develop a method that lists one by one all permutations of the numbers 1, 2, �, n (n is a positive integer).
    (a) Recursive method . Given a verbal description of the algorithm listing all permutations one by one, you are supposed to develop a recursive method with the following header:
    public static boolean nextPermutation(int[] array)The method receives an integer array parameter which is a permutation of integers 1, 2, �, n. If there is �next� permutation to the permutation represented by the array, then the method returns true and the array is changed so that it represents the �next� permutation. If there is no �next� permutation, the method returns false and does not change the array.
    Here is a verbal description of the recursive algorithm you need to implement:
    1. The first permutation is the permutation represented by the sequence (1, 2, �, n).
    2. The last permutation is the permutation represented by the sequence (n, �, 2, 1).
    3. If n a ,...,a 1 is an arbitrary permutation, then the �next� permutation is produced by
    the following procedure:
    (i) If the maximal element of the array (which is n) is not in the first position of the array, say i n = a , where i > 1, then just swap i a and i-1 a . This will give you the �next� permutation in this case.
    (ii) If the maximal element of the array is in the first position, so 1 n = a , then to find
    the �next� permutation to the permutation ( ,..., ) 1 n a a , first find the �next�
    permutation to ( ,..., ) 2 n a a , and then add 1 a to the end of thus obtained array of (n-1) elements.
    (iii) Consecutively applying this algorithm to permutations starting from (1, 2, �, n),you will eventually list all n! possible permutations. The last one will be (n, �, 2, 1).For example, below is the sequence of permutations for n = 3 .
    Please help...i have trying this for long time
    plesae help...i apreciate your time..and help..thank you

    public class Permu {
        public static boolean nextPermutation(int a[]) {
                return(permute(a, 0));
        public static boolean permute(int v[], int start) {
             int n = v.length;
             if (start == (n - 1)) {       //if its the end of the sequence genereated then print them
                count++;
                //print(v,n);
                return false;
            } else {
                for (int i = start; i < n; i++) { //swap the start element with the ith element to get n first sequeces
                    int temp = v[start];
                    v[start] = v;
    v[i] = temp;
    permute(v, start + 1);
    //of the n the first is kept constant the same is applied for the rest sequence
    //int tmp = v[i];
    v[i] = v[start];
    v[start] = temp;
    return true;
         public static void main(String[] args) {
    int v[] = {1, 2};//this is the array which should contain the items      to be permuted
    do{
    for(int i=0;i<2;i++)
    System.out.print(v[i]);
    System.out.println();
    }while(nextPermutation(v));
    [i]Output:
    123
    123
    123
    123
    123
    This is exact code i am trying to run...pls someone help me out...                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to make recursive query.Please help

    Dear Experts:
    I want to retrieve all employees located in a department in addition to all other employees located in the child's nodes of this department too.
    Problem Details:
    I have "Employees" table and "Departments" Table
    The structure of Dept Table is:
    ID   primary key
    parent_dept   foreign key(id)
    deptname  varchar2
    deptType varchar2
    The Employee table structure is
    ID primary key
    dept_id foreign key(Department.id)
    empName varchar2Sample data for departments
    ID : 1
    parent_dept : null
    deptname: General Manager office
    deptType : 'GM'
    ID :=2
    parent_dept : 1
    deptname: Information tech.
    deptType : 'DPT'
    ID :=3
    parent_dept : 2
    deptname: Software Development
    deptType : 'SECTION'Sample Data for employees
    ID : 101
    dept_id  :1
    empName  King
    ID : 102
    dept_id  :2
    empName  ALAN
    ID : 103
    dept_id  :2
    empName  SAM
    ID : 104
    dept_id  :3
    empName  JANEI want to create a query that accepts a parameter "p_department_id" and returns All employees on the following conditions
    1- In case the parameter value is null , then retrieve All Employees "king - alan- sam-jane"
    2- In Case the parameter value is 1 , then retrieve all the employees under department id =1 in addition to all the employees located under the children departments.
    in this case it will be "king - alan- sam-jane"
    3- In case parameter value is 2 , then return all the employees under department id =2 in addition to all the employees located under the children departments.
    In this case it will be " alan- sam-jane"
    4- In case parameter value is 3 , then return all the employees under department id =3 in addition to all the employees located under the children departments.
    in this case it will be only "JANE"
    In brief , If I pass any value to the parameter :p_department_id , I want to retrieve all employees located in this department in addition to other employees located in the child's nodes of this department id
    I use oracle database 11g release 2
    Please help me
    Thanks
    Edited by: ta**** on Apr 3, 2013 5:56 PM
    Edited by: ta**** on Apr 3, 2013 5:58 PM

    SQL> variable p_department_id number
    SQL> exec :p_department_id := null
    PL/SQL procedure successfully completed.
    SQL> with employees as (
      2                     select 101 id,1 dept_id,'King' empName from dual union all
      3                     select 102,2,'ALAN' from dual union all
      4                     select 103,2,'SAM' from dual union all
      5                     select 104,3,'JANE' from dual
      6                    ),
      7     departments as (
      8                     select 1 id,null parent_dept,'General Manager office' deptname,'GM' deptType from dual union all
      9                     select 2,1,'Information tech.','DPT' from dual union all
    10                     select 3,2,'Software Development','SECTION' from dual
    11                    )
    12  select  *
    13    from  employees
    14    where dept_id in (
    15                      select  id
    16                        from  departments
    17                        start with (
    18                                       (
    19                                            :p_department_id is null
    20                                        and
    21                                            parent_dept is null
    22                                       )
    23                                    or
    24                                       id = :p_department_id
    25                                   )
    26                        connect by parent_dept = prior id
    27                     )
    28  /
            ID    DEPT_ID EMPN
           101          1 King
           102          2 ALAN
           103          2 SAM
           104          3 JANE
    SQL> exec :p_department_id := 1
    PL/SQL procedure successfully completed.
    SQL> /
            ID    DEPT_ID EMPN
           101          1 King
           102          2 ALAN
           103          2 SAM
           104          3 JANE
    SQL> exec :p_department_id := 2
    PL/SQL procedure successfully completed.
    SQL> /
            ID    DEPT_ID EMPN
           102          2 ALAN
           103          2 SAM
           104          3 JANE
    SQL> exec :p_department_id := 3
    PL/SQL procedure successfully completed.
    SQL> /
            ID    DEPT_ID EMPN
           104          3 JANE
    SQL> SY.

  • Please help me on 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 recusive function which can generate a tree like category tree for customer navigation purpose.I don't know why my will loop only return once which means if category "vegetable" has two child and one of child has another child but the result will only display vegetable-->child-->grand child instead of vegetable-> 2 child -> one grand child of one of the child.Please help exam the codethax in

    Didn't I already answer this?

  • Recursion in java. please help

    I am writing a program for tree traversing as follows. The program is relatively long but please just focus on 2 lines with errors indicated.
    import java.io.*;
    import myBinaryTree;
    class myBinaryTreeTest{
         static int vertexArray[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 1, 3, 3, 7, 9, 11, 5, 11};     
         static myBinaryTree treeArray[] = new myBinaryTree[10];
         static myBinaryTree tree;
         static pTwoChildNode nodeParent, nodeLeft, nodeRight;
         static treeNodeData dataParent, dataLeft, dataRight;
         public static void main(String[] args) {
         for (int j=0; j<10; j++) {
         treeArray[j]=new myBinaryTree();
    boolean treeArrayEmpty;
    int treeArrayEmptyIndex;
    int treeArrayChildIndex, treeArrayParentIndex;
              int vertexCollapseChild, vertexCollapseParent;
              for (int i=0; i<20; i=i+2) {
    vertexCollapseChild=vertexArray;
    vertexCollapseParent=vertexArray[i+1];
    treeArrayEmptyIndex=-1;
    treeArrayChildIndex=-1;
              treeArrayParentIndex=-1;          
              for (int j=0; j<10; j++) {
                   if (treeArray[j].isEmpty()) {
    if (treeArrayEmptyIndex == -1) {
    treeArrayEmptyIndex=j;
    else {
    dataParent = (treeNodeData)treeArray[j].getData();
                   if (vertexCollapseChild==dataParent.vertex)
    {treeArrayChildIndex=j;};
    if (vertexCollapseParent==dataParent.vertex)
    {treeArrayParentIndex=j;};
    if (treeArrayChildIndex != -1 && treeArrayParentIndex != -1)
                        {break;}
    updateTreeArray(treeArrayChildIndex, treeArrayParentIndex,
                        treeArrayEmptyIndex, vertexCollapseChild,
    vertexCollapseParent);
              for (int j=0; j<10; j++) {                                               
                   System.out.println("\nIn-order:");
                   preOTrav(treeArray[j].getRoot());
         static void updateTreeArray(int c, int p, int e, int cc, int cp) {
                                  // c=treeArrayChildIndex
                                  // p=treeArrayParentIndex
                                  // e=treeArrayEmptyIndex
                                  // cc=vertexCollapseChild
                                  // cp=vertexCollapseParent
    System.out.println(c+" "+p+" "+e+" "+cc+" "+cp);
         if (c != -1) {
    if (p != -1) {
         dataParent = new treeNodeData();
              dataRight = (treeNodeData)treeArray[p].getData();
    dataParent.vertex=dataRight.vertex;
              nodeParent=new pTwoChildNode(dataParent);
    nodeParent.setLeft(treeArray[c].getRoot());
    nodeParent.setRight(treeArray[p].getRoot());
    treeArray[Math.min(c, p)].setRoot(nodeParent);
    treeArray[Math.max(c, p)].setRoot(null);
         else
              dataParent = new treeNodeData();
    dataParent.vertex=cp;
              nodeParent=new pTwoChildNode(dataParent);
    nodeParent.setLeft(treeArray[c].getRoot());
              dataRight = new treeNodeData();
    dataRight.vertex=cp;
              nodeParent.setRight(new pTwoChildNode(dataRight));
    treeArray[Math.min(c, e)].setRoot(nodeParent);
              treeArray[Math.max(c, e)].setRoot(null);
    else
    if (p != -1) {
    dataParent = new treeNodeData();
    dataRight = (treeNodeData)treeArray[p].getData();
    dataParent.vertex=dataRight.vertex;
              nodeParent=new pTwoChildNode(dataParent);
    dataLeft = new treeNodeData();
    dataLeft.vertex=cc;
    nodeParent.setLeft(new pTwoChildNode(dataLeft));
    nodeParent.setRight(treeArray[p].getRoot());
    treeArray[Math.min(p, e)].setRoot(nodeParent);
              treeArray[Math.max(p, e)].setRoot(null);
              else {
    dataParent=new treeNodeData();
    dataParent.vertex=cp;
              nodeParent=new pTwoChildNode(dataParent);
    dataRight=new treeNodeData();
    dataRight.vertex=cp;
              nodeRight=new pTwoChildNode(dataRight);
    nodeParent.setRight(nodeRight);
    dataLeft=new treeNodeData();
    dataLeft.vertex=cc;
              nodeLeft=new pTwoChildNode(dataLeft);
    nodeParent.setLeft(nodeLeft);
    treeArray[e].setRoot(nodeParent);
         static void preOTrav(pTwoChildNode n) {
              if (n == null)
              return;
              dataParent=(treeNodeData)n.getData();
              System.out.print(dataParent.vertex+" ");
              preOtrav(n.getLeft());
              preOtrav(n.getRight());
    //problems are here!!!!!
    class treeNodeData {
         int vertex;
         // data element2 -> a set of vertex fan;
    It doesn't compile but with the message saying that can not resolve the symbol in preOTrav(n.getLeft()); and preOTrav(n.getRight());
    Please help!

              preOtrav(n.getLeft());
              preOtrav(n.getRight());Don't write preOtrav when you mean preOTrav. Java is case-sensitive.
    Jesper

  • Statspack Problem(Please Help)

    Hi,
    I got the below error from Statspack report run. It runs after every one hour and the database version is 9.2.0.8. Please help how to resolve it.
    ERROR: Database/Instance does not exist in STATS$DATABASE_INSTANCE
    ERROR: Begin Snapshot Id specified does not exist for this database/instance
    ERROR: End Snapshot Id specified does not exist for this database/instance
    WARNING: timed_statitics setting changed between begin/end snaps: TIMINGS ARE IN
    VALID
    ERROR: Snapshots chosen span an instance shutdown: RESULTS ARE INVALID
    ERROR: Session statistics are for different sessions: RESULTS NOT PRINTED
    begin
    ERROR at line 1:
    ORA-20100: Missing Init.ora parameter db_block_size
    ORA-06512: at "PERFSTAT.STATSPACK", line 727
    ORA-06512: at "PERFSTAT.STATSPACK", line 1126
    ORA-06512: at line 2
    STATSPACK report for
    DB Name DB Id Instance Inst Num Release Cluster Host
    :ela := ;
    ERROR at line 4:
    ORA-06550: line 4, column 17:
    PLS-00103: Encountered the symbol ";" when expecting one of the following:
    ( - + case mod new not null <an identifier>
    <a double-quoted delimited-identifier> <a bind variable> avg
    count current exists max min prior sql stddev sum variance
    execute forall merge time timestamp interval date
    <a string literal with character set specification>
    <a number> <a single-quoted SQL string> pipe
    The symbol "null" was substituted for ";" to continue.
    ORA-06550: line 6, column 16:
    PLS-00103: Encountered the symbol ";" when expecting one of the following:
    ( - + case mod new not null <an identifier>
    <a double-quoted delimited-identifier> <a bind variable> avg
    count current exists max min prior sql stddev su
    Cache Sizes (end)
    ~~~~~~~~~~~~~~~~
    Buffer Cache: M Std Block Size: K
    Shared Pool Size: M Log Buffer: K
    Load Profile
    ~~~~~~~~~~~ Per Second Per Transaction
    Redo size:
    Logical reads:
    Block changes:
    Physical reads:
    Physical writes:
    User calls:
    Parses:
    Hard parses:
    Sorts:
    Logons:
    Executes:
    Transactions:
    % Blocks changed per Read: Recursive Call %:
    Rollback per transaction %: Rows per Sort:
    Instance Efficiency Percentages (Target 100%)
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Buffer Nowait %: Redo NoWait %:
    Buffer Hit %: In-memory Sort %:
    Library Hit %: Soft Parse %:
    Execute to Parse %: Latch Hit %:
    Parse CPU to Parse Elapsd %: % Non-Parse CPU:
    SGA Memory Summary for DB: Instance: Snaps: 23410 -23412
    SGA regions Size in Bytes
    sum
    End of Report
    UNDO Usage
    Free space in GB 29.52
    USED space in GB 75.2
    TEMP_TABLESPACE MB_TOTAL MB_USED MB_FREE
    TEMP 208162 6 208156
    WHS_CUBES_TEMP 33000 0 33000
    WHS_VIEWER_TEMP 67688 0 67688
    HP-UX eesci007 B.11.11 U 9000/800 08/18/10
    04:00:44 %usr %sys %wio %idle
    04:00:49 57 29 13 2
    04:00:54 57 24 17 2
    04:00:59 57 29 11 2
    04:01:04 54 31 13 3
    04:01:09 51 33 13 3
    Average 55 29 14 2
    procs memory page faults cpu
    r b w avm free re at pi po fr de sr in sy cs us sy id
    5 6

    user605926 wrote:
    Hi,
    I got the below error from Statspack report run. It runs after every one hour and the database version is 9.2.0.8. Please help how to resolve it.
    ERROR: Database/Instance does not exist in STATS$DATABASE_INSTANCE
    ERROR: Begin Snapshot Id specified does not exist for this database/instance
    ERROR: End Snapshot Id specified does not exist for this database/instance
    WARNING: timed_statitics setting changed between begin/end snaps: TIMINGS ARE IN
    VALID
    ERROR: Snapshots chosen span an instance shutdown: RESULTS ARE INVALID
    ERROR: Session statistics are for different sessions: RESULTS NOT PRINTED
    begin
    ERROR at line 1:
    ORA-20100: Missing Init.ora parameter db_block_size
    ORA-06512: at "PERFSTAT.STATSPACK", line 727
    ORA-06512: at "PERFSTAT.STATSPACK", line 1126
    ORA-06512: at line 2
    You might want to take a look at the docs: http://download.oracle.com/docs/cd/B10500_01/server.920/a96533/statspac.htm#21708
    Note:
    It is not correct to specify begin and end snapshots where the begin snapshot and end snapshot were taken from different instance startups. In other words, the instance must not have been shutdown between the times that the begin and end snapshots were taken.
    At the first part of the report the database id is given. Do a select * from STATS$DATABASE_INSTANCE and verify that the DBID present matches the database/instance you are attempting to run the reprot upon. The report should be ran from the same instance in which the snapshots were taken.

  • Please help...my browser can't display applets

    I know it might sound inept to be asking something about my mozilla browser in this forum but right now I am studying Java and using my browser to view the applet exercises I make. I am particularly in the methods section where you have to make recursions (I am using JAVA 2 how to program Third Edition by Deitel). I made my own version of the fibonacci program in the book . It has a GUI, action listener and the method where all the calculations take place. Unfortunately, when I test it on my brower, Mozilla Fireforx, it just displays the GUI and whole program does not work. The compiler, in this case javac, cannot sense anything wrong and I take it that my code is correct. However nothing still happens when I test it on my browser. As previously mentioned, it just displays the GUI and that's all. I really do not know what is wrong. Is it with my code or with the browser? Or is with the fact that I am using an outdated version of JAVA 2 how to program with a new version of J2SDK that makes my code incompatible with the new technology? please help. TY
    Here's my code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class AppletCode extends JApplet implements ActionListener {
         JLabel inputLabel, outputLabel;
         JTextField input, output;
         public void init(){
              Container c = getContentPane();
              c.setLayout(new FlowLayout());
              JLabel inputLabel = new JLabel();
              inputLabel.setText("Enter an Integer and press Enter");
              c.add(inputLabel);
              JTextField input = new JTextField(10);
              input.addActionListener(this);
              c.add(input);
              JLabel outputLabel = new JLabel();
              outputLabel.setText("Fibonacci Value is");
              c.add(outputLabel);
              JTextField output = new JTextField(20);
              output.setEditable(false);
              c.add(output);
         } // GUI
         public void actionPerformed(ActionEvent e) {
              long number, fibonacciValue;
              number = Long.parseLong(input.getText());
              fibonacciValue = fibonacci(number);
              output.setText(Long.toString(fibonacciValue));
         } // Action Listener
         public long fibonacci(long x) {
              if (x==0 || x==1)
                   return x;
              else
                   return fibonacci(x-1) + fibonacci(x-2);
         } // Fibonacci Module
    }

    I don't see anything obviously wrong with your code, but it's been a while since i coded applets, so there might still be something wrong. What exactly does not work? You see the 2 labels and the text fields? Can you enter any text into the text field? Have you looked into the Java Console wether it prints any exceptions? (and please use the [ code][ /code] tags to mark your code (without the spaces obviously))

  • Please help finding pre-exsisting methods

    please help find pre-existing methods
    JavaFirstTime Jan 2, 2005 3:21 PM
    please help clever people :)
    how to output decimals in 2 decimal places only?
    how to output large integers using format: 12,376,452
    I've been told there are pre-existing methods for that, but i just can't find it... ideally i need to know the source code...

    Well, there's many ways to do it ... Here's one:
    class NumberFormatDemo {
    public static void main(String[] args) {
    new NumberFormatDemo().go();
    public void go() {
    double decimal = 123.456;
    System.out.println((int) decimal + "." + (int)
    + (int) (decimal * 100 + 0.5) % 100);
    int largeInteger = 12376452;
    System.out.println(recursive(largeInteger));
    public String recursive(int largeInteger) {
    if (largeInteger > 999) {
    return recursive(largeInteger/1000) + ","
    1000) + "," + largeInteger%1000;
    } else {
    return "" + largeInteger;
    yes, that's exactly wot i need...
    how didn't i think of that myself, using mathematics, i was thinking it would be more complicated like converting decimals to string then count letters and so on.
    Thank you for putting me on the right track :)

  • Please help!! Semester Project due in 3 days...........

    I have a connectivity problem where I have to select a number of vertices(N) and
    connect them with random non repeating edges(M). I have to test with cases
    M=.1xNxN, M=.2xNxN,.............M= .9xNxN. Well, it works up to M=.2xNxN when using 10 edges but I get a Stackoverflow error with more than M=.2xNxN.
    Please Please help. I have two classes
    import java.util.Random;import java.util.Scanner;
    * Write a description of class QuickUnion here.
    * @author (your name)
    * @version (a version number or a date)
    public class Union
        private Random generator;
        int E1,E2; int count = 0; int n = 50000;
         int a[] = new int [n];
        int b[] = new int [n];
         //Actual random number generator
         public int Generator(int gen){
             generator = new Random();      
            return generator.nextInt(gen);}
        //Method uses Random Generator to get E1,E2(or p,q) values
        public void Generator(int e1, int e2, int N){
            E1=Generator(N-1);
            E2=Generator(N-1);
            while(E1==E2){E2=Generator(N);}
            check(E1,E2,N);}
        //Method checks both array a and b at the same time for p,q or q,p values already generated
        public void check(int e1, int e2, int N){
            for(int i=0; i<a.length; i++){
                if(((a==e1) && (b[i]==e2)) || ((b[i]==e1) && (a[i]==e2))){
    Generator(0,0,N); }}
    a[count]=e1; b[count]=e2; count++;
    //Methods to view a and b arrays
    public void arrayShow(){
    for(int k=0; k<a.length; k++){System.out.print(a[k] + " ");
    public void arrayShow2(){
    for(int k=0; k<a.length; k++){System.out.print(b[k] + " ");
    import java.util.*; import java.util.Scanner;
    * QUICKFIND QUICKFIND QUICKFIND
    * @author Degrion Hill
    * @version 3160 Project Program
    public class Client2
    {public static void main(String[] args)
    int answer =0;
    int N,E1,E2,counter= 0;
    Scanner in = new Scanner(System.in);
    // User Input for amount of Vertices
    System.out.println("Enter the number of Vertices");
    N=in.nextInt();
    //Populating Array
    int id[] = new int [N];
    for(int i = 0; i < N; i++){id[i]=i;}
    //User input for amount of edges
    System.out.println("Enter the number of edges");
    int edges = in.nextInt();
    Union test = new Union();
    //Random Edge Generator
    while(counter<edges){
    test.Generator(0,0,N);
    //Assignment of Random number to p,q values to make edge
    int p = test.E1, q = test.E2;
    int t = id[p];
    //Quick Find Algorithm
    System.out.println("p=" + p + " " + "q=" + q); counter++;
    for(int k =0; k < N; k++){
    System.out.print(" " + id[k]);}
    System.out.print("\n");
    if (t==id[q])continue;
    for(int i = 0; i<N; i++)
    if(id[i]==t) id[i]=id[q];
    System.out.println("SORTED");
    //Sort the array before Counting groups(Using Bubble Sort)
    Sort test2 = new Sort();
    test2.bubble(id,0,id.length-1);
    for(int m =0; m < N; m++){
    System.out.print(" " + id[m]);}
    //Count changes in the array(groups)
    int y=0; int group=0;
    for(int x=0; x<N; x++){
    if(x==0){id[y]=id[x];}
    if(id[x] != id[y]){id[y]=id[x];group++;}}
    System.out.println();
    System.out.println(group+1 + " Group/s");
    System.out.print("");
    System.out.println("Run Again? [1 for YES, 2 for NO]");
    answer=in.nextInt();
    //(Testing) Shows a and b arrays to see if ALL cases for p,q are there
    if(answer==1){main(args);} test.arrayShow(); System.out.println(""); test.arrayShow2();

    Whithout diving into your code: StackOverFlowError occurs usually if you do a recursion and don't stop it before memory blows.

  • Parse into array using JDOM! please help

    hey,
    i've managed to parse an xml document using JDOM
    i[b] need to be able to parse it and store the text (the value of each node) into an array, and then insert into db etc.
    the problem is with the recursive function listChildren which calls itself... can someone tell me where do i insert the block of code such that i can store it into an array of string.
    here's the code:
    public static void parse(String stock) throws SQLException
    SAXBuilder builder = new SAXBuilder();
    Reader r = new StringReader(stock);
    Document doc = builder.build(r);
    Element root = doc.getRootElement();
    listChildren(root, 0);
    public static void listChildren(Element current, int depth) throws Exception
    String nodes = current.getName();
    System.out.println(nodes + " : " + current.getText());
    List children = current.getChildren();
    Iterator iterator = children.iterator();
    while(iterator.hasNext())
    Element child = (Element) iterator.next();
    listChildren(child, depth+1);
    i'm looking for something like:
    a=current.getText();
    but i donno where to include this line of code, please help
    cheers,
    Shivek Sachdev

    hi, I suggest you make an array of byte arrays
    --> Byte[][] and use one row for each number
    you can do 2 things,
    take each cipher of one number and put one by one in each column of the row correspondent to that number. of course it may take too much room if the int[] is too big, but that is the easiest way I think
    the other way is dividing your number into bitsets(class BitSet) with sizes of 8 bits and then you can save each bit into each column of your array. and you still have one number in each row. To put your numbers back use the same class.
    Maybe someone has an easier way, I couldnt think of any.

  • How to integrate java + OpenCv. Please help me!!!

    Hi all.
    I am researching OpenCV and how to integrate OpenCV with java.
    If you have any experience with this problem please help me.
    OpenCV + Java . Can i control PTZ of logitech Usb webcam ?
    Thanks in advance.
    Diego
    Edited by: ThuCT on Jun 30, 2009 9:34 PM

    A recursive function is simply a function that calls itself sometimes. You have to be careful, because if it always calls itself, you have an "infinite regression" where it never stops calling itself and you get stack overflow. I don't know what recursion has to do with traversing result sets, but I can give you a simple example of a recursive function (statements can't be recursive):
    public class ArithmeticFunctions
         static int GreatestDivisor(int i, int j)
              if (j = 0) return i
                   else return GreatestDivisor(j, i%j); // this is the recursive part
         }This code will use Euclid's algorithm to quickly find the greatest common divisor of two numbers, i.e. GCD(27, 9) = 9; GCD(9, 6) = 3; GCD(25, 15) = 5
    Doug

  • DNS Setup Check Required...Please Help

    I have setup a Tiger Server machine running 10.4.9 (IP: 10.0.1.2)
    It is running a DNS server (smserver.strategies.ca)
    The following aliases have been set: mail, www, ftp, vpn. ns1
    Recursion is ON
    Zone Transfer is ON
    Our Airport Extreme N Router has a static public IP
    Port forwarding TCP/UDP on port 53 has been made on the router to point to the server (10.0.1.2)
    At our registrar, I put the primary nameserver to be smserver.strategies.ca with the IP being the static public IP I put on the Airport Extreme Router.
    Something is not working.
    From the outside, if I do:
    host smserver.strategies.ca
    I get Host smserver.strategies.ca not found: 3(NXDOMAIN)
    Same thing if I try with any of the aliases I created.
    What am I missing or doing wrong? Are there any files I need to edit?
    Please help as this is pretty urgent. It needs to result with the public static IP set on the router.
    Thanks to all in advance.

    Your DNS is incorrect.
    If I run host smserver.strategies.ca I get:
    smserver.strategies.ca has address 10.0.1.2
    You shouldn't ever publish 10.x.x.x addresses to the public internet. They're not valid.
    If this machine is running public DNS for your domain you need to enter the proper, valid public IP addresses in your zone file, not your internal addresses.
    If you want your internal clients to see a different result then you need to setup two DNS servers, one for the public view and one for internal. This can be done via one BIND server, using views (which use the source IP address of the query to determine which result to return), but you can't do this via Server Admin, only manually.

  • Low performance (please help)

    Hi!
    My DB objects are:create or replace TYPE T_G5RPP AS VARRAY(1000) OF NUMBER(2);
    CREATE TABLE "ROGADM"."ROG_TEMP_G5LKL" (
        "ID"     VARCHAR2(100 BYTE),
        "STATUS" NUMBER(2,0) DEFAULT 1,
        "G5IDL"  VARCHAR2(200 BYTE),
        "G5TLOK" NUMBER(1,0),
        "G5PEW"  NUMBER,
        "G5PPP"  NUMBER,
        "G5LIZ"  NUMBER(32,0),
        "G5LPP"  NUMBER(6,0),
        "G5RPP"  "ROGADM"."T_G5RPP",
        "G5WRT"  NUMBER(32,0),
        "G5DWR"  DATE,
        "G5DTW"  DATE,
        "G5DTU"  DATE,
        "ID_G5ADR_RADR" VARCHAR2(100 BYTE),
        "ID_G5JDR_RJDR" VARCHAR2(100 BYTE),
        "ID_G5BUD_RBUD" VARCHAR2(100 BYTE),
        "IDR"           VARCHAR2(100 BYTE),
        "PLS_ID"        NUMBER
    CREATE INDEX "T_G5LKL_ADR_FK" ON "ROG_TEMP_G5LKL" (PLS_ID, "ID_G5ADR_RADR");
    CREATE INDEX "T_G5LKL_BUD_FK" ON "ROG_TEMP_G5LKL" (PLS_ID, "ID_G5BUD_RBUD");
    CREATE INDEX "T_G5LKL_JDR_FK" ON "ROG_TEMP_G5LKL" (PLS_ID, "ID_G5JDR_RJDR");
    create unique index T_G5LKL_PK on ROG_TEMP_G5LKL(PLS_ID, ID);
    function get_obr_ark_dzi(p_obk_typ varchar2, p_obk_id varchar2, p_co varchar2, p_pls_id number)
      return varchar2 deterministic
    AS
      v_obk_typ varchar2(10);
      v_obk_id  G5ADR.ID%type;
      v_out   varchar2(400);
      v_sep   varchar2(2) := '';
      v_old   varchar2(10) := '';
      v_pls_id    number;
    begin
      if p_obk_typ not in ('G5DZE','G5BUD','G5LKL','G5OBR','G5KLU','G5UDZ','G5UDW','G5JDR', 'G5ADR') then
        return null;
      end if;
      v_obk_typ := p_obk_typ;
      v_obk_id  := p_obk_id;
      v_pls_id  := p_pls_id;
      if v_obk_typ = 'G5ADR' then
        -- sprawdzenie, adresem czego jest ten adres
        -- (odczytane będą dane dla adresów działek, budynków lub lokali, które są podpięte do tylko 1 obiektu)
        declare
          v_id  G5LKL.ID%type;
          v_co  varchar2(3);  -- ...jest adresem tego
        begin
          /** START **/
          begin
            v_co := 'LKL';
            execute immediate 'SELECT ID FROM ROG_TEMP_G5LKL WHERE ID_G5ADR_RADR = :obk AND pls_id = :pls'
               into v_id
              using v_obk_id, v_pls_id;
          exception when no_data_found then
            v_co := null;
          end;
          /** END **/
          if v_co is not null then
            v_obk_typ := 'G5'||v_co;
            v_obk_id  := v_id;
          else
            return null;
          end if;
        end;
      end if;
      if v_obk_typ = 'G5LKL' then
        execute immediate
    '   SELECT case when :p_co=''obreb'' then    SUBSTR(G5IDL,10,4)
                    when :p_co=''arkusz'' then   SUBSTR(G5IDL,18,INSTR(G5IDL,''.'',-1,3)-18)
                    when :p_co=''dzialka'' then  SUBSTR(G5IDL,
             instr(G5IDL,''.'',1,2 + case when SUBSTR(G5IDL,15, 3)=''AR_'' then 1 else 0 end) + 1,
             instr(G5IDL,''.'',-1,2)-1 - instr(G5IDL,''.'',1,2 + case when SUBSTR(G5IDL,15, 3)=''AR_'' then 1 else 0 end))
               end
          FROM ROG_TEMP_G5LKL
         WHERE ID = :p_obk_id AND pls_id = :pls' into v_out using p_co,p_co,p_co, v_obk_id, v_pls_id;
      else
        return null;
      end if;
      return v_out;
    exception
      when no_data_found then
        return null;
    end get_obr_ark_dzi;I have a query:SELECT log_pls_id,log_obk_id,
           log_obk_typ
           ,rog_pck_utl.get_obr_ark_dzi(log_obk_typ, log_obk_id, 'obreb', log_pls_id) AS log_obk_obreb
      FROM (SELECT distinct log_obk_id, log_obk_typ, log_pls_id
              FROM rog_log_ksat_zdarzenia
              JOIN rog_log on logkz_log_id = log_id
             WHERE logkz_f_obsluzony <> 'T')
       where log_obk_typ = 'G5ADR' and log_pls_id = 635 and rownum <= 200; which runs 7.2 seconds. When I comment the block bounded by /** START **/ and /** END **/ the query runs only 0.043 seconds.
    Here is part of trace file:SELECT log_pls_id,log_obk_id,
           log_obk_typ
           ,rog_pck_utl.get_obr_ark_dzi(log_obk_typ, log_obk_id, 'obreb', log_pls_id) AS log_obk_obreb
      FROM (SELECT distinct log_obk_id, log_obk_typ, log_pls_id
              FROM rog_log_ksat_zdarzenia
              JOIN rog_log on logkz_log_id = log_id
             WHERE logkz_f_obsluzony <> 'T')
       where log_obk_typ = 'G5ADR' and log_pls_id = 635 and rownum <= 200
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        1      0.00       0.00          0          0          0           0
    Execute      1      0.00       0.00          0          0          0           0
    Fetch        1      0.06       0.10          0       2480          0         200
    total        3      0.06       0.11          0       2480          0         200
    Misses in library cache during parse: 1
    Optimizer mode: ALL_ROWS
    Parsing user id: 379  (ROGADM)
    Rows     Execution Plan
          0  SELECT STATEMENT   MODE: ALL_ROWS
          0   COUNT (STOPKEY)
          0    VIEW
          0     SORT (UNIQUE NOSORT)
          0      TABLE ACCESS   MODE: ANALYZED (BY INDEX ROWID) OF
                     'ROG_LOG_KSAT_ZDARZENIA' (TABLE)
          0       NESTED LOOPS
          0        TABLE ACCESS   MODE: ANALYZED (BY INDEX ROWID) OF
                       'ROG_LOG' (TABLE)
          0         INDEX   MODE: ANALYZED (RANGE SCAN) OF 'LOG_I'
                        (INDEX (UNIQUE))
          0        INDEX   MODE: ANALYZED (RANGE SCAN) OF
                       'LOGKZ_LOG_FK_I' (INDEX)
    SELECT ID
    FROM
    ROG_TEMP_G5LKL WHERE ID_G5ADR_RADR = :obk AND pls_id = :pls
    call     count       cpu    elapsed       disk      query    current        rows
    Parse       42      0.00       0.00          0          0          0           0
    Execute     98      0.00       0.00          0          0          0           0
    Fetch       98      7.82       7.58          0    4519564          0           0
    total      238      7.82       7.58          0    4519564          0           0
    Misses in library cache during parse: 0
    Optimizer mode: ALL_ROWS
    Parsing user id: 379  (ROGADM)   (recursive depth: 1)
    Rows     Row Source Operation
          0  TABLE ACCESS BY INDEX ROWID ROG_TEMP_G5LKL (cr=138354 pr=0 pw=0 time=231295 us)
    205593   INDEX RANGE SCAN T_G5LKL_PK (cr=576 pr=0 pw=0 time=411229 us)(object id 433034)
    Rows     Execution Plan
          0  SELECT STATEMENT   MODE: ALL_ROWS
          0   TABLE ACCESS   MODE: ANALYZED (BY INDEX ROWID) OF
                  'ROG_TEMP_G5LKL' (TABLE)
    205593    INDEX   MODE: ANALYZED (RANGE SCAN) OF 'T_G5LKL_ADR_FK' (INDEX)
    (...)What do you think is the reason of such big value in 'query' column of 'Fetch'?
    Explain plan executed from SQL Developer is different:explain plan for
    SELECT ID
      FROM ROG_TEMP_G5LKL
    WHERE ID_G5ADR_RADR = :adr
       AND pls_id = 630;
    PLAN_TABLE_OUTPUT
    Plan hash value: 3052821629
    | Id  | Operation                   | Name           | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT            |                |     1 |   117 |     3   (0)| 00:00:01 |
    |*  1 |  TABLE ACCESS BY INDEX ROWID| ROG_TEMP_G5LKL |     1 |   117 |     3   (0)| 00:00:01 |
    |*  2 |   INDEX RANGE SCAN          | T_G5LKL_PK     |     1 |       |     2   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       1 - filter(ID_G5ADR_RADR=:ADR)
       2 - access(PLS_ID=630)Please help...

    Yes, this index can be unique:SELECT count(*)
      FROM ROG_TEMP_G5LKL
    GROUP BY pls_id, ID_G5ADR_RADR
    HAVING count(*) > 1;
    no rows selectedUnfortunately statistics are not up to date. I can't gather it, because DBA must fix some DB blocks first.
    Edited by: JackK on Aug 5, 2011 7:20 AM
    I've found something! When I add a condition to WHERE clause:SELECT log_pls_id,log_obk_id,
           log_obk_typ
           ,rog_pck_utl.get_obr_ark_dzi(log_obk_typ, log_obk_id, 'obreb', log_pls_id) AS log_obk_obreb
           ,rog_pck_utl.get_obr_ark_dzi(log_obk_typ, log_obk_id, 'arkusz', log_pls_id) AS log_obk_AR
           ,rog_pck_utl.get_obr_ark_dzi(log_obk_typ, log_obk_id, 'dzialka', log_pls_id) AS log_obk_dze
      FROM (SELECT distinct log_obk_id, log_obk_typ, log_pls_id
              FROM rog_log_ksat_zdarzenia
              JOIN rog_log on logkz_log_id = log_id
             WHERE logkz_f_obsluzony <> 'T')
       where log_obk_typ = 'G5ADR' and log_pls_id = 635 and rownum <= 200
         and exists (select 1 from g5lkl where id_g5adr_radr = log_obk_id);   -- added conditionthe statement runs in about 1 second. Without the condition it takes 22.4 seconds to complete. I think that's because in the latter case the querySELECT ID FROM G5LKL ... did not find any row.
    Edited by: JackK on Aug 8, 2011 6:16 AM
    I changed the index T_G5LKL_ADR_FK to:CREATE INDEX T_G5LKL_ADR_FK_ID ON ROG_TEMP_G5LKL (PLS_ID, ID_G5ADR_RADR, ID);and it runs fast enought - *200 rows in 1-2 seconds*. Now the plan shows only INDEX RANGE SCAN.

  • Problem with threads and simulation: please help

    please help me figure this out..
    i have something like this:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class DrawShapes extends JApplet{
         private JButton choices[];
         private String names[]={"line", "square", "oval"};
         private JPanel buttonPanel;
         private DrawPanel drawingArea;
         private int width=300, height=200;
         public void init(){
              drawingArea=new DrawPanel(width, height);
              choices=new JButton[names.length];
              buttonPanel=new JPanel();
              buttonPanel.setLayout(new GridLayout(1, choices.length));
              ButtonHandler handler=new ButtonHandler();
              for(int i=0; i<choices.length; i++){
                   choices=new JButton(names[i]);
                   buttonPanel.add(choices[i]);
                   choices[i].addActionListener(handler);
              Container c=getContentPane();
              c.add(buttonPanel, BorderLayout.NORTH);
              c.add(drawingArea, BorderLayout.CENTER);
         }//end init
         public void setWidth(int w){
              width=(w>=0 ? w : 300);
         public void setHeight(int h){
              height=(h>=0 ? h : 200);
         /*public static void main(String args[]){
              int width, height;
              if(args.length!=2){
                   height=200; width=300;
              else{
                        width=Integer.parseInt(args[0]);
                        height=Integer.parseInt(args[1]);
              JFrame appWindow=new JFrame("An applet running as an application");
              appWindow.addWindowListener(
                   new WindowAdapter(){
                        public void windowClosing(WindowEvent e){
                             System.exit(0);
              DrawShapes appObj=new DrawShapes();
              appObj.setWidth(width);
              appObj.setHeight(height);
              appObj.init();          
              appObj.start();
              appWindow.getContentPane().add(appObj);
              appWindow.setSize(width, height);
              appWindow.show();
         }//end main*/
         private class ButtonHandler implements ActionListener{
              public void actionPerformed(ActionEvent e){
                   for(int i=0; i<choices.length; i++){
                        if(e.getSource()==choices[i]){
                             drawingArea.setCurrentChoice(i);
                             break;
    }//end class DrawShapes
    class DrawPanel extends JPanel{
         private int currentChoice=-1;
         private int width=100, height=100;
         public DrawPanel(int w, int h){
              width=(w>=0 ? w : 100);
              height=(h>=0 ? h : 100);
         public void paintComponent(Graphics g){
              super.paintComponent(g);
              switch(currentChoice){
                   case 0:     g.drawLine(randomX(), randomY(), randomX(), randomY());
                             break;
                   case 1: g.drawRect(randomX(), randomY(), randomX(), randomY());
                             break;
                   case 2: g.drawOval(randomX(), randomY(), randomX(), randomY());
                             break;
         public void setCurrentChoice(int c){
              currentChoice=c;
              repaint();          
         private int randomX(){
              return (int) (Math.random()*width);
         private int randomY(){
              return (int) (Math.random()*height);
    }//end class drawPanel
    That one's from a book. I used that code to start with my applet. Mine calls different merthod from the switch cases. Say I have:
    case 0: drawStart(g); break;
    public void drawStart(Graphics g){
      /* something here */
    drawMain(g);
    public void drawMain(graphics g){
    g.drawString("test", x, y);
    //here's where i'm trying to pause
    //i've tried placing Thread.sleep between these lines
    g.drawLine(x, y, a, b);
    //Thread.sleep here
    g.drawRect(x, y, 50, 70);
    }I also need to put delays between method calls but I need to synchronize them. Am I doing it all wrong? The application pauses or sleeps but afterwards, it still drew everything all at once. Thanks a lot!

    It is. Sorry about that. Just answer any if you want to. I'd appreciate your help. Sorry again if it caused you anything or whatever. .n_n.

  • Apple Mini DVI to Video Adapter is not working. Please Help...

    I bought an Apple Mini DVI to Video Adapter to connect my Macbook to a TV using normal video cable. When I connect the cable, my Laptop DIsplay gives a flickr once and then it shows nothing. I checked Display in the system preference where I don't get a secondary monitor option. My TV is panasonic and it's an old one. I work on Final Cut Pro and it's very very important to see my videos on a TV. What am I doing wrong with the connection? Anyone Please Please help...

    Your probably not doing anything wrong. There are thousands of users with Similar issues and it seems to be with many different adapters.
    We have Mini DP to VGA (3 different brands) and they all fail most of the time. This seems more prevalent with LCD Projectors. I've tested some (50+) with VGA Monitor (HP) and they all worked, LCD Projector (Epson, Hitachi, and Sanyo) and they all fail, DLP Projector (Sanyo) and one worked.
    My Apple Mini DP to DVi works most of the time. My Mini DP to HDMI (Generic non Apple) works every time.
    The general consensus is that Apple broke something in the OS around 10.6.4 or 10.6.5 and its not yet fixed. As we are a school we have logged a case with the EDU Support group so will see what happens.
    Dicko

  • PSE icons instead of the photo. I need to view photos at a glance. Please help me????

    Please help, this is driving me crazy.  I have downloaded my free PSE #9, it came with my Leica Camera.  I cannot view at a glance any of my photos.  There is only an icon that reads, PSE.  To view any of my photos, I must click select and then preview.  This gets old, and I am doing 4 times the work. I am having to use the dates to guess where my photos might be.  I hate this!  My old Photo Shop #5 didn't do this.  When you went to my pictures, you could see every photo.
    I have tried the right click and open as any program.  What ever program I choose, that is the icon that appears.  No photo. Still no good.
    Please help.
    Thanking anyone in advance,
    Leica

    Hi,
    Are you using Windows Explorer to view the files?
    If so, load Explorer, go to the Tools menu and select Folder Options.
    Click on the View tab and make sure the first option (Always show icons, never thumbnails) is not checked.
    Click on OK and see if that is any better.
    Brian

Maybe you are looking for

  • Why do i have 2 of the same pictures on my computer

    When i import photos there always ends up being 2 of them... i always select don't add duplicates. But for instance when I put a picture in it goes under to categorires My name->Pictures->Iphoto Library->Masters->2008->Roll 92->Image name            

  • My screen is blurred

    Everytime when I drag and drop something on preview windows or on timeline, everything is blurred. Is thi normal bebaviour or I something have unlocked? My quality is set as FULL

  • How to create calendar type sheet?

    Hi, Does anybody knows how to create a calendar like sheet? I think there is a function that automatically put the dates into the header but I cannot find it. I really don't want to write down each day from now to next year... Thanks to anybody that

  • Guidance needed

    hi all , i am a new user of Hyperion Essbase , can anyone let me know for which certification i should start preparing either 7.X or 9.X ... my company is currently using essbase 7.X... also i am little bit confused regarding the certification like e

  • How to go to java section global variable declaration

    Hi all i am following this scenario http://www.sdn.sap.com/irj/scn/weblogs;jsessionid=(J2EE3417100)ID0446700150DB10376299506581707969End?blog=/pub/wlg/11287 in this scenario 3rd screen shot is about global variable declaration: In order to build the