2017-06-15 52 views
-3

请给我一点帮助。在ruby中创建最大方法

返回数组中最大的数字,不使用最大值。让测试通过。不要使用max,for或while。

def max(items) 
    # your code here 
end 

puts max([1,2,3,4,5,6]) == 6 
puts max([4,5,6,1,2,3]) == 6 
puts max([9,8,7,6,5,3,1]) == 9 

这是我第一次尝试的代码。我很新,可能会离开基地。另外,我相信它是不完整的。 不知道为什么我在这个问题上得到如此多的关注。有人可以解释这一点。

def max(items) 
x = items.each 
    if x > items 
    items = x 
    x 
    end 



end 
+3

你到目前为止尝试过什么? –

+0

刚刚编辑了我的第一个不完整的尝试。根本不可能在正确的轨道上看到我迄今从人们那里得到的答案。 –

回答

2

你能用sort吗?

def max(items) 
    items.sort.last 
end 

p max([1,2,3,4,5,6]) # => 6 
p max([4,5,6,1,2,3]) # => 6 
p max([9,8,7,6,5,3,1]) # => 9 
+0

你知道,我甚至没有想过这个。在我看来很好。由于 –

0

遵守法律的信,但也许不服从的精神:

def max items 
    items.max_by(&:itself) 
end 

def max items 
    items.min_by { |i| -i } 
end 

def max items 
    items.minmax.last 
end 

都给予产出如下:

puts max([1,2,3,4,5,6]) # 6 
puts max([4,5,6,1,2,3]) # 6 
puts max([9,8,7,6,5,3,1]) # 9 

详情请参阅Enumerable#max_byEnumerable#min_byEnumerable#minmax。精神内


更多,我们可以做这样的事情:

def max items 
    m = items[0] 
    items[1..items.length-1].each { |n| m = n if n > m } 
    m 
end 

这是假设第一个元素是最大的,然后通过所有其余的元素变为由左到右,并取代如果遇到较大号码n,则最大值为m

+1

我不认为你应该发生变异你的输入这样的(最后片段) –

+0

@SergioTulentsev没错。时隔审判:( –

+1

不担心这里有一个值得更换!?'M,*项目= items'(虽然性能稍微浪费,是) –

2

我觉得这个是很干净,并在运动的精神:

a = [9, 8, 7, 6, 5, 3, 1] 
a.reduce { |a, b| a > b ? a : b } 
#=> 9 
+2

'(a。第一个)'是多余的,'Enumerable#reduce'将使用第一个元素作为初始备忘录,如果没有明确提供:'a.reduce {| a,b | a> b? a:b}'。 – mudasobwa

+0

@mudasobwa好点,谢谢!最近我一直在切换语言,所以偶尔它会变得有点混乱。 –

1

递归比迭代建议效率较低,但仍然可以很有趣:

def max(items) 
    return nil if items.size < 1  # no data, no answer 
    return items[0] if items.size < 2 # one element is trivially the max 
    mid = items.size/2    # otherwise, find the midpoint of the array 
    first_half_max = max(items[0...mid]) # recursively find max of 1st half 
    second_half_max = max(items[mid..-1]) # recursively find max of 2nd half 
    first_half_max < second_half_max ? second_half_max : first_half_max # pick the larger 
end 

我去采取的办法是将名单减半,而不是比较容易“比较第一个元素和其余的最大元素”。这个控制递归深度,即使是非常大的列表也不会发生堆栈溢出。