Reputation:
I am trying to put a deck of cards (Blackjack) into an array or list. I have seen this done before but can't remember the syntax and can't find it anywhere.
I need something like this let list = [ 1 .. 10; 10; 10; 10 ] * 4
, but of course this doesn't work. If anybody could help I'd greatly appreciate it.
Upvotes: 0
Views: 142
Reputation: 52788
I'm not sure of the exact syntax you're after...
Ideally you want a list for suits and a list for cards and then you create a Cartesian Product, and it is probably easiest to store each card in the deck in a tuple of number, suit
let cards = [1..10]
let suits = [1..4]
let deck = seq {
for card in cards do //cards could just be [1..10]
for suit in suits do //suits could be too
yield card, suit }
//Show the answer
printfn "%A" (deck |> Seq.toList)
Usually a suit would be a Discriminated Union and you could map the numbers:
type Suit =
| Hearts
| Spades
| Diamonds
| Clubs
let toSuit suit =
match suit with
| 1 -> Hearts
| 2 -> Spades
| 3 -> Diamonds
| 4 -> Clubs
and change yield card, suit }
to yield card, toSuit suit }
You could do the same with the cards to by having a DU from Ace -> King. I'll leave that as an exercise for you ;)
Finally, if you are after a generic function to this, you could write something like this - I don't recall this been in FSharp.Core, but I may be wrong.
let multiplyList xs by = seq {
for x in xs do
for y in [1..by] do
yield x, y }
let deck = multiplyList cards 4 |> Seq.toList
Upvotes: 1
Reputation: 289
It would be nice if you stated what language you are using, because the answer may be different. I think you are looking for an array of array. You'll like need a bunch of arrays to keep track of the card rank, suit, rank value, and whether it has been played, not played, or whatever you'd like. So you need something like:
ranks = ['A', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K']
rankValues = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
suits = [ 'spades', 'hearts', 'clubs', 'diamonds' ]
deck = [[ 0,0,0,0,0,0,0,0,0,0,0,0,0],
[ 0,0,0,0,0,0,0,0,0,0,0,0,0],
[ 0,0,0,0,0,0,0,0,0,0,0,0,0],
[ 0,0,0,0,0,0,0,0,0,0,0,0,0]]
card = [suit, rank]
deck [suit][rank] = true
deck [suit][rank] = false
Upvotes: 0