Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

How to generate a random string of 5 characters without importing random library?

+2 votes
asked Mar 16, 2019 by SREEVALLICHALLAPALLI (140 points)
edited Mar 16, 2019 by Admin

2 Answers

0 votes
answered Feb 11 by Chakka Lakshmi priya (140 points)
public class Main {

    public static void main(String[] args) {

        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder result = new StringBuilder();

        for(int i = 0; i < 5; i++) {

            int index = (int)(Math.random() * characters.length());
            result.append(characters.charAt(index));
        }

        System.out.println(result.toString());
    }
}
commented Feb 14 by FRANK MATHEW SAJAN 23BCE8713 (100 points)
Still uses  int index = (int)(Math.random() * characters.length());
0 votes
answered Feb 12 by Jay Jatav (140 points)
import os
import string
import secrets # secrets module is generally available without separate installation

def generate_random_string(length):
    # Define the possible characters
    characters = string.ascii_uppercase + string.digits
    result = ''
    # Read random bytes from the OS
    random_bytes = os.urandom(length * 4) # Read more bytes to ensure enough randomness

    for i in range(length):
        # Use a byte to select a character index securely
        # % len(characters) ensures the index is within the valid range
        index = random_bytes[i] % len(characters)
        result += characters[index]
        
    return result

# Example usage
random_string = generate_random_string(5)
print(random_string)
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and receive answers from other members of the community.
...