10个苹果三个小朋友分怎么分 -- 数据分组,分页算法

这篇博客探讨了如何在程序开发中公平地将物品(如苹果)分配给多个组(如小朋友)。提供了两个方法,一个根据组的数量来平均分配,另一个确保每组至少达到指定数量。这两个C#方法分别用于解决不同场景下的分配问题,对于处理资源分配或任务分发等编程场景具有实际应用价值。

10个苹果三个小朋友分怎么分
这是一个经常遇到的问题
3,3,4或者
4,3,3

另外还有15个苹果,按照每个小朋友4个的方案往下分怎么分
4,4,4,3

这种问题在程序开发中也是经常遇到,因此总结了一个方法

//这是确定要分的组的数量,例如确定有多少个小朋友
public List<List<object>> ReOrganizeByGroupCount(List<Object> objects,int groupcount)
{
    List<List<object>> results = new List<List<object>>();
    
    if(groupcount <1)
        groupcount =1; 

    int countInEachGroup = (int)Math.Round((decimal)objects.Count / (decimal)groupcount);

    int counter = 0;
    while (objects.Count > 0)
    {
        if (counter < groupcount-1)
        {
            if (objects.Count > countInEachGroup)
            {
                counter++;
                List<object> subObjects = objects.Take<object>(countInEachGroup).ToList<object>();
                results.Add(subObjects);
                objects.RemoveRange(0, countInEachGroup);
            }
            else
            {
                //不足
                counter++;
                object[] array = new object[objects.Count];
                objects.CopyTo(array);
                results.Add(array.ToList<object>());
                objects.Clear();
            }
        }
        else
        {
            //多出
            counter++;
            object[] array = new object[objects.Count];
            objects.CopyTo(array);
            results.Add(array.ToList<object>());
            objects.Clear();
        }                
    }
    return results;
}

//这是确定每组最高的数量,例如确定每小朋友4个
public List<List<object>> ReOrganizeByCountInEachGroup(List<Object> objects, int countInEachGroup)
{
    List<List<object>> results = new List<List<object>>();

    if (countInEachGroup < 1)
    {
        results.Add(objects);
        return results;
    }

    int groupcount = (int)Math.Ceiling((decimal)objects.Count / (decimal)countInEachGroup);
    while (objects.Count > 0)
    {
        if (objects.Count > countInEachGroup)
        {
            //counter++;
            List<object> subObjects = objects.Take<object>(countInEachGroup).ToList<object>();
            results.Add(subObjects);
            objects.RemoveRange(0, countInEachGroup);
        }
        else
        {
            //counter++;
            object[] array = new object[objects.Count];
            objects.CopyTo(array);
            results.Add(array.ToList<object>());
            objects.Clear();
        }
    }

    return results;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值