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

Sunday, 19 June 2016

Find Duplicate Characters In String using Java

package com.zia.test;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class findDuplicateCharacter {

    /**
     * @param args
     */
    public static void findByusingMap(String str) {
        // HashMap with character and number of times they appear in given
        // String argument
        Map<Character, Integer> charMap = new HashMap<Character, Integer>();
        char[] charArr = str.toCharArray();

        for (char value : charArr) {

            if (Character.isLetter(value)) {
                if (charMap.containsKey(value)) {
                    charMap.put(value, charMap.get(value) + 1);

                } else {
                    charMap.put(value, 1);
                }
            }
        }

        Set<Character> charString = charMap.keySet();

        System.out.println("Duplicate Characters In =" + str);
        // set iteration
        for (Character ch : charString) {
            if (charMap.get(ch) > 1) {
                // If any char occur more than 1, printing it's count

                System.out.println(ch + " : " + charMap.get(ch));
            }
        }

    }

    public static void main(String[] args) {

        findDuplicateCharacter.findByusingMap("Hello How are You Doing?");
        findDuplicateCharacter.findByusingMap("Hope you all are doing good");
        findDuplicateCharacter.findByusingMap("Thank you very much for reading this");

    }

}


OutPut:-

Duplicate Characters In =Hello How are You Doing?
e : 2
o : 4
l : 2
H : 2
Duplicate Characters In =Hope you all are doing good
g : 2
d : 2
e : 2
a : 2
o : 5
l : 2
Duplicate Characters In =Thank you very much for reading this
e : 2
a : 2
n : 2
o : 2
h : 3
i : 2
u : 2
r : 3
y : 2




Its very simple program no need to explain,get the character array from String, iterate through that and put it in a Map with character and their count.Then get a Set containing all keys of map and iterate through Set and print characters which have appeared more than once.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Saturday, 18 June 2016

Swap two String variables in java without using a third variable.

First way to do it as below,

String s1 = "First";
String s2 = "Second";
    s1=s1+" "+s2;
s2=s1.split(" ")[0];
s1=s1.split(" ")[1];
System.out.println(s1 + " " + s2);


Another way to do it as,

String a="First";
String b="Second";

    a= a+b;
    b = a.substring(0,(a.length()-b.length())); 
    a = a.substring(b.length());

    System.out.println("a = "+a);
    System.out.println("b = "+b); 

one more way to do this as below,

String returnFirstString(String x, String y) {
    return x;
}

String a = "First"
String b = "Second"
a = returnFirstString(b, b = a); 
System.out.print(a+" "+b);


Another one more way we can do its as,

String s1 = "First";
String s2 = "Second";
AtomicReference<String> String1 = new AtomicReference<String>(s1);
AtomicReference<String> String2 = new AtomicReference<String>(s2);
String1.set(String2.getAndSet(String1.get()));
System.out.println(String1 + " " + String2);

Java Strings are implemented with references, so you need to swap their references.

Finding the first 100 prime numbers using array.

class GeneratePrime{
 public static boolean isPrime(int x)
    {
        for (int i = 2; i <= Math.sqrt(x); i++) {
            if (x % i == 0) {
                return false;
            }
        }

        return true;
    }

public static void main(String args[]){
    int currentNumber = 2;
    int primesFound = 0;

    while (primesFound < 100) {
        if (isPrime(currentNumber)) {
            primesFound++;

            System.out.print (currentNumber + " ");
            if (primesFound % 10 == 0) {
                System.out.println();
            }
        }

        currentNumber++;
    }
}}


Thursday, 16 June 2016

How do you test if a word is a palindrome?

A palindrome is a word, or phrase, that when the letters are reversed, the spelling is the same. Some
examples include, “eve,” “level,”.

public static boolean isPalindrome(final String s) {
final String toCheck = s.toLowerCase();
int left = 0;
int right = toCheck.length() - 1;
while (left <= right) {
while(left < toCheck.length() &&
!Character.isLetter(toCheck.charAt(left))) {
left++;
}
while(right > 0 && !Character.isLetter(toCheck.charAt(right))) {
right--;
}
if (left > toCheck.length() || right < 0) {
return false;
}
if (toCheck.charAt(left) != toCheck.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}

Or you may check it also by reversing the string and check the equality,

public static boolean isPalindrome(final String s) {
return s.equals(reverse(s));
}

public static String reverse(final String s) {
final StringBuilder builder = new StringBuilder(s);
for (int i = 0; i < builder.length() / 2; i++) {
final char tmp = builder.charAt(i);
final int otherEnd = builder.length() - i - 1;
builder.setCharAt(i, builder.charAt(otherEnd));
builder.setCharAt(otherEnd, tmp);
}
return builder.toString();
}

Write a method to reverse a String in java.

In Java, a String is immutable, so once it has been constructed it is not possible to change the contents. So when you are asked to reverse a String, you are actually being asked to produce a new String object, with the contents reversed,


public static String reverse(final String s)

Approach to reversing a String is to iterate over the contents in reverse

public static String reverse(final String s) {
final StringBuilder sb = new StringBuilder(s.length());
for (int i = s.length() - 1; i >= 0; i--) {
sb.append(s.charAt(i));
}
return sb.toString();
}

Or we can do by using Built-in Re verse Methods

Note-This approach, is fine when we do it with small size of data,  It hold the original String and the StringBuilder in memory and occupy large memory. This could be problematic if you were reversing some data of several gigabytes in size.



public static String stringReverse(final String s) {
final StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length() / 2; i++) {
final char tmp = sb.charAt(i);
final int otherEnd = sb.length() - i - 1;
sb.setCharAt(i, sb.charAt(otherEnd));
sb.setCharAt(otherEnd, tmp);
}
return sb.toString();
}

Write a method that returns the nth value of the Fibonacci sequence.

int num = 0;
 int num2 = 1; 
 int fibonacci
for (int i= 0; i< n; i++)
{
    fibonacci = num + num2;
    num = num2;
    num2 = fibonacci;
}
System.out.print(num);


to find the nth, you have to iterate the step n times and only print it when you've finished.


Write a method that returns a Fibonacci sequence from 1 to n.

The Fibonacci sequence is a list of numbers, where the next value in the sequence is the sum of the
last two. The sequence defines that the first number is zero, and the next is one.

class FibonacciwithoutRecursion{  
public static void main(String args[])  
{    
   int n1=0,n2=1,n3,i,count=10;    
   System.out.print(n1+" "+n2);//printing 0 and 1    
    
 for(i=2;i<count;++i) {    
  n3=n1+n2;    
  System.out.print(" "+n3);    
  n1=n2;    
  n2=n3;    
 }    
  
}} 


Fibonacci series with using recursive function,

class FibonacciRecursion{  
 static int n1=0,n2=1,n3=0;    
 static void printFib(int count){    
    if(count>0){    
         n3 = n1 + n2;    
         n1 = n2;    
         n2 = n3;    
         System.out.print(" "+n3);   
         printFib(count-1);    
     }    
 }    
 public static void main(String args[]){    
  int count=10;    
  System.out.print(n1+" "+n2);//printing 0 and 1    
  printFib(count-2);//n-2 because 2 numbers are already printed   
 }  
}  

Write an algorithm that prints all numbers between 1 and n, replacing multiples of 3 with the String Fizz, multiples of 5 with Buzz, and multiples of 15 with FizzBuzz.

Write an algorithm that prints all numbers between 1 and n, replacing multiples
of 3 with the String Fizz, multiples of 5 with Buzz, and multiples of 15 with
FizzBuzz.

This question is  popular, and  one of the most used on Interview. Below is the code block of the problem,
public static List<String> fizzBuzz(final int n) {
final List<String> toReturn = new ArrayList<>(n);
for (int i = 1; i <= n; i++) {
if(i % 15 == 0) {
toReturn.add("FizzBuzz");
} else if (i % 3 == 0) {
toReturn.add("Fizz");
} else if (i % 5 == 0) {
toReturn.add("Buzz");
} else {
toReturn.add(Integer.toString(i));
}
}
return toReturn;
}

Monday, 12 August 2013

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

public class FizzBuzzProgramme {
    public static void main(String[] args) {
        boolean flag;
        for (int i = 1; i<=100;i++)
        {
            flag = false;
            if (i%3==0)
            {   
                System.out.print("Fizz");
                flag = true;
            }
            if (i%5==0)
            {
                System.out.print("Buzz");
                flag = true;
            }
            if (flag == false)
            {
                System.out.print(i);
            }
            System.out.println();
        }
    }
 
}

Wednesday, 7 August 2013

Some Solution from---- http://www.betterprogrammer.com/


public class Program {

public static int getClosestToZero(int[] a) {
    /*
     Please implement this method to
     return the number in the array that is closest to zero.
     If there are two equally close to zero elements like 2 and -2
     - consider the positive element to be "closer" to zero.
    */
    int num = array[0];

  int absNum = Math.abs(num);

  for(int i = 1; i < array.length; ++i) {
    int newAbs = Math.abs(array[i]);

    if(newAbs < absNum) {
      absNum = newAbs;
      num = array[i];
    }
  }
  return num;
  }

public static int sumOfTwoLargestElements(int[] a) { /* Please implement this method to return the sum of the two largest numbers in a given array. */ int sum = Integer.MIN_VALUE; int maxsum = Integer.MIN_VALUE; for (int i = 1; i < a.length; i++) { if (a[i] < a[i - 1]) { sum = a[i] + a[i - 1]; if (sum > maxsum) { maxsum = sum; } } else { sum = a[i]; if (sum > maxsum) { maxsum = sum; } } } if (a.length == 0) { return Integer.MIN_VALUE; } else { return maxsum; } } public static List<Integer> getPrimeNumbers(int from, int to) { /* Please implement this method to return a list of all prime numbers in the given range (inclusively). A prime number is a natural number that has exactly two distinct natural number divisors, which are 1 and the prime number itself. The first prime numbers are: 2, 3, 5, 7, 11, 13 */ List<Integer> primeNumbers = new ArrayList<Integer>(); for(int i=from; i<=to; i++) { if(isPrime(i)) primeNumbers.add(i); } return primeNumbers; } static boolean isPrime(int n) { if(n==1) return false; for(int i=2;i<n;i++) { if(n%i==0) return false; } return true; } public static Object[] reverseArray(Object[] a) { /* Please implement this method to return a new array where the order of elements has been reversed from the original array. */ Object[] b = null; int o = 0; for (int i = a.length; i > 0; i--) { b[0] = a[i]; } return b; } public static int countWaysToProduceGivenAmountOfMoney(int cents) { int[] dp = new int[cents+1]; dp[0] = 1; for (int x : new int[] {1, 5, 10, 25, 50}) for (int i = 0; i+x <= cents; ++i) dp[i+x] += dp[i]; return dp[cents]; } public static int[] retainPositiveNumbers(int[] a) { /* Please implement this method to return a new array with only positive numbers from the given array. The elements in the resulting array shall be sorted in the ascending order. */ ArrayList<Integer> list = new ArrayList<Integer>(); for(int i : a){ if(i >= 0) list.add(i); } Integer[] posIntegers = list.toArray(new Integer[0]); int[] posInts = new int[posIntegers.length]; for (int i = 0; i < posInts.length; i++) { posInts[i] = posIntegers[i]; } Arrays.sort(posInts); return posInts; } public static class WriteOnceMap<K, V> extends HashMap<K, V> { public V put(K key, V value) { /* WriteOnceMap is a map that does not allow changing value for a particular key. It means that put() method should throw IllegalArgumentException if the key is already assosiated with some value in the map. Please implement this method to conform to the above description of WriteOnceMap. */ if (containsKey(key)) throw new IllegalArgumentException(key + " already in map"); return super.put(key, value); } public void putAll(Map<? extends K, ? extends V> m) { /* Pleaase implement this method to conform to the description of WriteOnceMap above. It should either (1) copy all of the mappings from the specified map to this map or (2) throw IllegalArgumentException and leave this map intact if the parameter already contains some keys from this map. */ for (K key : m.keySet()) if (containsKey(key)) throw new IllegalArgumentException(key + " already in map"); super.putAll(m); } } public static int countWords(String s) { /* Please implement this method to return the word count in a given String. Assume that the parameter String can only contain spaces and alphanumeric characters. */ String[] b = s.split(" "); return b.length; } public static boolean isPalindrome(String s) { /* Definition: A palindrome is a string that reads the same forward and backward. For example, "abcba" is a palindrome, "abab" is not. Please implement this method to return true if the parameter is a palindrome and false otherwise. */ int left = 0; int right = s.length() -1; while (left < right) { if (s.charAt(left) != s.charAt(right)) { return false; } left++; right--; } return true; }
public static double getAverage(Node root) { /* Please implement this method to return the average of all node values (Node.getValue()) in the tree. */ int total = 0; for (int i = 0; i < root.getChildren().size(); i++) { total += root.getChildren().get(i).getValue(); } return (total / root.getChildren().size()); } public static int getSumOfNumbers(String s) { /* Please implement this method to return the sum of all integers found in the parameter String. You can assume that integers are separated from other parts with one or more spaces (' ' symbol). For example, s="12 some text 3 7", result: 22 (12+3+7=22) */ int sum=0; String modifiedString = s.replaceAll("\\D+"," "); System.out.println(modifiedString); StringTokenizer st = new StringTokenizer(modifiedString, " "); while(st.hasMoreTokens()) { String numeric = st.nextToken(); sum+= Integer.parseInt(numeric); } return sum; } public static String capitalizeFirstLetters(String s) { StringBuilder res = new StringBuilder(); char prev = ' '; for (int i = 0; i < s.length(); ++i) { char ch = s.charAt(i); if (Character.isLetter(ch) && prev == ' ') res.append(Character.toUpperCase(ch)); else res.append(ch); prev = ch; } return res.toString(); } public static List<integer> getPerfectNumbers(int from, int to) { List<integer> res = new ArrayList<integer>(); for (int num = from; num <= to; ++num) { int sum = 0; for (int i = 1; i <= num/2; ++i) if (num%i == 0) sum += i; if (sum == num) res.add(num); } return res; } public static Change getCorrectChange(int cents) { int dol = cents/100; cents %= 100; int qua = cents/25; cents %= 25; int dim = cents/10; cents %= 10; int nic = cents/5; cents %= 5; return new Change(dol, qua, dim, nic, cents); } public static List<node> traverseTreeInDepth(Node root) { List<node> list = new ArrayList<node>(); depth(root, list); return list; } static void depth(Node root, List<node> list) { list.add(root); for (Node child : root.getChildren()) depth(child, list); } public static String getBinaryRepresentation(int n) { String res = ""; while (n > 0) { res = (char)('0'+n%2)+res; n /= 2; } if (res.length() == 0) res = "0"; return res; } public static List<string> transferFromAtoC(int n) { List<string> res = new ArrayList<string>(); hanoi(n, "A", "C", "B", res); return res; } static void hanoi(int n, String from, String to, String using, List<string> list) { if (n == 0) return; hanoi(n-1, from, using, to, list); list.add(from+to); hanoi(n-1, using, to, from, list); } public Node ReverseList(Node cur, Node prev) { if (cur == null) // if list is null return cur; Node n = cur.NextNode; cur.NextNode = prev; return (n == null) ? cur : ReverseList(n, cur); } }

Monday, 5 August 2013

calling one class main method from another class main method

Let's use these two classes to demonstrate:

public class MainIsCallingMain {

public static void main(String args[])
{
System.out.println("==INSIDE THE FIRST MAIN METHOD==");
String[] test = {"first", "second", "third"};

SecondMain.main(test);
}
}

public class SecondMain {

public  static void main(String args[])
{
System.out.println("==INSIDE THE SECOND TMAIN METHOD==");

for(String a: args)
{
System.out.println("Second Class===" + a);
}
}

}



MainIsCallingMain won't compile the way it is.Need to configure SecondMain  on the classpath or compile both Class at same time.

@In eclipse please add the SecondMain  in MainIsCallingMain's class path.

Thursday, 1 August 2013

Find the Duplicate element from ArrayList in Java

How To Find the Duplicate element in ArrayList(Simple Approach).

Here i am taking an simple approach to do this.

Car.java

public class Car {

public int model;
public String name;

public Car()
{

}

public int getModel() {
return model;
}
public void setModel(int model) {
this.model = model;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public boolean equals(Object obj) {  
Car carObj=null;  
if(obj instanceof Car){  
carObj=(Car)obj;  
}  
if(carObj!=null && (this.model==carObj.model) && (this.name.equals(carObj.name))){  
return true;  
}  
return false;  
}  

public String toString() {
       return ("Car Model: " + model + "and" +
       "Car Name: " + name);
   }

}



CarImpl.java
public class CarImpl{


public static void main(String[] args) {

System.out.println("Get the Duplicate Element in a list");
Car c=new Car();
c.setModel(1);
c.setName("Honda");

Car c1=new Car();
c.setModel(11);
c.setName("Hyundai");

List<Car> listcar=new ArrayList<Car>();
listcar.add(c);
listcar.add(c);
listcar.add(c);
listcar.add(c1);

for(int i=0;i<listcar.size();i++)
{
for(int j=0;j<i;j++)
{
if(listcar.get(j).equals(listcar.get(i)))
{
System.out.println("Dupliacte Object are" + listcar.get(i).toString());
}
}

}

/*Map<Car, Integer> counts = new HashMap<Car, Integer>();

for (Car str : listcar) {
   if (counts.containsKey(str)) {
       counts.put(str, counts.get(str) + 1);
   } else {
       counts.put(str, 1);
   }
}

for (Map.Entry<Car, Integer> entry : counts.entrySet()) {
   System.out.println(entry.getKey() + " = " + entry.getValue());
}

*/

}
}

This is very simple approach to find out the duplicate element in list.

# Commented code also worked.

@I hope you will like my Blog and post.Any suggestion must be appreciated.

Find Duplicate Characters In String using Java

package com.zia.test; import java.util.HashMap; import java.util.Map; import java.util.Set; public class findDuplicateCharacter { /**...