Friday, 4 October 2013

DM FINDING MISSING VALUE CODE IN JAVA

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Finder {

/**
* @param args
*/
public static void main(String[] args) {
String csvFile = "E:/Documents and Settings/student/Desktop/sample data 1.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
String[] reader;
File file = new File("E:/Documents and Settings/student/Desktop/sample data without nulls.csv");
FileWriter fw = null;
int count=0;
try {
fw = new FileWriter(file.getAbsoluteFile());

BufferedWriter bw = new BufferedWriter(fw);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
        // use comma as separator
reader = line.split(cvsSplitBy);
//System.out.println("Age " + country[1]  + "Marital Status" + country[3]);
for(int i=0;i<5;i++){
if(reader[i].length()==0) {
reader[i]="missing";
count++;
}
}
bw.write(reader[0]+","+reader[1]+","+reader[2]+","+reader[3]+","+reader[4]+"\n");
}
bw.close();
System.out.println("Number of missing values="+count+"Done");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();

 finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
 }
}
}


DM APRIORI ALGORITHM CODE IN JAVA


import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;


public class AprioriAlgo {

/**
* author: shwetha

* Execution:
* Enter Minimum Support.....
* 3
* Enter Transactions.....Bread,Milk
* Bread,Diaper,Beer,Eggs
* Milk,Diaper,Beer,Cola
* Bread,Milk,Diaper,Beer
* Bread,Milk,Diaper,Cola

*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in=new Scanner(System.in);
ArrayList<String> al=new ArrayList<String>();
ArrayList<String> out=new ArrayList<String>();
ArrayList<String> dup=new ArrayList<String>();
ArrayList<String> mutex=new ArrayList<String>();
int n=1,y=0,cnt;
int[] len=new int[10];
int minsupport;
String str;
String[] temp,temp1;
String[][] splitstr = new String[10][10];
int x=0,k=0,z=0,p=0;
System.out.println("Enter Minimum Support.....");
minsupport=in.nextInt();
System.out.print("Enter Transactions.....");
//in.reset();
in.nextLine();
while((str=in.nextLine()).length()!=0){
temp=str.split(",");
len[y++]=temp.length;
for(int i=0;i<temp.length;i++){
splitstr[x][i]=temp[i];
if(!al.contains(temp[i]))
al.add(temp[i]);
out.add(temp[i]);
}
x++;
}
//minsupport=(int) ((x-1)*0.7);
//minsupport=3;
Collections.sort(al);
boolean test=true;
while(test){
System.out.println("\nCandidate "+n+" Item set");
System.out.print("\nItems\t Support");
out.clear();
for(String s:al){
temp=s.split(",");
System.out.print("\n"+s);
y=0;
for(int i=0;i<x;i++){
z=0;
for(int j=0;j<temp.length;j++){
for(k=0;k<len[i];k++){
if(temp[j].equals(splitstr[i][k])) z++;
}
}
if(z==temp.length)y++;
}
if(y>=minsupport){
out.add(s);
if(n==1)
dup.add(s);
}
else
mutex.add(s);
System.out.print("\t"+y);
}
n++;
al.clear();
for(int i=0;i<out.size();i++){
for(int j=i;j<dup.size();j++){
if(!out.get(i).contains(dup.get(j))){
al.add(out.get(i)+","+dup.get(j));
}
}
}
for(int i=0;i<al.size();i++){
temp=al.get(i).split(",");
for(int j=i+1;j<al.size();j++){
cnt=0;
temp1=al.get(j).split(",");
for(k=0;k<temp.length;k++){
if(al.get(i).contains(temp1[k])) cnt++;
}
if(cnt==3){
al.remove(j);
}
}
}
//System.out.println(al);

for(int i=0;i<mutex.size();i++){
temp=mutex.get(i).split(",");
for(int j=0;j<al.size();j++){
temp1=al.get(j).split(",");
p=0;
for(k=0;k<temp1.length;k++){
for(z=0;z<temp.length;z++){
if(temp1[k].equals(temp[z])) {
p++;
break;
}
}
//if(p==temp.length)break;
}
if(p==temp.length){al.remove(j);
//System.out.println("yay");
}
}
}
//System.out.println(mutex);
if(out.size()==0)
test=false;
}
}

}

Thursday, 4 July 2013

BINARY TREE TRAVERSAL TYPES

      

         1.  PREORDER 


  •  ROOT OF THE TREE
  •  LEFT SUBTREE
  •  RIGHT SUBTREE

       2. POSTORDER

  •   LEFT SUBTREE
  •   RIGHT SUBTREE
  •   ROOT OF THE TREE

      3. INORDER

  • LEFT SUBTREE
  • ROOT OF THE TREE
  • RIGHT SUBTREE 

Monday, 3 June 2013

Java thread program for clock using JApplet

import java.awt.*;
import java.util.*;import java.text.DateFormat;

@SuppressWarnings("serial")
public class Clock  extends java.applet.Applet implements Runnable
{
      private Thread threadClock=null;
      public void init()
      {
            setBackground(Color.white);
      }
      public void start()
      {
            if(threadClock==null)
            {
                  threadClock=new Thread(this,"CLOCK");
                  threadClock.start();
                 
            }
      }
      public void run()
      {
            Thread threadCurrent= Thread.currentThread();
            while(threadClock==threadCurrent){
                  repaint();
                  try
                  {
                        Thread.sleep(1000);
                  }
                  catch(InterruptedException e)
                  {
                 }
      }
      }
             
            public void paint(Graphics g)
            {
                  Font font=new Font("arial",Font.BOLD,28);
                  g.setFont(font);
                  g.setColor(Color.blue);
                  Calendar calci= Calendar.getInstance();
                  Date CurrentTime= calci.getTime();
                  DateFormat dtFormat= DateFormat.getTimeInstance();
                  g.drawString(dtFormat.format(CurrentTime),95,100);
            }
           
            public void stop()
            {
           
                  threadClock=null;
            }
     
     
           
      }
     
                 
                 




Saturday, 11 May 2013

Java application for simple calculator using swings


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Calculator extends JFrame implements ActionListener,Runnable
{
  JButton bnum[];
  JButton bback,bce,bc;
  JButton bop[],jdb;
  JLabel jl;
  JTextField tf;
  JPanel p1,p2,p3;
  JDialog jd;
  double d1,d2,d3;
  //long n1,n2,n3;
  boolean frac=false;
  char op;
  boolean opc=false,ope=false;
  public void run()
  {
    while(true)
    {
      char ch=getTitle().charAt(0);
      setTitle(getTitle().substring(1,getTitle().length())+Character.toString(ch));
      try{
       Thread.sleep(200);
      }catch(InterruptedException ie){
       System.out.println(ie);
      }
    }
  }
  public Calculator(String str)
  {
    super(str);
    bnum=new JButton[10];
    jd=new JDialog(this,"Message",true);
    jdb=new JButton("OK");
    jl=new JLabel();
    jd.setLayout(new FlowLayout());
    jdb.setMargin(new Insets(2,5,2,5));
    jd.add(jl); jd.add(jdb);
    jdb.addActionListener(this);
    for(int i=0;i<10;i++)
      bnum[i]=new JButton(Integer.toString(i));
    bback=new JButton("Back");
    bce=new JButton("CE");
    bc=new JButton("C");
    p2=new JPanel();
    p2.setLayout(new FlowLayout());
    p2.add(bback);
    p2.add(bce);
    p2.add(bc);
    tf=new JTextField(15);
    p1=new JPanel();
    p1.add(tf);
    tf.setEditable(false);
    tf.setHorizontalAlignment(JTextField.RIGHT);
    tf.setText("0.");
    tf.setBackground(Color.white);
    tf.setFont(new Font("Dialog",Font.BOLD,12));
    //System.out.println(tf.getFont());
    bop=new JButton[10];
    bop[0]=new JButton("+");
    bop[1]=new JButton("-");
    bop[2]=new JButton("*");
    bop[3]=new JButton("/");
    bop[4]=new JButton(".");
    bop[5]=new JButton("=");
    bop[6]=new JButton("%");
    bop[7]=new JButton("Sqrt");
    bop[8]=new JButton("1/x");
    bop[9]=new JButton("+/-");
    for(int i=0;i<10;i++){
      bop[i].setMargin(new Insets(2,2,2,2));
      bop[i].addActionListener(this);
    }
    p3=new JPanel();
    p3.setLayout(new GridLayout(4,5,5,5));
    p3.add(bnum[1]);
    p3.add(bnum[2]);
    p3.add(bnum[3]);
    p3.add(bop[0]);
    p3.add(bop[7]);
    p3.add(bnum[4]);
    p3.add(bnum[5]);
    p3.add(bnum[6]);
    p3.add(bop[1]);
    p3.add(bop[8]);
    p3.add(bnum[7]);
    p3.add(bnum[8]);
    p3.add(bnum[9]);
    p3.add(bop[2]);
    p3.add(bop[6]);
    p3.add(bnum[0]);
    p3.add(bop[9]);
    p3.add(bop[4]);
    p3.add(bop[3]);
    p3.add(bop[5]);
    Container c=getContentPane();
    c.setLayout(new FlowLayout());
    c.add(p1);
    c.add(p2);
    c.add(p3);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setResizable(false);
    for(int i=0;i<=6;i++)
      bop[i].setFont(new Font("Dialog",Font.BOLD,13));
    for(int i=0;i<10;i++){
      bnum[i].addActionListener(this);
      bnum[i].setMargin(new Insets(2,10,2,10));
    }
    bce.addActionListener(this);
    bc.addActionListener(this);
    bback.addActionListener(this);
  }
  public void actionPerformed(ActionEvent ae)
  {
    String s=tf.getText();
    String str;
    if(!frac)
      str=s.substring(0,s.length()-1);
    else
      str=s;
    if(ae.getSource()==bback)
    {
      if(frac){
       if(str.charAt(str.length()-1)=='.')
        frac=false;
       else tf.setText(str.substring(0,str.length()-1));
      }
      else{
      if(!str.equals("0"))
       tf.setText(str.substring(0,str.length()-1)+".");
      }
      if(tf.getText().equals("."))
       tf.setText("0.");
    }
    else if(ae.getSource()==bce)
    {
      tf.setText("0.");
      frac=false;
      opc=false;
    }
    else if(ae.getSource()==bc)
    {
      tf.setText("0.");
      d1=0;
      d2=0;
      frac=false;
      opc=false;
      ope=false;
    }
    else if(ae.getSource()==bop[0])
    {
      if(ope){
       d2=Double.parseDouble(str);
       d3=calc(d1,d2,op);
       String dn=Double.toString(d3);
       if(dn.charAt(dn.length()-1)=='0')
        dn=dn.substring(0,dn.length()-1);
       tf.setText(dn);
       ope=false;
       str=dn;
      }
      d1=Double.parseDouble(str);
      opc=true;
      op='+';
    }
    else if(ae.getSource()==bop[1])
    {
      if(ope){
       d2=Double.parseDouble(str);
       d3=calc(d1,d2,op);
       String dn=Double.toString(d3);
       if(dn.charAt(dn.length()-1)=='0')
        dn=dn.substring(0,dn.length()-1);
       tf.setText(dn);
       ope=false;
       str=dn;
      }
      d1=Double.parseDouble(str);
      opc=true;
      op='-';
    }
    else if(ae.getSource()==bop[2])
    {
      if(ope){
       d2=Double.parseDouble(str);
       d3=calc(d1,d2,op);
       String dn=Double.toString(d3);
       if(dn.charAt(dn.length()-1)=='0')
        dn=dn.substring(0,dn.length()-1);
       tf.setText(dn);
       ope=false;
       str=dn;
      }
      d1=Double.parseDouble(str);
      opc=true;
      op='*';
    }
    else if(ae.getSource()==bop[3])
    {
      if(ope){
       d2=Double.parseDouble(str);
       d3=calc(d1,d2,op);
       String dn=Double.toString(d3);
       if(dn.charAt(dn.length()-1)=='0')
        dn=dn.substring(0,dn.length()-1);
       tf.setText(dn);
       ope=false;
       str=dn;
      }
      d1=Double.parseDouble(str);
      opc=true;
      op='/';
    }
    else if(ae.getSource()==bop[4])
    {
      frac=true;
    }
    else if(ae.getSource()==bop[5])
    {
      if(ope)
      {
       d2=Double.parseDouble(str);
       d3=calc(d1,d2,op);
       String dn=Double.toString(d3);
       if(dn.charAt(dn.length()-1)=='0')
        dn=dn.substring(0,dn.length()-1);
       tf.setText(dn);
       d1=d3;
       opc=false;
       ope=false;
      }
    }
    else if(ae.getSource()==bop[6])
    {
      if(ope)
      {
       double temp=Double.parseDouble(tf.getText());
       String tmp=Double.toString(d1*temp/100);
       if(tmp.charAt(tmp.length()-1)=='0')
        tmp=tmp.substring(0,tmp.length()-1);
       tf.setText(tmp);
      }
      else
       tf.setText("0.");
    }
    else if(ae.getSource()==bop[7])
    {
      double temp=Double.parseDouble(tf.getText());
      String tmp=Double.toString(Math.sqrt(temp));
      if(tmp.charAt(tmp.length()-1)=='0')
       tmp=tmp.substring(0,tmp.length()-1);
      tf.setText(tmp);
    }
    else if(ae.getSource()==bop[8])
    {
      double temp=Double.parseDouble(tf.getText());
      String tmp=Double.toString(1/temp);
      if(tmp.equals("Infinity")){
       jl.setText("Cannot divided by zero");
       jd.setSize(150,90);
       jd.setResizable(false);
       jd.setVisible(true);
      }
      else{
      if(tmp.charAt(tmp.length()-1)=='0')
       tmp=tmp.substring(0,tmp.length()-1);
      tf.setText(tmp);
      }
    }
    else if(ae.getSource()==bop[9])
    {
      double temp=Double.parseDouble(tf.getText());
      if(temp!=0){
      String tmp=Double.toString(-1*temp);
      if(tmp.charAt(tmp.length()-1)=='0')
       tmp=tmp.substring(0,tmp.length()-1);
      tf.setText(tmp);
      }else tf.setText("0.");
    }
    else if(ae.getSource()==jdb)
    {
      jd.setVisible(false);
    }
    else
    {
      if(opc){
       tf.setText("0.");
       frac=false;
       str="0";
       ope=true;
       opc=false;
      }
      if(frac)
       tf.setText(str+ae.getActionCommand());
      else{
      if(str.equals("0")){
       tf.setText("");
       tf.setText(ae.getActionCommand()+".");
      }
      else
       tf.setText(str+ae.getActionCommand()+".");
      }
    }
  }
  public double calc(double a,double b,char ch)
  {
    double c=0;
    switch(ch)
    {
      case '+':
       c=a+b;
       break;
      case '-':
       c=a-b;
       break;
      case '*':
       c=a*b;
       break;
      case '/':
       c=a/b;
       break;
    }
    return c;
  }
  public static void main(String[] args) 
  {
    Calculator c=new Calculator("Calculator      ");
    c.setSize(210,250);
    c.setVisible(true);
    Thread t=new Thread(c);
    t.start();
  }
}

Java application for tic tac toe using swings


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TicTacToe implements ActionListener
{
//Instance Variables
private int[][] winCombinations = new int[][] {
{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, //horizontal wins
{0, 3, 6}, {1, 4, 7}, {2, 5, 8}, //virticle wins
{0, 4, 8}, {2, 4, 6} //diagonal wins
};
private JFrame window = new JFrame("Tic-Tac-Toe");
private JButton buttons[] = new JButton[9];
private int count = 0;
private String letter = "";
private boolean win = false;
private static int startCount =0;
JMenuBar menu = new JMenuBar();
JMenuItem newGame = new JMenuItem("New Game"),
instr = new JMenuItem("Instructions"),
exit = new JMenuItem("Exit"),
name = new JMenuItem("Change Name");
static String x = "X";
static String y = "Y";

public TicTacToe()
{
//Create Window
window.setSize(370,370);
window.setLocationRelativeTo(null);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(new GridLayout(3,3));

//Add Buttons To The Window
for(int i=0; i<=8; i++)
{
buttons[i] = new JButton();
window.add(buttons[i]);
buttons[i].addActionListener(this);
}

menu.add(newGame);
menu.add(name);
menu.add(instr);
menu.add(exit);

name.addActionListener(this);
newGame.addActionListener(this);
exit.addActionListener(this);
instr.addActionListener(this);
window.setJMenuBar(menu);
//Make The Window Visible
window.setVisible(true);
}

public void setName()
{
x = JOptionPane.showInputDialog(null, "Enter Name of player X: ", "", 1);
y = JOptionPane.showInputDialog(null, "Enter Name of player O: ", "", 1);
if(x==null)
{
x = "X";
}
if(y==null)
{
y = "O";
}
if(x.length()==0)
{
x = "X";
}
if(y.length()==0)
{
y = "O";
}
JOptionPane.showMessageDialog(null, "Your names have been set\nTo change your names click on the Change name button in the menu bar","Name Changed!!!",JOptionPane.INFORMATION_MESSAGE);
}

/**
When an object is clicked, perform an action.
@param a action event object
*/
public void actionPerformed(ActionEvent a)
{
Object source = a.getSource();
//System.out.println(str1+"\t"+str2);

if(source == newGame)
{
int answer = JOptionPane.showConfirmDialog(null, "Your current game will not be saved...\nContinue Anyways??", "Do you want to start a new game?", JOptionPane.YES_NO_OPTION);

if (answer == JOptionPane.YES_OPTION)
{
this.clearIt();
}

}
else if(source == name)
{
this.setName();

}
else if(source == instr)
{
JOptionPane.showMessageDialog(null, "Your goal is to be the first player to get 3 X's or O's in a row. (horizontally, diagonally, or vertically)","Instructions",JOptionPane.INFORMATION_MESSAGE);
}
else if(source == exit)
{
int answer = JOptionPane.showConfirmDialog(null, "EXIT", "Are You sure you want to exit??", JOptionPane.YES_NO_OPTION);

if (answer == JOptionPane.YES_OPTION)
{
JOptionPane.showMessageDialog(null, "Thank you " + x+ " and " + y + " for playing");
System.exit(0);
}
}
else
{
count++;

/*Calculate whose turn it is*/
if(count % 2 == 0)
{
letter = "O";
}
else
{
letter = "X";
}

/*Write the letter to the button and deactivate it*/
JButton pressedButton = (JButton)source;
pressedButton.setText(letter);
pressedButton.setEnabled(false);

/*Determine who won*/
for(int i=0; i<=7; i++)
{
if( buttons[winCombinations[i][0]].getText().equals(buttons[winCombinations[i][1]].getText()) &&
buttons[winCombinations[i][1]].getText().equals(buttons[winCombinations[i][2]].getText()) &&
buttons[winCombinations[i][0]].getText() != "")
{
win = true;
}
}

/*Show a dialog when game is over*/
if(win == true)
{
if(letter.equals("X"))
letter = x;
else
letter = y;
JOptionPane.showMessageDialog(null, letter + " wins the game!");
int answer = JOptionPane.showConfirmDialog(null, "Start", "Do you want to start a new game", JOptionPane.YES_NO_OPTION);

if (answer == JOptionPane.YES_OPTION)
{
this.clearIt();
}
else
{
JOptionPane.showMessageDialog(null, "Thank you " + x+ " and " + y + " for playing");
System.exit(0);
}

}
else if(count == 9 && win == false)
{
JOptionPane.showMessageDialog(null, "The game was tie!");
int answer = JOptionPane.showConfirmDialog(null, "Start", "Do you want to start a new game", JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.YES_OPTION)
{
this.clearIt();
}
else
{
JOptionPane.showMessageDialog(null, "Thank you " + x+ " and " + y + " for playing");
System.exit(0);
}

}
}
}

public void clearIt()
{

window.setVisible(false);
//this.window = null;
this.startIt();
}

public void startIt()
{
new TicTacToe();

}

public static void main(String[] args)
{

TicTacToe starter = new TicTacToe();
starter.setName();
}
}









