R solving hackerrank challenge

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


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)

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

Tags:

R