this repo has no description
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

at c8d3db63099e68d453f8d28e369c6e9d129bd94c 108 lines 1.9 kB view raw
1package main 2 3import ( 4 "errors" 5 "flag" 6 "fmt" 7 "io/ioutil" 8 "os" 9 "sort" 10 "strings" 11) 12 13var inFile *string = flag.String("input", "input.txt", "the input file") 14 15func main() { 16 flag.Parse() 17 18 input, err := ioutil.ReadFile(*inFile) 19 if err != nil { 20 fail(err, "Couldn't read input file") 21 } 22 23 lines := strings.Split(string(input), "\n") 24 25 cs := checksum(lines) 26 fmt.Printf("Part1: %d\n", cs) 27 28 common, err := commonIDString(lines) 29 if err != nil { 30 fail(err, "error on part 2") 31 } 32 fmt.Printf("Part2: %s\n", common) 33} 34 35func fail(err error, msg string) { 36 fmt.Fprintf(os.Stderr, msg+": %v\n", err) 37 os.Exit(1) 38} 39 40func checksum(lines []string) int { 41 pairs, triples := 0, 0 42 for _, l := range lines { 43 if hasSetOfN([]byte(l), 2) { 44 pairs = pairs + 1 45 } 46 if hasSetOfN([]byte(l), 3) { 47 triples = triples + 1 48 } 49 } 50 return pairs * triples 51} 52 53func hasSetOfN(in []byte, n int) bool { 54 counts := make(map[byte]int) 55 for _, l := range in { 56 counts[l] = counts[l] + 1 57 } 58 for _, c := range counts { 59 if c == n { 60 return true 61 } 62 } 63 return false 64} 65 66func commonIDString(ids []string) (string, error) { 67 idPair := make([]string, 2) 68 sort.Strings(ids) 69 for i, id1 := range ids { 70 for _, id2 := range ids[i+1:] { 71 if onlyOneMismatch(id1, id2) { 72 idPair[0], idPair[1] = id1, id2 73 break 74 } 75 } 76 // Did we find our pair? Stop searching 77 if idPair[0] != "" || idPair[1] != "" { 78 break 79 } 80 } 81 if idPair[0] == "" || idPair[1] == "" { 82 return "", errors.New("Did not find ID pair") 83 } 84 return commonString(idPair[0], idPair[1]), nil 85} 86 87func onlyOneMismatch(id1, id2 string) bool { 88 mismatches := 0 89 for j, _ := range id1 { 90 if id1[j] != id2[j] { 91 mismatches = mismatches + 1 92 } 93 if mismatches > 1 { 94 break 95 } 96 } 97 return mismatches == 1 98} 99 100func commonString(s1, s2 string) string { 101 out := "" 102 for i, _ := range s1 { 103 if s1[i] == s2[i] { 104 out = out + string(s1[i]) 105 } 106 } 107 return out 108}