2016-06-23 53 views
0

確定給定數組中連續相等元素的最大數目。確定給定數組中連續相等元素的最大數目

arr = [1, 1, 1, 1, 1, 2, 3, 3, 3, 4, 4, 1, 1] 
def recurring(arr) 
    freq = arr.inject(Hash.new(0)) { |h,v| h[v] += 1; h } 
    freq.max_by { |k,v| v } 
end 

p重複(AR

+0

你希望確定連續的最大數量給定數組中的相等元素?如果是這樣,你的第一句話是不正確的,你的代碼是不相關的,因此誤導。您需要編輯問題以澄清您想要執行的操作。 –

回答

0

這應該工作

def recurring(arr) 
    elements = arr.uniq 
    elements.map { |el| arr.count(el) }.max 
end 
0

我假定任務是確定一個給定的陣列中的連續相等的元素的最大數量。

def recurring(arr) 
    arr.chunk(&:itself).map { |_,a| a.size }.max 
end 

arr = [1, 1, 1, 1, 1, 2, 3, 3, 3, 4, 4, 1, 1] 
recurring arr 
    #=> 5 

Object#itself在Ruby v2.2中引入。對於早期版本,請寫

arr.chunk { |e| e }.map { |_,a| a.size }.max 

步驟:

enum = arr.chunk(&:itself) 
    #=> #<Enumerator: #<Enumerator::Generator:0x007fbb04943088>:each> 

我們可以看到,通過將其轉換爲一個數組將被此枚舉可以產生什麼樣的元素:

enum.to_a 
    #=> [[1, [1, 1, 1, 1, 1]], [2, [2]], [3, [3, 3, 3]], [4, [4, 4]], [1, [1, 1]]] 

b = enum.map { |_,a| a.size } 
    #=> [5, 1, 3, 2, 2] 
b.max 
    #=> 5 
相關問題