...
| Code Block |
|---|
import java.util.regex.Pattern
keypadMap = [0:"", 1:"", 2:"abc", 3:"def", 4:"ghi", 5:"jkl", 6:"mno", 7:"pqrs", 8:"tuv", 9:"wxyz"]
dictionary = new File("words")
regexBuilder = { digit -> '[' + keypadMap[digit.toInteger()] + ']' }
patternBuilder = { number -> Pattern.compile('^' + number.collect(regexBuilder).join() + '$') }
def matchWords(phNumber) {
def p = patternBuilder(phNumber)
def matches = []
dictionary.eachLine{ line -> if (p.matcher(line).matches()) matches << line }
if (matches)
println "Matches for $phNumber: " + matches.join(' ')
else
println "No matches found for $phNumber"
}
def matchPairs(phNumber) {
def p1 = patternBuilder(phNumber[0..2])
def p2 = patternBuilder(phNumber[3..6])
def first = [], second = []
dictionary.eachLine { line ->
if (p1.matcher(line).matches()) first << line
if (p2.matcher(line).matches()) second << line
}
if (first && second)
println "$phNumber matches word pairs: " + [first, second].combinations()
else
println "Couldn't find word pair for $phNumber"
}
[ '2345678', '2455466', '2276228', '6662342', '2476642',
'2742742', '7338433', '7678243', '3742253', '7264253',
'7683353', '7684453', '7837453', '7378453', '3749953',
'7877363', '2668363', '5367273', '7377473', '7877673',
'7278873', '2646283', '3377483'
].each{ matchWords it }
[ '8765432', '9689474', '9687283', '2283278'
].each{ matchPairs it }
|
against the attached words file yields these results:
...