How to write a ruby ​​method that returns the number of elements that are the same in two arrays, but in different positions

I am trying to encode a version of Mastermind in Ruby. To do this, I need to write a method that will return the number of elements consisting of two different arrays, but with different positions. I already have a method that can return the number of elements that match the same index.

For instance:

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
+4
source share
3 answers
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
0
source

I went differently than @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"])
0
source

( ), , ( ).

0

Source: https://habr.com/ru/post/1655868/


All Articles