Anonymous user
Subset sum problem: Difference between revisions
→{{header|Ruby}}
m (→{{header|REXX}}: restructured the section header comments.) |
|||
Line 1,181:
a brute force solution:
<lang ruby>weights = {
'alliance' =>
'brute' =>
'departure' =>
'elysee' =>
'fiat' =>
'infra' =>
'mincemeat' =>
'smokescreen'
}
Line 1,194:
1.upto(words.length) do |n|
zerosum = words.combination(n).find do |subset|
subset.reduce(0) {|sum, word| sum +
end
if zerosum
puts "a subset of length #{n} that sums to zero: #{zerosum}"▼
else▼
puts "no subsets of length #{n} sum to zero"
▲ else
▲ puts "a subset of length #{n} that sums to zero: #{zerosum}"
end
end</lang>
{{out}}
<pre style="height: 40ex; overflow: scroll">
no subsets of length 1 sum to zero
a subset of length 2 that sums to zero: ["archbishop", "gestapo"]
a subset of length 3 that sums to zero: ["centipede", "markham", "mycenae"]
|