arr = [1,4,6,3]
arr2 = [3,4,3,6]
arr.each do |item|
p "X" if arr2.include?(item)
end
but the above only returns X if the element is found but I want it to return "O" when both array contain same element in the same index and I don't want the X to repeat if there is more than one element found.
I tried using each
with
index
but couldn't get the result
I would wrap the logic into a class with a few helper methods:
class CodeBreaker
def initialize(guess, code)
@guess = guess
@code = code
@numbers = Set.new(code)
return if guess.size == code.size
raise ArgumentError, 'guess and code need to share the same size'
end
def hint
guess.map.with_index do |number, index|
mark_when_equal_at_index(index) || mark_when_number_in_code(number) || '-'
end
end
private
attr_reader :guess, :code, :numbers
def mark_when_equal_at_index(index)
'O' if guess[index] == code[index]
end
def mark_when_number_in_code(number)
'X' if code.include?(number)
end
end
code_breaker = CodeBreaker.new([1, 4, 6, 3], [3, 4, 3, 6])
code_breaker.hint
#=> ["-", "O", "X", "X"]