473,382 Members | 1,786 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

Cross product of arrays

Hi all,

Can some one show me how to achieve a cross product of arrays. So that if I
had two arrays (could be any number) with three elements in each (once again
could be any number) I would get:
the two arrays
{"one","two","three"},{"red","green","blue}
the result
one red
one green
one blue
two red
two green
two blue
three red
three green
three blue

Thanks

Robert
Dec 7 '06 #1
6 13107
Robert Bravery <me@u.comwrote:
Can some one show me how to achieve a cross product of arrays. So that if I
had two arrays (could be any number) with three elements in each (once again
could be any number) I would get:
the two arrays
{"one","two","three"},{"red","green","blue}
the result
one red
one green
one blue
two red
two green
two blue
three red
three green
three blue
What do you want to do with the cross product? Just printing it out is
easy:

using System;

public class Test
{
static void Main()
{
string[] first = {"one", "two", "three"};
string[] second = {"red", "green", "blue"};

foreach (string x in first)
{
foreach (string y in second)
{
Console.WriteLine ("{0} {1}", x, y);
}
}
}
}

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 7 '06 #2
WEll I want to eventual extract the data and save it to a table.
I used two arrays as an example, but infact I don't know how many array sets
there can be, up to a maximum of 5, so there could be any number from one
to five sets. Then each array set can have any number of elements in that
array
The point is I don't know how many sets there will be , to a mx of five, and
I don't know how many elements there will be in each set
so I could also have the following, I dont know:

{'apple','orange','banana'},{'man','woman','child' },{'red','green','blue','w
hite','black'}

which should produce a cross product like:

apple man red
apple man green
apple man blue
apple man white
apple man black
apple woman red
apple woman green
apple woman blue
apple woman white
apple woman black
apple child red
apple child green
apple child blue
apple child white
apple child black
orange man red
orange man green
orange man blue
orange man white
orange man black
orange woman red
orange woman green
orange woman blue
orange woman white
orange woman black
orange child red
orange child green
orange child blue
orange child white
orange child black
banana man red
banana man green
banana man blue
banana man white
banana man black
banana woman red
banana woman green
banana woman blue
banana woman white
banana woman black
banana child red
banana child green
banana child blue
banana child white
banana child black

Thanks
Robert

"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:MP************************@msnews.microsoft.c om...
Robert Bravery <me@u.comwrote:
Can some one show me how to achieve a cross product of arrays. So that
if I
had two arrays (could be any number) with three elements in each (once
again
could be any number) I would get:
the two arrays
{"one","two","three"},{"red","green","blue}
the result
one red
one green
one blue
two red
two green
two blue
three red
three green
three blue

What do you want to do with the cross product? Just printing it out is
easy:

using System;

public class Test
{
static void Main()
{
string[] first = {"one", "two", "three"};
string[] second = {"red", "green", "blue"};

foreach (string x in first)
{
foreach (string y in second)
{
Console.WriteLine ("{0} {1}", x, y);
}
}
}
}

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Dec 7 '06 #3
Robert Bravery <me@u.comwrote:
WEll I want to eventual extract the data and save it to a table.
I used two arrays as an example, but infact I don't know how many array sets
there can be, up to a maximum of 5, so there could be any number from one
to five sets. Then each array set can have any number of elements in that
array
The point is I don't know how many sets there will be , to a mx of five, and
I don't know how many elements there will be in each set
so I could also have the following, I dont know:

{'apple','orange','banana'},{'man','woman','child' },{'red','green','blue','w
hite','black'}

which should produce a cross product like:
Okay. Here's a sample which takes as many string arrays as you like. It
uses recursion, which wouldn't be a good idea if you wanted a cross-
product of very deep arrays, but then that quickly becomes infeasible
anyway.

You'll want to consider how you want to process the table - you could
fairly easily write an iterator which returns a string array on each
iteration, especially with C# 2.0 iterators.

using System;
using System.Text;

public class Test
{
static void Main()
{
string[] first = {"one", "two", "three"};
string[] second = {"red", "green", "blue"};

PrintCrossProduct(new string[]{"apple","orange","banana"},
new string[]{"man","woman","child"},
new string[]{"red","green","blue",
"white","black"});
}

static void PrintCrossProduct(params string[][] arrays)
{
PrintCrossProduct(arrays, 0, new string[arrays.Length]);
}

static void PrintCrossProduct(string[][] arrays,
int depth, string[] current)
{
for (int i=0; i < arrays[depth].Length; i++)
{
current[depth] = arrays[depth][i];
if (depth < arrays.Length-1)
{
PrintCrossProduct(arrays, depth+1, current);
}
else
{
StringBuilder builder = new StringBuilder();
foreach (string x in current)
{
builder.Append(x);
builder.Append(" ");
}
// Remove the extraneous trailing space
// (This will fail if there are no arrays, but you can
// guard against that if you need to)
builder.Length--;
Console.WriteLine (builder);
}
}
}
}

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 7 '06 #4
"Robert Bravery" <me@u.comwrote:
>The point is I don't know how many sets there will be , to a mx of five, and
I don't know how many elements there will be in each set
so I could also have the following, I dont know:
{'apple','orange','banana'},{'man','woman','child '},{'red','green','blue','w
hite','black'}
To review here, each of these elements is an IEnumerable<string>.
Therefore the cross-product will be an
IEnumerable<IEnumerable<string>>. So here's the code:
static IEnumerable<stringpre(string x, IEnumerable<stringys)
{ yield return x;
if (ys!=null) foreach (string y in ys) yield return y;
}

static IEnumerable<IEnumerable<string>>
cross(IEnumerable<stringxs, IEnumerable<IEnumerable<string>yss)
{ foreach (string x in xs)
{ if (yss==null) yield return prepend(x,null);
else foreach(IEnumerable<string>ys in yss) yield return pre(x,ys);
}
}

static void Main(string[] args)
{ string[][] ars = new string[][] {new string[]{"a","b","c","d"},
new string[]{"u","v"},
new string[]{"x","y","z"}};

// Here we assemble the cross product of all of those strings:
IEnumerable<IEnumerable<string>c = null;
foreach (string[] ar in ars) c=cross(ar,c);

// and let's print out the cross product!
foreach (IEnumerable<stringcs in c)
{ foreach (string s in cs) Console.Write(s+",");
Console.WriteLine();
}
}

--
Lucian
Dec 7 '06 #5
Lucian Wischik <lu***@wischik.comwrote:
>{ foreach (string x in xs)
{ if (yss==null) yield return prepend(x,null);
else foreach(IEnumerable<string>ys in yss) yield return pre(x,ys);
}
Sorry, that should have been "yield return pre(x,null)" in the second
line.
Note that this solution has no recursion! This code uses c# "yield
return" iterators. Internally these construct an object on the heap
whose job it is to keep track of the enumeration. Effectively, the
role played by recursive stack-frames in Jon's code is fulfilled here
by the yield-return objects.

--
Lucian
Dec 7 '06 #6
Thanks,
A bit confusing at first. But actually works great

Robert

"Lucian Wischik" <lu***@wischik.comwrote in message
news:a4********************************@4ax.com...
Lucian Wischik <lu***@wischik.comwrote:
>>{ foreach (string x in xs)
{ if (yss==null) yield return prepend(x,null);
else foreach(IEnumerable<string>ys in yss) yield return pre(x,ys);
}

Sorry, that should have been "yield return pre(x,null)" in the second
line.
Note that this solution has no recursion! This code uses c# "yield
return" iterators. Internally these construct an object on the heap
whose job it is to keep track of the enumeration. Effectively, the
role played by recursive stack-frames in Jon's code is fulfilled here
by the yield-return objects.

--
Lucian

Dec 8 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Alex Hopson | last post by:
Hi, I'm trying to modify a shopping cart script from Mastering PHP/MySQL and am having trouble setting up some arrays for it. The original code, below, stores the cart items in a session...
17
by: middletree | last post by:
OK, you pros out there are rolling your eyes at the subject line, but I have never had to use arrays before. The scenario: ASP Intranet app keeps track of trouble tickets for a tech support group....
1
by: Bernhard Hidding | last post by:
Hello, I'm a beginner in c++ and I would like to implement some math operations into my program. Explicitly, would like to perform cross product calculations. Is there some library or predefined...
5
by: Ă…smund Kveim Lie | last post by:
Hi, We have found a possible bug in 7.3.1. It seems that using CROSS JOIN and doing plain Cartesian product, listing to tables in the from clause, gives different results. According to the...
4
by: David Peach | last post by:
Hello, hope somebody here can help me... I have a query that lists defects recorded in a user defined date range. That query is then used as the source for a Cross Tab query that cross-tabs count...
5
by: Michal Táborský | last post by:
I am wondering, if it's effective to use text arrays to store multilanguage information. We used to do it like this: CREATE TABLE product ( id serial NOT NULL, price float4, ... )
7
by: Efrain Marrero | last post by:
i want to now how to do this in python this is java for(int i=1 ; i<=lim ; i++){ for(int j=i+1; j<=lim+1; j++){ for(int k =j+1; k<=lim+2;k++){
2
by: hamiltongreg | last post by:
I am pretty new to Java and have a question about where to begin with my program. The assignment is to Modify the Inventory Program so the application can handle multiple items. Use an array to...
5
by: thelightkeeper | last post by:
Hi, I have 1 table contains about 4 millions entries structure like below: ( AlarmID int, SetTime datetime )
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.