Mysterious Organism Challenge Project (JavaScript)

Here’s my solution:

Thanks so much @1moregame this was very helpful!! :slightly_smiling_face:

1 Like

Hello,

Here’s my solution, any feedback would be really appreciated :slightly_smiling_face:

Mysterious Organism

Here’s my solution! In reviewing the solution code provided by Codecademy, there were two substantial differences that I saw:

  1. The use of the .filter() array method in willLikelySurvive() in the solution code.
  2. The use of the .reduce() array method in the compareDNA(), which I thought to be ingenious. I should have thought about using it!
// 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; }; // Returns an object representing P. aequor const pAequorFactory = (specimenNum, dna) => { return { // properties _specimenNum: specimenNum, _dna: dna, // methods // randomly mutates a base and returns array of dna bases mutate() { randIdx = Math.floor((Math.random() * 15)); newBase = returnRandBase(); if (this._dna[randIdx] != newBase) { this._dna[randIdx] = newBase; } else { this.mutate(); } return this._dna; }, // returns true if 60% or more of bases or Cs or Gs, false otherwise willLikelySurvive() { let cOrGCount = 0; this._dna.forEach(base => { if (base === 'C' || base === 'G') { cOrGCount++; } }); if ((cOrGCount / 15) >= 0.60) { return true; } else { return false; } }, // compares DNA with another object representing P. aequor and prints out % shared compareDNA(pAequorObj) { let dnaCommonCount = 0; for (let i = 0; i < 15; i++) { if (this._dna[i] === pAequorObj._dna[i]) { dnaCommonCount++; } } console.log(`specimen ${this._specimenNum} and specimen ${pAequorObj._specimenNum} have ${Math.floor((dnaCommonCount / 15) * 100)}% DNA in common`); } } }; // makes a set number of pAequor objects that are likely to survive const makeFitPAequor = n => { let fitPAequors = []; let fitCount = 0; let tempPAequor; while (fitCount < n) { tempPAequor = pAequorFactory(fitCount, mockUpStrand()); if (tempPAequor.willLikelySurvive()) { fitPAequors.push(tempPAequor); fitCount++; } } return fitPAequors; }; console.log(makeFitPAequor(30));

Hi guys!

This is my version of the solution. If someone would be so kind to review it and give me some feedback I would appreciate it so much!!!

This is the links to GitHub. If you prefer the code straight away in here please let me know!

Thanks!

This is my version of the Mysterious Organism Project! Let me know what you think. I had a really hard time with the Credit Card checker project, so the fact that this one didn’t take 4 days makes me pretty stoked :sweat_smile: Any feedback is appreciated so feel free!

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

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

const pAequorFactory = (num, dnaBaseArr) => {
  return {
    specimenNum: num,
    dna: dnaBaseArr,
    mutate() {
      let dnaSelector = Math.floor(Math.random() * this.dna.length);
      let baseSelect = this.dna[dnaSelector];
      if (baseSelect !== returnRandBase()) {
        this.dna.splice(dnaSelector, 1, returnRandBase());
        return this.dna
      } else {
         this.mutate();
      }
      return this.dna;
    },
    compareDNA(obj) {
      let similarDNA = 0;
      for (let i = 0; i < obj.dna.length; i++){
        if (this.dna[i] === obj.dna[i]){
          similarDNA++
        }
      };
      let percentage = (similarDNA / 15 * 100).toFixed(2); 
      console.log(`The percentage of identical DNA between the two given specimen is ${percentage}%`);
    },
    willLikelySurvive() {
      let survivalChance = 0
      for (let i=0; i<this.dna.length; i++){
        if (this.dna[i] === 'C' || this.dna[i] === 'G'){
          survivalChance++
        } 
      } if (survivalChance >= 9){
          return true
        } 
        return false
    },
  };
};

let pAequor = pAequorFactory(1, mockUpStrand());
const pAequorParty = (obj) => {
  let partyArr = [];
  while (partyArr.length < 30) {
    if(obj.willLikelySurvive() === true){
      partyArr.push(obj);
    } obj.mutate();
  } return partyArr;
};
console.log(pAequorParty(pAequor));

Hello, do forgive if my question(s) are silly:
Regarding the mutate function:


while (this.dna[randIndex] === newBase) {
newBase = returnRandBase();
}
this.dna[randIndex] = newBase;
return this.dna;

I don’t understand this dna[randIndex], what is it supposed to do: why not just use this.dna/randIndex on its own?
newBase = returnRandBase(); seems (to me) to repeat the declaration (let newBase = returnRandBase()), why though?
I understand the return this.dna but not this this.dna[randIndex] = newBase;.

