Hi everyone!
I’m currently stuck on the “Smallest Common Multiple” task and I feel I made things way to complicated, but also have no solid idea what I could do differently or what to google for to get closer to the solution. Also I don’t want to give up and just read the solution, so I decided to ask for help here.
This is my code (I tried to explain what I intended to do in the code directly rather then explaining it beforehand). It would be much appreciated if anyone can explain me what is going wrong and why it’s going wrong and whether or not I’m on the right track or I should rather start over (if that is the case, some pointers for what to do different in the next attempt would be much appreciated). Thanks in advance!
function smallestCommons(arr) {
var orderedArr = arr;
var fullNumArr = [];
var compareArr = [];
//orders arr in orderedArr, so that higher number is always the first one
if (arr[0] > arr[1]){
orderedArr = [arr[1], arr[0]];
}
//prepares arrays needed in findNum function
function prep (value){
//creates an array with all numbers between arr[0] and arr[1] (from largest to smallest number)
//creates subarrays for compareArr, that will be filled up in the next for loop
for (var i = orderedArr[1]; i >= 1; i--){
if (i >= orderedArr[0] && i <= orderedArr[1]){
fullNumArr.push(i);
compareArr.push([]);
} else {
return compareArr;
}
}
//fills subarrays of compareArr with multiples of each number, so that they can be compared within the findNum function
for (var j = 0; j < fullNumArr.length; j++){
for (var k = 1; k <= value; k++){
compareArr[j].push(fullNumArr[j] * k);
}
}
return compareArr;
}
//findNum compares compareArr[0] and compareArr[1] to find the smallest common multiple of these 2
//then it replaces the first two numbers in the fullNumArr with this smallest common multiple
//then it should (but currently doens't) go through the prep function again to update compareArr
//based on the changes made to fullNumArr. I want to repeat this process until only 1 number is left
//in the fullNumArr array and then (in my theory) the only thing left to do would be to return that number
function findNum (){
prep(orderedArr[1]);
for (var l = 0; l < compareArr.length; l++){
if (compareArr[l].length > 1){
for (var m = 0; m < compareArr[l].length; m++){
for (var n = 0; n < compareArr[l+1].length; n++){
if (compareArr.length == 1){
return fullNumArr[0];
}
else if (compareArr[l][m] == compareArr[l+1][n]){
fullNumArr[l] = compareArr[l][m];
fullNumArr.splice(l+1, 1);
compareArr = [];
prep(fullNumArr[0] * fullNumArr[1]);
}
}
}
} else {
return fullNumArr[0];
}
}
}
return findNum();
}
smallestCommons([1, 5]);