首页 > 解决方案 > 如何生成 2 位远程 PIN 码?

问题描述

我想生成彼此相距至少 2 位的 4 位 PIN 码。

例如:

排列很容易检查,但如何检查距离?

标签: java

解决方案


逻辑如下:

  • 检查pin1是否是排列
  • /使用,检查 pin1 的每个数字与 pin2 相同位置的数字%
  • 计算相同数字的数量。
  • 根据它们的数量返回真/假。

假设您有办法检查排列,这里有一个完整的解决方案:

class Solution {
    public static void main(String[] args) {
        /*
         * 5235 and 4068 is OK
         * 5235 and 5339 is OK
         * 5235 and 2553 is OK
         * 5235 and 5236 is NOT OK
         * 5325 and 5235 is NOT OK (permutation)
         */

        // threshold is the maximum number of digits that can be the same
        // while the pin1, pin2 are distant enough; in this case 2
        int threshold = 2;
        int pinLength = 4;

        System.out.println(areDistant(5235, 4068, threshold, pinLength));
        System.out.println(areDistant(5235, 5339, threshold, pinLength));
        System.out.println(areDistant(5235, 2553, threshold, pinLength));
        System.out.println(areDistant(5235, 5236, threshold, pinLength));
        System.out.println(areDistant(5325, 5235, threshold, pinLength));
    }

    public static boolean areDistant(int pin1, int pin2, int threshold, int pinLength) {
        if (isPermutation(pin1, pin2))
            return false;

        int sameDigits = 0;
        int ithDigit1, ithDigit2;
        for (int i=0; i<pinLength; i++) {
            ithDigit1 = (int) (pin1 / Math.pow(10, i)) % 10;
            ithDigit2 = (int) (pin2 / Math.pow(10, i)) % 10;
            // System.out.println(ithDigit1);
            // System.out.println(ithDigit2);
            if ( ithDigit1 == ithDigit2)
                sameDigits += 1;
        }
        return sameDigits <= threshold;
    }

    private static  boolean isPermutation(int pin1, int pin2) {
        return false;
        // fill the code here
    }
}

推荐阅读