File tree Expand file tree Collapse file tree 2 files changed +1063
-0
lines changed
Expand file tree Collapse file tree 2 files changed +1063
-0
lines changed Original file line number Diff line number Diff line change 1+ package day1
2+
3+ import (
4+ "bufio"
5+ "fmt"
6+ "os"
7+ "sort"
8+ "strconv"
9+ "strings"
10+ "testing"
11+ )
12+
13+ func TestDay1 (t * testing.T ) {
14+ file , err := os .Open ("input" )
15+ if err != nil {
16+ t .Fatal ("can't open input file" )
17+ }
18+ defer file .Close ()
19+
20+ var column1 []int
21+ var column2 []int
22+
23+ // 1. scan data
24+ scanner := bufio .NewScanner (file )
25+ for scanner .Scan () {
26+ // ex: 31594 93577
27+ line := scanner .Text ()
28+
29+ lineStrSlice := strings .Split (line , " " )
30+ lineIntVar1 , err := strconv .Atoi (lineStrSlice [0 ])
31+ if err != nil {
32+ t .Fatal (err )
33+ }
34+
35+ lineIntVar2 , err := strconv .Atoi (lineStrSlice [1 ])
36+ if err != nil {
37+ t .Fatal (err )
38+ }
39+
40+ column1 = append (column1 , lineIntVar1 )
41+ column2 = append (column2 , lineIntVar2 )
42+ }
43+
44+ if scanner .Err () != nil {
45+ t .Fatal ("scanner err" )
46+ }
47+
48+ // 2. sort column1 and column2
49+ sort .Ints (column1 )
50+ sort .Ints (column2 )
51+
52+ // 3. get abs value and sum
53+ var sum int
54+ for i := range column1 {
55+ distance := column1 [i ] - column2 [i ]
56+ if distance < 0 {
57+ distance = - distance
58+ }
59+ sum += distance
60+ }
61+
62+ fmt .Println (sum )
63+ }
You can’t perform that action at this time.
0 commit comments