2015-11-16 89 views
-2

我有字符數組,看起來像這樣:拆分的數組子陣

chars = ["x", "o", "o", "x", "x", "o", "o", "x", "x", "x", "o", "o"] 

我需要連續字符的數量和字符的索引。它應該是這樣的:

[ 
    { index: 0, length: 1 }, # "x" 
    { index: 1, length: 2 }, # "o", "o" 
    { index: 3, length: 2 }, # "x", "x" 
    { index: 5, length: 2 }, # "o", "o" 
    { index: 7, length: 3 }, # "x", "x", "x" 
    { index: 10, length: 2 } # "o", "o" 
] 

是否有一個簡單的方法來實現這一目標?

+1

請顯示您嘗試的內容。 – lurker

+0

什麼是'x's和'o's?它們是局部變量嗎?或者是其他東西? – sawa

+0

這些只是字符'x'和'o' –

回答

4

不知道你是否可以簡單地稱呼它,但這是一個單線的方式。結果數組的格式爲[index, length]

chars.each_with_index.chunk {|i, _| i}.map {|_, y| [y.first.last, y.length]} 
#=> [[0, 1], [1, 2], [3, 2], [5, 2], [7, 3], [10, 2]] 
+2

'chunk(&:first)'也可以 – Stefan

1

兩個人做的方式:

使用Emumerable#slice_when(V.2.2 +)

count = 0 
arr = chars.slice_when { |a,b| a != b }.map do |arr| 
    sz = arr.size 
    h = { index: count, length: sz } 
    count += sz 
    h 
end 
    #=> [{:index=>0, :length=>1}, {:index=>1, :length=>2}, {:index=>3, :length=>2}, 
    # {:index=>5, :length=>2}, {:index=>7, :length=>3}, {:index=>10, :length=>2}] 

使用了反向引用

count = 0 
arr = chars.join.scan(/((.)\2*)/).map do |run, _| 
    sz = run.size 
    h = { index: count, length: sz } 
    count += sz 
    h 
end 
    #=> [{:index=>0, :length=>1}, {:index=>1, :length=>2}, {:index=>3, :length=>2}, 
    # {:index=>5, :length=>2}, {:index=>7, :length=>3}, {:index=>10, :length=>2}] 
正則表達式