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); } }

1 comment:

  1. Nice Job and appreciate the good coding details

    ReplyDelete

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 { /**...