在不使用 while 和 Double For 循环的情况下在 R 中创建一副牌 [英] Creating A Deck Of Cards In R Without Using While And Double For Loop

查看:21
本文介绍了在不使用 while 和 Double For 循环的情况下在 R 中创建一副牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 R 中创建一个二十一点模拟器.下面的代码成功地创建了我想要的一副或多副牌.(对于那些玩的,我稍后会处理A的价值).

I am creating a blackjack simulator in R. The code below succeeds in creating the deck(s) of cards that I want. (For those that play, I will deal with the value of an Ace later).

我的问题是,有没有更好的方法来创建不涉及 while 循环和双 for 循环的牌组?我有更多关于双 for 循环的问题.while 循环可能不可避免,因为创建的套牌数量是可变的.

My question is, is there a better way to create the deck that doesn't involve a while loop plus a double for loop? I have more of an issue with the double for loop. The while loop is likely unavoidable since the number of decks created is variable.

我还初始化了一个空数据框,我知道这不是最佳做法,但是,在这种情况下,数据集太小,不会影响性能.

I also initialize an empty data frame which I know isn't the best practice, however, the data set is so small in this case that it won't effect performance.

最后,在 R 中是否有 i++ 的等价物?我也一直在用java编程并且已经习惯了.

And lastly, is there an equivalent of i++ in R? I have been programming in java as well and have gotten used to it.

谢谢.

createDeck <- function(totalNumOfDecks = 2)
{
  suits <- c("Diamonds", "Clubs", "Hearts", "Spades")
  cards <- c("Ace", "Deuce", "Three", "Four","Five", 
             "Six", "Seven", "Eight", "Nine", "Ten", 
             "Jack", "Queen", "King")
  values <- c(0,2,3,4,5,
              6,7,8,9,10,
              10,10,10)

  deck <- data.frame(Suit=character(0), Card=character(0), Value=numeric(0))

  numOfDecks = 1

  while (numOfDecks <= totalNumOfDecks){
    for (i in suits){
      for (j in cards){
        deck <- rbind.data.frame(deck, cbind.data.frame(j, i, values[match(j, cards)]))
      }
    }
    numOfDecks = numOfDecks + 1
  }

  print(deck)
}

推荐答案

expand.grid 函数应该有帮助:

# Define suits, cards, values
suits <- c("Diamonds", "Clubs", "Hearts", "Spades")
cards <- c("Ace", "Deuce", "Three", "Four","Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King")
values <- c(0, 2:9, rep(10, 4))
totalNumOfDecks <- 2

# Build deck, replicated proper number of times
deck <- expand.grid(cards=cards, suits=suits)
deck$value <- values
deck <- deck[rep(seq(nrow(deck)), totalNumOfDecks),]

expand.grid 的调用计算所有的牌和花色配对.value 变量是通过回收每个花色的 value 向量来创建的.最后,rep(seq(nrow(deck))) 将第 1-52 行重复适当的次数以获得您的套牌的多个副本.

The call to expand.grid computes all pairing of cards and suits. The value variable is created by recycling the value vector for each suit. Finally, rep(seq(nrow(deck))) repeats rows 1-52 the proper number of times to get multiple copies of your deck.

这篇关于在不使用 while 和 Double For 循环的情况下在 R 中创建一副牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