0

Can we generate multiple random strings as per regex /^[0-9A-F]$/

I have written the below code, is there any better way to generate it, please do not use any lib, use only java API

public static void printRandomStrings(int numOfStrings){
  
    Random random = new Random();
    char[] chars = {'A','B','C','D','E','F'}; // 6 characters
    
    for(int i=0;i<numOfStrings;i++){
      
      String randomString = "";
      
        for(int j=0;j<4;j++){
        
          int choice = random.nextInt(2); // 0 -1
          
          if(choice == 1){
            randomString= randomString+generateRandomInt(random);
          }else{
            randomString= randomString+generateRandomChar(random,chars);
          }            
        }
      
        System.out.println(randomString);
    }        
  }      
  
  public static int generateRandomInt(Random random){
    return random.nextInt(10);
  }
  
  public static char generateRandomChar(Random random,char[] chars){
    int charIdx = random.nextInt(6);
    return chars[charIdx];
  }
azro
  • 53,056
  • 7
  • 34
  • 70
Bravo
  • 8,589
  • 14
  • 48
  • 85
  • 1
    What do you mean by better? What are your criteria? (speed (don't use java), readability, ...) – gkhaos Apr 20 '21 at 09:28
  • See https://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string – azro Apr 20 '21 at 09:34
  • 1
    Your method always generates 4-character strings. Is that part of the requirement? – k314159 Apr 20 '21 at 11:23
  • Also, note a major flaw in your code is that the six characters 'A' to 'F' have equal chance of appearing as the ten characters '0' to '9'. Because they are fewer, they will be over-represented in your random strings. – k314159 Apr 20 '21 at 11:29

0 Answers0