Reputation: 715
I want to generate 4-digits PIN codes that are at least 2-digits distant from each other.
For example:
Permutation is easy to check but how to check the distance?
Upvotes: 0
Views: 89
Reputation: 17454
If have have no issues with permutation with your given problem description, it seems you only want to check if the digit of each position is having a difference of at least 2.
There are so many ways to do it in Java. One "primitive" way I personally like is using basic math operations:
public boolean isDistantPins (int pinA, int pinB, int requiredSpacedDigits, int distance){
int spacedDigits = 0, aDigit = 0, bDigit = 0;
while(pinA > 0 ){
aDigit = pinA % 10; //get last digit from the right
bDigit = pinB % 10; //get last digit from the right
if(Math.abs(aDigit - bDigit) >= distance) //find difference
spacedDigits ++;
pinA = pinA / 10; //remove last digit from the right
pinB = pinB / 10; //remove last digit from the right
}
return spacedDigits == requiredSpacedDigits;
}
To invoke it:
System.out.println(isDistantPins(5235, 4068, 1, 2));
System.out.println(isDistantPins(5235, 5339, 1, 2));
System.out.println(isDistantPins(5235, 2553, 1, 2));
System.out.println(isDistantPins(5235, 5236, 1, 2));
System.out.println(isDistantPins(5235, 5235, 1, 2));
Output:
true
true
true
false
false
Note that this does not check the permutation. Hence you can run this after your permutation check (which you have no issues) so the codes for checking permutation is not shown here.
Upvotes: 1
Reputation: 287
Calculate the XOR of two numbers. Count the number of set bits.
Upvotes: 0
Reputation: 517
The logic is the following:
/
, %
.Assuming you have a way to check for permutations, here's a complete solution:
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
}
}
Upvotes: 1