Here is my code

I created my own version but it produces different output can you help me explain why my code produces different results? Mycode:

```
const splitNum = (num) => {
return num
.toString()
.split("")
.reduce((sum, digit) => sum + parseInt(digit), 0);
};
const validateCard = (arr) => {
let sumOddArr = 0;
let sumEvenArr = 0;
//check from right
for (let i = arr.length - 1; i >= 0; i--) {
if ((arr.length - 1 - i) % 2 === 0) {
let double = arr[i] * 2;
sumEvenArr += double > 9 ? splitNum(double) : double;
} else {
sumOddArr += arr[i];
}
}
let total = sumOddArr + sumEvenArr;
return total % 10 === 0;
};
```

Hi all,

Hi - I’m not sure if I’m reading the instructions incorrectly or if i’m adding more than i should. .Here’s the link to my code: Codecademy export · GitHub

Also pasted the full code below.

My questions are:

(1) one of the tests on my validateCred does not pass. Not sure why. I added a new variable (testingItem) with one item in the array (a credit card number NOT separated by commas). The function itself converted it into individual numbers separated by commas. It prints true when it should be false just when passing this particular variable. Number was taken from the card generator link provided on question 7. Since the numbers are fake, i was expecting a false value.

(2) my findInvalidCards function works when i use the batch provided in the exercise, but it does not work with two new variables i added (testingItem, and fakeNums). The latter is a nested array just like batch and should provide me with all 3 items since they are all fake, but instead it gives me an empty array. The test with variable testingItem gives me an error message and points to an issue with this: let reversedArr = arr1.reverse(); (on line 29) Why is that happening?

(3) Lastly, the idInvalidCardCompanies function should give me the name of three credit cards when passing the fakeNums variable and instead prints out ‘company not found.’ Also, shouldn’t we be using the info from the findInvalidCards() function? After all, the instruction reads the paramenter for the idInvalidCardCompanies is of an array of INVALID numbers.

What am i doing wrong? Any guidance is greatly appreciated!

P.S. test also asked (question 7) we create a function that will convert invalid numbers into valid numbers. Not sure how to accomplish this. Wouldn’t i just be making up real credit card numbers? am i reading this wrong?

Thanks again!!!

```
// All valid credit card numbers
const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8];
const valid2 = [5, 5, 3, 5, 7, 6, 6, 7, 6, 8, 7, 5, 1, 4, 3, 9];
const valid3 = [3, 7, 1, 6, 1, 2, 0, 1, 9, 9, 8, 5, 2, 3, 6];
const valid4 = [6, 0, 1, 1, 1, 4, 4, 3, 4, 0, 6, 8, 2, 9, 0, 5];
const valid5 = [4, 5, 3, 9, 4, 0, 4, 9, 6, 7, 8, 6, 9, 6, 6, 6];
// All invalid credit card numbers
const invalid1 = [4, 5, 3, 2, 7, 7, 8, 7, 7, 1, 0, 9, 1, 7, 9, 5];
const invalid2 = [5, 7, 9, 5, 5, 9, 3, 3, 9, 2, 1, 3, 4, 6, 4, 3];
const invalid3 = [3, 7, 5, 7, 9, 6, 0, 8, 4, 4, 5, 9, 9, 1, 4];
const invalid4 = [6, 0, 1, 1, 1, 2, 7, 9, 6, 1, 7, 7, 7, 9, 3, 5];
const invalid5 = [5, 3, 8, 2, 0, 1, 9, 7, 7, 2, 8, 8, 3, 8, 5, 4];
// Can be either valid or invalid
const mystery1 = [3, 4, 4, 8, 0, 1, 9, 6, 8, 3, 0, 5, 4, 1, 4];
const mystery2 = [5, 4, 6, 6, 1, 0, 0, 8, 6, 1, 6, 2, 0, 2, 3, 9];
const mystery3 = [6, 0, 1, 1, 3, 7, 7, 0, 2, 0, 9, 6, 2, 6, 5, 6, 2, 0, 3];
const mystery4 = [4, 9, 2, 9, 8, 7, 7, 1, 6, 9, 2, 1, 7, 0, 9, 3];
const mystery5 = [4, 9, 1, 3, 5, 4, 0, 4, 6, 3, 0, 7, 2, 5, 2, 3];
// An array of all the arrays above
const batch = [valid1, valid2, valid3, valid4, valid5, invalid1, invalid2, invalid3, invalid4, invalid5, mystery1, mystery2, mystery3, mystery4, mystery5];
//Numbers from the credit card generator link
let fakeNums = [[4,1,6,7,4,2,8,9,7,7,5,8,4,3,1,4,5,1,8],[5,4,4,3,6,2,8,1,7,9,8,3,0,4,1,3,2],[3,4,9,5,9,8,1,0,4,9,6,7,2,8,9]];
let strTesting = 'coding 1234';
//Numbers from the credit card generator link
let testingItem = [349598104967289];
// Add your functions below:
//PART OF THE PROJECT EXTENSION: FUNCTION ACCEPTS A STRING AND CONVERTS IT INTO ARR OF NUMS
const fromStrToArr = str =>{
//converts str to array
let toArr = [...str];
//converts strings into numbers and if letters are present, it gives NaN
let convertsToNum = toArr.map(x => Number(x));
// removes any NaN items from the array
return convertsToNum.filter(item => !Number.isNaN(item));
};
console.log(fromStrToArr('hapiness345yes'));
//THIS RETURNS TRUE IF CARD IS VALID AND FALSE IF INVALID
const validateCred = arr => {
//ensures we are working with an array of numbers and not letters
let arr1 = arr; //as to not mutate initial array
if(typeof arr1 === 'string'){
arr1 = fromStrToArr(arr1);
//code in else statment makes sure that if credit card is entered as a full number instead of an array of numbers, we'll break that long number into individual items
} else if(arr1.length === 1){
arr1 = [...arr1.toString()].map(Number);
}
let reversedArr = arr1.reverse();
let newArr = [];
let sumModulo;
for(let i = 0; i< reversedArr.length; i++){
if(i === 0 || i % 2 == 0){
newArr.push(reversedArr[i]);
} else {
let value = reversedArr[i] * 2;
if(value > 9){
newArr.push(value - 9)
} else {
newArr.push(value)
}
}
sumModulo = newArr.reduce((a,b)=> a + b);
}
return sumModulo % 10 === 0 ? true : false;
};
console.log(validateCred(invalid1));
console.log(validateCred(valid4));
console.log(validateCred(strTesting));
console.log(validateCred(testingItem));// Error.gives true but should be false as it's a fake number taken from the card generator link provided on question 7.
//CREATES A NESTED ARRAY OF INVALID CARDS
//code seems faulty. It works with the batch array included here but not with the nested array fakeNums on line 28. These numbers were taken from the credit card generator link provided on question 7.
const findInvalidCards = nestedArr => {
let invalidCards = [];
nestedArr.forEach(x => {
if(validateCred(x) === false){
invalidCards.push(x);
}
});
//Thought perhpas a double foreach was necessary as we are dealing with nested arrays. However code below gives an error and points to line 65 (let reversedArr = arr1.reverse());
// nestedArr.forEach(firstArr =>{
// firstArr.forEach(x=>{
// if(validateCred(x) === false){
// invalidCards.push(x);
// }
// })
// });
return invalidCards;
};
console.log(findInvalidCards(fakeNums));// this should give me the 2 cc numbers since those are fake, but it gives me an empty array.
console.log(findInvalidCards(batch));
//console.log(findInvalidCards(testingItem));// gives me an error message for line 64 (resersedArr = arr.reverse()); not sure why
//IDENTIFY CC COMPANIES THAT ISSUED INVALID CARDS
//CONFUSED HERE. Shouldn't we be using the info from the findInvalidCards() function? After all, the instruction reads the paramenter for the idInvalidCardCompanies is of an array of invalid numbers.
const idInvalidCardCompanies = arrOfInvNum=> {
let company;
let arrOfCompanies = [];
for(let i = 0; i < arrOfInvNum.length; i++){
switch(arrOfInvNum[i][0]){
case 3:
company = 'Amex';
break;
case 4:
company = 'Visa';
break;
case 5:
company = 'Mastercard';
break;
case 6:
company = 'Discover';
break;
default:
company = 'company not found';
}
//without === -1 when using index we get 11 items
if(arrOfCompanies.indexOf(company) === -1){
arrOfCompanies.push(company);
}
}
return arrOfCompanies;
}
console.log(idInvalidCardCompanies(batch));
console.log(idInvalidCardCompanies(fakeNums)); // prints company not found; however, it should print Visa, Mastercard, Amex.
///PROJECT EXTENSIONS
//7.1 used numbers form the validator site but response is not what i expected. What i think should return false, returns true.
//7.2 function that accepts strings and converts them into an array has been created (first function)
//7.3 create a function that will convert invalid numbers into valid numbers. Not sure how to accomplish this.
//function invalidToValid = arr => {};
```

