- Home /
How to get quantity of same item in list?
How could I get quantity of same item in list? Lets say I have a treasureBag
list, which contains Treasure
class variables, and inside there's 3 sapphires, 1 ruby, and 1 emerald. How could I possibly return specific integer for their amount?
Answer by Unitraxx · Dec 09, 2014 at 07:42 PM
Ok I read your comments in the other answer and it looks like you have a unique id for each item. If this unique id starts at 0 you can hold an array of counts with as index the id of the item and as value the count of that item.
To initialize this you just start with an integer array with size equal to the number of items there are and all values set to 0. Then you iterate over all your items, use the unique id as index to access the count in the array, and increase that number with one.
Pretty simple and if you don't have a unique id starting from zero, you can apply the same principle with a dictionary that maps integers to integers.
The advantages of this method is that you only have to iterate once over the entire list to get ALL the counts. Also you never need to adjust your function when you add a new item type. (With a switch statement you would.)
This sounds like a good idea, I'm going to try this tomorrow or later today if I'll be given enough time and wont stay lazy, thanks :D
Yes! It works this way, it also solved up some other little things for me, how couldn't I have thought of this simple, yet efficient way before, thanks!
Answer by EvilTak · Dec 09, 2014 at 04:09 PM
If the Treasure class has a variable type
with type of enum TreasureType { Sapphire, Ruby, Emerald }
then:
int sapphireCount, rubyCount, emeraldCount;
foreach(Treasure item in treasureBag){
switch(item.type){
case TreasureType.Sapphire:
sapphireCount++;
break;
case TreasureType.Ruby:
rubyCount++;
break;
case TreasureType.Emerald:
emeraldCount++;
break;
}
}
No, sadly it doesn't have enum type, it would be way too much enums to make for all the treasure types I plan to have. Thanks for suggestion though.
I assigned each of them unique ID (Int), I guess I could use 'Switch' thing with them too, but then I'd still have to assign many custom integers for their quantities. I guess I'll try to do something with those IDs when I'll have some free time. I'll reply on how it went, if you have any more suggestions, let me know.
I have an idea, but I need the number of treasure types for that. It is a very fast and efficient idea.