Referencing the extra project in Mysterious Organisms, where you’re asked to find the two most related organisms in a sample group (array) of organisms, for i<sampleArray.length, I would like to compare the DNA of object at sampleArray[i]
with the DNA of every object in sampleArray with an index greater than i.
This would run through every combination (i, j) in the sampleArray without repeating any unnecessary calculations (so if it’s already run through (i, j), it doesn’t repeat the calculation with (j, i)), but it’s freezing the codeacademy evaluator thing, so I’m guessing you’re not allowed to do this?
Code below:
const mostRelated = (sampleArray) => {
let currentMax = 0;
let currentMost = [];
for (i=0; i<sampleArray.length; i++) {
for (j=i+1; j<sampleArray.length; j++) {
let ijPercentage = sampleArray[i].compareDNA(sampleArray[j]);
if (ijPercentage > currentMax) {
currentMax = ijPercentage;
currentMost = [sampleArray[i], sampleArray[j]];
}
}
}
return `Sample ${currentMost[0].id} and Sample ${currentMost[1].id} are the most related organisms in the sample, with ${currentMax}% DNA in common.`;
};
I suspect this is not something that works, but I don’t know why, or what other construction one might use to get the same effect.
Does anyone know why you can’t do this (initialize j to i+1), and know how else to achieve the same effect without unnecessarily duplicating calculations?