Power set: Difference between revisions

m (→‎{{header|REXX}}: added/changed whitespace and comments, split a compound statement.)
Line 2,149:
 
=={{header|Kotlin}}==
<lang scala>// purely functional & lazy version, 1leveraging recursion and Sequences (a.1k.3a. streams)
fun <T> Set<T>.subsets(): Sequence<Set<T>> =
 
ifwhen (k >= msize) {
class PowerSet<T>(val items: List<T>) {
0 -> sequenceOf(emptySet())
private lateinit var combination: IntArray
} else -> {
val head = first()
init {
println("Power set of $items comprises:")val tail = this - head
for tail.subsets(m) in+ 0tail..items.sizesubsets().map { setOf(head) + it }
combination = IntArray(m)}
generate(0, m)
}
}
 
// if recursion is an issue, you may change it this way:
private fun generate(k: Int, m: Int) {
 
if (k >= m) {
fun <T> Set<T>.subsets(): Sequence<Set<T>> = sequence {
println(combination.map { items[it] })
when (size) }{
else0 {-> yield(emptySet<T>())
else -> for (j in 0 until items.size){
val head = if first(k == 0 || j > combination[k - 1]) {
val tail = this@subsets - combination[k] = jhead
generateyieldAll(k + 1, mtail.subsets())
for (subset in tail.subsets()) }{
yield(setOf(head) + subset)
generate(0, m)}
}
}
}
}</lang>
fun main(args: Array<String>) {
val itemsList = listOf(
listOf(1, 2, 3, 4),
emptyList<Int>(),
listOf(emptyList<Int>())
)
for (items in itemsList) {
PowerSet(items)
println()
}
}</lang>
 
{{out}}
<pre>
Power set of [setOf(1, 2, 3, 4]) comprises:
[]
[1]
[2]
[3]
[4]
[1, 23]
[1, 3]
[1, 4]
[2, 3]
[2, 4]
[3, 4]
[1, 2, 3]
[1, 2, 4]
[12, 3, 4]
[2, 3, 4]
[1]
[1, 34]
[1, 3]
[1, 3, 4]
[1, 2]
[1, 2, 4]
[1, 2, 3]
[1, 2, 3, 4]
 
Power set of []emptySet<Any>() comprises:
[]
 
Power set of [[]]setOf(emptySet<Any>()) comprises:
[]
[[]]
Anonymous user