Thursday, October 12, 2017

Fun Game : FLAMES Calculator.

In School time every one had tried out this game seriously/secretly with your dream one name. So we all know the rules of the game right?!.

 Lets look it into coding,

Here i have done the coding for this fun game,


/**
* Do flames check.Here we are finding the number of unmatched characters in both name.
*
* @param p_sYourName the p s your name
* @param p_sPartnerName the p s partner name
*/
private static void doFlamesCheck(String p_sYourName, String p_sPartnerName) {
int l_iUnLength = p_sYourName.length();
int l_iPnLength = p_sPartnerName.length();
for (int i = 0; i < p_sYourName.length(); i++) {
Loop: for (int j = 0; j < p_sPartnerName.length(); j++) {
if (p_sYourName.charAt(i) == p_sPartnerName.charAt(j)) {
l_iUnLength--;
l_iPnLength--;
break Loop;
}
}
}

int count = l_iUnLength + l_iPnLength;
doFlames(count);
}


/**
* Do flames.Here we find the character for the flame.
*
* @param val the val
*/
private static void doFlames(int val) {
String l = "FLAMES";
while (l.length() > 1) {
int k = val % l.length();
if (k != 0) {
l = l.substring(k, l.length()) + l.substring(0, k - 1);
}
if (k == 0) {
l = l.substring(0, l.length() - 1);
}

}
findRelation(l.charAt(0));
}


/**
* Find relation. Here just to print the relationship between both depends on doFlames() return char.
*
* @param rel the rel
*/
private static void findRelation(char rel) {
switch (rel) {
case 'F':
System.out.println("friendship");
break;
case 'L':
System.out.println("Love");
break;
case 'A':
System.out.println("Affection");
break;
case 'M':
System.out.println("Marriage");
break;
case 'E':
System.out.println("Enemy");
break;
case 'S':
System.out.println("Sister");
break;

default:
System.out.println("--");
break;
}
}

       /**
* The main method. Get the input from user to find the flames relationship.
*
* @param args the arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter Your Name : ");
String l_sYourName = input.next();
System.out.println("Enter Your Partner Name : ");
String l_sPartnerName = input.next();
doFlamesCheck(l_sYourName, l_sPartnerName);
}

NOTE: Please share your comments to improve the blog. Thank you.!

Tuesday, September 26, 2017

ZOHO QUESTION :Find his no of grandchildren of given person.

Question: Given a two dimensional array of string like

  <”luke”, “shaw”>
  <”wayne”, “rooney”>
  <”rooney”, “ronaldo”>
  <”shaw”, “rooney”>

Where the first string is “child”, second string is “Father”. And given “ronaldo” we have to find his no of grandchildren Here “ronaldo” has 2 grandchildren. So our output should be 2.


Discussion and Analysis :

Do find grandchildren, we need to find the son of ronaldo. Then need to find the son of the ronaldo's son.

First find the number of son ronaldo have, get this as list.


/**
     * Find grand son.
     *
     * @param a
     *            the a
     * @param l_sPerson
     *            the l s person
     * @param l_sSon
     *            the l s son
     */
    private static void findGrandSon(String[][] a, String l_sPerson,
            String l_sSon) {
        List<String> l_lstGrandSon = new ArrayList<String>();
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[i].length; j++) {
                if (l_sSon.contains(a[i][j])) {
                    if (j != 0) {
                        l_lstGrandSon.add(a[i][j - 1]);
                        System.out.println(a[i][j - 1] + " is grand son of  "
                                + l_sPerson + " son of " + l_sSon);
                    }
                }
            }

        }
    }


Then do find the son of the ronaldo's son.  

/**
     * Find grand son.
     *
     * @param a
     *            the a
     * @param l_sPerson
     *            the l s person
     * @param l_sSon
     *            the l s son
     */
    private static void findGrandSon(String[][] a, String l_sPerson,
            String l_sSon) {
        List<String> l_lstGrandSon = new ArrayList<String>();
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[i].length; j++) {
                if (l_sSon.contains(a[i][j])) {
                    if (j != 0) {
                        l_lstGrandSon.add(a[i][j - 1]);
                        System.out.println(a[i][j - 1] + " is grand son of  "
                                + l_sPerson + " son of " + l_sSon);
                    }
                }
            }

        }
    }

