iluwatar / 30-seconds-of-java

Collection of reusable tested Java 17 compatible code snippets that you can understand in 30 seconds or less.
https://java-design-patterns.com/snippets.html
MIT License
1.04k stars 408 forks source link

Damm algorithm #114

Open iluwatar opened 3 years ago

iluwatar commented 3 years ago

In error detection, the Damm algorithm is a check digit algorithm that detects all single-digit errors and all adjacent transposition errors.

https://en.wikipedia.org/wiki/Damm_algorithm

stale[bot] commented 1 year ago

This issue has been automatically marked as stale because it has not had recent activity. The issue will be unassigned if no further activity occurs. Thank you for your contributions.

AddeusExMachina commented 1 year ago

Hi, I implemented three snippets of the Damm algorithm validation.

  1. Traditional for loop
    boolean damm(String s) {
    int row = 0;
    for (int i = 0; i < s.length(); i++) {
      row = table[row][s.charAt(i) - '0'];
    }
    return row == 0;
    }
  2. Enhanced for loop
    boolean damm(String s) {
    int row = 0;
    for (var c : s.toCharArray()) {
      row = table[row][c - '0'];
    }
    return row == 0;
    }
  3. Stream
    boolean damm(String s) {
    return s.chars().reduce(0, (row, col) -> table[row][col - '0']) == 0;
    }
stale[bot] commented 1 year ago

This issue has been automatically marked as stale because it has not had recent activity. The issue will be unassigned if no further activity occurs. Thank you for your contributions.

stale[bot] commented 4 months ago

This issue has been automatically marked as stale because it has not had recent activity. The issue will be unassigned if no further activity occurs. Thank you for your contributions.