I'm working on the 3n+1 problem but I have a general coding question. The way the ACM contest constructs the problem is there will be a series of pairs integers greater than 0 and less than 10000 - the number of pairs is not specified. It is entered into standard input.
Sample input:
1 10
100 200
210 220
900 1000
The code I have written processes any number of inputs and gives the correct answers, where I have a problem is that it never terminates because of the while(console.hasNextLine())
is there a way I can make this while loop terminate? The input is input as a block, basically copy and pasted into the console.
import java.util.Arrays;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
int[] solutions = new int[10000];
Arrays.fill(solutions, -1);
solutions[0] = 1;
for(int i = 1; i < 10000; i++){
int n = i+1;
int cycleCount = 0;
boolean solved = false;
while(!solved){
if(n-1 < 10000 && solutions[n-1] != -1){
solutions[i] = solutions[n-1] + cycleCount;
solved = true;
}
else{
n = process(n);
cycleCount++;
}
}
}
Scanner console = new Scanner(System.in);
while(console.hasNextLine()){
int i = console.nextInt();
int j = console.nextInt();
int max = 0;
if(i < j){
int n = i;
while(n < j){
if(solutions[n] > max) max = solutions[n];
n++;
}
}
else{
int n = j;
while(n < i){
if(solutions[n] > max) max = solutions[n];
n++;
}
}
System.out.println(i + " " + j + " " + max);
}
}
public static int process(int input){
if(input%2 == 1){
return 3*input+1;
}
else{
return input/2;
}
}
}