import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;

public class Problem_2_The_Luhn_Algorithm {
    
    public static boolean isValid(String base, String checkDigit) {
        
        String s = base + checkDigit;
        s = s.trim();
        
        int total = 0;
        
        // every other digit (starting from the right)
        for (int i = s.length() - 2; i > -1; i -= 2) {
            
            // that digit multiplied by 2
            int x2 = Integer.parseInt(s.substring(i, i + 1)) * 2;
            String doubled = String.valueOf(x2);
            
            int sumOfDigits = 0;
            
            if (doubled.length() == 2) {
                // add both the digits
                sumOfDigits = Integer.parseInt(doubled.substring(0,1)) + Integer.parseInt(doubled.substring(1));
            } else if (doubled.length() == 1) {
                // add the only digit
                sumOfDigits = Integer.parseInt(doubled.substring(0));
            }
            
            // every iteration, add the sum of the digits to the total sum
            total += sumOfDigits;
        }
        
        // add each of the other, not doubled, numbers to the sum
        for (int i = s.length() - 1; i > -1; i -= 2) {
            total += Integer.parseInt(s.substring(i, i + 1));
        }
        
        // valid if divisible by 10
        if (total % 10 == 0) {
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        
        try {
            ArrayList<String> list = new ArrayList<String>();

            // read in the file to the ArrayList
            Scanner file = new Scanner(new File("C:\\Users\\Mike\\Desktop\\problem_2_the_luhn_algorithm_DATA20.txt"));
            while (file.hasNextLine()) {
               list.add(file.nextLine());
            }
            
            for (String batch : list) { // batch is each line in the file
                for (String base : batch.split("\\s+")) { // bases are the set of numbers in each batch separated by spacing
                    
                    for (int i = 0; i < 10; i++) { // test if any digit from 0-9 is the check digit for the base
                        
                        if (isValid(base, String.valueOf(i))) {
                            System.out.print(i);
                            break;
                        }
                    }
                }
                System.out.println();
            }
                
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Exception");
        }
         
    }
}
