Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
zeroone001 opened this issue May 5, 2019 · 200 comments

Comments

@zeroone001
Copy link

No description provided.

@swchenxixi
Copy link

我眉头一皱,又不会…………

@benzhemin
Copy link

benzhemin commented May 6, 2019

我起的早, 我先来吧

受思维惯性, 以为是求连续, 好吧, 修改了一波

function formArray(arr: any[]) {
  const sortedArr = Array.from(new Set(arr)).sort((a, b) => a - b);

  const map = new Map();

  sortedArr.forEach((v) => {
    const key = Math.floor(v / 10);
    const group = map.get(key) || [];
    group.push(v);

    map.set(key, group);
  });

  return [...map.values()];
}

// 求连续的版本
function formArray1(arr: any[]) {
  const sortedArr = Array.from(new Set(arr)).sort((a, b) => a - b);

  return sortedArr.reduce((acc, cur) => {
    const lastArr = acc.slice().pop() || [];

    const lastVal = lastArr.slice().pop();
    if (lastVal!=null && cur-lastVal === 1) {
      lastArr.push(cur);
    } else {
      acc.push([cur]);
    }

    return acc;
  }, []);
}

function genNumArray(num: number, base = 100) {
  return Array.from({length: num}, () => Math.floor(Math.random()*base));
}

const arr = genNumArray(10, 20); //[2, 10, 3, 4, 5, 11, 10, 11, 20];
const res = formArray(arr);

console.log(`res ${JSON.stringify(res)}`);

@ryanZiegler
Copy link

ryanZiegler commented May 6, 2019

区间分类

// 得到一个两数之间的随机整数,包括两个数在内
function getRandomIntInclusive(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值,含最小值 
}
// 随机生成10个整数数组, 排序, 去重
let initArr = Array.from({ length: 10 }, (v) => { return getRandomIntInclusive(0, 99) });
initArr.sort((a,b) => { return a - b });
initArr = [...(new Set(initArr))];

// 放入hash表
let obj = {};
initArr.map((i) => {
    const intNum = Math.floor(i/10);
    if (!obj[intNum]) obj[intNum] = [];
    obj[intNum].push(i);
})

// 输出结果
const resArr = [];
for(let i in obj) {
    resArr.push(obj[i]);
}
console.log(resArr);

@zhuzhh
Copy link

zhuzhh commented May 6, 2019

// 生产随机数
var arr = (function(len){
    var a = []
    for(var i = 0; i < len; i++) {
        a.push(Math.floor(Math.random() * 100))
    }
    return a
})(20)

// 排序
arr.sort(function(a, b) {
    return a - b
})
// 去重 (arr 转 set 然后 set 转 arr)
arr = [...(new Set([...arr]))]

var subArr = []

// 用 map 存储
var map = {}
arr.forEach(item => {
    var key = Math.floor(item / 10)
    if(!map[key]) {
        map[key] = []
    }
    map[key].push(item)
})

// map 转 数组
for(var key in map) {
    subArr.push(map[key])
}

console.log(JSON.stringify(subArr))

@douchaoyang
Copy link

douchaoyang commented May 6, 2019

// 随机生成一个长度为10的数组
function buildArr() {
	var _arr = [];
	for(var i=0; i<10; i++) {
		_arr.push(Math.floor(Math.random() * 20))
	}
	return _arr;
}

// 排序去重
function sortArr(a) {
	var _arr = [];
	for(var i=0; i<a.length; i++) {
		if(_arr.indexOf(a[i]) < 0) {
			_arr.push(a[i]);
		}
	}
	_arr.sort(function(item1, item2) {
		return item1 - item2;
	});
	return _arr;
}

// 整合
function intoArr(a) {
	if(a.length < 0)
		return [];
	var _arr = [];
	var _idx = 0;
	function p(item) {
		if(!_arr[_idx]) {
			_arr[_idx] = [];
		}
		_arr[_idx].push(item);
	}
	for(var i=0; i<a.length; i++) {
		if(i == 0 || a[i] - a[i-1] == 0 || a[i] - a[i-1] == 1) {
			p(a[i]);
		}
		else {
			_idx++;
			p(a[i]);
		}
	}
	return _arr;
}

var arr = buildArr(); // 生成长度为10的数组
console.log('生成数组', arr);
arr = sortArr(arr); // 排序去重
console.log('排序去重', arr);
arr = intoArr(arr); // 整合
console.log('整合数组', arr);

@sgzhm4444
Copy link

var arr = [2, 10, 3, 4, 5, 11, 10, 11, 20];
arr.sort(function(a, b) {
	return a - b
});
arr = [...new Set(arr)];
var result = [];
arr.forEach(function(val) {
	let index = parseInt(val / 10);
	if (!result[index]) {
		result[index] = [];
	}
	result[index].push(val);
})
result = result.filter(arr => arr.length > 0);
console.log(result);

@YouziXR
Copy link

YouziXR commented May 6, 2019

我发现楼上的朋友们和我想的不太一样啊,我理解的题目意思是把连续的元素组成一个数组,比如1,2,3,4组成一个数组,7,8,9,10组成一个数组,楼上的做法基本是把0-9,10-19这样的区间组成一个数组。姑且也贴一个我的理解的解法。

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

// 随机生成数组
const randomAry = (n = 10, range = { min: 1, max: 20 }) => {
  let ary = new Array(n).fill(0)
  ary = ary.map((val) => {
    val = Math.floor(Math.random() * (range.max - range.min + 1) + range.min)
    return val
  })
  console.log('random: ', ary)
  return ary
}
let ary = randomAry()
// 去重
ary = Array.from(new Set(ary))
// 排序
ary.sort((a, b) => a - b)
console.log('sorted: ', ary)
// 保存结果
let newAry = []
for (let i = 0; i < ary.length; i++) {
  let tmpAry = [ary[i]]
  // index用于跳过已经处理过的数组元素
  let index = ary.length
  for (let j = i + 1, count = 1; j < ary.length; j++, count++) {
    if (ary[i] + count === ary[j]) {
      tmpAry.push(ary[j])
    } else {
      index = j - 1
      break
    }
  }
  i = index
  // debugger
  newAry.push(tmpAry)
}
console.log('result', newAry)

@schaoss
Copy link

schaoss commented May 6, 2019

// 隨機生成 Array
function randomArray(length = 10, max = 100) {
  return Array.from({ length }, () => ~~(Math.random() * max))
}

// 10位分組
function newArray(array) {
  return array
    .reduce((acc, c) => {
      let i = ~~(c / 10)
      if (!acc[i]) acc[i] = []
      acc[i].push(c)
      return acc
    }, [])
    .filter(c => !!c)
    .map(arr => Array.from(new Set(arr)).sort())
}

// 連續數列分組
function continueArray(array) {
  return Array.from(new Set(array))
    .sort((a, b) => a - b)
    .reduce(
      (acc, c, i, arr) => {
        if (i === 0) acc[0].push(c)
        else {
          if (arr[i - 1] !== c - 1) acc.push([])
          acc[acc.length - 1].push(c)
        }
        return acc
      },
      [[]]
    )
}

let a = randomArray(10, 20)
newArray(a)
continueArray(a)

@swchenxixi
Copy link

我发现楼上的朋友们和我想的不太一样啊,我理解的题目意思是把连续的元素组成一个数组,比如1,2,3,4组成一个数组,7,8,9,10组成一个数组,楼上的做法基本是把0-9,10-19这样的区间组成一个数组。姑且也贴一个我的理解的解法。

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

// 随机生成数组
const randomAry = (n = 10, range = { min: 1, max: 20 }) => {
  let ary = new Array(n).fill(0)
  ary = ary.map((val) => {
    val = Math.floor(Math.random() * (range.max - range.min + 1) + range.min)
    return val
  })
  console.log('random: ', ary)
  return ary
}
let ary = randomAry()
// 去重
ary = Array.from(new Set(ary))
// 排序
ary.sort((a, b) => a - b)
console.log('sorted: ', ary)
// 保存结果
let newAry = []
for (let i = 0; i < ary.length; i++) {
  let tmpAry = [ary[i]]
  // index用于跳过已经处理过的数组元素
  let index = ary.length
  for (let j = i + 1, count = 1; j < ary.length; j++, count++) {
    if (ary[i] + count === ary[j]) {
      tmpAry.push(ary[j])
    } else {
      index = j - 1
      break
    }
  }
  i = index
  // debugger
  newAry.push(tmpAry)
}
console.log('result', newAry)

image
是的就是这个操作

@ryanZiegler
Copy link

连续元素分类

// 得到一个两数之间的随机整数,包括两个数在内
function getRandomIntInclusive(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值,含最小值 
}
// 随机生成10个整数数组, 排序, 去重
let initArr = Array.from({ length: 10 }, (v) => { return getRandomIntInclusive(0, 99) });
initArr.sort((a, b) => { return a - b });
initArr = [...(new Set(initArr))];

// 连续元素分类放入数组
let continueArr = [], tempArr = [];
initArr.map((e, index) => {
    tempArr.push(e);
    if (initArr[index+1] !== ++e) {
        continueArr.push(tempArr);
        tempArr = [];
    }
});
console.log(continueArr);

@FounderIsShadowWalker
Copy link

function Test(){

let a = Array.from(new Set(new Array(10).fill(1).map(_ => Math.ceil(Math.random() * 10)))).sort((a, b) => a - b);

let result = [[a[0]]];

if(a.length === 1){
return result;

}

a.reduce((prev, next) => {

if(next - prev === 1){

result[result.length - 1].push(next);

}else{

result.push([next]);
}

return next;

})
return result;

}

@TheCrookedMan
Copy link

[...new Set([...Array(10)].map(x = >parseInt(Math.random() * 10)))].sort((x, y) = >x - y).reduce(function(acc, cur, index, source) {
if (cur - acc[acc.length - 1] !== 1 && acc.length > 0) {
acc.push('-')
}
acc.push(cur) return acc
},
[]).toString().replace(/,/g, '').split('-').map((x) = >[x.split('')])

@yygmind yygmind mentioned this issue May 6, 2019
@JonathonChen
Copy link

去重后还要保证数组的长度是不是10...

@GuoYuFu123
Copy link

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

@methods思路: 10以下为一组 10以上1开头为一组,2一组,依次。。。
*/
   function create() {
        let arr = [];
        for(let i = 0; i< 10; i++) {
            arr.push(Math.floor(Math.random() * 100))
        }        
        arr = [...new Set(arr)]
        arr = arr.sort(function(a,b){return a-b})
        return arr;
   }    
   function sort(arr) {
    let newArr = [];
    let dict = {};
    let length = 0;
    let keyArr = [];
    arr.forEach((ele) => {
        let key = Math.floor(ele/10)
        keyArr = [];
        for(let i in dict) {
            keyArr.push(i * 1)
        }   
        if(keyArr.indexOf(key) > -1) {            
            newArr[dict[key]].push(ele)
        } else {            
            newArr[length] = [ele]
            dict[key] = length
            length ++;
        }
    })
    return newArr;
   }
   function transform() {
        let arr = create();
        let sortArr = sort(arr)
        return sortArr;
   }
   console.log(transform())

@Nolaaaaa
Copy link

Nolaaaaa commented May 6, 2019

// 随机生成长度为 10 的整数
let arr = function randomArray() {
  let arr = []
  for(let i = 0; i < 10; i++) {
    arr.push(Math.floor(Math.random() * 100))
  }
  return arr
}()

// 排序
arr.sort((a,b) => a-b )

// 去重
arr = [...new Set(arr)]

// 连续值存一个数组,不连续的单独存一个数组
let resultArr = [],  newArr = [arr[0]],  index = 0                  
for(let i = 1; i < arr.length; i++) {
  if(arr[i] == arr[i -1] + 1) {
    newArr.push(arr[i])
  } else {
    resultArr.push(newArr)
    newArr = [arr[i]]
    index++
  }
}

