Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import(
- "os"
- "bufio"
- "errors"
- "fmt"
- )
- func main() {
- wordlist, err := getWordlistFrom("wordlist.txt")
- if err != nil {
- fmt.Println(err)
- return
- }
- start, end, err := getUserInput()
- if err != nil {
- fmt.Println(err)
- return
- }
- ladder, err := getWordLadder(start, end, wordlist)
- if err != nil {
- fmt.Println(err)
- return
- }
- for _, word := range ladder {
- println(word)
- }
- }
- func getWordLadder(start, end string, wordlist []string) ([]string, error) {
- ladder := []string{start}
- for step := 1; step <= 4; step++ {
- next := ""
- for _, word := range wordlist {
- matchesWithStart := getMatchingCharsBetweenStrings(start, word)
- matchesWithEnd := getMatchingCharsBetweenStrings(end, word)
- if matchesWithStart == len(start) - step && matchesWithEnd == step {
- next = word
- break
- }
- }
- if len(next) == 0 {
- return nil, errors.New("Word ladder not possible with current wordlist")
- }
- ladder = append(ladder, next)
- }
- ladder = append(ladder, end)
- return ladder, nil
- }
- func getUserInput() (string, string, error) {
- if len(os.Args) != 3 {
- return "", "", errors.New("Invalid number of arguments")
- }
- return os.Args[1], os.Args[2], nil
- }
- func getWordlistFrom(path string) ([]string, error) {
- file, err := os.Open(path)
- if err != nil {
- return nil, err
- }
- defer file.Close()
- var lines []string
- scanner := bufio.NewScanner(file)
- for scanner.Scan() {
- lines = append(lines, scanner.Text())
- }
- return lines, scanner.Err()
- }
- func getMatchingCharsBetweenStrings(a, b string) (matches int) {
- for _, charA := range a {
- for _, charB := range b {
- if charA == charB {
- matches++
- }
- }
- }
- return
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement