Jump to content

Power set: Difference between revisions

554 bytes added ,  13 years ago
m (→‎Recursive: subheading change)
Line 766:
 
=={{header|Icon}} and {{header|Unicon}}==
 
The two examples below show the similarities and differences between constructing an explicit representation of the solution, i.e. a set containing the powerset, and one using generators. The basic recursive algorithm is the same in each case, but wherever the first stores part of the result away, the second uses 'suspend' to immediate pass the result back to the caller. The caller may then decide to store the results in a set, a list, or dispose of each one as it appears.
 
===Set building===
Line 777 ⟶ 779:
then insert (result, set ()) # empty set
else {
head := set(?s) # take a random element
# and find powerset of remaining part of set
tail_pset := power_set (x -- set(head))
result ++:= tail_pset # add powerset of remainder to results
every ps := !tail_pset do # and add head to each powerset from the remainder
insert (result, ps ++ set(head))
}
return result
Line 792 ⟶ 794:
<lang Icon>
procedure main ()
every s := !power_set (set(1,2,3,4)) do { # requires '!' to generate items in the result set
writes ("[ ")
every writes (!s || " ")
Line 829 ⟶ 831:
then suspend set ()
else {
head := set(?s)
every ps := power_set (delete (copy(s), -- head)) do {
suspend ps
suspend insert (copy(ps), ++ head)
}
}
Line 838 ⟶ 840:
 
procedure main ()
every s := power_set (set(1,2,3,4)) do { # power_set's values are generated by 'every'
writes ("[ ")
every writes (!s || " ")
342

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.