Ask a Question

Create groovy script to generate Luhn Algorithm

jwindrum
New Contributor

Create groovy script to generate Luhn Algorithm

I am looking to create a groovy script to generate data that follows the Luhn Algorithm. I need to be able to create Canadian Social Insurance Numbers and Credit Card numbers that are valid for testing. Wondering if anyone has done this before that could help me out please?

3 REPLIES 3
sanj
Super Contributor

here are few useful links

 

https://gist.github.com/mdp/9691528

 approach to java and groovy would be very similar

https://stackoverflow.com/questions/20740444/check-credit-card-validity-using-luhn-algorithm

 

jwindrum
New Contributor

Hi Sanj,

 

I am looking to create the data, rather than validate it. There really are not a lot of resources specific to creation that I've found. One of my coworkers had created a Google app script to generate the data so that it can be used in Sheets, and I've extracted the script, but am having one heck of a time converting it to Groovy. 

 

function RanSin () {
  for (;;){
    var n=9, sum=0, rn, ranSin, nextDigit, total=0;
    var evenDigit = false;
    while (n>0){
      rn = Math.floor(Math.random()*(9-1))+1;   
      sum+=rn;
      if ( n == 1){
        break;
      }
      sum*=10;
      n-=1;
    }
    ranSin=sum;
    while ( ranSin > 0 ) {
      nextDigit = ranSin %10;
      ranSin = Math.floor(ranSin / 10);
      if (evenDigit) {
        nextDigit = 2* nextDigit;
        nextDigit = Math.floor(nextDigit / 10) + (nextDigit % 10); 
      }
      total += nextDigit;
      evenDigit = !evenDigit;
    } 
    if ( 0 == (total%10)){
      return sum; 
      break;
    }
  }
}
larsn
Contributor

 

Read closely  https://en.wikipedia.org/wiki/Luhn_algorithm - about verifying a number against the check digit which is the last digit. I created a function that generated a random number  - one digit shorter than I needed, then ran the Luhn check  to get the check digit and then appended that. 

This example shows a function that returns the check digit in Java

https://github.com/nishan/luhn_java/blob/master/src/org/luhn/Luhn.java

 

FYI, here is another way to verify a number in Groovy

http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#Groovy

cancel
Showing results for 
Search instead for 
Did you mean: