1 files changed, 28 insertions(+), 0 deletions(-)

M main.go
M main.go +28 -0
@@ 49,6 49,34 @@ func main() {
 	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)
 }