连续数

时间:2013-11-07 16:58:41

标签: ruby arrays string count

我需要编写一个执行以下操作的方法

consecutive_count("aaabbcbbaaa") == [["a", 3], ["b", 2], ["c", 1], ["b", 2], ["a", 3]]

我收到了代码,但看起来很难看,我正在努力寻找更好的解决方案,请提供建议。

这是我的代码:

def consecutive_count(str)

  el = str[0]; count = 0; result = []
  str.split("").each do |l|

    if (el != l)
      result << [el, count]
      count = 1
      el = l
    else
      count +=1
    end

  end
  result << [el, count] if !el.nil?

  return result

end

5 个答案:

答案 0 :(得分:3)

"aaabbcbbaaa".scan(/(?<s>(?<c>.)\k<c>*)/).map{|s, c| [c, s.length]}
# => [["a", 3], ["b", 2], ["c", 1], ["b", 2], ["a", 3]]

"aaabbcbbaaa".scan(/((.)\2*)/).map{|s, c| [c, s.length]}
# => [["a", 3], ["b", 2], ["c", 1], ["b", 2], ["a", 3]]

答案 1 :(得分:3)

这是一种方式:

s = "aaabbcbbaaa"
s.chars.chunk{|e| e }.map{|item,ary| [item,ary.size]}
# => [["a", 3], ["b", 2], ["c", 1], ["b", 2], ["a", 3]]

答案 2 :(得分:0)

Regexp解决方案:

my_s = "aaabbcbbaaa"
p  my_s.scan(/(.)(\1*)/).map{|x,y| [x, y.size + 1]}
#=> [["a", 3], ["b", 2], ["c", 1], ["b", 2], ["a", 3]]

a, result = "aaabbcbbaaa", []
result << a.slice!(/(\w)\1*/) until a.empty?

然后将结果映射到计数。

答案 3 :(得分:0)

一个不涉及正则表达式魔法的解决方案(虽然它们有点短,可能更快)是这样的:

str.each_char.each_with_object([]) do |char, result|
  if (result.last || [])[0] == char
    result.last[1] += 1
  else
    result << [char, 1]
  end
end

根据您的理解程度,它可能更好地传达您的预期意义,这可能有助于在6个月内调试该事物:)

答案 4 :(得分:-1)

您可以尝试:

def consecutive_count(str)
  result = {}
  array = str.split(//).uniq
  array.each.map {|char| result[char] = 0}
  array.each do |char|
    while str.starts_with?(char) do        
      result[char] += 1
      str[0] = ""
   end
  result
end