-
Notifications
You must be signed in to change notification settings - Fork 68
/
LifeOfPossibilities.rb
60 lines (51 loc) · 1.16 KB
/
LifeOfPossibilities.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
=begin
Given a map of words and their translations, generate a list of all possible
unique combinations of translations, sorted lexically.
For example, given the map of words:
words = {
life: %w{ vida vie Leben },
death: %w{ muerte mort Tode }
}
The method should return the result:
{
life: [
['Leben'],
['Leben', 'vida'],
['Leben', 'vida', 'vie'],
['Leben', 'vie'],
['vida'],
['vida', 'vie'],
['vie']
],
death: [
['Tode'],
['Tode', 'mort'],
['Tode', 'mort', 'muerte'],
['Tode', 'muerte'],
['mort'],
['mort', 'muerte'],
['muerte']
]
}
=end
# My Solution
def possibilities(words)
l = [] ; d = []; temp = []
(1..words[:life].length).each do |x|
temp = words[:life].to_a.combination(x).to_a
l += temp.each {|x| x.sort!}
end
words[:life] = l.sort!
(1..words[:death].length).each do |x|
temp = words[:death].to_a.combination(x).to_a
d += temp.each {|x| x.sort!}
end
words[:death] = d.sort!
{:life=>words[:life], :death=>words[:death]}
end
# Better Solution
def possibilities(words)
Hash[words.map { |k,v|
[k, v.sort.repeated_combination(v.size).map(&:uniq).uniq.sort]
}]
end