文字列に含まれる全てのパターンをカウントする問題。
count_all_pattern がごちゃっとしてしまっている。もう少し良い方法がありそう。
CHALLENGE DESCRIPTION:
You have a string composed of the following symbols: ‘>’, ‘<’, and ‘-’. Your task is to find, count, and print to the output a number of arrows in the string. An arrow is a set of the following symbols: ‘>>–>’ or ‘<–<<’.
Note that one character may belong to two arrows at the same time. Such example is shown in the line #1.
INPUT SAMPLE:
The first argument is a path to a file. Each line includes a test case with a string of different length from 10 to 250 characters. The string consists of ‘>’, ‘<’, and ‘-’ symbols.
<--<<--<< <<>>--><--<<--<<>>>-->< <-->>
OUTPUT SAMPLE:
2 4 0
CONSTRAINTS:
- An arrow is a set of the following symbols: ‘>>–>’ or ‘<–<<’.
- One symbol may belong to two arrows at the same time.
- The number of test cases is 40.
My Code
#!/usr/bin/env ruby -w ARROWS = [">>-->", "<--<<"] def count_arrows(str) ARROWS.inject(0) do |count, arrow| count += count_all_pattern(str, arrow) end end def count_all_pattern(str, pattern) i = 0 count = 0 str_size = str.size while i < str_size index = str.index(pattern, i) unless index.nil? i = index count += 1 end i += 1 end count end ARGF.each_line do |line| puts count_arrows(line.chomp) end