And finally main method with array input./**
     * The main method.
     *
     * @param args
     *            the arguments
     */
    public static void main(String[] args) {
        String[][] a = { { "luke", "shaw" }, { "wayne", "rooney" },
                { "rooney", "ronaldo" }, { "shaw", "rooney" } };

        String l_sPerson = "ronaldo";
        String l_sSon = findSon(a, l_sPerson);
        findGrandSon(a, l_sPerson, l_sSon);
    }

Output:

rooney is son of  ronaldo
wayne is grand son of  ronaldo son of rooney
shaw is grand son of  ronaldo son of rooney




NOTE : Please comment below it will help me to improve the solution. Thank you..!

ZOHO QUESTION : Given a 9×9 sudoku we have to evaluate it for its correctness. We have to check both the sub matrix correctness and the whole sudoku correctness.

Discussion and Analysis:

Here is some interesting question we have about checking sudoku correctness.

Here the rules of sudoku following,

For example we have 9*9 sudoku,

So we have 81 number of square grid. This grid divided into 9 blocks.Each block have 9 square so totally 81 square.

So it has 9 rows and 9 columns. Each rows have number 1-9. But a number appears only once in the row as well as same rule for column.


Solution : 


/**
     * Find correctness.
     *
     * @return true, if successful
     */
    private static boolean evaluateSudoku() {
//Here is our input as 9*9 matrix.
        int[][] l_arrSudukoMatrix = new int[][] {
                { 5, 1, 3, 6, 8, 7, 2, 4, 9 },
                { 8, 4, 9, 5, 2, 1, 6, 3, 7 },
                { 2, 6, 7, 3, 4, 9, 5, 8, 1 },
                { 1, 5, 8, 4, 6, 3, 9, 7, 2 },
                { 9, 7, 4, 2, 1, 8, 3, 6, 5 },
                { 3, 2, 6, 7, 9, 5, 4, 1, 8 },
                { 7, 8, 2, 9, 3, 4, 1, 5, 6 },
                { 6, 3, 5, 1, 7, 2, 8, 9, 4 },
                { 4, 9, 1, 8, 5, 6, 7, 2, 3 } };
        Set<Integer> l_stRowSet = new HashSet<Integer>();
        Set<Integer> l_stColumnSet = new HashSet<Integer>();
//Here haveDuplicate variable to return the true/false. If haveDuplicate is false the sudoku is valid one.Otherwise its wrong sudoku.
        boolean haveDuplicate = true;

        for (int i = 0; i < l_arrSudukoMatrix.length; i++) {
            for (int j = 0; j < l_arrSudukoMatrix[i].length; j++) {
//Here to check the entered value is greater than zero and less than 10
              if(l_arrSudukoMatrix[i][j] > 0 && l_arrSudukoMatrix[i][j] < 10){
                l_stRowSet.add(l_arrSudukoMatrix[i][j]);
                }
            }
            for (int j = 0; j < l_arrSudukoMatrix[i].length; j++) {
//Here to check the entered value is greater than zero and less than 10
              if(l_arrSudukoMatrix[j][i] > 0 && l_arrSudukoMatrix[j][i] < 10){
                l_stColumnSet.add(l_arrSudukoMatrix[j][i]);
                }
            }
//If Row/Column have less than 9 size we have some repeated value, so we can return true.
            if (l_stRowSet.size() != 9 && l_stColumnSet.size() != 9) {
                return false;
            }
        }

        return haveDuplicate;

    }

Output : For this given input matrix true will be return.
If you modify some input with repeated value or greater than 9 and less than zero then system return false.


NOTE: Please share your comments to improve the flag. Thank you!

Monday, September 25, 2017

ZOHO Question : Find sum of weights based on the following conditions

Question :

Given a set of numbers like <10, 36, 54,89,12> we want to find sum of weights based on the following conditions
    1. 5 if a perfect square
    2. 4 if multiple of 4 and divisible by 6
    3. 3 if even number

