-1

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 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

3 Comments

Nice, thanks! Is there a simple way of doing this without knowing the total number of shelves? So that I could basically use any input I wanted.
I know that I can do "rep(c(6, 4), times=20)" for example, but is there a way of making the input decide how many shelves there are. So I can have an undecided amount of shelves. (I hope it's understandable what I mean)
Sure, just wrap the code in a function with the number of books and shelves as inputs (assuming the shelf capacity follows a certain pattern, e.g., alternates between 4 and 6).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.