Skip to content

Instantly share code, notes, and snippets.

@wat-aro
Last active September 21, 2016 13:30
Show Gist options
  • Save wat-aro/674785662777c3575afdd9f05ae55ebb to your computer and use it in GitHub Desktop.
Save wat-aro/674785662777c3575afdd9f05ae55ebb to your computer and use it in GitHub Desktop.
class Hoge
def combination(array, num)
if array.empty? || num == 0
[]
elsif num == 1
array.map{ |elem| [elem] }
else
rest = array.drop(1)
combination(rest, num - 1).map{ |elem| [array.first] + elem } +
combination(rest, num)
end
end
end
array = %w(a b c d e f g)
p Hoge.new.combination(array, 4) == array.combination(4).to_a
(define (combination lst n)
(cond ((or (null? lst)
(= n 0))
'())
((= n 1)
(map (lambda (x) (list x)) lst))
(else
(append (map (lambda (x) (cons (car lst) x))
(combination (cdr lst) (- n 1)))
(combination (cdr lst) n)))))
gosh> (combination '() 1)
()
gosh> (combination '(a b c) 0)
()
gosh> (combination '(a b c) 1)
((a) (b) (c))
gosh> (combination '(a b c) 2)
((a b) (a c) (b c))
gosh> (combination '(a b c d e) 2)
((a b) (a c) (a d) (a e) (b c) (b d) (b e) (c d) (c e) (d e))
gosh> (combination '(a b c d e) 3)
((a b c) (a b d) (a b e) (a c d) (a c e) (a d e) (b c d) (b c e) (b d e) (c d e))
gosh> (combination '(a b c d e) 4)
((a b c d) (a b c e) (a b d e) (a c d e) (b c d e))
gosh> (combination '(a b c d e) 5)
((a b c d e))
gosh> (combination '(a b c d e) 6)
()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment