当前位置: 代码迷 >> C# >> 求1高效分组算法
  详细解决方案

求1高效分组算法

热度:83   发布时间:2016-05-05 03:22:43.0
求一高效分组算法
内容如下:
有n本不同的书,每m本分成一组,其中n>m,如不能均分,则最后一组放n%m本书,程序列出所有分组的可能。
例如:10本书,每3本为一组,则列出所有3,3,3,1的分组可能。
------解决思路----------------------
static void DistinctGroupArray()
        {
            List<List<List<int>>> list = new List<List<List<int>>>();//假定全组合后已按规则分组
            IEnumerable<List<List<int>>> result = list.Distinct(new SpecialEqualityComparer());
        }

        public class SpecialEqualityComparer : IEqualityComparer<List<List<int>>>
        {
            public bool Equals(List<List<int>> x, List<List<int>> y)
            {
                var tmpx = string.Join(",", x.Select(i => string.Join("", i.OrderBy(m => m))).OrderBy(m => m.Length).ThenBy(m => m));
                var tmpy = string.Join(",", y.Select(i => string.Join("", i.OrderBy(m => m))).OrderBy(m => m.Length).ThenBy(m => m));
                return tmpx == tmpy;
            }

            public int GetHashCode(List<List<int>> obj)
            {
                return obj.GetHashCode();
            }
        }

去重的初步代码,没测试,但思路应该表达出来了
然后性能估计……不是很好看
------解决思路----------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[] arr = { 1, 2, 3, 4, 5,6,7,8,9,10 };
var query = Split(arr, 3);
int max = 0;
foreach (var item in query)
{
// Console.WriteLine(string.Join("
------解决思路----------------------
", item.Select(x => string.Join(", ", x))));
int r = item.Sum(x => x.Aggregate(1, (a, b) => a * b));
if (max < r) max = r;
}
Console.WriteLine(max);
}
static IEnumerable<IEnumerable<IEnumerable<int>>> Split(IEnumerable<int> source, int n)
{
int[] splitter = Enumerable.Range(1, n - 1).ToArray();
splitter[n - 2]--;
int[] lastsp = Enumerable.Range(source.Count() - n, n -1).ToArray();
while (splitter.Zip(lastsp, (x, y) => x != y).Any(x => x == true))
{
for (int i = n - 2; i >= 0; i--)
{
if (splitter[i] < lastsp[i])
{
splitter[i]++;
for (int j = i + 1; j < n - 1; j++)
{
splitter[j] = splitter[i] + j - i;
}
break;
}
}
IEnumerable<int>[] result = new IEnumerable<int>[n];
int acc = 0;
for (int i = 0; i < n; i++)
{
if (i == n - 1)
{
result[i] = source.Skip(acc);
}
else
{
result[i] = source.Skip(acc).Take(splitter[i] - acc);
acc = splitter[i];
}
}
yield return result;
}
}
}
}
  相关解决方案