ramkumarn
ramkumarn

Reputation: 11

how convert recursive method to nonrecursive in java

I am trying to get the combination of five numbers which sum is equal to 20 and whose average value equal to some specified value.

my code is

package Others;

 import java.util.ArrayList;
import java.util.List;
import java.util.Random;

 public class RandomNumbers {

/**
 * @param args
 */
// Max average = 3.6 ///Min average=2.2
public static void main(String[] args) {
    // TODO Auto-generated method stub
    List<Integer> i = getNumbers();
}

public static List<Integer> getNumbers() {
    List<Integer> n = new ArrayList<Integer>();
    Random r = new Random();
    for (int i = 0; i < 5; i++) {
        int rr = r.nextInt(10);
        n.add(rr);
    }

    int sum = 0;
    double average = 0;
    for (int j = 0; j < n.size(); j++) {
        sum += n.get(j);
        average += ((j + 1) * n.get(j));
        System.out.println(n.get(j));
    }
    System.out.println("Avearge:" + average / 20);
    if (sum == 20 && (average / 20) == 2.1) {
        getCombination(n);
    } else {
        getNumbers();
    }
    return n;
}

public static void getCombination(List<Integer> n) {
    int total = 0;
    for (int i = 0; i < n.size(); i++) {
        total += n.get(i);
        if (n.get(i) == 0) {
            getNumbers();
        } else {
            System.out.println("Item: " + i + ":" + n.get(i));
        }
    }
    System.out.println("Total:" + total);
}
  }

it is working fine for average values from 2.2 to 3.6. When we give other number which is not in between 2.2 and 3.6 it is giving the error as

Exception in thread "main" java.lang.StackOverflowError
at sun.nio.cs.SingleByte.withResult(Unknown Source)
at sun.nio.cs.SingleByte.access$000(Unknown Source)
at sun.nio.cs.SingleByte$Encoder.encodeArrayLoop(Unknown Source)
at sun.nio.cs.SingleByte$Encoder.encodeLoop(Unknown Source)`package Others; 

I Searched in some sites and some of them suggested to that avoid recursive and use iterators.But I am in confusion how to redevelop this program using iterators.

It is required my project . Any help would be appreciated. Please help me.

Upvotes: 0

Views: 203

Answers (1)

Paul Hicks
Paul Hicks

Reputation: 13999

This isn't a generic answer for converting recursion into iteration. It's just resolving bugs in your code.

  1. Get rid of getCombination(), it doesn't do anything useful. If it is important that there be no zeroes, at least call the method something like "regenerateListIfThereAreAnyZeroes". Or just improve the generation logic (see point 2).
  2. Create a method generateListOfNumbers() that generates a list whose sum is 20. There's no need to use five totally random numbers and hope; improve the logic so that (for example)
    1. the first number is mostly random (0 to 16, maybe);
    2. the second, third and fourth numbers, when added to the existing total, add up to something under (20 - existingTotal);
    3. the fifth number is whatever is required to get the total to 20.
  3. Create a method boolean isAverageInRange(double floor, double ceiling) that provides that interesting logic you've implemented (average += ((j + 1) * n.get(j));, etc)
  4. Change the main method to loop, calling generateListOfNumbers() until isAverageInRange() returns true.

As an additional exercise, you could create methods decreaseAverage() and increaseAverage() that modify the existing list instead of creating a whole new one each time. That would be worth oodles of credit from your teacher, I bet.

For future reference, there is another Stack Exchange site CodeReview that is may be useful, if you get your code working but want to improve it.

Upvotes: 0

Related Questions