user2543622 user2543622 - 2 months ago 9
R Question

R solving hackerrank challenge

I would like to solve the challenge. The language of my preference is R. I am not sure how to receive input. On hackerrank coding window it says that

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

So far I am used to receiving input by using
v1 <- readline("Enter two integers: ")

How should i receive input on hackerrank? I tried to see solved examples but couldn't find any solved examples :(

--------------------------------------------------------------------



update 1

Below code works in R. Only problem is number of steps and ball values are not provided from keyboard input. We have to update them manually on line 1 and line2. How could I get update below solution so that it works on 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



Below code produces correct answer

# 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,)


I get below output

[1] 2.0
2


which is different from expected output which is below. How can i modify my code to get the correct format of output

2.0

Answer

Look at the "warmup".

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

Alternatively you can use

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