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;

}