8.6 知识测试:练习

  • 练习8-1

在掷骰子游戏中,玩家(射手)准备掷出两个骰子,每个骰子都有六个面。如果掷出的总数为2、3或12,则该射手失败。如果总数是7或11,则对手(他)胜出。如果是其他任何得分,那么此得分将变成新的目标,它将被称为“点”。使用以下辅助函数为掷骰子生成得分:

  1. two_d6 <- function(n)
  2. {
  3. random_numbers <- matrix(
  4. sample(6, 2 * n, replace = TRUE),
  5. nrow = 2
  6. )
  7. colSums(random_numbers)
  8. }

编写代码为掷骰子生成得分,并将以下值分配给game_statuspoint变量:

得分 游戏状态
2, 3, 11 FALSE NA
7, 11 TRUE NA
4, 5, 6, 8, 9, 10 NA 与得分相同

[10]

  • 练习8-2

如果射手没有马上赢或马上输,那么他必须不断地滚动骰子,直到他赢得得分点值取胜,或得分为7而失败为止。编写代码检查游戏状态是否为NA,如果是则反复生成掷骰子直到碰到点值为止(设置game_statusTRUE)或得分为7(设置game_statusFALSE)。[15]

  • 练习8-3

这是著名的sea shells绕口令:

  1. sea_shells <- c(
  2. "She", "sells", "sea", "shells", "by", "the", "seashore",
  3. "The", "shells", "she", "sells", "are", "surely", "seashells",
  4. "So", "if", "she", "sells", "shells", "on", "the", "seashore",
  5. "I'm", "sure", "she", "sells", "seashore", "shells"
  6. )

使用nchar函数来计算每个单词的字母数。现在,循环遍历所有可能的单词长度,找出所有与其长度相等的单词。例如,长度为6的单词应该有shell和surely,它们都有六个字母。[10]