Saturday, October 18, 2014

Largest palindrome product

Ques:
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
Ans:
 This can be achieved in 2 differnet ways..
Ist: Declare as wrapper class integer
Convert to String
Use tochar to seperate the digits
Read them backwards
convert back to Int and get answer

I have used basics of math to arrive at solution.
Extract the digits using maths fundamentals
store them in variables.
re-arrange them using Maths fundamentals.

AND YOU HAVE THE ANSWER.
 ==========================

Package palindrome;

public class Palindrome {

  
    public static void main(String[] args) {
          int mult = 906609;
        for (int i = 100; i < 1000; i++) {
            for (int j = 100; j < 1000; j++) {
                mult = i * j;
                      if (mult - placeholdervalue(mult) == 0) {
                    System.out.println("Original number=" + mult + " and its palindrome=" + placeholdervalue(mult));
                    System.out.println("i=" + i + "j=" + j);
                }
            }

                   }
    }

    public static int placeholdervalue(int num) {

        int var0 = 0, var, var1, var2, var3, var4, var5, var6;
        var = num / 10000;

        if (var >= 10) {
            var0 = num / 100000;
            var = (num - var0 * 100000) / 10000;
        }
        var1 = (num - var * 10000 - var0 * 100000) / 1000;
        var2 = (num - var * 10000 - var0 * 100000 - var1 * 1000) / 100;
        var3 = (num - var * 10000 - var0 * 100000 - var1 * 1000 - var2 * 100) / 10;
        var4 = (num - var * 10000 - var0 * 100000 - var1 * 1000 - var2 * 100 - var3 * 10);
     
              var5 = var4 * (var0 > 0 ? 100000 : 10000);
        var5 = var5 + var3 * (var0 > 0 ? 10000 : 1000);
        var5 = var5 + var2 * (var0 > 0 ? 1000 : 100);
        var5 = var5 + var1 * (var0 > 0 ? 100 : 10);
        var5 = var5 + var * (var0 > 0 ? 10 : 1);
        var5 = var5 + var0;
        return var5;
    }

Wednesday, October 15, 2014

Highly divisible triangular number

Ques:
The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
 1: 1
 3: 1,3
 6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred divisors?


Ans:

package highlydivisible;

public class HighlyDivisible {
 

    public static void main(String[] args) {
          int nthtriplet = 9;
        int tripdes = 500;
        int cnt = 0;
        int gettriplet = 0;
        boolean val=false;
        int[] obtaindivisor=new int[nthtriplet-1];
        int matchpos=0;
   
        for (int i = 2; i < 200000; i++) {
           
            gettriplet = findtriplet(i);
            obtaindivisor=getdivisor(gettriplet, i);
            for(int j:obtaindivisor){
                if(j!=0){
                    cnt++;
                }
                if(cnt==tripdes){
                    val=true;
                    matchpos=i;
                    break;
                }
            }

            if(val){
                System.out.println("the position is "+matchpos+" & triplet is "+findtriplet(i));
                break;
            }
            cnt=0;
        }
    }

    public static int findtriplet(int num) {
        int sump = 0;
        for (int i = 1; i <= num; i++) {
            sump += i;
        }
        return sump;
    }

    public static int[] getdivisor(int sumoftriplets, int uptonum) {
        int[] getd = new int[uptonum+2];
        int j = 0;
        for (int i = 1; i <= sumoftriplets; i++) {
              if (sumoftriplets % i == 0) {
                getd[j] = i;
                j++;     
            }
        }
        return getd;
    }
}

Monday, October 13, 2014

Summation of Primes

Ques:
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.

Ans:
public static void main(String[] args) {
        int count = 0;
        int pcount=1;
        int tarprnum=10001;
        int sump=2;
        for (int i = 3; i < 2000000; i++) {
            count=0;
            for (int j = 2; j < i; j++) {
                if (i % j == 0) {
                           count++;
                    break;
                }
            }
            if(count==0){
                pcount++;
                sump+=i;
                           }
                 }
        System.out.println("sum="+sump);
    }

}

Sunday, October 12, 2014

10001st prime

Ques:
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
 
 
Ans:
Prime number is number divided by 1 or itself. 
1st Prime=2 is fixed. 2nd onwards we calculate as below........
============================================================
package isprime;

public class IsPrime {

        public static void main(String[] args) {
        int count = 0;
        int pcount=1;//counts Prime
        int tarprnum=10001;//target expected to be met
        for (int i = 3; i < 1000000000; i++) {
            count=0;
            for (int j = 2; j < i; j++) {
                if (i % j == 0) {
                    count++;
                    break;
                }
            }
            if(count==0){
                pcount++;
                    }
            if(pcount==tarprnum){
          System.out.println("The target prime num="+i);break;}
        }
    }

}

