็ตใฟๅใใ
Rubyใง็ตใฟๅใใใๆฑใใๆฉไผใใใฃใใ
Rubyใซใฏไพฟๅฉใชใกใฝใใใใใฃใฆใไปฅไธใฎใใใซๆฑใใใใจใใงใใใ
arr = [1, 2, 3, 4, 5]
p arr.combination(2).to_a
# OUTPUT
[[1, 2], [1, 3], [1, 4], [1, 5], [2, 3], [2, 4], [2, 5], [3, 4], [3, 5], [4, 5]]
ใใใใใใใๅฎ้ใซ่ชๅใงๅฎ่ฃ ใใใใจใใใจๆๅคใจ้ฃใใใชใจๆใใใฎใงใพใจใใฆใฟใใ
ๅฎ่ฃ
่ใๆน
็ดๆ็ใช่ใๆนใฏใ่ชๅใงๆจนๅฝขๅณใๆธใใใญใปในใงใใใ
ไพใใฐใ[1,2,3,4]
ใใ3ใคใฎ่ฆ็ด ใๅใ็ตใฟๅใใใ่ใใใ
ใพใใ1
ใๅใใๆฎใฃใ[2,3,4]
ใใ2ใคใๅใฃใฆใใฆ1
ใซๅ ใใใ
[1,2,3][1,2,4][1,3,4]
ใใงใใใ
ๆฌกใซใ2
ใๅใใๆฎใฃใ[3,4]
ใใ2ใคๅใฃใฆใใฆ2
ใซๅ ใใใ
[2,3,4]
ใใงใใใ
ๅใใใฆใ๏ผใคใฎ็ตใฟๅใใใใงใใใ
ใใใฏๅๅธฐ็ใซๅฎ่ฃ
ใใใใใจใใงใใใ
ๅๅธฐ็ตไบๆกไปถ
[1,2,3]
ใใ3ใคๅใฃใฆใใใใใชใจใใฏ[[1,2,3]]
ใ่ฟใใ
[1,2,3]
ใใ1ใคๅใฃใฆใใใใใชใจใใฏ[[1],[2],[3]]
ใ่ฟใใ
Rubyใงใฏใใคใณในใฟใณในใกใฝใใไธญใงใฌใทใผใใ็็ฅใใใจself
ใๆ้ป็ใซใฌใทใผใใซใชใใ
ใใณใผใ
class Array
# EXAMPLE: [1.2.3.4].combination_array(3) => [[1,2,3], [1,2,4], [1,3,4], [2,3,4]]
def combination_array(comb_size)
return [] if comb_size > size # 4C5ใฎใใใชใใฎใฏ็ฉบใ่ฟใ
return [] if comb_size == 0 # 4C0ใฎใใใชใใฎใฏ็ฉบใ่ฟใ
return [self] if comb_size == size
return map { |e| [e] } if comb_size == 1
ret = []
(0..size - comb_size).each do |i|
picked = self[i]
rest = self[i + 1..-1]
rest.combination_array(comb_size - 1).each do |c|
ret << [picked] + c
end
end
ret
end
end
if $PROGRAM_NAME == __FILE__
p %i[asahi kirin sapporo suntory].combination_array(2)
# ้่คใใชใๆ(ๆขๅญใกใฝใใใจใฎๆฏ่ผ)
p [1, 2, 3, 4, 5, 6, 7, 8, 9].combination_array(3) == [1, 2, 3, 4, 5, 6, 7, 8, 9].combination(3).to_a
# ้่คใใใๆ(ๆขๅญใกใฝใใใจใฎๆฏ่ผ)
p [1, 2, 3, 4, 5, 6, 1, 8, 3].combination_array(4) == [1, 2, 3, 4, 5, 6, 1, 8, 3].combination(4).to_a
end
## OUTPUT
[[:asahi, :kirin], [:asahi, :sapporo], [:asahi, :suntory], [:kirin, :sapporo], [:kirin, :suntory], [:sapporo, :suntory]]
true
true
ๅ่