我正在尝试用Ruby编写游戏Mastermind的版本。为此,我需要编写一个方法,该方法将返回两个不同数组共有多少个元素的计数,但这些元素位于不同的位置。我已经有一个方法可以返回在同一索引处正确的项目数。
例如:
comparing ["red", "green", "red", "orange"] to ["blue", "red", "blue", "blue"]
#should return 1
comparing ["red", "red", "orange", "orange"] to ["orange", "orange", "red", "red"]
#should return 4
comparing ["green", "green", "orange", "blue"] to ["green", "green", "orange", "red"]
#should return 0
答案 0 :(得分:0)
def f a, b
c = [a, b].transpose.inject [] do |m, e|
m << e if e.first != e.last
m
end.transpose
puts c.first.size - (c.last - c.first).size
end
f [:red, :green, :red, :orange], [:blue, :red, :blue, :blue] # => 1
f [:red, :red, :orange, :orange], [:orange, :orange, :red, :red] # => 4
f [:green, :green, :orange, :blue], [:green, :green, :orange, :red] # => 0
# it works with Strings, also
f %w/red green red orange/, %w/blue red blue blue/ # => 1
f %w/red red orange orange/, %w/orange orange red red/ # => 4
f %w/green green orange blue/, %w/green green orange red/ # => 0
答案 1 :(得分:0)
我的方式与@DigitalRoss不同。
def match_at_wrong_position(master, guess)
guess = guess.dup # dup, so we do not modify the input param
master.each_with_index.inject(0) do |count, (item, index)|
found_at = guess.index(item) # is it provided as a guess
next count if found_at.nil? # not found
guess[found_at] = nil # make sure it is not found again
found_at != index ? count + 1 : count # if not same position, then increment
end
end
p match_at_wrong_position(["red", "green", "red", "orange"], ["blue", "red", "blue", "blue"])
p match_at_wrong_position(["red", "red", "orange", "orange"], ["orange", "orange", "red", "red"])
p match_at_wrong_position(["green", "green", "orange", "blue"], ["green", "green", "orange", "red"])
答案 2 :(得分:0)
只需要发明一种方法来计算正确的颜色(不要介意位置),然后减去相同指数(你已经拥有)的正确颜色数。