From 851e273b0782909b3c2edad7d6fb1f5c46ea1e0b Mon Sep 17 00:00:00 2001 From: James Griffin Date: Wed, 2 Dec 2020 12:53:54 -0400 Subject: [PATCH] Day 2: Part 2 --- main.go | 1 + two/day_two.go | 23 ++++++++++++++++++----- two/day_two_test.go | 14 +++++++++++++- 3 files changed, 32 insertions(+), 6 deletions(-) diff --git a/main.go b/main.go index ca510cf..308ef94 100644 --- a/main.go +++ b/main.go @@ -13,4 +13,5 @@ func main() { // Day 2 fmt.Println(two.PartOne()) + fmt.Println(two.PartTwo()) } diff --git a/two/day_two.go b/two/day_two.go index 3ced230..a97efae 100644 --- a/two/day_two.go +++ b/two/day_two.go @@ -65,10 +65,20 @@ func validate(password string, policy passwordPolicy) bool { return (instances >= policy.min && instances <= policy.max) } -func (d *db) validate() int { +func tobogganValidate(password string, policy passwordPolicy) bool { + var first, second string + first = string(password[policy.min-1]) + if len(password) >= policy.max { + second = string(password[policy.max-1]) + } + + return ((first == policy.mustHave && second != policy.mustHave) || (first != policy.mustHave && second == policy.mustHave)) +} + +func (d *db) validate(validator func(string, passwordPolicy) bool) int { valid := 0 for _, entry := range d.passwords { - if validate(entry.password, entry.policy) { + if validator(entry.password, entry.policy) { valid++ } } @@ -80,11 +90,14 @@ func (d *db) validate() int { func PartOne() string { database := db{} database.load("two/passwords.txt") - valid := database.validate() + valid := database.validate(validate) return fmt.Sprintf("Found %d valid passwords", valid) } -// PartTwo +// PartTwo Find how many passwords are valid with the new interpretation of the policy func PartTwo() string { - return "" + database := db{} + database.load("two/passwords.txt") + valid := database.validate(tobogganValidate) + return fmt.Sprintf("Found %d valid passwords", valid) } diff --git a/two/day_two_test.go b/two/day_two_test.go index 59e3a85..c540af8 100644 --- a/two/day_two_test.go +++ b/two/day_two_test.go @@ -19,10 +19,22 @@ func Test_db_valiate(t *testing.T) { database := db{} database.load("sample.txt") - validCount := database.validate() + validCount := database.validate(validate) if validCount != 2 { t.Logf("Expected 2 valid passwords, Got %d valid passwords", validCount) t.FailNow() } } + +func Test_db_tobogganValidate(t *testing.T) { + database := db{} + database.load("sample.txt") + + validCount := database.validate(tobogganValidate) + + if validCount != 1 { + t.Logf("Expected 1 valid password, Got %d valid passwords", validCount) + t.FailNow() + } +}