473,732 Members | 2,204 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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","t hree"},{"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 13158
Robert Bravery <me@u.comwrot e:
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","t hree"},{"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.WriteLi ne ("{0} {1}", x, y);
}
}
}
}

--
Jon Skeet - <sk***@pobox.co m>
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','orang e','banana'},{' man','woman','c hild'},{'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.co mwrote in message
news:MP******** *************** *@msnews.micros oft.com...
Robert Bravery <me@u.comwrot e:
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","t hree"},{"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.WriteLi ne ("{0} {1}", x, y);
}
}
}
}

--
Jon Skeet - <sk***@pobox.co m>
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.comwrot e:
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','orang e','banana'},{' man','woman','c hild'},{'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"};

PrintCrossProdu ct(new string[]{"apple","orang e","banana"} ,
new string[]{"man","woman", "child"},
new string[]{"red","green", "blue",
"white","black" });
}

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

static void PrintCrossProdu ct(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)
{
PrintCrossProdu ct(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.WriteLi ne (builder);
}
}
}
}

--
Jon Skeet - <sk***@pobox.co m>
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.comwrot e:
>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','oran ge','banana'},{ 'man','woman',' child'},{'red', 'green','blue', 'w
hite','black '}
To review here, each of these elements is an IEnumerable<str ing>.
Therefore the cross-product will be an
IEnumerable<IEn umerable<string >>. So here's the code:
static IEnumerable<str ingpre(string x, IEnumerable<str ingys)
{ yield return x;
if (ys!=null) foreach (string y in ys) yield return y;
}

static IEnumerable<IEn umerable<string >>
cross(IEnumerab le<stringxs, IEnumerable<IEn umerable<string >yss)
{ foreach (string x in xs)
{ if (yss==null) yield return prepend(x,null) ;
else foreach(IEnumer able<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<IEn umerable<string >c = null;
foreach (string[] ar in ars) c=cross(ar,c);

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

--
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(IEnumer able<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.c om...
Lucian Wischik <lu***@wischik. comwrote:
>>{ foreach (string x in xs)
{ if (yss==null) yield return prepend(x,null) ;
else foreach(IEnumer able<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
1837
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 variable array ($HTTP_SESSION_VARS = array();) basically this stores an associative array with the id number of the product and the qty (ie cart = qty of that product). This works fine, but I need to be able to have sub options AND colours for
17
2713
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. Table called Ticket has one row per ticket. Table named History has 0, 1, or many rows per ticket. As the tech support person makes notes to update the ticket, it adds a new row per entry into History table. One of the things storeed in this...
1
6053
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 function that is capable to do this or do I have to write a function that can calculate vector products for myself? Furthermore, what data structure should I use? Thanks in advance, Bernhard Hidding
5
2561
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 documentation this should be equivalent. The following example should explain the problem: CREATE TABLE a (a1 text, a2 text); CREATE TABLE b (b1 text, b2 text); CREATE TABLE c (a1 text, b1 text, c1 text);
4
5580
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 of defect type by calendar month. Defect types are stored in one table, defect transactions in another along with date etc. When I cross-tab the results, defect types that have no defects recorded against them appear as a blank (null) value. That...
5
3064
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
1449
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
2066
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 store the items. The output should display the information one product at a time, including the item number, the name of the product, the number of units in stock, the price of each unit, and the value of the inventory of that product. In addition,...
5
12579
by: thelightkeeper | last post by:
Hi, I have 1 table contains about 4 millions entries structure like below: ( AlarmID int, SetTime datetime )
0
8946
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9447
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9307
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6735
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4809
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2721
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2180
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.