Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Thursday, May 5, 2022

ZOHO QUESTION : Given a 9×9 sudoku we have to evaluate it for its correctness.

Here we have some simplest way to check the sudoku validation. And we have few discussion and suggestion on this post comments section, so we decided to give the solution as per the discussion.

Coding snippet:

private static boolean check(){

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

for(int i = 0 ; i < l_arrSudukoMatrix.length; i++){
int sumRow = 0;
int sumColumn = 0;
int col = 0;
for(int j = 0 ; j < l_arrSudukoMatrix.length; j++){
sumColumn += l_arrSudukoMatrix[i][j];
sumRow += l_arrSudukoMatrix[j][i];
col = j;
}
if(sumRow != 45 || sumColumn != 45){
System.out.println("invalid");
return false;
}
}
System.out.println("valid");
return true;
}


Output: valid

If you change input array to duplicate any value in row or column you will get output like this.

Input: 

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, 0 }, //0 is not a valid one.
{ 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 } };

Ouput: Invalid


Thank you.

Wednesday, March 30, 2022

Interview Question: Sub String Palindrome using java.

Recent day interviews you may faced this question in programing interview. Find the sub string palindrome of given string input.

We have many way to solve it. Here I added coding snippet which I tried to solve it.

First one I used two for loop to solve it. Its very simple and easy.


private static List<String> subStringPalindrome(String value) {
List<String> list = new ArrayList<>();
for(int i =0 ; i < value.length(); i++){
for(int j = i+1 ; j < value.length(); j++){
StringBuffer s1 = new StringBuffer(value.substring(i,j));
String s2 = s1.reverse().toString();
if(value.substring(i,j).contentEquals(s2) && s1.length()> 1){
list.add(s1.toString());
}

}
}
return list;
}
List<String> list = subStringPalindrome("eetestseeammadam");
Output: [ee, ete, estse, sts, ee, amma, mm, ada]
Its very simple and easy. This code look simple and easy  and I tried another way using recursion.

private static List<String> printPalindromeSubString(String value;) {
List<String> list = new ArrayList<>();
if(value.equals(new StringBuilder(value).reverse()))
list.add(value);
for(int i=0; i <= value.length(); i++){
if(i > 1 && i < value.length() -1){
StringBuffer reverse = new StringBuffer(value.substring(i-2, i+1));
if(value.substring(i-2, i+1).contentEquals(reverse.reverse())){
System.out.println("Called2");
list.add(value.substring(i-2, i+1));
if(i>2){
if(i+2 <= value.length()){
new Test().callRecursion(value,value.substring(i-2, i+1), i-1, i, list );
}
}
}
}
if(i > 0 && i < value.length() ){
StringBuffer stringBuffer = new StringBuffer(value.substring(i-1, i+1));
if(value.substring(i-1, i+1).contentEquals(stringBuffer.reverse())){
list.add(value.substring(i-1, i+1));
System.out.println("Called");
if(i > 1){
new Test().callRecursion(value,value.substring(i-1, i+1), i, i, list );
}
}
}
}
return list;
}

private List<String> callRecursion(String value, String reversed, int i, int j, List<String> list){
if(j+1 >= value.length())
return list;
else if(value.charAt(i-2) == value.charAt(j+1)){
String s = value.charAt(i-2) +reversed+ value.charAt(j+1);
list.add(s);

callRecursion(value, s, i-1, j+1, list);
}
System.out.println(list);
return list;
}
List<String> list = printPalindromeSubString("eetestseeammadam");
Here i used recursion to find palindrome on given substring. And the output is 
[ee, ete, sts, estse, ee, mm, amma, ada, madam]

And the output is  If you check the output from two logic, there is a mismatch.. First one print only 8 palindrome and recursion logic print 9 palindrome. 'madam' missing in first logic. 
Lets make this blog more interactive with techies, Please find the missing condition or part of code on comment area.✌✌ 

Thanks in advance.

Wednesday, March 16, 2022

Lambda expression in java.

In this post we will going to discuss about what is lambda expression in java?. How to use them?. How it helps developers?. All this question will be answered end of this post.

Before we start answering this question, let we look in to some implementation to get 10+years experience employee from list of employee object.

Here coding snippet: 


public class Employee {


private int id;
private String name;
private double experience;
private long salary;
private int rating;

public Employee(int id, String name, double experience, long salary, int rating) {
this.id = id;
this.name = name;
this.experience = experience;
this.salary = salary;
this.rating = rating;

    }

    //Getter and Setter here

 }  

Here my implementation class to print 10+years experience employee. 


public static void main(String[] args) {
Employee employee1 = new Employee(5, "Antwaun", 5.5, 10000L, 1);
Employee employee2 = new Employee(2, "Rick", 32.5, 2000L, 3);
Employee employee3 = new Employee(1, "Richard", 50, 3000L, 4);
Employee employee4 = new Employee(3, "Corey", 22.5, 20000L, 2);
Employee employee5 = new Employee(4, "Chumlee", 10.5, 15000L, 5);

List<Employee> employeeList = new ArrayList<>();
employeeList.add(employee1);
employeeList.add(employee2);
employeeList.add(employee3);
employeeList.add(employee4);
employeeList.add(employee5);

printEmployeeExpGreaterTenYears(employeeList);
}
public static void printEmployeeExpGreaterTenYears(List<Employee> employeeList){
for(Employee employee: employeeList){
if(employee.getExperience() >= 10){
System.out.println(employee);
}
}
}

Output:
Employee{id=2, name='Rick', experience=32.5, salary=2000, rating=3}
Employee{id=1, name='Richard', experience=50.0, salary=3000, rating=4}
Employee{id=3, name='Corey', experience=22.5, salary=20000, rating=2}
Employee{id=4, name='Chumlee', experience=10.5, salary=15000, rating=5}

This looks good. we are iterating list and check the experience grater or equals to 10. If in future the requirement change like we need to get 10+ experience and rating will be more than 4+. So then we need to change the existing logic or else we need to write a new method with two param. 

Let see the implementation,
public static void printEmployeeExpGreaterTenYearsAndSalaryPassed(
List<Employee> employeeList, int rating){
for(Employee employee: employeeList){
if(employee.getExperience() >= 10 && employee.getRating() >= rating){
System.out.println(employee);
}
}
}

These condition may be change in future. Like employee salary, employee name or we may add some new variable in Employee class. So its not good to change existing logic or add new logic when we have new enhancement to be implement. 
So what else we can do?? .. Let think about Functional Interface in java 8. 
  • Functional interface, which have only one abstract method and any number of default method.
Let we create a Function interface with one abstract method. Interface name CheckEmployee for now have method name test(). 

public interface CheckEmployee {
boolean test(Employee employee);
}

Here we need to implement this test method, so I have created CheckEmployeeService class.
public class CheckEmployeeService implements CheckEmployee {
@Override
public boolean test(Employee employee) {
return (employee.getExperience() >= 10 && employee.getRating() >= 4);
}
}
Let add a method to printEmployee in out Impl class.
public static void printPersons(
List<Employee> employeeList, CheckEmployee checkEmployee){
for(Employee employee: employeeList){
if(checkEmployee.test(employee)){
System.
out.println(employee);
}
}
}
Now we can call this printPersons method from main method, 
printPersons(employeeList, new CheckEmployeeService());
Output:
Employee{id=1, name='Richard', experience=50.0, salary=3000, rating=4}
Employee{id=4, name='Chumlee', experience=10.5, salary=15000, rating=5}

Its looks good. but we have created a Interface and Service class, that's not necessary we can create them inside the Impl class itself.

As already said CheckPerson interace is Functional interface. Because it has one and only abstract method. Java provide lambda operation for functional interface. We can use lambda expression on functional interface.
Let see how we can use them,

printPersons(employeeList, new CheckEmployeeService());
System.out.println("Lambda expression ");
printPersons(employeeList,
(Employee employee) -> employee.getExperience() >= 10 && employee.getRating() >= 4);
Output: 
Employee{id=1, name='Richard', experience=50.0, salary=3000, rating=4}
Employee{id=4, name='Chumlee', experience=10.5, salary=15000, rating=5}
Lambda expression 
Employee{id=1, name='Richard', experience=50.0, salary=3000, rating=4}
Employee{id=4, name='Chumlee', experience=10.5, salary=15000, rating=5}
Now you might get idea of how do we use lambda expression in java 8. In Functional interface we can use lambda expression. By using lambda expression it reduces the coding effort. Java provide many Functional interface, they all available in java.util.function 
For example we can use you can use the Predicate<T> interface in place of CheckEmployee. This interface contains the method boolean test(T t).
Let see how to use predicate interface instead of CheckEmployee.
public static void printEmployeesWithPredicate(
List<Employee> roster, Predicate<Employee> tester) {
for (Employee p : roster) {
if (tester.test(p)) {
System.out.println(p);
}
}
}
call from main method, 
printEmployeesWithPredicate(employeeList,
(Employee employee) -> employee.getExperience() >= 10 && employee.getRating() >= 4);
This will print the same output ass like what we have printed by using CheckEmployee interface. So far we have answered what is lambda expression, how to use them and how it helps developer to reduce the coding effort. I hope this will give some basic and deep understanding of lambda expression. 
There are lot of Functional interface we have in java. Please go through the JavaDoc . So When we are speaking about lambda expression you might think of Steams.. Are you??. Okay. Let see how to we use Stream to printPersion.

