Returning all maximum or minimum values that can be multiple

后端 未结 3 690
情深已故
情深已故 2020-12-02 02:30

Enumerable#max_by and Enumerable#min_by return one of the relevant elements (presumably the first one) when there are multiple max

3条回答
  •  旧巷少年郎
    2020-12-02 02:45

    arr=[1, 2, 3, 5, 7, 8]
    mods=arr.map{|e| e%3}
    

    find max

    max=mods.max
    indices = []
    mods.each.with_index{|m, i| indices << i if m.eql?(max)}
    arr.select.with_index{|a,i| indices.include?(i)}
    

    find min

    min = mods.min
    indices = []
    mods.each.with_index{|m, i| indices << i if m.eql?(min)}
    arr.select.with_index{|a,i| indices.include?(i)}
    

    Sorry for clumsy code, will try to make it short.

    Answer by @Sergio Tulentsev is the best and efficient answer, found things to learn there. +1

提交回复
热议问题