Day2, readFile refactor

master
Karl Spickermann 1 year ago
parent
commit
94fe097922
  1. 10
      day1/day1.go
  2. 53
      day2/day2.go
  3. 1000
      day2/day2Input.txt
  4. 1000
      day2/day2Max.txt
  5. 3
      day2/day2Test.txt
  6. 28
      helper/readFile.go

@ -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 {

@ -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
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

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

@ -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
}
Loading…
Cancel
Save