# HG changeset patch # User Sean E. Russell # Date 1614099454 21600 # Tue Feb 23 10:57:34 2021 -0600 # Node ID 7f00e615e1ab7846a7b5671eb5b8bf5bfbb496d4 # Parent 54ee3f979fc984ba3e3d34fc8a4fd2be672274b9 Add cycle detection diff --git a/main.go b/main.go --- a/main.go +++ b/main.go @@ -49,6 +49,34 @@ ttl := total(ints, diffs) // wc is the index of the final winner wc := max(ttl) + // Look for cycles + past := make([]int, 0) + for { + d2 := diff(ints, wc, R) + t2 := total(ints, d2) + w2 := max(t2) + // If the current max is the same as the previous max, then the algorithm has settled + // on a winner. + if w2 == wc { + break + } + // Check to see if we've seen this winner before (but not immediately before); if so, + // then we're looping; dump the cycle list and exit. + for _, cand := range past { + if w2 == cand { + fmt.Print("Cycle found in ") + for _, c := range past { + fmt.Printf("%s => ", lines[0][c]) + } + fmt.Printf("%s => ...\n", lines[0][w2]) + return + } + } + // Add the current winner to the "seen before" list + past = append(past, w2) + // Set the "immediately previous" winner to the current winner for the next loop + wc = w2 + } printDetails(wc, lines, badVotes, ints, diffs, ttl) }