Pythagorean triplet

Ques:
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.

Ans:

package gradesforeexam;


public class GradesforeExam {

     public static void main(String[] args) {
        double a=0, b=0, c = 0;
        for (int i = 1; i < 1000; i++) {
            for (int j=i+1;j<1000;j++ ) {
                c = Math.pow(Math.pow(i, 2) + Math.pow(j, 2), 0.5);
               
                if ((c - (int) c == 0.0)&&(i+j+(int)c==1000)) {
                   System.out.println(a*b*c);
                   }
            }
        }
    }

}

Saturday, October 11, 2014

noTeenSum

Ques:
Given 3 int values, a b c, return their sum. However, if any of the values is a teen -- in the range 13..19 inclusive -- then that value counts as 0, except 15 and 16 do not count as a teens. Write a separate helper "public int fixTeen(int n) {"that takes in an int value and returns that value fixed for the teen rule. In this way, you avoid repeating the teen code 3 times (i.e. "decomposition"). Define the helper below and at the same indent level as the main noTeenSum()

Ans:public int noTeenSum(int a, int b, int c) {
//  public static int noTeenSum(int a, int b, int c){
      
       return fixteen(a)+fixteen(b)+fixteen(c);
   }
    public int fixteen(int age){
        int helper=0;
        if(age>=13&&age<=19){
            if(age==15||age==16){
                helper=age;
       //         continue a;
            }else{helper=0;}
        }else helper=age;
          return helper;
    }

luckySum

Ques:
Given 3 int values, a b c, return their sum. However, if one of the values is 13 then it does not count towards the sum and values to its right do not count. So for example, if b is 13, then both b and c do not count.

Ans:
public int luckySum(int a, int b, int c) {
       if(a==13){
          a=0;
          b=0;
          c=0;
      }
        if(b==13){
            b=0;
            c=0;
        }
        if(c==13){
            c=0;
        }
        return a+b+c;
}

Sunday, October 5, 2014

notAlone

Ques:We'll say that an element in an array is "alone" if there are values before and after it, and those values are different from it. Return a version of the given array where every instance of the given value which is alone is replaced by whichever value to its left or right is larger.

Ans:
public int[] notAlone(int[] nums, int val) {
         int swap = 0;
        for (int i = 0; i < nums.length-1; i++) {
            if ((nums[i] == val&&i!=0)&&(nums[i] == val&&i!=nums.length-1)){
              //check the vale before and after it
                if ((nums[i-1] > nums[i + 1])) {
                    nums[i] = nums[i - 1];
                } else if (nums[i-1] < nums[i + 1]) {
                    nums[i] = nums[i + 1];
                }
            }
        }
 
        return nums;
    }


Caught Speeding

Ques:You are driving a little too fast, and a police officer stops you. Write code to compute the result, encoded as an int value: 0=no ticket, 1=small ticket, 2=big ticket. If speed is 60 or less, the result is 0. If speed is between 61 and 80 inclusive, the result is 1. If speed is 81 or more, the result is 2. Unless it is your birthday -- on that day, your speed can be 5 higher in all cases.


Ans:
public int caughtSpeeding(int speed, boolean isBirthday) {
           int val = 0;
        if (isBirthday) {
            if (speed <= 65) {
                val = 0;
            }
            if (speed > 65 && speed <= 85) {
                val = 1;
            }
            if (speed > 85) {
                val = 2;
            }
        }
       
        if(!isBirthday){
            if (speed <= 60) {
                val = 0;
            }
            if (speed > 60 && speed <= 80) {
                val = 1;
            }
            if (speed > 80) {
                val = 2;
            }
        }
        return val;

squirrelPlay

Ques:The squirrels in Palo Alto spend most of the day playing. In particular, they play if the temperature is between 60 and 90 (inclusive). Unless it is summer, then the upper limit is 100 instead of 90. Given an int temperature and a boolean isSummer, return true if the squirrels play and false otherwise.

Ans: public static boolean squirrelPlay(int temp, boolean isSummer) {
        boolean val = false;
        if (isSummer&& (temp >= 60 && temp <= 100)) {
                val = true;
            } else if (!isSummer && (temp >= 60 && temp <= 90)) {
                val = true;
            } else {
                val = false;
            }
       
        return val;
    }

dateFashion

Ques:You and your date are trying to get a table at a restaurant. The parameter "you" is the stylishness of your clothes, in the range 0..10, and "date" is the stylishness of your date's clothes. The result getting the table is encoded as an int value with 0=no, 1=maybe, 2=yes. If either of you is very stylish, 8 or more, then the result is 2 (yes). With the exception that if either of you has style of 2 or less, then the result is 0 (no). Otherwise the result is 1 (maybe).

Ans:
       int val = 0;
        if((you<=2||date<=2)){
            val=0;
        }else if((you>2&&you<8)&&(date>2&&date<8)){
            val=1;
        }else{
            val=2;
        }
        return val;

Cigar Party

Ques:
When squirrels get together for a party, they like to have cigars. A squirrel party is successful when the number of cigars is between 40 and 60, inclusive. Unless it is the weekend, in which case there is no upper bound on the number of cigars. Return true if the party with the given values is successful, or false otherwise.

Ans:
 public static boolean cigarParty(int cigars, boolean isWeekend) {
       
        return isWeekend&&(cigars>=40)?true:!isWeekend&&(cigars>=40&&cigars<=60?true:false);
    }

Saturday, October 4, 2014

tenRun

Ques:For each multiple of 10 in the given array, change all the values following it to be that multiple of 10, until encountering another multiple of 10. So {2, 10, 3, 4, 20, 5} yields {2, 10, 10, 10, 20, 20}.

Ans:
        for(int i=0;i<nums.length;i++){
            if(nums[i]%10==0){
               for(int j=i+1;j<nums.length;j++){
                   if(nums[j]%10!=0){
                       nums[j]=(nums[i]/10)*10;
                      
                   }else break;
               }
             }
        }
        return nums;
    }

Friday, October 3, 2014

Two-Twos Together

Ques: Given an array of ints, return true if every 2 that appears in the array is next to another 2.

Ans:

 public boolean twoTwo(int[] nums) {
         boolean count=true;
//Check if there is one element and that is 2 then set the count flag to false     
  if(nums.length==1){if(nums[0]==2)count=false;}

//if the number of elements are greater than 1
        for(int i=1;i<nums.length;i++){
            if(nums[i]==2&&nums.length>1){
                //check wehther the next element is 2?
                if(nums[i-1]==2){
                    count=true;
                    i++;
                }else{ count=false;}
            }
        }
      
      
        return count;
    }

Two 2s somewhere

Ques: Given an array of ints, return true if the array contains a 2 next to a 2 somewhere.

Ans:
public static boolean has22(int[] nums) {
        int count = 0;
        for (int i = 0; i < nums.length - 1; i++) {
            if (nums[i] ==2&& nums[i + 1]==2) {
                count++;
            }
        }
        return count > 0 ? true : false;
    }

Sum of numbers in array and ignoring numbers between 6&7

Ques: Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 7 (every 6 will be followed by at least one 7). Return 0 for no numbers.

Ans:
public static int sum67(int[] nums) {
        int sum = 0;
        for(int i=0;i<nums.length;i++){
           
            if(nums[i]==6){
             do{
                i++;
            }while (nums[i]!=7);  
            }else{
                sum+=nums[i];
            }
           
        }
       
        return sum;

    }

Rearrange Even and Odd integers in an Array

Ques:
Return an array that contains the exact same numbers as the given array, but rearranged so that all the even numbers come before all the odd numbers. Other than that, the numbers can be in any order. You may modify and return the given array, or make a new array.


Ans:
public int[] evenOdd(int[] nums) {
  int swap = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] % 2 != 0) {
                for (int j = i + 1; j < nums.length; j++) {
                    if (nums[j] % 2 == 0) {
                        swap = nums[j];
                        nums[j] = nums[i];
                        nums[i] = swap;
                        break;
                    }
                }
            }
        }
        return nums;
}

Thursday, October 2, 2014

ZeroMax

Ques: Return a version of the given array where each zero value in the array is replaced by the largest odd value to the right of the zero in the array. If there is no odd value to the right of the zero, leave the zero as a zero.

Ans:
 public static int[] zeroMax(int[] nums) {
 int maxoddtrval = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 0) {
                for (int j = i + 1; j < nums.length; j++) {
                    if(nums[j]%2==1){
                        maxoddtrval=nums[j];
                        for(int k=j+1;k<nums.length;k++){
                            if(nums[k]>maxoddtrval){
                                maxoddtrval=nums[k];
                                break;
                            }
                        }
//swap the max identified value with zero
                        nums[i]=maxoddtrval;
                        break;
                    }
                }

              
            }
        }
        return nums;
}

Without ten

Ques:
Return a version of the given array where all the 10's have been removed. The remaining elements should shift left towards the start of the array as needed, and the empty spaces a the end of the array should be 0. So {1, 10, 10, 2} yields {1, 2, 0, 0}

