【发布时间】:2018-12-24 12:22:06
【问题描述】:
这可能不是最有效的方法,但我在书的帮助下为水果机创建了一个代码(有效)(不确定我是否可以分享标题,但它是非常适合新手)。不过这段代码很简单,它运行一个函数,依次调用另外两个函数:
-
pull()通过从预先确定的向量中随机选择字符来模拟轮子机制。 -
prize()分析来自pull()的响应,以使用查找表为符号添加值。
代码有效,但我想对其进行修改,以便代码运行,直到达到三颗钻石的头奖; "DD"。我还希望它量化所有其他响应,直到它达到这个目标,所以我尝试了一个 while 循环,它似乎没有产生任何结果:
play2 <- function(){
response <- pull()
# I put the while loop straight after calling the first function,
# hoping that if the condition is not met, then the first function
# runs again, creating a new "response" until conditions are met.
while (sum(response == "DD") != 3) {
# I set the condition so that if the jackpot is not achieved, the
# while loop causes the other responses to be investigated. It
# it determines this by counting booleans.
# The following assignments are designed to begin the count for how
# many responses that are considered prizes occur, and how often no
# prize occurs.
cherry_prize <- 0
B_prize <- 0
BB_prize <- 0
BBB_prize <- 0
seven_prize <- 0
no_prize <- 0
if ("C" %in% response){
cherry_prize <- cherry_prize + 1
# A cherry prize occurs if any "C" is returned. The following
# statements will asses the other non-jackpot three of a kinds.
}
else if (sum(response == "B") != 3) {
B_prize <- B_prize + 1
}
else if (sum(response == "BB") != 3) {
BB_prize <- BB_prize + 1
}
else if (sum(response == "BBB") != 3) {
BBB_prize <- BBB_prize + 1
}
else if (sum(response == "7") != 3) {
seven_prize <- seven_prize + 1
}
else {
no_prize <- no_prize + 1
}
}
# After the jackpot is achieved, the number of other prizes (or lack
# thereof) that were returned are quantified, prior to the jackpot
# were won. The jackpot triplicate would then also be returned and
# quantified.
print(cherry_prize)
print(B_prize)
print(BB_prize)
print(BBB_prize)
print(seven_prize)
print(no_prize)
print(response)
# The last function quantifies the jackpot, once it has been reached.
prize(response)
}
希望我提供了足够的信息。非常感谢所有帮助,希望它可以帮助其他人。
【问题讨论】:
-
response在循环内部没有变化,所以循环只能是无限的(如果进入的话) -
您可能需要在
while循环内使用response <- pull()... -
首先,循环每次都将所有向量重置为零。为了防止这种情况,需要在“while”循环开始之前启动这些向量。其次,如果您希望将最终值作为输出,您需要使用像
return()这样的输出函数,或者只调用所需的向量列表来代替print()函数。最后,response变量需要在 while 循环内更改,正如 @Moody_Mudskipper 所指的那样
标签: r function if-statement while-loop boolean