Search code examples
rtriplet

R: Count triplets with sum smaller than a given value


I've been able to find multiple solutions to this problem on other languages but can not seem to get it right in R. Here's what I have so far:

Given an array (-2, 0, 1, 3) find the count of triplets less than the sum variable given.

sum = 2
ar<-c(-2, 0, 1, 3);ar

sumtrip<- function (vec,n,sum) {
  ctr=0
  for (i in 1:n-2){
    for (j in i+1:n-1){
      for (k in j+1:n){
        if ((vec[i]+vec[j]+vec[k]) < sum){
          ctr=ctr+1
        }
      }
    }
  }
return(ctr)
}

sumtrip(ar,length(ar),sum)

This results in: Error in vec[i] + vec[j] : non-numeric argument to binary operator


Solution

  • You just have bad punctuation. This should do what you want. Please compare your parentheses with mine.

    sum = 2
    ar<-c(-2, 0, 1, 3);ar
    
    sumtrip<- function (vec,n,sum) {
      ctr=0
      for (i in 1:(n-2)){
        for (j in (i+1):(n-1)){
          for (k in (j+1):n){
            if ((vec[i]+vec[j]+vec[k]) < sum){
              ctr=ctr+1
            }
          }
        }
      }
    return(ctr)
    }
    
    sumtrip(ar,length(ar),sum)