And sort the numbers based on the weight and print it as follows

<10,its_weight>,<36,its weight><89,its weight>.

Solution : 
      
              To solve this program we need some logic to find the give conditions,
  • Weight is 5 if given number is perfect square of any number for example : 4,9,16,36
  • Weight is 4 if given number multiple of 4 AND divisible by 6
  • Weight is 3 if given number is even number. 
Some number may pass any two of the above condition, some of them pass single condition.

Program solution:

Condition 1 : Weight is 5 if given number is perfect square of any number for example : 4,9,16,36

 /**
     * Check squere.
     *
     * @param number the number
     * @return the int
     */
    private static int checkSquere(int number) {
        int l_ireturn = 0;
            for (int i = 2; i < number; i++) {
                int j = number / i;
                if (i == j && i*j == number) {
                    l_ireturn = i;
                }
            }
            return l_ireturn;
    }

 Condition 2 : Weight is 4 if given number multiple of 4 AND divisible by 6

/**
     * Logic multiple divison.
     *
     * @param number the number
     * @return the int
     */
    private static int logicMultipleDivison(int number){
        int l_ireturn = 0;
        int l_iMulti = number/4;
        if(l_iMulti*4 == number)
        {
            l_iMulti = number/6;
            if(l_iMulti*6 == number)
            {
                l_ireturn = 4;
            }
        }
       
        return l_ireturn;
    }

Condition 3 : Weight is 3 if given number is even number. 

/**
     * Logic even number.
     *
     * @param number the number
     * @return the int
     */
    private static int logicEvenNumber(int number)
    {
        int l_ireturn = 0;
       
        if(number%2 == 1)
        {
             l_ireturn = 3;
        }
        return  l_ireturn;
    }

Do you think i have missed something from the question? . yes we missed it but we have the coding solution below?


In the question we have set of numbers are given as input so we need to iterate all the numbers from given set and check the above condition 

Do Iterate the set of given number and find the weight of each number by calling the logic what we have done before..!

private static Map<Integer,Integer> doIterateSet(Set<Integer> l_setInteger)
    {
        Iterator<Integer> itr = l_setInteger.iterator();
        Map<Integer,Integer> l_mapWeightMap = new HashMap<Integer,Integer>();
        while (itr.hasNext()) {
            int number = itr.next();
            int l_iSquere = checkSquere(number);
            int l_iMulDiv = logicMultipleDivison(number);
            int l_iEven = logicEvenNumber(number);
            l_mapWeightMap.put(number, l_iSquere+l_iMulDiv+l_iEven);
        }
        return l_mapWeightMap;
    }


Yes, We are iterate the set but where is the set input, Cool we have the main method, which have the set of integer input...

 public static void main(String[] args) {
      
        Set<Integer> l_setNumberSet = new HashSet<Integer>();
        l_setNumberSet.add(10);
        l_setNumberSet.add(36);
        l_setNumberSet.add(54);
        l_setNumberSet.add(89);
        l_setNumberSet.add(12);
        Map<Integer,Integer> l_mapWeightMap = doIterateSet(l_setNumberSet);
        System.out.println(l_mapWeightMap);
      

    }

Finally the println method prints the given number and there weights for given condition.

Output : 

{54=0, 36=10, 10=0, 89=3, 12=4}

Here i just print the map as output if you want some readable format please do the the change on the main method and iterate the map and print the output whatever you want. 
 

 NOTE : Please give your comment to improve my coding standard as well as my functional logics.

Friday, September 22, 2017

Find the sentance is pangrams or not using java?

First Pangrams explanation:
 
Pangrams are sentences constructed by using every letter of the alphabet at least once.


 Here is java code to find the pangrams,


private static void findPangrams(String p_sSentance) {
        Set<Character> l_objSet = new HashSet<Character>();
        int l_iLength = p_sSentance.length();
        while(l_iLength > 0)
        {
            if(p_sSentance.charAt(l_iLength-1) != ' '){
            l_objSet.add(p_sSentance.charAt(l_iLength-1));
            }
            l_iLength--;
        }
        if(l_objSet.size() == 26)
        {
            System.out.println("Pangram");
        }else{
            System.out.println("Not pangram");
        }
    }

Input 1 : "Pack my box with five dozen liquor jugs"
Input 2 : "Pack my box with five liquor jugs"

Output 1 :  Pangram
Output 2 :  Not pangram


Tuesday, July 4, 2017

JDK,JRE and JVM.


 JDK - Used for develop the application, its provider the tool kit for develop.Here we write the .java class.It includes the JRE, set of API classes, Java compiler and additional files needed to write Java applications.

JRE - Used for compile the java class. Its convert the java code into byte code, mean .java to .class using java compiler.Its JER contains compiler and APIs.Its contains JVM , Core libraries and other additional components to run applications.

JVM - Used to execute the .java class. To execute the .class file we have interpretor. This interpretor read every line of byte code and execute that.

Friday, June 30, 2017

How to Compare Two Objects with the equals Method in Java? What is the differents between == and equals()?

Difference between == and equals() in java.

  •  == check object reference are same or not.It check only the objects are same, not equality of object.
  • equals() check reference values are same are not.Its checks the equality of the object fields. If you want to check the object equality we need to override the equals(). 
Example:

    //Value stored in String Pool
   String l_sValue = "Equals";

    //Reference stored in heap memory.
    String l_sSecValue = new String("Equals");

   //Both objects having same value. The values are equals.So its returns true.
    if(l.equals(k)) Output: return true;

   //Both are addressing different object, returns false.
    if((l == k)) Output: return false;

/**
 * @author palrajb
 *
 */
public class Test {

    private String name;
    private int age;
    private int marks;

    public Test() {
    }

    public Test(String name, int age, int marks) {
        this.name = name;
        this.age = age;
        this.marks = marks;
    }

    public void setMarks(int marks) {
        this.marks = marks;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {


        Test t = new Test("1", 1, 1);// Create the object t with three parameter constructor.

        Test t1 = (Test) t;
// Addressing same reference.

        t1.setMarks(2);
// Changes on t1 directly affect t. Because t1 is addressing t reference.                      
// Here t and new object having same values, but we are not override the equals() to equals the fields of Test class. So passing reference are different. 

       System.out.println(t.equals(new Test("1", 1, 1)));Output : false
// Here we are t and t1 are addressing single object t.So their address  and fields are same, returns  true.
      System.out.println(t.equals(t1)); Output : true
// Here we are t and t1 are addressing single object t. As per state check only the objects are same, return true.
      System.out.println(t == t1);Output : true




if you want to make t.equals(new Test("1",1,1)) true, we need to override the equals()

@Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Test other = (Test) obj;
        if (age != other.age)
//Here checking the age of t and new Test("1",1,1) object age is not same.
            return false;
        if (name == null) {
//Null check for name, because we have setter method for name variable.
            if (other.name != null)
//Same null check for new Test("1",1,1).
                return false;
        } else if (!name.equals(other.name))
//Here checking the name of t and new Test("1",1,1) object name is not same.
            return false;
        return true;
    }


After the equals() implementation, now execute the

System.out.println(t.equals(new Test("1", 1, 1)));//Output: true. Because we customized the equals method as we want. We just compare the age and name variable only, we are not consider the marks variable for equals() implementation so changes the value by using
t1.setMarks(2); not affect anything on the equality.


Meanwhile we know that if we override the equals() then we need to override hashCode().

@Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }


Do you feel we would missed any variable in equals() and hashCode().
    Yes, the marks variable is missing. Key to override the equals() and hashCode() is the filed used in equals() must be used hashCode implementation.





Thursday, June 29, 2017

Java is pass-by-value or pass-by-reference?

Java is strictly pass-by-value. 

Then the next question is how it is pass-by-value ?
   
 Here the explanation from SCJP.


"Java is actually pass-by-value for all variables running within a single VM. Pass-by-value means pass-by-variable-value. And that means, pass-by-copy-ofthe-variable,which means pass-by-copy-of-the-bits-in-the-variable"


Here we have example for passing variable and passing reference.


package com.test.java;

/**
 * @author palrajb
 *
 */
public class Test {

