Friday, August 31, 2012

Insertion Sort Algorithmn in Java ?


public class InsertionSort {

public static void main(String a[]) {

int i;
int array[] = { 12, 9, 4, 99, 120, 1, 3, 10 };

System.out.println("Values Before the sort:\n");
for (i = 0; i < array.length; i++) {
System.out.print(array[i] + "  ");
}

System.out.println();

insertion_srt(array, array.length);

System.out.print("Values after the sort:\n");

for (i = 0; i < array.length; i++) {
System.out.print(array[i] + "  ");
}
}

public static void insertion_srt(int array[], int n) {
for (int i = 1; i < n; i++) {
int j = i;
int B = array[i];
while ((j > 0) && (array[j - 1] > B)) {
array[j] = array[j - 1];
j--;
}
array[j] = B;
}
}
}


Below is the output..

Values Before the sort:

12  9  4  99  120  1  3  10

Values after the sort:

1  3  4  9  10  12  99  120

Heap Sort algorithmn in Java ?


public class HeapSort {

public static void main(String a[]) {

int i;
int arr[] = { 1, 3, 4, 5, 2 };

for (i = 0; i < arr.length; i++) {
System.out.print(" " + arr[i]);
}

for (i = arr.length; i > 1; i--) {
fnSortHeap(arr, i - 1);
}

System.out.println("\n  Sorted array\n---------------\n");

for (i = 0; i < arr.length; i++) {
System.out.print(" " + arr[i]);
}

}

public static void fnSortHeap(int array[], int arr_ubound) {
int i, o;
int lChild, rChild, mChild, root, temp;
root = (arr_ubound - 1) / 2;

for (o = root; o >= 0; o--) {
for (i = root; i >= 0; i--) {
lChild = (2 * i) + 1;
rChild = (2 * i) + 2;
if ((lChild <= arr_ubound) && (rChild <= arr_ubound)) {
if (array[rChild] >= array[lChild])
mChild = rChild;
else
mChild = lChild;
} else {
if (rChild > arr_ubound)
mChild = lChild;
else
mChild = rChild;
}

if (array[i] < array[mChild]) {
temp = array[i];
array[i] = array[mChild];
array[mChild] = temp;
}
}
}
temp = array[0];
array[0] = array[arr_ubound];
array[arr_ubound] = temp;
return;
}
}


Below is the output....

 1 3 4 5 2

Sorted array
---------------

 1 2 3 4 5

Bi-directional bubble sort Algorithmn in java ?


public class BidirectionalBubbleSort {

public static void main(String a[]) {

int i;
int array[] = { 12, 9, 4, 99, 120, 1, 3, 10 };

System.out.println("Values Before the sort:\n");
for (i = 0; i < array.length; i++){
System.out.print(array[i] + "  ");
}

System.out.println();

bidirectionalBubble_srt(array, array.length);

System.out.print("Values after the sort:\n");

for (i = 0; i < array.length; i++){
System.out.print(array[i] + "  ");
}

}

public static void bidirectionalBubble_srt(int array[], int n) {
int j;
int st = -1;
while (st < n) {
st++;
n--;
for (j = st; j < n; j++) {
if (array[j] > array[j + 1]) {
int T = array[j];
array[j] = array[j + 1];
array[j + 1] = T;
}
}
for (j = n; --j >= st;) {
if (array[j] > array[j + 1]) {
int T = array[j];
array[j] = array[j + 1];
array[j + 1] = T;
}
}
}
}
}


Values Before the sort:

12  9  4  99  120  1  3  10

Values after the sort:

1  3  4  9  10  12  99  120

BubbleSort Algorithmn in Java ?



