面试题——整理背包

    /// <summary>
    /// 背包整理是游戏中常用的逻辑,将玩家目前背包中的所有格子,按照ID排序统一摆放,同时每个格子中的道具数量不能超过20.
    /// 输入
    /// [[100,4], [101, 5], [0, 0], [100, 5], [101, 8]],20
    /// 输出
    /// [[100, 9],[101,13]]
    /// 注:空项清除
    /// </summary>
    /// <param name="vtBag">背包里项目编号以及个数,实质是二维数组</param>
    /// <param name="maxStack">每项最大个数</param>
    /// <returns></returns>
    public List<List<int>> TidyBag(List<List<int>> vtBag, int maxStack) {
        List<List<int>> bag = new List<List<int>>();//临时背包
        for (int i = 0; i < vtBag.Count; i++) {//遍历所有项
            if (vtBag[i][0] != 0) {//判断数量是否为0
                int index = HasItem(vtBag[i][0], bag);//判断包里是否有该编号的物品
                if (index == -1) {
                    bag.Add(vtBag[i]);
                } else {
                    bag[index][1] += vtBag[i][1];
                }
            }
        }
        bag.Sort((a, b) => { return a[0] > b[0] ? 1 : -1; });//对bag排序

        List<List<int>> lastBag = new List<List<int>>();
        foreach (List<int> item in bag) {//遍历临时包内每一项
            if (item[1] > maxStack) {//如果大于单项的阈值
                for (int i = 0; i < item[1] / maxStack; i++) {//满个数的
                    lastBag.Add(new List<int> { item[0], maxStack });
                }
                lastBag.Add(new List<int> { item[0], item[1] % maxStack });//多余的
            } else {
                lastBag.Add(item);
            }
        }
        return lastBag;
    }

    public int HasItem(int id, List<List<int>> bag) {//判断是否存在
        for (int i = 0; i < bag.Count; i++) {
            if (bag[i][0] == id) {
                return i;       //存在返回index
            }
        }
        return -1;      //返回-1则无此项
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值