console.log(arr)           // [36, 37, 44, 50, 57, 61, 62, 78, 79]
console.log(resultArr)     // [[36, 37], [44], [50], [57], [61, 62]]

代码测试地址

@XianHuiDeDiZhongHai
Copy link

XianHuiDeDiZhongHai commented May 7, 2019

let arr = [20, 10, 11, 10, 2, 3, 1, 1];
        console.log(
            Object.values(
                [...new Set(arr)].sort((a, b) => a - b).reduce((obj, val) => {
                    let key = parseInt(val / 10);
                    Array.isArray(obj[key]) ? obj[key].push(val) : obj[key] = [val]
                    return obj
                }, {})
            )
        )    //[[1,2,3],[10,11],[20]]

菜鸟见解,轻喷

@fuqianxi
Copy link

fuqianxi commented May 7, 2019

const randomArr = [];
while (randomArr.length<10) {
let num = parseInt(Math.random()*100);
if(randomArr.indexOf(num)==-1){
randomArr.push(num)
}
}
const sortArr = randomArr.sort((a,b)=>a-b);
//生成数组
console.log(sortArr)
const obj = {};
sortArr.forEach(el=>{
let cur = el+'';
if(cur.length==1){
if(!obj[0]){
obj[0] = [];
}
obj[0].push(el)
}else{
if(!obj[cur[0]]){
obj[cur[0]] = []
}
obj[cur[0]].push(el)
}
})
console.log(obj)
const arr = [];
for (const k in obj) {
arr.push(obj[k])
};
//输出结果
console.log(arr)

@Ray-56
Copy link

Ray-56 commented May 7, 2019

function randomNumber(len) {
    const max = 20;
    const arr = [];
    for (let i = 0; i < len; i++) {
        arr.push(Math.floor(Math.random() * max));
    }

    const sorted = [...new Set(arr)].sort((a, b) => a - b); // 去重排序
    return sorted;
}

function sort(arr) {
    let dict = {};
    let length = 0;
    arr.forEach(i => {
        let key = Math.floor(i / 10);
        if (Reflect.has(dict, key)) {
            dict[key].push(i);
        } else {
            dict[key] = [i];
            length++;
        }
    });
    dict.length = length;
    return Array.from(dict);
}

const res = randomNumber(10);
console.log(sort(res));

@susiwen8
Copy link

susiwen8 commented May 7, 2019

function test(len, range) {
    let test = [];

    for (let i = 0; i < len; i++) {
      test.push(Math.round(Math.random() * range));
    }

    test =  Array.from(new Set(test)).sort((a, b) => a - b);

    let arr1 = [];

    for (let i = 0, len = parseInt(Math.max(...test) / 10) + 1; i < len; i++) {
      arr1.push([]);
    }

    test = test.map(item => {
      const section = parseInt(item / 10);
      arr1[section].push(item);
    })

    console.log(arr1);
  }


test(10, 20);

@Forx-Js
Copy link

Forx-Js commented May 7, 2019

const arr = Array.from({
        length: 10
      }, () => ~~(Math.random() * 50)) //创建数据
      .sort((a, b) => a - b), //排序
      arr1 = [...new Set(arr.map(i => ~~(i / 10)))] //划分区域
      .map(i => arr.filter(a => ~~(a / 10) === i)) //数据划分

@zengfan0605
Copy link

// 生成随机数组
function createNum() {
var arr = []
for(var i =0; i<10; i++) {
var num = Math.floor(Math.random()*100)
arr .indexOf(num)!=-1?i--:arr .push(num)
}
arr.sort((a,b) => { return a-b } )
return arr
}

// 生成map
function createMap () {
var map = {}
createNum().forEach(item => {
if(map[Math.floor(item/10)]) {
map[Math.floor(item/10)].push(item)
} else {
map[Math.floor(item/10)] = [item]
}
})
return map
}

// 结果
var numMap = createMap()
var newArr = []
for(var o in numMap ) {
newArr.push(numMap [o])
}

