Skip to content

Instantly share code, notes, and snippets.

@inertiave
Created July 5, 2019 23:41
Show Gist options
  • Save inertiave/11b1a47d6b33f3d5cb89d1be59e91dc5 to your computer and use it in GitHub Desktop.
Save inertiave/11b1a47d6b33f3d5cb89d1be59e91dc5 to your computer and use it in GitHub Desktop.
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class RandomBox : MonoBehaviour
{
Dictionary<string, int> entry = new Dictionary<string, int>();
public void AddEntry(string _name, int amount)
{
if (!entry.TryGetValue(_name, out int previousAmount)) {
entry[_name] = amount;
}
else {
entry[_name] = previousAmount + amount;
}
Debug.Log($"{_name}:{entry[_name]}");
}
public int Count() => entry.Values.Sum(x => x);
public float GetPossibility(string _name)
{
if (!entry.TryGetValue(_name, out int amount)) {
return 0;
}
return (float) amount / Count();
}
public string Pick(bool removePickedItem = false)
{
// 더 명백한 확률 유지를 위해서는 미리 픽 어레이를 만들어두고 차례로 뽑는것이 적절함.
var entryInstance = new List<string>();
foreach (var key in entry.Keys) {
int count = entry[key];
for (int i = 0; i < count; i++) {
entryInstance.Add(key);
}
}
int pickedIndex = Random.Range(0, Count() - 1);
string picked = entryInstance[pickedIndex];
Debug.Log($"{picked} : {GetPossibility(picked) * 100}%");
if (removePickedItem) {
if (entry[picked] == 1) {
entry.Remove(picked);
}
else {
entry[picked] = entry[picked] - 1;
}
Debug.Log($"New Possibility {picked} : {GetPossibility(picked) * 100}%");
}
return picked;
}
private void Awake()
{
AddEntry("Apple", 4);
AddEntry("Banana", 3);
AddEntry("Grape", 15);
Debug.Log($"Banana Possibility : {GetPossibility("Banana") * 100}%");
AddEntry("Apple", 2);
Debug.Log($"Banana Possibility : {GetPossibility("Banana") * 100}%");
Pick(false);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment