.net C# 实现任意List的笛卡尔乘积算法代码

可以扩展到多个集合的情况。类似的例子有,如果A表示某学校学生的集合,B表示该学校所有课程的集合,则A与B的笛卡尔积表示所有可能的选课情况

代码如下:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace 算法
{
    public static class 算法
    {
        /// <summary>
        /// 笛卡尔乘积
        /// </summary>
        public static List<List<T>> CartesianProduct<T>(this List<List<T>> lstSplit)
        {
            int count = 1;
            lstSplit.ForEach(item => count *= item.Count);
            //count = lstSplit.Aggregate(1, (result, next) => result * next.Count);

var lstResult = new List<List<T>>();

for (int i = 0; i < count; ++i)
            {
                var lstTemp = new List<T>();
                int j = 1;
                lstSplit.ForEach(item =>
                {
                    j *= item.Count;
                    lstTemp.Add(item[(i / (count / j)) % item.Count]);
                });
                lstResult.Add(lstTemp);
            }
            return lstResult;
        }
    }

class Program
    {
        public static void Main()
        {
            StringDemo();
            根据Sector生成Routing的Demo();
            根据Sector生成Routing的Demo2();
        }

/// <summary>
        /// 简单字符串 笛卡尔乘积
        /// </summary>
        private static void StringDemo()
        {
            var lstSource = new List<List<string>>
            {
                new List<string>() { "A","B","C"},
                new List<string>() { "D","E","F"},
                new List<string>() { "G","H","I"},
            };

var sw = new Stopwatch();
            sw.Start();
            var lstResult = lstSource.CartesianProduct();
            Console.WriteLine(sw.Elapsed);
        }

private static void 根据Sector生成Routing的Demo()
        {
            //默认允许输入多个BookingClass,表示使用任意一个都可以。
            var lstSectorDef = new List<Sector>
            {
                new Sector{ SeqNO=1, BookingClass="A/A1/A2"},
                new Sector{ SeqNO=2, BookingClass="B/B1/B2"},
                new Sector{ SeqNO=3, BookingClass="C/C1/C2"},
                //.....数量不定
            };

var sw = new Stopwatch();
            sw.Start();

var lstSectorGroup = new List<List<Sector>>();
            lstSectorDef.ForEach(item =>
            {
                var lstSector = new List<Sector>();
                foreach (var bookingClass in item.BookingClass.Split('/'))
                {
                    var sector = item.Clone();
                    sector.BookingClass = bookingClass;

lstSector.Add(sector);
                }
                lstSectorGroup.Add(lstSector);
            });

var lstRouting = lstSectorGroup.CartesianProduct();

Console.WriteLine(sw.Elapsed);
        }

private static void 根据Sector生成Routing的Demo2()
        {
            //默认允许输入多个BookingClass,表示使用任意一个都可以。
            var lstSectorDef = new List<Sector>
            {
                new Sector{ SeqNO=1, BookingClass="A1/A2/A3"},
                new Sector{ SeqNO=2, BookingClass="B1/B2/B3"},
                new Sector{ SeqNO=3, BookingClass="C1/C2/C3"},
                //.....数量不定
            };

var sw = new Stopwatch();
            sw.Start();

var lstTemp = new List<List<string>>();
            lstSectorDef.ForEach(item =>
            {
                lstTemp.Add(item.BookingClass.Split('/').ToList());
            });

var lstBookingClassGroup = lstTemp.CartesianProduct();

var lstRouting = new List<List<Sector>>();
            for (int i = 0; i < lstBookingClassGroup.Count; i++)
            {
                var lstSector = new List<Sector>();
                for (int j = 0; j < lstSectorDef.Count; j++)
                {
                    var sector = lstSectorDef[j].Clone();
                    sector.BookingClass = lstBookingClassGroup[i][j];
                    lstSector.Add(sector);
                }
                lstRouting.Add(lstSector);
            }

Console.WriteLine(sw.Elapsed);
        }

}

[DebuggerDisplay("Sector:SeqNO={SeqNO},BookingClass={BookingClass}")]
    public class Sector
    {
        public int SeqNO { get; set; }
        public string BookingClass { get; set; }

public Sector Clone()
        {
            return this.MemberwiseClone() as Sector;
        }
    }
}

(0)

相关推荐

  • c#哈希算法的实现方法及思路

    有想过hash["A1"] = DateTime.Now;这句是怎么实现的吗?我们来重温下学校时代就学过的哈希算法吧. 我们要写个class,实现如下主程序调用: 复制代码 代码如下: static void Main(string[] args)        {            MyHash hash = new MyHash();            hash["A1"] = DateTime.Now;            hash["A2

  • c#汉诺塔的递归算法与解析

    从左到右 A  B  C 柱 大盘子在下, 小盘子在上, 借助B柱将所有盘子从A柱移动到C柱, 期间只有一个原则: 大盘子只能在小盘子的下面. 如果有3个盘子, 大中小号, 越小的越在上面, 从上面给盘子按顺序编号 1(小),2(中),3(大), 后面的原理解析引用这里的编号. 小时候玩过这个游戏, 基本上玩到第7个,第8个就很没有耐心玩了,并且操作的动作都几乎相同觉得无聊.  后来学习编程, 认识到递归, 用递归解决汉诺塔的算法也是我除了简单的排序算法后学习到的第一种算法. 至于递归,简单来说

  • asp.net(c#)两种随机数的算法,可用抽考题

    第一种算法,存大一点问题.没有查出来  复制代码 代码如下: static void Main(string[] args)  {  //  // TODO: 在此处添加代码以启动应用程序  int singletitlemeasure=5;  int n=1;//声明一个表示考试类型的int变量  Random ran=new Random(unchecked((int)DateTime.Now.Ticks));  int Int1Random;  switch(n)  {  case 1:/

  • 基于C#代码实现九宫格算法横竖都等于4

    最近在朋友圈有朋友问我,这样一道题,具体如图所示: 我的算法: static void Main(string[] args) { /* * a + b - 9 = 4 * + - - * c - d * e =4 * / * - * f + g - h=4 * || || || * 4 4 4 * */ int flag = 50; for(int a=0;a<14; a++) //a { for (int b = 0; b <14; b++) //b { //a+b-9=4 故 a+b=1

  • c# 实现MD5,SHA1,SHA256,SHA512等常用加密算法源代码

    复制代码 代码如下: using System; using System.IO; using System.Data; using System.Text; using System.Diagnostics; using System.Security; using System.Security.Cryptography; /**//* * .Net框架由于拥有CLR提供的丰富库支持,只需很少的代码即可实现先前使用C等旧式语言很难实现的加密算法.本类实现一些常用机密算法,供参考.其中MD5算

  • C#加密算法汇总(推荐)

    方法一: 复制代码 代码如下: //须添加对System.Web的引用 using System.Web.Security; ... /// <summary> /// SHA1加密字符串 /// </summary> /// <param name="source">源字符串</param> /// <returns>加密后的字符串</returns> public string SHA1(string sour

  • C#常见算法面试题小结

    本文实例汇总了C#面试常见的算法题及其解答.具有不错的学习借鉴价值.分享给大家供大家参考.具体如下: 1.写出冒泡,选择,插入排序算法. //冒泡排序 public class bubblesorter { public void sort(int[] list) { int i, j, temp; bool done = false; j = 1; while ((j < list.Length) && (!done)) { done = true; for (i = 0; i &

  • C#的3DES加密解密算法实例代码

    C#类如下: 复制代码 代码如下: using System;using System.Collections.Generic;using System.Text;using System.Security.Cryptography;using System.IO; namespace ConsoleApplication1{    /// <summary>    /// 加解密类    /// </summary>    public class EncryptHelper  

  • 基于私钥加密公钥解密的RSA算法C#实现方法

    本文实例讲述了基于私钥加密公钥解密的RSA算法C#实现方法,是一种应用十分广泛的算法.分享给大家供大家参考之用.具体方法如下: 一.概述 RSA算法是第一个能同时用于加密和数字签名的算法,也易于理解和操作. RSA是被研究得最广泛的公钥算法,从提出到现在已近二十年,经历了各种攻击的考验,逐渐为人们接受,普遍认为是目前最优秀的公钥方案之一.RSA的安全性依赖于大数的因子分解,但并没有从理论上证明破译RSA的难度与大数分解难度等价. RSA的安全性依赖于大数分解.公钥和私钥都是两个大素数( 大于 1

  • C#实现的海盗分金算法实例

    本文实例讲述了C#实现的海盗分金算法.分享给大家供大家参考,具体如下: 海盗分金的故事 5个海盗抢到了100颗宝石,每一颗都一样的大小和价值连城. 他们决定这么分: 1.抽签决定自己的号码(1,2,3,4,5) 2.首先,由1号提出分配方案,然后大家5人进行表决,当且仅当半数和超过半数的人同意时,按照他的提案进行分配,否则将被扔入大海喂鲨鱼. 3.如果1号死后,再由2号提出分配方案,然后大家4人进行表决,当且仅当半数和超过半数的人同意时,按照他的提案进行分配,否则将被扔入大海喂鲨鱼. 4.依次类

  • C#数据结构与算法揭秘五 栈和队列

    这节我们讨论了两种好玩的数据结构,栈和队列. 老样子,什么是栈, 所谓的栈是栈(Stack)是操作限定在表的尾端进行的线性表.表尾由于要进行插入.删除等操作,所以,它具有特殊的含义,把表尾称为栈顶(Top) ,另一端是固定的,叫栈底(Bottom) .当栈中没有数据元素时叫空栈(Empty Stack).这个类似于送饭的饭盒子,上层放的是红烧肉,中层放的水煮鱼,下层放的鸡腿.你要把这些菜取出来,这就引出来了栈的特点先进后出(First in last out).   具体叙述,加下图. 栈通常记

  • C# 生成高质量缩略图程序—终极算法

    先看代码: using System; using System.Drawing; using System.Drawing.Imaging; using System.Drawing.Drawing2D; /**//// <summary> ///  /// **生成高质量缩略图程序** ///  ///  File: GenerateThumbnail.cs ///  ///  Author: 周振兴 (Zxjay 飘遥) ///  ///  E-Mail: tda7264@163.com

随机推荐