简体   繁体   中英

Testing string for ascending order

I have written a piece of code here to generate a random PIN number of a specified length. The code works fine but I want to add an exception where a PIN would be invalid if it ends up in ascending order. For example if a PIN ended up being 1234, 3456, 4567 they would be invalid PINs.

public static String generatePin(int nmrPinDigits)
{
    String pin = new String();
    NUMBER_PIN_DIGITS = nmrPinDigits;
    for(int i = 0; i < NUMBER_PIN_DIGITS; i += 1) 
    {
        double rnd = Math.random();
        rnd *= 9;
        rnd += 1;
        byte rndByte = (byte)rnd;
        String rndStr = Byte.toString(rndByte);
        pin += rndStr;
    }
    return pin;
}

Edit

Actually the question of the OP is probably more to know if the pin is a sequence. In which case:

char prev = pin.charAt(0);
for (char ch : pin.substring(1).toCharArray()) {
    if (chr - prev != 1) {
        // Not a sequence
        return false;
    }
    prev = chr;
}
// Is a sequence !
return true;

Same goes for descending order, just with -1 as a test value.

The simplest solution would be to compare each random digit generated in your loop to the previous one. If the difference is +1, discard the digit and generate another one.

This is the method to detect ascending or descending string..

public static boolean checkForAscendingOrDescendingPart(String txt, int l)
{
    for (int i = 0; i <= txt.length() - l; ++i)
    {
        boolean success = true;
        char c = txt.charAt(i);
        for (int j = 1; j < l; ++j)
        {
            if (((char) c + j) != txt.charAt(i + j))
            {
                success = false;
                break;
            }
        }
        if (success) return true;

        success = true;

        for (int j = 1; j < l; ++j)
        {
            if (((char) c - j) != txt.charAt(i + j))
            {
                success = false;
                break;
            }
        }
        if (success) return true;
    }
    return false;
}

Call this method before returning pin..and throw exception there..like..

checkForAscendingOrDescendingPart(pin, pin.length());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM