func AnagramsFromReader(in io.Reader) map[string][]string { reader := bufio.NewReader(in) var nextTok func() (string, error) anagrams := make(map[string][]string) nextTok = func() (string, error) { line, notDone, err := reader.ReadLine() if err != nil { return "", err } for notDone { var nextChunk []byte nextChunk, notDone, err = reader.ReadLine() if err != nil { return "", err } line = append(line, nextChunk...) } return string(line), err } // nextTok = func() (string, error) { // line, notDone, err := reader.ReadLine() // if err != nil { // return "", err // } else if notDone { // restline, err2 := nextTok() // possible problem // if err2 != nil { // return "", err2 // } // return string(line) + string(restline), nil // } // return string(line), err // } line, linerr := nextTok() for linerr == nil { if !wordValidator.MatchString(line) { // skip non validating lines line, linerr = nextTok() continue } ss := ss.NewSortString(line) sort.Sort(ss) index := ss.String() slice := anagrams[index] if slice == nil { slice = make([]string, 1) } anagrams[index] = append(slice, line) line, linerr = nextTok() } return anagrams }
// maps have unique keys, so lets just use it as a set func getUniques(perms []string, size int) map[string]int { results := make(map[string]int) for _, cur := range perms { cur = cur[0:size] // slice it sorts := ss.NewSortString(cur) sort.Sort(sorts) // sort it results[sorts.String()] = 0 // store it } return results }
func runHandler(w http.ResponseWriter, r *http.Request) { in := ss.NewSortString(r.FormValue("input")) allperms := getAllPerms(in) size := in.Len() output := "Results are: \n" for n := size; n >= 3; n-- { output += fmt.Sprintf("\n\nFor size: %d\n", n) uniques := getUniques(allperms, n) for k, _ := range uniques { output += fmt.Sprintf("%s", strings.Join(anagrams[k], "\n")) } } output += fmt.Sprintf("\n") renderTemplate(w, "results", &templateParams{output, in.String()}) }