【问题标题】:Create a functions, which creates a new array out of an existing one, which has less or equal amount of elements and no repeats创建一个函数,该函数从现有数组中创建一个新数组,该数组具有更少或相等数量的元素并且没有重复
【发布时间】:2020-07-24 08:14:32
【问题描述】:

我有一个这样的数组:

var arr = [0,1,2,3,4,5]

我需要编写一个函数,它将生成一个新的随机长度数组(但小于或等于 arr.length)并且不会生成重复的数字。比如:

var arrNew = [2,4,0]

但不是

var arrNew = [2,4,2,2,0]

我想出了这个,但它会产生重复的元素:

var list = [0,1,2,3,4,5];

var getRandomNumberRange = function (min, max) {
  return Math.floor(Math.random() * (max - min) + min);
};

var getRandomArr = function (list) {
  var arr = new Array(getRandomNumberRange(1, 6));
  for (var i = 0; i < arr.length; i++) {
    arr[i] = list[getRandomNumber(list.length)];
  }
  return arr;
};

感谢您的帮助!

【问题讨论】:

标签: javascript arrays


【解决方案1】:

注意:没有什么能阻止这段代码给你一个空数组作为你的随机数组。

var arr = [0,1,2,3,4,5, 36, 15, 25]

function generateRandomArrayFromSeed(arr) {
  // Create a new set to keep track of what values we've used
  const used = new Set();
  // generate a new array.
  const newArr = [];
  // what random length will we be using today?
  const newLength = getRandomNumber(arr.length);
  // while our new array is still less than our newly randomized length, we run this block of code
  while(newArr.length < newLength) {
    // first, we generate a random index
    const randomNumber = getRandomNumber(arr.length);
    // then we check if the value at this index is in our set; if it is, we continue to the next iteration of the loop, and none of the remaining code is ran.
    if(used.has(arr[randomNumber])) continue;
    // otherwise, push this new value to our array
    newArr.push(arr[randomNumber]);
    // and update our used set by adding our random number
    used.add(arr[randomNumber]);
  }
  // finally return this new random array.
  return newArr;
}

function getRandomNumber(limit = 10) {
  return Math.floor(Math.random() * limit);
}

console.log(generateRandomArrayFromSeed(arr));

【讨论】:

    【解决方案2】:

    将数据从数组数据结构移动到 Set 可以解决问题。
    集合不接受重复值。
    更多关于 Set in javascript,见 MDN here

    要将 Set 转换回数组,请使用 Array.from()

    【讨论】:

      【解决方案3】:

      为避免最终数组中出现重复,只需使用 Set 并使用 Array.from 将其转换回数组

      将结果保存在如下集合中:

      arr = Array.from(new Set(<result array>));
      

      【讨论】:

        猜你喜欢
        • 2018-12-19
        • 2021-10-16
        • 1970-01-01
        • 2020-12-23
        • 1970-01-01
        • 2021-10-16
        • 2021-03-09
        • 1970-01-01
        • 2013-03-23
        相关资源
        最近更新 更多