Power set: Difference between revisions

Content added Content deleted
Line 3,193: Line 3,193:
This method is much faster than a recursive method, though the speed is still O(2^n).
This method is much faster than a recursive method, though the speed is still O(2^n).


<lang R>powerset = function(set){
<lang R>powerset <- function(set){
ps = list()
ps <- list()
ps[[1]] = numeric() #Start with the empty set.
ps[[1]] <- numeric() #Start with the empty set.
for(element in set){ #For each element in the set, take all subsets
for(element in set){ #For each element in the set, take all subsets
temp = vector(mode="list",length=length(ps)) #currently in "ps" and create new subsets (in "temp")
temp <- vector(mode="list",length=length(ps)) #currently in "ps" and create new subsets (in "temp")
for(subset in 1:length(ps)){ #by adding "element" to each of them.
for(subset in 1:length(ps)){ #by adding "element" to each of them.
temp[[subset]] = c(ps[[subset]],element)
temp[[subset]] = c(ps[[subset]],element)
}
}
ps=c(ps,temp) #Add the additional subsets ("temp") to "ps".
ps <- c(ps,temp) #Add the additional subsets ("temp") to "ps".
}
}
return(ps)
ps
}
}