Day2, readFile refactor

This commit is contained in:
Karl Spickermann 2020-12-02 17:47:40 +01:00
parent fca5536f60
commit 94fe097922
6 changed files with 2091 additions and 3 deletions

View File

@ -11,12 +11,16 @@ import (
func main() {
args := os.Args[1:]
input, err := helper.GetInput(args[0])
fmt.Println(input)
if err != nil {
fmt.Println(err)
}
fmt.Println(day1(input))
fmt.Println(day1_part2(input))
numbers, err := helper.MapToNumber(input)
if err != nil {
fmt.Println(err)
}
fmt.Println(day1(numbers))
fmt.Println(day1_part2(numbers))
}
func day1(numbers []int) int {

53
day2/day2.go Normal file
View File

@ -0,0 +1,53 @@
package main
import (
"AoC2020/helper"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
args := os.Args[1:]
input, err := helper.GetInput(args[0])
if err != nil {
fmt.Println(err)
}
count := 0
countPart2 := 0
for _, row := range input {
if checkPassword(disassembleRow(row)) {
count ++
}
if checkPasswordPart2(disassembleRow(row)) {
countPart2 ++
}
}
fmt.Println(count)
fmt.Println(countPart2)
}
func disassembleRow(row string) (int, int, string, string) {
fields := strings.Split(row, " ")
scope := strings.Split(fields[0], "-")
min, _ := strconv.Atoi(scope[0])
max, _ := strconv.Atoi(scope[1])
return min, max, string(fields[1][0]), fields[2]
}
func checkPassword(min int, max int, char string, password string) bool {
occurence := strings.Count(password, char)
return (min <= occurence && occurence <= max)
}
func checkPasswordPart2(p1 int, p2 int, char string, password string) bool {
count := 0
if string(password[p1 - 1]) == char {
count++
}
if string(password[p2 - 1]) == char {
count ++
}
return count == 1
}

1000
day2/day2Input.txt Normal file

File diff suppressed because it is too large Load Diff

1000
day2/day2Max.txt Normal file

File diff suppressed because it is too large Load Diff

3
day2/day2Test.txt Normal file
View File

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

28
helper/readFile.go Normal file
View File

@ -0,0 +1,28 @@
package helper
import (
"io/ioutil"
"strconv"
"strings"
)
func GetInput(filename string) ([]string, error) {
content, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
lines := strings.Split(string(content), "\n")
return lines, err
}
func MapToNumber(strings []string) ([]int, error) {
var numbers []int
for _, line := range strings {
number, err := strconv.Atoi(line)
if err != nil {
return numbers, err
}
numbers = append(numbers, number)
}
return numbers, nil
}