"Peter Duniho" <(E-Mail Removed)> skrev i meddelandet
news:(E-Mail Removed)...
> On 3/9/11 5:23 PM, Tony Johansson wrote:
>> Hello!
>>
>> Here is some code that initialize one card of Deck A card of Deck have 52
>> cards.
>> Now to my question I also want to be able to initialize any number of
>> decks
>> in a collection
>> For example when this method InitDeck is called the array collection
>> cards
>> have already been allocated to the right size.
>> So the comment is there now but I just wonder if there is possible to
>> write
>> some nice code that initialize for example 3
>> card of deck which mean that this cards array can store three decks of
>> card
>
> Yes, it is possible to write the code _much_ more nicely than what you've
> posted, and for it to work as well (though, Arne's suggestion should
> address the basic logic error in your original code).
>
> First: the "index on position 0 is not used" is ridiculous. If it's not
> used, why are you allocating a Card instance to store in it? And why not
> use it? Zero-based arrays are a fundamental feature of C#; it's silly to
> not base your index values on 0, because if you don't, you just wind up
> having to add or subtract 1 everywhere when using indexes.
>
> Second: casting your (apparently?) enum values to ints and then iterating
> that way is silly and fragile. What if Club winds up not being the first
> value, or Spade winds up not being the last? Why should the enum values
> have to have anything at all to do with the array index being computed?
> What if for whatever reason it turns out you need your enum values to be
> something other than a sequential index? Why should your code have to
> assume any underlying value for the enum at all?
>
> Third: what's with all the computation for the index into the array of
> Cards? In theory, you're just going to be iterating through the array
> sequentially, so you might as well just maintain an index and increment it
> with each new card.
>
> Here's a version of the code that IMHO is much better:
>
> enum CardSuit { Club, Diamond, Heart, Spade }
>
> enum CardRank
> {
> Ace, One, Two, Three, Four, Five, Six, Seven,
> Eight, Nine, Ten, Jack, Queen, King
> }
>
> // One deck is always 52 cards; a shoe may have more than one deck
> static void InitShoe(Card[] cards)
> {
> if (cards.Length % 52 != 0)
> {
> throw new ArgumentException("cards array must have a multiple of 52
> elements");
> }
>
> int icard = 0;
>
> while (icard < cards.Length)
> {
> foreach (CardSuit suit in Enum.GetValues(typeof(CardSuit)))
> {
> foreach (CardRank rank in Enum.GetValues(typeof(CardRank)))
> {
> cards[icard++] = new Card(suit, rank);
> }
> }
> }
> }
>
> Hope that helps.
>
> Pete
Really nice solution Pete!!
//Tony
|