Created
April 10, 2019 19:46
-
-
Save srcnalt/6819c75dd022b0cfcf6b8890486bccfb 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
void Main() | |
{ | |
RandomItem<string> operation = new RandomItem<string>(); | |
operation.Add("A", 0.4d); | |
operation.Add("B", 0.5d); | |
operation.Add("D"); | |
Console.WriteLine(operation.Random().item); | |
Console.WriteLine(operation.Random().item); | |
Console.WriteLine(operation.Random().item); | |
Console.WriteLine(operation.Random().item); | |
Console.WriteLine(operation.Random().item); | |
Console.WriteLine(operation.Random().item); | |
Console.WriteLine(operation.Random().item); | |
Console.WriteLine(operation.Random().item); | |
Console.WriteLine(operation.Random().item); | |
Console.WriteLine(operation.Random().item); | |
Console.WriteLine(operation.Random().item); | |
Console.WriteLine(operation.Random().item); | |
} | |
// Define other methods and classes here | |
public class Item<T> | |
{ | |
public T item; | |
public double rate; | |
public Item(T item, double rate = 0) | |
{ | |
if(rate > 1) throw new Exception("Rate can't be bigger than 1"); | |
this.item = item; | |
this.rate = rate; | |
} | |
} | |
public class RandomItem<T> | |
{ | |
private List<Item<T>> itemList = new List<Item<T>>(); | |
private double cumulativeRate = 0; | |
private int unratedItemCount = 0; | |
private bool calculated = false; | |
private Random random = new Random(); | |
public void Add(T item, double rate = 0) | |
{ | |
itemList.Add(new Item<T>(item, rate)); | |
if(rate == 0) | |
{ | |
unratedItemCount++; | |
} | |
else | |
{ | |
cumulativeRate += rate; | |
} | |
if(cumulativeRate > 1) throw new Exception("Cumulative rate exceeded 1"); | |
} | |
public Item<T> Random() | |
{ | |
CalculateAllRates(); | |
double rand = random.NextDouble(); | |
Console.WriteLine(rand); | |
double pivot = 0; | |
foreach(var item in itemList) | |
{ | |
pivot += item.rate; | |
if(pivot >= rand) | |
{ | |
return item; | |
} | |
} | |
return null; | |
} | |
private void CalculateAllRates() | |
{ | |
if(!calculated) | |
{ | |
double unitRate = (1 - cumulativeRate) / unratedItemCount; | |
foreach(var item in itemList) | |
{ | |
if(item.rate == 0) | |
{ | |
item.rate = unitRate; | |
} | |
} | |
calculated = true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment