Showing posts with label Java coding. Show all posts
Showing posts with label Java coding. Show all posts

Java Coding Problems

 These are some Java coding problems for practice, these could be helpful for interview preparation as well.


package test;

 

import java.util.ArrayList;

import java.util.Arrays;

 

public class PracticeVariousCodingExamples {

 

       public static void main(String[] args) {

            // Coding problems to practice:


                    //methods

 //-------------------method 1----------------------------

             //removeDuplicateChars();

 //-------------------method 2----------------------------

             //countRepetitionOfChars();

 //-------------------method 3----------------------------

             //findUniqueChars();

 //-------------------method 4----------------------------

/*           Palindrome:

            3 ways to call a method:

            1. if static and return keyword is used in the method name:

System.out.println("is Palindrome ? true/false with static "+palindrome());//this proves that variable does not need to be static

            2. without using static in the method and without using return

             PracticeAll a = new PracticeAll();

             a.palindrome();

             System.out.println("is Palindrome ? true/false "+a.palindrome());

            3. PracticeAll.Palindrome();//Method can be called this way also with class name or just call the method name like in 2 when static keyword is used in the method declaration. This is also without using 'return' keyword.

The method has been written in such a way that it can be called in the way mentioned in point 2 or point 3 only. Return keyword has not been used in out example here.

 

*/

 //-------------------method 5----------------------------

             //reformatGivenText(); //"bbbaadddddu"--> //3a-2b-4d-1u

 //-------------------method 6----------------------------      

             //sumValueOfaString(); //find sum of the numerical values of each char from a given string

 //-------------------method 7----------------------------

             //sumTestfromArray();//find the array Elements from a given array whose sum equals a given number

 //-------------------method 8----------------------------

             //primeNum(); //prime number

 //-------------------method 9----------------------------

             //startingAndEndgingDigitSame(); //numbers having same starting and ending digits

 //-------------------method 10----------------------------

             //countUpperlower(); //Count upper case chars and lower case chars in a given string.


 //-------------------method 11----------------------------

             //Case statement in java

             System.out.println(caseTest(2));

             System.out.println(caseTest(3));

       

      }

 //-------------------method 1----------------------------

       public static void removeDuplicateChars() {//show unique chars only

             String str = "this is a beautiful world.";

             String[] strArray = new String[str.length()];

             for(int i=0;i<str.length();i++) {

                    strArray[i]= Character.toString(str.charAt(i));

             }

             System.out.println("Array1 = "+Arrays.toString(strArray));//[t, h, i, s,  , i, s,  , a,  , b, e, a, u, t, i, f, u, l,  , w, o, r, l, d, .]

             Arrays.sort(strArray);

             System.out.println("Array1 = "+Arrays.toString(strArray));//[ ,  ,  ,  , ., a, a, b, d, e, f, h, i, i, i, l, l, o, r, s, s, t, t, u, u, w]

            

             ArrayList<String> alist = new ArrayList<>();

             for(int i=1;i<str.length();i++) {

                    if(!(strArray[i-1].equals(strArray[i]))) {

                           alist.add(strArray[i]);

                    }

             }

             alist.add(strArray[strArray.length-1]);

             System.out.println("unique chars = "+alist);//[., a, b, d, e, f, h, i, l, o, r, s, t, u, w, w]

       }

      

//-------------------method 8----------------------------

       public static void primeNum() {

 

        // Find if the given number is a prime number or not. Return the smallest divisible number if not Prime Number OR return 1 if it is a Prime Number

        int givenNumber = 17;

        boolean isPrime = true;

        int returnNum = 1;

        for (int i = 2; i < givenNumber; i++) {

               if ((givenNumber % i) == 0) {

                      isPrime = false;

                      returnNum = i;

                      break;

               }

        }

   

        System.out.println("Is the number Prime ?"+isPrime + " The number returned is "+ returnNum);

  }

 

 //-------------------method 2----------------------------

    

       public static void countRepetitionOfChars() {

             String str = "helloworld.";

             String[] strArray = new String[str.length()];

             for(int i=0;i<str.length();i++) {

                    strArray[i]= Character.toString(str.charAt(i));

             }

             System.out.println("Array1 = "+Arrays.toString(strArray));//[h, e, l, l, o, w, o, r, l, d, .]

             Arrays.sort(strArray);

             System.out.println("Array1 = "+Arrays.toString(strArray));//[., d, e, h, l, l, l, o, o, r, w]

            

             ArrayList<String> alist = new ArrayList<>();//unique chars

             ArrayList<Integer> blist = new ArrayList<>();//index where the char changed

             ArrayList<Integer> clist = new ArrayList<>();//count of each char

             ArrayList<String> dlist = new ArrayList<>();//count of each char, number +char

             for(int i=1;i<str.length();i++) {

                    if(!(strArray[i-1].equals(strArray[i]))) {

                           alist.add(strArray[i-1]);

                    }

             }

             alist.add(strArray[strArray.length-1]);

             System.out.println("unique chars = "+alist);//[., d, e, h, l, o, r, w]

            

             for(int i=1;i<str.length();i++) {

                    if(!(strArray[i-1].equals(strArray[i]))) {

                           blist.add(i-1);

                    }

             }

             blist.add(str.length()-1);

             System.out.println("lower index where char changed = "+blist);//[0, 1, 2, 3, 6, 8, 9, 10]

            

             clist.add(blist.get(0)+1);//imp

             for(int i=1;i<blist.size();i++) {

                    clist.add(blist.get(i)-blist.get(i-1));

             }

             System.out.println("count of each char = "+clist);//[1, 1, 1, 1, 3, 2, 1, 1]

            

             for(int i=0;i<blist.size();i++) {

                    dlist.add(alist.get(i).concat(Integer.toString(clist.get(i))));

             }

             System.out.println("Final Char with number = "+dlist);//[.1, d1, e1, h1, l3, o2, r1, w1]

       }

      

 //-------------------method 3----------------------------

 

       public static void findUniqueChars() { //find chars which have no repetition.

             String str = "helloworld.";

             String[] strArray = new String[str.length()];

             for(int i=0;i<str.length();i++) {

                    strArray[i]= Character.toString(str.charAt(i));

             }

             System.out.println("Array1 = "+Arrays.toString(strArray));//[h, e, l, l, o, w, o, r, l, d, .]

             Arrays.sort(strArray);

             System.out.println("Array1 = "+Arrays.toString(strArray));//[., d, e, h, l, l, l, o, o, r, w]

            

             ArrayList<String> alist = new ArrayList<>();//unique chars

             ArrayList<Integer> blist = new ArrayList<>();//index where the char changed

             ArrayList<Integer> clist = new ArrayList<>();//count of each char

             ArrayList<String> dlist = new ArrayList<>();//unique Char

             for(int i=1;i<str.length();i++) {

                    if(!(strArray[i-1].equals(strArray[i]))) {

                           alist.add(strArray[i-1]);

                    }

             }

             alist.add(strArray[strArray.length-1]);

             System.out.println("unique chars = "+alist);//[., d, e, h, l, o, r, w]

            

             for(int i=1;i<str.length();i++) {

                    if(!(strArray[i-1].equals(strArray[i]))) {

                           blist.add(i-1);

                    }

             }

             blist.add(str.length()-1);

             System.out.println("lower index where char changed = "+blist);//[0, 1, 2, 3, 6, 8, 9, 10]

            

             clist.add(blist.get(0)+1);//imp

             for(int i=1;i<blist.size();i++) {

                    clist.add(blist.get(i)-blist.get(i-1));

             }

             System.out.println("count of each char = "+clist);//[1, 1, 1, 1, 3, 2, 1, 1]

            

             for(int i=0;i<blist.size();i++) {

                    if(clist.get(i)==1) {

                           dlist.add(alist.get(i));

                    }

             }

             System.out.println("unique chars = "+dlist);//[., d, e, h, r, w]

       }

    

 //-------------------method 4----------------------------

            

