替换 Javascript 数组中的随机项

Substitute random items in a Javascript array

在 Javascript 中,我试图用不同的(所有相同类型的)随机替换数组中的一半(在本例中,6 个中的 3 个)项目,我需要原始的物品的位置要保持。例如,如果我有:

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

我想 select 将三个随机的替换为 0,而其他的则保持其初始位置。所以假设 a、c 和 d 是随机的 select 或者会在一个实例中消失,那么我的数组将变为:

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

在另一个 运行 上,随机 selector 可能会选择 b、c 和 f,所以我会:

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

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

你需要计算arraylength的一半,随机生成这个数量的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));

您可以对数组进行闭包并需要零计数和 return 一个生成随机整数并使用零或值映射数组的函数。

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());

另一种选择

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());

首先获取唯一的随机索引。 遍历索引并使它们为 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));

这是一种解决方案。

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));