美文网首页
前端进阶|第十天 数组分组编程,区间还是连续大不同

前端进阶|第十天 数组分组编程,区间还是连续大不同

作者: 皮卡球ca | 来源:发表于2019-10-17 16:19 被阅读0次

    先看题面:

    随机生成一个长度为 10 的整数类型的数组,例如 [2, 10, 3, 4, 5, 11, 10, 11, 20],将其排列成一个新数组,要求新数组形式如下,例如 [[2, 3, 4, 5], [10, 11], [20]]。

    看完有点懵,根据他举的例子,数组被分为了三个子数组,但分类的依据却有两种理解,1.按照区间划分,即0-9,10-19,20-29等等,依此类推,以10为阶梯进行分组。2.按照连续区间划分,大小连续的分为一组。

    嗯,到底出题人咋想的,不得而知。so 管他呢,写就完了。

    我们先按照第一种理解:

          // IIFE 生成随机数组
            var arr = (function (len) {
                let temp = []
                for (var i = 0; i < len; i++) {
                    temp.push(Math.floor(Math.random() * 100));
                }
                return temp;
            })(10)
            console.log(arr);
    
            //1.排序 重写sort 排序
            arr.sort((a, b) => { return a - b })
            console.log(arr);
    
            //2去重 利用set不可重复性对数组进行去重
            arr = [...new Set(arr)]
            console.log(arr);
    
           //3.区间分组 利用map的key记录阶梯索引
            let map = new Map();
            arr.forEach((item) => {
                let key = Math.floor(item / 10)
                let temp=map[key];
                if(!temp)
                {
                    temp=[];
                }
                temp.push(item);
                map[key]=temp;
            })
    
            let arr1=[]
           
            for(var key in map)
            {
                arr1.push(map[key]);
            }
            console.log(arr1);
    

    如果是连续区间其实也可以利用我们已经排序的优势来实现。

           //4.连续分组 利用map的key记录分组索引
            let map2 = new Map();
            let index = 0
            arr.forEach((item) => {
    
                let temp = map2[index];
                if (!temp) {
                    temp = [];
                    temp.push(item);
                }
                else {
                    if (item - temp[temp.length - 1] == 1) {
                        temp.push(item);
                    }
                    else {
                        index++;
                        temp = []
                        temp.push(item);
                    }
                }
                map2[index] = temp;
            })
    
            let arr2 = []
    
            for (var key in map2) {
                arr2.push(map2[key]);
            }
            console.log(arr2);
    

    最终效果如图


    image.png

    以上写法使用的算法都比较传统,有网友提出用reduce函数进行处理,等我学会了再来写一稿。

    相关文章

      网友评论

          本文标题:前端进阶|第十天 数组分组编程,区间还是连续大不同

          本文链接:https://www.haomeiwen.com/subject/peafuctx.html