Mysterious Organism Challenge Project (JavaScript)

nice work.
But your sample always returns a list where all 30 samples come back ar ‘true’. I am having the same trouble actually. Why are all instances beeing pushed into the sampleList?

nice work.
But your sample always returns a list where all 30 samples come back as ‘true’., no? I am having the same trouble actually. Why are all instances beeing pushed into the sampleList?

This is my solution. I know it would be cleaner, but it works. (Extra challenge included)

Here’s my solution, everything seems to be working alright:

// 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;
};

const pAequorFactory = (specimenNum, dna) => {
  return {
    specimenNum,
    dna,
    mutate() {
      let randomNum = Math.floor(Math.random() * this.dna.length + 1);
      let randomBase = this.dna[randomNum];
      switch(randomBase) {
        case 'A':
          this.dna[randomNum] = ['T', 'C', 'G'][Math.floor(Math.random() * 3)];
          break;
        case 'T':
          this.dna[randomNum] = ['A', 'C', 'G'][Math.floor(Math.random() * 3)];
          break;
        case 'C':
          this.dna[randomNum] = ['A', 'T', 'G'][Math.floor(Math.random() * 3)];
          break;
        case 'G':
          this.dna[randomNum] = ['A', 'T', 'C'][Math.floor(Math.random() * 3)];
          break;
      }
      return this.dna;
    },
    compareDNA(pAequor) {
      let sameBase = 0;
      for (let i = 0; i < this.dna.length; i++) {
        if (this.dna[i] === pAequor.dna[i]) {
          sameBase += 1;
        }
      }
      console.log(`P. Aequor specimen ${this.specimenNum} and P. Aequor specimen ${pAequor.specimenNum} have ${(sameBase / this.dna.length * 100).toFixed(2)}% dna in common.`);
    },
    willLikelySurvive() {
      let cOrG = 0;
      for (let base of this.dna) {
        if (base === 'C' || base === 'G') {
          cOrG += 1;
        }
      }
      return cOrG / this.dna.length >= 0.6;
    }
  }
};

const createSurvivableStrands = (numberOfStrands) => {
  let arr = [];
  for (let i = 1; i <= numberOfStrands; i++) {
    let strandObj = pAequorFactory(i, mockUpStrand());
    while (!strandObj.willLikelySurvive()) {
      strandObj.mutate();
    }
    arr.push(strandObj);
  }
  return arr;
}

// let testObj = pAequorFactory(1, mockUpStrand());
// console.log(testObj);
// console.log(testObj.mutate());
// console.log(testObj.compareDNA(pAequorFactory(2, mockUpStrand())));
// console.log(testObj.willLikelySurvive());
// const thirtyStrands = createSurvivableStrands(30);
// console.log(thirtyStrands);
// for (let strand of thirtyStrands) {
//   console.log(strand.willLikelySurvive());
// }

Here’s my take on finding the most related strands. If anyone did this with the compareDNA method I’d like to know how you did it. Thanks! There’s probably a more efficient way to do this with built in functions let me know how you did it.

const findMostRelatedStrands = arr => {
  let compareArr = [];
  let percentArr = [];
  for (let i = 0; i < arr.length; i++) {
    for (let j = i; j < arr.length; j++) {
      if (arr[i] !== arr[j]) {
        let sameBase = 0;
        for (let x = 0; x < arr[i].dna.length; x++) {
          if (arr[i].dna[x] === arr[j].dna[x]) {
            sameBase += 1;
          }
        }
        let percentInCommon = (sameBase / arr[i].dna.length * 100).toFixed(2);
        compareArr.push({
          specimen1: arr[i],
          specimen2: arr[j],
          percentInCommon
        });
        percentArr.push(percentInCommon);
      }
    }
  }
  let maxPercent = percentArr.reduce((a, b) => Math.max(a, b)).toFixed(2);
  for (let pairs of compareArr) {
    if (pairs.percentInCommon === maxPercent) {
      console.log(`The two specimens with the most in common are specimen ${pairs.specimen1.specimenNum} and specimen ${pairs.specimen2.specimenNum}, with ${maxPercent}% bases in common.`);
    }
  }
};

It took me a while, but I finally finished it. I just didn’t do the final compareDNA() to find the two most similar strands.
My solution

Creative & interesting usage of this.DNA.reduce() in method .compareDNA() - how did the coder come up with this way?

Hi :), hope you’re all well,

    compareDNA(otherOrg) {
      const similarities = this.dna.reduce((acc, curr, idx, arr) => {
        if (arr[idx] === otherOrg.dna[idx]) {
          return acc + 1;
        } else {
          return acc;
        }
      }, 0);
      const percentOfDNAshared = (similarities / this.dna.length) * 100;
      const percentageTo2Deci = percentOfDNAshared.toFixed(2);
      console.log(`${this.specimanNum} and ${otherOrg.specimanNum} have ${percentageTo2Deci}% DNA in common.`);
    },

