Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

ruby - Counting changes in an array

I would like to count the number of times "red" is followed by "green" in this array:

["red", "orange", "green", "red", "yellow", "blue", "green"]

If it is another color, the code should ignore it and proceed to the next item in the array.

event_type.each_slice(2) do |red, green|
  break unless green
  count = count + 1
end

p "The count is #{count}"

Step 1:

Look for red

Step 2:

IF not last item 
           Compare with next item on array
ELSE       Go to Step 4

Step 3:

IF green, count = count + 1
          Go to Step 1
ELSE      Go to Step 2

Step 4:

Print Count
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is a perfect use-case for Ruby famous flip-flop:

input = %w[red orange green red yellow blue green]

input.reduce(0) do |count, e|
  if (e == "red")..(e == "green") and (e == "green")
    count + 1  # inc on right boundary
  else
    count
  end
end
#??2

Also tested on

%w[yellow green green red orange green red yellow blue green red yellow]

FWIW, this is a second question I answered suggesting the flip-flop in a week. The previous one is here.


Clean solution from Stefan Pochmann

input.count { |x| x == "green" if (x == "red")..(x == "green") }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...