Skip to content

Instantly share code, notes, and snippets.

@timyates
Created July 27, 2011 10:44
Show Gist options
  • Save timyates/1109127 to your computer and use it in GitHub Desktop.
Save timyates/1109127 to your computer and use it in GitHub Desktop.
Phone Number coding problem in Groovy
// 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' )
@timyates
Copy link
Author

Requires Groovy 1.8.1 for take and drop

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment