Computing Moon algorithm with Java 8 thread

I am trying to check IMEI number using Stream API help in Java 8.

private void ValidateIMEI() {
    field //a field holding an IMEI Number
            .getText().chars()
            .map(this::ConvertASCIIToNumer);
}

The part I'm stuck with is doubling an even number and dividing by 10.

First I tried the traditional loop:

private void ValidateIMEI() {
    int[] numbers = field //a field holding an IMEI Number
            .getText().chars()
            .map(this::ConvertASCIIToNumer).toArray();

    int sum = 0;
    for (int i = 0; i < numbers.length; i++) {
        //Double the even number and divide it by 10. add quotient and remainder
        if ((numbers[i]+1) % 2 == 0) {
            numbers[i] = numbers[i] * 2;
            numbers[i] = numbers[i] / 10 + numbers[i] % 10;
        }
        sum += numbers[i];
    }

    if (sum%10==0) {
        status.setText("Valid");
    }
    else{
        status.setText("InValid");
    }        
}

But the code is broken and most specifically uses a For loop, which I don't want.

So, can anyone help implement the Luhn algorithm using only the Stream API in Java 8?

Code for ConvertASCIIToNumer:

private int ConvertASCIIToNumer(int value) {
    return Character.digit(value, 10);
}
+4
source share
2 answers

, , . , IntStream :

boolean isValid =
    IntStream.range(0,numbers.length)
             .map (i -> (((i%2) ^ (numbers.length%2)) == 0) ? ((2*numbers[i])/10+(2*numbers[i])%10) : numbers[i])
             .sum() % 10 == 0;

: , , 2.

, :

Index 0 1 2 3 4 5

Digit 1 5 2 5 2 6
      -   -   -

, :

Index 0 1 2 3 4

Digit 1 5 2 5 2
        -   -
+2

, :

String num; // your IMEI number
int[] a = {num.length() % 2 == 0 ? 1 : 2};        // 1 if length even, 2 otherwise
boolean isLuhn = num.chars()
        .map(i -> i - '0')         // convert to the int equivalent
        .map(n -> n * (a[0] = a[0] == 1 ? 2 : 1)) // multiply by 1, 2 alternating
        .map(n -> n > 9 ? n - 9 : n)              // handle sum of digits
        .sum() % 10 == 0;                         // mod 10 should be zero

"" int[] int, . , " " ; , ( ) !

+2

Source: https://habr.com/ru/post/1614922/


All Articles