Skip to content

Instantly share code, notes, and snippets.

@niku
Created March 1, 2012 06:20
Show Gist options
  • Save niku/1947745 to your computer and use it in GitHub Desktop.
Save niku/1947745 to your computer and use it in GitHub Desktop.
1から365の数字の組み合わせで、合計が 1000 になるもののうち,組み合わせた要素の数が最大のものを求める
# -*- coding: utf-8 -*-
result = (1..365).take_while { |i|
# 枝刈り
# (1..i)の合計(組み合わせの最小値)が1000を超えないものを対象にする
(1..i).reduce(:+) < 1000
}.map { |i|
(1..365).to_a.combination(i)
}.map { |e|
# スレッドに分けて高速化
Thread.new(e) { |g|
loop do
ary = g.next
break ary if ary.reduce(:+) == 1000
end
}
}.map(&:value).reject(&:nil?).max_by(&:size)
File.open('result.txt', 'w') { |f| f << r.join(',') }
# => [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,139]
# 42 個
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment