0

In Javascript, am trying to randomly substitute half (in this case, 3 out of 6) of the items from an array with different ones (all of the same type), and I need the original items' position to be kept. So for instance, if I have:

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

I would want to select three random ones to be substituted with a 0, while the others to keep their initial position. So let's say a, c, and d are the ones the random selector will make go away on one instance, then my array would become:

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

On a different run, the random selector would perhaps pick b, c, and f and so I'd have:

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

And so on. Thank you so much for your help!

2
  • 4
    what does not work? Commented Aug 15, 2020 at 9:45
  • @NinaScholz I am just new to JavaScript and I am not sure where to start from! I've been using a shuffle function and then select the first three items to get a random selection so far, but that doesn't keep the original positions in place Commented Aug 15, 2020 at 9:51

5 Answers 5

2

You could take a closure over the array and wanted zero counts and return a function which generates random integer and map the array with zeros or values.

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

Sign up to request clarification or add additional context in comments.

Comments

1

Another option

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

Comments

0

You need to calculate half of the length of the array, generate random indexes of this amount, and then change them:

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

Comments

0

First get unique random indexes. Loop over the indexes and make them 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));

Comments

0

Here is one solution.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.