I want to creat an alogrithm in R using while and for such that, given a vector V and an integer M, sums the elements of the vector V until that sum exceeds M, and I want it to inform the value that exceeded M as well as how many repetitions it took in order to exceed such number (i.e., how many elements of the vector did it summed). I was thinking in something like this:
V <- 1:10
X <- 14
Sum <- 0
n <- 0
for (i in 1:length(V)){
while (Sum <= X){
Sum <- sum(V[1:i])
n <- n 1
}
}
print(Sum)
print(n)
But the loop doesn't load. Something's off. Hope the problem it's clear. Thanks!
CodePudding user response:
V <- 1:10
X <- 14
Sum <- 0
n <- 0
# For each i between 1 and 10
for (i in 1:length(V)){
# Sum is equal to the sum of the i first terms
Sum <- sum(V[1:i])
# I increment n by 1
n <- n 1
# if Sum is greater than X I get out of the for loop
if (Sum > X) {
break
}
}
print(Sum)
print(n)
V <- 1:10
X <- 14
Sum <- 0
n <- 1
# as long as Sum is smaller or equal than X
while (Sum <= X){
# Sum is the sum of the first n terms of V
Sum <- sum(V[1:n])
# I increment n by 1
n <- n 1
}
print(Sum)
print(n-1)