+ 2

Filling MD arrays with loops in C#

{C#}So, say one wishes to create a deck of cards (sans jokers) using a 2D array. How would one fill it with for-loops? Is this even possible?

11th May 2018, 3:58 AM
Paul Blum
Paul Blum - avatar
7 Antworten
+ 6
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoloLearn { class Program { static void Main(string[] args) { Card[,] deck = new Card[4, 13]; for(int i = 0; i < 4; ++i) { for(int j = 0; j < 13; ++j) { deck[i, j] = new Card(i, j); } } foreach(Card card in deck) { Console.WriteLine("{0} of {1}",card.CardValue, card.CardSuit); } } } enum Suit { Hearts, Spades, Diamonds, Clubs } enum CardFace { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace } class Card { private Suit cardSuit; private CardFace cardValue; public Suit CardSuit { get => cardSuit; set => cardSuit = value; } public CardFace CardValue {get => cardValue; set => cardValue = value; } public Card(int suit, int cardValue) { this.cardSuit = (Suit)suit; this.cardValue = (CardFace)cardValue; } } }
11th May 2018, 7:21 AM
ChaoticDawg
ChaoticDawg - avatar
+ 5
hinanawi a matrix makes sense here, because the deck has fixed dimensions, which is when you'd normally use a matrix. It would really make more sense not to use either a matrix or a jagged array, but a collection instead.
11th May 2018, 1:58 PM
ChaoticDawg
ChaoticDawg - avatar
+ 2
@ChaoticDawg thank you!
12th May 2018, 7:42 AM
Paul Blum
Paul Blum - avatar
+ 1
So far I have tried and imagine a 4X13 array. Then using a nested loop to fill it. I couldn’t get that to work however. I know using Enum is easier, but this was my curiosity peaking! :)
11th May 2018, 4:01 AM
Paul Blum
Paul Blum - avatar
+ 1
ChaoticDawg honestly yes
11th May 2018, 1:59 PM
hinanawi
hinanawi - avatar
0
int c = 1; int[][] cards = new int[13][4]; for(int i = 0; i < 13; i++) { for(int j = 0; j < 4; j++) { cards[i][j] = c; } c++; if(c == 11) c++; } this is the simplest solution you can go with
11th May 2018, 5:46 AM
hinanawi
hinanawi - avatar
- 1
ChaoticDawg i recommend a jagged array instead of a matrix, but good code
11th May 2018, 9:16 AM
hinanawi
hinanawi - avatar