multiplication of C# lists -
i having brain freeze , cant figure out solution problem.
i created class called customset contained string list. class holding reference customset stores list.
public class customset : ienumerable<string> { public string name { get; set; } internal ilist<string> elements; public customset(string name) { this.name = name; this.elements = new list<string>(); } public ienumerable<string> elements { { return elements; } } public ienumerator<string> getenumerator() { return elements.getenumerator(); } ienumerator ienumerable.getenumerator() { return getenumerator(); } } so iterate on list of custom sets out put 2d string array columns number of customset(s) , rows multiplication of customset elements.
as example, if there 3 custom sets in list: 1st had 3 elements, 2nd had 2 elements , 3rd had 3 elements. want output 3 columns , 18 rows (3*2*3). following code attempt @ solution:
customset motion = new customset("motion"); motion.elements.add("low"); motion.elements.add("medium"); motion.elements.add("high"); customset speed = new customset("speed"); speed.elements.add("slow"); speed.elements.add("fast"); customset mass = new customset("mass"); mass.elements.add("light"); mass.elements.add("medium"); mass.elements.add("heavy"); list<customset> aset = new list<customset>(); aset.add(motion); aset.add(speed); aset.add(mass); //problem code int rows = 1; for(int = 0; < aset.count; i++) { rows *= aset[i].elements.count; } string[,] array = new string[aset.count, rows]; int modulus; (int = 0; < aset.count; i++) { (int j = 0; j < rows; j++) { modulus = j % aset[i].elements.count; array[i, j] = aset[i].elements[modulus]; } } (int j = 0; j < rows; j++) { (int = 0; < aset.count; i++) { console.write(array[i, j] + " / "); } console.writeline(); } //end console.readline(); however, code not output correct string array (though close). out put following:
low / slow / light /
low / slow / medium /
low / slow / heavy /
low / fast / light /
low / fast / medium /
low / fast / heavy /
medium / slow / light /
medium / slow / medium /
medium / slow / heavy /
medium / fast / light /
medium / fast / medium /
medium / fast / heavy /
high / slow / light /
high / slow / medium /
high / slow / heavy /
high / fast / light /
high / fast / medium /
high / fast / heavy /
now variables in problem number of customsets in list , number of elements in each customset.
you can product in 1 go:
var crossjoin = m in motion s in speed ms in mass select new { motion = m, speed = s, mass = ms }; foreach (var val in crossjoin) { console.write("{0} / {1} / {2}", val.motion, val.speed, val.mass); } now, since don't know number of lists, need more. eric lippert covers in this article, can use certesianproduct function defined there in following manner:
var cproduct = somecontainerclass.cartesianproduct(aset.select(m => m.elements)); var stringstooutput = cproduct.select(l => string.join(" / ", l));
Comments
Post a Comment