Saturday 24 August 2013

Finding minimum possible degree of a graph(n,e)

The following code snippet is to find the minimum possible degree of a graph whose number of vertices(n) and edges(e) are given.
The algorithm is such that a vertex can have maximum degree equal to (n-1) but if it is having degree 1 it means there is one more vertex whose degree is one and if its degree is 2 then there are 2 vertices whose degree is 1.
The here is the code for finding minimum degree of a graph

import java.io.*;
import java.util.Arrays;
public class MinDegree {
        //function to find sum of an array
 static int sum(int[] arr){
  int sum = 0;
  for(int a: arr){
   sum += a;
  }
  return sum;
 }
        //function to find minimum of an array
 static int minimum(int[] arr){
  int min = Integer.MAX_VALUE;
  for(int i=0; i<arr.length; i++){
    if(arr[i] < min)
       min = arr[i];
   }
  }
  return min;
 }
 public static void main(String[] ar) throws Exception{
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                //number of edges should not exceed n(n-1)/2
                System.out.println("Enter no of vertices and edges: n e");
  String[] in = br.readLine().split(" ");//input should be like 5 7
  int vertices = Integer.parseInt(in[0]);//parsing string into integers
  int edges = Integer.parseInt(in[1]);
  int[] degree = new int[vertices];//buffer to store degrees 
  int counter = 0;
  int round = 0;
  while(sum(degree) < (2*edges)){//sum of degrees must be less than 2*edges
   if(degree[counter] < (vertices-1)){
    degree[counter] += 1;
    degree[round+counter+1] += 1;//it will increase neighbours degree
    round++;
   }
   else{
    counter++;
    round = 0;
   }
  }
  System.out.println(minimum(degree));
 }
}

Happy Coding :)

Thursday 15 August 2013

Converting OpenCV Mat to BufferedImage of Java

While working with opencv and java i got stuck on how to display an image in java's JFrame, because i can't directly put Mat object of opencv in drawImage function of Java's Graphics class, so i need a hack to convert Mat object into BufferedImage which is as follows.
First think of how can we do it, we have some methods to make a BufferedImage such as
  • Directly passing the path of image, which is not the case.
  • Passing stream of bytes of image into BufferedImage, which can be useful, lets focus on it.

Suppose image is my Mat object
Mat image = Highgui.imread("/Users/Sumit/Desktop/image.jpg");
and i want to convert it into BufferedImage
So lets take an object of MatOfByte.
MatOfByte bytemat = new MatOfByte();
byte mat is to convert image into stream of bytes.
Highgui.imencode(".jpg", image, bytemat);
this will put the bytes into bytemat object
Now convert byte mat into array of bytes.
byte[] bytes = bytemat.toArray();
Pass these bytes into ByteArrayInputStream to get a stream of bytes.
InputStream in = new ByteArrayInputStream(bytes);
Now pass this stream in read method of ImageIO class.
BufferedImage img = ImageIO.read(in);
Now we have BufferedImage object, we can use it to display it in JFrame's paint method.

This is the complete snippet
Mat image = Highgui.imread("/Users/Sumit/Desktop/image.jpg");
MatOfByte bytemat = new MatOfByte();
Highgui.imencode(".jpg", image, bytemat);
byte[] bytes = bytemat.toArray();
InputStream in = new ByteArrayInputStream(bytes);
BufferedImage img = ImageIO.read(in);
Happy Coding!!! :)

Monday 5 August 2013

Installing opencv for java on MAC OS X and Configuring Eclipse

Opencv is an open source library for computer vision, Now i am going to show you how to install it on Mac OS X.
Steps:

  • Download a fresh copy of opencv-2.4.6.1 from here.
  • Extract it to some location in your Mac.
  • now open terminal go inside the extracted folder opencv-2.4.6.1.
  • Type following commands
  • mkdir build
  • cd build
  • Make sure your JAVA_HOME environment variable is set or explicitly type export JAVA_HOME=<location of java home folder>
  • cmake -G "Unix Makefiles" -D CMAKE_CXX_COMPILER=/usr/bin/g++ -D CMAKE_C_COMPILER=/usr/bin/gcc -D WITH_CUDA=ON .. 
  • make -j4 // here number 4 means the number of cores in your processor
  • make install

Configuring Eclipse with opencv


  • Open eclipse
  • Click on File-> New Project-> Java Project
  • Give an appropriate Project Name
  • Now right click on Project and choose Properties.

  • Select Java Build Path and then select Libraries.


  • Click on Add Library.


  • Choose User Library.
  • Click on User Libraries, then Select New and give a name to your library.


  • Now Select your library and click on Add External JARs, go to your build folder and then open bin folder, there you will find opencv-246.jar, Select this file.
  • If you are not able to find .jar then make sure your JAVA_HOME variable is set in the environment variables at the time of build.
  • Now Select Native Library Location and click on Edit.


  • Insert the path of your cv.so file, mine is in /build/lib.


  • Click on Finish, Now your project is configured with openCV library.


Thursday 18 July 2013

Calling a constructor within a constructor in JAVA

Constructor is basically used to initialize variables, but sometimes we have more than one constructor in our class which is also known as Constructor overloading. The object we create is actually the call to constructor and since the name of constructor is same as the name of class so we often call them the object of class.
Now suppose we have a constructor and we want to call another constructor inside it, then this can be done with the help of this keyword.

class abc{
    int i, j;
    abc(){
        i = 10;
    }
    abc(int j){
        this();
        this.j = j;
        //this(); calling this() here will give us error because 
        //   what if we started using i and it had not been initialised
        // thats why we must call this or super in first line while calling constructors
    }
    public static void main(String[] args){
        abc a = new abc(6);
    }
}

this keyword represents object of its own class. It can be used for two purposes, one is two access class member with in the class itself or in more simple language whenever we have to distinguish between a local variable and a class variable we have to use this keyword, like we did in our example 'this.j = j' it means assign the value of local variable j to the class variable j.
Second use of this keyword is to call a constructor within in a constructor.
Note: if you are calling constructor within a constructor than this must come in your first line.
In the above example we are calling a blank constructor within a parametrized constructor, so here first it will call the blank constructor and initializes variable i and then initializes variable j.
Similarly we can call parametrized construction within blank constructor like, this(5) as the first line, but we cannot do this for both the constructors, it will give you compile time error.

Saturday 13 July 2013

Snake Game Code in java

This is the working code of well known game Snake.


//package snake_game;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.RenderingHints;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Vector;

import javax.swing.ActionMap;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.KeyStroke;

//Each circle in snake body
class snake_node{
 int centerx, centery, radius, pcenterx, pcentery;
 snake_node(){
  
  radius = 10;
 }
}
//actual gui for game
public class Snake_game extends JFrame {
 snake panel = null;
 JMenuBar menu = null;
 JMenu controls = null;
 JMenuItem play = null;
 JMenuItem restart = null;
 JMenuItem instructions = null;
 boolean firstplay = true;
 Snake_game(){
  this.setResizable(false);
  menu = new JMenuBar();
  play = new JMenuItem("Play");
  controls = new JMenu("Controls");  
  restart = new JMenuItem("Restart");
  instructions = new JMenuItem("Instructions");
  restart.setMnemonic(KeyEvent.VK_R);
  restart.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, InputEvent.CTRL_MASK));
  restart.setMnemonic(KeyEvent.VK_I);
  instructions.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, InputEvent.CTRL_MASK));
  play.setMnemonic(KeyEvent.VK_P);
  play.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, InputEvent.CTRL_MASK));
  controls.add(play);
  controls.add(restart);
  controls.add(instructions);
  menu.add(controls);
  this.setJMenuBar(menu);
  //GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(this);
  panel = new snake();
  this.setLayout(new BorderLayout());
  this.setMinimumSize(new Dimension(800, 595));
  panel.dim = this.getSize();
  this.add(panel, BorderLayout.CENTER);
  this.setLocationRelativeTo(null);
  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  play.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent eee){play();}});
  restart.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent ee){restart();}});
  instructions.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent ee){instruct();}});
  this.addKeyListener(new KeyAdapter(){public void keyPressed(KeyEvent e){panel.keyPress(e);}});      
  this.setVisible(true);
  this.pack();
 }
        //function to start thread for starting game
 public void play(){
  if(firstplay){
   panel.t.start();
   firstplay = false;
   play.setEnabled(false);
  }
 }
        //function for restarting game, it will resize the snake to its initial position and initial length
 public void restart(){
  int pos = 0;
  panel.vector.clear();
  snake_node[] snode = new snake_node[5];
  for(int i =0; i < 5; i++){
   snode[i] = new snake_node();
   snode[i].centerx = 200;
   snode[i].centery = 150-pos;
   snode[i].pcentery = 150-pos;
   snode[i].pcenterx = 200;
   panel.vector.add(snode[i]);
   pos = pos+10;
  }
  panel.gameover = false;
  panel.dir = 'D';
  panel.repaint();
 }
        //function to be called on the click of instructions
 public void instruct(){
  JOptionPane.showMessageDialog(this, "1. Ctrl+R - Restart \n2. S - Increase Snake speed \n3. D - Decrease Snake speed \n4. LEFT - Turn left \n5. RIGHT - Turn right \n6. UP - go up \n7. DOWN - go down \n8. Ctrl+I - to view Instructions", "Instructions",1);
 }
 public static void main(String[] ar){
  new Snake_game();// object of the game class
 }
}

//a panel where all the drawings take place and it is embedded into JFrame
class snake extends JPanel implements Runnable{
 Vector<snake_node> vector = null;   //vector which will hold all the beads of snake body
 snake_node[] snode = null;
 int centx = 0, centy = 0;
 int inc = 10, pos = 0;
 char dir = 'D';
 Dimension dim = null;
 Thread t = null;
 boolean b = true, gameover = false;
 snake(){
  vector = new Vector();
  snode = new snake_node[5];
  for(int i =0; i < 5; i++){
   snode[i] = new snake_node();
   snode[i].centerx = 200;
   snode[i].centery = 150-pos;
   snode[i].pcentery = 150-pos;
   snode[i].pcenterx = 200;
   vector.add(snode[i]);
   pos = pos+10;
  }
  t = new Thread(this);
  this.setLayout(null);
  this.setBackground(Color.black);
  this.setDoubleBuffered(true);
  dim = this.getSize();
  this.addKeyListener(new KeyAdapter(){public void keyTyped(KeyEvent e){keyPress(e);}});
  this.setVisible(true);
 }
 int time = 70;
 boolean gamepause = true;
        //setting keyevents 
 void keyPress(KeyEvent e){
  if(e.getKeyCode() == KeyEvent.VK_DOWN){
   if(dir != 'U')
    dir = 'D';
  }
  else if(e.getKeyCode() == KeyEvent.VK_UP){
   if(dir != 'D')
    dir = 'U';
  }
  else if(e.getKeyCode() == KeyEvent.VK_LEFT){
   if(dir != 'R')
    dir = 'L';
  }
  else if(e.getKeyCode() == KeyEvent.VK_RIGHT){
   if(dir != 'L')
    dir = 'R';
  }
  else if(e.getKeyCode() == KeyEvent.VK_ESCAPE)
   System.exit(0);
  else if(e.getKeyCode() == KeyEvent.VK_SPACE){
   if(gamepause){
    t.suspend();
    gamepause = false;
   }
   else{
    t.resume();
    gamepause = true;
   }
  }
  else if(e.getKeyCode() == KeyEvent.VK_S){
   time--;
  }
  else if(e.getKeyCode() == KeyEvent.VK_D){
   time++;
  }
  
 }
 //generating random position of food
 int foodx = 20+(int)(Math.random()*56)*10;
 int foody = 20+(int)(Math.random()*52)*10;
 int score = 0;
 public void paintComponent(Graphics g){
  super.paintComponent(g);
  Graphics2D g2 = (Graphics2D)g;
  score = vector.size()-5;
  g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  int red = 30+(int)(Math.random()*220);
  int green = 30+(int)(Math.random()*220);
  int blue = 30+(int)(Math.random()*220); 
  g2.setColor(Color.red);
  g2.drawRect(600, 0, 199, 550);
  g2.setColor(Color.orange);
  g2.setFont(new Font("bauhaus 93", 1, 50));
  g2.drawString("Snake", 630, 80);
  g2.setFont(new Font("Arial", 1, 20));
  g2.drawString("Score: "+score,650, 230);
  g2.fillRect(0, 0, dim.width-200, dim.height);
  g2.setColor(Color.black);
  g2.fillRect(10, 10, dim.width-220, dim.height-65);
  g2.setColor(new Color(red, green, blue));
  g2.fillOval(foodx, foody, 10, 10);
  g2.setColor(Color.red);
                //if game over then it will be display on screen
  if(gameover){
   g2.setFont(new Font("Monotype Corsiva", 1, 120));
   g2.drawString("Game Over", 60, 260);
   g2.setFont(new Font("typewriter",1,14));
   g2.drawString("This game is made by", 220, 330);
   g2.drawString("Sumit Kumar", 255, 370);
   g2.setColor(Color.yellow);
   g2.drawString("E-mail: sumit.kumar1310@gmail.com", 170, 410);
   //t.stop();
  }
  else{   
   g2.fillOval(vector.get(0).centerx, vector.get(0).centery, vector.get(0).radius, vector.get(0).radius);
   for(int i=1; i < vector.size(); i++){
    g2.fillOval(vector.get(i).centerx, vector.get(i).centery, vector.get(i).radius, vector.get(i).radius);
    vector.get(i).pcenterx = vector.get(i).centerx;
    vector.get(i).pcentery = vector.get(i).centery;
    vector.get(i).centerx = vector.get(i-1).pcenterx;
    vector.get(i).centery = vector.get(i-1).pcentery;
   }
  }  
 }
        //important function which will see collision of snake with wall or itself
 void checkOutOfBounds(int x, int y){
  if(x < 10 || x > dim.width-220 || y < 10 || y > dim.height-61){
   gameover = true;
   try{Thread.sleep(1000);}catch(Exception e){}
   repaint();
  }
  else if(x==foodx && y==foody){
   snake_node snode = new snake_node();
   snode.centerx = vector.get(vector.size()-1).pcenterx;
   snode.centery = vector.get(vector.size()-1).pcentery;
   vector.add(snode);
   foodx = 20+(int)(Math.random()*56)*10;
   foody = 20+(int)(Math.random()*52)*10;   
  }
  for(int i=1; i < vector.size(); i++){
   if(x == vector.get(i).centerx && y == vector.get(i).centery){
    gameover = true;
    try{Thread.sleep(1000);}catch(Exception e){}
    repaint();
   }
  }
 }
 
 public void run(){
  
  while (true){
   switch(dir){
    case 'L':
     vector.get(0).centerx = (vector.get(0).centerx-inc);
     vector.get(0).pcenterx = vector.get(0).centerx;
     checkOutOfBounds(vector.get(0).centerx, vector.get(0).centery);
     repaint();
     break;
    case 'R':     
     vector.get(0).centerx = (vector.get(0).centerx+inc);
     vector.get(0).pcenterx = vector.get(0).centerx;
     checkOutOfBounds(vector.get(0).centerx, vector.get(0).centery);
     repaint();
     break;
    case 'U':     
     vector.get(0).centery = (vector.get(0).centery-inc);
     vector.get(0).pcentery = vector.get(0).centery;
     checkOutOfBounds(vector.get(0).centerx, vector.get(0).centery);
     repaint();
     break;
    case 'D':     
     vector.get(0).centery = (vector.get(0).centery+inc);
     vector.get(0).pcentery = vector.get(0).centery;
     checkOutOfBounds(vector.get(0).centerx, vector.get(0).centery);
     repaint();
     break;
   }
   try{
    Thread.sleep(time);
   }
   catch(Exception e){}
  }
 }
}


Save this file as Snake_game.java
Compile : javac Snake_game.java
Run : java Snake_game