AdventOfCode2021/day07/7a/main.go

52 lines
894 B
Go
Raw Normal View History

2021-12-07 12:53:48 +00:00
package main
import (
2021-12-16 21:11:39 +00:00
"AdventOfCode2021/shared"
2021-12-07 12:53:48 +00:00
"bufio"
"fmt"
"math"
"os"
"strconv"
"strings"
)
func main() {
content := returnContent("../input")
2021-12-16 19:55:49 +00:00
//content := returnContent("../testInput")
2021-12-07 12:53:48 +00:00
2021-12-16 21:11:39 +00:00
list := shared.MergeSort((*content), 0, len(*content)-1)
2021-12-07 12:53:48 +00:00
position := list[len(list)/2]
var cost float64
for i := 0; i < len(list); i++ {
cost += math.Abs(float64(position) - float64(list[i]))
}
fmt.Println(cost)
}
func returnContent(path string) *[]int {
//read file and return it as an array of integers
file, err := os.Open(path)
var content []int
if err != nil {
fmt.Println("Unlucky, the file didn't open")
return &content
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
text := strings.Split(scanner.Text(), ",")
for _, v := range text {
num, _ := strconv.Atoi(v)
content = append(content, num)
}
}
return &content
}