jeudi 14 janvier 2016

Pattern Lock with java, code explanation

I found a code that works in java from this site: TopCoder/PatternLock/PatternLock.java . I have difficulties to understand how the code works.

public class PatternLock {
public int solve(int n, int MOD) {
    int[][] dp = new int[n+1][n+1];
    dp[0][0] = 1;
    int[] count = new int[n+1];
    for (int i = 0; i < n; ++ i) {
        for (int j = 0; j < n; ++ j) {
            if (dp[i][j] == 0) continue;
            int dt = dp[i][j] << 1;
            if (dt >= MOD)
                dt -= MOD;
            dp[i][j+1] += dt;
            if (dp[i][j+1] >= MOD)
                dp[i][j+1] -= MOD;
            if (j+1 != n) {
                dp[i+1][j+1] += (long) dp[i][j] * (n-j) % MOD;
                if (dp[i+1][j+1] >= MOD)
                    dp[i+1][j+1] -= MOD;
            } else {
                count[i+1] += (long) dp[i][j] * (n-j) % MOD;
                if (count[i+1] >= MOD)
                    count[i+1] -= MOD;
            }
        }
    }
    int ret = 0;
    for (int i = 1; i <= n; ++ i) {
        ret += (long) count[i] * count[i] % MOD;
        if (ret >= MOD)
            ret -= MOD;
        if (i != 1) {
            ret += (long) count[i] * count[i-1] % MOD;
            if (ret >= MOD)
                ret -= MOD;
        }
    }
    ret <<= 1;
    if (ret >= MOD)
        ret -= MOD;
    return ret;
}

Actually there's a method called solve as a parameter it takes this :

-- Example 0
1
12345667
2

Where n = 1 , MOD = 12345667 and result is compared with 2. I don't understand how the procedure of checking if a pattern is valid if someone can help me! I understand that this question may seem basic and someone can say learn java, but I have problems understanding the logic of this code!

Aucun commentaire:

Enregistrer un commentaire