Ans:
public static int[] withoutTen(int[] nums) {
        int countof0 = 0;
        int swap = 0;
        int rep=0;
   //Replacing all tens with 0  
     for (int i=0;i<nums.length;i++){
            if(nums[i]==10){
                nums[i]=0;
            }
        }
// Identifying the number with zero
//Swapping the same with a non-zero
//Breaking out once identified and replaced

        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 0) {
                for (int j = i + 1; j < nums.length; j++) {
                    if (nums[j] != 0) {
                        swap = nums[j];
                        nums[j] = nums[i];
                        nums[i] = swap;
                        break;
                    }
                }
            }
        }
       
    return nums;
    }

Get Zeros together

Ques:Return an array that contains the exact same numbers as the given array, but rearranged so that all the zeros are grouped at the start of the array. The order of the non-zero numbers does not matter. So {1, 0, 0, 1} becomes {0 ,0, 1, 1}. You may modify and return the given array or make a new array

Ans:
 public static int[] notAlone(int[] nums, int val) {
        int countof0=0;
        int swap=0;
        for(int i=0;i<nums.length;i++){
            if(nums[i]==0){
               swap=nums[countof0];
                nums[countof0]=0;
                nums[i]=swap;
                countof0++;
            }
        }
               return nums;
    }

Sorting thru elements in an array

Ques: How does one sort in an array?

Ans:
      public int[] zeroFront(int[] nums) {
        //Method 1-->Arrays.sort(nums);
        int swap=0;
        for(int i=0;i<nums.length-1;i++){

            for(int j=i;j<nums.length;j++){
            if(nums[i]>nums[j]){
                swap=nums[i];
                nums[i]=nums[j];
                nums[j]=swap;
                           }
                     }
           }
        return nums;
    }

Wednesday, October 1, 2014

Creating an Array post an element in an existing array

Ques: Given a non-empty array of ints, return a new array containing the elements from the original array that come after the last 4 in the original array. The original array will contain at least one 4. Note that it is valid in java to create an array of length 0.

Ans:
This can be achieved in 2 different ways-

The usage of System.arraycopy is a strong method which can achieve this in one single command which is covered in method 2.

Method 1:
public int[] post4(int[] nums) {
        int j=0;
        int pos4=0;
        //last Position of 4
        //assign a variable
        //this will store the last position of 4 after detecting the for position in //for loop
        for(int i=0;i<nums.length;i++){
            if(nums[i]==4){
                pos4=i;
            }
        }
     
        int[] temparray=new int[nums.length-pos4-1];
        for(int i=pos4+1;i<nums.length;i++){
        temparray[j]=nums[i];
        j++;
        }
       
        return temparray;
 
}

Method2:

public int[] post4(int[] nums) {
        int j=0;
        int pos4=0;
        //last Position of 4
        //assign a veriable
        //this will store the last pos of 4 after detecting the for position in //for loop
        for(int i=0;i<nums.length;i++){
            if(nums[i]==4){
                pos4=i;
            }
        }
     
        int[] temparray=new int[nums.length-pos4-1];
       System.arraycopy(nums,pos4+1,temparray,0,nums.length-pos4-1);          
        return temparray;

}

Sunday, September 28, 2014

Elements before 4 in an int array

Ques:Given a non-empty array of ints, return a new array containing the elements from the original array that come before the first 4 in the original array.

Ans:
 public static int[] pre4(int[] nums) {
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
                  if (nums[i] == 4) {
                break;
            }
            count++;
        }
        int[] tempArray=new int[count];
        for(int j=0;j<count;j++){
            tempArray[j]=nums[j];
              }
     return tempArray;
    }

Saturday, September 27, 2014

Shifted Array

Ques: Return an array that is "left shifted" by one -- so {6, 2, 5, 3} returns {2, 5, 3, 6}. You may modify and return the given array, or return a new array.

Ans:
public int[] shiftLeft(int[] nums) {
  int var = 0;
       if (nums.length>0){
        var = nums[0];
               for (int i = 1; i < nums.length; i++) {
            if ( i != nums.length - 1) {
      
                nums[i-1] = nums[i];
            }
         
            if (i == nums.length - 1) {
            
                nums[nums.length-2]=nums[nums.length-1];       
                nums[nums.length - 1] = var;
           
              }
          }
        }

        return nums;
}

Arrays: Create arrays dynamically

Ques:Given start and end numbers, return a new array containing the sequence of integers from start up to but not including end, so start=5 and end=10 yields {5, 6, 7, 8, 9}. The end number will be greater or equal to the start number. Note that a length-0 array is valid.

Ans:
public int[] fizzArray3(int start, int end) {
   int[] temparray=new int[end-start];
        int tot=end-start;
        for(int i=0;i<tot;i++){
                      temparray[i]=start;
                              start++;
        }
        return temparray;
}

Arrays: Numbers in ascending order

Ques:Return true if the array contains, somewhere, three increasing adjacent numbers like .... 4, 5, 6, ... or 23, 24, 25.

Ans:
public boolean tripleUp(int[] nums) {
  int count=0;
        for (int i=0;i<nums.length-2;i++ ) {
            if((nums[i+1]-nums[i]==nums[i+2]-nums[i+1])&&(nums[i+1]-nums[i]>0)){
                               count++;
                }
        }
        return count>0;
}

Array Examles same Ends

Comment: The below mentioned example uses some very basic concept of arrays all the while testing the logic. The question is in response to a question posed in battery of questions in codingbat.com

Ques:Return true if the group of N numbers at the start and end of the array are the same. For example, with {5, 6, 45, 99, 13, 5, 6}, the ends are the same for n=0 and n=2, and false for n=1 and n=3. You may assume that n is in the range 0..nums.length inclusive.

Ans:
public boolean sameEnds(int[] nums, int len) {
 int[] hnums = new int[len== 0 ? 2 * len + 1 : 2 * len];
        int[] hrnums = new int[len == 0 ? 2 * len + 1 : 2 * len];
        int count = 0;
              for (int k = 0; k < len; k++) {
            if (nums[k] == nums[k + nums.length - len]) {
                 }
            }

        return count == len ? true : false;
}

Sunday, September 21, 2014

3 appears in the array exactly 3 times

Ques: Given an array of ints, return true if the value 3 appears in the array exactly 3 times, and no 3's are next to each other.

Ans:
package countofthreenotnnext;
public class CountofthreenotnNext {

     public static void main(String[] args) {
             int[] nums = {3,2,3};
        System.out.println("Output=" + haveThree(nums));
    }

    public static boolean haveThree(int[] nums) {
        int count = 0;
        boolean mark = false;
        int[] trackpos = new int[nums.length];
        int pos = 0;
        if (nums.length > 2) {
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] == 3) {
                    count++;
                    pos = pos + i;
                    trackpos[count - 1] = i;
                             }
                          }

            for (int i = 0; i < 3; i++) {
            }
            if ((trackpos[1] - trackpos[0]) == 2 && (trackpos[2] - trackpos[1]) == 2) {
                mark = true;
            }

          
        }
     return (count == 3) && mark ? true : false;
    }
}
 

Consetive 3 odd or even values

Ques: Given an array of ints, return true if the array contains either 3 even or 3 odd values all next to each other.

Ans:
package oddorevenin.array;
public class OddorEveninArray {
  public static void main(String[] args) {

        int[] nums = {2, 2, 2, 5, 9};
        System.out.println("Nunber=" + modThree(nums));
    }

    public static boolean modThree(int[] nums) {
        int ecount = 0;
        int ocount = 0;
        int oloop = 0;
        int eloop = 0;
        for (int i = 0; i < nums.length; i++) {
            oloop = i;
            if (nums[oloop] % 2 == 1) {

                for (int j = 0; j < 3; j++) {
                         if (j + i > nums.length - 1) {
                        break;
                    }
                    if (nums[j + i] % 2 == 1) {
                             ocount++;
                        oloop++;
                    }
                    if (ocount == 3) {
                        break;
                    }
                }
                if (ocount < 3) {
                    ocount = 0;
                }
            }
            if (ocount == 3) {
                break;
            }
        }

        /////////////////////////Starting the Even loop
        for (int i = 0; i < nums.length; i++) {
            eloop = i;
            if (nums[eloop] % 2 == 0) {

                for (int j = 0; j < 3; j++) {
                    if (j + i > nums.length - 1) {
                        break;
                    }
                    if (nums[j + i] % 2 == 0) {
                        ecount++;
                        eloop++;
                    }
                    if (ecount == 3) {
                        break;
                    }
                }
                if (ecount < 3) {
                    ecount = 0;
                }
            }
            if (ecount == 3) {
                break;
            }
        }

        return (ocount == 3 || ecount == 3) ? true : false;
    }

}



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;
}

Saturday, July 12, 2014

Making DBConnection to SQLite from Netbeans8.0

Key Learning: Netbeans does not allow direct conneciton to sqlite database. You require to import the jdbc connectivity jar available from the site: https://bitbucket.org/xerial/sqlite-jdbc . Once downloaded, goto the project from where the connection is being sought and right-click and goto properties >>Libraries>>Add Jar/Folder. Once added if the code is complied and run then it executes successfully. I have used here sqlite-jdbc-3.7.15-M1 downloaded from the above site.

I already have a sqlite database running in my D:\drive named as test.sqlite.
The sqlite database tables can be accessed from Firefox plugin for sqlite.

Some quick references from where the codes can be picked up are:
http://en.wikibooks.org/wiki/Java_JDBC_using_SQLite
https://bitbucket.org/xerial/sqlite-jdbc

I have successfully created my own code using the above references and is being reproduced here below for reference-

package dbconnection;
import java.sql.*;
import java.lang.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class DbConnection {

    public static void main(String[] args) throws ClassNotFoundException {
        String sDrivername="org.sqlite.JDBC";
        Class.forName(sDrivername);
        String sTempDb="test.sqlite";
        String sJDBC="jdbc:sqlite:D:\\SQLite\\AllDBs\\test.sqlite";
        String sDBurl=sJDBC;
       
        int iTimeout=30;
       String sMaketable="CREATE TABLE testtable (Empno integer, Ename char);";
        String sMakeInsert="INSERT INTO testtable values(1234,'ST')";
        String sSelect="Select Empno from testtable";
        try {
            Connection conn=DriverManager.getConnection(sDBurl);
            Statement stmt=conn.createStatement();
             stmt.executeUpdate(sMaketable);
             stmt.executeUpdate(sMakeInsert);
             ResultSet rs=stmt.executeQuery(sSelect);
            while(rs.next()){
                String sResult=rs.getString("Empno");
                System.out.println(sResult);
               
            }
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException ex) {
            Logger.getLogger(DbConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
       
       
    }
   
}

Saturday, May 17, 2014

Usage of Substring

Ques:

Given a non-empty string and an int N, return the string made starting with char 0, and then every Nth char of the string. So if N is 3, use char 0, 3, 6, ... and so on. N is 1 or more.

everyNth("Miracle", 2) → "Mrce"
everyNth("abcdefg", 2) → "aceg"
everyNth("abcdefg", 3) → "adg

Ans:


public String everyNth(String str, int n) {
  String stri=str.substring(0,1);
  String strc="";
   
  for(int i=0;i<str.length();i++){
     if(n*i>str.length()-1){
          break;
      }
     strc+=str.substring(n*(i),n*(i)+1);
   }
  return strc;
}

Saturday, May 10, 2014

Use of Else..if....


Ques: 

Given two temperatures, return true if one is less than 0 and the other is greater than 100. 

icyHot(120, -1) → true
icyHot(-1, 120) → true
icyHot(2, 120) → false

Ans:

public boolean icyHot(int temp1, int temp2) {
  if(temp1>100){return temp2<0?true:false;}
  else if(temp1<0){return temp2>100?true:false;}
  else{return false;}
 
}

Some simple appending of Strings

Ques: 

Given a string, we'll say that the front is the first 3 chars of the string. If the string length is less than 3, the front is whatever is there. Return a new string which is 3 copies of the front.

front3("Java") → "JavJavJav"
front3("Chocolate") → "ChoChoCho"
front3("abc") → "abcabcabc"

Ans:
















public String front3(String str) {
  String totstr=null;
  if (str.length()<3){ 
  totstr=str;
  for(int i=0;i<2;i++){
  totstr+=str;
  }
  return totstr;}
  else{
  totstr=str.substring(0,3);
  for(int i=0;i<2;i++){
  totstr+=str.substring(0,3);
  }
  return totstr;}
}

Fibonaaci Series

One can generate a Fibonacci Series using the following classes
-
Method 1:
public static int Fib(int nth){
          int a=1;
          int b=1;
          int c=0;
          int loop=3;
          while(nth>3){
          if (loop>nth){
              break;
          }
          c=a+b;
          a=b;
          b=c;
          loop++;
          }
         
      return nth<3?1:c;
      }

Method 2: Using Recursion
public static int Fib(int nth){
  if(nth<2){return 1;}
          else{
          return Fib(nth-1)+Fib(nth-2);
          }
}

Nth Prime number

Ques: 

Identify the 50th Prime Number?

Ans: 

package primenumber;

public class PrimeNumber {

    public static void main(String[] args) {
       int j=1;
       int i=1;
            while(j<51){
           if(isPrime(i)){
              if (j==50){
               System.out.println(j + "th Prime number is "+ i);
               }
               j++;
                          }
           i++;
           }
     
    }

      public static boolean isPrime(int num){
     
         for(int i=2; i<num;i++){
           if (num%i==0||num==1){
               return false;
                    }
                }
      return true;
         }
}

Sunday, May 4, 2014

Calculate LCM and GCF

Ques: 

Calculate LCM and GCF  of 2 numbers

Ans: 


The formula used for LCM = a*b/gcf(a,b)
for GCF we have used Euclid's approach.

package createlcm;
public class CreateLcm {

    public static void main(String[] args) {

        Integer result=0;
        result=gcfcalc(22,13);
        System.out.println("the gcf is=="+result);
        System.out.println("the lcm for numbers is== "+LCMcalc(16,10));
    }
    public static Integer LCMcalc(int a,int b){
         return (a*b)/gcfcalc(a,b);
           }
    public static Integer gcfcalc(int c, int d){
        int inum=0;
        while(c%d!=0){
                 inum=c;
            c=d;
            d=(inum%d);
                  }
        return(d);
    }
}

Age Problem

Ques:

 A young man and his grandfather meet an old lady. The old lady asks the young man: "How old are you?"
The man answers :
If you divide my age by 3 the remainder will be 1
If you divide my age by 4 the remainder will be 2
if you divide my age by 5 the remainder will be 4

What is my age?

Ans:

package extrial;

public class ExTrial {

    public static void main(String[] args) {
       int loop=0;
       int ouloop=0;
       int oloop=0;
       int iloop=0;
       int i=0;
       int j=3;
       int k=4;
       int NUM=100;
       int[] cnums=new int[NUM];
       int[] cnumo=new int[NUM];
       int[] cnumi=new int[NUM];
       
       //outer loop
       while(loop<100){
           if (i%j==1){
               cnums[ouloop]=i;
                 if (cnums[ouloop]%k==2){
                   cnumo[oloop]=i;
                      if(cnumo[oloop]%5==4){
                             cnumi[iloop]=i;
                              iloop++;
                             } 
                   oloop++;
               }
               ouloop++;
           }
          loop++;       
          i++;
       }
       System.out.println("the age is: "+cnumi[0] );
           
       }
        
    }
}

Saturday, May 3, 2014

Use of Substring

Ques: 

Given a string, return a new string where the first and last chars have been exchanged. 
frontBack("code") → "eodc"
frontBack("a") → "a"
frontBack("ab") → "ba"

Answer:

public String frontBack(String str) {

return(str.length()>1?(str.substring(str.length()-1,str.length())+str.substring(1,str.length()-1)+str.substring(0, 1)):str);
   }

Use of StringBuilder() and deleteCharAt

Ques:

Given a non-empty string and an int n, return a new string where the char at index n has been removed. The value of n will be a valid index of a char in the original string (i.e. n will be in the range 0..str.length()-1 inclusive).

Ans: 


public String missingChar(String str, int n) {
  StringBuilder sb=new StringBuilder(str);
   if(n<=sb.length()-1){
        return sb.deleteCharAt(n).toString();}else{return sb.toString();}
}

Use of Substring

Ques:Given a string, return a new string where "not " has been added to the front. However, if the string already begins with "not", return the string unchanged. Note: use .equals() to compare 2 strings. 


notString("candy") → "not candy"
notString("x") → "not x"
notString("not bad") → "not bad"


Ans:

public String notString(String str) {
if (str.contains("not")){
       if(str.substring(0,3).equals("not")){return str;
           }else{return "not "+str;}
       }else{return "not "+str;}
}

Friday, May 2, 2014

Roll of Dice Problem

Ques:Given an input file of 3000 random dice throws, (here: dice.txt) calculate how many doubles were rolled.It is known for this problem that each die are fair in that they are labeled with the numbers 1,2,3,4,5 and 6. It is also known that a double is defined as both dice showing the same number after they are rolled.

Answer:

Highlights:

1. Use of BufferedReader to read the file
2. Use of string split to read the values input and  compared

======================================================================

package rollofdice;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class RollofDice {
 
    public static void main(String[] args) {
        try {
                     
            BufferedReader br=new BufferedReader(new FileReader("d:\\dice.txt"));
            String line;
            String sline[];
              try {
                while((line=br.readLine())!=null){
                    System.out.println(line);
                    sline=line.split(" ");
                        if(sline[0].equals(sline[1])){
                        System.out.println("the roll of die matches");
                    }
                }
            } catch (IOException ex) {
                Logger.getLogger(RollofDice.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(RollofDice.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
   
}

Math.signum() usage in Java

Question: 

Given 2 int values, return true if one is negative and one is positive. Except if the parameter "negative" is true, then return true only if both are negative.

posNeg(1, -1, false) → true
posNeg(-1, 1, false) → true
posNeg(-4, -5, true) → true

Answer: 

public boolean posNeg(int a, int b, boolean negative) {

  if(negative){
    if(a==1.0 &&b==1.0){
    return(false);
    }else{
     return (Math.signum(a)*Math.signum(b)==1.0)?true:false;
     }
  }else{
  return (Math.signum(a)*Math.signum(b)==-1.0)?true:false;
  }
}

Thursday, May 1, 2014

Invoking windows commands using java

Question: Need to invoke the windows command-prompt and run dos-commands within the same.


Answer: Here is a example that goes a a directory called D searches for a folder called "Activiti" and performs dir operation. Similar to this unix shell can be called and invoked

IDE used: Netbeans
JDK:1.7.0_51

package launchcmd;

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class LaunchCmd {

    public static void main(String[] args) {
      ProcessBuilder builder=new ProcessBuilder("cmd","/c","start","dir");
      builder=builder.directory(new File("D:\\Activiti"));
        try {
            builder.start();
            } catch (IOException ex) {
            Logger.getLogger(LaunchCmd.class.getName()).log(Level.SEVERE, null, ex);
                          }
        }
  }


Ouput: 

The output is as below



Wednesday, April 16, 2014

Prime numbers addition

In math, a prime number is a number only divisible by 1 and itself. Given the first few prime numbers 2 3 5 7 11 13 17 ...
What is the sum of the first 250 prime numbers


package primenumbersum;

public class Primenumbersum {

    
    public static void main(String[] args) {
        Integer val;
        Integer sum=0;
        Integer prnum=2;
        int cycle=1;
        while(cycle<251){
           if(isPrime(prnum)){
                sum+=prnum;
                   cycle++;
            }
         
           
           prnum++;
            
        }
        System.out.println("Sum: "+(int)sum);
    }
    
    //Determine whether a number is prime by doing a check

    public static boolean isPrime(int num){
       
         for(int i=2; i<num;i++){
           if (num%i==0||num==1){
               return false;
                    }
                }
      return true;
         }
}

Tuesday, April 15, 2014

Another Java Challenge

Challenge:

Given the following information:

a = 26, b = 25, c = 24, d = 23 ..... x = 3, y = 2, z = 1

What is the sum of each letter of this sentence: "The quick brown fox jumped over the cow"?

Answer:

public class Revalphabetcodes {
   
    public static void main(String[] args) {
        String element="The quick brown fox jumped over the cow";
        int cycle=element.length()-1;
        int sum=0;
        while(cycle>-1){
              if(Character.getNumericValue(element.charAt(cycle))!=-1){
         
            sum+=36-Character.getNumericValue(element.charAt(cycle));
                }
             cycle--;
            }
        System.out.println("sum is: "+sum);
        }
   
}

Friday, April 11, 2014

Java Examples executed

1. List Iterator with input from console

The following is a an example run for inputting an ArrayList from console and reads out. This example is for novices only............

package iteratortut;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.ListIterator;

public class Iteratortut {
    public static void main(String[] args) throws IOException {
        ArrayList<String> vegs=new ArrayList<String>();
        ListIterator ltr=null;
        BufferedReader bufferRead=new BufferedReader(new InputStreamReader(System.in));
        boolean inputreq=true;
        String s=null;
        String veginput=null;
           while(inputreq){
            System.out.println("Whether you want to continue : ");
            try{
            s=bufferRead.readLine();
                }catch(IOException e){
                e.printStackTrace();
                }
           
            if (s.equals("no")){
               inputreq=false;
            }
           
            System.out.println("The vegetable name is= ");
            veginput=bufferRead.readLine();
            vegs.add(veginput);
        }
       
        for(String veg: vegs){
            System.out.println("hi"+veg);
              }
       
    }
   
}

2. Challenge:  the sum of the digits of 2 to the 10th power is: 2^10 = 1024 => 1+0+2+4 => 7

What is the sum of the digits of 2^50?

 package powaddition;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Scanner;

public class Powaddition {
    public static void main(String[] args) {
       int number=0;
       int power=0;
       int cycle=0;
      //Input number from console       
        System.out.println("What is the power: " );
        Scanner pscn=new Scanner(System.in);
        power=pscn.nextInt();

        System.out.println("What is the number: " );
        Scanner scn=new Scanner(System.in);
        number = (int) Math.pow(scn.nextInt(), power);

//How many cycle this will iterate through
        cycle=String.valueOf(number).length();
//Length of array to be created
         int[] intarry=new int[String.valueOf(number).length()];
     
//Call the function to perform seperation
 while(cycle>0){
            int res=addpower(number,cycle);
            System.out.println("the value returned is "+res);
            intarry[cycle-1]=res;
            number=(int) (number-res*Math.pow(10, cycle-1));
            cycle=cycle-1;
            }
       int sum=0;
       int iter=0;
        for(Integer n:intarry){
           sum=sum+intarry[iter];
           iter++;
                 }
        System.out.println("Sum is="+sum);
    }
//Function that performs separation
 
   public static int addpower(double d, int n){
               int num=(int) ((int)d/Math.pow(10, n-1));
                System.out.println("The rerune value is "+ num);
       return num;
      
           }
   
}