【问题标题】:Substitute random items in a Javascript array替换 Javascript 数组中的随机项
【发布时间】:2020-08-15 09:43:42
【问题描述】:

在 Javascript 中,我尝试用不同的项目(所有相同类型)随机替换数组中的一半(在本例中为 6 个项目中的 3 个),并且我需要保留原始项目的位置.例如,如果我有:

var my_array = [a, b, c, d, e, f]

我想选择三个随机的替换为 0,而其他的则保持其初始位置。因此,假设 a、c 和 d 是随机选择器将在一个实例上消失的那些,那么我的数组将变为:

my_array = [0, b, 0, 0, e, f]

在不同的运行中,随机选择器可能会选择 b、c 和 f,所以我会有:

my_array = [a, 0, 0, d, e, 0]

等等。 非常感谢您的帮助!

【问题讨论】:

  • 什么不起作用?
  • @NinaScholz 我刚接触 JavaScript,不知道从哪里开始!到目前为止,我一直在使用 shuffle 函数,然后选择前三个项目以获得随机选择,但这并不能保持原来的位置

标签: javascript arrays random replace substitution


【解决方案1】:

您可以对数组进行闭包并希望计数为零,并返回一个生成随机整数并用零或值映射数组的函数。

function getRandom(array, count) {
    return function () {
        const indices = new Set();
        do {
            indices.add(Math.floor(Math.random() * array.length));
        } while (indices.size < count)
        return array.map((v, i) => indices.has(i) ? 0 : v);
    };
}

var myArray = ['a', 'b', 'c', 'd', 'e', 'f'],
    getArrayWithZeros = getRandom(myArray, 3);


console.log(...getArrayWithZeros());
console.log(...getArrayWithZeros());
console.log(...getArrayWithZeros());
console.log(...getArrayWithZeros());
console.log(...getArrayWithZeros());

【讨论】:

    【解决方案2】:

    另一种选择

    const myArray = ['a', 'b', 'c', 'd', 'e', 'f'];
    
    // Randomizer function
    const rand = ([...arr], len, rep) => {
      let ins = {};
      while(Object.keys(ins).length < len) {
        let r = ~~(Math.random() * arr.length);
        if(!ins[r]) ins[r] = true;
      }
      for(let i = 0; i < arr.length; i++) if(ins[i]) arr[i] = rep;
      return arr;
    }
    
    // Array, number of elements to replace, replace with
    // Here we transform toString for better readability
    console.log(rand(myArray, 3, 0).toString());
    console.log(rand(myArray, 3, 0).toString());
    console.log(rand(myArray, 3, 0).toString());
    console.log(rand(myArray, 3, 0).toString());
    console.log(rand(myArray, 3, 0).toString());

    【讨论】:

      【解决方案3】:

      你需要计算array的一半length,生成这个数量的随机indexes,然后改变它们:

      var my_array = ['a', 'b', 'c', 'd', 'e', 'f'];
      function alterHalfWithZero(arr){
           let my_array = [...arr];
           let indexList = {};
           let len = Math.floor(my_array.length / 2)
           while(Object.values(indexList).length != len){
                let random_index = Math.floor(Math.random() * my_array.length);
                indexList[random_index] = random_index;
           }
           indexList = Object.values(indexList);
           for(let i = 0; i < indexList.length; i++)
                 my_array[indexList[i]] = 0;
           return my_array;
      }
      
      console.log(...alterHalfWithZero(my_array));
      console.log(...alterHalfWithZero(my_array));
      console.log(...alterHalfWithZero(my_array));

      【讨论】:

        【解决方案4】:

        首先获取唯一的随机索引。 循环遍历索引并将它们设为 0。

        var my_array = ["a", "b", "c", "d", "e", "f"];
        
        // Get unique random indexes
        const random = (num, count) => {
          const set = new Set();
          while (set.size < count) {
            set.add(Math.floor(Math.random() * num));
          }
          return [...set];
        };
        
        const alter = (arr, count = 3) => {
          const output = [...arr];
          random(arr.length, count).forEach((index) => (output[index] = 0));
          return output;
        };
        
        console.log(alter(my_array));
        console.log(alter(my_array));

        【讨论】:

          【解决方案5】:

          这是一种解决方案。

          var my_array = ["a", "b", "c", "d", "e", "f"];
          
          const substitute = array => {
            const indexes = Array.from(Array(array.length).keys())
              .sort(() => Math.random() - 0.5)
              .slice(0, array.length / 2);
            return array.map((value, index) =>
              indexes.some(i => i === index) ? value : 0
            );
          };
          
          console.log(substitute(my_array));

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-03-10
            • 1970-01-01
            • 2019-04-19
            • 2012-06-13
            • 2015-10-02
            • 1970-01-01
            • 2012-08-15
            • 1970-01-01
            相关资源
            最近更新 更多