Helping people with the algorithms, I end up going back and re-factoring my own solutions. This is good practice, but on the last one, I was amazed at the difference between my solution to Smallest Common Multiple today, versus the solution I came up with last year:
Last Year:
function smallestCommons(arr) {
var baseNumbers = [];
arr.sort(function (a, b) { return a - b; });
for (var i = arr[0]; i <= arr[1]; i++) {
baseNumbers.push(i);
}
var divisible = true,
divisorList = [],
currentDivisor = 2;
while (divisible) {
divisible = false;
for (i = 0; i < baseNumbers.length; i++) {
if (baseNumbers[i] % currentDivisor === 0) {
baseNumbers[i] = baseNumbers[i] / currentDivisor;
divisible = true;
}
}
for (i = 0, baseValues = 0; i < baseNumbers.length; i++) {
baseValues += baseNumbers[i];
}
if (divisible) {
divisorList.push(currentDivisor);
}
else if (baseValues !== baseNumbers.length) {
currentDivisor++;
divisible = true;
}
}
var LCM = 1;
for (i = 0; i < divisorList.length; i++) {
LCM *= divisorList[i];
}
return LCM;
}
Today:
function smallestCommons(arr) {
arr.sort();
var LCM, mult = 1, check = false;
while(!check){
mult++; check = true; LCM = arr[1] * mult;
for(var i = arr[0]; i < arr[1]; i++) if(LCM % i) check = false;
}
return LCM;
}
I’m not saying that the new solution is the best one, and as I gain more experience I may think of better solutions to this and all the algorithm challenges, but I still find it fascinating to see how much I’ve grown. Do you have any interesting examples of how you’ve grown as a coder?