From 2b64b527804b4201ab5a213fa0f67ae345f8b680 Mon Sep 17 00:00:00 2001 From: Kunal Mehta Date: Fri, 20 Apr 2012 05:24:42 -0700 Subject: [PATCH] Final refactoring of anomaly script. --- ruby/finalfantasyxiii2_anomaly.rb | 39 ++++++++++++------------------- 1 file changed, 15 insertions(+), 24 deletions(-) diff --git a/ruby/finalfantasyxiii2_anomaly.rb b/ruby/finalfantasyxiii2_anomaly.rb index 864352f..ec8278e 100644 --- a/ruby/finalfantasyxiii2_anomaly.rb +++ b/ruby/finalfantasyxiii2_anomaly.rb @@ -7,17 +7,20 @@ where the Xs are the values of the nodes numbered 0 to n clockwise. You can pick 0 arbitrarily. + Output: An array of clock indices to visit in sequence. + This script brute-forces the clock anomaly puzzles found in the temporal rifts around the timeline. Because the script - maintains a global state during the recursion (versus passing a - copy of the state throughout each step), it could probably handle - some really large versions of the puzzle. + maintains a global state during the recursion (versus passing + copies throughout each step), it could probably handle some + really large versions of the puzzle. 04/19/2012 - original - 04/20/2012 - initial cleanup, command-line argument + 04/20/2012 - refactoring =end + # GLOBAL STATE # The clock is represented as an array of pairs of the form [value, active?]. @@ -37,14 +40,6 @@ def value(index) $clock[index][0] end -def upper(start) - (start + value(start)) % $clock.length -end - -def lower(start) - (start - value(start)) % $clock.length -end - # Checks if a node is empty. def empty?(index) not $clock[index][1] @@ -56,49 +51,45 @@ def win? end # Checks if both clock hands point to empty nodes. -def lose?(hand1, hand2) - empty?(hand1) and empty?(hand2) +def lose? + empty?($hands[0]) and empty?($hands[1]) end # Updates the clock hands based on a move. def update_hands(move) $hands = [-value(move), value(move)].map{|h| (h + move) % $clock.length} - $hands = [(move - value(move)) % $clock.length, (move + value(move)) % $clock.length] end # Executes the move, updates state, and returns the new positions of the clock hands. def execute(move) $moves << move $clock[move][1] = false + update_hands(move) end # Reverts the state to before the last move. def revert $clock[$moves.pop][1] = true + update_hands($moves[-1]) end -# RECURSIVE FUNCTION +# SCRIPT LOGIC def do_move(move) return if empty?(move) - h1 = lower(move) - h2 = upper(move) execute(move) if win? puts $moves.inspect exit - elsif lose?(h1, h2) + elsif lose? revert and return else - do_move(h1) - do_move(h2) + do_move($hands[0]) + do_move($hands[1]) revert and return end end - -# EXECUTION - (0..($clock.length - 1)).each{|start| do_move(start)}