Skip to content

Commit

Permalink
Final refactoring of anomaly script.
Browse files Browse the repository at this point in the history
  • Loading branch information
kmeht committed Apr 20, 2012
1 parent bff48e4 commit 2b64b52
Showing 1 changed file with 15 additions and 24 deletions.
39 changes: 15 additions & 24 deletions ruby/finalfantasyxiii2_anomaly.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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?].
Expand All @@ -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]
Expand All @@ -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)}

0 comments on commit 2b64b52

Please sign in to comment.