0

This calculates a chain of numbers.

biggestList and upperBound are initialized on top.

Even if I set i to some non 1 number, it only prints 1-> That's 1 numbers long!

The code was working fine with long tallys, but once I replaced them with ArrayLists that held the chains, it broke. Am I doing something wrong in the ArrayList code?

private void calculateIterations(){
    for (long i = 1; i <= upperBound; i++){
        calculateAnswer(i);
    }
}

private void calculateAnswer(long i) {
    long number = i;
    ArrayList <Long> tempList = new ArrayList<>();

    if (number == 1 ){
        tempList.add(number);
        if (tempList.size() > biggestList.size()){
            biggestList.clear();
            biggestList.addAll(tempList);
            printLargest();
        }
    }
    else if (number % 2 == 0){
        tempList.add(number);
        number /= 2;
        calculateAnswer(number);

    }
    else {
        tempList.add(number);
        number = number * 3 + 1;
        calculateAnswer(number);
    }
}
private void printLargest(){
    biggestList.stream().forEach((n) -> {
        System.out.print(n + " → ");
    });
    System.out.println("");
    System.out.println("That's " + biggestList.size() + " numbers long!");
}
2
  • It shows no compiler errors. I'm new to recursions and copying ArrayLists so I'm not even sure where to look. AFAIK calculateIterations only runs once, but print prints 1 even if i = whatever. So confused. Commented Aug 26, 2014 at 19:32
  • Hint, your method shouldn't be void and to use recursion it seems like it would need to take a List. Commented Aug 26, 2014 at 19:33

1 Answer 1

1

I looks like every time you enter calculateAnswer() you create a new instance of the ArrayList and assign it to the tempList variable that is only in scope within that method. Seems like you need to have access to a tempList that is persistent across multiple calculateAnswer() calls.

Sign up to request clarification or add additional context in comments.

1 Comment

That was exactly the problem. I put it up top and it worked like a charm. Don't know why a locally declared tally worked before, come to think of it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.