HashTable Beginning Question
-
This is my first time working with hashtables. Here's what I'm trying to do, and what I need to do. First, I have a HashTable that's initialized with the capacity of 169 (the number of possible pocket hands in holdem poker). I deal two random cards to a player - and then create a string that looks like this, from the cards: AKo, AKs, KKo, 32s ... etc. It'll always be in that format. Now, I have a hashtable called HandCounter. What I want to do, is check if that string exists as a "key" in the hash table. If it does, then get the value from that key and increment the value that is stored by 1. If it doesn't, then create a new key/value pair with the pocket string as the key and the int value 1. Here's what I thought the code would probably look like: if(HandCounter.ContainsKey(Hand.ToPocketString())) { HandCounter[Hand.ToPocketString()]++; } else { HandCounter.Add(Hand.ToPocketString(), 1); } Though something is wrong here. I'm attempting to use a string as the key, but it says it requires a type of "object" for the key. I'm attempting to use the value as an integer, but it says it uses type "object" as the value as well. Do I need to typecast these?
-
This is my first time working with hashtables. Here's what I'm trying to do, and what I need to do. First, I have a HashTable that's initialized with the capacity of 169 (the number of possible pocket hands in holdem poker). I deal two random cards to a player - and then create a string that looks like this, from the cards: AKo, AKs, KKo, 32s ... etc. It'll always be in that format. Now, I have a hashtable called HandCounter. What I want to do, is check if that string exists as a "key" in the hash table. If it does, then get the value from that key and increment the value that is stored by 1. If it doesn't, then create a new key/value pair with the pocket string as the key and the int value 1. Here's what I thought the code would probably look like: if(HandCounter.ContainsKey(Hand.ToPocketString())) { HandCounter[Hand.ToPocketString()]++; } else { HandCounter.Add(Hand.ToPocketString(), 1); } Though something is wrong here. I'm attempting to use a string as the key, but it says it requires a type of "object" for the key. I'm attempting to use the value as an integer, but it says it uses type "object" as the value as well. Do I need to typecast these?
I just got this to work. How do I enumerate through it, displaying the Key Value pairs?
-
I just got this to work. How do I enumerate through it, displaying the Key Value pairs?
Alright, i just figured that out as well: foreach(string Key in HandCounter.keys) Console.WriteLine(Key + ": " + HandCounter[Key].ToString()); Very simple, jeez.