【问题标题】:How can I take values a user selects from a sample?如何获取用户从样本中选择的值?
【发布时间】:2021-03-22 22:43:02
【问题描述】:

我有一个由“Rolls

我想要做的是要求用户从样本中选择两个值,然后我希望将这两个值添加并存储在样本中。 (我不需要对加法中使用的值发生任何事情)

我的主要问题是我一直在使用:

"first_number

这并不能确保他们选择的值在我的样本中。

例如,假设我的示例是 4 5 6 6 2,而我当前使用的代码用户可以选择任何值,例如 1、0 甚至 200,即使这些都不是在给定的样本集中。如果我能解决这个问题,那么我接下来要做的事情就很简单了。

任何支持将不胜感激

【问题讨论】:

    标签: r sample dice


    【解决方案1】:

    大概是这样的:

    
    #Rolls <- c( 4,5,6,6,2 )
    
    set.seed(100)
    Rolls<-sample(1:6, 5, replace=TRUE)
    chosen <- c()
    ordinals <- c("first","second")
    
    while( length(chosen) < 2 ) {
    
        cat( "Dice = ",Rolls, "\n" )
    
        pick <- readline(
            prompt=paste("Please enter the", ordinals[length(chosen)+1],"value you'd like to add: ")
        )
    
        if( pick %in% Rolls ) {
            chosen <- append( chosen, as.numeric(pick) )
            Rolls <- Rolls[ -match( pick, Rolls ) ]
        } else {
            cat("Whoops, that's not a valid choice!\n")
        }
    
    }
    
    

    在我的会话中看起来像这样:

    
    Dice =  2 6 3 1 2 
    Please enter the first value you'd like to add: 4
    Whoops, that's not a valid choice!
    Dice =  2 6 3 1 2 
    Please enter the first value you'd like to add: 2
    Dice =  6 3 1 2 
    Please enter the second value you'd like to add: 5
    Whoops, that's not a valid choice!
    Dice =  6 3 1 2 
    Please enter the second value you'd like to add: 3
    
    

    【讨论】:

    • 谢谢,这看起来不错,唯一的问题是您的代码以将劳斯莱斯设置为一组特定数字(我给出的数字作为示例)开始,但是,在我的代码中,数字是由随机生成的“sample”函数,如果第一行改为“Rolls
    • 我问这个是因为这段代码是我为棋盘游戏制作的函数的一部分,所以会有很多卷和许多样本,所以像你一样定义卷(用非随机生成的数字)对我不起作用
    • 是的,将其替换为您的代码以执行滚动
    • np!我更新以反映这一点(应该首先完成)
    • 抱歉还有一件事,用户选择的值存储在哪里?我可以看到第一个存储在“pick”中,第二个存储在哪里?还是两者都存储在“pick”中?
    【解决方案2】:

    您需要自己控制该逻辑。试试这个功能:

    readline_int <- function(..., lo = -Inf, hi = Inf, maxtries = 10) {
      ans <- as.numeric(readline(...))
      while (maxtries > 0 && (anyNA(ans) || ans < lo || ans > hi)) {
        warning("value not within expected bounds: [", lo, ",", hi, "]")
        maxtries <- maxtries - 1
        ans <- as.numeric(readline(...))
      }
      ans
    }
    
    readline_int(prompt="Please enter the first value you'd like to add: ", lo=1, hi=6)
    # Please enter the first value you'd like to add: 9
    # Warning in readline_int(prompt = "Please enter the first value you'd like to add: ",  :
    #   value not within expected bounds: [1,6]
    # Please enter the first value you'd like to add: 5
    # [1] 5
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-18
      • 1970-01-01
      • 1970-01-01
      • 2017-05-01
      • 2016-02-14
      • 1970-01-01
      相关资源
      最近更新 更多