Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Monday, October 15, 2018

Movie Sentiment Analysis (Java)

Sentiment Analysis Background


Sentiment analysis is the process of using software to classify a piece of text into a category that reflects the opinion of the writer. Sentiment analysis falls into the growing field of machine learning. In this assignment, you will be writing a simple sentiment analysis program to predict the score a movie reviewer would give based on the words that they use.
 

Sentiment Analysis Algorithm

The goal of your program is to use a data set of known reviews to predict the review for a new piece of text. Our algorithm for sentiment analysis is a simple one: For each word in the input text, calculate the average score of the reviews that use that word per word use. (For the sake of clarity, let’s call that score the “word score”) Then, find the averages of the word scores for the words in your input review. That number is your predicted score for the input text. You should ignore capitalization 
and punctuation.
 

For example, let’s say we have two reviews:

Score: 1, Text: “The plot holes were the most outrageous I’ve ever seen.”
Score: 4, Text: “The outrageous slapstick sequences left me howling.”
In this example, “Outrageous” is used once in a 1 score review and once in a 4 score review. That means that its word score is 2.5. “The” is used twice in a 1 score review and once in a 4 score review, meaning that its word score is 2. If our input text was just “the outrageous,” we would predict a score of 2.25.



Code:


Caution: please change the file directory before running.

MovieApp.java

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;

public class MovieApp {


    public static void main(String[] nt) throws IOException {

        HashMap<String, Word> wordHashMap = new HashMap<>();
        FileReader in = null;
        Scanner scanner = new Scanner(System.in);
        StringBuffer stringBuffer = new StringBuffer();


        while (true) {



            System.out.println("Review filename?");
            String fileName = scanner.nextLine();


            try {
                in = new FileReader("/Users/mrdishant/Assignment Java/src/" + fileName);


                int c;
                while ((c = in.read()) != -1) {
                    stringBuffer.append((char) c);
                }

            } catch (FileNotFoundException e) {
                System.out.println("Please Enter a valid fileName.");
//                e.printStackTrace();                continue;
            } catch (IOException e) {
                System.out.println("Please Enter a valid fileName.");
//                e.printStackTrace();                continue;
            } finally {
                if (in != null) {
                    in.close();
                }
            }


            try {

                String[] lines = stringBuffer.toString().toLowerCase().split("\n");

                for (String line : lines) {

                    String[] words = line.replaceAll("\\p{Punct}", "").split(" ");


                    double score = Double.parseDouble(words[0]);

                    for (int i = 1; i < words.length; i++) {

                        if (wordHashMap.containsKey(words[i].trim())) {
                            wordHashMap.get(words[i].trim()).scores.add(score);

                        } else {
                            Word word1 = new Word();
                            word1.word = words[i].trim();

                            word1.scores = new ArrayList<>();
                            word1.scores.add(score);

                            wordHashMap.put(words[i].trim(), word1);
                        }
                    }

                }

            } catch (Exception e) {

                System.out.println("File doesn’t match the input structure please try again.");

                stringBuffer.delete(0,stringBuffer.length());

                continue;
            }



            System.out.println("Input review?");
            String inputReview = scanner.nextLine();

            String[] wordsInput = inputReview.trim().toLowerCase().split(" ");



            double sum = 0;

            for (String wInput : wordsInput) {

                wInput=wInput.trim();



                if (wordHashMap.containsKey(wInput)) {
                    wordHashMap.get(wInput).calculateScore();
                    sum += wordHashMap.get(wInput).wordScore;
                }

            }



            if (wordsInput.length > 0 && sum != 0.0) {

                double average = sum / wordsInput.length;

                System.out.println("" + Math.round(average * 100.0) / 100.0);

                break;

            } else {
                System.out.println("-1");
                break;
            }


        }
////        Word the=wordHashMap.get("1");//        the.calculateScore();//        System.out.print(the.toString());
////        for (Word word:wordHashMap.values()){//            word.calculateScore();//            //System.out.println(word.toString());//        }
        //System.out.println("Size "+hashMap.values().size());

//        for (String s:words)//            System.out.println("Words are "+s);
    }


}

Word.java


import java.util.ArrayList;

public class Word {

    String word;
    ArrayList<Double> scores;
    double wordScore;


    @Override    public String toString() {
        return "Word{" +
                "word='" + word + '\'' +
                ", scores=" + scores +
                ", wordScore=" + wordScore +
                '}';
    }

    public void calculateScore(){

        double sum=0.0;

        for (Double score : scores){
            sum+=score;
        }

        wordScore=sum/scores.size();

        wordScore=Math.round(wordScore * 100.0) / 100.0;

    }

}


Output:




Github repo url : https://github.com/mrdishant/Movie-Sentiment-Analysis-Java/tree/master/src

 




Saturday, November 11, 2017

Kruskal's Algoritm DAA

Question: Write a program to find the minimum cost of connecting all the engineering colleges in your state using Kruskal's algorithm.
Code:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Kruskal {

    static  class  edge{
        int distance,s,d;

        public edge(int distance, int s, int d) {
            this.distance = distance;
            this.s = s;
            this.d = d;
        }

        @Override        public String toString() {
            return "edge{" +
                    "distance=" + distance +
                    ", s=" + s +
                    ", d=" + d +
                    '}';
        }
    }

    public static void main(String[] nt){

        int graph[][]= {{0, 2, 0, 6, 0},
                {2, 0, 3, 8, 5},
                {0, 3, 0, 0, 7},
                {6, 8, 0, 0, 9},
                {0, 5, 7, 9, 0},
        };

        boolean[] visited=new boolean[graph.length];
        ArrayList<edge>edgeArrayList=new ArrayList<>();

        for(int i=0;i<graph.length;i++){
            visited[i]=false;
            for(int x=0;x<graph[i].length;x++){
                if(graph[i][x]!=0){
                    edgeArrayList.add(new edge(graph[i][x],i,x));
                }
            }
        }

        Collections.sort(edgeArrayList, new Comparator<edge>() {
            @Override            public int compare(edge edge, edge t1) {
                return edge.distance-t1.distance;
            }
        });
        int count=0;
        edge edgenow;
        int min=0;
        while (count!=graph.length-1){
            edgenow=edgeArrayList.get(0);
            edgeArrayList.remove(0);
            if(visited[edgenow.d]==false || visited[edgenow.s]==false){
                min+=edgenow.distance;
               System.out.println((edgenow.s+1)+" -> "+(edgenow.d+1)+" : "+edgenow.distance);
                visited[edgenow.d]=true;
                visited[edgenow.s]=true;
                count++;
            }
        }
        System.out.println("Cost is : "+min);
    }
}

Output:

Dijkstra’s algorithm.

Question: Write a program to find shortest path from your home to college using Dijkstra’s algorithm.