    private String name;
    private int age;
    private int marks;

    public Test() {
    }

    public Test(String name, int age, int marks) {
        this.name = name;
        this.age = age;
        this.marks = marks;
    }

    public void setMarks(int marks) {
        this.marks = marks;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {

        Test l_objTest = new Test("A", 1, 12);
        int l_iIntValue = 1;
        System.out.println("Mark Before invoke : " + l_objTest.marks + " IntValue :" + l_iIntValue);
      
  //Output:Mark Before invoke : 12 IntValue :1
        doTest(l_objTest, l_iIntValue);
//Here we are passing reference and variable as parameter.
        System.out.println("Mark After invoke : " + l_objTest.marks    + " IntValue :" + l_iIntValue);
       
//Output:Mark After invoke : 14 IntValue :1
    }





Here we got the copy of calling method reference variable. We change the p_iIntValue +1, but the called method can't change the caller's variable.So when we print this from main method its still 1. For p_objTest.setMarks(14) will change the caller l_objTest object marks to 14,because the called method can change the object the variable referred.

     static void doTest(Test p_objTest, int p_iIntValue)
    {
        p_iIntValue = p_iIntValue + 1;
//Using same reference but in different address.So increment happens only on newly created address not on old one.The called method can't change the caller's variable
        p_objTest.setMarks(14);
//called method can change the object the variable referred.
        p_objTest = new Test("B", 2, 13);
//we using same reference but in different address. So the caller reference not going to change anyway.
        p_objTest.setMarks(15);//
change the mark value in newly referenced object.
    }

}

Tuesday, June 27, 2017

What happen when you are not print or throw the exception in catch block?

try block-- Here the actual logic and implementation. 
catch block--If try block may have come error in the logic or implementation we can catch the error.Here we can catch the try block error.Catching error is just do print the stack trace of the what error is occurred.

Now consider we are trying below condition, its just do create exception in try block,do not bother about implementation in try block.

package com.test.java;

import java.util.Scanner;

/**
 * @author boomiraj
 *
 */
public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Scanner l_objInput = new Scanner(System.in);
        System.out.println("Please Enter the value : ");
        convertStringToInt(l_objInput.next());
    }

    private static void convertStringToInt(String p_sValue) {
        int i = 0;
        try {

            i = Integer.parseInt(p_sValue);
            if (i < 100) {
                i = i + 1;
            } else {
                i = i - 1;
            }

        } catch (NumberFormatException e) {
         }
        System.out.println("Converted into interger from string : " + i);
    }

}


In public method we are calling convertStringToInt(String) to convert given String Value to Int.
   
    We are getting input from user, so user can enter any possible combination of input like
    Alphabet
    Alphanumeric
    Number
    Special character
   
    If user enters only Number, its not problem we can get the output without error.
    But if he tries any other combination then there is possibility to have an error.
    In this scenario we are catch the exception, but in the catch block we don't have any print stack trace or print log.
    then the user does not know that the entered values are not able to convert into Int. But he always get some output.

    This may cause the some blocker issue in your project.

  catch (NumberFormatException e) {
            System.err.println("Cannot convert the value '" + p_sValue
                    + "' to integer");
        }


So always print something into your catch block.

Monday, June 19, 2017

Change the execution value by the time of debug in eclipse.

If you want to change the value of the primitive instance we can change by using variables tab.
or else we can change the value by using "Display" window.

In Variable tab we can see the all the object and instance of the current thread.
Press (Cntl+f) and type the variable name you want to change the value.
Then click on the right side of the variable and change the value.
Note : By this way we can only change the value of primitive data type. We cannot change the object reference.


In Display window you can write the value to be change and select the line and press (ctrl+u).
If I have the String l_sValue = "World"; if i want to change the String l_sValue = "Change the World";
l_sValue = "Change the World"; copy this line and press (ctrl+u)
Note : By this we can do change both primitive and object reference.