Created
July 27, 2011 10:44
-
-
Save timyates/1109127 to your computer and use it in GitHub Desktop.
Phone Number coding problem in Groovy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Numerics to chars they represent | |
def mnemonics = [ | |
'2': 'ABC', | |
'3': 'DEF', | |
'4': 'GHI', | |
'5': 'JKL', | |
'6': 'MNO', | |
'7': 'PQRS', | |
'8': 'TUV', | |
'9': 'WXYZ' | |
] | |
// Contruct the reverse of the mnemonics map, so chars map to numbers | |
def charCode = mnemonics.collectEntries { num, keys -> | |
keys.toList().collectEntries { [ (it):num ] } | |
} | |
// For a given word, what is its numeric representaion | |
def encodeWord = { String word -> | |
word.toUpperCase().collect { charCode[ it ] }.join() | |
} | |
def words = new File( '/usr/share/dict/words' ).with { | |
// Uppercase each line, and construct a map of numericRep->[word,word,...] | |
readLines()*.toUpperCase().inject( [:].withDefault { [] as Set } ) { map, word -> | |
map[ encodeWord( word ) ] << word.toUpperCase() | |
map | |
} | |
} | |
def encode = { String number -> | |
def splitWords = (1..<number.size()).collect { split -> | |
[ words[ number.take( split ) ], words[ number.drop( split ) ] ].with { r -> | |
r.any { it.size() == 0 } ? null : r | |
} | |
} | |
// Remove nulls, get all the pair combinations, and join them as a String | |
[[words[ number ]], *splitWords].findAll{ it }*.combinations()*.collect { | |
it.join( ' ' ) | |
}.flatten() | |
} | |
assert encode( '6327537' ).contains( 'MEASLES' ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Requires Groovy 1.8.1 for
take
anddrop