Skip to content

Instantly share code, notes, and snippets.

@catalan42
Created June 7, 2013 17:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save catalan42/5730957 to your computer and use it in GitHub Desktop.
Save catalan42/5730957 to your computer and use it in GitHub Desktop.
A simple demo to count all the space-delimited words in a file. Usage: counter <filename>
#!/usr/bin/env groovy
// A simple demo to count all the space-delimited words in a file.
// Usage: counter <filename>
class Counter {
// A list of sets. Words of length L are stored in words[L]. All words are
// stored as lowercase.
List<Set> words = []
void run( args ) {
if ( args.size() < 1 ) {
println "Usage: counter <filename>"
return
}
File file = new File( args[0] )
println ""
println "Loading: " + file.getCanonicalPath()
List fileWords = file.text.tokenize()
int maxLen = fileWords*.size().max()
// Init empty words structure
words = []
for ( int ii in (0 .. maxLen) ) {
words[ii] = new HashSet()
}
int totalWords = 0;
fileWords.each { word ->
def wordLen = word.size()
def wordLower = word.toLowerCase()
words[ wordLen ] << wordLower
totalWords++
}
println()
words.eachWithIndex { wordSet, idx ->
int numWords = wordSet.size()
println "$idx".padLeft(5) + ": " + "${numWords}".padLeft(7) + " words"
}
}
static main(args) {
new Counter().run( args )
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment