DEV Community

Discussion on: Custom Card Number Verification System Challenge

Collapse
 
kevinmungai profile image
Kevin Mungai

Thank you for contribution.

I have really tried my best to understand, but have failed.

Could you use examples?

Collapse
 
filipe_mdsr profile image
Filipe Ramalho • Edited

Actually I had an error. You shouldn't convert the digit. And instead modulo through 7.

For 9999|8

  1. 9999 % 7 = 3 //First you modulo through 7
  2. 8 - 3 = 5 //Then you subtract the result from the checksum.
  3. 5 % 7 = 5 //Then you modulo that through 7.

The end result isn't 0, so the digit isn't valid

For 1234|2

  1. 1234 % 7 = 2 //First you modulo through 7
  2. 2 - 2 = 0 //Then you subtract the result from the checksum.
  3. 0 % 7 = 0 //Then you modulo that through 7

The end result is 0, so the digit is valid

For 1169|7

1.1169 % 7 = 0 //If you modulo through 7, when the digit sum is 7 instead 0 comes out, so you can consider 0=7.

  1. 7 - 0 = 7
  2. 7 % 7 = 0 //If you modulo 0 or 7 through 7, the result is 0.

The end result is 0, so the digit is valid

Updated code

boolean checkdigit(int digit,int checksum):     
    int sum = digit % 7 //% is the modulo operator
    if(sum == 0):
        sum = 7
    return checksum - sum == 0

You can also consider 0 and 7 equal and spare the conversion from 0 to 7:

boolean checkdigit(int digit,int checksum): 
    int sum = digit % 7 //% is the modulo operator
    return checksum - sum == 0 || checksum - sum == 7

Or you could modulo the difference through 7. The difference must be either 7 or 0 and both have the same result for modulo 7.

boolean checkdigit(int digit,int checksum): 
    int sum = digit % 7 //% is the modulo operator
    return (checksum - sum) % 7 == 0

So in one line it would look like this

boolean check = (checksum - digit % 7 ) % 7 == 0
x digitsum(x) x%7
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
6 6 6
7 7 0
8 1 1
9 2 2
10 3 3
11 4 4
12 5 5
13 6 6
14 7 0
Thread Thread
 
kevinmungai profile image
Kevin Mungai • Edited

Thank you for clarifying. I have now understood.

It is actually a really neat solution it basically reduces the code to just two functions.

(defn is-valid-modified?
  [number]
  (let [first-four (quot number 10)
        check-sum (rem number 10)]
    (-> first-four
        (mod 7)
        (- check-sum)
        (mod 7)
        (= 0))))

user> (is-valid-modified? 10006)
true
user> (is-valid-modified? 99993)
true
user> (is-valid-modified? 99998)
false
user> (is-valid-modified? 12342)
true
user> (is-valid-modified? 11697)
true
(defn validate-scratch-card [card-number]
  (let [f (comp is-valid-modified? #(Integer/parseInt %))]
    (->> (string/split card-number #"(-|\s)")
         (map f)
         (every? true?))))


user> (validate-scratch-card "10006 12342 00081 99998")
false
user> (validate-scratch-card "10006 12342 00081 99993")
true

I have learnt something, thank you.