@wubetter
Copy link

wubetter commented May 7, 2019

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

理解:把连续的数字从小到大放到一个数组中
*/
//生成随机数
let arr = Array.from({length:10},()=>~~(Math.random()*20));
//[2, 10, 3, 4, 5, 11, 10, 11, 20]
[...new Set(arr)].sort((a,b)=>a-b).reduce((a,b)=>{
  var l= a.slice(-1)[0]; 
  l&& l.slice(-1)[0] + 1 == b ? l.push(b) : a.push([b]);
  return a;
},[]) // [[2,3,4,5],[10,11],[20]]

@arronf2e
Copy link

arronf2e commented May 7, 2019

比较通俗的解法~

function createRandomArray(length = 10) {
    var arr = [];
    for(var i = 0; i < length; i++) {
        arr.push(parseInt(Math.random() * 100))
    }
    return arr;
}

function sort(arr) {
    return arr.sort((a, b) => a - b)
}

function part(arr) {
    var length = arr.length;
    var map = {};
    for(var i = 0; i < length; i++) {
        var tp = parseInt(arr[i]/10);
        if(map[tp]) {
            map[tp].push(arr[i])
        }else {
            var value = [];
            map[tp] = [...value, arr[i]]
        }
    }
    return map
}

function genArray(map) {
    var arr = []
    for(var key in map) {
        arr.push(map[key])
    }
    return arr;
}

var randomArray = createRandomArray();
var sortedRandomArray = sort(randomArray);
var partMap = part(sortedRandomArray);
var result = genArray(partMap);
console.log(result);

@master-kolan
Copy link

  let arr = [2, 10, 3, 4, 5, 11, 10, 11, 20];

  arr = Array.from(new Set(arr)).sort((a, b) => a - b);

  let start = 0;
  for(let i = 0; i < arr.length - 1; i ++){
    if (arr[i + 1] - arr[i] > 1) {
      console.log(arr.slice(start,i + 1));
      start = i + 1;
    }
  }
  console.log(arr.slice(start,arr.length));

以为求连续 + 1

@XianHuiDeDiZhongHai
Copy link

const arr = Array.from({
        length: 10
      }, () => ~~(Math.random() * 50)) //创建数据
      .sort((a, b) => a - b), //排序
      arr1 = [...new Set(arr.map(i => ~~(i / 10)))] //划分区域
      .map(i => arr.filter(a => ~~(a / 10) === i)) //数据划分

arr没有去重

@Vera1128
Copy link

// 随机生成长度为 10 的整数
let arr = function randomArray() {
  let arr = []
  for(let i = 0; i < 10; i++) {
    arr.push(Math.floor(Math.random() * 100))
  }
  return arr
}()

// 排序
arr.sort((a,b) => a-b )

// 去重
arr = [...new Set(arr)]

// 连续值存一个数组,不连续的单独存一个数组
let resultArr = [],  newArr = [arr[0]],  index = 0                  
for(let i = 1; i < arr.length; i++) {
  if(arr[i] == arr[i -1] + 1) {
    newArr.push(arr[i])
  } else {
    resultArr.push(newArr)
    newArr = [arr[i]]
    index++
  }
}

console.log(arr)           // [36, 37, 44, 50, 57, 61, 62, 78, 79]
console.log(resultArr)     // [[36, 37], [44], [50], [57], [61, 62]]

代码测试地址

你这个数组最后一个值是没有放到结果数组里面去的?

@ouxuwen
Copy link

ouxuwen commented May 10, 2019

// 生成随机数组
const randomArr = (n = 10, range = { min: 1, max: 20 }) => {
  let arr = new Array(n).fill(0);
  arr = arr.map(val => {
    val = Math.floor(Math.random() * (range.max - range.min) + range.min);
    return val;
  });
  return arr;
};

let arr = randomArr();

// 数组去重
arr = Array.from(new Set(arr));
// 数组排序
arr = arr.sort((a, b) => a - b);
console.log(arr);

let newArr = [[arr[0]]];
let k = 0; // 已经标记已经计算过的子组
for (let i = 1, l = arr.length; i < l; i++) {
  for (let j = k; j < newArr.length; j++) {
    let len = newArr[j].length;
    if (arr[i] === newArr[j][len - 1] + 1) {
      // 如果与子组的最后一位相邻,就压入
      newArr[j].push(arr[i]);
    } else {
      // 如果与子组的最后一位不相邻,就压入新子组
      newArr.push([arr[i]]);
      // 已经标记已经计算过的子组
      k++;
      break;
    }
  }
}
console.log(newArr);
``

@LiuMengzhou
Copy link

/**
 * 返回 min 到 max 之间的随机整数,包括 min 和 max
 */
function getRandomInt(min, max) {
  const MIN = Math.ceil(min);
  const MAX = Math.floor(max);
  return Math.floor(Math.random() * (MAX - MIN + 1)) + MIN;
}

/**
 * 返回指定长度的数组,数组元素为[0, 99]的随机整数
 */
function getRandomArray(length) {
  return Array.from({ length }, item => getRandomInt(0, 99));
}

/**
 * 返回处理后的数组,包括排序、去重和分类
 */
function getProcessedArray(array) {
  const sortedArray = [...array].sort((a, b) => a - b);
  const uniqueSortedArray = [...(new Set(sortedArray))];
  const hash = {};
  let result = [];
  uniqueSortedArray.forEach((val, i) => {
    const key = Math.floor(val / 10);
    if (!hash[key]) {
      hash[key] = [uniqueSortedArray[i]];
    }
    else {
      hash[key].push(uniqueSortedArray[i]);
    }
  })
  for (let key in hash) {
    result.push(hash[key]);
  }
  return result;
}

// 测试
const array = getRandomArray(10);
console.log(array);
console.log(getProcessedArray(array)); // 纯函数
console.log(array); // 不改变原数组

@IWANABETHATGUY
Copy link
Contributor

既然用到了sort就不用set去重了,双reduce搞定

const arrange = arr => {
  return arr
    .sort((a, b) => a - b)
    .reduce(
      (acc, cur) => (acc[acc.length - 1] === cur ? acc : acc.concat([cur])),
      [],
    )
    .reduce(
      (acc, cur) => {
        return ~~(acc[acc.length - 1][0] / 10) === ~~(cur / 10)
          ? (acc[acc.length - 1].push(cur), acc)
          : (acc.push([cur]), acc);
      },
      [[]],
    );
};

@ItachLuo
Copy link

function swift(arr) {
const o = {};
arr.forEach((item) => {
const order = (item / 10) | 0;
if (o[order]) o[order].push(item);
else o[order] = [item];
});
return Object.values(o);
}

@catbea
Copy link

catbea commented Nov 18, 2022 via email

@Vera1128
Copy link

Vera1128 commented Nov 18, 2022 via email

@benzhemin
Copy link

benzhemin commented Feb 19, 2023

const categoriezSequenceList = (numberList) => {
    const sortedList = Array.from(new Set(numberList)).sort((a, b) => a-b);

    const result = [];
    const end = sortedList.length;

    for (let i=0; i<end; i++) {
        const sequenceList = [sortedList[i]];

        for (let j=i+1; j<end && sortedList[j] - sortedList[i] === 1; j++) {
            sequenceList.push(sortedList[j]);
            i = j;
        }

        result.push(sequenceList);
    }

    return result;
}

const generateArray = (length, cap) => {
    return Array.from({length}).map(() => Math.floor(Math.random()*cap))
}

const inputList = [2, 10, 3, 4, 5, 11, 10, 11, 20];

const resultList = categoriezSequenceList(inputList);
console.log((resultList));

@catbea
Copy link

catbea commented Apr 7, 2023 via email

@Vera1128
Copy link

Vera1128 commented Apr 7, 2023 via email

@pxd112421
Copy link

const arr = [2, 10, 3, 4, 5, 11, 10, 11, 20, 1, 33, 31]
        const fn = (numArr, pre) => {
            const newNumArr = [...new Set(numArr)].sort((a, b) => a-b)
            let res = []
            const maxNum = Math.max(...newNumArr)
            const length = Math.round(maxNum / pre) + 1
            for(let i = 0; i < length; i++){
                const newArr = newNumArr.filter(item => item < pre*(i+1) && item >= pre*i)
                res.push(newArr)    
            }
            return res
        }
        const result =  fn(arr, 10)
        console.log("result", result)

@GpingFeng
Copy link

// [2, 10, 3, 4, 5, 11, 10, 11, 20] => [[2, 3, 4, 5], [10, 11], [20]]
let a = [2, 10, 3, 4, 5, 11, 10, 11, 20];
let res = [];
[...new Set(a)].sort().forEach(item => {
  let index = Math.floor(item/10);
  if (!res[index]) {
    res[index] = [item];
  } else {
    res[index].push(item);
  }
})

console.log(res);

@Vera1128
Copy link

Vera1128 commented May 10, 2023 via email

@catbea
Copy link

catbea commented May 10, 2023 via email

@XW666
Copy link

XW666 commented May 18, 2023

const getRandomIntInclusive = (arr) => {
    let map = {}
    for (let c of arr) {
      let m = Math.floor(c / 10);
      if (map[m]) map[m].push(c)
      else map[m] = [c]
    }

    let lis = Object.values(map)
    console.log('jj', lis)
  }
  getRandomIntInclusive([2, 10, 3, 4, 5, 11, 10, 11, 20])

@qifengla
Copy link

qifengla commented May 30, 2023

let arr1 = Array.from({length: 10}).map(() => Math.floor(Math.random() * 100));


arr1.sort((a, b) => a-b);
arr1 = [...(new Set(arr1))];
let res1 = [[arr1[0]]];
for (let i=1; i<arr1.length; i++) {
	if (arr1[i] === res1[res1.length-1][res1[res1.length - 1].length - 1] + 1) {
		res1[res1.length - 1].push(arr1[i])
	}
	else {
		res1.push([arr1[i]])
	}  
} 

console.log(res1)

@hanzehua666
Copy link

// 随机生成一个长度为length的整数数组,随机数范围为min ~ max
const randomFn = (length, min, max) => {
  return Array.from({ length }, v => Math.floor(Math.random() * (max - min + 1) + min));
};
const randomArr = randomFn(10, 1, 20);

// 去重并排序
const setSortArr = [...new Set(randomArr)].sort((a, b) => a - b);

// 分组处理(相邻连续数字为一组,不连续的数字单独为一组)
const resultFn = arr => {
  let current = [];
  const result = [];
  for (let i = 0; i < arr.length; i++) {
    current.push(arr[i]);
    if (arr[i] + 1 !== arr[i + 1]) {
      result.push(current);
      current = [];
    }
  }
  return result;
};

console.log(randomArr, 'randomArr>>>'); // [2, 10, 3, 4, 5, 11, 10, 11, 20]
console.log(setSortArr, 'setSortArr>>'); // [2, 3, 4, 5, 10, 11, 20]
console.log(resultFn(setSortArr), 'resultFn>>'); // [[2, 3, 4, 5], [10, 11], [20]]

@88wixi
Copy link

88wixi commented Jul 20, 2023

function randomMath(n) {
let arr = []
for (let i = 0; i < n; i++) {
arr.push(Math.floor(Math.random() * 100)); // 生成0到99之间的随机整数
}
return arr
}
arr = randomMath(10)
console.log(arr);
arr.sort((a, b) => a - b)
let newarr = Array.from(new Set(arr))
console.log(newarr)
let endarr = []
function wx(newarr) {
for (i = 0; i < newarr.length - 1; i++) {
if (newarr[i] !== newarr[i + 1] - 1) {
endarr.push(newarr.splice(0, i + 1))
return wx(newarr)
}
}
if (newarr.length == 1) {
endarr.push(newarr)
}
return newarr
}
wx(newarr)
console.log(endarr)

@catbea
Copy link

catbea commented Jul 20, 2023 via email

@Vera1128
Copy link

Vera1128 commented Jul 20, 2023 via email

@zz201276
Copy link

function srotArr(arr){
    let arr3 = [];
    Array.from(new Set(arr)).sort((a,b)=>{
        return a-b
    }).forEach(item =>{
        if(!(arr3[parseInt(item/10,10)] instanceof Array))arr3[parseInt(item/10,10)] = []
            arr3[parseInt(item/10,10)].push(item)
    })
    let arr4 = arr3.filter(item=>{
        return item.length >0
    })
    return arr4
}

闲的发慌

@Vera1128
Copy link

Vera1128 commented Oct 12, 2023 via email

@adele-ty
Copy link

adele-ty commented Dec 2, 2023

const arr = [2, 10, 3, 4, 5, 11, 10, 11, 20];
      const res = [];
      for (let item of arr) {
        const index = Math.floor(item / 10);
        if (!res[index]) {
          res[index] = [];
        } else {
          if (res[index].includes(item)) continue;
        }
        res[index].push(item);
      }
      console.log(res);

@catbea
Copy link

catbea commented Dec 2, 2023 via email

@hicoldcat
Copy link

// 生成随机数
var genRandomNum = (min,max) => Math.floor(Math.random() * (max - min + 1)) + min; 

// 生成数组
function genArray(size,min,max){
  //去重
  var array = new Set();
 
  // 生成指定长度数组
  while(array.size < size){
    array.add(genRandomNum(min,max))
  }

  // 排序
  array = Array.from(array).sort((a,b) => (a-b));
  
  // 构建hash
  var map = new Map();
  
  // 放入hash
  array.forEach(v => {
    let index = Math.floor(v / 10);
    if(map.has(index)){
      map.set(index, map.get(index).concat(v));
    }else{
      map.set(index, [v]);
    }
  })

  // 输出结果
  return Array.from(map.values())
}

@Vera1128
Copy link

Vera1128 commented Apr 17, 2024 via email

@catbea
Copy link

catbea commented Apr 17, 2024 via email

@QueueingHater
Copy link

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

const generateRandomInteger = (min, max) => {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

const generateIntegerArray = (min, max, len) => {
    return Array.from(new Array(len), x => generateRandomInteger(min, max))
}

const transformTo2DArray = (arr) => {
    console.log(arr);
    arr.sort((a,b) => a - b);
    
    const result = [];
    const obj = {};

    arr.map((i) => {
        const intNum = Math.floor( i / 10);
        if(!obj[intNum]) obj[intNum] = [];
        obj[intNum].push(i);
    });

    for(let key in obj) {
        result.push(obj[key])
    }

    console.log(result);
}

transformTo2DArray(generateIntegerArray(0, 100, 20))

@catbea
Copy link

catbea commented Jun 15, 2024 via email

@wubing0324
Copy link

let arr = [2, 10, 3, 4, 5, 11, 10, 11, 20]
arr = Array.from(new Set(arr))
arr.sort((a,b) => a - b)
let index = 0
let lenth = arr.length
let ret = [[]]
while(index < lenth) {
    let lastLen = ret.length - 1
    if (index === 0) {
        ret[lastLen].push(arr[index])
        index++
        continue
    }
    if (arr[index] - arr[index - 1] === 1) {
        ret[lastLen].push(arr[index])
    } else {
        ret.push([])
        lastLen = ret.length - 1
        ret[lastLen].push(arr[index])
    }
    index++
}

@moshang-ax
Copy link

function randomArray() {
  let arr = [];
  for (let i = 0; i < 10; i++) {
    let t = Math.floor(Math.random() * 100);
    let index = Math.floor(t / 10);
    if (!arr[index]) {
      arr[index] = [];
    }
    arr[index].push(t);
  }
  return arr.filter(Boolean);
}

@catbea
Copy link

catbea commented Sep 23, 2024 via email

@Vera1128
Copy link

Vera1128 commented Sep 23, 2024 via email

@brother-forteen
Copy link

brother-forteen commented Sep 23, 2024 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests