Skip to content

Instantly share code, notes, and snippets.

@divide-by-zero
Last active January 3, 2016 10:27
Show Gist options
  • Save divide-by-zero/e135465f125483faca75 to your computer and use it in GitHub Desktop.
Save divide-by-zero/e135465f125483faca75 to your computer and use it in GitHub Desktop.
public class MyUtil
{
//渡された重み付け配列からIndexを得る
public static int GetRandomIndex(params int[] weightTable)
{
var totalWeight = weightTable.Sum();
var value = Random.Range(1, totalWeight + 1);
var retIndex = -1;
for (var i = 0; i < weightTable.Length; ++i)
{
if (weightTable[i] >= value)
{
retIndex = i;
break;
}
value -= weightTable[i];
}
return retIndex;
}
}
public void Start()
{
var weightTable = new int[]{
1000,
50,
1
};
int index1 = MyUtil.GetRandomIndex(1000, 50, 1);
Debug.Log("index1:" + index1);
int index2 = MyUtil.GetRandomIndex(weightTable);
Debug.Log("index2:" + index2);
}
var count = new int[3];
for (int i = 0; i < 100000; ++i)
{
var index = MyUtil.GetRandomIndex(1000,50,1);
count[index]++;
}
for (int index = 0; index < count.Length; index++)
{
Debug.Log(index + ":" + count[index]);
}
var weightTable = new int[]{1000,50,1};
var count = new int[3];
for (int i = 0; i < 500; ++i)
{
var index = MyUtil.GetRandomIndex(weightTable);
count[index]++;
weightTable[index]--;
}
for (int index = 0; index < count.Length; index++)
{
Debug.Log("取得" + index + ":" + count[index]);
}
for (int index = 0; index < weightTable.Length; index++)
{
Debug.Log("残り" + index + ":" + weightTable[index]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment