1
0
Fork 0

update day1

rewrite all functions to methods
This commit is contained in:
Sebastian Mark 2024-12-02 17:13:25 +01:00
parent e492d553aa
commit 3fbc954566

View file

@ -6,39 +6,43 @@ import (
"sort" "sort"
) )
var list_a, list_b []int type list struct {
a []int
b []int
}
func main() { func main() {
list_a, list_b = helper.ReadLinesTwoIntSlices() list_a, list_b := helper.ReadLinesTwoIntSlices()
list := list{a: list_a, b: list_b}
// part 1 // part 1
distance := list_distance(list_a, list_b) distance := list.distance()
fmt.Printf("Distance: %v\n", distance) fmt.Printf("Distance: %v\n", distance)
// part 2 // part 2
similarity := list_similarity(list_a, list_b) similarity := list.similarity()
fmt.Printf("Similarity: %v\n", similarity) fmt.Printf("Similarity: %v\n", similarity)
} }
func list_distance(list_a []int, list_b []int) (dist int) { func (l list) distance() (dist int) {
sort.Ints(list_a) sort.Ints(l.a)
sort.Ints(list_b) sort.Ints(l.b)
for i := range list_a { for i := range l.a {
dist += helper.Abs(list_a[i] - list_b[i]) dist += helper.Abs(l.a[i] - l.b[i])
} }
return dist return dist
} }
func list_similarity(list_a []int, list_b []int) (sim int) { func (l list) similarity() (sim int) {
for _, val := range list_a { for _, val := range l.a {
valcount := countIntInList(list_b, val) valcount := countIntInSlice(l.b, val)
sim += valcount * val sim += valcount * val
} }
return sim return sim
} }
func countIntInList(lst []int, i int) (count int) { func countIntInSlice(lst []int, i int) (count int) {
for _, val := range lst { for _, val := range lst {
if val == i { if val == i {
count++ count++