Add solution for Day 1

This commit is contained in:
2021-12-01 14:03:38 +00:00
parent 3d206d4d45
commit d41d58d2cf
4 changed files with 2129 additions and 3 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -1,16 +1,24 @@
package one
import "fmt"
type One struct {
radar radar
}
func Init(filepath string) *One {
return nil
one := &One{
radar: radar{},
}
one.radar.scan(filepath)
return one
}
func (d *One) Answer() string {
return "Hello"
return fmt.Sprintf("There were %d increases in depth", d.radar.depthIncreases())
}
func (d *One) FollowUp() string {
return "World!"
return fmt.Sprintf("There were %d increases in depth when sampling a window", d.radar.windowedDepthIncreases())
}

66
one/radar.go Normal file
View File

@@ -0,0 +1,66 @@
package one
import (
"bufio"
"os"
"strconv"
)
type radar struct {
input []int
}
// scan Loads the data from input.txt into radar
func (r *radar) scan(filename string) error {
r.input = []int{}
file, err := os.Open(filename)
if err != nil {
return err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
depth, err := strconv.Atoi(scanner.Text())
if err != nil {
return err
}
r.input = append(r.input, depth)
}
return nil
}
// countIncreases for a given array of numbers how many times does one value increment after another
func countIncreases(input []int) int {
increases := 0
previousValue := -1
for _, value := range input {
if previousValue == -1 {
previousValue = value
continue
}
if value > previousValue {
increases++
}
previousValue = value
}
return increases
}
func (r *radar) depthIncreases() int {
return countIncreases(r.input)
}
func (r *radar) windowedDepthIncreases() int {
windowedDepths := []int{}
for i := 0; i < len(r.input)-2; i++ {
value := r.input[i] + r.input[i+1] + r.input[i+2]
windowedDepths = append(windowedDepths, value)
}
return countIncreases(windowedDepths)
}

52
one/radar_test.go Normal file
View File

@@ -0,0 +1,52 @@
package one
import "testing"
var testInput = []int{
199,
200,
208,
210,
200,
207,
240,
269,
260,
263,
}
func Test_scan(t *testing.T) {
r := radar{}
if err := r.scan("input.txt"); err != nil {
t.FailNow()
}
if len(r.input) != 2000 {
t.Logf("Expected 2000 entries, found %d", len(r.input))
t.Fail()
}
}
func Test_depthIncreases(t *testing.T) {
r := radar{
input: testInput,
}
increases := r.depthIncreases()
if increases != 7 {
t.Logf("Expected 7 increases, found %d", increases)
t.FailNow()
}
}
func Test_windowDepthIncrease(t *testing.T) {
r := radar{
input: testInput,
}
increases := r.windowedDepthIncreases()
if increases != 5 {
t.Logf("Expected 5 increases, found %d", increases)
t.FailNow()
}
}