Categories

See More
Popular Forum

MBA (4887) B.Tech (1769) Engineering (1486) Class 12 (1030) Study Abroad (1004) Computer Science and Engineering (988) Business Management Studies (865) BBA (846) Diploma (746) CAT (651) B.Com (648) B.Sc (643) JEE Mains (618) Mechanical Engineering (574) Exam (525) India (462) Career (452) All Time Q&A (439) Mass Communication (427) BCA (417) Science (384) Computers & IT (Non-Engg) (383) Medicine & Health Sciences (381) Hotel Management (373) Civil Engineering (353) MCA (349) Tuteehub Top Questions (348) Distance (340) Colleges in India (334)
See More

Keys of a hash whose values sum to a particular value

General Tech Bugs & Fixes

Max. 2000 characters
Tuteehub
Replies

usr_profile.png

User

( 7 months ago )

I have a hash:

a = {"Q1"=>1, "Q2"=>2, "Q5"=>3, "Q8"=>3}

I want to retrieve a set of keys from it such that the sum of their values equals a certain number, for example 5. In such case, the output should be:

Q2 Q5

Please help me on how to get this.

usr_profile.png

User

( 7 months ago )

def find_combo(h, tot)
  arr = h.to_a
  (1..arr.size).find do |n|
    enum = arr.combination(n).find { |e| e.map(&:last).sum == tot }
    return enum.map(&:first) unless enum.nil?
  end
 end
h = {"Q1"=>1, "Q2"=>2, "Q5"=>3, "Q8"=>3}

find_combo(h, 5)   #=> ["Q2", "Q5"] 
find_combo(h, 2)   #=> ["Q2"] 
find_combo(h, 6)   #=> ["Q5", "Q8"] 
find_combo(h, 4)   #=> ["Q1", "Q5"] 
find_combo(h, 8)   #=> ["Q2", "Q5", "Q8"] 
find_combo(h, 9)   #=> ["Q1", "Q2", "Q5", "Q8"] 
find_combo(h, 10)  #=> nil 

usr_profile.png

User

( 7 months ago )

Just out of curiosity:

hash = {"Q1"=>1, "Q2"=>2, "Q5"=>3, "Q8"=>3}
arr = hash.to_a

1.upto(hash.size).
  lazy.
  find do |i|
    res = arr.combination(i).find do |h|
      h.map(&:last).sum == 5
    end
    break res if res
  end.tap { |result| break result.to_h if result }  
#⇒ {"Q2" => 2, "Q5" => 3}

what's your interest


forum_ban8_5d8c5fd7cf6f7.gif