Java application for calendar using Swings


import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Date;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

public class CalendarDemo extends JFrame implements ItemListener
{
    JPanel p1, p2;
    JComboBox month;
    JComboBox year;
    int days[]={31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    String weekdays[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
    String months[] = {"January", "February", "March", "April", "May", "June", "July",     "August", "September", "October", "November", "December"};
    public CalendarDemo(String title)
    {
        super();
        setTitle(title);
        p1 = new JPanel();
        //p1.setSize(350, 30);
        //p1.setLayout(new FlowLayout());
        month = new JComboBox();
        for(int i=0;i< months.length;i++)
        {
            month.addItem(months[i]);
        }
        month.addItemListener(this);
        year = new JComboBox();
        for(int i=1980;i<=2099;i++)
        {
            year.addItem(i);
        }
        year.addItemListener(this);
        p1.add(month);
        p1.add(year);
        p2 = new JPanel();
        p2.setLayout(new GridLayout(0,7,5,5));
        Date date = new Date();
        drawCalendar(months[date.getMonth()], (1900+date.getYear()));
        year.setSelectedItem((1900+date.getYear()));
        month.setSelectedItem(months[date.getMonth()]);
        Container c=getContentPane();
        c.setLayout(new FlowLayout());
        add(p1);
        add(p2);
        setVisible(true);
        //setBounds(200, 200, 350, 300);
        setSize(230,220);
        setResizable(false);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
    public static void main(String args[])
    {
        CalendarDemo frame = new CalendarDemo("Calendar");
    }

    @Override
    public void itemStateChanged(ItemEvent e)
    {
        if(e.getStateChange() == ItemEvent.SELECTED)
        {
            drawCalendar((String)month.getSelectedItem(),  (Integer)year.getSelectedItem());
        }
    }
    
    public void drawCalendar(String inputMonth, int inputYear)
    {
        p2.removeAll();
        for(int i=0;i< weekdays.length;i++)
        {
            JLabel label = new JLabel(weekdays[i]);
            label.setHorizontalAlignment(SwingConstants.RIGHT);
            p2.add(label);
        }
        Date date = new Date("01-"+inputMonth+"-"+inputYear);
        int noOfDaysInMonth = days[date.getMonth()];
        if(date.getYear()%4==0 && date.getMonth()==1)
        {
            noOfDaysInMonth = 29;
        }

        for(int i=1, day=1;day<=noOfDaysInMonth;i++)
        {
            for(int j=0;j<7;j++)
            {
                if(day==1)
                {
                    if(j==date.getDay())
                    {
                        JLabel label = new JLabel(String.valueOf(day));
                        label.setHorizontalAlignment(SwingConstants.RIGHT);
                        p2.add(label);
                        day++;
                    }
                    else
                    {
                        JLabel label = new JLabel("");
                        p2.add(label);
                    }
                }
                else
                {
                    JLabel label = new JLabel(String.valueOf(day));
                    label.setHorizontalAlignment(SwingConstants.RIGHT);
                    p2.add(label);
                    day++;
                }
                if(day>noOfDaysInMonth)
                {
                    break;
                }
            }
        }
        p2.validate();
        setTitle(inputMonth+", "+inputYear);
    }
}