[Above: from the solution code]

I used a different way, but was wondering how did the coder figure that way out? Is there anything in MDN’s documentation that would indicate this way of using .reduce()? From the lessons, it seemed like .reduce() is used to basically sum up array values into a single value…But here it uses a conditional and .reduce()'s accumulator variable to count strings common amongst 2 DNA arrays. Would be cool if someone from the Codecademy team shared some yumm insights (@codecademycodecademy @annajiali). [Tried searching this thread but didnee find anything].

Thanks in advance :slight_smile:

Which greeting is better?
  • Hi :slight_smile:
  • Greetings fellow nerrrds :slight_smile: (and then ending with Nerrds Rule!)

0 voters

@lilybird @maryboydc @oduffy @catower @fede_hq :slight_smile:

Hi Everyone,

When I call compareDNA(newOrganism) it comes up with an error “CompareDNA is not defined at object.”

I’m sure there’s a lot more wrong here aside from that but I’m not really sure where to start. Thanks for the help.


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
}

 const pAequorFactory = (specimenNum, dna) => {
   return {
     specimenNum: 1, 
     dna: mockUpStrand,
     mutate () {
       let randomIndex = Math.floor(Math.random() * this.dna.length);
       let newBase = returnRandBase()
       while (this.dna[randomIndex] === newBase) {
         newBase = returnRandBase()
       }
       this.dna[randomIndex] = newBase
       return this.dna
     },
     compareDNA(pAequor) {
    let total = 0;
    for(let i = 0; i < pAequor.dna.length; i++){
      if(pAequor.dna[i] === this.dna[i]) {
        total += 1;
    }
   }
    console.log(`specimen #${pAequor.specimenNum} and specimen #${this.specumenNum} have (${total}/${pAequor.length})in common.`)
  
  },
 }
};

const newOrganism = pAequorFactory(2145, mockUpStrand())
compareDNA(newOrganism)

``
1 Like

When you run that compare dna method it takes a second organism as an argument…so try making 2 organisms and calling the compare dna method on 1 of them while passing the 2nd as an argument?

Oh I see…why you got that message though. You called the compareDNA method by itself instead of newCreature.compareDNA(secondCreature)

Just like you’d run mutate by
newCreature.mutate()
And not by
Mutate()

Since they are object methods they belong to the object and called from the object, not like a regular function. :slight_smile: that’s my guess as a total newbie who just finished this project yesterday

Here is my solution to the mysterious organism project.

thanox

Merely a tiny tip here.
I find it simpler to add 1 to the counter by typing:
++count
instead of:
count += 1

Does anyone know why when I enter console.log(newOrganism.willLikelySurvive()) it either comes up as true or undefined? Really not getting this lol. The survival array also does not work but I think that’s partially because of the first part of my question.

Thank you.

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
}

 const pAequorFactory = (specimenNum, dna) => {
   return {
     specimenNum: specimenNum, 
     dna: dna,
     mutate () {
       let randomIndex = Math.floor(Math.random() * this.dna.length);
       let newBase = returnRandBase()
       while (this.dna[randomIndex] === newBase) {
         newBase = returnRandBase()
       }
       this.dna[randomIndex] = newBase
       return this.dna
     },

     compareDNA(pAequor) {
    let total = 0;
    for(let i = 0; i < this.dna.length; i++){
      if(pAequor.dna[i] === this.dna[i]) {
        total += 1;
    }
   }
    let percentage = Math.floor((total/pAequor.dna.length) * 100) 
    console.log(`specimen #${pAequor.specimenNum} and specimen #${this.specumenNum} have ${percentage}% in common.`)
  },

willLikelySurvive () {
  let count = 0
  for (let i = 0; i < this.dna.length; i++) {
    if (this.dna[i] === 'C' || this.dna[i] === 'G') {
      count ++;
    }
   }
   if (((count * 100) / this.dna.length) >= 60) {
     return true
   } else {
     false
   }
  },
 }
};

let survivalArray =[]
let idCounter = 1

while (survivalArray.length <= 30) {
  let newOrg = pAequorFactory(idCounter, mockUpStrand())
  if (newOrg.willLikelySurvive()) {
    survivalArray.push(newOrg);
  }
  idCounter++
}

const newOrganism = pAequorFactory(21145, mockUpStrand())
const otherOrganism = pAequorFactory(62352,mockUpStrand())


console.log(newOrganism.willLikelySurvive())

Any input here??? @mtf

Forgot “return” false
You have “return true”
Else “false”