Again, I’m a rather slow learner, do understand that. Thanks! =)

Hi,
My question regards the compareDNA(otherOrg) method:

compareDNA(otherOrg) {
const similarities = this.dna.reduce((acc, curr, idx, arr) => {

I don’t understand what these parameters are/ where they come from(acc/idx etc)?

    if (arr[idx] === otherOrg.dna[idx]) {
      return acc + 1;
    } else {
      return acc;
    }
  }, 0);

What was the method/ thinking behind declaring the conditional (arr[idx] === otherOrg.dna[idx]) and the rest of the statement?

Hey,
How is your learning experience going so far?
I’ll try to answer your question, hope this will be helpful:

-what did you mean by use this.dna/randIndex on its own?
lets consider that randIndex return a number from 0 to 14, in this.dna[randIndex] this= the object itself; dna = an array of 15 elements; [randIndex]= is the index of one element (chosen randomly among the 15elements)

therefore with this.dna[randIndex] you are accessing directly the element located at the given DNA index of our object.
ex:

pAequor= { dna: ['g', 'c' , 'd' , 'g'], printBase(){ randIndex= 2; console.log(this.dna[randIndex]) } } pAequor.printBase(); // will print d;

Here, the code would first create a newBase then check if it is the same as the base we want to replace. As long as it is the same, it replace the new base as many time as necessary until it is no longer equal to that base.
to avoid repetition i think we could use a Do…While Statement to perform the action at least once and repeat it until the condition given in while is no longer true.
however you MUST declare newBase in the function scope and not in the block scope of the while loop (so we can access newBase outside the while loop).
ex:

const changeBase=()=>{
let newBase; // function scope
do{ newBase = returnRandBase()} //perform the action at least once
while( this.dna[randIndex] === newBase) //repeat until the statement is no longer true
return newBase
// you can return newBase because it was declare in the function scope instead of the block scope

}

This will give a new value at the given dna index of our current object

let say

this.dna= ['a', 'b' , 'c' , 'd' , 'e' , 'f'] const randIndex=4; newBase= 'a'; console.log(this.dna[randIndex]) // will print e this.dna[randIndex] = newBase; console.log(this.dna[randIndex]) // will print a

Hey
I just had a look at your code i think it’s pretty awesome, thanks to you i now know how to use .tofixed() method, seems really useful :slight_smile:

also i like how you called the mutate methods inside itself.

I have only one observation, in your pAequorParty function i think that all your object will have the same secimenNum value of 1, is this correct?

Hi every one,

here is my code for the Mysterious Organism project.
don’t hesitate to comment, any observation would be gladly welcome :slight_smile:

Hello everyone, I am a beginner programmer. I can’t do this project at all. Can anyone help me please?

Hi there,

I’m David, I did this project just a few days ago, it would be my pleasure to work on it with you and assist you in your project, what time zone are you on? if you are free we can work on it tomorrow?

My solution for this code challenge:

const pAequorFactory = (num, arr) => {
    return {
        specimenNum: num,
        dna: arr,
        mutate() {
            let randomIndex = Math.floor(Math.random() * (this.dna.length));
            let randomBase = ['A', 'T', 'C', 'G'].filter(base => base !== this.dna[randomIndex])[Math.floor(Math.random() * 3)]
            this.dna[randomIndex] = randomBase;
            return this.dna;
        },
        compareDNA(pObj){
            const matchList = [...this.dna].filter((base,index) => { 
                return base === pObj.dna[index];
            });
            const matchPercentage = Math.round((matchList.length * 100) / this.dna.length);
            console.log(`specimen #${this.specimenNum} and specimen #${pObj.specimenNum} have ${matchPercentage}% DNA in common`) 
        },
        willLikelySurvive(){
            const cgList = [...this.dna].filter(base => base === 'C' || base === 'G');
            return Math.round((cgList.length * 100) / this.dna.length) >= 60;
        },
        complementStrand(){
            const baseCouple = {'A':'T','T':'A','C':'G','G':'C'};
            return [...this.dna].map(base => {
                return baseCouple[base];
            });
        }
    };
}

Github Repo for challenge

Here is my solution:

Here is my solution. I think it works. Any feedback welcomed.

Here is my Solution: :slightly_smiling_face:

Why do we use while for .mutate()? Isn’t that used for loops? What do we need to loop through when we are just replacing one base?

This was amazing to read through. Top stuff

This is my solution: