samedi 13 février 2021

Pull random array member and store index of that member

I am doing a task where i need to take 1 member of an array, randomly generate a member from another predefined array, and insert the change to the original array in that position.

We have two helper functions:

// Returns a random DNA base
const returnRandBase = () => {
  const dnaBases = ['A', 'T', 'C', 'G']
  return dnaBases[Math.floor(Math.random() * 4)] 
}

// Returns a random single stand of DNA containing 15 bases
const mockUpStrand = () => {
  const newStrand = []
  for (let i = 0; i < 15; i++) {
    newStrand.push(returnRandBase())
  }
  return newStrand
}

And this is my unfinished object so far:

const pAqueorFactory = (num, arr) => {
  const newObj = {
    _specimenNum: num,
    _dna: arr,
    get specimenNum() {
      return this._specimenNum;
    },
    get dna() {
      return this._dna;
    },
    mutate() {
      //Select random base in obj array
      let randObjBase = arr.indexOf(this.dna[Math.floor(Math.random() * 15)]);
      console.log(randObjBase);
      console.log(arr[randObjBase]);
      //Generate random base from helper function
      let genBase = returnRandBase();
      //While generated base is same as selected base, generate a new one.
      while (randObjBase === genBase) {
        genBase = returnRandBase();
      }
      randObjBase = genBase;
      return randObjBase;
    }
  };

  return newObj
}

And then the calls:

let arrToDisp = pAqueorFactory(1, mockUpStrand());
console.log(arrToDisp.dna);
console.log(arrToDisp.mutate());

The problem I am facing is within the mutate() method:

//Select random base in obj array
      let randObjBase = arr.indexOf(this.dna[Math.floor(Math.random() * 15)]);
      console.log(randObjBase);
      console.log(arr[randObjBase]);

let randObjBase stores of the index of a randomly selected member, but due to how indexOf() works, a random member will be picked but will only return the first instance of it. So when making changes and reapplying it to the array it may not apply it to the original position if that makes sense.

If I opt to not using indexOf, then the code will simply pass the value into randObjBase but I won't have the index of which to put it back. Any suggestions you guys may have?


AFTERTHOUGHT: While writing this I just had a thought that I should break down the process even further and generate a random number and store it, then use that number to perform operations. I am going to try that now, but I wish to still learn from others that may or may not have a more effective approach to this.

EDIT: Separating the generation of the index worked! Hopefully reading this can help someone else out




Aucun commentaire:

Enregistrer un commentaire