Created
August 9, 2017 20:18
-
-
Save heshamnaim/ff3a244fe422f7569c42a5616335ced2 to your computer and use it in GitHub Desktop.
Prancing Pony (Golang)
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
package main | |
import ( | |
"fmt" | |
"time" | |
"strings" | |
) | |
func palindromeCombinations(dwarf_names []string) <-chan []string { | |
name_channel := make(chan []string) | |
for i, v := range dwarf_names { | |
dwarf_names[i] = strings.ToUpper(v) | |
} | |
// Start a go routine on a closure that will add the outputs to the channel | |
go func(c chan []string) { | |
defer close(c) // close the channel when everything is finished | |
AddName(c, []string{}, dwarf_names, len(dwarf_names)) // We start by feeding it an empty string | |
}(name_channel) | |
return name_channel // Return the channel to the calling function | |
} | |
func isPalindrome(name string) bool { | |
for i := 0; i < len(name)/2; i++ { | |
if name[i] != name[len(name)-i-1] { | |
return false | |
} | |
} | |
return true | |
} | |
func AddName(name_channel chan []string, combo []string, dwarf_names []string, length int) { | |
if length <= 0 { | |
return | |
} | |
var newCombo []string | |
for i, ch := range dwarf_names { | |
newCombo = append(combo,ch) | |
newd := make([]string, len(dwarf_names)-1) | |
copy(newd[:i],dwarf_names[:i]) | |
copy(newd[i:],dwarf_names[i+1:]) | |
if isPalindrome(strings.Join(newCombo,"")){ | |
name_channel <- newCombo | |
} | |
AddName(name_channel, newCombo, newd, length-1) | |
} | |
} | |
func main() { | |
start := time.Now() | |
for combinations := range palindromeCombinations([]string{"Gimli", "Fili","Ilif","Ilmig","Mark"}) { | |
fmt.Println(combinations) | |
} | |
elapsed := time.Since(start) | |
fmt.Println("") | |
fmt.Printf("Running took %s", elapsed) | |
fmt.Println("Done!") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment