BITKit/Packages/Runtime~/Core/Mathematics/MathE.cs

137 lines
3.8 KiB
C#
Raw Normal View History

2023-06-29 14:57:11 +08:00
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace BITKit
{
public static class MathE
{
public static bool Equals<T>(params T[] objs)
{
var a = objs.FirstOrDefault();
foreach (var b in objs)
{
if (a.Equals(b))
{
a = b;
continue;
}
else
{
return false;
}
}
return true;
}
public static IEnumerable<T> Subtract<T>(IEnumerable<T> a, IEnumerable<T> b) where T : IEnumerable
{
List<T> list = new();
foreach (var x in a)
{
if (b.Contains(x))
{
}
else
{
list.Add(x);
}
}
return list;
}
public static bool Contains<T>(IEnumerable<T> a, IEnumerable<T> b)
{
foreach (var x in b)
{
if (a.Contains(x))
{
}
else
{
return false;
}
}
return true;
}
public static IEnumerable<T[]> Combinations<T>(IEnumerable<T> source)
{
if (null == source) throw new ArgumentNullException(nameof(source));
T[] data = source.ToArray();
return Enumerable.Range(0, 1 << (data.Length) - 1)
.Select(index => data.Where((v, i) => (index & (1 << i)) != 0).ToArray());
}
public static IEnumerable<T> InsertOf<T>(this IEnumerable<T> self, int index, T item)
{
if (self is null) return null;
switch (self)
{
case List<T> list:
list.Insert(index,item);
break;
default:
var _list = self.ToList();
_list.Insert(index,item);
return _list;
}
return self;
}
public static bool TryGetSingle<T>(this IEnumerable<T> self, out T value)
{
value = default;
if (self.Any())
{
value = self.ElementAt(0);
}
return value is not null;
}
/// <summary>
/// 组合集合中的所有元素
/// </summary>
/// <param name="self"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static IEnumerable<T> AllCombinations<T>(this IEnumerable<T> self)
{
var list = self.ToList();
var count = list.Count;
for (var i = 0; i < count; i++)
{
var item = list[i];
for (var j = i + 1; j < count; j++)
{
yield return item;
yield return list[j];
}
}
}
/// <summary>
/// 获取集合中所有的组合,每个组合中的元素个数为输入集合的元素个数,每个元素只出现一次
/// </summary>
/// <param name="self"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static IEnumerable<IEnumerable<T>> GetAllCombination<T>(this IEnumerable<T> self)
{
var list = self.ToList();
var count = list.Count;
for (var i = 0; i < count; i++)
{
var item = list[i];
for (var j = i + 1; j < count; j++)
{
yield return new List<T> { item, list[j] };
}
}
}
}
}