In the `validateCred`

function,

you have `let arr1 = arr;`

But this does not copy the array, it makes a new *reference* to the array.

So `arr1`

and `arr`

are the same array.

And doing `arr1.reverse()`

reverses the original array.

Also, I think the idea for making an invalid card become a valid one is to change the last number/digit of the card.

Every couple years we get the impulse to add some thoughts to this topic. Today we’re exploring methodology:

```
def bin_parity(w):
"""Mutate every other member in a list based on length parity
:param w - list
:return list - mutated
"""
n = len(w)
m = n % 2
for i in range(m, n, 2):
a = w[i] * 2
w[i] = a // 10 + a % 10
return w
u = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]
v = [3, 7, 1, 6, 1, 2, 0, 1, 9, 9, 8, 5, 2, 3, 6]
print (u)
print (bin_parity(u))
print (sum(u) % 10)
print (v)
print (bin_parity(v))
print (sum(v) % 10)
```

The function name is not meant to convey anything more than the idea of a bin, or box, and its relation to the length parity. Notice that `m`

will be `0`

when `n`

is even.

Also note, the above code is an exploration using a different programming language, though it is easily ported to JavaScript. The intent is to explore the ideas.

Study the code and infer what each piece means, keeping what you know about JavaScript front and center in your awareness for comparative sake. Relate it back to the language you are using, but study and question where the logic is taking us.

Can anyone predict what the printout is for those last six lines? I’ll leave this for as long as it takes for someone to reply.

While we’re waiting let’s explore this program a step further but offering a function that will validate our input, using the above code.

```
def valid(w):
"""Determine validity of sequence
:param w - list
:return bool - list is valid or not
:dependency - bin_parity()
"""
return not sum(bin_parity(w)) % 10
```

Now our print statements look like this:

```
print (u)
print (u, '\n', valid(u))
print (v)
print (v, '\n', valid(v))
```

Can anybody predict what the print out will look like for the last four lines?

Are we ever going to use that bin_parity function from anywhere else in a program? Not likely. So why not turn a dependency into a helper function?

```
def is_valid(w):
def f(w):
n = len(w)
m = n % 2
for i in range(m, n, 2):
a = w[i] * 2
w[i] = a // 10 + a % 10
return w
return not sum(f(w)) % 10
u = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]
v = [3, 7, 1, 6, 1, 2, 0, 1, 9, 9, 8, 5, 2, 3, 6]
print (u)
print (u, '\n', is_valid(u))
print (v)
print (v, '\n', is_valid(v))
```

Having reduced the code to this, we can easily port to JavaScript. We won’t be doing that unless somebody shows an interest.

```
p = [int(x) for x in ''.join([str(x) for x in u])]
print (p, '\n', is_valid(p))
```

What will the print out be? Hmmm…

Anybody pretending to be interested in computer science would be all over this stuff, by now. Must have hit on the wrong audience, the ‘reverse the list’ type. Their loss…

Will output

```
> [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]
> [8, 5, 6, 9, 3, 7, 5, 9, 0, 8, 0, 1, 3, 8, 0, 8]
> 7
> [3, 7, 1, 6, 1, 2, 0, 1, 9, 9, 8, 5, 2, 3, 6]
> [3, 5, 1, 3, 1, 4, 0, 2, 9, 9, 8, 1, 2, 6, 6]
> 60
```

As for

```
print (u)
print (u, '\n', valid(u))
print (v)
print (v, '\n', valid(v))
```

Will output

```
> [8, 5, 6, 9, 3, 7, 5, 9, 0, 8, 0, 1, 3, 8, 0, 8]
> [8, 5, 6, 9, 3, 7, 5, 9, 0, 8, 0, 1, 3, 8, 0, 8]
> False
> [3, 5, 1, 3, 1, 4, 0, 2, 9, 9, 8, 1, 2, 6, 6]
> [3, 5, 1, 3, 1, 4, 0, 2, 9, 9, 8, 1, 2, 6, 6]
> True
```

Note that we have modify the input array (`w`

) in the `bin_parity`

function, so the output will be the modified array and not the original one. The logic is quite magnificent specifically you can use pure arithmetic operations to do the trick and not requiring a ternary operator whatsoever.

```
p = [int(x) for x in ''.join([str(x) for x in u])]
print (p, '\n', is_valid(p))
```

This line of code you used should only be for demonstrative purpose and not real-life / industry-standardized coding practices. Because it returns the list itself and performing integer to string, then string to integer conversion consumes a lot of memory if the number gets really big. Also, the code above can be simplified to use `generator expression`

rather than a `list comprehension`

as they both serve the same purpose.

```
p = [int(x) for x in ''.join(str(x) for x in u)]
```

The equivalent code in JavaScript should be left to the fellow learners out there, so I am not going to post it here. Kudos ! ^^

It is for demonstration, particularly to produce a string from the U list, then convert it back to list of integers. Just pretend that we have a string, here,

```
''.join([str(x) for x in u])
```

As for the output of the first example, it will be,

```
def bin_parity(w):
"""Mutate every other member in a list based on length parity
:param w - list
:return list - mutated
"""
n = len(w)
m = n % 2
for i in range(m, n, 2):
a = w[i] * 2
w[i] = a // 10 + a % 10
return w
u = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]
print (u)
[4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]
print (bin_parity(u))
[8, 5, 6, 9, 3, 7, 5, 9, 0, 8, 0, 1, 3, 8, 0, 8]
print (sum(u) % 10)
0
v = [3, 7, 1, 6, 1, 2, 0, 1, 9, 9, 8, 5, 2, 3, 6]
print (v)
[3, 7, 1, 6, 1, 2, 0, 1, 9, 9, 8, 5, 2, 3, 6]
print (bin_parity(v))
[3, 5, 1, 3, 1, 4, 0, 2, 9, 9, 8, 1, 2, 6, 6]
print (sum(u) % 10)
0
```

As to the last example,

```
def is_valid(w):
def f(w):
n = len(w)
m = n % 2
for i in range(m, n, 2):
a = w[i] * 2
w[i] = a // 10 + a % 10
return w
return not sum(f(w)) % 10
```

the output is,

```
[4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]
[8, 5, 6, 9, 3, 7, 5, 9, 0, 8, 0, 1, 3, 8, 0, 8]
True
[3, 7, 1, 6, 1, 2, 0, 1, 9, 9, 8, 5, 2, 3, 6]
[3, 5, 1, 3, 1, 4, 0, 2, 9, 9, 8, 1, 2, 6, 6]
True
```

You’re right about the use of arithmetic logic as opposed to program logic as the idea behind this approach. I wanted a method that did not use any `if`

statements, and it does not reverse the list to iterate it.

Perhaps you might try your hand at porting the `is_valid()`

function to JavaScript?

## Can't wait...

```
const is_valid = function (w){
const f = function (w) {
const n = w.length
const m = n % 2
for (let i = m; i < n; i += 2) {
const a = w[i] * 2
w[i] = Math.floor(a / 10) + a % 10
}
return w
}
return ! (f(w).reduce((a, b) => a + b) % 10)
}
```

```
u = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]
console.log(u)
console.log(is_valid(u))
console.log(u)
```

[4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]

true

[8, 5, 6, 9, 3, 7, 5, 9, 0, 8, 0, 1, 3, 8, 0, 8]

Let’s look at this code from an arithmetic perspective. The first order of business is to obtain the length of the list. The second order of business is to determine the parity of the length. 1 is odd, 0 is even. This gives us the starting index in our loop over the list. From there the step of 2 is all natural.

```
n = w.length
m = n % 2
```

```
* * * * * => m is 1
0123456789
* * * * * => m is 0
```

The starting position out of the way, now we work on the mutation of the elements. We’ve targeted an element, want to double its value but still leave only a single digit. That is the whole reason for subtracting 9, but that needs an if statement. Again, arithmetic came to bear.

The first digit of the product of two degree zero numbers will at most be degree one. We have at most, two digits. In this example we are only doubling a single digit so should not expect anything in the 20s, since 9 * 2 == 18. Notice the sum of digits is `9`

.

Following is a table of two digit results of doubling a single integer and sum of the digits:

```
5 10 1
6 12 3
7 14 5
8 16 7
9 18 9
```

Mining the digits is the ultimate goal. Since we know that the product described above is less than 19, the sum of its digits will be less than 10, so single digit. Thus we have the first digit being the floor of the number divided by 10, and the second digit being the modulo of the number and 10. Integer math, as it were.

Those are the secrets to this code. Whether it is how we want production code to be written is not my forte, so not my problem. We’re in it for the fun and discovery.

```
const isValid = function (w) {
const f = function (w) {
const n = w.length
for (let i = n % 2; i < n; i += 2) {
const a = w[i] * 2
w[i] = Math.floor(a / 10) + a % 10
}
return w
}
return ! (f(w).reduce((a, b) => a + b) % 10)
}
```

We saw it here, first. One could say it is the least interrogative approach.

Thanks.

So to make sure i understand, you are saying I’m still mutating the original array? (i though this would avoid mutating it)

yes, i intended to reverse the arr, but not sure why some errors (for the variables I created) point to that specific line (arr1.reverse()).

Thanks!

Yes, you are mutating the original array `arr`

when you do

```
const arr1 = arr;
arr1.reverse();
```

There are many ways to make a copy of an array.

`const arr1 = arr.slice();`

is one way for `arr1`

to be a copy of `arr`

~~Note that the maximum possible integer in JavaScript is 9007199254740991 so some 16-digit card numbers may not work as a single JavaScript number [distinctly].~~

I wasn’t able to recreate the error that you mentioned.

If our feed stalk is coming directly from our data source (which it is) then we need to cut it off right at the input stage else risk corrupting the original data source. Your suggestion of a slice is bang on. Its only caveat is whether a shallow copy is sufficient to the task. Slice after determining depth, would be the way to a solution, but that adds to complexity. Of course, that doesn’t apply here, so why dither on about complexity?

```
const isValid = function (w) {
const f = function () {
const n = w.length
for (let i = n % 2; i < n; i += 2) {
const a = w[i] * 2
w[i] = Math.floor(a / 10) + a % 10
}
return w
}
return ! (f(w.slice()).reduce((a, b) => a + b) % 10)
}
```

We used to count on @ionatan, @appylpye, and @alexc to proofread and test our code. Are there any willing replacements?

Thank you so much!

It prompts me an error only with the variable I created… going to spend a bit more time on this to try to figure it out. Thanks so much!

hi can i have some help on my java course

Hi everyone,

Here is my complete project. Any feedback would be appreciated!

Here is my solution:

Do you get any output or do you just get nothing? It would help us to help you if you tell us or better still give a screen shot of the errors you are getting.

I see a few things here

First I’m not sure if it’s just how it printed but at

it looks like you have ‘i-’ with a single minus sign.

The decrement operator is ‘–’ not ‘-’ so that line should read

for (let i = numArray.length - 1; i >= 0; i–)

Apologies if I’ve mis-read it.

The next thing I notice is that you have

if (currValue >= 10)

I think it only needs to be ‘>9’ but I’m sure if this makes a difference;