Sergy Fedorchuk Sergy Fedorchuk - 5 months ago 10
Ruby Question

Find min and extract a key from a hash

How to find a min by last values in hash:

tasks = {1=>[[2, 9]], 2=>[[3, 4]], 3=>[[1, 6]]}


So, it must return a "key" - "2", as its last value "4" is the smallest in comparison to "9" and "6".

Answer

You could re-arrange your hash slightly so you have an array of hashes rather than taking the last value of each array in a multi-dimensional array.

tasks = {2=>4, 4=>3}

pc = {
  1 => [{ 
    task: 1,
    load: 5
  }],
  2 => [{
    task: 3,
    load: 4
  }]
}

tasks.each do |key, value|
  pc[(pc.min_by {|k,v| v.map {|k| k[:load]}.reduce(&:+)}.first)] << {
    task: key,
    load: value
  }
end

> pc
#=> {1=>[{:task=>1, :load=>5}, {:task=>4, :load=>3}], 2=>[{:task=>3, :load=>4}, {:task=>2, :load=>4}]}

Or to match your new question, you could use this (I'm sure there's something simpler, but I can't wrap my head around it currently). The following returns the hash key of the lowest amount of tasks.

> tasks = {1=>[[2, 9]], 2=>[[3, 4]], 3=>[[1, 6]]}
#=> {1=>[[2, 9]], 2=>[[3, 4]], 3=>[[1, 6]]}
> tasks.min_by {|_,v| v.map {|x| x.last}.reduce(&:+)}.first
#=> 2