所以我让这种方法在数据集很小的情况下也能正常工作。然而,当它变得更大一点时......
此脚本的目的是找到每个可能的集合组合,而不会重复。这样我就可以将它们存储在数据库表中。
set 1: [701,744,410,646,723,434]
set 2: [701,744,410,646,723,435]
set 3: etc..
我还应该注意,我需要保持与原始键的关系。因此 type1 中的项目不能移动到任何其他类型。希望这是有道理的。
Collecting pieces...
pieces[type1] = [701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716, 717, 718, 719, 720, 721, 722]
pieces[type2] = [744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765]
pieces[type3] = [410, 412, 413, 414, 415, 419, 422, 424, 426, 427, 429, 372, 374, 376, 378, 380, 382, 385, 395, 397, 399, 401]
pieces[type4] = [646, 647, 649, 651, 653, 655, 657, 671, 672, 673, 674, 679, 681, 684, 686, 688, 691, 695, 697, 698, 699, 700]
pieces[type5] = [723, 724, 725, 726, 727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743]
pieces[type6] = [434, 435, 438, 440, 443, 446, 447, 462, 464, 467, 469, 484, 485, 486, 487, 488, 489, 490, 491, 492, 494, 496]
Took 0.4265 seconds to collect.
Generating possibilities...
/Projects/my_project/lib/tasks/possibilities.rake:109: [BUG] Segmentation fault
ruby 1.9.3p286 (2012-10-12 revision 37165) [x86_64-darwin12.2.0]
是的,段错误。
这是我用来实现它的代码。
def permutations!(input)
permutations_start = Time.now
puts "Generating possibilities..."
input.each do |key, possibilities|
possibilities.map!{|p| {key => p} }
end
digits = input.keys.map!{|key| input[key] }
# This is the line that seems to want to cry.
result = digits.shift.product(*digits)
puts "# of generated possibilities: #{result.length}"
puts "Took #{(Time.now - permutations_start).round(4)} seconds to generate.\n\n"
return result
end
pieces = {}
pieces['type1'] = [701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716, 717, 718, 719, 720, 721, 722]
pieces['type2'] = [744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765]
pieces['type3'] = [410, 412, 413, 414, 415, 419, 422, 424, 426, 427, 429, 372, 374, 376, 378, 380, 382, 385, 395, 397, 399, 401]
pieces['type4'] = [646, 647, 649, 651, 653, 655, 657, 671, 672, 673, 674, 679, 681, 684, 686, 688, 691, 695, 697, 698, 699, 700]
pieces['type5'] = [723, 724, 725, 726, 727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743]
pieces['type6'] = [434, 435, 438, 440, 443, 446, 447, 462, 464, 467, 469, 484, 485, 486, 487, 488, 489, 490, 491, 492, 494, 496]
possibilities = permutations!(pieces)