+ 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?
7 ответов
+ 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;
}
}
}
+ 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.
+ 2
@ChaoticDawg thank you!
+ 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! :)
+ 1
ChaoticDawg honestly yes
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
- 1
ChaoticDawg i recommend a jagged array instead of a matrix, but good code