Classes to support functional-style operations on streams of elements,
such as map-reduce transformations on collections. - JavaDoc .

Stream support functional style operation on stream element. Let we use stream element to printPersons. Here code snippet.
employeeList
.stream()
.filter(
employee -> employee.getExperience() >= 10 && employee.getRating() >= 4)
.forEach(employee -> System.out.println(employee));
This will print the same output ass like what we have printed by using CheckEmployee interface.

I hope this will give some basic and deep understanding of lambda expression and stream.  

Thank you all.
Consolidated Coding snippet.
package com.example.monitoring.lambda;

import com.example.monitoring.compare.CheckEmployee;
import com.example.monitoring.compare.CheckEmployeeService;
import com.example.monitoring.compare.Employee;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

public class EmployeeServiceImpl {

public static void main(String[] args) {
Employee employee1 = new Employee(5, "Antwaun", 5.5, 10000L, 1);
Employee employee2 = new Employee(2, "Rick", 32.5, 2000L, 3);
Employee employee3 = new Employee(1, "Richard", 50, 3000L, 4);
Employee employee4 = new Employee(3, "Corey", 22.5, 20000L, 2);
Employee employee5 = new Employee(4, "Chumlee", 10.5, 15000L, 5);

List<Employee> employeeList = new ArrayList<>();
employeeList.add(employee1);
employeeList.add(employee2);
employeeList.add(employee3);
employeeList.add(employee4);
employeeList.add(employee5);

printEmployeeExpGreaterTenYears(employeeList);
printPersons(employeeList, new CheckEmployeeService());
System.out.println("Lambda expression ");
printPersons(employeeList,
(Employee employee) -> employee.getExperience() >= 10 && employee.getRating() >= 4);
printEmployeesWithPredicate(employeeList,
(Employee employee) -> employee.getExperience() >= 10 && employee.getRating() >= 4);

employeeList
.stream()
.filter(
employee -> employee.getExperience() >= 10 && employee.getRating() >= 4)
.forEach(employee -> System.out.println(employee));
}

public static void printEmployeeExpGreaterTenYears(List<Employee> employeeList){
for(Employee employee: employeeList){
if(employee.getExperience() >= 10){
System.out.println(employee);
}
}
}

public static void printEmployeeExpGreaterTenYearsAndSalaryPassed(
List<Employee> employeeList, int rating){
for(Employee employee: employeeList){
if(employee.getExperience() >= 10 && employee.getRating() >= rating){
System.out.println(employee);
}
}
}
public static void printPersons(
List<Employee> employeeList, CheckEmployee checkEmployee){
for(Employee employee: employeeList){
if(checkEmployee.test(employee)){
System.out.println(employee);
}
}
}

public static void printEmployeesWithPredicate(
List<Employee> roster, Predicate<Employee> tester) {
for (Employee p : roster) {
if (tester.test(p)) {
System.out.println(p);
}
}
}


}

Thursday, February 24, 2022

How to Check if an Array Contain Duplicate In Java?

Hello All, 

Here the coding snippet to check duplicate in array. I used char[] to check the duplicate character check in a string. 


private static void findDuplicate(String input){
char[] strChar = input.toCharArray();
boolean haveDuplicate = false;
for(int i = 0 ; i < input.length(); i++){
for(int j = i+1 ; j < input.length(); j++){
if(strChar[i] == strChar[j]){
haveDuplicate = true;
System.out.print(strChar[i]);
}
}
}
if(!haveDuplicate){
System.out.println("No duplicate found in array");
}
}
Let pass input as "Java".
Output : a

Pass input as "Python"
Output : No duplicate found in array

Tuesday, January 25, 2022

Java Long variable not equals on == check , why?

 Today we faced a issue in dev environment, the same code works perfectly in local. We have no clue what happens in prod, we thought of data is problem in dev environment. While comparing data between environment we find the empId (Long Type is problem), which mean the type is not a problem, the way compare the Long variable makes the problem in different environment.

Here code snippet of problematic code. 

Boolean isEmployee = employee.getEmpId() == emp.getEmpId();

Since in local we have limited data might be around 50 data max, so empId is might max 50.

Let see what happen in dev environment.

    Dev environment we have lot of data for this particular table. approximately 10000+ records.

Is count of employee table makes that problem??. Partially Yes. How??
Let me explain what is the problem with above code??
In java Long variable will have [-128 to 127] range. If the value is greater than -128 and
less than 127 above condition will return true. else false. why??


Let see how internally Long works, literal values auto boxing using Long.valueOf(String),
this will works on Long [-128 to 127] range and it will find the value from LongCache.
If number greater than 127, then new Long object will create, so while using "==" return false.


What is the fix for our problem??

    We need to use .equals instead of ==. Fix is employee.getEmpId().equals(emp.getEmpId()) or employee.getEmpId().longValue() == emp.getEmpId().longValue().


Here is two example of < 127 and > 127.

public static void main(String[] args) {
Employee employee = new Employee("B", 1, 128L);
Employee emp = new Employee("B", 1, 128L);
Boolean isEmployee = employee.getEmpId() == emp.getEmpId();
if(isEmployee){
//Logic here.
System.out.println("Same Employee");
}else{
System.out.println("Different Employee");
}
System.out.println(employee.getEmpId() == emp.getEmpId());
System.out.println(employee.getEmpId().equals(emp.getEmpId()));
}

Output:

Same Employee
true// two variable pointing to same address
true


If we change empId to 128 and the output below is,
Different Employee
false //False because new object created and reference pointing two different object.
true

Integer also works same way. Here the link for Integer on == 

Tuesday, January 11, 2022

Print nth Fibonacci using java recursion.

 Hey there, 

    We know the fibonacci start with 0, 1, then addition of previous two number. Here next numbers are 1(0+1), 2(1+1), 3(1+2), 5(2+3), 8(3+5), 13(5+8) like wise. 

Here i will post the recursion program for find the Nth fibonacci number. Recursion is calling a method from that method, simple calling itself. 

For Example : 


private static void sayHello(){
System.out.println("Hello !");
return sayHello();
}

If you execute this method we will end up with stackoverflow exception. The exception will
be thrown after jvm stack overloaded,

......... here is lot of Hello ! printed.
Hello !
Hello !
Hello !
Hello !
Exception in thread "main" java.lang.StackOverflowError
	at sun.nio.cs.UTF_8$Encoder.encodeLoop(UTF_8.java:691)
	at java.nio.charset.CharsetEncoder.encode(CharsetEncoder.java:579)

Because in this method we don't have any base condition to return this recursion stack trace.
This is very important when you go for recursion we need to have base condition at
first in you implementation.


private static void sayHello(int n){
if(n<1){
return ;
}
System.out.println("Hello !");
sayHello(n-1);
}

Here if condition check n is less than 1, this is our base condition. So now you will get
some idea about how recursion works in java. Let we get in our fibonacci program,


private static long printFibonacci(int n){
if(n<=1){
return n;
}
return printFibonacci(n-1) + printFibonacci(n-2);
}
If user input n is 5 then this program will print 5(0,1,1,2,3,5) the number is start with 0
so we will get 5.
Explanation for printFibonacci() is loading...

Tuesday, December 28, 2021

Java Memory

 As developer its important to know how memory works in java, its helps code optimization. Here we will learn how to manage memory in java.


Java memory split in to two section 


The stack and the Heap.


Stack is widely used memory, all the primitive types other than String are stored in stack, values stored in stack is not shared across the JVM because every thread have its own stack. Java exactly knows when the data on the stack be destroyed. We all know that stack is First In Last Out, so very time its create a data in a stack it will be the top of the existing data. For example, in below code

    int age = 12;

    int height = 100;

    String name = "User";

Data of the age variable is stored in stack at first on the top, then height variable is created on the stack on top of the age, then the name reference is create in stack on the top of the height variable.

                                



In the above stack image we can see the primitive values are stored in stack, but the String reference only saved in stack, where the data of String is getting saved, yes its getting saved in heap memory.

Heap 

Data allowed in heap will be live longer than stack, because there only one heap per application, so the data saved in heap will be shared with other method or function across the application. 


Here I add some code snippet for collection object. I am adding list of string in List object, and then printing the string calling other method. Below code up to line number 12, we are adding string in list called stringList. 





Above image stringList reference is stored in stack and all data in the list is saved in heap List and each string stored in separately. Since Line 10 and 12 we are adding "One" to the list, so index 2 of  list will use existing string One.                                                                                                                              

Let see what happen if we execute lien 13, calling a method from main method. Here jvm will create a new thread for new method call getList().                                                                                                  




If you see the above image stringList is out of scope. Because the current thread is running getList() until line 22 execute stringList is out of scope. After Line 22 execute stringList will be on visible, see the below image                                                                                                                                      

stringList has 3 string in it before execute getList(), after execution of getList() the stringList having 4 string in it. Because of getList method works on copy of reference of  value of the stringList.    
    
Are you confused with pass by value and pass by reference, check below post there I explained clearly.

Print Number of occurrences of each character from a string.

 Print the Number of occurrences of character form a string, we have many solution to solve this.

Here I posted a simple way I used to print number of occurrences of each character. 


private static void occurrenceOfChar(String input) {
int length = input.length();
char[] inputArray = input.toCharArray();
while(input.length() > 0){
input = input.replace(inputArray[0]+"", "");
System.out.println(inputArray[0] +" Occurrences is " + (length - input.length()));
inputArray = input.toCharArray();
length = input.length();
}
}
Input : Helloworld
Output : 
H Occurrences is 1
e Occurrences is 1
l Occurrences is 3
o Occurrences is 2
W Occurrences is 1
r Occurrences is 1
d Occurrences is 1


Thursday, October 10, 2019

String Manupulation Interview Questions

I/P : "ABC","DEF","GHI","JKL","MNO" (1,2,3,4,..N)
O/P:"ABC","MNO","DEF","JKL","GHI" (1,N-1,2,N-2.....)

Logic :


    public static void main(String[] args) {

        String[] str = { "ABC", "DEF", "GHI", "JKL", "MNO" };

        int ln = str.length - 1;
        for (int i = 0, j = ln; i <= j; i++, j--) {
            if (i == j) {
                System.out.println(str[i]);
            } else {
                System.out.println(str[i]);
                System.out.println(str[j]);
            }
        }

    }

How to create singleton object and how to make it thread safe?

Singleton class is a class which can have only one object at a time.

Restriction/avoid to create the multiple object. Single object can be used over the application.

We can restrict/avoid to create a object of class from other class, we can achive by setting constructor private.

/**
 *
 */
package com.learn.java.thread;

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

    private SingleTon() {
       
    }

}


If we made constructor private, then what is the use of class and how it will going to be used in application.

Give public static factory method to create instance

public static final SingleTon objectSingleTon = new SingleTon();

its looking good, but its getting eagerly initialized, if nobody used this variable then we are created unused object??!!

Let make it lazt initialize,

public class SingleTon {

    public static SingleTon objectSingleTon = null;

    private SingleTon() {

    }

    public static SingleTon createObject() {

        objectSingleTon = new SingleTon();

        return objectSingleTon;

    }

}


Its always better do null check before object creatation is good practice.

public static SingleTon createObject() {

        if (objectSingleTon == null) {

            objectSingleTon = new SingleTon();

        }

        return objectSingleTon;

    }

   
Above logic is works perfect for single thread enviroment. If multiple thread is trying to create the object, first thread is checking object is null and creating object, at this time    next thread checks object null , yes instance is null so it will come to next line and create object so totally two object ??? . Do avoid this we can use synchronised key.


public static SingleTon createObject() {
        if (objectSingleTon == null) {
            synchronized (SingleTon.class) {
                if (objectSingleTon == null) {

                    objectSingleTon = new SingleTon();

                }
            }
        }
        return objectSingleTon;
    }


Its always better to have double check the object null.

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) {
         double sqrt = Math.sqrt(number);
            if (sqrt == (int) sqrt) {
                return 5;
            }
         return 0;
    }

 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){
        if (number % 4 == 0 && number % 6 == 0) { return 4; }
        return 0;
    }

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)
    {
        if (number % 2 == 0 ) { return 3; }
        return 0;
    }

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);
              
        l_mapWeightMap.entrySet().stream()
        .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue())) // Sort descending by weight
        .forEach(e -> System.out.print("<" + e.getKey() + "," + e.getValue() + ">"));

    }

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

Output : 

<36,12>, <12,7>, <10,3>, <54,3>, <89,0>,

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