Skip to content

Instantly share code, notes, and snippets.

@nkjzm
Created November 19, 2019 09:33
Show Gist options
  • Save nkjzm/af7149634a11b2912ba19257d8f33bed to your computer and use it in GitHub Desktop.
Save nkjzm/af7149634a11b2912ba19257d8f33bed to your computer and use it in GitHub Desktop.
【C#】リスト中から重複せずに要素を取り出すクラス
using System.Collections.Generic;
/// <summary>
/// リスト中から重複せずに要素を取り出すクラス
/// </summary>
public class UniqueItemPicker<T>
{
T[] AllItems;
/// <summary>
/// コンストラクタ
/// </summary>
/// <param name="allItems">取り出したい要素の配列</param>
public UniqueItemPicker(T[] allItems)
{
AllItems = allItems;
InitIndexList();
}
void InitIndexList()
{
indexList.Clear();
for (int i = 0; i < AllItems.Length; i++)
{
indexList.Add(i);
}
}
/// <summary>
/// リスト中から重複せずに要素を取り出す
/// </summary>
public T GetUniqueItem()
{
if (indexList.Count == 0)
{
UnityEngine.Debug.LogError("要素がありません");
return default(T);
}
return AllItems[GetIndex()];
}
List<int> indexList = new List<int>();
int GetIndex()
{
int index = UnityEngine.Random.Range(0, indexList.Count);
int result = indexList[index];
indexList.RemoveAt(index);
return result;
}
/// <summary>
/// 使用履歴を初期化する
/// </summary>
public void ResetUsageHistory()
{
InitIndexList();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment