R solving hackerrank challenge

后端 未结 5 837
挽巷
挽巷 2020-12-31 18:55

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

\"# En         


        
相关标签:
5条回答
  • 2020-12-31 19:06
    #---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)
    
    0 讨论(0)
  • 2020-12-31 19:15

    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)
    
    0 讨论(0)
  • 2020-12-31 19:16

    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

    0 讨论(0)
  • 2020-12-31 19:19

    Another approach:

    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")
    
    0 讨论(0)
  • 2020-12-31 19:32

    A very handy one-liner to read in from standard input is the scan function, for instance:

    text <- scan(file = 'stdin', what = 'character', sep = '\r')
    
    0 讨论(0)
提交回复
热议问题