Code:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Dijkstras {

    static class vertex{
        int distance;
        boolean visited;
        int no;
        int previous;

        @Override        public String toString() {
            return "vertex{" +
                    "distance=" + distance +
                    ", visited=" + visited +
                    ", no=" + (no+1) +
                    ", previous=" + (previous+1) +
                    '}';
        }

        public vertex(int distance, boolean visited, int no, int previous) {
            this.distance = distance;
            this.visited = visited;
            this.no = no;
            this.previous = previous;
        }


    }

    public static void main(String[] nt){
        ArrayList<vertex> arrayList=new ArrayList<>();
        ArrayList<vertex> result=new ArrayList<>();
       /* int graph[][] = new int[][]{{0, 4, 0, 0, 0, 0, 0, 8, 0},                {4, 0, 8, 0, 0, 0, 0, 11, 0},                {0, 8, 0, 7, 0, 4, 0, 0, 2},                {0, 0, 7, 0, 9, 14, 0, 0, 0},                {0, 0, 0, 9, 0, 10, 0, 0, 0},                {0, 0, 4, 14, 10, 0, 2, 0, 0},                {0, 0, 0, 0, 0, 2, 0, 1, 6},                {8, 11, 0, 0, 0, 0, 1, 0, 7},                {0, 0, 2, 0, 0, 0, 6, 7, 0}        };       */       int[][] graph={{0,4,8,0,0},{0,0,5,8,10},{0,4,0,0,3},{0,0,0,0,6},{0,0,0,7,0}};
       for (int i=0;i<graph.length;i++){
            arrayList.add(new vertex(Integer.MAX_VALUE,false,i,Integer.MAX_VALUE));
        }

        arrayList.get(0).distance=0;
        arrayList.get(0).previous=0;

        Comparator<vertex> com=new Comparator<vertex>() {
            @Override            public int compare(vertex vertex, vertex t1) {
                return vertex.distance-t1.distance;
            }
        };

        vertex poped;
        while (arrayList.size()!=0){
            Collections.sort(arrayList,com);
            poped=arrayList.get(0);
            arrayList.remove(0);


            if(poped.visited==false){
                for (int i=0;i<graph[poped.no].length;i++){
                    if(graph[poped.no][i]!=0&& find(arrayList,i)!=Integer.MAX_VALUE){
                        int x=find(arrayList,i);
                            if(graph[poped.no][i]+poped.distance<arrayList.get(x).distance){
                                arrayList.get(x).distance=graph[poped.no][i]+poped.distance;
                                arrayList.get(x).previous=poped.no;
                            }
                    }
                }
                poped.visited=true;
                result.add(poped);
            }
        }

        Comparator<vertex>comp2=new Comparator<vertex>() {
            @Override            public int compare(vertex vertex, vertex t1) {
                return vertex.no-t1.no;
            }
        };
        Collections.sort(result,comp2);
        for(int i=0;i<result.size();i++){

            System.out.println(result.get(i).toString());
        }

    }

    static int find(ArrayList<vertex> arrayList,int n){
        int i=Integer.MAX_VALUE;

        for (int x=0;x<arrayList.size();x++){
            if(arrayList.get(x).no==n){
                return x;
            }
        }
        return i;
    }
}

Output:


Sunday, October 29, 2017

Prim's Java DAA 6

Code:




import java.util.ArrayList;

public class Prims {

   static class Vertex{
        int parent;
        boolean set;
        int key;


        public Vertex(int parent, boolean set, int key) {
            this.parent = parent;
            this.set = set;
            this.key = key;
        }

       @Override       public String toString() {
           return "Vertex{" +
                   "parent=" + parent +
                   ", set=" + set +
                   ", key=" + key +
                   '}';
       }
   }

    public static void main(String[] nt){

        int graph[][]= {{0, 2, 0, 6, 0},
                {2, 0, 3, 8, 5},
                {0, 3, 0, 0, 7},
                {6, 8, 0, 0, 9},
                {0, 5, 7, 9, 0},
        };

        int n=graph.length;

        ArrayList<Vertex> vertices=new ArrayList<>();
        for(int i=0;i<n;i++) {
            vertices.add(new Vertex(-1, false, Integer.MAX_VALUE));
        }
        vertices.get(0).key=0;


        for (int i=0;i<n;i++){

            int min=find(vertices);
            vertices.get(min).set=true;

            for(int j=1;j<n;j++){
                if(graph[min][j]<vertices.get(j).key&&vertices.get(j).set==false && graph[min][j]!=0){
                    vertices.get(j).key=graph[min][j];
                    vertices.get(j).parent=min;
                }
            }
        }

        System.out.println("Edge    Weight");
        for(int i=1;i<vertices.size();i++){
            System.out.println(vertices.get(i).parent+" - "+i+"  : "+graph[i][vertices.get(i).parent]);
            //System.out.println(vertices.get(i).toString());        }
    }

    static int find(ArrayList<Vertex> vertices){
        int min=Integer.MAX_VALUE,i=0;

        for(int x=0;x<vertices.size();x++){
            if(vertices.get(x).key<min && vertices.get(x).set!=true){
                min=vertices.get(x).key;
                i=x;
            }
        }

        return i;
    }

}
Output:



Friday, October 27, 2017

Knapsack Java

Knapsack Using Greedy Algorithm

Code:
package com.nearur;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class KNAPSACK {
 static int capacity=40;

 public static void main(String[] args) {
package com.nearur;

public class Item {

String name;
int value,weight;
public Item(String name, int value, int weight) {
super();
this.name = name;
this.value = value;
this.weight = weight;
}

int compareWeight(Item x) {
if(x.weight>weight) {
return -1;
}return 1;
}

int compareValue(Item x) {
if(x.value>value) {
return 1;
}return -1;
}

int compareratio(Item x) {
if(x.value/x.weight>value/weight) {
return 1;
}return -1;
}

}

  Item [] item=new Item[4];
  item[0]=new Item("I1",100,20);
  item[1]=new Item("I2",90,10);
  item[2]=new Item("I3",40,15);
  item[3]=new Item("I4",50,5);

  ArrayList<Item> knapsack=new ArrayList<>();
  ArrayList<Item> allitems=new ArrayList<>();

  for(int i=0;i<item.length;i++) {
   allitems.add(item[i]);
  }

  Comparator<Item> com=new Comparator<Item>() {
 
   @Override
   public int compare(Item o1, Item o2) {
    return o1.compareratio(o2);
    //return o1.compareValue(o2);
    //return o1.compareWeight(o2);
   }
  };

  Collections.sort(allitems,com);

  for(Item ite:allitems) {
   System.out.println(ite.name);
   if(ite.weight<=capacity) {
    knapsack.add(ite);
    capacity=capacity-ite.weight;
   }
  }

  int mvalue=0,mweight=0;

  for(Item i: knapsack) {
   mvalue +=i.value;
   mweight +=i.weight;
  }

  System.out.println("Total Value: "+mvalue+"\nTotal Weight: "+mweight);
 }
}


Output:


Sunday, September 3, 2017

Number To Equivalent InWords String

Code:
package com.nearur;

import java.util.Scanner;

public class English {

String[] ones= {"","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","ninteen"};
String[] tens= {"","","twenty","thirty","fourty","fifty","sixty","seventy","eighty","ninty"};
StringBuffer buffer=new StringBuffer();

String c(int n) {
if(n<0) {
return "Minus "+c(-n);
}else if(n<20) {
return ones[n];
}else if(n<100) {
return tens[n/10]+" "+ones[n%10];
}else if(n<1000) {
return c(n/100)+" hundred "+c(n%100);
}else if(n<100000) {
return c(n/1000)+" thousand "+c(n%1000);
}else if(n<10000000) {
return c(n/100000)+" lakh "+c(n%100000);
}else if(n<1000000000) {
return c(n/10000000)+" crore "+c(n%10000000);
}

return "";
}

public static void main(String[] args) {
English a=new English();
Scanner in =new Scanner(System.in);
System.out.print("Enter Any Number : ");
int n=in.nextInt();
System.out.println(a.c(n).toUpperCase());

}

}

Output:


Friday, September 1, 2017

Name In Binary

Code:

package com.nearur;

import java.util.Scanner;

public class NTB {


static StringBuffer buffer=new StringBuffer();
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.print("Enter Your Name:");
String a=in.nextLine();
String[] name=a.split(" ");

for(String x:name) {
convert(x);
}

System.out.println("Binary Code is : "+buffer.toString());
}

static void convert(String name) {

char[] a=name.toCharArray();
for(char x: a) {
binary((int)x);
buffer.append(" ");
}

}
static void binary(int n) {
while(n>0) {
if(n%2==0) {
buffer.append("0");
}else {
buffer.append("1");
}
n=n/2;
}
}


}


Output:


Tuesday, August 22, 2017

HangMan

Following Code is Hangman Like game without graphics inspired by Duta http:duta.in:


Code:

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

public class Main {
static String check="AEIOU";
public static void main(String[] args) {
ArrayList<String> questions=new ArrayList<>();
questions.add("ABRUPTLY");
questions.add("BOOKWORM");
questions.add("GALAXY");
questions.add("PNEUMONIA");
questions.add("STRONGHOLD");
questions.add("WHIZZING");
questions.add("PUZZLING");
questions.add("WRISTWATCH");
questions.add("ZODIAC");
questions.add("THUMBSCREW");
questions.add("YACHTSMAN");
questions.add("MNEMONIC");
questions.add("TRANSPLANT");
questions.add("RHYTHM");
questions.add("MICROWAVE");
Collections.shuffle(questions);
String ques=questions.get(0);
   char[] given=new char[ques.length()];
   int count=0;
   for(int i=0;i<given.length;i++) {
    if(varcheck(ques.charAt(i))) {
    given[i]=ques.charAt(i);
    }else {
    given[i]='_';
    }
   }
   boolean win=false;
   Scanner in=new Scanner(System.in);
   StringBuffer buffer=new StringBuffer();
outer:
   while(count<7 && !win) {
    for(int i=0;i<given.length;i++) {
    System.out.print(given[i]+" ");
    }
    System.out.println();
    System.out.println("Guess a Letter");
    char c=in.nextLine().toUpperCase().charAt(0);
    int i=0;
    while(i<given.length) {
    if(given[i]==c) {
    System.out.println("Already Present in Word!!");
    System.out.println("Guessed Letters : "+buffer);
    System.out.println("Chances left : "+(7-count));
    System.out.println("------------------------------");
    continue outer;
    }i++;
    }
    if(buffer.toString().contains(c+"")) {
    System.out.println("Already Guessesed!!");
    System.out.println("Guessed Letters : "+buffer);
    System.out.println("Chances left : "+(7-count));
    System.out.println("------------------------------");
    continue outer;
    }
    if(ques.contains(c+"")) {
    int idx=ques.indexOf(c);
    while(idx>=0) {
    given[idx]=c;
    idx=ques.indexOf(c,idx+1);
    win=true;
    }
    System.out.println("Good Guess!!");
    }else {
    count++;
    System.out.println("Bad Guess!!");
    }
    buffer.append(c+",");
    System.out.println("Guessed Letters : "+buffer.toString().substring(0,buffer.length()-1));
    System.out.println("Chances left : "+(7-count));
    for(char x: given) {
    if(x=='_') {
    win=false;
    }
    }
    System.out.println("--------------------------------\n");
   }
    System.out.println("Word is : "+ques);
   if(win) {
    System.out.println("Congratulations,You win!!");
   }else {
    System.out.println("You Loose!!,Don't Worry Try Again");
   }
   in.close();
}
static boolean varcheck(char c) {
if(check.contains(c+"")) return true;
return false;
}

}

Output:






Sunday, August 20, 2017

Desired Number of Quark Pairs

Following Code will give you desired number of quark pairs:


Code:

import java.util.Scanner;

public class MainQuark {
public static void main(String[] nt) {
System.out.print("Enter Value of N :");
int n;
Scanner in=new Scanner(System.in);
n=in.nextInt();
        int count=0,i=1,num;
        StringBuffer buffer=new StringBuffer();
while(count!=n) {
num=i;
int q=quark(num);
if(!prime(q)) {
for(int j=num+1;j<q;j++) {
if(q==quark(j)) {
buffer.append(i+"-"+j+"\n");
count++;
}
}
}
i++;
}
System.out.println("Pairs are\n"+buffer.toString());
}
static int quark(int n) {
int one=0,i=n;
while(n>0) {
if(n%2==1) {
one++;
}n=n/2;
}return one*(i);
}

static boolean prime(int n) {
for(int i=2;i<n/2;i++) {
if(n%i==0) return false;
}return true;
}

}


Output:




Quark Pairs Upto N

Quark Pairs: 



Code:

import java.util.Scanner;

public class MainQuark {
public static void main(String[] nt) {
System.out.print("Enter Value of N :");
int n;
Scanner in=new Scanner(System.in);
n=in.nextInt();
int[] quarks=new int[n];
int num=0;
for(int i=0;i<n;i++) {
num=i+1;
int one=0;
while(num>0) {
if(num%2==1) {
one++;
}num=num/2;
}
quarks[i]=one*(i+1);
}
StringBuffer buffer=new StringBuffer();
for(int i=0;i<n;i++) {
for(int j=i+1;j<n;j++) {
if(quarks[i]==quarks[j]) {
buffer.append((i+1)+"-"+(j+1)+"\n");
}
}
}
System.out.println("All Pairs upto "+n+" : ");
System.out.println(buffer.toString());
}

}


Output:


Saturday, August 19, 2017

K-means Clustering

 What is K-means? 
1. Partitional clustering approach 
2. Each cluster is associated with a centroid (center point) 
3. Each point is assigned to the cluster with the closest centroid 
4 Number of clusters K must be specified 


Following Code will find the value of K :


Code:

Main.Java

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

public class Main {

   public static void main(String[] args) {
        long start=System.currentTimeMillis();
       int k=1;
      Point[] p=new Point[5];
      p[0]=new Point(1,1);
      p[1]=new Point(1,0);
      p[2]=new Point(0,2);
      p[3]=new Point(2,4);
      p[4]=new Point(3,5);
      
      ArrayList<Point> given=new ArrayList<>();
      given.add(p[0]);
      given.add(p[1]);
      given.add(p[2]);
      given.add(p[3]);
      given.add(p[4]);
      
      Collections.shuffle(given);
      Point c1=new Point(given.get(0));
      Point c2=new Point(given.get(1));


      ArrayList<Point>cluster1=new ArrayList<>();
      ArrayList<Point>cluster2=new ArrayList<>();

      ArrayList<Point>newcluster1=new ArrayList<>();
      ArrayList<Point>newcluster2=new ArrayList<>();

      double dc1,dc2;
      for(int i=0;i<5;i++) {
         dc1=c1.distance(p[i]);
         dc2=c2.distance(p[i]);
         if(dc1<dc2) {
            cluster1.add(p[i]);
         }else if(dc2<dc1) {
            cluster2.add(p[i]);
         }
      }
        c1.x=meanx(cluster1);
        c1.y=meany(cluster1);
        c2.x=meanx(cluster2);
        c2.y=meany(cluster2);
        do {
            if(!(newcluster1.isEmpty()&& newcluster2.isEmpty())) {
                cluster1.clear();
                System.out.println(cluster1.size());
                cluster1.addAll(newcluster1);
                cluster2.clear();
                cluster2.addAll(newcluster2);
                newcluster1.clear();
                newcluster2.clear();
            }
            for(int i=0;i<5;i++) {
                dc1=c1.distance(p[i]);
                dc2=c2.distance(p[i]);
                if(dc1<=dc2) {
                    newcluster1.add(p[i]);
                }else {
                    newcluster2.add(p[i]);
                }
            }
            c1.x=meanx(newcluster1);
            c1.y=meany(newcluster1);
            c2.x=meanx(newcluster2);
            c2.y=meany(newcluster2);
            k++;
        }while(!(compareCluster(cluster1, newcluster1)||compareCluster(cluster1, newcluster2))&&(compareCluster(cluster2, newcluster2)||compareCluster(cluster2, newcluster1)));
        System.out.println("Value of K is  : "+k);
      System.out.println("Time Taken : "+(System.currentTimeMillis()-start)+" milliseconds");
   }

    static boolean compareCluster(ArrayList<Point> c1,ArrayList<Point> c2) {
      if(c1.size()!=c2.size()||c1==null&&c2!=null||c1!=null&&c2==null) return false;
      if(c1==null && c2==null) return true;
      for(int i=0;i< c1.size();i++){
           if(! c2.contains(c1.get(i))) return false;
        }
        return true;
   }


   static double meanx(ArrayList<Point> c) {
      double sumx=0;
      for(int i=0;i<c.size();i++) {
         sumx+=c.get(i).x;
      }
      return sumx/c.size();
   }

    static double meany(ArrayList<Point> c) {
        double sumy=0;
        for(int i=0;i<c.size();i++) {
            sumy+=c.get(i).y;
        }
        return sumy/c.size();
    }
}


-------------------------------------------------------------------------------------------
Point.Java

public class Point {
   double x,y;
   
   Point(double a,double b){
      x=a;
      y=b;
   }
   Point(Point b){
      x=b.x;
      y=b.y;
   }
   
   double distance(Point b) {
      return Math.sqrt(Math.pow((x-b.x),2)+Math.pow((y-b.y),2));
   }

   @Override   public String toString() {
      return "Point [x=" + x + ", y=" + y + "]";
   }

}


For any Suggestions please Click Here


Output: