Skip to content

Instantly share code, notes, and snippets.

@tomoumi-n
Created April 28, 2016 17:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tomoumi-n/810ed255e5d0c3b201cc6fb4b96e7c77 to your computer and use it in GitHub Desktop.
Save tomoumi-n/810ed255e5d0c3b201cc6fb4b96e7c77 to your computer and use it in GitHub Desktop.
部分集合を算出する
def combination[T](set: Set[T], size: Int): Set[Set[T]] = {
def solve[T](list: List[T], size: Int): Set[Set[T]] = {
if(list.size < size) {
Set.empty[Set[T]]
} else {
if(size == 1) {
list.map(item => Set(item)).toSet
} else {
def loop(remain: List[T], set: Set[Set[T]] = Set.empty[Set[T]]): Set[Set[T]] = {
remain match {
case Nil => set
case item :: remain if remain.size < size - 1 => set
case item :: remain =>
loop(remain, set ++ solve(remain, size - 1).map(set => set + item))
}
}
loop(list)
}
}
}
solve(set.toList, size)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment