Monday, February 20, 2012

count characters, sort and display

/*
 * Write a program that takes an input string from command lines.
 * displays unique characters.
 * displays them in sorted order 
 * and displays their no of accurances as showed in screenshot
 */


/*
 * bhatt.umang7@gmail.com
 */

import java.util.*;

class Node
{
    public final char c ;

    int count ;
    public Node(char c)
    {

        this.c = c ;    
    }
}
public class Program
{

    public static void main(String args[])
    {
        if(args.length != 1)
        {

            System.out.println("Invalid arguments.");
            System.exit(0);
        }

        int max = 0 ;
        HashMap<Character,Node> map =new HashMap<Character,Node>();

        String input = args[0];
        for(int i = 0 ; i < input.length() ;i++)
        {

            Node d = map.get(Character.toLowerCase((Character)input.charAt(i)));

            if(d==null)
            {
                d = new Node(args[0].charAt(i));

                d.count++;
                map.put(Character.toLowerCase(args[0].charAt(i)),d);
            }

            else
            {
                d.count++;
            }
            if(d.count>max)
            {

                max = d.count;
            }
        }
        TreeSet<Character> tree = new TreeSet<Character>(map.keySet());

        for(Character key : tree )
        {
            System.out.print(" " + key + " " );
        }

        System.out.println();
        for(int i = 0 ; i <= max ; i++)
        {

            for(Character key : tree )
            {
                Node d = map.get(key);

                if(d.count>0)
                {
                    System.out.print(" * " );

                    d.count--;
                }
                else
                {
                    System.out.print("   " );
                }
            }    
            System.out.println();
        }
    }
}

No comments:

Post a Comment