public class BubbleSort {

public static void main(String a[]) {

int i;
int array[] = { 12, 9, 4, 99, 120, 1, 3, 10 };

System.out.println("Values Before the sort:\n");

for (i = 0; i < array.length; i++) {
System.out.print(array[i] + "  ");
}
System.out.println();

bubble_srt(array, array.length);

System.out.print("Values after the sort:\n");

for (i = 0; i < array.length; i++) {
System.out.print(array[i] + "  ");
}
}

public static void bubble_srt(int a[], int n) {
int i, j, t = 0;
for (i = 0; i < n; i++) {
for (j = 1; j < (n - i); j++) {
if (a[j - 1] > a[j]) {
t = a[j - 1];
a[j - 1] = a[j];
a[j] = t;
}
}
}
}
}

Below is the output.....

Values Before the sort:

12  9  4  99  120  1  3  10  

Values after the sort:

1  3  4  9  10  12  99  120  

Generate array of random numbers with quickSort in Java?



import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class QuickSort {
/**
* Main method.
* @param args
*/
public static void main(String[] args) {

QuickSort app = new QuickSort();

//Generate an integer array of length 7
   List<Integer> input = app.generateRandomNumbers(7);

   //Before sort
   System.out.println(input);

   //After sort
   System.out.println(app.quicksort(input));

}

/**
* This method sort the input ArrayList using quick sort algorithm.
* @param input the ArrayList of integers.
* @return sorted ArrayList of integers.
*/
private List<Integer> quicksort(List<Integer> input){

if(input.size() <= 1){
return input;
}

int middle = (int) Math.ceil((double)input.size() / 2);
int pivot = input.get(middle);

List<Integer> less = new ArrayList<Integer>();
List<Integer> greater = new ArrayList<Integer>();

for (int i = 0; i < input.size(); i++) {
if(input.get(i) <= pivot){
if(i == middle){
continue;
}
less.add(input.get(i));
}
else{
greater.add(input.get(i));
}
}

return concatenate(quicksort(less), pivot, quicksort(greater));
}

/**
* Join the less array, pivot integer, and greater array
* to single array.
* @param less integer ArrayList with values less than pivot.
* @param pivot the pivot integer.
* @param greater integer ArrayList with values greater than pivot.
* @return the integer ArrayList after join.
*/
private List<Integer> concatenate(List<Integer> less, int pivot, List<Integer> greater){

List<Integer> list = new ArrayList<Integer>();

for (int i = 0; i < less.size(); i++) {
list.add(less.get(i));
}

list.add(pivot);

for (int i = 0; i < greater.size(); i++) {
list.add(greater.get(i));
}

return list;
}

/**
* This method generate a ArrayList with length n containing random integers .
* @param n the length of the ArrayList to generate.
* @return ArrayList of random integers with length n.
*/
private List<Integer> generateRandomNumbers(int n){

   List<Integer> list = new ArrayList<Integer>(n);
   Random random = new Random();

   for (int i = 0; i < n; i++) {
   list.add(random.nextInt(n * 10));
   }

   return list;
}
}

Below is the output....


[25, 58, 65, 19, 59, 8, 39]
[8, 19, 25, 39, 58, 59, 65]


QuickSort algorithm Java?



public class QuickSort {

public static void main(String a[]) {

int i;
int array[] = { 12, 9, 4, 99, 120, 1, 3, 10, 13 };

System.out.println("Values Before the sort:\n");
for (i = 0; i < array.length; i++){
System.out.print(array[i] + "  ");
}


quick_srt(array, 0, array.length - 1);
System.out.println("");
System.out.print("Values after the sort:\n");

for (i = 0; i < array.length; i++){
System.out.print(array[i] + "  ");
}
}

public static void quick_srt(int array[], int low, int n) {
int lo = low;
int hi = n;
if (lo >= n) {
return;
}
int mid = array[(lo + hi) / 2];
while (lo < hi) {
while (lo < hi && array[lo] < mid) {
lo++;
}
while (lo < hi && array[hi] > mid) {
hi--;
}
if (lo < hi) {
int T = array[lo];
array[lo] = array[hi];
array[hi] = T;
}
}
if (hi < lo) {
int T = hi;
hi = lo;
lo = T;
}
quick_srt(array, low, lo);
quick_srt(array, lo == low ? lo + 1 : lo, n);
}
}

Below is the output.....


Values Before the sort:

12  9  4  99  120  1  3  10  13

Values after the sort:

1  3  4  9  10  12  13  99  120


Dijkstra's (Shortest path) algorithm in Java?

Below is the example to find out the shortest path between edges......


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.PriorityQueue;

public class Dijkstra {
public static void computePaths(Vertex source) {
source.minDistance = 0.;
PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>();
vertexQueue.add(source);

while (!vertexQueue.isEmpty()) {
Vertex u = vertexQueue.poll();

// Visit each edge exiting u
for (Edge e : u.adjacencies) {
Vertex v = e.target;
double weight = e.weight;
double distanceThroughU = u.minDistance + weight;
if (distanceThroughU < v.minDistance) {
vertexQueue.remove(v);
v.minDistance = distanceThroughU;
v.previous = u;
vertexQueue.add(v);
}
}
}
}

public static List<Vertex> getShortestPathTo(Vertex target) {
List<Vertex> path = new ArrayList<Vertex>();
for (Vertex vertex = target; vertex != null; vertex = vertex.previous)
path.add(vertex);
Collections.reverse(path);
return path;
}

public static void main(String[] args) {
MinimumWindow a = new MinimumWindow();

Vertex v0 = a.new Vertex("Redvile");
Vertex v1 = a.new Vertex("Blueville");
Vertex v2 = a.new Vertex("Greenville");
Vertex v3 = a.new Vertex("Orangeville");
Vertex v4 = a.new Vertex("Purpleville");

v0.adjacencies = new Edge[] { a.new Edge(v1, 5), a.new Edge(v2, 10),a.new Edge(v3, 8) };
v1.adjacencies = new Edge[] { a.new Edge(v0, 5), a.new Edge(v2, 3),a.new Edge(v4, 7) };
v2.adjacencies = new Edge[] { a.new Edge(v0, 10), a.new Edge(v1, 3) };
v3.adjacencies = new Edge[] { a.new Edge(v0, 8), a.new Edge(v4, 2) };
v4.adjacencies = new Edge[] { a.new Edge(v1, 7), a.new Edge(v3, 2) };
Vertex[] vertices = { v0, v1, v2, v3, v4 };

computePaths(v0);

for (Vertex v : vertices) {
System.out.println("Distance to " + v + ": " + v.minDistance);
List<Vertex> path = getShortestPathTo(v);
System.out.println("Path: " + path);
}
}

public class Vertex implements Comparable<Vertex> {

public final String name;
public Edge[] adjacencies;
public double minDistance = Double.POSITIVE_INFINITY;
public Vertex previous;

public Vertex(String argName) {
name = argName;
}

public String toString() {
return name;
}

public int compareTo(Vertex other) {
return Double.compare(minDistance, other.minDistance);
}
}

class Edge {
public final Vertex target;
public final double weight;

public Edge(Vertex argTarget, double argWeight) {
target = argTarget;
weight = argWeight;
}
}
}



Below is the output...


Distance to Redvile: 0.0
Path: [Redvile]
Distance to Blueville: 5.0
Path: [Redvile, Blueville]
Distance to Greenville: 8.0
Path: [Redvile, Blueville, Greenville]
Distance to Orangeville: 8.0
Path: [Redvile, Orangeville]
Distance to Purpleville: 10.0
Path: [Redvile, Orangeville, Purpleville]







Wednesday, August 29, 2012

How to find the length of longest subString from Java String ?


Below is the example for finding out the longest subString with no repetition in java subString.........

