【发布时间】:2021-03-05 17:09:47
【问题描述】:
所以我有这个哈希,我想写一个程序,给定一个人的分数可以告诉他们:
a)无论他们是否对特定物品过敏
b)完整的过敏列表。
allergies = {
1 => "eggs",
2 => "peanuts",
4 => "shellfish",
8 => "strawberries",
16 => "tomatoes",
32 => "chocolate",
64 => "pollen",
128 => "cat",
}
我想过我将如何实现这一目标。请参阅下面的 cmets。
# 1+2 = eggs & peanuts (3) # 1+2+4 = eggs & peanuts & shellfish (7) # 1+2+4+8 = eggs & peanuts & shellfish & strawberries (15)
# 1+4 = eggs & shellfish (5) # 1+2+8 = eggs & peanuts & strawberries (11) # 1+2+4+16 = eggs & peanuts & shellfish & tomatoes (23)
# 1+8 = eggs & strawberries (9) # 1+2+16 = eggs & peanuts & tomatoes (19) # 1+2+4+32 = eggs & peanuts & shellfish & chocolate (39)
# 1+16 = eggs & tomatoes (17) # 1+2+32 = eggs & peanuts & chocolate (35) # 1+2+4+64 = eggs & peanuts & shellfish & pollen (71)
# 1+32 = eggs & chocolate (33) # 1+2+64 = eggs & peanuts & pollen (67) # 1+2+4+128 = eggs & peanuts & shellfish & cat (135)
# 1+64 = eggs & pollen (65) # 1+2+128 = eggs & peanuts & car (131) #etc
# 1+128 = eggs & cat (129)
所以我可以使用的帮助是,我如何遍历哈希,确保考虑到所有 255 个可能的组合并返回与该可能组合关联的键,这样当我调用带有 35 参数的方法,它会返回值 ["eggs", "peanuts", "chocolate"]。 希望这是有道理的。
我愿意接受您可能需要实现的其他想法。
谢谢!
【问题讨论】:
标签: ruby loops hash combinations key-value