Re-write day 2 solution to run in O(n*m) time.
This commit is contained in:
parent
3ca1a1068b
commit
d57d3ca80b
|
@ -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
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
@ -8,25 +13,22 @@ import (
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
ids := util.ReadInput()
|
ids := util.ReadInput()
|
||||||
|
subIDs := make(map[string]struct{})
|
||||||
|
|
||||||
for _, box1 := range ids {
|
for _, id := range ids {
|
||||||
for _, box2 := range ids {
|
// iterate over each letter
|
||||||
diffIndex := -1 // diffIndex doubles as the letter to remove and a 'found' flag
|
for i := range id {
|
||||||
for i := range box1 {
|
// create a subID with just letter id[i] omitted
|
||||||
if box1[i] != box2[i] {
|
subID := id[0:i] + id[i+1:]
|
||||||
if diffIndex != -1 {
|
|
||||||
// If we reach here, we've detected more than one error, so we set
|
// if it's already in our map, we've found the correct output
|
||||||
// diffIndex back to -1 here to avoid the conditional below this loop.
|
if _, found := subIDs[subID]; found {
|
||||||
diffIndex = -1
|
fmt.Println(subID)
|
||||||
break
|
|
||||||
}
|
|
||||||
diffIndex = i
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if diffIndex != -1 {
|
|
||||||
fmt.Printf("%s%s\n", box1[0:diffIndex], box1[diffIndex+1:])
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// otherwise, add the substring to our map
|
||||||
|
subIDs[subID] = struct{}{}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue
Block a user