Wednesday, April 19, 2017

java binary tree







// ref: http://javabeat.net/binary-search-tree-traversal-java/

package binarysearchtreedemo;

public class BinarySearchTreeDemo {

    public static void main(String[] args) {
        BinarySearchTree bst = new BinarySearchTree();

        int[] nums = {40, 25, 78, 10, 32};
//        int[] nums = {10, 20, 0, 5, 15};
        for (int i : nums) {
            bst.insert(i);
        }
//        System.out.println("Inorder traversal");
//        bst.printInorder();

        System.out.println("Preorder Traversal");
        bst.printPreorder();

//        System.out.println("Postorder Traversal");
//        bst.printPostorder();
//
//        System.out.println("The minimum value in the BST: " + bst.findMinimum());
//        System.out.println("The maximum value in the BST: " + bst.findMaximum());
        System.out.println("Print Same Level Node: "  );
        bst.printSameLevelNode(3);
   
    }
}



------------------------------------------------------------------------------------------------------------------


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package binarysearchtreedemo;

import java.util.ArrayList;

/**
 * Represents the Binary Search Tree.
 */
public class BinarySearchTree {

    //Refrence for the root of the tree.
    public Node root;

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

    int level_no, count = 0,tree_height, desired_level;

    public BinarySearchTree insert(int value) {
        Node node = new Node(value);

        if (root == null) {
            root = node;
            return this;
        }

        insertRec(root, node);
        return this;
    }

    private void insertRec(Node latestRoot, Node node) {

        if (latestRoot.value > node.value) {

            if (latestRoot.left == null) {
                latestRoot.left = node;
//        return;
            } else {
                insertRec(latestRoot.left, node);
            }
        } else {
            if (latestRoot.right == null) {
                latestRoot.right = node;
//        return;
            } else {
                insertRec(latestRoot.right, node);
            }
        }
    }

    public void printSameLevelNode(int _desired_level) {

//        level_no = _level_no;
//        printSameLevelNode(root);
//        nodeAl.clear();
        tree_height = height(root);
        desired_level = _desired_level;
        System.out.println("height=" + tree_height);

        int i;
//        for (i = 1; i <= h; i++) {
//            printGivenLevel(root, i);
//        }
        if(desired_level>tree_height || desired_level<=0)
        {
            System.out.print("Highest level number can be 1 to "+tree_height);
        }
        else
        {
            printGivenLevel(root, desired_level);
            
        }
        System.out.print("\n");
        

    }

    /* Print nodes at the given level */
    void printGivenLevel(Node root, int level) {
        if (root == null) {
            
            return;
        }
        if (level == 1) {
            
            count++;
            if(count==1)
            {
                System.out.print("Level "+ desired_level+" Nodes are: ");
            }
            
            System.out.print(root.value + " ");
        } else if (level > 1) {
            printGivenLevel(root.left, level - 1);
            printGivenLevel(root.right, level - 1);
        }
    }

    int height(Node root) {
        if (root == null) {
            return 0;
        } else {
            /* compute  height of each subtree */
            int lheight = height(root.left);
            int rheight = height(root.right);

            /* use the larger one */
            if (lheight > rheight) {
                return (lheight + 1);
            } else {
                return (rheight + 1);
            }
        }
    }

    public void printSameLevelNode(Node _currRoot) {

        Node currNode = _currRoot;

        System.out.println("parent Node=" + currNode.value + " left child=" + currNode.left.value + " right child=" + currNode.right.value);

        for (int i = 0; i <= level_no; i++) {
            if (i == level_no) {
//                nodeAl.add(currNode.left.value);
//                nodeAl.add(currNode.right.value);
            } else {
                printSameLevelNode(currNode.left);
                printSameLevelNode(currNode.right);
            }
        }

//        System.out.println("nodeAl=" + nodeAl);
    }

    /**
     * Returns the minimum value in the Binary Search Tree.
     */
    public int findMinimum() {
        if (root == null) {
            return 0;
        }
        Node currNode = root;
        while (currNode.left != null) {
            currNode = currNode.left;
            System.out.println("currNode=" + currNode.value);
        }
        return currNode.value;
    }

