I have two arrays and for each number in the first array I need to find the largest number from the second array that fits into that number and break the first number into its components. Since 25
from the second array is the largest number that fits into 80
of the first, I need to transform 80
into two numbers - 75, 5
. Likewise for 6
and 5
the result should be 5, 1
. So the end result should be an array [75, 5, 5, 1]
let arr = [80, 6]
let arr2 = [25, 5]
for (let x of arr) {
for (let y of arr2) {
if (x / y > 1 && x / y < 4) {
let mlt = Math.floor(x / y)
largestFit = y * mlt
arr.splice(arr.indexOf(x), 1, largestFit)
}
}
}
console.log(arr)
The code above gives [75, 5]
so thought I could add one more splice
operation to insert the remainders, but doing this arr.splice(arr.indexOf(x 1), 0, x - largestFit)
just crashes the code editor. Why isn't this working and what is the solution? Thank you.
CodePudding user response:
It is not advised to splice an array that is being iterated, and it is the reason why your loop got suck sometimes.
Instead build a new array, so it doesn't affect the iteration on the input array.
If you first sort the second array in descending order, you can then find the first value in that array that fits the amount, and be sure it is the greatest one. For sorting numerically in descending order, you can use sort
with a callback function.
Once you have found the value to subtract, you can use the remainder operator (%
) to determine what is left over after this subtraction.
function breakDown(amounts, coins) {
// Get a sorted copy (descending) of denominations:
coins = [...coins].sort((a, b) => b - a);
const result = []; // The results are stored here
for (let amount of amounts) {
for (let coin of coins) {
if (coin < amount) {
result.push(amount - amount % coin);
amount %= coin;
}
}
if (amount) result.push(amount); // remainder
}
return result;
}
const arr = [80, 6];
const arr2 = [25, 5];
const result = breakDown(arr, arr2);
console.log(result);
CodePudding user response:
I found the issue. After the first splice()
operation indexOf(x)
was returning -1
, since x's
are being replaced, so the solution is to assign indexOf(x)
to a variable and use that variable for both splice()
operations.
let arr = [80, 6]
let arr2 = [25, 5]
for (let x of arr) {
for (let y of arr2) {
if (x / y > 1 && x / y < 4) {
let mlt = Math.floor(x / y)
largestFit = y * mlt
let idx = arr.indexOf(x)
arr.splice(idx, 1, largestFit)
arr.splice(idx 1, 0, x - largestFit)
}
}
}
console.log(arr)