r/learnruby • • Sep 22 '14

Mastermind Game Question

I have two strings guess = 'rgby' code = 'gbyg'

How do I count the correct number of colors/characters guessed in the code? In this case the answer would be 3. The guess has 3 correct guesses contained in the code, irrespective of position.

1 Upvotes

3 comments sorted by

View all comments

Show parent comment

1

u/zaclacgit Sep 22 '14 edited Sep 22 '14
def check_position(guess, answer)
  positions = []
  guess.split(//).each_with_index {|color, position| positions.push(color == answer[position])}
  positions
end

Like that?

Edit - Oh, you're wanting the number of correct positions? Not where the correct positions are, right?

def check_position(guess, answer)
  count = 0
  guess.split(//).each_with_index {|color, position| count += 1 if color == answer[position]}
  count
end

Or, using the top version of check_position

 correct_positions = check_position(guess, answer).count(true)