As a programmer, you use statistics and modeling (best case) or made-up assumptions based on your own subjective experience.
In your example the programmer would use the assumption (or the statistics) that most people who want to go down want to go down all the way to ground level or parking. Couple that with the assumption that people who want to enter an elevator on the 2nd floor (íf the building is a tall one) want to go up.
You would therefore not stop before going as far down as the lowest floor input by the people in the elevator.
Basically, the general answer is you use statistics of movements. Those differ between different buildings. If the building is new and there is no data yet you look at what is on the floor and try to make predictions about movements. Basically, you create a model of people's movements. Then you try to create an optimization function that minimizes waiting time, for example, or queue size, or energy consumption.
You may also take into account time of day. For example, in a business tower you may optimize for going up during the morning rush hour, and for going down in the late afternoon/early evening.
Modeling, simulation and statistics are key to finding good algorithms in such scenarios.
Add to that conditions. For example, you may set the condition to the optimization that nobody should wait for longer than 20 seconds, even if the overall efficiency would go down. For example, if all traffic is on the lower floors and there is a single person on on the 50th floor. It might be most efficient to ignore him/her for an hour, but that's not acceptable. Or an elevator that senses it is full may not stop except on the floor selected by people inside of it.
You can find courses on how to do modeling on the Internet, for example. on education sites such as edX. Here is an example (the course is closed but still accessible): "Mathematical Modeling Basics -- Use mathematics to create models to solve real-life problems."
Here is an example for a paper (of which there are many!) on how to model elevators: "Modeling Elevator System With Coloured Petri Nets" (PDF)
Just to show that this modeling approach is indeed actually used in practice, here is an example of a software (Oasys MassMotion) and how it could be used to model elevators: "Oasys Software Blog: Modelling Lifts"
That is the computer science graduate way of doing this. What works almost as well in practice and requires a lot less skills and knowledge is that you come up with whatever you feel like (making common sense assumptions) and if somebody (in charge) complains you adjust the algorithm :-)