Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save h12w/35a0dd0d3074ec95a5ea7ec267c1f065 to your computer and use it in GitHub Desktop.
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
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