Friday, 22 August 2014

JAVA Adapter classes for Mouse event handling

Inheriting from adapter class  saves ours time as we need not  implement all the functions of the interface we want to use.The adapter class
implement that interface and overrides the functions with empty
 body and then we gonna easily inherit the adapter class and use only the required functions.

 For example in the following code  i just used onMouseClicked() ,
 see this for handling Mouse events with adapter class 




import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class GUI extends JFrame {
private String details;
private JLabel statusBar;

public GUI() {
super("title");

statusBar = new JLabel("default stage");

add(statusBar, BorderLayout.SOUTH);
addMouseListener(new MouseClass());


}

// An abstract adapter class for receiving mouse events.
// The methods in this class are empty.
// This class exists as convenience for creating listener objects.
private class MouseClass extends MouseAdapter {


//MouseEvent is an event which indicates that a mouse
//action occurred in a component
public void mouseClicked(MouseEvent e) {
details = "";
details += String.format("I clicked %d ", e.getClickCount());

if(e.isMetaDown())
details += " with right mouse button" ;
else if(e.isAltDown())
details += " with centeer mouse button " ;
else
details += " with left mouse button ";

statusBar.setText(details);

}

}

}

Thursday, 21 August 2014

UVa - 10258- Contests Score Board

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

class Main {
public static void main(String args[]) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

// a string buffer to show ours final result
// A thread-safe, mutable sequence of characters.
// A string buffer is like a String, but can be modified.
// At any point in time it contains some particular sequence of
// characters,
// but the length and content of the sequence can be changed through
// certain
// method calls.

StringBuffer sb = new StringBuffer("");
int cases = Integer.parseInt(in.readLine());
// read the empty line
in.readLine();

// evaluate each case
for (int i = 0; i < cases; ++i) {

// add a new line to string buffer after first line
if (i > 0) {
sb.append("\n");
}

// create object refernce array for all teams
Teams[] teams = new Teams[101];

// initialise all Teams object
for (int j = 0, length = teams.length; j < length; ++j) {

teams[j] = new Teams(j);
}

// a 2d array of int and boolean for mapping total attempts
// to solve a particular question and to know whther a question is
// finally solved by a particular team respectiviely
int ttlAttemptPerQstByTeam[][] = new int[101][10];
boolean questionSolvedByTeam[][] = new boolean[101][10];

String m = "";

// create a boolean array of serial numbers
// to know which team particiapted
boolean[] teamParticipated = new boolean[101];

while ((m = in.readLine()) != null) {
if (m.trim().equals("")) {
break;
}

String[] details = m.split(" ");
int teamNo = Integer.parseInt(details[0]);
teamParticipated[teamNo] = true;
int problem = Integer.parseInt(details[1]);
int penalty = Integer.parseInt(details[2]);
String stat = details[3];

// default value of boolean is false , #SnikItz
if (!questionSolvedByTeam[teamNo][problem]) {
// if the stat is correct "C"
if (stat.equals("C")) {
int currPenality = ttlAttemptPerQstByTeam[teamNo][problem]
* 20 + penalty;
questionSolvedByTeam[teamNo][problem] = true;
teams[teamNo].addsolved();
teams[teamNo].addPenalty(currPenality);


} else if (stat.equals("I")) {
ttlAttemptPerQstByTeam[teamNo][problem]++;
                    }

}

}


 Arrays.sort(teams);
          for (int j = 0 , length = teams.length; j < length; ++j) {
              int num = teams[j].getTeamNumber();
              if ( teamParticipated[num]) {
                  sb.append(teams[j].getTeamNumber()).append(" ").append(teams[j].getSolved()).append(" ").append(teams[j].getPenalty());
                  sb.append("\n");
              }
          }
      }
      System.out.print(sb);
  }
}


class Teams implements Comparable<Teams> {

private int teamNumber, solved, penalty;

public Teams(int n) {
this.teamNumber = n;
this.solved = this.penalty = 0;

}

public int getPenalty() {
return this.penalty;
}

public void setPenalty(int penalty) {
this.penalty = penalty;
}

public void addPenalty(int penalty) {
this.penalty += penalty;
}

public void addsolved() {
this.solved++;
}

public int getSolved() {
return solved;
}

public void setSolved(int solved) {
this.solved = solved;
}

public int getTeamNumber() {
return teamNumber;
}

public void setTeamN(int teamN) {
this.teamNumber = teamN;
}

// Compares this object with the specified object for order.
// Returns a negative integer, zero, or a positive integer as this
// object
// is less than, equal to, or greater than the specified object.

@Override
public int compareTo(Teams o) {
if (this.solved > o.getSolved())
return -1;
else if (this.solved < o.getSolved())
return 1;
// if theres a tie in total correct solved
// check for least penalty time
else {
if (this.penalty > o.getPenalty())
return 1;
else {
if (this.teamNumber > o.getTeamNumber()) {
return 1;
} else {
return -1;
}

}

}

}

}

Friday, 15 August 2014

JAVA -Mouse event and Motion event listener

We will be handling various mouse event and mouse motion events in this implementation.

We gonna refresh ours green days of disney time when Micky mouse used to hang around with his Mini lol


Interfaces and the function -
MouseListener -

                      mouseClicked() , mousePressed() , mouseEntered() , mouseReleased() , mouseExit()

MouseMotionListener -
                        
                       mouseDragged() , mouseMoved()

Main Class

import javax.swing.JFrame;


public class Main extends JFrame {
public static void main(String[]  args){
GUI go = new GUI();

//defines the operation done on closing the app , programme terminates
//exit the JFrame 
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//set the frame size
go.setSize(275, 275);

//set visibility
go.setVisible(true);
}
}


Mouse Listener class

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class GUI extends JFrame {

private JPanel mousePanel;
private JLabel statusBar;

// constructor
public GUI() {

super("Micky the Mouse");

mousePanel = new JPanel();
mousePanel.setBackground(Color.WHITE);
add(mousePanel, BorderLayout.CENTER);

statusBar = new JLabel("Micky's sweet home");
add(statusBar, BorderLayout.SOUTH);

HandlerClass handler = new HandlerClass();

// Add the specified mouse listener to receive mouse
// events and motion events from this component.
mousePanel.addMouseListener(handler);
mousePanel.addMouseMotionListener(handler);

}

private class HandlerClass implements MouseListener, MouseMotionListener {

// mouse motion event
// Invoked when a mouse button is pressed on a component and then
// dragged
@Override
public void mouseDragged(MouseEvent e) {
statusBar.setText("Mouse dragged");

}

// Invoked when the mouse cursor has been moved onto a
// component but no buttons have been pushed
@Override
public void mouseMoved(MouseEvent e) {
statusBar.setText("Micky Mouse movin");

}

// mouse event

// Invoked when the mouse button has been clicked
// (pressed and released) on a component
@Override
public void mouseClicked(MouseEvent e) {
statusBar.setText(String.format("Micky mouse clicked at %d ,  %d ",
e.getX(), e.getY()));

}

// Invoked when a mouse button has been pressed on a component
@Override
public void mousePressed(MouseEvent e) {
statusBar.setText("micky mouse pressed");

}

// Invoked when a mouse button has been released on a component.
@Override
public void mouseReleased(MouseEvent e) {
statusBar.setText("u released micky Mouse ");

}

// Invoked when the mouse enters a component.
@Override
public void mouseEntered(MouseEvent e) {
statusBar.setText("MMicky mouse entered the arena");
mousePanel.setBackground(Color.BLACK);

}

@Override
public void mouseExited(MouseEvent e) {
statusBar.setText("Micky Mouse went to sleep zzzzzzzZZZ  ");
mousePanel.setBackground(Color.WHITE);

}

}


}





JAVA -JList multiple selection list

An implementation of JList to select multiple girl's name and enjoy dumping them lol

Basically we gonna select multiple list items from left and show them at right list with click event of button pressed ,with java's inbuilt function , while setting action listener  for button  -

any_list_name.setListData(any_other_list_name.getSelectedValues()); 


Main class-
import javax.swing.JFrame;


public class Main extends JFrame {
public static void main(String[]  args){
GUI go = new GUI();

//defines the operation done on closing the app , programme terminates
//exit the JFrame 
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//set the frame size
go.setSize(275, 275);

//set visibility
go.setVisible(true);
}

}


JList with multiple selection -

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;

public class GUI extends JFrame{

private JList leftList, rightList;
private static String[] girls = { "jenny", "lopez", "stacy",
"jessica", "avril", "cheryl", "cher" };
private JButton moveButton;



//constructor
public GUI(){

super("dump em up");
setLayout(new FlowLayout());
leftList =  new JList(girls);
leftList.setVisibleRowCount(3);
//set the left list to select multiple list items
leftList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
//add the view 
add(new JScrollPane(leftList));

//set the button and its functionality
moveButton = new JButton("Dump em up :P ----> ");
moveButton.addActionListener(
// create an anonymous class
new ActionListener(){
public void  actionPerformed(ActionEvent event){
//Returns an array of all the selected values, 
//in increasing order based on their indices in the list.

rightList.setListData(leftList.getSelectedValues());

}
}
);
add(moveButton);

rightList = new JList();
rightList.setVisibleRowCount(3);
rightList.setFixedCellWidth(100);
rightList.setFixedCellHeight(15);
rightList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
//add the view 
add(new JScrollPane(rightList));


}


}








JAVA - JList

An example of JAVA's SWING  JList  .

To display the selected color from list and change the background
I choosed black, coz its my favourite ... lol 

Main class -

import javax.swing.JFrame;


public class Main  extends JFrame{
public static void main(String args[]){
GUI go = new GUI();
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.setSize(300,200);
go.setVisible(true);
}


}


JList functionality class - 


import java.awt.Color;
import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;


public class GUI extends JFrame {
private JList list;
private static String[] colorNames = {"red", "blue" , "black", "red", "blue" , "black","red", "blue" , "black"};
private static  Color[] colors= {Color.RED ,Color.BLUE ,Color.BLACK, Color.RED ,Color.BLUE ,Color.BLACK ,Color.RED ,Color.BLUE ,Color.BLACK};

//constructor
public GUI(){
super("Title");
setLayout(new FlowLayout());
//initialise  list with color names to select
list = new JList(colorNames);
//set visible row count 
list.setVisibleRowCount(9);
//set the list selection mode
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//add the list view 
//JScrollPane  displays the contents of the specified component, 
//where both horizontal and vertical scrollbars
//appear whenever the component's contents are larger than the view
add(new JScrollPane(list));
//add  a listener to the list, to be notified each time a change 
//to the selection occurs; the preferred way of listening for 
//selection state changes.
list.addListSelectionListener(
new ListSelectionListener(){
public void valueChanged(ListSelectionEvent event){
//set backgroud via content pane
// there are three layers of a view - background ,glass , content 
getContentPane().setBackground(colors[list.getSelectedIndex()]);
}
}
);
}
}


Thursday, 7 August 2014

Java - Stack using Linked List



/*
 * Implements a generic type of node to implement a generic stack  - see  here - using a generic linked list
 */

public class Node<E> {
// instance variables
private E element;
private Node<E> next;

// create a node with null references
public Node() {
this(null, null);
}
   //create a node with the given elemment and next node
public Node(E e , Node<E> n){
element = e;
next = n ;
}

//accessor methods
public E getElement(){
return element;
}
public Node<E> getNext(){
return next;
}

//modifier methods 
public void setElement(E newElem){
this.element =  newElem ;
}

public void setNext(Node<E> newNext){
next = newNext;
}
}





/*
 * Implements the Stack interface  - see  here - using a singly linked list , whose nodes are objects of class Node 
 * All mehtods of Stack interface are executed in constant time 
 * Space requirement - O(n)
 * New exception  creation for overflow problem is not required , unlike arrays based stack 
 * 
 */

import java.util.EmptyStackException;
public class NodeStack<E> implements Stack<E> {
protected Node<E> top;// reference to head
protected int size;

// construct an empty stack
public NodeStack() {
top = null;
size = 0;
}

@Override
public int size() {
return size;
}

@Override
public boolean isEmpty() {
if (top == null)
return true;
return false;
}

@Override
public E top() throws EmptyStackException {
if(isEmpty()) throw new EmptyStackException();
return top.getElement();
}

@Override
public void push(E element) {
Node<E> v = new Node<>(element, top); // create and link in a new node
top = v;
++size;
}



@Override
public E pop() {
if(isEmpty()) throw new EmptyStackException();
E temp =  top.getElement();
top = top.getNext(); //  link out former top node 
--size;
return temp ; 
}


}


Stack - An implementation using Arrays


Stack Interface

import java.util.EmptyStackException;

/*
 * Interface for a stack : collection of objects over principle of LIFO , including main
 * method from java.util.Stack
 * @see EmptyStackException
 */

public interface Stack<E> {

//@return number of elements in stack
public int size();

//@return true if the stack is empty , false otherwise
public boolean isEmpty();

/*
* @return top element in the stack
* @exception EmptyStackException if the stack is empty.
*/
public E top() throws EmptyStackException;

//@param element to be inserted
public void push(E element);

/*
* @return element removed
* @exception EmptyStackException if the stack is empty
*/
public E pop();

}



Stack Implementation

import java.util.EmptyStackException;

/*
 * Implementation of the stack Abstract Data Type (ADT) using fixed length array
 * An exception is thrown if a push operation is attempted when the size of the 
 * stack is equal to the length of the array
 */
public class ArrayStack<E> implements Stack<E> {
protected int capacity; // actual capacity of the stack array
public static final int CAPACITY = 1000; // default array capacity
protected E S[]; // generic array used to implement the stack
protected int top = -1; // index of the top of the stack

// constructor
public ArrayStack() {
this(CAPACITY); // default capacity
}

public ArrayStack(int cap) {
capacity = cap;
S = (E[]) new Object[capacity]; // compiler may generate warning , but
// chillax , its ok

}

@Override
public int size() {
return (top + 1);
}

@Override
public boolean isEmpty() {
return (top < 0);
}

@Override
public E top() throws EmptyStackException {
if (isEmpty())
throw new EmptyStackException() ; //"Stack Is Empty";
return S[top];
}

@Override
public void push(E element) throws FullStackException {

if (size() == capacity)
throw new FullStackException("Stack is full");
S[++top] = element;

}

@Override
public E pop() throws EmptyStackException {
E element;
if (isEmpty())
throw new EmptyStackException("Stack Is Empty");
element = S[top];
S[top--] = null; // dereference S[top] for garabage collection
return element;

}

public String toString() {
String s;
s = "[";
if (size() > 0)
s += S[0];
if (size() > 1)
for (int i = 1; i <= (size() - 1); ++i) {
s += ", " + S[i];
}
return s + "] ";
}

// prints status info about recent operation on stack
public void status(String op, Object element) {
System.out.println("--------> " + op); // print this operation
System.out.println(" , returns " + element); // what was returned
System.out.println("result: size = " + size() + " , isEmpty = "
+ isEmpty());
System.out.println(" , stack: " + this);// contents of the stack i.e a
// call to toString(
}
public static void main(String[] args ){
Object o;
ArrayStack<Integer> A = new ArrayStack<>();
A.status("new ArrayStack<Integer> A ", null);
A.push(1);
A.status("A.push(1) ", null);
o = A.pop();
A.status(" A.pop() ", o);
A.push(7);
A.status(" A.push(7) ", null);
o = A.pop();
A.status("A.pop() ", o);

ArrayStack<String> B = new ArrayStack<>();
B.status("new ArrayStack<String> B ", null);
B.push("dont");
B.status("B.push(\"dont\") ", null);
B.push("stop");
B.status("B.push(\"stop\") ", null);
B.push("till");
B.status("B.push(\"till\") ", null);
B.push("u");
B.status("B.push(\"u\") ", null);
B.push("get");
B.status("B.push(\"get\") ", null);
B.push("enough");
B.status("B.push(\"enough\") ", null);
o = B.pop();
B.status("B.pop() ", o);


}
}



Result -


--------> new ArrayStack<Integer> A 
 , returns null
result: size = 0 , isEmpty = true
 , stack: [] 
--------> A.push(1) 
 , returns null
result: size = 1 , isEmpty = false
 , stack: [1] 
-------->  A.pop() 
 , returns 1
result: size = 0 , isEmpty = true
 , stack: [] 
--------> A.push(7) 
 , returns null
result: size = 1 , isEmpty = false
 , stack: [7] 
--------> A.pop() 
 , returns 7
result: size = 0 , isEmpty = true
 , stack: [] 
--------> new ArrayStack<String> B 
 , returns null
result: size = 0 , isEmpty = true
 , stack: [] 
--------> B.push("dont") 
 , returns null
result: size = 1 , isEmpty = false
 , stack: [dont] 
--------> B.push("stop") 
 , returns null
result: size = 2 , isEmpty = false
 , stack: [dont, stop] 
--------> B.push("till") 
 , returns null
result: size = 3 , isEmpty = false
 , stack: [dont, stop, till] 
--------> B.push("u") 
 , returns null
result: size = 4 , isEmpty = false
 , stack: [dont, stop, till, u] 
--------> B.push("get") 
 , returns null
result: size = 5 , isEmpty = false
 , stack: [dont, stop, till, u, get] 
--------> B.push("enough") 
 , returns null
result: size = 6 , isEmpty = false
 , stack: [dont, stop, till, u, get, enough] 
--------> B.pop() 
 , returns enough
result: size = 5 , isEmpty = false
 , stack: [dont, stop, till, u, get] 


Sunday, 3 August 2014

UVa 612 - DNA Sorting


/*
 * @author Divyanshu
 * @mail divyanshu17x@gmail.com
 * @place GNDU RC SATHIALA
 * @judge uva.onlinejudge.org
 * @verdict Accepted 
 * @problem UVa-612 -DNA SORTING
 * @problemType  stable_sort based on inversion index count

 */


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.TreeSet;

class Main {
public static void main(String args[]) throws IOException {

class NodeTree implements Comparable<NodeTree> {
//inversion index is total swap required to swap an array in order
int inversionIndex = 0, position;
char array[];

public NodeTree(int pos, char array[]) {
this.position = pos;
this.array = array;
//calculate the inverion index as per the problem spec of comparing DNA CODE character
for(int i = 0 , length = array.length; i < length; ++i )
{
for(int j = i+1 ; j<length ; ++j)
{
// if the character compared are out of order , increment the inversion index
if(array[j] < array[i] )++inversionIndex;
}
}
}

/*
* do the natural ordering of the nodes in tree as per specs . the
* natural odering will be feeded to TreeSet for inorder ascending
* order sorting with log(n) commplexity basically we just gotta find
* out the order( to place a node earlier or later)of a node with
* respect to other node as per specs rest the tree set will
* automate the sorting order for each node added.
* finally a stable sort is accomplished
*/
@Override
public int compareTo(NodeTree o) {
if (this.inversionIndex != o.inversionIndex) {
return this.inversionIndex - o.inversionIndex;
}
return this.position - o.position;
}

}
// initialise reader
Reader.init(System.in);
int cases = Reader.nextInt();

//usin a string buffer for showing DNA sorted code strings in a file
StringBuffer sb = new StringBuffer();
while (cases-- > 0) {
// input length and total DNA code strings
int length = Reader.nextInt(), ttlCodes = Reader.nextInt();

TreeSet<NodeTree> set = new TreeSet<>();
int pos;

// input DNA code strings
// and add each string as a NodeTree object to a TreeSet
for ( pos = 0; pos++ < ttlCodes ;) {

set.add(new NodeTree(pos, Reader.reader.readLine().trim()
.toCharArray()));
}
//print the DNA data set as required
for(NodeTree n : set )
{
//new String object Allocates a new String so that it represents 
//the sequence of characters currently contained in the character array argument.
sb.append(new String(n.array)+"\n");
}

if(cases > 0) sb.append("\n");

}
System.out.print(new String(sb));

}

}

/** Class for buffered reading int and double values */

class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;

/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}

/** get next word */
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}

static int nextInt() throws IOException {
return Integer.parseInt(next());
}

}