Sunday, August 31, 2014

Sequential odd or even identification

Ques: Requirement is to identify odd sequence of 3 nos in an int array.

Ans:
    public static void main(String[] args) {
        int count = 0;
        int loop = 0;
        int[] nums={1,2,4,6,1,3};
       // for (int i = 0; i < nums.length; i++) {

           for(int i=0;i<nums.length;i++){
               if(count==3){break;}
              // loop=i;   
                System.out.print("Starting from="+nums[i]);
                System.out.println(" and Loop="+loop);
               do {
                    if(nums[i]%2==0){
                    count++;
                        System.out.print("Count "+count);
                        System.out.print(" value "+nums[loop]);
                        }
                    System.out.println(" loop"+ loop);
                    loop++;
                  
                } while (loop < 3);
                if(count==3){
                        System.out.println("breaking");
                        break;
                    }
               loop=0;
               count=0;
           }
        //}
        System.out.println("Final Count="+count);
    }

}

1 followed by 2

Given an array of ints, return true if there is a 1 in the array with a 2 somewhere later in the array.

has12({1, 3, 2}) → true
has12({3, 1, 2}) → true
has12({3, 1, 4, 5, 2})-->true

Answer:
public boolean has12(int[] nums) {
   int count=0;
   int count1=0;
   int count2=0;
   for(int i=0;i<nums.length;i++){
  if(nums[i]==1){count++;count1=i;}
  if(nums[i]==2){count++;count2=i;}
  }
  return (count>1)&&(count1<count2)?true:false;
}