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