Saturday, January 9, 2016

1.6.1 The 3n+1 problem

import java.util.Scanner;  
 /**  
  * Created by mridul on 1/9/16.  
  */  
 public class Program_1_6_1 {  
   public static void main(String[] args) {  
     System.out.println("Please enter the lower and upper bounds : ");  
     int bounds[]=readAndValidateInput();  
     if(checkBounds(bounds[0],bounds[1])){  
       System.out.printf("\n The maximum cycle length between %d and %d is : %d ",  
           bounds[0],bounds[1],maxCycleLength(bounds[0],bounds[1]));  
     }else {  
       System.out.println("Please ensure that second number is greater than first number");  
     }  
   }  
   private static int maxCycleLength(int lowerBound, int upperBound){  
     int maxCycleLength=0;  
     for(int index=lowerBound; index <= upperBound; index++){  
       int cycleLength=cycleLength(index);  
       maxCycleLength = (cycleLength > maxCycleLength) ? cycleLength : maxCycleLength;  
     }  
     return maxCycleLength;  
   }  
   private static int cycleLength(int candidate){  
     int cycleLength=0;  
     System.out.printf("The transformation for %d is : ",candidate);  
     while (candidate >=1){  
       System.out.print(candidate+ " ");  
       ++cycleLength;  
       if(candidate==1) break;  
       candidate = (candidate % 2 == 0) ? candidate/2 : (3*candidate + 1);  
     }  
     System.out.println();  
     return cycleLength;  
   }  
   private static int[] readAndValidateInput() throws NumberFormatException{  
     Scanner scanIn = new Scanner(System.in);  
     int[] vars = new int[2];  
     System.out.println("Enter "+vars.length+" vars: ");  
     for(int i = 0; i < vars.length; i++)  
       vars[i] = scanIn.nextInt();  
     scanIn.close();  
     return vars;  
   }  
   private static boolean checkBounds(int lowerBound, int upperBound){  
     return (checkRange(lowerBound) && checkRange(upperBound)  
           && lowerBound <= upperBound)  
             ? Boolean.TRUE : Boolean.FALSE;  
   }  
   private static boolean checkRange(int bound){  
     return (bound >0 && bound <1000000)? Boolean.TRUE : Boolean.FALSE;  
   }  
 }