Day 2: Part 1

This commit is contained in:
James Griffin
2020-12-02 12:41:39 -04:00
parent 1225256007
commit 004b5c07a8
5 changed files with 1128 additions and 3 deletions

10
main.go
View File

@@ -3,10 +3,14 @@ package main
import ( import (
"fmt" "fmt"
"github.com/thatguygriff/aoc2020/one" "github.com/thatguygriff/aoc2020/two"
) )
func main() { func main() {
fmt.Println(one.PartOne()) // Day 1
fmt.Println(one.PartTwo()) // fmt.Println(one.PartOne())
// fmt.Println(one.PartTwo())
// Day 2
fmt.Println(two.PartOne())
} }

90
two/day_two.go Normal file
View File

@@ -0,0 +1,90 @@
package two
import (
"bufio"
"fmt"
"os"
)
type passwordPolicy struct {
min int
max int
mustHave string
}
type passwordEntry struct {
policy passwordPolicy
password string
}
type db struct {
passwords []passwordEntry
}
func (d *db) load(filename string) error {
file, err := os.Open(filename)
if err != nil {
return err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
var min, max int
var mustHave, p string
count, err := fmt.Sscanf(scanner.Text(), "%d-%d %1s: %s", &min, &max, &mustHave, &p)
if err != nil {
return err
} else if count != 4 {
return fmt.Errorf("Unable to parse entry %q", scanner.Text())
}
e := passwordEntry{
policy: passwordPolicy{
min: min,
max: max,
mustHave: mustHave,
},
password: p,
}
d.passwords = append(d.passwords, e)
}
return nil
}
func validate(password string, policy passwordPolicy) bool {
instances := 0
for _, letter := range password {
if string(letter) == policy.mustHave {
instances++
}
}
return (instances >= policy.min && instances <= policy.max)
}
func (d *db) validate() int {
valid := 0
for _, entry := range d.passwords {
if validate(entry.password, entry.policy) {
valid++
}
}
return valid
}
// PartOne Find how many passwords are valid according to their policy
func PartOne() string {
database := db{}
database.load("two/passwords.txt")
valid := database.validate()
return fmt.Sprintf("Found %d valid passwords", valid)
}
// PartTwo
func PartTwo() string {
return ""
}

28
two/day_two_test.go Normal file
View File

@@ -0,0 +1,28 @@
package two
import "testing"
func Test_db_load(t *testing.T) {
database := db{}
if err := database.load("sample.txt"); err != nil {
t.Log(err)
t.FailNow()
}
if len(database.passwords) != 3 {
t.Logf("Expected 3 passwords, Got %d passwords", len(database.passwords))
t.FailNow()
}
}
func Test_db_valiate(t *testing.T) {
database := db{}
database.load("sample.txt")
validCount := database.validate()
if validCount != 2 {
t.Logf("Expected 2 valid passwords, Got %d valid passwords", validCount)
t.FailNow()
}
}

1000
two/passwords.txt Normal file

File diff suppressed because it is too large Load Diff

3
two/sample.txt Normal file
View File

@@ -0,0 +1,3 @@
1-3 a: abcde
1-3 b: cdefg
2-9 c: ccccccccc