Wednesday, April 30, 2014

Reverse a string without reversing the words and trim extra space

Input: "   MY NAME IS      ABHINAV   "
Output: "ABHINAV IS NAME MY"

public class ReverseString {
    static String str = "   MY NAME IS      ABHINAV   ";
    static char s[]  = str.toCharArray();

   static void reverse( int startIndex, int endIndex){
 
     for(int i=startIndex;i<(endIndex/2);i++){
       char c = s[i];
       s[i] = s[endIndex-i-1];
       s[endIndex-i-1] = c;
     }
 }

 static int leadingSpaceIndex(){
    int i = 0;
    while (s[i++] == ' ');
    return (i-1);
 }

static int trailingSpaceIndex(){
  int i = s.length;
  while (s[--i] == ' ');
  return i;
}

static int trim(int leadingSpace,int  trailingSpace){
  int place = leadingSpace;
  for (int i=leadingSpace;i<(trailingSpace+1);i++){
   if (s[i] != ' '){
     s[i-place] = s[i];
     s[i] = ' ';
   }else{
    while (s[i+1] == ' '){
      i = i+1;
      place++;
    }
   }
  }
  return 0;
 }
 public static void main(String args[]){
 
  
  int leadingIndex = leadingSpaceIndex();
  int trailingIndex = trailingSpaceIndex();
 
  reverse(0, s.length);
 
 
  int i = 0, index =0;
 
  while ( i < s.length){
   if (s[i] == ' ' || s[i] == '\0'){
    reverse( index, (index+i));
    index = i+1;
   }
   i++;
  
  }
//  int leadingIndex = leadingSpaceIndex();
  System.out.println("pre final string "+ new String(s));
  trim(leadingIndex, trailingIndex);
  System.out.println("final string "+ new String(s));
  
 }
}

Reverse a linked list from a given location

Suppose you have following list
1->2->3->4->5

if add you are asked to reverse the list from 3 node, then output sequence would be
1->2->5->4->3


 if add you are asked to reverse the list from 2 node, then output sequence would be
1->5->4->3->2

Code


class linkedList{
    private linkedList next;
 private int val;

 public linkedList(int x){
  val = x;
 }

 public void addToList(linkedList n){
  linkedList templinkedList = this;
  while (templinkedList.next != null){
   templinkedList = templinkedList.next;
  }
  templinkedList.next = n;
 }

 public void print(){
  linkedList templinkedList = this;
  while (templinkedList != null){
   System.out.println(templinkedList.val);
   templinkedList = templinkedList.next;
  
  }
 }
 public linkedList reverseA(int x) {
  x =x-1;
  boolean firstNode = true;
  linkedList init = this;
  linkedList root = this;
  linkedList current = root;
  linkedList forward;
  linkedList chainList = null;
  int i = 0;
  while ( current.next!= null){
   if ( i == x){
    i =0;
    if (firstNode == true){
     init = root;
     firstNode = false;
    }
    chainList = current;
    root = current.next;
    current = root;
   
   
   }
  
   i++;
   forward = current.next;
  
   current.next = forward.next;
  
   if (firstNode){
    forward.next = root;
    root = forward;
   }
   else{
    forward.next = chainList.next;
    chainList.next = forward;
   }
  
  }
  if ( x== -1)
   return root;
  return init;
 }
 public void reverseFromMid(linkedList root){
 // linkedList init = root.next;
  linkedList current = root.next;
  linkedList forward = current.next;
 
  while (forward.next != null){
   current.next = forward.next;
   forward.next = root.next;
   root.next = forward;
   forward = current.next;
  }
 
  int tempVal = forward.val;
  forward.val = root.val;
  root.val = tempVal;
 }
}
public class RevListInParts {
 public static void main(String[] args) {
  linkedList n = new linkedList(1);
  linkedList n2 = new linkedList(2);
  linkedList n3 = new linkedList(3);
  linkedList n4 = new linkedList(4);
  linkedList n5 = new linkedList(5);
  linkedList n6 = new linkedList(6);
  linkedList n7 = new linkedList(7);
  linkedList n8 = new linkedList(8);
  n.addToList(n2);
  n.addToList(n3);
  n.addToList(n4);
  n.addToList(n5);
  n.addToList(n6);
  n.addToList(n7);
  n.addToList(n8);
  n.print();
 // n = n.reverse(3);
  n.reverseFromMid(n2);
  System.out.println("Post reverse");
  n.print();
 
 }
}
 

Code: What are the various combinations of quarters, dimes, fives and cents to make x cents

Suppose one has 35 cents then what are the various combinations of quarters, dimes, cents and fives which can make  this amount.

For ex:
1 quarter, 1 dimes
1 quarter, 2 fives
1 quarter, 1 fives, 5 cents
.......

Following is the program which generates these combinations:


import java.util.HashSet;
import java.util.Set;

public class Cents {
   public Set<String> s = new HashSet<String>();
   public void getChange(int nos, int qua, int dimes, int fives, int cents){
         if ( nos == 0){
            s.add("" + qua + "," + dimes + "," + fives + "," + cents);
           return;
         }
         if (nos < 0){
               return;
         }

         if ( (nos-25) >= 0)
               getChange((nos-25), (qua+1), dimes, fives, cents);

          if ( (nos-10) >= 0)
              getChange((nos-10), qua, (dimes+1), fives, cents);

         if ( (nos-5) >= 0)
               getChange((nos-5), qua, dimes, (fives+ 1), cents);

         if ( (nos-1) > 0)
              getChange((nos-1), qua, dimes, fives, (cents+ 1));

   }


 public static void main(String[] args) {
   Cents c = new Cents();
  c.getChange(35, 0, 0 , 0 , 0);

  for (String s : c.s){
   System.out.println(s);
  }

 }
}

Java Program to generate permutations of a string

If one wants to generate various possible permutations ( order  matters) from a string.
Ex:
For input {'a','b'},  output would be 'a','b','ab','ba'
For input {'a','b','c'} , output would be 'a','b','c','ac','ab','bc','ac', 'abc'


import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;

public class AllPerm {
        static String originalString = "abc";
        static Vector<String> stringSet = new Vector<String>();
        static void addCharAt(int index){
             int vecSize = stringSet.size();
              for (int i=0;i<vecSize;i++){
                 StringBuffer element = new StringBuffer(stringSet.get(i));
                 for (int j=0;j<(element.length()+1);j++){
                       element.insert(j, originalString.charAt(index));
                       stringSet.add(element.toString());
                        element.deleteCharAt(j);
               }
             }
       }

      public static void main(String[] args) {
 
              stringSet.add("");
 
              for (int i=0;i<originalString.length();i++){
                 addCharAt(i);
              }
 
              for (int i=0;i<stringSet.size() ;i++){
                  System.out.println(i + " " +  stringSet.get(i));
              }
 }
    }

Java Program to generate combination

If one wants to generate various possible combinations ( order doesn't matter) from char array.
Ex:
For input {'a','b'},  output would be 'a','b','ab'
For input {'a','b','c'} , output would be 'a','b','c','ac','ab','bc','ac', 'abc'

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;

public class AllComb {
          static char arr[] = {'a','b','c','d'};
          public static void main(String args[]) {
                Vector<String> wordSet = new Vector<String>();
                wordSet.add("");
                for (int i=0;i<arr.length;i++){
                        int vectorSize = wordSet.size();
                        for (int index=0;index<vectorSize;index++){
                                String str = wordSet.get(index) + arr[i];
                                wordSet.add(str);
                        }
  
                   }
 
               int vectorSize = wordSet.size();
              for (int index=0;index<vectorSize;index++){
                   System.out.println( wordSet.get(index));
              }
        }
}