Redistribute users over (chat)rooms I'm working on some kind of multiplayer game and for the best experience for the users I want to make sure the rooms are somewhat balanced at all time. By balancing I just mean the amount of users in the room (not score based or anything). I already figured out what the size of rooms should be and how many users there should be per room (based on a fixed maximum number of users per room). For a maximum of 4 users per room I came to the following distributions:

(total users) | (array of rooms (number is amount of users in room))
----------------------------------------------------------------------
4:              [4]
5:              [3, 2]
7:              [4, 3]
9:              [3, 3, 3]
13:             [4, 3, 3, 3]
...


I use the following code/algorithm to determine the distribution:

function calculateRoomDistribution(numUsers, maxUsersPerRoom) {
  const numRooms = Math.ceil(numUsers / maxUsersPerRoom)
  let distribution = []
  for (let i = 0; i &lt; numRooms; i++) {
    distribution[i] = 0
  }
  for (let i = 0; i &lt; numUsers; i++) {
    distribution[i % numRooms]++
  }
  return distribution
}


What I couldn't figure out however, is how to transition from one state to another. Let's say I have 13 users, divided over 5 rooms, respectively 4, 2, 2, 3, 2 users... I want to redistribute them into 4 rooms, with 4, 3, 3, 3 users. How would I approach such a problem? I was thinking of first removing the rooms that already have the right amount of users (4 and 3). That would leave me with [2, 2, 2]. But I noticed I would have to write a lot of edges and exceptions and I have a feeling there must be a smarter way. What type of algorithm am I looking for?
Here is one simple algorithm.  Pick one room that has too many people in it, and one room that has too few people in it, and move one person from the first room to the second room.  Repeat until convergence.