Skip to content

Instantly share code, notes, and snippets.

@suakig
Created April 17, 2015 13:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suakig/cdee094cfc94be8b209a to your computer and use it in GitHub Desktop.
Save suakig/cdee094cfc94be8b209a to your computer and use it in GitHub Desktop.
RatePicker.cs
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// 要素と重みのリストから確率に従ったデータを取り出すクラス
/// </summary>
public class RatePicker<T>
{
private List<int> RateList = new List<int>();
private List<T> keyList = new List<T>();
/// <summary>
/// 要素と重みを入れたリストから乱数テーブルを作成する。
/// keyListに要素
/// RateListに要素の重み分だけ配列番号を入れる
/// </summary>
/// <param name="itemMap">Item map.</param>
public RatePicker(Dictionary<T, int> itemMap)
{
int keyIndex = 0;
foreach (KeyValuePair<T, int> item in itemMap)
{
keyList.Add(item.Key);
for (int rate = 0; rate < item.Value; rate++) {
RateList.Add (keyIndex);
}
keyIndex++;
}
if (RateList.Count == 0 || keyList.Count == 0)
{
Debug.Log ("RatePicker 要素 または 確率がありません");
}
}
public bool PickeAble()
{
return RateList.Count != 0 && keyList.Count != 0;
}
/// <summary>
/// 確率を返す。PickeAbleがTrue出ないとエラーが出るので注意
/// </summary>
/// <returns>The rate.</returns>
public T PickeRate()
{
return keyList[RateList[Random.Range(0, RateList.Count)]];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment