Advertisement
jocarrillo

Cartesianple

Sep 19th, 2019
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.15 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. public class CartesianProductSelectManyExample
  7. {
  8.     public static void Main(string[] args)
  9.     {
  10.         var abcArray = new string[]{"a", "b", "c"};
  11.         var xyzArray = new string[]{"x", "y", "z"};
  12.  
  13.         var combos = CartesianProductSmart(abcArray, xyzArray);
  14.  
  15.         foreach(var combo in combos)
  16.         {
  17.             Console.WriteLine(string.Format("[{0},{1}]", combo[0], combo[1]));
  18.         }
  19.     }
  20.  
  21.     private static string[][] CartesianProductSmart(string[] arr1, string[] arr2)
  22.     {
  23.         // for each s1 in arr1, extract arr2,
  24.         // then pass s1 and s2 into a newly-made string array.
  25.         return arr1.SelectMany(s1 => arr2, (s1, s2) => new string[]{s1, s2})
  26.             .ToArray();
  27.     }
  28.  
  29.     private static string[][] CartesianProductDumb(string[] arr1, string[] arr2)
  30.     {
  31.         // the dumb way; nested foreach
  32.         string[][] combos = new string[arr1.Length * arr2.Length][];
  33.  
  34.         int ii = 0;
  35.         foreach(var strOne in arr1)
  36.         {
  37.             foreach(var strTwo in arr2)
  38.             {
  39.                 string[] combo = new string[2];
  40.  
  41.                 combo[0] = strOne;
  42.                 combo[1] = strTwo;
  43.                 combos[ii] = combo;
  44.  
  45.                 ii++;
  46.             }
  47.         }
  48.  
  49.         return combos;
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement