I was trying to write a function that would get a random card from a dictionary of cards in a players deck weighted by the number of cards of each type you have. I don't know if the solution I came up with is the fates way of doing something like this and this is something I'm going to be doing a lot per turn because of certain mechanics in the games design. Please let me know if there is something i missed that could help the performance of this code.
For some contexts _deck._card
is a dictionary with the key being a string and the value being a int. Dictionary<string, int> _cards
Also Nez.Random
is a singleton of my random class for the project. Random.nextInt(int max)
takes in a int for the max value of the random number.
static public int nextInt( int max )
{
return random.Next( max );
}
Code:
public string GetRandomCard()
{
string result = "";
var totalWeight = 0;
foreach (var cardNumber in _deck._cards)
totalWeight += cardNumber.Value;
var randNumber = Nez.Random.nextInt(totalWeight);
foreach (var cardNumber in _deck._cards)
{
var value = cardNumber.Value;
if (randNumber >= value)
{
randNumber -= value;
}
else
{
result = cardNumber.Key;
break;
}
}
return result;
}
Time complexity O(N^2) I dont think there is a way to decrease the time complexity but there might be other ways to optimize this code.
numCardTypes
for when you're not using it? \$\endgroup\$