Spock Web Console

subscribe to the feed Subscribe
WordCountSpec (via #spockwebconsole)
tweet this script Tweet

WordCountSpec

Published 1 month ago by Eric
Actions  ➤ Edit In Console Back To Console Show/Hide Line Numbers View Recent Scripts
import spock.lang.Specification

class WordCountSpec extends Specification {

    def "start"() {
        expect:
        wordCount()
    }

    final alphabetMap = generate()

    def wordCount() {
        def wordsFound = []

        // you must provide word list, each word on a new line
        new File('words.txt').eachLine { word ->
            def valueOfWord = count2(word.toLowerCase())
            if(valueOfWord == 100) {
                wordsFound << word.toLowerCase()
            }
        }
        println wordsFound
        println wordsFound.size()
        true
    }

    // Builds a map to lookup values of letters.
    // [a:1, b:2, c:3, d:4, e:5, f:6, g:7,....]
    static generate() {
        def map = [:]
        ('a'..'z').eachWithIndex { String letter, int numVal -> // i starts at 0
            map[(letter)] = numVal + 1
        }
        map
    }

    // Count the values of each letter in a word
    def count2(String word) {
        def result = 0
        word.each {
            if(!alphabetMap.containsKey(it)){
                // a non letter was found, ignore it
                return 0
            }
            result += alphabetMap[(it)]
        }
        result
    }

    //
    def count(word) {
        final offset = 96
        def result = 0
        def charArray = word.toCharArray()

        charArray.each { character ->
            result += ((int)character.charValue() - offset)
        }
        result
    }
}