Created
June 17, 2022 12:56
-
-
Save h12w/35a0dd0d3074ec95a5ea7ec267c1f065 to your computer and use it in GitHub Desktop.
Find all English words by its length and sum of alphabetical value of letters
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" | |
"fmt" | |
"log" | |
"os" | |
"strings" | |
) | |
func main() { | |
const targetValue = 42 | |
const targetLenght = 4 | |
if err := findWordValue(targetValue, targetLenght, func(word string) { | |
fmt.Println(word) | |
for _, c := range word { | |
fmt.Printf("%s = %02d\n", strings.ToUpper(string(c)), wordValue(string(c))) | |
} | |
}); err != nil { | |
log.Fatal(err) | |
} | |
} | |
func findWordValue(targetValue, targetLength int, output func(string)) error { | |
f, err := os.Open("/usr/share/dict/words") | |
if err != nil { | |
return err | |
} | |
defer f.Close() | |
scanner := bufio.NewScanner(f) | |
for scanner.Scan() { | |
word := strings.ToLower(scanner.Text()) | |
if len(word) != targetLength || wordValue(word) != targetValue { | |
continue | |
} | |
output(word) | |
} | |
if err := scanner.Err(); err != nil { | |
return err | |
} | |
return nil | |
} | |
func wordValue(word string) int { | |
sum := 0 | |
for _, c := range word { | |
sum += int(c - 'a' + 1) | |
} | |
return sum | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment