javascript number counting - javascript

I am slightly stuck on the javascript logic to accomplish this.
Basically
If I give a number (say 30)
I want to show 5 either side.
so
25 26 27 28 29 30 31 32 33 34 35
That part is easy.
But then I need to handle cases where the number is below 5 (say 3).
What I want to to is,
for every number not shown on the right,
add it to the left
so
1 2 3 4 5 6 7 8 9 10 11
But then I need to handle cases where the number is above a (maximum-5) (say maximum = 100, number = 98).
What I want to to is,
for every number not shown on the left,
add it to the right
so
90 91 92 93 94 95 96 97 98 99 100
But then I need to handle cases where the maximum is below 10 (say number = 3, maximum = 8
What I want to to is,
only show the applicable range
so
1 2 3 4 5 6 7 8
But I am not sure on the logic

function ranger(num) {
//Establish limits and pre/post array storage
var low = 0, high = 100, howMany = 5;
var pre = [];
var post = [];
//Increment/decrement if appropriate
for(x=1;x<=howMany;x++) {
if((num-x) > low) { pre.push(num-x); }
if((num+x) < high) { post.push(num+x); }
}
pre.reverse();
alert("Before: "+pre+'\nNumber: '+num+'\nAfter: '+post)
}
ranger(7);
ranger(2);
ranger(96);

Tested for all your cases:
range = 5;
maximum = 8;
number = 3;
left = right = number;
while(right - left < range*2 ) {
if (right + 1 <= maximum) {
right++;
}
if (left - 1 > 0 ) {
left--;
}
if (right == maximum && left == 1) {
break;
}
}
for(i=left;i<=right;i++) {
console.log(i);
}

One possible solution:
function getPages(fromPageNumber) {
var result = [];
fromPageNumber= Math.min(94, Math.max(6, fromPageNumber));
for(var i = -5; i <=5; i++)
result.push(fromPageNumber + i);
return result;
}

// Set up your limits and bounds
var radius = 5.
middleNumber = 20,
lowerBound = 1,
upperBound = 100;
// For the defined (and available range) create an array of valid numbers
var results = [];
for (int i = Math.max(middleNumber - radius, lowerBound);
i <= Math.min(middleNumber + radius, upperBound);
i++) {
results.push(i);
}
// Print out the resulting numbers with spaces in between
console.log(results.join(' '));

function getSequence(num, length)
{
var min = 0;
var max=100;
Array result;
for(int i=num-(length/2); i<num+(length/2);i++)
{
if(i>min && i< max)
result.add(i);
}
return result;
}

Related

how to get a random number from fibonacci series

I want to get a random number from the Fibonacci series:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, ...
Here is my code:
var number = Math.floor(Math.random() * 100000);
var series_element = -1;
if (number < 1) {
series_element = 1;
} else {
if (number < 2) {
series_element = 2;
} else {
if (number < 3) {
series_element = 3;
} else {
if (number < 5) {
series_element = 5;
} else {
if (number < 8) {
series_element = 8;
} else {
if (number < 13) {
series_element = 13;
} else {
if (number < 21) {
series_element = 21;
}
////// series continues to 317811
}
}
}
}
}
}
alert(series_element);
But I never got the value of series_element less than 100. It always shows me higher values.
I think you mean that you're not getting a random number less than 100 from the Math.random() function. So you're not getting your variable series_element to be 11 or less (the first 11 terms of the Fibonacci sequence: 0 1 1 2 3 5 8 13 21 34 55 89).
In fact, it's a matter of probabilities.
100 / 1000000 = 0.0001
If you keep executing it you'll get a value less than 100 at some point... approximately 1 from 10000 times you do it.
There's nothing wrong with your code, but it could be improved so you don't have to put so much ifs.
First, let's define a function to calculate the fibonacci numbers. Details on how to do that can be find here: https://medium.com/developers-writing/fibonacci-sequence-algorithm-in-javascript-b253dc7e320e
function fibonacci(num){
var a = 1, b = 0, temp;
while (num >= 0){
temp = a;
a = a + b;
b = temp;
num--;
}
return b;
}
To get a random Fibonacci number you can call this function with a random number.
var number = Math.floor(Math.random()*100);
var result = fibonacci(number);
I don't recommend going after 100 as your computer may take too much time to process the result...
You are using with poorly structured code to generate fabonacci series. Try something like following, you will get value under 100 and 1000
Where N is position of Fibonacci number from 1 to N and X is actual number.
var n = function getRandomNum() {
return Math.floor(Math.random()*100) +1;
}
var result = [];
result[0] = 1;
result[1] = 1;
function fib(x) {
var ix, ixLen;
for(ix = 0, ixLen = x; ix < ixLen; ix++){
if(!result[ix]){
result[ix] = result[ix-2] + result[ix-1];
}
}
console.log('n:', x, ' result: ', result[ix-1]);
return result[ix-1];
}
console.log(fib(n()));

Smallest Common Multiple Code produces the wrong answer on one array

[edit]
I should clarify, I am attempting to find the smallest common multiple of a range of numbers. Sorry about that. I have attempted another solution but I still run into an incorrect answer on the last array [23, 18].
function smallestCommons(arr) {
arr = arr.sort(function (a, b) { return a - b; });
var count = 1;
for (var i = arr[0]; i <= arr[1]; i++) {
if (count % i !== 0) {
i = arr[0];
count++;
}
}
return count;
}
smallestCommons([23,18]);
My solution produces 2018940 when it should be 6056820
Your endless loop is becouse of your inner for loop which starts at the value 19 and runs to 22
414 (smallestMultiple of 18 & 23) % 19 == 15
414 % 20 = 14
414 % 21 = 15
414 % 22 = 18
which leads to your statement if(count % i == 0) being false and your for loop goes on with 415 416 ...
if u want to get the
least common multiple
var isSmallestMultipe = 0;
while(isSmallestMultiple == 0)
{
for(var i = 1; i <= arr[1]; i+)
{
if((arr[0]*i) % arr[1] == 0)
{
isSmallestMultiple = arr[0] * i;
}
}
}

Print integers 1-20 in groups of five per line

I'm just starting out with JS and stuck on a question which is print integers 1-20 using a while loop. Print only five integers per line.
Any help would be great!
I tried a few things, here's the latest:
var x=" ";
var i=1;
while (i<=20; i++) {
x=i%5=0; "\n"
}
alert(x);
For very basic JavaScript like this, it would probably help to use a console rather than write code for a web page. Ideally, you'd write a bunch of programs using console.log(), and then you'd write a bunch of programs that manipulate and generate DOM elements, and you'll entirely skip the awkward stage of alert() and document.write(). Eloquent JavaScript is a book that I followed in precisely this way.
In any case, here are three loops that do about what you describe. The first is very similar to your attempt. The other two output lines of output at a time, but differ considerably in their looping logic.
console.log('\nloop one')
;(function() {
var x = '',
i = 1
while (i <= 20) {
x += i
x += i%5 ? ' ' : '\n'
i++
}
console.log(x)
})()
console.log('\nloop two')
;(function() {
var line = ''
for (var i = 1; i <= 20; i++) {
line += i + ' '
if (i % 5 === 0) {
console.log(line)
line = ''
}
}
})()
console.log('\nloop three')
;(function() {
for (var i = 1, line = ''; i <= 20; line = '') {
for (var j = 0; j < 5; j++)
line += i++ + ' '
console.log(line)
}
})()
node example, with the above all in a file named 'example', produces this output:
loop one
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
loop two
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
loop three
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
You need some syntax and logic changes, like below:
var i=1;
while (i<=20){
var x=i%5; // checks for 5 numbers in a line
if(x==0)
document.write(i+",<br>"); // give a break if 5 numbers on line
else
document.write(i+",");
i++;
};
Try using an array to store values of i , Array.prototype.splice()
var x = []
, i = 1
, len = 5
, max = 20;
while (i <= max) {
x.push(i++); --len;
if (len === 0 && x[x.length - 1] !== max) {
x.splice(x.length, 0, "\n");
len = 5
}
}
console.log(x);
alert(x.join(" "));
that's my version over here:
http://jsbin.com/pamaledopi/1/edit?js,console
Don't forget to turn F12 on! (Be sure you have console opened and click "Run")
_padEmpty is for formatting purposes, you can drop it and call to it too.

counting the amount of times a number occurs in array javascript

I have an array of size 50 that holds random integers between 1 and 49.
I would like to be able to count the amount of times the numbers between 10 and 19 occur within the array.
<script type = "text/javascript">
var arr = [];
function getRandom( num ){
return Math.round(Math.random() * num)+1;
}
var counter = 0;
for (var i = 0; i < 50; i++) {
arr.push(getRandom( 49 ));
counter++;
}
var count=0;
for (var i=0;i<50;i++{
if(arr[i]<19 && arr[i]>10){
count++;
}
}
that is if you mean 10 and 19 not to be counted if you want to count 10 and 19 also, then change the limit to 20 and 9
Try using the Arry.filter method:
var nBetween10and19 = [yourArraY]
.filter(function(b){return b>10 && b<19;}).length;
See MDN for information on Array.filter and a shim for older browsers
It is always a good idea to make a function because you can reuse it later with different parameters.
I wrote a function that accepts min and max values, and counts the number of occurrences that satifies the limits.
you can pass null for either min or max if you do not want to specify them.
function countRange(list, min, max) {
var c = 0;
for (var i = 0, l = list.length, item; i < l; i++) {
item = list[i];
if ((min == null || item >= min) && (max == null || item <= max)) {
c++;
}
}
return c;
}
countRange(arr, 10, 19); // count x >= 10 and x <= 19
countRange(arr, 10, null); // count x >= 10
countRange(arr, null, 30); // count x <= 30

Implementation of Luhn algorithm

I am trying to implement simple validation of credit card numbers. I read about the Luhn algorithm on Wikipedia:
Counting from the check digit, which is the rightmost, and moving
left, double the value of every second digit.
Sum the digits of the products (e.g., 10: 1 + 0 = 1, 14: 1 + 4 = 5)
together with the undoubled digits from the original number.
If the total modulo 10 is equal to 0 (if the total ends in zero)
then the number is valid according to the Luhn formula; else it is
not valid.
On Wikipedia, the description of the Luhn algorithm is very easily understood. However, I have also seen other implementations of the Luhn algorithm on Rosetta Code and elsewhere (archived).
Those implementations work very well, but I am confused about why they can use an array to do the work. The array they use seems to have no relation with Luhn algorithm, and I can't see how they achieve the steps described on Wikipedia.
Why are they using arrays? What is the significance of them, and how are they used to implement the algorithm as described by Wikipedia?
Unfortunately none of the codes above worked for me. But I found on GitHub a working solution
// takes the form field value and returns true on valid number
function valid_credit_card(value) {
// accept only digits, dashes or spaces
if (/[^0-9-\s]+/.test(value)) return false;
// The Luhn Algorithm. It's so pretty.
var nCheck = 0, nDigit = 0, bEven = false;
value = value.replace(/\D/g, "");
for (var n = value.length - 1; n >= 0; n--) {
var cDigit = value.charAt(n),
nDigit = parseInt(cDigit, 10);
if (bEven) {
if ((nDigit *= 2) > 9) nDigit -= 9;
}
nCheck += nDigit;
bEven = !bEven;
}
return (nCheck % 10) == 0;
}
the array [0,1,2,3,4,-4,-3,-2,-1,0] is used as a look up array for finding the difference between a number in 0-9 and the digit sum of 2 times its value. For example, for number 8, the difference between 8 and (2*8) = 16 -> 1+6 = 7 is 7-8 = -1.
Here is graphical presentation, where {n} stand for sum of digit of n
[{0*2}-0, {1*2}-1, {2*2}-2, {3*2}-3, {4*2}-4, {5*2}-5, {6*2}-6, {7*2}-7....]
| | | | | | | |
[ 0 , 1 , 2 , 3 , 4 , -4 , -3 , -2 ....]
The algorithm you listed just sum over all the digit and for each even spot digit, look up the the difference using the array, and apply it to the total sum.
Compact Luhn validator:
var luhn_validate = function(imei){
return !/^\d+$/.test(imei) || (imei.split('').reduce(function(sum, d, n){
return sum + parseInt(((n + imei.length) %2)? d: [0,2,4,6,8,1,3,5,7,9][d]);
}, 0)) % 10 == 0;
};
Works fine for both CC and IMEI numbers. Fiddle: http://jsfiddle.net/8VqpN/
Lookup tables or arrays can simplify algorithm implementations - save many lines of code - and with that increase performance... if the calculation of the lookup index is simple - or simpler - and the array's memory footprint is affordable.
On the other hand, understanding how the particular lookup array or data structure came to be can at times be quite difficult, because the related algorithm implementation may look - at first sight - quite different from the original algorithm specification or description.
Indication to use lookup tables are number oriented algorithms with simple arithmetics, simple comparisons, and equally structured repetition patterns - and of course - of quite finite value sets.
The many answers in this thread go for different lookup tables and with that for different algorithms to implement the very same Luhn algorithm. Most implementations use the lookup array to avoid the cumbersome figuring out of the value for doubled digits:
var luhnArr = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9];
//
// ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
// | | | | | | | | | |
//
// - d-igit=index: 0 1 2 3 4 5 6 7 8 9
// - 1st
// calculation: 2*0 2*2 2*2 2*3 2*4 2*5 2*6 2*7 2*8 2*9
// - intermeduate
// value: = 0 = 2 = 4 = 6 = 8 =10 =12 =14 =16 =18
// - 2nd
// calculation: 1+0 1+2 1+4 1+6 1+8
//
// - final value: 0 2 4 6 8 =1 =3 =5 =7 =9
//
var luhnFinalValue = luhnArray[d]; // d is numeric value of digit to double
An equal implementation for getting the luhnFinalValue looks like this:
var luhnIntermediateValue = d * 2; // d is numeric value of digit to double
var luhnFinalValue = (luhnIntermediateValue < 10)
? luhnIntermediateValue // (d ) * 2;
: luhnIntermediateValue - 10 + 1; // (d - 5) * 2 + 1;
Which - with the comments in above true and false terms - is of course simplified:
var luhnFinalValue = (d < 5) ? d : (d - 5) * 2 + 1;
Now I'm not sure if I 'saved' anything at all... ;-) especially thanks the value-formed or short form of if-then-else. Without it, the code may look like this - with 'orderly' blocks
and embedded in the next higher context layer of the algorithm and therefore luhnValue:
var luhnValue; // card number is valid when luhn values for each digit modulo 10 is 0
if (even) { // even as n-th digit from the the end of the string of digits
luhnValue = d;
} else { // doubled digits
if (d < 5) {
luhnValue = d * 2;
} else {
lunnValue = (d - 5) * 2 + 1;
}
}
Or:
var luhnValue = (even) ? d : (d < 5) ? d * 2 : (d - 5) * 2 + 1;
Btw, with modern, optimizing interpreters and (just in time) compilers, the difference is only in the source code and matters only for readability.
Having come that far with explanation - and 'justification' - of the use of lookup tables and comparison to straight forward coding, the lookup table looks now a bit overkill to me. The algorithm without is now quite easy to finish - and it looks pretty compact too:
function luhnValid(cardNo) { // cardNo as a string w/ digits only
var sum = 0, even = false;
cardNo.split("").reverse().forEach(function(dstr){ d = parseInt(dstr);
sum += ((even = !even) ? d : (d < 5) ? d * 2 : (d - 5) * 2 + 1);
});
return (sum % 10 == 0);
}
What strikes me after going through the explanation exercise is that the initially most enticing implementation - the one using reduce() from #kalypto - just lost totally its luster for me... not only because it is faulty on several levels, but more so because it shows that bells and whistles may not always 'ring the victory bell'. But thank you, #kalypto, it made me actually use - and understand - reduce():
function luhnValid2(cardNo) { // cardNo as a string w/ digits only
var d = 0, e = false; // e = even = n-th digit counted from the end
return ( cardNo.split("").reverse().reduce(
function(s,dstr){ d = parseInt(dstr); // reduce arg-0 - callback fnc
return (s + ((e = !e) ? d : [0,2,4,6,8,1,3,5,7,9][d]));
} // /end of callback fnc
,0 // reduce arg-1 - prev value for first iteration (sum)
) % 10 == 0
);
}
To be true to this thread, some more lookup table options have to be mentioned:
how about just adjust varues for doubled digits - as posted by #yngum
how about just everything with lookup tables - as posted by #Simon_Weaver - where also the values for the non-doubled digits are taken from a look up table.
how about just everything with just ONE lookup table - as inspired by the use of an offset as done in the extensively discussed luhnValid() function.
The code for the latter - using reduce - may look like this:
function luhnValid3(cardNo) { // cardNo as a string w/ digits only
var d = 0, e = false; // e = even = n-th digit counted from the end
return ( cardNo.split("").reverse().reduce(
function(s,dstr){ d = parseInt(dstr);
return (s + [0,1,2,3,4,5,6,7,8,9,0,2,4,6,8,1,3,5,7,9][d+((e=!e)?0:10)]);
}
,0
) % 10 == 0
);
}
And for closing lunValid4() - very compact - and using just 'old fashioned' (compatible) JavaScript - with one single lookup table:
function luhnValid4(cardNo) { // cardNo as a string w/ digits only
var s = 0, e = false, p = cardNo.length; while (p > 0) { p--;
s += "01234567890246813579".charAt(cardNo.charAt(p)*1 + ((e=!e)?0:10)) * 1; }
return (s % 10 == 0);
}
Corollar: Strings can be looked at as lookup tables of characters... ;-)
A perfect example of a nice lookup table application is the counting of set bits in bits lists - bits set in a a (very) long 8-bit byte string in (an interpreted) high-level language (where any bit operations are quite expensive). The lookup table has 256 entries. Each entry contains the number of bits set in an unsigned 8-bit integer equal to the index of the entry. Iterating through the string and taking the unsigned 8-bit byte equal value to access the number of bits for that byte from the lookup table. Even for low-level language - such as assembler / machine code - the lookup table is the way to go... especially in an environment, where the microcode (instruction) can handle multiple bytes up to 256 or more in an (single CISC) instruction.
Some notes:
numberString * 1 and parseInt(numberStr) do about the same.
there are some superfluous indentations, parenthesis,etc... supporting my brain in getting the semantics quicker... but some that I wanted to leave out, are actually required... when
it comes to arithmetic operations with short-form, value-if-then-else expressions as terms.
some formatting may look new to you; for examples, I use the continuation comma with the
continuation on the same line as the continuation, and I 'close' things - half a tab - indented to the 'opening' item.
All formatting is all done for the human, not the computer... 'it' does care less.
algorithm datastructure luhn lookuptable creditcard validation bitlist
A very fast and elegant implementation of the Luhn algorithm following:
const isLuhnValid = function luhn(array) {
return function (number) {
let len = number ? number.length : 0,
bit = 1,
sum = 0;
while (len--) {
sum += !(bit ^= 1) ? parseInt(number[len], 10) : array[number[len]];
}
return sum % 10 === 0 && sum > 0;
};
}([0, 2, 4, 6, 8, 1, 3, 5, 7, 9]);
console.log(isLuhnValid("4112344112344113".split(""))); // true
console.log(isLuhnValid("4112344112344114".split(""))); // false
On my dedicated git repository you can grab it and retrieve more info (like benchmarks link and full unit tests for ~50 browsers and some node.js versions).
Or you can simply install it via bower or npm. It works both on browsers and/or node.
bower install luhn-alg
npm install luhn-alg
If you want to calculate the checksum, this code from this page is very concise and in my random tests seems to work.
NOTE: the verification algorithmns on this page do NOT all work.
// Javascript
String.prototype.luhnGet = function()
{
var luhnArr = [[0,1,2,3,4,5,6,7,8,9],[0,2,4,6,8,1,3,5,7,9]], sum = 0;
this.replace(/\D+/g,"").replace(/[\d]/g, function(c, p, o){
sum += luhnArr[ (o.length-p)&1 ][ parseInt(c,10) ]
});
return this + ((10 - sum%10)%10);
};
alert("54511187504546384725".luhnGet());​
Here's my findings for C#
function luhnCheck(value) {
return 0 === (value.replace(/\D/g, '').split('').reverse().map(function(d, i) {
return +['0123456789','0246813579'][i % 2][+d];
}).reduce(function(p, n) {
return p + n;
}) % 10);
}
Update: Here's a smaller version w/o string constants:
function luhnCheck(value) {
return !(value.replace(/\D/g, '').split('').reverse().reduce(function(a, d, i) {
return a + d * (i % 2 ? 2.2 : 1) | 0;
}, 0) % 10);
}
note the use of 2.2 here is to make doubling d roll over with an extra 1 when doubling 5 to 9.
Code is the following:
var LuhnCheck = (function()
{
var luhnArr = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9];
return function(str)
{
var counter = 0;
var incNum;
var odd = false;
var temp = String(str).replace(/[^\d]/g, "");
if ( temp.length == 0)
return false;
for (var i = temp.length-1; i >= 0; --i)
{
incNum = parseInt(temp.charAt(i), 10);
counter += (odd = !odd)? incNum : luhnArr[incNum];
}
return (counter%10 == 0);
}
})();
The variable counter is the sum of all the digit in odd positions, plus the double of the digits in even positions, when the double exceeds 10 we add the two numbers that make it (ex: 6 * 2 -> 12 -> 1 + 2 = 3)
The Array you are asking about is the result of all the possible doubles
var luhnArr = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9];
0 * 2 = 0 --> 0
1 * 2 = 2 --> 2
2 * 2 = 4 --> 4
3 * 2 = 6 --> 6
4 * 2 = 8 --> 8
5 * 2 = 10 --> 1+0 --> 1
6 * 2 = 12 --> 1+2 --> 3
7 * 2 = 14 --> 1+4 --> 5
8 * 2 = 16 --> 1+6 --> 7
9 * 2 = 18 --> 1+8 --> 9
So for example
luhnArr[3] --> 6 (6 is in 3rd position of the array, and also 3 * 2 = 6)
luhnArr[7] --> 5 (5 is in 7th position of the array, and also 7 * 2 = 14 -> 5 )
Another alternative:
function luhn(digits) {
return /^\d+$/.test(digits) && !(digits.split("").reverse().map(function(checkDigit, i) {
checkDigit = parseInt(checkDigit, 10);
return i % 2 == 0
? checkDigit
: (checkDigit *= 2) > 9 ? checkDigit - 9 : checkDigit;
}).reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
}) % 10);
}
Alternative ;) Simple and Best
<script>
// takes the form field value and returns true on valid number
function valid_credit_card(value) {
// accept only digits, dashes or spaces
if (/[^0-9-\s]+/.test(value)) return false;
// The Luhn Algorithm. It's so pretty.
var nCheck = 0, nDigit = 0, bEven = false;
value = value.replace(/\D/g, "");
for (var n = value.length - 1; n >= 0; n--) {
var cDigit = value.charAt(n),
nDigit = parseInt(cDigit, 10);
if (bEven) {
if ((nDigit *= 2) > 9) nDigit -= 9;
}
nCheck += nDigit;
bEven = !bEven;
}
return (nCheck % 10) == 0;
}
console.log(valid_credit_card("5610591081018250"),"valid_credit_card Validation");
</script>
Best Solution here
http://plnkr.co/edit/34aR8NUpaKRCYpgnfUbK?p=preview
with all test cases passed according to
http://www.paypalobjects.com/en_US/vhelp/paypalmanager_help/credit_card_numbers.htm
and the credit goes to
https://gist.github.com/DiegoSalazar/4075533
const LuhnCheckCard = (number) => {
if (/[^0-9-\s]+/.test(number) || number.length === 0)
return false;
return ((number.split("").map(Number).reduce((prev, digit, i) => {
(!(( i & 1 ) ^ number.length)) && (digit *= 2);
(digit > 9) && (digit -= 9);
return prev + digit;
}, 0) % 10) === 0);
}
console.log(LuhnCheckCard("4532015112830366")); // true
console.log(LuhnCheckCard("gdsgdsgdsg")); // false
I worked out the following solution after I submitted a much worse one for a test..
function valid(number){
var splitNumber = parseInt(number.toString().split(""));
var totalEvenValue = 0;
var totalOddValue = 0;
for(var i = 0; i < splitNumber.length; i++){
if(i % 2 === 0){
if(splitNumber[i] * 2 >= 10){
totalEvenValue += splitNumber[i] * 2 - 9;
} else {
totalEvenValue += splitNumber[i] * 2;
}
}else {
totalOddValue += splitNumber[i];
}
}
return ((totalEvenValue + totalOddValue) %10 === 0)
}
console.log(valid(41111111111111111));
I recently wrote a solution using Javascript, I leave the code here for anyone who can help:
// checksum with Luhn Algorithm
const luhn_checksum = function(strIn) {
const len = strIn.length;
let sum = 0
for (let i = 0; i<10; i += 1) {
let factor = (i % 2 === 1) ? 2: 1
const v = parseInt(strIn.charAt(i), 10) * factor
sum += (v>9) ? (1 + v % 10) : v
}
return (sum * 9) % 10
}
// teste exampple on wikipedia:
// https://en.wikipedia.org/wiki/Luhn_algorithm
const strIn = "7992739871"
// The checksum of "7992739871" is 3
console.log(luhn_checksum(strIn))
If you understand this code above, you will have no problem converting it to any other language.
For example in python:
def nss_checksum(nss):
suma = 0
for i in range(10):
factor = 2 if (i % 2 == 1) else 1
v = int(nss[i]) * factor
suma += (1 + v % 10) if (v >9) else v
return (suma * 9) % 10
For more info, check this:
https://en.wikipedia.org/wiki/Luhn_algorithm
My Code(En español):
https://gist.github.com/fitorec/82a3e27fae3bab709a07c19c71c3a8d4
def validate_credit_card_number(card_number):
if(len(str(card_number))==16):
group1 = []
group1_double = []
after_group_double = []
group1_sum = 0
group2_sum = 0
group2 = []
total_final_sum = 0
s = str(card_number)
list1 = [int(i) for i in list(s)]
for i in range(14, -1, -2):
group1.append(list1[i])
for x in group1:
b = 0
b = x * 2
group1_double.append(b)
for j in group1_double:
if(j > 9):
sum_of_digits = 0
alias = str(j)
temp1 = alias[0]
temp2 = alias[1]
sum_of_digits = int(temp1) + int(temp2)
after_group_double.append(sum_of_digits)
else:
after_group_double.append(j)
for i in after_group_double:
group1_sum += i
for i in range(15, -1, -2):
group2.append(list1[i])
for i in group2:
group2_sum += i
total_final_sum = group1_sum + group2_sum
if(total_final_sum%10==0):
return True
else:
return False
card_number= 1456734512345698 #4539869650133101 #1456734512345698 # #5239512608615007
result=validate_credit_card_number(card_number)
if(result):
print("credit card number is valid")
else:
print("credit card number is invalid")

Categories

Resources