Created
September 23, 2011 19:35
-
-
Save fronx/1238240 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Mastermind | |
| attr_reader :answer | |
| def initialize(answer) | |
| @answer = answer | |
| end | |
| def match(picks) | |
| clues = [] | |
| picks.each_with_index do |pick, p_index| | |
| if pick == answer[p_index] | |
| clues[p_index] = :exact | |
| elsif pos = (0...answer.count).detect do |a_index| | |
| (pick == answer[a_index]) && # correct color | |
| !clues[a_index] # answer index not used yet | |
| end | |
| clues[pos] = :right_color | |
| end | |
| end | |
| clues.compact.sort_by(&:to_s) | |
| end | |
| end | |
| # tests | |
| class Object | |
| def should(value) | |
| puts(self == value ? true : "#{self.inspect} is not #{value.inspect}") | |
| end | |
| end | |
| m = Mastermind.new \ | |
| [:b, :a, :f, :a] | |
| m.match([:a, :d, :e, :a]).should [:exact, :right_color] | |
| m.match([:b, :b, :a, :b]).should [:exact, :right_color] | |
| m.match([:c, :b, :f, :a]).should [:exact, :exact, :right_color] | |
| m.match([:a, :b, :a, :e]).should [:right_color, :right_color, :right_color] | |
| m.match([:c, :a, :a, :e]).should [:exact, :right_color] | |
| m.match([:f, :f, :e, :e]).should [:right_color] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment