//-----------------------------------------------------------------------
// <copyright file="Permutation.cs"
// project="SteelGame"
// assembly="SteelGame"
// solution="Steel"
// company="Opuno">
// Copyright (c) Opuno. All rights reserved.
// </copyright>
// <author id="">Andreas Brekken</author>
// <summary></summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Opuno.Steel.Utils
{
public static class Permutation
{
public static IEnumerable<List<int>> WaysToMake(int components, int highestNumber)
{
var distinct = false;
var componentN = components - 1;
var current = new List<int>();
for (int i = 0; i < components; i++)
{
current.Add(1);
}
while (true)
{
yield return current.ToList();
while (componentN > 0 && current[componentN] == (distinct ? current[componentN - 1] : highestNumber))
{
componentN--;
}
if (componentN == 0 && current[0] == highestNumber)
{
yield break;
}
current[componentN] += 1;
for (int i = componentN + 1; i < components; i++)
{
current[i] = 1;
}
componentN = components - 1;
}
}
public class ListEqualityComparer : IEqualityComparer<List<int>>
{
public static readonly ListEqualityComparer Instance = new ListEqualityComparer();
public bool Equals(List<int> x, List<int> y)
{
if (x.Count != y.Count)
{
return false;
}
if (x == y)
{
return true;
}
for (int i = 0; i < x.Count; i++)
{
if (!x[i].Equals(y[i]))
{
return false;
}
}
return true;
}
public int GetHashCode(List<int> obj)
{
var result = 0;
for (int i = 0; i < obj.Count; i++)
{
result ^= obj[i];
}
return result;
}
}
public static IEnumerable<List<int>> DisregardOrder(IEnumerable<List<int>> combinations)
{
return combinations.Select(combination => combination.OrderBy(k => k).ToList()).Distinct(ListEqualityComparer.Instance);
}
}
}
|