Question Seeking Advice on Distributing Items Equally

Alex1009

New member
Joined
Oct 19, 2023
Messages
1
Programming Experience
Beginner
Hey everyone! I hope you're doing well. I'm still pretty new around here and not exactly a pro in the world of C#, but I love programming in my spare time. A few weeks back, I started with C# and now I'm working on this project for an app.

I'm tinkering with a program that evenly distributes different things (like 3 tomatoes, 4 bananas, and 6 apples) among a set number of bags (let's say 3 bags). The total count of each type of fruit and the overall count of items shouldn't differ by more than one, so it's as fair as possible for each bag.

Are the rounded numbers correctly stored in the 'results' array and the remainders, i.e., the decimal remainders, in the 'sumUp' array? Now, the only thing left is the distribution, but is this approach correct?"

C# Code link:

Or here:

C#:
using System;

public class HelloWorld
{
    public static void Main()
    {
        double[] objects = new double[]{4,4,2};
        Pack(objects, 3);
    }
 
    public static void Pack(double[] things, int numBags)
    {
        double[] results = new double[]{0,0,0};
        double[] sumUp = new double[]{0,0,0};
   
        for(int i = 0; i < things.Length; i++)
        {
            double current = things[i] / numBags;
            double nextnumber = (double)Math.Floor(current);
        
            results[i] = current;
        
            double part = current - nextnumber;
            sumUp[i] = part;
        
            Console.WriteLine(results[i] + "/" + Math.Floor(current) + "/" + part);
        }
    
        for(int b = 0; b < sumUp.Length; b++)
        {
            sumUp[b] = sumUp[b] * numBags;
            Console.WriteLine(sumUp[b]);
        }
    }
}
 
Last edited by a moderator:
All that can be done with integer math instead of floating point so that you don't have to deal with using Floor().

A better approach would look something like the following pseudo code:
C#:
currentBagIndex = 0
for each itemType in itemTypes
    quotient = itemType.Count / numberOfBags
    remainder = itemType.Count % numberOfBags
    for each bag
        add quotient items into bag
    while remainder > 0
        add one more item into bag[currentBagIndex]
        increment currentBagIndex
        currentBagIndex = currentBagIndex % numberOfBags
        decrement remainder

The % operator is the modulo operator.
 
Last edited:

Latest posts

Back
Top Bottom