       public static void palindrome() {

             String str = "abcdcbaa";

            

             int lengthstr = str.length();

             int midLength = Math.abs(lengthstr/2);//////Math.abs

             ArrayList<String> alist = new ArrayList<>();

             ArrayList<String> blist = new ArrayList<>();

             ArrayList<String> clist = new ArrayList<>();

             for(int i=0;i<midLength;i++) {

                    alist.add(Character.toString(str.charAt(i)));

             }

             for(int j=midLength+1;j<lengthstr;j++) {/////// very imp

                    blist.add(Character.toString(str.charAt(j)));

             }

             for(int i=blist.size()-1;i>=0;i--) {

                    clist.add(blist.get(i));

             }

             System.out.println(alist);

             System.out.println(blist);

             System.out.println(clist);

             boolean isPalindrome = false;

             if(alist.equals(clist)) {//////imp

                    isPalindrome = true;

             }

             System.out.println(isPalindrome);

            

             /////////////////////////integer///////////////////////////////

             int num = 123454321;

             String strr = Integer.toString(num); /////this is main thing, you can not use charAt or num.length with int value

             int lengthnum = strr.length();

             int midLengthnum = Math.abs(lengthnum/2);//////Math.abs

             ArrayList<String> dlist = new ArrayList<>();

             ArrayList<String> elist = new ArrayList<>();

             ArrayList<String> flist = new ArrayList<>();

             for(int i=0;i<midLengthnum;i++) {

                    dlist.add(Character.toString(strr.charAt(i)));

             }

             for(int j=midLengthnum+1;j<lengthnum;j++) {/////// very imp

                    elist.add(Character.toString(strr.charAt(j)));

             }

             for(int i=elist.size()-1;i>=0;i--) {

                    flist.add(elist.get(i));

             }

             System.out.println(dlist);

             System.out.println(elist);

             System.out.println(flist);

             boolean isPalindromeNum = false;

             if(dlist.equals(flist)) {

                    isPalindromeNum = true;

             }

             System.out.println(isPalindromeNum);

       }

      

 //-------------------method 5----------------------------

       public static void reformatGivenText() {

             String str = "bbbaadddddu"; //output should be "3a-2b-4d-1u"

             String[] strArray = new String[str.length()];

             int lgth = str.length();

             for(int i=0;i<lgth;i++) {

                    strArray[i]= Character.toString(str.charAt(i));

             }

             System.out.println("Array = "+Arrays.toString(strArray));//[b, b, b, a, a, d, d, d, d, d, u]

            

             ArrayList<String> alist = new ArrayList<>();//unique chars

             ArrayList<Integer> blist = new ArrayList<>();//index of unique chars

             ArrayList<Integer> clist = new ArrayList<>();//count of each unique chars

             ArrayList<String> dlist = new ArrayList<>();//combined number and char

             for(int i=1;i<lgth;i++) {

                    if(!(strArray[i]).equals(strArray[i-1])) {

                           alist.add(strArray[i-1]);

                           blist.add(i-1);

                    }

                   

             }

             alist.add(strArray[lgth-1]);

             blist.add(lgth-1);

             System.out.println("alist = "+alist);//[b, a, d, u]

             System.out.println("blist = "+blist);//[2, 4, 9, 10]

            

             clist.add(blist.get(0)+1);

             for(int i=1;i<blist.size();i++) {

                    clist.add(blist.get(i)-blist.get(i-1));

             }

             System.out.println("clist = "+clist);//[2, 4, 9, 10]

             for(int i=0;i<blist.size();i++) {

                    dlist.add( Integer.toString(clist.get(i)).concat(alist.get(i)));

             }

             System.out.println("dlist = "+dlist);//[3b, 2a, 5d, 1u]

            

             String result = dlist.get(0);

             for(int i=1;i<blist.size();i++) {

                    //result = result+"-"+dlist.get(i); //OR

                    result = result.concat("-").concat(dlist.get(i));

             }

             System.out.println("result = "+result);//3b-2a-5d-1u

       }

           

//-------------------method 6---------------------------- 

