Last active
August 29, 2015 14:19
-
-
Save bprosnitz/bf7f98feb041223132bb to your computer and use it in GitHub Desktop.
Brute force shortest sentence with all the letters
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" | |
"io/ioutil" | |
"unicode" | |
"strings" | |
) | |
const noRepeatFirstLetter = true | |
const maxLength = 26 | |
func main() { | |
words := getWords() | |
input := generateInput(words) | |
pickLetter(input, [26]bool{}, "") | |
} | |
func getWords() []string { | |
b, err := ioutil.ReadFile("oxford.txt") | |
if err != nil { | |
panic(err) | |
} | |
return strings.Split(string(b), "\n") | |
} | |
type WordData struct { | |
body string | |
letters [26]bool | |
} | |
func processWord(word string) (wd WordData) { | |
wd.body = word | |
for _, r := range word { | |
index := unicode.ToLower(r) - 'a' | |
if index >= 0 && index < 26 { | |
wd.letters[index] = true | |
} | |
} | |
return | |
} | |
func processWords(words []string) []WordData { | |
wds := make([]WordData, len(words)) | |
for i, word := range words { | |
wds[i] = processWord(word) | |
} | |
return wds | |
} | |
type Input struct { | |
letterList [26][]WordData | |
} | |
func generateInput(words []string) (in Input) { | |
wd := processWords(words) | |
for _, word := range wd { | |
for i, hasLetter := range word.letters { | |
if hasLetter { | |
in.letterList[i] = append(in.letterList[i], word) | |
} | |
} | |
} | |
return | |
} | |
func pickLetter(in Input, usedLetters [26]bool, str string) { | |
if len(str) > maxLength { | |
return | |
} | |
hasAllLetters := true | |
for _, hasLetter := range usedLetters { | |
if !hasLetter { | |
hasAllLetters = false | |
break | |
} | |
} | |
if hasAllLetters { | |
fmt.Printf("%s\n", str) | |
return | |
} | |
for i, isUsed := range usedLetters { | |
if !noRepeatFirstLetter || !isUsed { | |
pickWord(in, usedLetters, i, str) | |
} | |
} | |
} | |
func pickWord(in Input, usedLetters [26]bool, firstLetter int, str string) { | |
for _, word := range in.letterList[firstLetter] { | |
newUsedLetters := [26]bool{} | |
for i, _ := range newUsedLetters { | |
newUsedLetters[i] = usedLetters[i] || word.letters[i] | |
} | |
pickLetter(in, newUsedLetters, str + " " + word.body) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment