Showing posts with label JAVA. Show all posts
Showing posts with label JAVA. Show all posts

Friday, December 19, 2014

wordCounter Program using HashMap

Look at previous post for the context:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

class wordCounter2 {

String readFile(String fileName) throws IOException {
   BufferedReader br = new BufferedReader(new FileReader(fileName));
   try {
       StringBuilder sb = new StringBuilder();
       String line = br.readLine();

       while (line != null) {
           sb.append(line);
           sb.append(" ");
           line = br.readLine();
       }
       return sb.toString();
   } finally {
       br.close();
   }
}

void countAllWords(String filename) throws IOException
{
String fileContent = readFile(filename);
String[] arr = fileContent.split(" ");

Map<String, Integer> map = new HashMap<>();
   for (String w : arr) 
   {
       Integer n = map.get(w);
       n = (n == null) ? 1 : ++n;
       map.put(w, n);
   }
   
   Map <String, Integer> sortedMap = new TreeMap<String, Integer>(map);
   System.out.println("After Sorting:");
        Set<Entry<String, Integer>> set2 = sortedMap.entrySet();
        Iterator<Entry<String, Integer>> iterator2 = set2.iterator();
        while(iterator2.hasNext()) {
             Map.Entry me2 = (Map.Entry)iterator2.next();
             System.out.print(me2.getKey() + ": ");
             System.out.println(me2.getValue());
        }

        int maxValueInMap=(Collections.max(sortedMap.values()));  // This will return max value in the Hashmap
        for (Entry<String, Integer> entry : sortedMap.entrySet()) {  // Itrate through hashmap
            if (entry.getValue()==maxValueInMap) {
                System.out.println("Max Frequency: " + entry.getKey() + " ==> " + entry.getValue());     // Print the key with max value
            }
        }

}

void countWords(String filename, String word) throws IOException
{

String fileContent = readFile(filename);
String[] arr = fileContent.split(" ");

int counter = 0;

for (int i=0; i<arr.length; i++)
{
if (arr[i].equals(word))
{counter = counter + 1;}
else
continue;
}
System.out.println(counter);
}
}

public class wordCount2{

public static void main (String args[]) throws IOException
{
wordCounter2 wordcounter = new wordCounter2();
wordcounter.countAllWords("hello.txt");
//wordcounter.countWords("hello.txt", "Socket");
}
}

wordcounter Program


  • A Program that can count all the occurrence of all the words in a text file.
  • It can also find the frequency of a given word in the Program.


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

class wordCounter {

String readFile(String fileName) throws IOException {
   BufferedReader br = new BufferedReader(new FileReader(fileName));
   try {
       StringBuilder sb = new StringBuilder();
       String line = br.readLine();

       while (line != null) {
           sb.append(line);
           sb.append(" ");
           line = br.readLine();
       }
       return sb.toString();
   } finally {
       br.close();
   }
}

String[] sort(String[] arr)
{
String tmp;
for (int i = 0;i < arr.length;i++)
{
 tmp = arr[i];
 for (int j = 0;j < arr.length;j++)
 {
   if (i == j) continue; // Same place.. Nothing to do.
   int x = tmp.compareTo(arr[j]); // Bigger smaller?!
   if (x < 0) // Need to swap.
   {
     /* Swaping proccess... */
     tmp = arr[j];
     arr[j] = arr[i];
     arr[i] = tmp;
   }
 }
}
return arr;
}

void countAllWords(String filename) throws IOException
{
String fileContent = readFile(filename);
String[] arr = fileContent.split(" ");
String[] sortedArray = sort(arr);

int counter = 0;

for (int i=0; i<sortedArray.length; i++)
{
counter = 0;
for (int j=0; j<sortedArray.length; j++)
{
if (sortedArray[i].equals(arr[j]))
{counter = counter + 1;}
else
continue;
}

if (i == 0)
System.out.println(sortedArray[i] + " : " + counter);
else
{
if (sortedArray[i].equals(sortedArray[i-1]))
continue;
else
System.out.println(sortedArray[i] + " : " + counter);
}
}
}

void countWords(String filename, String word) throws IOException
{
String fileContent = readFile(filename);
String[] arr = fileContent.split(" ");
//String[] sortedArray = sort(arr);

int counter = 0;

for (int i=0; i<arr.length; i++)
{
if (arr[i].equals(word))
{counter = counter + 1;}
else
continue;
}
System.out.println(counter);

}
}

public class wordCount{

public static void main (String args[]) throws IOException
{
wordCounter wordcounter = new wordCounter();
wordcounter.countAllWords("input.txt");
//wordcounter.countWords("input.txt", "Socket");
}
}


Following is the content of my input.txt:
Socket Class Methods:
The java.net.Socket class represents the socket that both the client and server use to
communicate with each other. The client obtains a Socket object by instantiating one,
whereas the server obtains a Socket object from the return value of the accept()
method


Running the program will produce following output


Changing above program a little-bit to find out the string with highest frequency and the frequency value: void countAllWords(String filename) throws IOException{String fileContent = readFile(filename);String[] arr = fileContent.split(" ");String[] sortedArray = sort(arr);int counter = 0;int maxcounter = counter;String maxString = null;for (int i=0; i<sortedArray.length; i++){ counter = 0;for (int j=0; j<sortedArray.length; j++){if (sortedArray[i].equals(arr[j])){counter = counter + 1;}elsecontinue; if (counter > maxcounter){maxcounter = counter;maxString = sortedArray[i];}} /*if (i == 0)System.out.println(sortedArray[i] + " : " + counter);else{if (sortedArray[i].equals(sortedArray[i-1]))continue;elseSystem.out.println(sortedArray[i] + " : " + counter);}*/}System.out.println("Highest Frequency = " + maxcounter);System.out.println("Highest Frequency String = " + maxString);}








Tuesday, December 16, 2014

Recursively listing directories

Note that this code is OS Agnostic (just because I am using File.separator instead of "//"), it has been tested on windows as well as Linux. Compile it as JAR and provide the directory name to iterate as sys.argv[0] and filename to store all the listing as sys.argv[1] . If using eclipse, refer to my previous post on how to provide the arguments in eclipse to a program -- it is very simple, just go to run configuration and you will find "arguments" there only.

This will list complete directory structure in my centos machine:
java -jar readDir2.jar / allFiles.txt


import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

class dirTraversal{

public void traverseDir(String parentDir, String filename) throws IOException
{

File f = new File(parentDir);
FileWriter filewriter = new FileWriter(filename);
try {
listDir(f,filewriter);
filewriter.flush();
filewriter.close();
} catch (IOException e) {e.printStackTrace();}

}


private void listDir(File dirObject, FileWriter writer) throws IOException
{
String[] files;
files = dirObject.list();
for (String file:files)
{
File testDir = new File(dirObject + File.separator + file);
boolean isDir = testDir.isDirectory();
if(isDir == true)
{
writer.write("Directory Content for dir: " + testDir + "\n");
listDir(testDir,writer);
}
else
{
writer.write(file+ "\n");
}
}

}
}

public class readDir
{
public static void main(String[] args) throws IOException
{
dirTraversal obj = new dirTraversal();
obj.traverseDir(args[0], args[1]);

}
}

Error: No Main Manifest Attribute

Have caught into this error  "no main manifest attribute" when I tried to create the jar file in Eclipse.



Instantly, tried runnable JAR file instead of "JAR File" in export settings and it worked out for me.






















Other JAR commands:


1. To view the contents of a JAR File:

jar tf jar-file
Let's look at the options and argument used in this command:
  • The t option indicates that you want to view the table of contents of the JAR file.
  • The f option indicates that the JAR file whose contents are to be viewed is specified on the command line.
  • The jar-file argument is the path and name of the JAR file whose contents you want to view.
The t and f options can appear in either order, but there must not be any space between them.
This command will display the JAR file's table of contents to stdout.
You can optionally add the verbose option, v, to produce additional information about file sizes and last-modified dates in the output.

2. To extract content of JAR File:

jar xf jar-file [archived-file(s)]

Let's look at the options and arguments in this command:
  • The x option indicates that you want to extract files from the JAR archive.
  • The f options indicates that the JAR file from which files are to be extracted is specified on the command line, rather than through stdin.
  • The jar-file argument is the filename (or path and filename) of the JAR file from which to extract files.
  • archived-file(s) is an optional argument consisting of a space-separated list of the files to be extracted from the archive. If this argument is not present, the Jar tool will extract all the files in the archive.
3. To create a JAR File

The basic format of the command for creating a JAR file is:
jar cf jar-file input-file(s)
The options and arguments used in this command are:
  • The c option indicates that you want to create a JAR file.
  • The f option indicates that you want the output to go to a file rather than to stdout.
  • jar-file is the name that you want the resulting JAR file to have. You can use any filename for a JAR file. By convention, JAR filenames are given a .jar extension, though this is not required.
  • The input-file(s) argument is a space-separated list of one or more files that you want to include in your JAR file. The input-file(s) argument can contain the wildcard * symbol. If any of the "input-files" are directories, the contents of those directories are added to the JAR archive recursively.
The c and f options can appear in either order, but there must not be any space between them.
This command will generate a compressed JAR file and place it in the current directory. The command will also generate a default manifest file for the JAR archive.

Monday, December 15, 2014

BigInteger to the rescue


Java's Math library provides BigInteger that can hold any kind of largest number (no idea how BigInteger breaks the barrier of 64 bit and I am looking for an answer)

import java.math.*;

class bigfactorial {
    
public static BigInteger compute(int num) 
    { 
   if(num < 0) 
   { throw new IllegalArgumentException("negative number passed for factorial computation");}
   
   if(num < 2) 
   {return BigInteger.ONE;} 
   
   BigInteger factorial = BigInteger.ONE; 
   
   while(num > 1) 
   {  factorial = factorial.multiply(BigInteger.valueOf(num--)); }
   return factorial; 
    }
    
}

public class biginteger {

public static void main(String args[]){
    for (int i=2; i<25;i++)
    System.out.println("The " + i + " ! is: " 
    + bigfactorial.compute(i));
    }

}



JAVA Program for factorial 20


This JAVA program illustrate the use of long to store the output of factorial 20. 

In JAVA, an int is 4 byte long therefore the largest number starting from 0 that an unsigned int can store is =  (2^32 - 1) OR 4,294,967,295 or to remember easily 4.2x10^9.

To store negative integers we generally sacrifice one bit to indicate the sign of number and use rest of the 31 bits to store the number, therefore signed int can store number fro -2,147,483,647 to 2,147,483,647 ( $\pm 2^{31} - 1$). To remember simply we can say 4.2/2 = 2.1 and therefore signed int can store -2.1x10^9 to +2.1x10^9

Long is 8 bytes long: therefore the largest number that an unsigned long can store starting from 0 is =  (2^64-1) OR 18,446,744,073,709,551,615  OR 1.8X10^19.
Unsigned we can sacrifice one bit and it will be like 0.9x10^19

Now, the problem is how are we going to produce and store a number which is larger than the order of 10^19. 


class calcFactorial
{
long number;
long calculation(long num)
{
  number = num;
    if (number == 1)
  { return 1;}
  else
   return (number * calculation(number-1));
}
}


public class factorial {
public static void main (String[] args)
{
  calcFactorial variable1 = new calcFactorial();
     for (int i=1; i<=21; i++)
{System.out.println("factorial of " + i + " is = " + variable1.calculation(i));}
}
}










Aggregation in JAVA


If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A relationship.

Consider a situation, Employee object contains many informations such as id, name, emailId etc. It contains one more object named address, which contains its own informations such as city, state, country, zipcode etc. as given below.

class Employee{  
int id;  
String name;  
Address address;//Address is a class  
...  
}  

In such case, Employee has an entity reference address, so relationship is Employee HAS-A address.

Why use Aggregation?

For Code Reusability.

Sunday, December 7, 2014

Height and Diameter of a Tree

Code Snippets in JAVA - pretty much straightforward (This is O(n^2)):

public static int getDiameter(treeNode rootNode)
{
  if (rootNode == null) return 0;
  else
 {
   int rootDiameter = getHeight(goLeft(rootNode)) + getHeight(goRight(rootNode)) + 1;

 int leftDiameter = getDiameter(goLeft(rootNode));



 int rightDiameter =  getDiameter(goRight(rootNode));
 return Math.max(rootDiameter, Math.max(leftDiameter, rightDiameter));
}

}

public static int getHeight (treeNode rootNode)

{
if(rootNode == null) return 0;
else
return Math.max((getHeight(goLeft(rootNode))),(getHeight(goRight(rootNode)))) + 1; 

}

public static treeNode goLeft(treeNode Node)
{
return Node.leftChild;
}

public static treeNode goRight(treeNode Node)
{
return Node.rightChild;
}


public void inOrder(treeNode rootNode)
{
if (rootNode != null)
{
inOrder(goLeft(rootNode));
System.out.print(rootNode.data + ", ");
inOrder(goRight(rootNode));
}


}

Insert Function:

public void insert(treeNode rootElement, int givenData)
{
if (rootElement == null)
{
rootElement = new treeNode(givenData);
         }

else
{
treeNode nodeElement = getParentNode(rootElement, givenData);
if (nodeElement.leftChild == null && givenData < nodeElement.data )
{
nodeElement.leftChild = new treeNode(givenData);

}
else
{
nodeElement.rightChild = new treeNode(givenData);
}

}

}

private treeNode getParentNode(treeNode node, int data)
{
if(data < node.data)
{
if(node.leftChild == null)
{
  return node;
}
else
{
return getParentNode(node.leftChild, data);
}
}
else
{
if(node.rightChild == null)
{
return node;
}
else
{
return getParentNode(node.rightChild, data);
}
}

}




Diameter of a tree

There are three cases to consider when trying to find the longest path between two nodes in a binary tree (diameter): 

  • The longest path passes through the root, 
  • The longest path is entirely contained in the left sub-tree, 
  • The longest path is entirely contained in the right sub-tree. 
  • The longest path through the root is simply the sum of the heights of the left and right sub-trees + 1 (for the root node), and the other two can be found recursively

Int function:

BinaryTree bst = new BinaryTree();
treeNode root = new treeNode(20);
bst.insert(root, 10);
bst.insert(root, 30);
bst.insert(root, 11);
bst.insert(root, 12);
bst.insert(root, 13);
bst.insert(root, 14);
bst.insert(root, 9);
bst.insert(root, 21);
bst.insert(root, 22);
bst.insert(root, 1);
bst.insert(root, 18);
bst.inOrder(root);

System.out.println("\ntreeHeight : " + getHeight(root));
System.out.println("tree-Diameter : " + getDiameter(root));