Function or a loop for counting - R studio

72 Views Asked by At

I am practicing my R skills and I want to know if someone is skilled in functions or loops for counting. My idea is quite vague, but I can give an example.

For an example:

I have 4 book-shelves each above the other. The first (bottom) one can carry 6 books, the second shelf 4 books, the third shelf 6 books and the fourth shelf 4 books.

How can I make a function/loop where my input is a number of books I buy, and the output is how many shelves are full. I want the system to start at the bottom and work it's way up.

I have thought of finding the average number of books that can fit on the shelves, but if the input is 5 the program would think the first shelf is full when it isn't.

1

There are 1 best solutions below

3
dufei On

No need for a loop:

shelves <- c(6, 4, 6, 4)
n_books <- 15

# count number of filled shelves
sum(cumsum(shelves) < n_books)
#> [1] 2

Created on 2024-01-07 with reprex v2.0.2