Created
October 20, 2018 20:19
-
-
Save ipcjk/1edb696cc3a3cad8edb6c72aaa7438e8 to your computer and use it in GitHub Desktop.
Find anagramms in go
This file contains hidden or 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 ( | |
| "bufio" | |
| "log" | |
| "os" | |
| "strings" | |
| ) | |
| func main() { | |
| var anagramm = make(map[string]int, 2^20) | |
| var sawBefore = make(map[string]bool, 2^20) | |
| file, err := os.Open(os.Args[1]) | |
| if err != nil { | |
| log.Fatal(err) | |
| } | |
| defer file.Close() | |
| scanner := bufio.NewScanner(file) | |
| for scanner.Scan() { | |
| word := strings.ToLower(scanner.Text()) | |
| if _, ok := sawBefore[word]; ok { | |
| continue | |
| } | |
| sawBefore[word] = true | |
| signature := makeSig(word) | |
| if _, ok := anagramm[signature]; !ok { | |
| anagramm[signature]++ | |
| } else { | |
| anagramm[signature]++ | |
| } | |
| } | |
| } | |
| func makeSig(s string) string { | |
| if len(s) == 1 { | |
| return s | |
| } | |
| /* reserve memory for runes */ | |
| r := make([]rune, len(s)) | |
| /* Copy string runes to arrays of rune */ | |
| for k, v := range s { | |
| r[k] = v | |
| } | |
| /* Sort runes by selection sort */ | |
| for i := 0; i < len(r); i++ { | |
| pos := i | |
| for j := i + 1; j < len(r); j++ { | |
| if r[j] < r[pos] { | |
| pos = j | |
| } | |
| } | |
| if pos != 0 { | |
| r[pos], r[i] = r[i], r[pos] | |
| } | |
| } | |
| /* return string */ | |
| return string(r) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment