File: wordfreq.java

package info (click to toggle)
groovy2 2.2.2%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: jessie-kfreebsd
  • size: 23,916 kB
  • sloc: java: 136,570; xml: 948; sh: 486; makefile: 67; ansic: 64
file content (62 lines) | stat: -rw-r--r-- 1,827 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
 * The Great Computer Language Shootout
 * http://shootout.alioth.debian.org/
 *
 * contributed by James McIlree
 */

import java.io.*;
import java.util.*;
import java.util.regex.*;

public class wordfreq {
  static class Counter {
    int count = 1;
  }

  public static void main(String[] args) 
    throws IOException
  {
    HashMap map = new HashMap();
    Pattern charsOnly = Pattern.compile("\\p{Lower}+");

    BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
    String line;
    while ((line = r.readLine()) != null) {
      Matcher matcher = charsOnly.matcher(line.toLowerCase());
      while (matcher.find()) {
        String token = matcher.group();
        Counter c = (Counter)map.get(token);
        if (c != null)
          c.count++;
        else
          map.put(token, new Counter());
      }
    }
    
    ArrayList list = new ArrayList(map.entrySet());
    Collections.sort(list, new Comparator() {
        public int compare(Object o1, Object o2) {
          int c = ((Counter)((Map.Entry)o2).getValue()).count - ((Counter)((Map.Entry)o1).getValue()).count;
          if (c == 0) {
            c = ((String)((Map.Entry)o2).getKey()).compareTo((String)((Map.Entry)o1).getKey());
          }
          return c;
        }
      });
    
    String[] padding = { "error!", " ", "  ", "   ", "    ", "     ", "      ", "error!" };
    StringBuffer output = new StringBuffer();
    Iterator it = list.iterator();
    while (it.hasNext()) {
      Map.Entry entry = (Map.Entry)it.next();
      String word = (String)entry.getKey();
      String count = String.valueOf(((Counter)entry.getValue()).count);
      if (count.length() < 7)
        System.out.println(padding[7 - count.length()] + count + " " +word);
      else
        System.out.println(count + " " +word);
    }
  }
}