R解决黑客挑战

时间:2015-08-18 17:33:19

标签: r

我想解决the challenge。我喜欢的语言是R.我不确定如何接收输入。在hackerrank编码窗口,它说

"# Enter your code here. Read input from STDIN. Print output to STDOUT"

到目前为止,我习惯使用

接收输入
v1 <- readline("Enter two integers: ")

我应该如何收到hackerrank的输入?我试图看到已解决的例子,但找不到任何已解决的例子。

更新1

下面的代码适用于R.唯一的问题是步数和键值输入不提供球值。我们必须在第1行和第2行手动更新它们。我怎样才能在解决方案下面获得更新,以便它可以在hackerrank上运行?

steps=4
ball_numbers=c(1,2,2,2)
d=as.data.frame(c(0,1))

    for (i in (1:(length(ball_numbers)-1)))
    {
      assign(x = paste("A", i, sep = ""),value = c(0,1))
      e <- as.data.frame(get(paste("A", i, sep = "")))
      colnames(e) <- paste("A", i, sep="")
      d <- merge(d,e)
}


d=as.matrix(t(d))
answer=sum(ball_numbers %*% d)/ncol(d)

UPDATE2

下面的代码会产生正确答案

# Enter your code here. Read input from STDIN. Print output to STDOUT
nums <- read.table("/dev/stdin", sep=" ");
nums <- as.matrix(as.data.frame(t(nums)))

steps=nums[1]
ball_numbers=nums[2:length(nums)]
d=as.data.frame(c(0,1))

for (i in (1:(length(ball_numbers)-1)))
{
    assign(paste("A", i, sep = ""),value = c(0,1))
    e <- as.data.frame(get(paste("A", i, sep = "")))
    colnames(e) <- paste("A", i, sep="")
    d <- merge(d,e)
}


d=as.matrix(t(d))
#answer=as.numeric(format(round(sum(ball_numbers %*% d)/ncol(d),1),nsmall=1))
answer = print(format(sum(ball_numbers %*% d)/ncol(d),nsmall=1, digits = 1), quote = F)
write.table(as.numeric(answer), sep = "", append=T, row.names = F, col.names = F,quote = FALSE,)

我得到以下输出

[1] 2.0
2

与下面的预期输出不同。如何修改我的代码以获得正确的输出格式

2.0

5 个答案:

答案 0 :(得分:13)

看看“热身”。

data <- suppressWarnings(read.table("stdin", sep=" "));

或者你可以使用

data <- suppressWarnings(readLines(file("stdin")))

Also Refer this page in hackerrank

答案 1 :(得分:6)

我在hackerrank中阅读R中的输入时遇到了类似的问题。然后使用我使用的readLines:

input<-file('stdin', 'r')
x <- readLines(input, n=1)

如果您再次想要阅读其他数据,请使用相同的方法:

y <- readLines(input, n=1)

答案 2 :(得分:1)

#---this solves the problem
# Enter your code here. Read input from STDIN. Print output to STDOUT
nums <- suppressWarnings(readLines(file("stdin")))
#nums <- suppressWarnings(readLines(file("new.txt")))
nums <- as.matrix(as.data.frame(t(nums)))
class(nums) <- "numeric"

steps=nums[1]
ball_numbers=nums[2:length(nums)]
d=as.data.frame(c(0,1))

for (i in (1:(length(ball_numbers)-1)))
{
  assign(paste("A", i, sep = ""),value = c(0,1))
  e <- as.data.frame(get(paste("A", i, sep = "")))
  colnames(e) <- paste("A", i, sep="")
  d <- merge(d,e)
}


d=as.matrix(t(d))
answer=sum(ball_numbers %*% d)/ncol(d)
write.table(cat(format(answer, nsmall=1), sep="\n"), sep = "", append=T, row.names = F, col.names = F)

答案 3 :(得分:0)

另一种方法:

con = file('stdin', open ='r')
input  = readLines(con)
z = c()
for(i in 2:length(input)){
  z = c(z, as.numeric(input[[i]]))
}

cat(format(round(sum(z)/2, 1), nsmall = 1), sep = "\n")

答案 4 :(得分:0)

从标准输入中读取的非常方便的单行代码是scan函数,例如:

text <- scan(file = 'stdin', what = 'character', sep = '\r')