       public static void sumValueOfaString() { //find the summation of equivalent number of each char present in a string.

             String str ="Hello WorldaA";

             int asciiValueofa = 'a';

             int asciiValueofA = 'A';

             int asciiValueofz = 'z';

             int asciiValueofZ = 'Z';

             System.out.println("samll letters a-z:"+asciiValueofa+"-"+asciiValueofz);//97-122

             System.out.println("Cap letters A-Z:"+asciiValueofA+"-"+asciiValueofZ);//65-90

            

             int sumValue = 0;

             for(int i=0;i<str.length();i++) {

                    int x = str.charAt(i);

                    System.out.println("x= "+x);

                    sumValue=sumValue+x;

             }

             System.out.println(sumValue);

       }

      

       public static void removeDuplicateChars1() {

             String str = "this is a beautiful world.";

             String[] strArray = new String[str.length()];

             for(int i=0;i<str.length();i++) {

                    strArray[i]= Character.toString(str.charAt(i));

             }

             System.out.println("Array1 = "+Arrays.toString(strArray));//[t, h, i, s,  , i, s,  , a,  , b, e, a, u, t, i, f, u, l,  , w, o, r, l, d, .]

             Arrays.sort(strArray);

             System.out.println("Array1 = "+Arrays.toString(strArray));//[ ,  ,  ,  , ., a, a, b, d, e, f, h, i, i, i, l, l, o, r, s, s, t, t, u, u, w]

            

             ArrayList<String> alist = new ArrayList<>();

             for(int i=1;i<str.length();i++) {

                    if(!(strArray[i-1].equals(strArray[i]))) {

                           alist.add(strArray[i]);

                    }

             }

             alist.add(strArray[strArray.length-1]);

             System.out.println("unique chars = "+alist);//[., a, b, d, e, f, h, i, l, o, r, s, t, u, w, w]

       }

      

       public static void removeAllArrayList() { //subtract/remove array elements using another array using removeAll keyword.

             ArrayList<Integer> alist = new ArrayList<>();

             ArrayList<Integer> blist = new ArrayList<>();

             ArrayList<Integer> clist = new ArrayList<>();

             for(int i=0;i<5;i++) {

                    alist.add(i);

                   

             }

             System.out.println(alist);

             blist = alist;

             System.out.println(blist);

             blist.remove(4) ;

             System.out.println(blist);

             alist.removeAll(blist);

             System.out.println(alist);

       }

      

//-------------------method 7----------------------------

       public static void sumTestfromArray() { //Find which of the array digits make a sum of 10.

             int[] intArray = {1,3,4,5,7,8,9,2};

             for(int i=0;i<intArray.length; i++) {

                    for(int j=0;j<intArray.length; j++) {

                           if((!(i==j)) && ((intArray[i]+intArray[j])==10)) {

                                 //if((intArray[i]+intArray[j])==10) {

 

                                        System.out.println(intArray[i]+"-------------"+intArray[j]);

                                        System.out.println("-------------");

                                 //}

                           }

                    }

                   

             }

}


//-------------------method 9----------------------------

    public static void startingAndEndgingDigitSame() { //check if the given number has the same first and last digit.

             int num = 12221;

             String str = Integer.toString(num);

            

             int len = str.length();

              if((Character.toString(str.charAt(0))).equals(Character.toString(str.charAt(len-1)))) {

                    System.out.println("Same");

             } else {

                    System.out.println("NOT Same");

             }

            

       }


 //-------------------method 10----------------------------

       public static void countUpperlower() { //count the upper case and lower case characters in a string.

            

             String str = "HelloHello";

             System.out.println(str.toUpperCase());

             System.out.println(str.toLowerCase());

             int upCount = 0;

             int lowCount = 0;

             for(int i=0; i<str.length();i++) {

                    String UpperStr = Character.toString(str.charAt(i)).toUpperCase();

                    if(((Character.toString(str.charAt(i))).equals(UpperStr))){

                           upCount ++;

                    } else {

                           lowCount++;

                    }

             }

             System.out.println(upCount);

             System.out.println(lowCount);

       }


 //-------------------method 11----------------------------

       public static String caseTest(int month) { //practice case statement in java

             String convertedMonth ;

             switch(month){

             case 1 : convertedMonth = "1st";

             break ;

             case 2 : convertedMonth = "2nd";

             break ;

             default : convertedMonth = "enter valid month";

             break ;

             }

             return convertedMonth ;

       }

}