diff --git a/2018/day02-2.go b/2018/day02-2.go index 16ce19c..8aa19d8 100644 --- a/2018/day02-2.go +++ b/2018/day02-2.go @@ -1,3 +1,8 @@ +// This is my second solution, c.f. https://github.com/annabunches/adventofcode/commit/3ca1a1068b749bab4d0626af32549ce2385d57bb +// for the original solution. +// +// This solution is far more elegant; it runs in O(n*m) time, instead of the original implementation's O(n^2 * m) time. +// Thanks to @lizthegrey for (probably unintentionally) prompting me to rewrite this >_> package main import ( @@ -8,25 +13,22 @@ import ( func main() { ids := util.ReadInput() + subIDs := make(map[string]struct{}) - for _, box1 := range ids { - for _, box2 := range ids { - diffIndex := -1 // diffIndex doubles as the letter to remove and a 'found' flag - for i := range box1 { - if box1[i] != box2[i] { - if diffIndex != -1 { - // If we reach here, we've detected more than one error, so we set - // diffIndex back to -1 here to avoid the conditional below this loop. - diffIndex = -1 - break - } - diffIndex = i - } - } - if diffIndex != -1 { - fmt.Printf("%s%s\n", box1[0:diffIndex], box1[diffIndex+1:]) + for _, id := range ids { + // iterate over each letter + for i := range id { + // create a subID with just letter id[i] omitted + subID := id[0:i] + id[i+1:] + + // if it's already in our map, we've found the correct output + if _, found := subIDs[subID]; found { + fmt.Println(subID) return } + + // otherwise, add the substring to our map + subIDs[subID] = struct{}{} } } }