Skip to content

Instantly share code, notes, and snippets.

@iskigow
Created December 21, 2011 03:35
Show Gist options
  • Save iskigow/1504441 to your computer and use it in GitHub Desktop.
Save iskigow/1504441 to your computer and use it in GitHub Desktop.
TecSinapse DOJO -> One solution for the anagram's problem, using Groovy.
package br.com.tecsinapse.dojo
class Anagram {
def static anagram ( word ) {
// If the word has the size 1 it is itself the anagram, otherwise I want the permutations
return (word?.size() == 1) ? [ word ] : permutation( word )
}
def static permutation ( word ) {
if (word?.size() == 2) { // If the word has the size 2
// I know how to do the permutation!
[ "${word[0]}${word[1]}", "${word[1]}${word[0]}" ]
} else { // otherwise I will
def permutations = [] // create a list of permutations
word.each { character -> // and fix a character of the word
// then get the permutation of the word without the character
permutation( word - character ).each { interchange -> // and for each interchange I will
permutations << "${character}${interchange}" // add the new permutation
}
}
permutations
}
}
}
Anagram.anagram("biro");
package br.com.tecsinapse.dojo
class Anagram2 {
def static anagram ( word ) {
def permutation = []
if ( word?.size() > 0 ) {
word?.collect { character ->
character
}.eachPermutation { interchange ->
permutation << interchange.join( "" )
}
}
return permutation
}
}
Anagram2.anagram("biro");
package br.com.tecsinapse.dojo
String.metaClass.anagram << {
def permutation = []
if ( size() > 0 ) {
delegate.collect { character ->
character
}.eachPermutation { interchange ->
permutation << interchange.join( "" )
}
}
return permutation
}
"biro".anagram()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment