0

I want to be able to generate sequential alphanumeric strings of a given length 8. Also, I want the string to start with a specific string let's say "ABC00". Just imagine a license plate starts with a specific string and other generated alphanumeric strings. I have tried a number of things I have seen here and not getting the desired results.

This is what I currently have

import java.security.SecureRandom;
import java.util.Random;

public class RandomString {


    static final String AB = "SCV00" + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    static SecureRandom rnd = new SecureRandom();

    String randomString(int len){
        StringBuilder sb = new StringBuilder(len);
        for(int i = 0; i < len; i++)
            sb.append(AB.charAt(rnd.nextInt(AB.length())));
        return sb.toString();
    }

}

I want my output to look like this. When users provide the number of IDs they want I should be able to generate it. Say, user wants 3 IDs. I should have. So, I just read the requirement properly and there is a slight difference.

Lowercase will be eliminated. This is how the format should look like. The starting string is "CLV0".

CLVO 0001
CLV0 0002
CLV0 0003
:
CLV0 0009
CLV0 000A
CLVO 000B
:
CLV0 000Z
CLV0 0010

This is the actual sequence. It's not random. Kindly help with this

Eritrean
  • 15,851
  • 3
  • 22
  • 28
Curious
  • 72
  • 7
  • What do you mean by _**sequential alphanumeric strings**_ ? – Eritrean Mar 10 '22 at 11:08
  • It should follow an order sort of. Let's say SCV00Axyz, SCV00Apyt, SCV00Buye, etc – Curious Mar 10 '22 at 11:11
  • "It should follow an order sort of", what are the exact rules you expect? Why comes `Axyz` before `Apyt`, and `Buye` at last? – sp00m Mar 10 '22 at 11:16
  • Okay. So, I want the alphabet that Comes immediately after is important. SCV00A"aplhanumericString", SCV00BalphanumericString, SCV00CalphanumericString, etc – Curious Mar 10 '22 at 11:29
  • @Curious The sequence from `0001` to `000Z` is obvious, but what comes after `0010`? Is it `0020`, `0030` and so on? Or is it `0011`, `0012` and so on? Or something else? – Chaosfire Mar 10 '22 at 16:33

2 Answers2

0

I'll assume you need 0000 to 000Z, then 0010, 0011, 0012 and so on. You would need to keep track of the current id you need to generate. Something like this:

public class SequentialString {

    private static final String START = "CLV0";
    private static final String ALPHANUMERIC = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static void main(String[] args) {
        int totalLength = 8;
        int numberOfIds = 111;
        int countRemainingSymbols = totalLength - START.length();
        for (int i = 0; i < numberOfIds; i++) {
            StringBuilder end = new StringBuilder();
            int current = i;//depending on exact case, you would need to keep track of current
            int remainder = current % ALPHANUMERIC.length();//the index of next character
            do {
                end.append(ALPHANUMERIC.charAt(remainder));
                current /= ALPHANUMERIC.length();//update to check if we need to add more characters
                remainder = current % ALPHANUMERIC.length();//update index, only used if more chars are needed
            } while (current > 0);
            int padCount = countRemainingSymbols - end.length();
            StringBuilder result = new StringBuilder(START).append("-");//- is for easier debugging, remove it for your case
            for (int j = 0; j < padCount; j++) {
                result.append("0");
            }
            result.append(end.reverse());
            System.out.println(result);
        }
    }
}

Basically, using current and length of ALPHANUMERIC to calculate next char index, then calculate if more characters are needed, keep looping until no more chars are needed. Note that i am reversing generated sequence(variable end in code) before appending it.

Also note that this solution is not limited to ZZZZ, it can keep generating the sequence even after that.

Chaosfire
  • 4,818
  • 4
  • 8
  • 23
  • Thanks a lot. I am going to update my question now. Kindly check – Curious Mar 10 '22 at 15:12
  • @Curious Check new solution, answer got completely overhauled. – Chaosfire Mar 10 '22 at 17:52
  • This is exactly what I was looking for. Thanks! – Curious Mar 10 '22 at 20:24
  • I want to save this in the db or a tempFile. Such that, when next a user makes the request, it doesn't start all over again. It starts from the last time it stops. Kindly help. Thanks – Curious Mar 15 '22 at 22:28
  • @Curious Make another question, which includes the setup of your program, so people can suggest correct solution. Currently there is not enough information, the best i can help with is that you need to save the value of `current` and start next generation with next value of `current`. – Chaosfire Mar 16 '22 at 07:58
  • here is the link to the new question. Kindly go through it. Thanks https://stackoverflow.com/questions/71504860/how-to-save-alphanumeric-sequence-in-mongodb-and-start-generating-from-the-last – Curious Mar 16 '22 at 22:19
-1

You could leverage UUID here:

String uuid = UUID.randomUUID().toString().replace("-", "");
String randomString = "SCV00" + uuid.substring(0, 5);
System.out.println(randomString);  // SCV00f044d
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360