Created
December 7, 2021 05:48
-
-
Save Nv7-GitHub/270c73d94e9b48d9d4882e81ebcc2ed3 to your computer and use it in GitHub Desktop.
Advent of Code 2021 Day 7
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
_ "embed" | |
"fmt" | |
"math" | |
"strconv" | |
"strings" | |
) | |
//go:embed input.txt | |
var input string | |
func parseInt(val string) int { | |
v, err := strconv.Atoi(val) | |
if err != nil { | |
panic(err) | |
} | |
return v | |
} | |
func calcFuel(target int, dists []int) int { | |
fuel := 0 | |
for _, dist := range dists { | |
fuel += int(math.Abs(float64(dist - target))) | |
} | |
return fuel | |
} | |
func main() { | |
vs := strings.Split(input, ",") | |
nums := make([]int, len(vs)) | |
for i, v := range vs { | |
nums[i] = parseInt(v) | |
} | |
min := 100 | |
max := -1 | |
for _, v := range nums { | |
if v < min { | |
min = v | |
} | |
if v > max { | |
max = v | |
} | |
} | |
lowest := 100000000 | |
for v := min; v <= max; v++ { | |
fuel := calcFuel(v, nums) | |
if fuel < lowest { | |
lowest = fuel | |
} | |
} | |
fmt.Println(lowest) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
_ "embed" | |
"fmt" | |
"math" | |
"strconv" | |
"strings" | |
) | |
//go:embed input.txt | |
var input string | |
func parseInt(val string) int { | |
v, err := strconv.Atoi(val) | |
if err != nil { | |
panic(err) | |
} | |
return v | |
} | |
func calcNum(v int) int { | |
/* diff := 0 | |
for i := 1; i <= v; i++ { | |
diff += i | |
} | |
return diff*/ | |
return v * (v + 1) / 2 | |
} | |
func calcFuel(target int, dists []int) int { | |
fuel := 0 | |
for _, dist := range dists { | |
d := int(math.Abs(float64(dist - target))) | |
diff := calcNum(d) | |
fuel += diff | |
} | |
return fuel | |
} | |
func main() { | |
vs := strings.Split(input, ",") | |
nums := make([]int, len(vs)) | |
for i, v := range vs { | |
nums[i] = parseInt(v) | |
} | |
min := 100 | |
max := -1 | |
for _, v := range nums { | |
if v < min { | |
min = v | |
} | |
if v > max { | |
max = v | |
} | |
} | |
lowest := math.MaxInt | |
for v := min; v <= max; v++ { | |
fuel := calcFuel(v, nums) | |
if fuel < lowest { | |
lowest = fuel | |
} | |
} | |
fmt.Println(lowest) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment