• 任意数相加求和


    在网上看到一端代码,觉得很新颖,特此记录下来以供大家学习参考:

    用C#写一个函数。功能如下:
    任意给定一组数,例如{12,60,-8,99,15,35,17,18},
    找出任意数相加(不能重复)之后的结果为35(任意设定)的情况
    例如:12+8+15; 35; 17+18。

    算法如下:

         private static readonly int[] values = {12,60,8,99,15,35,17,18 };
         private const int toltal = 35;

           private void Test()
            {
                Array.ForEach(Array.FindAll(values,x=>x==toltal),Console.WriteLine);
                Dictionary<string, int> dic = new Dictionary<string, int>();
                for (int i = 0; i < values.Length; i++)
                {
                    dic.Add(values[i].ToString(), i);
                }
                GetString(dic);
                Console.ReadLine();
            }

            private static void GetString(Dictionary<string,int> dd)
            {
                Dictionary<string, int> dic = new Dictionary<string, int>();
                foreach (KeyValuePair<string, int> kv in dd)
                {
                    for (int i = kv.Value + 1; i < values.Length; i++)
                    {
                        string calc = kv.Key + "+" + values[i];
                        if (Convert.ToInt32(new DataTable().Compute(calc, null)) == toltal)
                        {
                            Console.WriteLine(calc);
                        }
                        dic.Add(kv.Key+"+"+values[i],i);
                    }
                }
                if (dic.Count > 0)
                    GetString(dic);
            }

  • 相关阅读:
    Linux下redis的安装
    elasticsearch使用时问题
    Elasticsearch 2.x plugin 问题汇总
    elasticsearch-jdbc 插件说明
    ElasticSearch 2.x 问题汇总
    深入JVM《一》
    linux fastdfs 搭建配置(单机)
    mybatis自动generator
    spring-boot mybatis 配置 主从分离 事务
    Maven Nexus
  • 原文地址:https://www.cnblogs.com/xiaolifeidao/p/3770291.html
Copyright © 2020-2023  润新知