Thứ Hai, 25 tháng 8, 2014

Matrix problem in java.

problem: 

            Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0.

for example:

A matrix of order 3X3 contains elemennts like 

124
037
598

after performing algorithm out put will be

024
000
098


solution:


package logics;

public class matrixProblem {
    public static void main(String []a)
    {
        int [][]data=new int[][]{{1,2,4},{0,3,7},{5,9,8}};
        System.out.print("Before completing task \n");
        printdata(data);
        getdata(data);
    }

public static void getdata(int [][] mat)
{
    int rowlength=mat.length;
    int collength=mat[0].length;
    int row[]=new int[rowlength];
    int col[]=new int[collength];
    for(int i=0;i<rowlength;i++)
    {
            for(int j=0;j<collength;j++)
            {
                if(mat[i][j]==0)
                {
                    row[i]=1011;//am setting reference as 1011  where i need to set 0 .
                    col[j]=1011;
                }
            }
   
    }
    for(int i=0;i<rowlength;i++)
    {
            for(int j=0;j<collength;j++)
            {
                if(row[i]==1011 || col[j]==1011)
                {
                    mat[i][j]=0;
                }
            }
    }
    //printing matrix
    System.out.print("After completing task \n");
    printdata(mat);
}
public static void  printdata(int [][]data)
{
    for(int i=0;i<data.length;i++)
    {
        for(int j=0;j<data[0].length;j++)
        {
            System.out.print(data[i][j]);
        }
        System.out.println();
    }
}
}//class



 output:

------------------------------------------------
Before completing task
124
037
598
After completing task
024
000
098
 

 

Finding Common Elements Of Two Arrays using java

Hi  Guys,

for example array1=[1,2,3,4,5,6] ,array2=[4,5,6] then  your program need to give output as [4,5,6].

Solution:

Here am giving two solutions one by using an iteration method ,other one is using collections.

solution1:
----------------------------------

package logics;

public class comonBetweenTwoArrays {
    public static void main(String []a)
    {
        int first[]=new int[]{1,2,3,4,5,6,7};
        int second[]=new int[]{4,5,6,7,8,9,0};
        for(int i=0;i<first.length;i++)
        {
            for(int j=0;j<second.length;j++){
                if(first[i]==second[j])
                {
                    System.out.print(first[i]);
                }
            }
        }
    }

}
output:

----------------------
4567



solution2:
--------------------------------------

package logics;
import java.util.*;
public class commonnInArraysUsingHastSet {
    public static void main(String []a)
    {
        Set<Integer > s=new HashSet<Integer>();
        Set<Integer> common=new HashSet<Integer>();
       
        int first[]=new int[]{1,2,3,4,5,6,7,8,9,10};
        int second[]=new int[]{0,4,5,6,7,8,9};
        for(int index:first)
        {
            s.add(index);
        }
        for(int c:second)
        {
            if(s.contains(c))
            {
                common.add(c);
            }
                           
        }
        //printing common values
        Iterator<Integer> i=common.iterator();
        while(i.hasNext())
        {
            System.out.print(i.next());
        }
       
    }
}

output:
-------------------
456789

finding First Two maximum numbers in an array

This is very simple program.

let arr[]={1,2,333,44}; out put will be 333,44 where 333 is first max number and 44 is second max number.

logic:just sort the array and return last two elements.[you can sort array by using any sort method ].Here am telling you a one line code for sorting.

---> java has a class called Arrays .you can use Arrays.sort(array) to sort elements in user defined array.

program:


package logics;
import java.util.*;

public class twoMax {
public static void main(String []a )
{
   
    int arr[]=new int[]{1,22,33,222,0,66};
    Arrays.sort(arr);
    int firstMax=arr[arr.length-1];
    int secondMax=arr[arr.length-2];
    System.out.print("first max is"+firstMax+"\n second max is"+secondMax);
   
}
}
 

output:
---------------------------
first max is222
 second max is66


 
 

Java Program To Find Repeating characters in String

For example if a string like"shashi kumar" ,we need to find repeating characters i'e 
s repeated 2 times,a repeated 2 times,h repeated 2 times.

Solution:

1.Basically you can do thing using bruteforce approach  but it takes probably O(n^2) time .
2.For an efficiency you can do this in O(n) if you use collection frame Work.
3.Here am using HashMap() class of collection frame work ,which was defined in java.util package.
 4.The logic here is , first converting string to a character array ,then inserting it into hashmap(key,value) pair.
5.The insertion process in such a way that if a value is already present in map ,am increasing th count by using get(character)+adding1.

program:

package logics;
import java.util.*;

public class repeatingCharactorsInString {

    public static void  main(String []args)
    {
        String data="shashi kumar";
        char ch[]=data.toCharArray();
        Map<Character, Integer> m=new HashMap<Character, Integer>();
        for(char c:ch)
        {
            if(m.containsKey(c))//checking already have been there in a string
            {
                m.put(c, m.get(c)+1);
            }
            else
            {
                m.put(c, 1);
            }
        }
        //now printing repeated values.
        Iterator<Character> i=m.keySet().iterator();
        while(i.hasNext())
        {
            Object key=i.next();
            Integer val=m.get(key);
            if(val>1)
            {
            System.out.println(key+" repeated ----->"+val);
            }
        }
       
    }
}

output:
-----------------------------
s repeated ----->2
a repeated ----->2
h repeated ----->2


 

Java Program To converting a decimal to binary and back to decimal

package logics;

public class decimalToBinary {
    public static void main(String []a)
    {
       
        convert(3);
    }

public static void convert(int dec)
{

    int barray[]=new int[32];
    int index=0;
    while(dec>0)
    {
        barray[index++]=dec%2;
        dec=dec/2;
    }
    System.out.println("binary equivalant is");
    for(int i=barray.length-1;i>=0;i--)
    {
        System.out.print(barray[i]);
    }
    /* converting again into decimal*/
    System.out.println("\nDecimal equivalant is");

    int sum=0;
    int pow=0;
    for(int i=0;i<barray.length-1;i++)
    {
       
        sum=sum+(barray[i]*(int)Math.pow(2.0,pow ));

        pow=pow+1;
    }
    System.out.print(sum);
   
}
}//class


output:
--------------------------
binary equivalant is
00000000000000000000000000000011
Decimal equivalant is
3

Java Program to find Biggest Of Three Numbers Using Ternary Operator(?:)

package logics;

public class biggestTernery {
     public static void main(String []args)
     {
         int res=biggest(10,1300,600);
         System.out.print(res);
     }
public static int biggest(int a,int b,int c)
{
    return ((a>b)&&(b>c)? a :(b>c)?b:c);
}
}//class


output:
--------------------
1300

Java Program to find a duplicate number in an array.

package logics;

public class findDuplicate {
public static void main(String []args)
{
    int arr[]=new int[]{1,2,3,4,5,6,7,8,1,8};
    duplicate(arr);
}

public static void duplicate(int a[])
{
    for(int i=0;i<a.length;i++)
    {
        for(int j=i+1;j<a.length;j++)
        {
            if( (i!=j) &&  a[i]==a[j])
                System.out.printf("duplicate is %d \n",a[i]);
        }
    }
}
}//clas
s

output:
-------------------
duplicate is 1
duplicate is 8