Just another update

This commit is contained in:
Ingy döt Net 2015-02-20 00:35:01 -05:00
parent a25938f123
commit 00a190b0a6
6591 changed files with 94363 additions and 23227 deletions

View file

@ -1,6 +1,20 @@
A [[set]] is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored.
{{omit from|GUISS}}
A [[set]] is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the [[wp:Power_set|power set]] (or powerset) of S, written P(S), or 2<sup>S</sup>, is the set of all subsets of S.<br>
Given a set S, the [[wp:Power_set|power set]] (or powerset) of S, written P(S), or 2<sup>S</sup>, is the set of all subsets of S.<br />
'''Task : ''' By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2<sup>S</sup> of S.
For example, the power set of {1,2,3,4} is {{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}.
For a set which contains n elements, the corresponding power set has 2<sup>n</sup> elements, including the edge cases of [[wp:Empty_set|empty set]].<br />
The power set of the empty set is the set which contains itself (2<sup>0</sup> = 1):<br />
<math>\mathcal{P}</math>(<math>\varnothing</math>) = { <math>\varnothing</math> }<br />
And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (2<sup>1</sup> = 2):<br />
<math>\mathcal{P}</math>({<math>\varnothing</math>}) = { <math>\varnothing</math>, { <math>\varnothing</math> } }<br>
'''Extra credit: ''' Demonstrate that your language supports these last two powersets.

View file

@ -1,84 +1,42 @@
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Text_IO, Ada.Command_Line;
procedure Power_Set is
type Universe is (A,B,C,D,E);
-- The type Set are subsets of Universe
type Set is array (Universe) of Boolean;
Empty : constant Set := (others => False);
function Cardinality (X : Set) return Natural is
N : Natural := 0;
type List is array (Positive range <>) of Positive;
Empty: List(1 .. 0);
procedure Print_All_Subsets(Set: List; Printable: List:= Empty) is
procedure Print_Set(Items: List) is
First: Boolean := True;
begin
Ada.Text_IO.Put("{ ");
for Item of Items loop
if First then
First := False; -- no comma needed
else
Ada.Text_IO.Put(", "); -- comma, to separate the items
end if;
Ada.Text_IO.Put(Ada.Command_Line.Argument(Item));
end loop;
Ada.Text_IO.Put_Line(" }");
end Print_Set;
Tail: List := Set(Set'First+1 .. Set'Last);
begin
for I in X'Range loop
if X (I) then
N := N + 1;
end if;
end loop;
return N;
end Cardinality;
function Element (X : Set; Position : Positive) return Universe is
N : Natural := 0;
begin
for I in X'Range loop
if X (I) then
N := N + 1;
if N = Position then
return I;
end if;
end if;
end loop;
raise Constraint_Error;
end Element;
procedure Put (X : Set) is
Empty : Boolean := True;
begin
for I in X'Range loop
if X (I) then
if Empty then
Empty := False;
Put (Universe'Image (I));
else
Put ("," & Universe'Image (I));
end if;
end if;
end loop;
if Empty then
Put ("empty");
if Set = Empty then
Print_Set(Printable);
else
Print_All_Subsets(Tail, Printable & Set(Set'First));
Print_All_Subsets(Tail, Printable);
end if;
end Put;
end Print_All_Subsets;
-- Set_Of_Set are sets of subsets of Universe
type Set_Of_Sets is array (Positive range <>) of Set;
function Power (X : Set) return Set_Of_Sets is
Length : constant Natural := Cardinality (X);
Index : array (1..Length) of Integer := (others => 0);
Result : Set_Of_Sets (1..2**Length) := (others => Empty);
begin
for N in Result'Range loop
for I in 1..Length loop -- Index determines the sample N
exit when Index (I) = 0;
Result (N) (Element (X, Index (I))) := True;
end loop;
Next : for I in 1..Length loop -- Computing the index of the following sample
if Index (I) < Length then
Index (I) := Index (I) + 1;
if I = 1 or else Index (I - 1) > Index (I) then
for J in reverse 2..I loop
Index (J - 1) := Index (J) + 1;
end loop;
exit Next;
end if;
end if;
end loop Next;
end loop;
return Result;
end Power;
P : Set_Of_Sets := Power ((A|C|E => True, others => False));
Set: List(1 .. Ada.Command_Line.Argument_Count);
begin
for I in P'Range loop
New_Line;
Put (P (I));
for I in Set'Range loop -- initialize set
Set(I) := I;
end loop;
Print_All_Subsets(Set); -- do the work
end Power_Set;

View file

@ -1,7 +1,9 @@
(defn powerset
[coll]
(defn powerset [coll]
(reduce (fn [a x]
(set (concat a (map #(set (concat #{x} %)) a))))
(->> a
(map #(set (concat #{x} %)))
(concat a)
set))
#{#{}} coll))
(powerset #{1 2 3})

View file

@ -1,4 +1,4 @@
T[][] powerSet(T)(in T[] s) pure nothrow {
T[][] powerSet(T)(in T[] s) pure nothrow @safe {
auto r = new typeof(return)(1, 0);
foreach (e; s) {
typeof(return) rs;
@ -11,5 +11,6 @@ T[][] powerSet(T)(in T[] s) pure nothrow {
void main() {
import std.stdio;
[1, 2, 3].powerSet.writeln;
}

View file

@ -1,23 +1,32 @@
auto powerSet(T)(T[] xs) pure nothrow {
auto output = new T[xs.length];
immutable size_t len = 1U << xs.length;
struct Result {
auto powerSet(T)(T[] xs) pure nothrow @safe {
static struct Result {
T[] xsLocal, output;
size_t len;
size_t bits;
@property empty() const pure nothrow { return bits == len; }
void popFront() pure nothrow { bits++; }
@property save() pure nothrow { return this; }
T[] front() nothrow {
this(T[] xs_) pure nothrow @safe {
this.xsLocal = xs_;
this.output.length = xs_.length;
this.len = 1U << xs_.length;
}
@property empty() const pure nothrow @safe {
return bits == len;
}
void popFront() pure nothrow @safe { bits++; }
@property save() pure nothrow @safe { return this; }
T[] front() pure nothrow @safe {
size_t pos = 0;
foreach (immutable size_t i; 0 .. xs.length)
foreach (immutable size_t i; 0 .. xsLocal.length)
if (bits & (1 << i))
output[pos++] = xs[i];
output[pos++] = xsLocal[i];
return output[0 .. pos];
}
}
return Result();
return Result(xs);
}
version (power_set2_main) {

View file

@ -1,108 +1,117 @@
package main
import (
"fmt"
"strconv"
"bytes"
"fmt"
"strconv"
)
// types needed to implement general purpose sets are element and set
// element is an interface, allowing different kinds of elements to be
// implemented and stored in sets.
type element interface {
// an element must be distinguishable from other elements to satisfy
// the mathematical definition of a set. a.eq(b) must give the same
// result as b.eq(a).
eq(element) bool
// String result is used only for printable output. Given a, b where
// a.eq(b), it is not required that a.String() == b.String().
String() string
type elem interface {
// an element must be distinguishable from other elements to satisfy
// the mathematical definition of a set. a.eq(b) must give the same
// result as b.eq(a).
Eq(elem) bool
// String result is used only for printable output. Given a, b where
// a.eq(b), it is not required that a.String() == b.String().
fmt.Stringer
}
// integer type satisfying element interface
type intEle int
type Int int
func (i intEle) eq(e element) bool {
if j, ok := e.(intEle); ok {
return i == j
}
return false
func (i Int) Eq(e elem) bool {
j, ok := e.(Int)
return ok && i == j
}
func (i intEle) String() string {
return strconv.Itoa(int(i))
func (i Int) String() string {
return strconv.Itoa(int(i))
}
// set type implemented as a simple list. methods will be added to
// make it satisfy the element interface, allowing sets of sets.
type set []element
// a set is a slice of elem's. methods are added to implement
// the element interface, to allow nesting.
type set []elem
// uniqueness of elements can be ensured by using add method
func (s *set) addEle(e element) {
if !s.hasEle(e) {
*s = append(*s, e)
}
func (s *set) add(e elem) {
if !s.has(e) {
*s = append(*s, e)
}
}
func (s *set) hasEle(e element) bool {
for _, ex := range *s {
if e.eq(ex) {
return true
}
}
return false
func (s *set) has(e elem) bool {
for _, ex := range *s {
if e.Eq(ex) {
return true
}
}
return false
}
// method to satify element interface
func (s set) eq(e element) bool {
t, ok := e.(set)
if !ok {
return false
}
if len(s) != len(t) {
return false
}
for _, se := range s {
if !t.hasEle(se) {
return false
}
}
return true
// elem.Eq
func (s set) Eq(e elem) bool {
t, ok := e.(set)
if !ok {
return false
}
if len(s) != len(t) {
return false
}
for _, se := range s {
if !t.has(se) {
return false
}
}
return true
}
// method to satify element interface
// elem.String
func (s set) String() string {
r := "{"
for _, e := range s {
if len(r) > 1 {
r += " "
}
r += fmt.Sprint(e)
}
return r + "}"
if len(s) == 0 {
return "∅"
}
var buf bytes.Buffer
buf.WriteRune('{')
for i, e := range s {
if i > 0 {
buf.WriteRune(',')
}
buf.WriteString(e.String())
}
buf.WriteRune('}')
return buf.String()
}
// method required for task
func (s set) powerSet() set {
r := set{set{}}
for _, es := range s {
var u set
for _, er := range r {
u = append(u, append(er.(set), es))
}
r = append(r, u...)
}
return r
r := set{set{}}
for _, es := range s {
var u set
for _, er := range r {
u = append(u, append(er.(set), es))
}
r = append(r, u...)
}
return r
}
func main() {
var s set
for _, i := range []intEle{1, 2, 2, 3, 4, 4, 4} {
s.addEle(i)
}
fmt.Println(s)
fmt.Println("length =", len(s))
ps := s.powerSet()
fmt.Println(ps)
fmt.Println("length =", len(ps))
var s set
for _, i := range []Int{1, 2, 2, 3, 4, 4, 4} {
s.add(i)
}
fmt.Println(" s:", s, "length:", len(s))
ps := s.powerSet()
fmt.Println(" 𝑷(s):", ps, "length:", len(ps))
var empty set
fmt.Println(" empty:", empty, "len:", len(empty))
ps = empty.powerSet()
fmt.Println(" 𝑷(∅):", ps, "len:", len(ps))
ps = ps.powerSet()
fmt.Println("𝑷(𝑷(∅)):", ps, "len:", len(ps))
}

View file

@ -2,9 +2,9 @@ public static <T extends Comparable<? super T>> LinkedList<LinkedList<T>> BinPow
LinkedList<T> A){
LinkedList<LinkedList<T>> ans= new LinkedList<LinkedList<T>>();
int ansSize = (int)Math.pow(2, A.size());
for(Integer i= 0;i< ansSize;++i){
String bin= Integer.toString(i, 2); //convert to binary
while(bin.length() < A.size())bin = "0" + bin; //pad with 0's
for(int i= 0;i< ansSize;++i){
String bin= Integer.toBinaryString(i); //convert to binary
while(bin.length() < A.size()) bin = "0" + bin; //pad with 0's
LinkedList<T> thisComb = new LinkedList<T>(); //place to put one combination
for(int j= 0;j< A.size();++j){
if(bin.charAt(j) == '1')thisComb.add(A.get(j));

View file

@ -0,0 +1,21 @@
use strict;
use warnings;
sub powerset(&@) {
my $callback = shift;
my $bitmask = '';
my $bytes = @_/8;
{
my @indices = grep vec($bitmask, $_, 1), 0..$#_;
$callback->( @_[@indices] );
++vec($bitmask, $_, 8) and last for 0 .. $bytes;
redo if @indices != @_;
}
}
print "powerset of empty set:\n";
powerset { print "[@_]\n" };
print "powerset of set {1,2,3,4}:\n";
powerset { print "[@_]\n" } 1..4;
my $i = 0;
powerset { ++$i } 1..9;
print "The powerset of a nine element set contains $i elements.\n";

View file

@ -1,5 +1,6 @@
# Based on http://johncarrino.net/blog/2006/08/11/powerset-in-ruby/
# See the link if you want a shorter version. This was intended to show the reader how the method works.
# See the link if you want a shorter version.
This was intended to show the reader how the method works.
class Array
# Adds a power_set method to every array, i.e.: [1, 2].power_set
def power_set

View file

@ -0,0 +1,53 @@
options mprint mlogic symbolgen source source2;
%macro SubSets (FieldCount = );
data _NULL_;
Fields = &FieldCount;
SubSets = 2**Fields;
call symput ("NumSubSets", SubSets);
run;
%put &NumSubSets;
data inital;
%do j = 1 %to &FieldCount;
F&j. = 1;
%end;
run;
data SubSets;
set inital;
RowCount =_n_;
call symput("SetCount",RowCount);
run;
%put SetCount ;
%do %while (&SetCount < &NumSubSets);
data loop;
%do j=1 %to &FieldCount;
if rand('GAUSSIAN') > rand('GAUSSIAN') then F&j. = 1;
%end;
data SubSets_ ;
set SubSets loop;
run;
proc sort data=SubSets_ nodupkey;
by F1 - F&FieldCount.;
run;
data Subsets;
set SubSets_;
RowCount =_n_;
run;
proc sql noprint;
select max(RowCount) into :SetCount
from SubSets;
quit;
run;
%end;
%Mend SubSets;

View file

@ -0,0 +1 @@
%SubSets(FieldCount = 5);

View file

@ -0,0 +1,9 @@
import scala.compat.Platform.currentTime
object Powerset extends App {
def powerset[A](s: Set[A]) = s.foldLeft(Set(Set.empty[A])) { case (ss, el) => ss ++ ss.map(_ + el)}
assert(powerset(Set(1, 2, 3, 4)) == Set(Set.empty, Set(1), Set(2), Set(3), Set(4), Set(1, 2), Set(1, 3), Set(1, 4),
Set(2, 3), Set(2, 4), Set(3, 4), Set(1, 2, 3), Set(1, 3, 4), Set(1, 2, 4), Set(2, 3, 4), Set(1, 2, 3, 4)))
println(s"Successfully completed without errors. [total ${currentTime - executionStart} ms]")
}

View file

@ -0,0 +1 @@
def powerset[A](s: Set[A]) = (0 to s.size).map(s.toSeq.combinations(_)).reduce(_ ++ _).map(_.toSet)

View file

@ -1 +0,0 @@
def powerset[A](s: Set[A]) = s.foldLeft(Set(Set.empty[A])) { case (ss, el) => ss ++ ss.map(_ + el) }

View file

@ -1,7 +1,5 @@
(1 2)
(1 3)
(1)
(2 3)
(2)
(3)
()
(define (power_set_iter set)
(let loop ((res '(())) (s set))
(if (empty? s)
res
(loop (append (map (lambda (i) (cons (car s) i)) res) res) (cdr s)))))