UVA – 10008 – What’s Cryptanalysis?

  • ID : UVA – 10008 – What’s Cryptanalysis?
  • Difficulty : Easy
  • Type : Sorting
  • Description:-
    • count each letter and then sort ascendengly.
  • Problems :
    • I faced a problem during using the java Arrays.sort() i realized that i had a mistake in the compareTo function in it’s second condition were it should have been reversed.
  • Code:


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

public class Main {

	public static void main(String[] args) throws NumberFormatException,
			IOException {
		HashMap<Character, Letter> letters = new HashMap<Character, Letter>();
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		int T = Integer.parseInt(bf.readLine());
		while (T-- != 0) {
			String s = bf.readLine().toUpperCase();

			for (char c : s.toCharArray())
				if (Character.isLetter(c)) {
					if (!letters.containsKey(c))
						letters.put(c, new Letter(c));
					else {
						letters.get(c).n++;
					}
				}

		}

		ArrayList<Letter> list= new ArrayList<Letter>(letters.size());
		list.addAll(letters.values());

		Collections.sort(list);
		Collections.reverse(list);

		for(Letter c : list)
			System.out.println(c);
	}

}

class Letter implements Comparable<Letter> {

	char c;
	int n;

	public Letter(char c2) {
		c = c2;
		n = 1;
	}

	@Override
	public int hashCode() {
		return c - 'A';
	}

	@Override
	public boolean equals(Object o) {
		return ((Letter) o).c == c;
	}

	@Override
	public int compareTo(Letter o) {
		return (n - o.n == 0) ? o.c -c : n - o.n;
	}

	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return c+ " " + n;
	}
}

Advertisements

One thought on “UVA – 10008 – What’s Cryptanalysis?

  1. Easy Because of Java
    Ugly for C 😀

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: