Skip to content

Commit

Permalink
Implemented change on Union function from receiver function to a regu…
Browse files Browse the repository at this point in the history
…lar function that uses divide and conquer to merge sets into a union
  • Loading branch information
kelvinmwinuka committed Feb 17, 2024
1 parent c809d7b commit 128fa1a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 12 deletions.
4 changes: 2 additions & 2 deletions src/modules/set/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -704,7 +704,7 @@ func handleSUNION(ctx context.Context, cmd []string, server utils.Server, conn *
sets = append(sets, set)
}

union := sets[0].Union(sets[1:])
union := Union(sets...)

res := fmt.Sprintf("*%d", union.Cardinality())
for i, e := range union.GetAll() {
Expand Down Expand Up @@ -755,7 +755,7 @@ func handleSUNIONSTORE(ctx context.Context, cmd []string, server utils.Server, c
sets = append(sets, set)
}

union := sets[0].Union(sets[1:])
union := Union(sets...)

destination := cmd[1]

Expand Down
26 changes: 16 additions & 10 deletions src/modules/set/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,16 +108,6 @@ func (set *Set) Contains(e string) bool {
return set.Get(e) != nil
}

func (set *Set) Union(others []*Set) *Set {
union := NewSet(set.GetAll())
for _, s := range others {
for k, _ := range s.members {
union.Add([]string{k})
}
}
return union
}

// Subtract received a list of sets and finds the difference between sets provided
func (set *Set) Subtract(others []*Set) *Set {
diff := NewSet(set.GetAll())
Expand Down Expand Up @@ -175,3 +165,19 @@ func Intersection(limit int, sets ...*Set) (*Set, bool) {
return Intersection(limit, left, right)
}
}

// Union takes a slice of sets and generates a union
func Union(sets ...*Set) *Set {
switch len(sets) {
case 1:
return sets[0]
case 2:
union := sets[0]
union.Add(sets[1].GetAll())
return union
default:
left := Union(sets[0 : len(sets)/2]...)
right := Union(sets[len(sets)/2:]...)
return Union(left, right)
}
}

0 comments on commit 128fa1a

Please sign in to comment.