public class LongestSubStringWithNoRepetition {

public static void main(String args[]) {

int x = lengthOfLongestSubstringNoRepetitions("Hi, this is a tesgft string.jgdfgdfkhfjrestjkbngfld ");
System.out.println(""+x);

}

public static int lengthOfLongestSubstringNoRepetitions(String s) {

   if (s == null)
       return 0;

   // Trimming input even for the non-empty case is more consistent.
   final String str = s.trim();

   if (str.equals(""))
       return 0;

   int seen[] = new int[Character.MAX_VALUE+1];
   for (int i = 0; i <= Character.MAX_VALUE; ++i)
       seen[i] = -1;

   int max = 1;
   int len = 0;

   for (int j = 0; j < str.length(); ++j) {
       char ch = str.charAt(j);
       // If ch was recently seen,
       // counting must restart after the last place it was seen.
       // Otherwise, it adds 1 to the length.
       len = Math.min(j-seen[ch], len+1);
       if (len > max)
           max = len;
       seen[ch] = j;
   }
   return max;
}

}

Below is the output........

12


How to find Minimum Window subString from Java String ?

Below is the example for finding the minimum window subString from Java String........


public class MinimumWindow {

public static void main(String args[]) {

Vector<Character> set = new Vector<Character>();
set.add('t');
set.add('i');
set.add('s');
set.add('t');
String x = minWindow("Hi, this is a test string ", set);
System.out.println(x);

}

public static String minWindow(String s, Vector<Character> charset) {
int n = charset.size();
int startindex = 0;
int endindex = n - 1;

Map<Character, Integer> CharSet = new HashMap<Character, Integer>();
for (Character c : charset) {
if (CharSet.containsKey(c)) {
int val = CharSet.get(c);
CharSet.put(c, val + 1);
} else
CharSet.put(c, 1);
}

int end = 0, start = 0;
for (; end < s.length() && n > 0; ++end) {
if (CharSet.containsKey(s.charAt(end))) {
int val = CharSet.get(s.charAt(end));
CharSet.put(s.charAt(end), val - 1);
if (val - 1 >= 0)
--n;
}
}
while (!CharSet.containsKey(s.charAt(start)))
++start;

int min_length = end - start + 1;
startindex = start;
endindex = end - 1;
System.out.println(startindex + " " + endindex);

for (; end < s.length(); ++end) {

if (CharSet.containsKey(s.charAt(end))) {
int val = CharSet.get(s.charAt(end));
CharSet.put(s.charAt(end), val - 1);
// System.out.println("E"+start+" "+end);

while (!CharSet.containsKey(s.charAt(start))
|| CharSet.get(s.charAt(start)) < 0) {

if (CharSet.containsKey(s.charAt(start))
&& CharSet.get(s.charAt(start)) < 0) {
val = CharSet.get(s.charAt(start));
CharSet.put(s.charAt(start), val + 1);
}
++start;
}

int currentLength = end - start + 1;
if (currentLength < min_length) {
min_length = currentLength;
startindex = start;
endindex = end;
}
System.out.println("S----"+start+" "+end);
}
}

System.out.println(startindex + " " + endindex);
return s.substring(startindex, endindex + 1);
}

}



Below is the output.....


1 14
S----4 16
S----9 17
S----9 19
S----9 20
S----17 22
17 22
t stri


Thursday, August 23, 2012

How to retrieve arrayList object through SOAP?

After retrieving data from the Server side through SOAP.....you can store it in the Vector collection and the store it in the Class Object property........!!!!!!!!

Declare the List variables for storing the array object


private  List<String>  downloadList= new ArrayList<String>();
private  List<String>  usenameAttr = new ArrayList<String>();
private  List<String>  imageList = new ArrayList<String>();
private  List<String>  purposeList = new ArrayList<String>();

then create the List of class type for storing the value

List<GVDownlaodObjectEntity>  downloadGVObjectList= new ArrayList<GVDownlaodObjectEntity>();

Where GVDownlaodObjectEntity is a class below.........


package com.ags.entity;

public class GVDownlaodObjectEntity {


private String info="";

private String gvThumbnail="";

private String gvTitle="";

private String gvUserName="";

public String getGvUserName() {
return gvUserName;
}

public void setGvUserName(String gvUserName) {
this.gvUserName = gvUserName;
}

public String getInfo() {
return info;
}

public void setInfo(String info) {
this.info = info;
}

public String getGvThumbnail() {
return gvThumbnail;
}

public void setGvThumbnail(String gvThumbnail) {
this.gvThumbnail = gvThumbnail;
}

public String getGvTitle() {
return gvTitle;
}

public void setGvTitle(String gvTitle) {
this.gvTitle = gvTitle;
}


}



then retrieves the response and see how to get the data and store it in property....




Vector result = (Vector)envelope.getResponse();
System.out.println("result:"+ result.get(0));

for(int i = 0; i < ((SoapObject) result.get(0)).getPropertyCount(); i++) {
String  gvdownloadObject =  ((SoapObject) result.get(0)).getProperty(i).toString();
int firstIndex =gvdownloadObject.indexOf("{");
String newListGVObject = gvdownloadObject.substring(firstIndex+1, gvdownloadObject.length()-1);
System.out.println("NewGVObject["+i+"]:"+gvdownloadObject);
StringTokenizer str= new StringTokenizer(newListGVObject,";");
GVDownlaodObjectEntity gVDownlaodObjectEntity = new GVDownlaodObjectEntity();
while (str.hasMoreTokens()) {
String token = str.nextToken().trim();
System.out.println("Token:"+token);
 
if(token.compareToIgnoreCase("") != 0){
String gvDownloadTokens=token.substring(0,token.indexOf('='));
System.out.println("ObjectTokens:"+gvDownloadTokens);
if(gvDownloadTokens.compareToIgnoreCase("UserName") == 0){
gVDownlaodObjectEntity.setGvUserName(token.substring(token.indexOf('=')+1,token.length()));
}else if(gvDownloadTokens.compareToIgnoreCase("GvInfo") == 0){
gVDownlaodObjectEntity.setInfo(token.substring(token.indexOf('=')+1,token.length()));
}else if(gvDownloadTokens.compareToIgnoreCase("GvThumb") == 0){
gVDownlaodObjectEntity.setGvThumbnail(token.substring(token.indexOf('=')+1,token.length()));
}else if(gvDownloadTokens.compareToIgnoreCase("Id") == 0)
gVDownlaodObjectEntity.setGvId(token.substring(token.indexOf('=')+1,token.length()));
else if(gvDownloadTokens.compareToIgnoreCase("GvTitle") == 0){
gVDownlaodObjectEntity.setGvTitle(token.substring(token.indexOf('=')+1,token.length()));

downloadList.add(gVDownlaodObjectEntity.getGvTitle());
purposeList.add(gVDownlaodObjectEntity.getInfo());
usenameAttr.add(gVDownlaodObjectEntity.getGvUserName());
imageList.add(gVDownlaodObjectEntity.getGvThumbnail());

}
}


}
if(gVDownlaodObjectEntity != null)
downloadGVObjectList.add(gVDownlaodObjectEntity);
System.out.println("downloadGVObjectList size:"+downloadGVObjectList.size()+"|"+downloadGVObjectList.get(i).getGvThumbnail());
}

totalRecords=Integer.parseInt(((SoapObject) result.get(1)).toString());
System.out.println("total count from server:"+totalRecords);







Wednesday, August 8, 2012

How to save custom class object in android Cache?


Create the class MyClass for writing to save object and also for retrieval object........

public class MyClass implements Serializable
{
    private static final long serialVersionUID = 1L;
    public String title;
    public String startTime;
    public String endTime;
    public String day;
    public boolean classEnabled;

     public MyClass(String title, String startTime, boolean enable){
            this.title = title;
            this.startTime = startTime;
            this.classEnabled = enable;
        }


     public MyClass()
     {
     }

     public boolean saveObject(MyClass obj) {

        final File suspend_f=new File(SerializationTest.cacheDir, "test");

            FileOutputStream   fos  = null;
            ObjectOutputStream oos  = null;
            boolean            keep = true;

            try {
                fos = new FileOutputStream(suspend_f);
                oos = new ObjectOutputStream(fos);
                oos.writeObject(obj);
            }
            catch (Exception e) {
                keep = false;


            }
            finally {
                try {
                    if (oos != null)   oos.close();
                    if (fos != null)   fos.close();
                    if (keep == false) suspend_f.delete();
                }
                catch (Exception e) { /* do nothing */ }
            }
            return keep;


        }

     public MyClass getObject(Context c)
     {
         final File suspend_f=new File(SerializationTest.cacheDir, "test");

         MyClass simpleClass= null;
         FileInputStream fis = null;
         ObjectInputStream is = null;
        // boolean            keep = true;

         try {

             fis = new FileInputStream(suspend_f);
             is = new ObjectInputStream(fis);
             simpleClass = (MyClass) is.readObject();
         }catch(Exception e)
         {
            String val= e.getMessage();

         }finally {
                try {
                    if (fis != null)   fis.close();
                    if (is != null)   is.close();

                }
                catch (Exception e) { }
            }

         return simpleClass;
     }
}

And from any of the Activity you can call the above class to save object......

if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"MyCustomObject");
        else
            cacheDir= getCacheDir();
        if(!cacheDir.exists())
            cacheDir.mkdirs();




       MyClass m= new MyClass( "umer", "asif", true);

          boolean  result =m.saveObject(m);

      if(result)
        Toast.makeText(this, "Saved object", Toast.LENGTH_LONG).show();
      else
          Toast.makeText(this, "Error saving object", Toast.LENGTH_LONG).show();

        MyClass m= new MyClass();
        MyClass c = m.getObject(this);
        if(c!= null)
            Toast.makeText(this, "Retrieved object", Toast.LENGTH_LONG).show();
        else
            Toast.makeText(this, "Error retrieving object", Toast.LENGTH_LONG).show();

}

Dont forget to use write_external_storage permissions in manifest file.And dont use context in it otherwise nonserializable exception will be raised.

Wednesday, August 1, 2012

How to get the Dimension of layouts in android ?


In Android, you attach a view tree to your Actitity in order to be able to interact with the UI.
Once this is done, you can get references to your widgets (views) using a call like this from your Activity:
TextView t = (TextView) findViewById(R.id.txtName);

Now, views all sport a method like this: t.getHeight()
Which, presumably returns the actual height of that view element. Problem is, this method invariably returns zero.

At first I thought it was because I was calling this during the onCreate() method in my activity class. Perhaps the layout wasn't fully calculated at this time. So I moved my code to the onResume() method. This method is called whenever the activity is entered or re-entered. But again, no luck. Strange, as the layout at this point should be fully ready to display. I think there's a bug here in Android (I'm at version 2.2 currently.)

Luckily, I accidentally hit the search button while running a test on my EVO and, lo and behold, the height values I was trying to report on a TextView in my layout suddenly had non-zero values in them. Obviously, some sort of layout process had been forced, and the state of the view tree had been updated.

How can I get notified when the layout is fully calculated? The short answer is to attached a listener for a callback when the layout is calculated. Here's what it looks like.

@Override
public void onCreate(Bundle savedInstanceState)
{
  super.onCreate(savedInstanceState);
  RelativeLayout vMain = (RelativeLayout) 
     this.getLayoutInflater().inflate(R.layout.main, null);
  vMain.getViewTreeObserver().addOnGlobalLayoutListener(
  new ViewTreeObserver.OnGlobalLayoutListener() {
    public void onGlobalLayout() {
      DisplayLayoutDimensions();
    }
  });
  setContentView(vMain);
}




public void DisplayLayoutDimensions()
{
  StringWriter sw = new StringWriter(1000);
  PrintWriter out = new PrintWriter(sw);
  TextView t = (TextView) findViewById(R.id.textview);
  ImageView img = (ImageView) findViewById(R.id.hp67);
  out.printf("\nImage Drawable\n");
  out.printf("ImageView Height dp: %d\n", img.getHeight());
  out.printf("ImageView Measured Height dp: %\n",
     img.getMeasuredHeight());
  t.setText(sw.toString());
}