while loop : total sum of numbers and total counts

I need 30 students to form a group to find out the best group size in their project work.
the principle forming a group is the last group size lower than by one, the number of groups = the total count
for example 30 students:
7+6+5+4+3+2+1 = 28, here the total number is not equal 30 , here, we ignore 2 students since 2 students are not sufficient to form a group.
The total number of groups is 7
how we can make this in a while loop, could you share your knowledge?
the result shows like this if students = 30
print(group_total)
[1] 36

print(group_size)
[1]
print(n_groups)
[1] 7

however, the result should look like this
print(group_total)
[1] 28

print(group_size)
[1] 7
[1] 6
[1] 5
[1] 4
[1] 3
[1] 2
[1] 1
print(n_groups)
[1] 7

students  <- as.integer(readline(prompt="Please Enter any integer number of students:  "))
group_size<- 0
n_groups <-0
group_total <- 0

while (group_size <= students) {
  group_total <- group_total + n_groups
  n_groups <- n_groups + 1
  group_size <- group_total + 1
  
  }

print(group_total)
print(group_size)

find_grps <- function(N) {
  which(cumsum(seq(1:N)) < N)
}
find_grps(30)
#> [1] 1 2 3 4 5 6 7

Thank you for your response, you get my idea, perfectly I can get my group_size and number of groups: my quesion is can I do this code in while loop?

find_grps <- function(N) {
  which(cumsum(seq(1:N)) <= N)
}

n_groups <- length(find_grps(2))
n_groups

#  n_groups <- length(find_grps(30))
# n_groups
#[1] 7
#find_grps <- function(N) {
#  which(cumsum(seq(1:N)) <= N)
# }
#n_groups<- length(find_grps(21))
# n_groups
#[1] 6

Good catch.

If only n_groups is of interest

find_num_grps <- function(N) {
  length(which(cumsum(seq(1:N)) <= N))
}
find_num_grps(30)
#> [1] 7
find_num_grps(21)
#> [1] 6

I have a bias against control structures, such as while because from a user-facing perspective R presents as a functional language—f(x)=y. It's almost always better to specify what is desired than how, if for no other reason than that it forces clarification of exactly the outcome being sought.

But, yes, these functions can be used in a loop, but what does that get you that this doesn't?

find_grps <- function(N) {
  which(cumsum(seq(1:N)) <= N)
}
find_grps(30)
#> [1] 1 2 3 4 5 6 7

This shows all the intermediate results that could be viewed in a control statement one at a time.

it is exactly meets the objective, how we can do is to see more options about problems, thank you so much

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.