Question

I'm really confused about how to use the java for each - loop correct. Can anyone help me?

Okay, so here is the deal. I've got an extended Collatz problem that I can't get out of my head. The thing is that I want to list all Collatz iterations for the range between two variables x and y where x>y in range 0-10000. My problem is that in the second foor-loop I want to execute the whole collatz-calculation on each number in value so if value = 7 I want to calculate the collatz-iterations for x = 7 (16) and so on up to y = 19 (20), the whole sequence being 16, 3, 19, 6, 14, 9, 9, 17, 17, 4, 12, 20, 20. I'm doing this in Java.

import java.util.; import java.lang.;

public class hackCollatz{

public static void main(String[] args){

    Scanner input = new Scanner(System.in);

    int x;
    int y;
    int result = 0;

    System.err.print("Sätt ett värde på x: ");
    x  = input.nextInt();
    System.err.print("Sätt ett värde på y: ");
    y = input.nextInt();

    List<Integer> storeValue = new ArrayList<Integer>();

    for(int i=x; i<=y; i++){
        int value = i;
        storeValue.add(value);
        }       

    for(Integer value : storeValue){
        for(int j = value; j > 1; j++){
            if(j % 2 == 0){
                j=j/2;
            //  System.out.println(j);
                result++;

            }
            else{
                j=j*3+1;
                result++;
        //      System.out.println(j);
            }
        }
        }
        System.out.println(result);
        }       

}

Was it helpful?

Solution

If you change your inner FOR loop to: for(int j = value; j > 1;), then if value = 7, it will take 16 iterations to reach the value 1 (as expected).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top