Hallo there,
can anyone please lend a hand trying to figure out this problem. I don’t know what has gone wrong with my code. This is for the credit card checker too. I think I’m not doing the calculations correctly but not sure why that is. Any help would be greatly appreciated. Thanks
const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]; //for this my function returns false.
const validateCred = (array) => {
let len = array.length
let newArray = []
for(let i = len-1; i >= 0; i--) {
let num = array[i];
if ( i % 2 !== 0) {
num*= 2;
if (num > 9) {
num -= 9;
newArray.push(num);
} else {
newArray.push(num);
}
} else {
newArray.push(num);
}
}
newArray.push(array[len-1]);
const reducer = (a, b) => (a + b);
sum = newArray.reduce(reducer)
return sum % 10 === 0
};
I see a problem here:
if ( i % 2 !== 0) {
The algorithm says to double every other number starting from the end (where the next-to-last one is doubled).
However, yours doubled any number at each odd-numbered index.
Using the odd index only matches (doubling the numbers that algorithm says to double) only when the length of the array is an odd number. [The algorithm would match doubling the even indices if the length of the array is even.]
Also,
newArray.push(array[len-1]);
should not be there;
because you already handled stuff at the len-1
index in the loop previously.
You can delete that line of code.
Thanks for your help. I was quite confused with the whole correct index to double problem. I gave in and looked at the solution in the end. And changing the way I approached getting the correct indicies has solved the problem. I’m also not adding anything to an array anymore, just looping through and adding to a total. So simple. Simplicity is the way to go.
Here’s the final code. Works perfectly. Thanks alot for you help.
[codebyte language=golang]
const validateCred = (array) => {
//console.log(array)
let len = array.length
let sum = 0
for(let i = len-2; i >= 0; i--) {
let num = array[i];
if ((array.length - 1 - i) % 2 === 1) {
num*= 2;
if (num > 9) {
num -= 9;
}
}sum += num;
}
let checkDigit = array.pop();
sum += checkDigit;
return sum % 10 === 0;
};
[/codebyte]