将数组拆分为给定范围内的随机长度的块

时间:2019-02-27 15:51:25

标签: javascript arrays split

请在这里需要帮助。
所以我有以下数组:

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

我正在尝试将此数组拆分为长度在给定范围之间的块

const minChunkSize = 2;
const maxChunkSize = 5;

因此,块大小可以是minChunksizemaxChunkSize之间随机生成的任何值。

可能的输出:

[[1, 2, 3], [4, 5, 6, 7], [8, 9, 10]]
or
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
or
[[1, 2], [3, 4, 5, 6, 7], [8, 9, 10]]
or
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]

etc...

谢谢您的帮助!

3 个答案:

答案 0 :(得分:4)

这有点低效,但是您可以创建一种递归方法,以逐步 slice() 个元素的随机数(在某些$(document).ready(function(){ // https://www.npmjs.com/package/slick-carousel var $my_slider = $('#my_slider'); $my_slider.slick({ autoplay: true, infinite: true, autoplaySpeed: 0, speed: 5*1000, cssEase: 'linear', centerMode: true, slidesToShow: 3, dots: false, arrows: false, pauseOnHover: false, pauseOnFocus: false, }); $my_slider.on('beforeChange', function(e, slick, currentSlide, nextSlide) { var $slides_active = slick.$slides.filter('[aria-hidden="false"]'); var $slides_notActive = slick.$slides.filter('[aria-hidden="true"]'); $($slides_active).each(function(i, el){ $(this).addClass('_red'); var self = this; setTimeout(function(){ $(self).removeClass('_red'); }, 5000); }); }); EntityType之间)从数组。如果最终生成的结果具有长度小于最小长度的 some() 数组,则该方法将重新调用自身。

min
max

答案 1 :(得分:2)

即使这不是最有效的解决方案,您也可以尝试生成块,如果最后一项短于最小所需值,则可以尝试再次生成(递归),如下所示:

const generate = (input, min, max) => {
  const random = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
  
  const inner = arr => {
    if (arr.length === 0) return;
    
    const minIndex = arr.length < min ? arr.length : min;;
    const maxIndex = arr.length < max ? arr.length : max;
    
    const splitIndex = random(minIndex, maxIndex);
    
    const generatedArray = arr.slice(0, splitIndex);
    const remainingArray = arr.slice(splitIndex);
    
    if (remainingArray.length === 0) {
      return [generatedArray];
    } else {
      return [generatedArray].concat(inner(remainingArray));
    }
  };
  
  const result = inner(input);
  return result.every(item => item.length >= min) ? result : generate(input, min, max);
};

console.log(
  generate(
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    2,
    4,
  )
);

答案 2 :(得分:1)

递归函数将完成这项工作:

var N = 150;
var test = Array.apply(null, {length: N}).map(Number.call, Number);

console.log('inputArray', test);

var minChunkSize = 2;
var maxChunkSize = 5;

function chunk(inputArray, minChunkSize, maxChunkSize) {
  if(inputArray.length <= maxChunkSize) {
    return inputArray;
  }

  return inputArray.splice(0, Math.round(Math.random() * (maxChunkSize - minChunkSize)) + minChunkSize);
}

function chunkAll(inputArray, minChunkSize, maxChunkSize) {
  var ret = [];
  while(inputArray.length > maxChunkSize) {
    ret.push(chunk(inputArray, minChunkSize, maxChunkSize));
  }
  if(inputArray.length > 0) {
    ret.push(inputArray);
  }
  return ret;
}

console.log('chunked', chunkAll(test, minChunkSize, maxChunkSize));