69 lines
1.7 KiB
C#
69 lines
1.7 KiB
C#
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using UnityEngine;
|
|
|
|
namespace AibisDream.Framework
|
|
{
|
|
public class MultipleSelector<T> : IMultipleSelector<T>
|
|
{
|
|
private readonly List<T> _items;
|
|
private int _batchSize;
|
|
|
|
public MultipleSelector(IEnumerable<T> items, int batchSize)
|
|
{
|
|
_items = new List<T>(items);
|
|
_batchSize = batchSize;
|
|
}
|
|
|
|
public T[] Select()
|
|
{
|
|
int[] indexArray = IMultipleSelector<T>.MultiRange(0, Count - 1, _batchSize);
|
|
return indexArray.Select(index => _items[index]).ToArray();
|
|
}
|
|
|
|
public void RemoveItem(T item)
|
|
{
|
|
_items.Remove(item);
|
|
}
|
|
|
|
public void AddItem(T item)
|
|
{
|
|
_items.Add(item);
|
|
}
|
|
|
|
public void SetBatchSize(int batchSize)
|
|
{
|
|
_batchSize = batchSize;
|
|
}
|
|
|
|
public int Count => _items.Count;
|
|
}
|
|
|
|
public interface IMultipleSelector<T>
|
|
{
|
|
T[] Select();
|
|
void RemoveItem(T item);
|
|
void AddItem(T item);
|
|
int Count { get; }
|
|
|
|
static int[] MultiRange(int start, int end, int batchSize)
|
|
{
|
|
// 确保要求的数量不超过范围
|
|
if (batchSize > end - start + 1)
|
|
{
|
|
Debug.LogError("要求的数量超过了范围内的数字总数");
|
|
return default;
|
|
}
|
|
|
|
var uniqueNumbers = new HashSet<int>();
|
|
|
|
while (uniqueNumbers.Count < batchSize)
|
|
{
|
|
var number = Random.Range(start, end + 1);
|
|
uniqueNumbers.Add(number);
|
|
}
|
|
|
|
return uniqueNumbers.ToArray();
|
|
}
|
|
}
|
|
} |