    /**
     * Returns the maximum value in the Binary Search Tree
     */
    public int findMaximum() {
        if (root == null) {
            return 0;
        }

        Node currNode = root;
        while (currNode.right != null) {
            currNode = currNode.right;
        }
        return currNode.value;
    }

    /**
     * Printing the contents of the tree in an inorder way.
     */
    public void printInorder() {
        printInOrderRec(root);
        System.out.println("");
    }

    /**
     * Helper method to recursively print the contents in an inorder way
     */
    private void printInOrderRec(Node currRoot) {
        if (currRoot == null) {
            return;
        }
        printInOrderRec(currRoot.left);
        System.out.print(currRoot.value + ", ");
        printInOrderRec(currRoot.right);
    }

    /**
     * Printing the contents of the tree in a Preorder way.
     */
    public void printPreorder() {
        printPreOrderRec(root);
        System.out.println("");
    }

    /**
     * Helper method to recursively print the contents in a Preorder way
     */
    private void printPreOrderRec(Node currRoot) {
        if (currRoot == null) {
            return;
        }
        System.out.print(currRoot.value + ", ");
        printPreOrderRec(currRoot.left);
        printPreOrderRec(currRoot.right);
    }

    /**
     * Printing the contents of the tree in a Postorder way.
     */
    public void printPostorder() {
        printPostOrderRec(root);
        System.out.println("");
    }

    /**
     * Helper method to recursively print the contents in a Postorder way
     */
    private void printPostOrderRec(Node currRoot) {
        if (currRoot == null) {
            return;
        }
        printPostOrderRec(currRoot.left);
        printPostOrderRec(currRoot.right);
        System.out.print(currRoot.value + ", ");

    }
}


------------------------------------------------------------------------------------------------------------------


package binarysearchtreedemo;


public class Node {
  //The value present in the node.
  public int value;

  //The reference to the left subtree.
  public Node left;

  //The reference to the right subtree.
  public Node right;

  public Node(int value) {
    this.value = value;
  }

}

------------------------------------------------------------------------------------------------------------------

output:

Preorder Traversal
40, 25, 10, 32, 78,
Print Same Level Node:
height=3
Level 3 Nodes are: 10 32 

Monday, March 20, 2017

java thread Wait & Notify example

WaitNotifyTest .java
------------------------------------------------------



package waitnotifytest;

public class WaitNotifyTest {

    public static void main(String[] args) {
        Message msg = new Message("process it");
        Waiter waiter = new Waiter(msg);
        new Thread(waiter,"waiter_1").start();
       
        Waiter waiter1 = new Waiter(msg);
        new Thread(waiter1, "waiter2").start();
       
        Notifier notifier = new Notifier(msg);
        new Thread(notifier, "notifier").start();
        System.out.println("All the threads are started");
    }

}







Waiter.java
----------------------------------------------------------------------

package waitnotifytest;

import java.util.Date;

public class Waiter implements Runnable{
   
    private Message msg;
   
    public Waiter(Message m){
        this.msg=m;
    }

    @Override
    public void run() {
        String thread_name = Thread.currentThread().getName();
       
        synchronized (msg) {
            try{
                System.out.println(thread_name+" waiting to get notified at time:"+System.currentTimeMillis()+ " min="+new Date().getMinutes()+" sec=" + new Date().getSeconds());
                msg.wait();
                System.out.println("--wait()");
            }catch(InterruptedException e){
                e.printStackTrace();
            }
            System.out.println(thread_name+" after wait at time:"+System.currentTimeMillis()+ " min="+new Date().getMinutes()+" sec="  + new Date().getSeconds());
            //process the message now
            System.out.println(thread_name+" processed: "+msg.getMsg());
        }
    }

}








Notifier.java
------------------------------------------------------

package waitnotifytest;

public class Notifier implements Runnable {

    private Message msg;
   
    public Notifier(Message msg) {
        this.msg = msg;
    }

    @Override
    public void run() {
        String thread_name = Thread.currentThread().getName();
        System.out.println(thread_name+" started");
        try {
            Thread.sleep(1000);
            synchronized (msg) {
                msg.setMsg("Notifier thread_name=" + thread_name+" Notifier work done");
//                msg.notify();
                 msg.notifyAll();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
       
    }

}


Message.java
-----------------------------------------------------------------------------------
package waitnotifytest;

public class Message {
    private String msg;
   
    public Message(String str){
        this.msg=str;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String str) {
        this.msg=str;
    }

}



###############output#################
All the threads are started
notifier started
waiter_1 waiting to get notified at time:1490077406336 min=23 sec=26
waiter2 waiting to get notified at time:1490077406342 min=23 sec=26
--wait()
waiter2 after wait at time:1490077407336 min=23 sec=27
waiter2 processed: Notifier thread_name=notifier Notifier work done
--wait()
waiter_1 after wait at time:1490077407336 min=23 sec=27
waiter_1 processed: Notifier thread_name=notifier Notifier work done

java thread & synchronized example

package threadjoinexample;

import java.util.logging.Level;
import java.util.logging.Logger;

public class ThreadJoinExample {

    public static void main(String[] args) {
        Table mTable = new Table();//only one object 
       
        Thread t1 = new Thread(new MyRunnable(mTable), "1st");
        Thread t2 = new Thread(new MyRunnable(mTable), "2nd");
        Thread t3 = new Thread(new MyRunnable(mTable), "3rd");

        t1.start();

        //start second thread after waiting for 2 seconds or if it's dead
//        try {
////            t1.join(2000);
//            System.out.println("1st try");
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        try {
            t1.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(ThreadJoinExample.class.getName()).log(Level.SEVERE, null, ex);
        }
        t2.start();

        //checks if this thread is alive
        System.out.println(t1.getName() + "=, isAlive = " + t1.isAlive());

        //start third thread only when first thread is dead
//        try {
////            t1.join();
//            System.out.println("2nd block  try="+t1.getName());
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        try {
            t2.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(ThreadJoinExample.class.getName()).log(Level.SEVERE, null, ex);
        }
        t3.start();
       
        try {
            t3.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(ThreadJoinExample.class.getName()).log(Level.SEVERE, null, ex);
        }

        //let all threads finish execution before finishing main thread
//        try {
//
////            t1.join();
//
//            System.out.print(t2.getName());
//            //checks if this thread is alive
//            System.out.println(", t2 isAlive = " + t2.isAlive());
//
////            t2.join();
////            t3.join();
//        } catch (InterruptedException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }

        System.out.println("All threads are dead, exiting main thread");
    }

}

class MyRunnable implements Runnable {
    Table t;
   
    MyRunnable(Table t) {
        this.t = t;
    }

    synchronized void test() {
        for (int i = 1; i <= 5; i++) {
            try {
                Thread.sleep(500);
            } catch (Exception e) {
                System.out.println(e);
            }
            System.out.println(i*100 + " " + Thread.currentThread().getName());
        }
    }

    @Override
    public void run() {
        System.out.println("--Thread started:::" + Thread.currentThread().getName());
        t.printTable(100);
//        test();
//        try {
//            Thread.sleep(4000);
//            System.out.println("run() 4s after=" + Thread.currentThread().getName());
//
//            test();
//
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        System.out.println("!--Thread ended:::" + Thread.currentThread().getName()+"\n\n");
    }

}

class Table {

    synchronized void printTable(int n) {//synchronized method 
        for (int i = 1; i <= 5; i++) {
            try {
                Thread.sleep(500);
            } catch (Exception e) {
                System.out.println(e);
            }
            System.out.println(i*100 + " " + Thread.currentThread().getName());
        }

    }
}

Sunday, March 19, 2017

java thread join example

package threadjoinexample;

import java.util.logging.Level;
import java.util.logging.Logger;

public class ThreadJoinExample {

    public static void main(String[] args) {
        Thread t1 = new Thread(new MyRunnable(), "1st");
        Thread t2 = new Thread(new MyRunnable(), "2nd");
        Thread t3 = new Thread(new MyRunnable(), "3rd");

//        try {
//            t2.join();
//        } catch (InterruptedException ex) {
//            Logger.getLogger(ThreadJoinExample.class.getName()).log(Level.SEVERE, null, ex);
//        }

        t1.start();

        //start second thread after waiting for 2 seconds or if it's dead
//        try {
////            t1.join(2000);
//            System.out.println("1st try");
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        try {
            t1.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(ThreadJoinExample.class.getName()).log(Level.SEVERE, null, ex);
        }
        t2.start();
       
       
            //checks if this thread is alive
      System.out.println(t1.getName()+"=, isAlive = " + t1.isAlive());

        //start third thread only when first thread is dead
//        try {
////            t1.join();
//            System.out.println("2nd block  try="+t1.getName());
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        try {
            t2.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(ThreadJoinExample.class.getName()).log(Level.SEVERE, null, ex);
        }
        t3.start();

        //let all threads finish execution before finishing main thread
        try {
           
           
            t1.join();
           
            System.out.print(t2.getName());
            //checks if this thread is alive
      System.out.println(", t2 isAlive = " + t2.isAlive());
           
            t2.join();
            t3.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("All threads are dead, exiting main thread");
    }

}

class MyRunnable implements Runnable {

    @Override
    public synchronized void run() {
        System.out.println("--Thread started:::" + Thread.currentThread().getName());
        try {
            Thread.sleep(4000);
            System.out.println("run() 4s after=" + Thread.currentThread().getName());

            for (int i = 1; i <= 5; i++) {
                try {
                    Thread.sleep(500);
                } catch (Exception e) {
                    System.out.println(e);
                }
                System.out.println(i + " " + Thread.currentThread().getName());
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("--Thread ended:::" + Thread.currentThread().getName());
    }

}








----------------------------------
output:
--Thread started:::1st
run() 4s after=1st
1 1st
2 1st
3 1st
4 1st
5 1st
--Thread ended:::1st
1st=, isAlive = false
--Thread started:::2nd
run() 4s after=2nd
1 2nd
2 2nd
3 2nd
4 2nd
5 2nd
--Thread ended:::2nd
2nd, t2 isAlive = false
--Thread started:::3rd
run() 4s after=3rd
1 3rd
2 3rd
3 3rd
4 3rd
5 3rd
--Thread ended:::3rd
All threads are dead, exiting main thread

Sunday, March 5, 2017

android custom camera with surface view

Download: http://www.mediafire.com/file/m99on6dc2d42dss/SurfaceviewExample4.zip




package com.javacodegeeks.androidsurfaceviewexample;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidSurfaceviewExample extends Activity implements SurfaceHolder.Callback {


    Camera camera;
    SurfaceView surfaceView;
    SurfaceHolder surfaceHolder;

    PictureCallback jpegCallback;
    TextView capture;
    LinearLayout llcontainer;

    /**     * Called when the activity is first created.     */    @Override    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
        capture = (TextView) findViewById(R.id.capture);
        llcontainer= (LinearLayout) findViewById(R.id.container);


        surfaceHolder = surfaceView.getHolder();

        // Install a SurfaceHolder.Callback so we get notified when the        // underlying surface is created and destroyed.        surfaceHolder.addCallback(this);

        // deprecated setting, but required on Android versions prior to 3.0        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);


        capture.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                try {
                    captureImage(view);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        llcontainer.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                try {
                    captureImage(view);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        jpegCallback = new PictureCallback() {
            public void onPictureTaken(byte[] data, Camera camera) {
                FileOutputStream outStream = null;
                try {
                    outStream = new FileOutputStream(String.format("/sdcard/%d.jpg", System.currentTimeMillis()) );
                    outStream.write(data);
                    outStream.close();
                    Log.d("Log", "onPictureTaken - wrote bytes: " + data.length);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                }
                Toast.makeText(getApplicationContext(), "Picture Saved", Toast.LENGTH_SHORT).show();
                refreshCamera();
            }
        };
    }

    public void captureImage(View v) throws IOException {
        //take the picture        camera.takePicture(null, null, jpegCallback);
    }

    public void refreshCamera() {
        if (surfaceHolder.getSurface() == null) {
            // preview surface does not exist            return;
        }

        // stop preview before making changes        try {
            camera.stopPreview();
        } catch (Exception e) {
            // ignore: tried to stop a non-existent preview        }

        // set preview size and make any resize, rotate or        // reformatting changes here        // start preview with new settings        try {
            camera.setPreviewDisplay(surfaceHolder);
            camera.startPreview();
        } catch (Exception e) {

        }
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        // Now that the size is known, set up the camera parameters and begin        // the preview.        refreshCamera();
    }

    public void surfaceCreated(SurfaceHolder holder) {
        try {
            // open the camera            camera = Camera.open();

        } catch (RuntimeException e) {
            // check for exceptions            System.err.println(e);
            return;
        }
        Camera.Parameters param;
        param = camera.getParameters();





        param.setRotation(90); //set rotation to save the picture
        camera.setDisplayOrientation(90); //set the rotation for preview camera


        // modify parameter        param.setPreviewSize(352, 288);
        camera.setParameters(param);
        try {
            // The Surface has been created, now tell the camera where to draw            // the preview.            camera.setPreviewDisplay(surfaceHolder);
            camera.startPreview();
        } catch (Exception e) {
            // check for exceptions            System.err.println(e);
            return;
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // stop preview and release camera        camera.stopPreview();
        camera.release();
        camera = null;
    }

}

Tuesday, January 24, 2017

java tree example

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package treetest;

public class TreeTest {

    public static void main(String[] args) {
        Node treeRootNode = new Node(null);

        treeRootNode.setId("1");

        // add child to root node
        Node childNode = addChild(treeRootNode, "2");//742
        // add child to the child node created above
        addChild(childNode, "4");//69c
        addChild(childNode, "5");//69c
//
//        // add child to root node
        Node child2 = addChild(treeRootNode, "3");//742
//        // add child to the child node created above
//        addChild(child2, "child-2-1");//922
//        addChild(child2, "child-2-2");//922
//        addChild(child2, "child-2-2");//922

        printTree(treeRootNode, " ");

        deleteChild(treeRootNode, "3");
//
//        deleteChild(treeRootNode, "1");

//        deleteChild(treeRootNode, "1");
        printTree(treeRootNode, " ");

    }

    static Node addChild(Node parent, String id) {
        Node node = new Node(parent);
        node.setId(id);
        node.getParent().getChildren().add(node);

//        parent.getChildren().add(node);
        System.out.println("---parent.getChildren().get(0)=" + parent.getChildren().get(0).getId() + " Parent=" + parent.getChildren().get(0).getParent().getId());
        return node;
    }

    static void deleteChild(Node parent, String id) {

//        if(parent.getParent().getId().equalsIgnoreCase(""))
//        {
//            System.out.println("---empty tree=" );
//            parent.getChildren().clear();
//        }
//      
        for (int i = 0; i < parent.getChildren().size(); i++) {
            System.out.println("i=" + i + " " + parent.getChildren().get(i).getId());

            if (parent.getId().equalsIgnoreCase(id)) {
                System.out.println("--- tree=");
                parent.getChildren().clear();
                System.out.println("---empty tree=" + parent.getId());
//                parent.getParent().setId("");
                break;
            }

            if (id.equalsIgnoreCase(parent.getChildren().get(i).getId())) {

                System.out.println("----deleted =" + parent.getChildren().get(i).getId() + " parent=" + parent.getId());

//                parent.getChildren().remove(parent.getChildren().get(i).getId());
                parent.getChildren().remove(i);

                break;
            }
            deleteChild(parent.getChildren().get(i), id);
        }

//        parent.getChildren().add(node);
//        System.out.println("---parent.getChildren().get(0)="+parent.getChildren().get(0).getId()+ " Parent="+parent.getChildren().get(0).getParent().getId());
    }

    private static void printTree(Node node, String appender) {

//        for (Node each : node.getChildren()) {
//            printTree(each, appender + " ** ");
//        }
        System.out.println(appender + node.getId());
        for (int i = 0; i < node.getChildren().size(); i++) {
//            System.out.println("i="+i+" "+node.getId());
            printTree(node.getChildren().get(i), appender + " ** ");
        }
    }
}









//////////////////////////////////////////////////////////////


package treetest;
import java.util.ArrayList;
import java.util.List;

public class Node {

    private String id;
    private  List<Node> children = new ArrayList<>();
    private Node parent;

    public Node(Node parent) {
       
        this.parent = parent;
       
        System.out.println("--cons() parent="+this.parent);
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public List<Node> getChildren() {
//        children.clear();
       
        return children;
    }

    public Node getParent() {
        return parent;
    }

}




output:
root
  ** child#1
  **  ** child-1-1
  **  ** child-1-2
  ** child#2
  **  ** child-2-1
  **  ** child-2-2