Last active
January 3, 2016 10:27
-
-
Save divide-by-zero/e135465f125483faca75 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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]); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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