Rubyã§ã®é åãçµã¿åããã
Rubyã§ã¯ãé åãã¨ãçµã¿åããããArrayã¯ã©ã¹ã®combinationã¡ã½ããã¨permutationã¡ã½ãããç¨ãããã¨ã§ãç°¡åã«æ±ãããã¨ãã§ãã¾ãã
array = [1,2,3,4] p array.combination(3).to_a
[[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]
combinationã®å¼æ°ã¯é¸ã³åºãè¦ç´ ã®åæ°ãæå®ããã
array = [1,2,3] p array.permutation(3).to_a
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
両æ¹ã¨ã便å©ãªã¡ã½ããã§ãã
ã¾ããè¦ç´ ã®éè¤ã許å¯ããå ´å㯠repeated_combination ã repeated_permutation ãå©ç¨ã§ãã¾ãã
ãªããIntegerã¯ã©ã¹ã«åå¨ããªã
Arrayã¯ã©ã¹ã«ã¯ãé åããçµã¿åãããã¡ã½ãããåå¨ããã®ã§ããããªããIntegerã¯ã©ã¹ã«ã¯åå¨ãã¾ããããªã®ã§åç´ãªçµã¿åããã®åæ°ãé åã®åæ°ãæ±ãããã¨ããã¨ãArray.countã¡ã½ããã使ç¨ããå¿
è¦ãããã¾ãã
array = [1,2,3,4,5] p array.permutation(3).to_a.count # n_P_k p array.combination(3).to_a.count # n_C_k
60 10
å°ããå¤ã ã¨ããã¾ã§å½±é¿ã¯ãã¾ããããå é¨ã®å¦ççã«ã¯é åã®ãã¿ã¼ã³ãå ¨ã¦åæãã¦ããã®ã§ã大ããªå¤ã«ãªã£ã¦ããã¨æéãããã£ã¦ãã¾ãã¾ãã
array = (1..20).to_a p array.permutation(5).to_a.count # n_P_k p array.combination(5).to_a.count # n_C_k
1860480 15504 ruby array.rb 1.14s user 0.11s system 99% cpu 1.257 total
1ç§è¿ãå®è¡æéãè²»ããã¦ããã
array = (1..30).to_a p array.permutation(5).to_a.count # n_P_k p array.combination(5).to_a.count # n_C_k
17100720 142506 ruby array.rb 11.55s user 0.83s system 99% cpu 12.389 total
è¦ç´ ã10åå¢ãããã ãã§å®è¡æéãã»ã¼10åè¿ãå¢å ã
ã»ç¡ããªãä½ã
ã¨ãããã¨ã§Integerã¯ã©ã¹ããªã¼ãã³ãã¦ãcombinationããpermutationããfactorialãã¡ã½ãããå®ç¾©ã
class Integer def combination(k) return 1 if k.zero? (self - k + 1..self).inject(:*) / k.factorial end def permutation(k) return 1 if k.zero? (self - k + 1..self).inject(:*) end def factorial return 1 if self.zero? (1..self).inject(:*) end end puts "3.factorial => #{3.factorial}" puts "0.factorial => #{0.factorial}" puts "10.factorial => #{10.factorial}" puts "4.combination(1) => #{4.combination(1)}" puts "4.combination(0) => #{4.combination(0)}" puts "10.combination(5) => #{10.combination(5)}" puts "3.permutation(2) => #{3.permutation(2)}" puts "20.permutation(5) => #{20.permutation(5)}" puts "20.combination(5) => #{20.combination(5)}"
3.factorial => 6 0.factorial => 1 10.factorial => 3628800 4.combination(1) => 4 4.combination(0) => 1 10.combination(5) => 252 3.permutation(2) => 6 20.permutation(5) => 1860480 20.combination(5) => 15504
å®è¡æéãå¤§å¹ ã«æ¹åããã¾ããã