Advent of Code in Go: #4

1 minute read

In this series I explore the Advent of Code, or AoC for short, with the Go programming language. Every day, as real life permits, I will be solving a puzzle from the series. I will document each day with a solution in Go and a walkthrough of the code.

You can find the previous walkthroughs here.

The puzzle

We are faced with a password challenge. The first rule of this password system is that no passphrase may contain 2 the same words.

I chose to split the passphrase and push each field into a map, incrementing its value when doing so. Whenever I hit a value greater than 1 I know that the word occurs 2 times in the passphrase and thus the password is invalid.

// validates the given password
func validate(password string) bool {
	m := make(map[string]int)

	fields := strings.Fields(password)

	for _, v := range fields {
		m[v]++

		if m[v] > 1 {
			return false
		}
	}

	return true
}

Next the following rule is added “words in a passphrase may not be anagrams”. Using the same technique as before I can construct a map of the words. Anagrams are basically the same characters used in a different sequence, so sorting the strings before adding it to the map will solve this question.

func validateAnagram(password string) bool {
	m := make(map[string]int)

	fields := strings.Fields(password)

	for _, v := range fields {

		chars := strings.Split(v, "")
		sort.Strings(chars)

		v2 := strings.Join(chars, "")

		m[v2]++

		if m[v2] > 1 {
			return false
		}
	}

	return true
}

I learned about the strings library a little more. Creating and using arrays and maps is also quite different from the Java and Clojure world. I think they will cause me quite some headache, but that also means these puzzles will give me a good understanding of how they function.

Tags: , ,

Updated: