Last active
April 16, 2016 08:35
-
-
Save kunitoo/6b03d7446e8d67555b9847535b1129dc to your computer and use it in GitHub Desktop.
Toyama.rb #05 問題2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Q2 | |
def self.strike | |
board = *(1..9) | |
count = deliver(board) | |
two_numbers = (board.zip(board.rotate) + board.zip(board.rotate(3))). #=> [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9], [9, 1], [1, 4], [2, 5], [3, 6], [4, 7], [5, 8], [6, 9], [7, 1], [8, 2], [9, 3]] | |
select {|ns| ns[0] < ns[1] }. | |
reject {|ns| ns.include?(5) }. | |
reject {|n| [[3, 4], [6, 7]].include?(n) } | |
(1..4).each do |n| | |
two_numbers.combination(n).each do |nums| | |
next if nums.flatten.size != nums.flatten.uniq.size | |
numbers = nums + board.select {|b| !nums.flatten.include?(b) } | |
count += deliver(numbers) | |
end | |
end | |
count | |
end | |
def self.deliver(numbers) | |
return 1 if numbers.empty? | |
count = 0 | |
numbers.each do |number| | |
next_numbers = numbers.dup | |
next_numbers.delete(number) | |
count += deliver(next_numbers) | |
end | |
count | |
end | |
end | |
puts "answer : #{Q2.strike}" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Q2 | |
def self.strike | |
board = *(1..9) | |
count = factorial(board.count) | |
two_numbers = (board.zip(board.rotate) + board.zip(board.rotate(3))). #=> [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9], [9, 1], [1, 4], [2, 5], [3, 6], [4, 7], [5, 8], [6, 9], [7, 1], [8, 2], [9, 3]] | |
select {|ns| ns[0] < ns[1] }. | |
reject {|ns| ns.include?(5) }. | |
reject {|n| [[3, 4], [6, 7]].include?(n) } | |
(1..4).each do |n| | |
two_numbers.combination(n).each do |nums| | |
next if nums.flatten.size != nums.flatten.uniq.size | |
numbers = nums + board.select {|b| !nums.flatten.include?(b) } | |
count += factorial(numbers.count) | |
end | |
end | |
count | |
end | |
def self.factorial(number) | |
(1..number).inject(1,:*) | |
end | |
end | |
require 'benchmark' | |
Benchmark.bm do |x| | |
x.report { puts "answer : #{Q2.strike}" } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment