Skip to content

add Intersect() to compute the intersection of multiple slices#7

Open
ndrpnt wants to merge 1 commit into
bradenaw:mainfrom
ndrpnt:main
Open

add Intersect() to compute the intersection of multiple slices#7
ndrpnt wants to merge 1 commit into
bradenaw:mainfrom
ndrpnt:main

Conversation

@ndrpnt

@ndrpnt ndrpnt commented Jul 11, 2022

Copy link
Copy Markdown

Hi, I needed to compute the intersection of several slices. Algorithm is probably not optimal, but I thought that might interest you nonetheless.
Feel free to reword, rename, add an IntersectFunc[T comparable](eq func(T, T) bool, in ...[]T) []T variant…

@bradenaw

bradenaw commented Aug 3, 2022

Copy link
Copy Markdown
Owner

Interesting. What was your use of this?

For what it's worth, you could make this a bit more efficient by using two map[T]int, one for the current list and one for the previous, and taking the min between the two at each step. Cuts down on needing a whole make([]int, len(in)) allocation for each element.

@ndrpnt

ndrpnt commented Aug 7, 2022

Copy link
Copy Markdown
Author

For a given user, I had some (short) lists of permissions and resources, e.g.

{
  {
    "permission": "read",
    "resources": ["foo", "bar", "baz"]
  },
  {
    "permission": "write",
    "resources": ["bar", "baz"]
  },
  ...
}

and needed to compute the list of resources for which the user has both read and write permissions. In the end I went with a naive/obvious O(n^2) implementation. 🙈

Later on I stumbled upon your library and thought I'd write something better for fun and contribute it. Thanks for the optimization btw, should I update the PR with it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants