Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R solving hackerrank challenge

Tags:

r

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
like image 594
user2543622 Avatar asked Aug 18 '15 17:08

user2543622


2 Answers

Look at the "warmup".

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

Alternatively you can use

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

Also Refer this page in hackerrank

like image 197
scribbles Avatar answered Sep 19 '22 13:09

scribbles


I faced the similar issue for reading input in R in hackerrank . Then to use readLines i used following :

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

If u again want to read another data y use same approach :

y <- readLines(input, n=1)
like image 39
Vijay P R Avatar answered Sep 21 '22 13:09

Vijay P R