Reputation: 13
I am looking for a way where I can generated different combination of 4 sets elements in such a manner that every set's element has a fixed place in the final combination: To explain better my requirement let me give sample of those 4 sets and finally what I am looking for:
Set#1(Street Pre Direction) { N, S } Set#2(Street Name) {Frankford, Baily} Set#3(Street Type) {Ave, St} Set#4(Street Post Direction) {S}
Let me list few expecting combinations:
N Baily Ave S
S Frankford St S
S Baily Av S
.
.
.
Now as you can see that every set's element is falling into its place
Pre Direction is in Place 1
Street Name is in Place 2
Streety Type is in Place 3
Street Description is in Place 4
I am looking for the most efficient way to carry out this task, One way to do it is to work at 2 sets at a time like:
Make Combination of Set 1 and Set 2 --> create a new set 5 of resulting combinations
Make Combination of Set 5 and Set 3 --> create a new set 6 of resulting combinations
Make Combination of Set 6 and Set 4 --> This will give me the final combinations
Is there a best way to do this thing? Kindly help. I will prefer C# or Java.
Thanks
Upvotes: 0
Views: 786
Reputation: 13
@ David B What if predirections list is empty, is there a way that we still get the combinations since through your way none cartesian product will be returned.
David B here:
var query =
from d in predirections.DefaultIfEmpty()
from n in names.DefaultIfEmpty()
from t in types.DefaultIfEmpty()
from s in postdirections.DefaultIfEmpty()
select new {d, n, t, s};
Upvotes: 0
Reputation: 110181
Here's some linq (c#) that gives you all combinations, it is not "the most efficient way".
var query =
from d in predirections
from n in names
from t in types
from s in postdirections
select new {d, n, t, s};
Upvotes: 2
Reputation: 213648
It sounds like you're looking for the cartesian product of some sets. You can do it using nested for loops. Here's the Haskell code, which you didn't ask for.
Prelude> [[x,y] | x <- ['1'..'3'], y <- ['A'..'C']]
["1A","1B","1C","2A","2B","2C","3A","3B","3C"]
Upvotes: 1