Random Code Generator: Guide in JavaScript, Python, Go, C#, Java

Introduction

In this guide, I will show you how to create a random code generator in different programming languages: JavaScript, Python, Go, C#, and Java. I will walk you step by step through the process of developing a customizable function that can generate codes of varying lengths, with optional prefixes, suffixes, and special characters. We will start from the basics to ensure that the guide is accessible even to beginners.


Project Requirements

The function we are about to create will have the following requirements:

  • Input:
    • Number of characters (minimum = 3, default = 10)
    • Number of codes to generate (optional, default = 1)
    • Prefix and suffix (optional, default = empty string)
    • Uppercase, Lowercase, Numbers, and Special Characters (all optional, default = true)
  • Output: A list of generated codes according to the specified parameters.

1. Random Code Generator in JavaScript

Development Environment

To create the generator in JavaScript, you can use Node.js or insert the code directly into a web page.

JavaScript Code Snippet

function generateRandomCode(length = 10, count = 1, prefix = "", suffix = "", options = {}) {
  const defaultOptions = { uppercase: true, lowercase: true, numbers: true, specialChars: true };
  options = { ...defaultOptions, ...options };
  
  const charSets = {
    uppercase: "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
    lowercase: "abcdefghijklmnopqrstuvwxyz",
    numbers: "0123456789",
    specialChars: "!@#$%^&*()-_=+[]{}<>?"
  };

  let availableChars = "";
  if (options.uppercase) availableChars += charSets.uppercase;
  if (options.lowercase) availableChars += charSets.lowercase;
  if (options.numbers) availableChars += charSets.numbers;
  if (options.specialChars) availableChars += charSets.specialChars;

  if (availableChars.length === 0) throw new Error("You must select at least one character set.");

  const generateCode = () => {
    let code = "";
    for (let i = 0; i < length; i++) {
      code += availableChars.charAt(Math.floor(Math.random() * availableChars.length));
    }
    return `${prefix}${code}${suffix}`;
  };

  return Array.from({ length: count }, generateCode);
}

// Example usage
console.log(generateRandomCode(10, 5, "PRE-", "-SUF", { uppercase: true, numbers: true, specialChars: false }));

Example Output

PRE-XA9DZL5F7-SUF
PRE-7GLF2PXD3J-SUF
PRE-ZY6DFJ3Q89-SUF
PRE-3LKD9ZFA7X-SUF
PRE-5DJQAZ9F2L-SUF

2. Random Code Generator in Python

Development Environment

Make sure Python is installed. You can use any text editor or an IDE like PyCharm or VSCode.

Python Code Snippet

import random
import string

def generate_random_code(length=10, count=1, prefix="", suffix="", uppercase=True, lowercase=True, numbers=True, special_chars=True):
    char_sets = {
        "uppercase": string.ascii_uppercase,
        "lowercase": string.ascii_lowercase,
        "numbers": string.digits,
        "special_chars": "!@#$%^&*()-_=+[]{}<>?"
    }
    
    available_chars = ""
    if uppercase:
        available_chars += char_sets["uppercase"]
    if lowercase:
        available_chars += char_sets["lowercase"]
    if numbers:
        available_chars += char_sets["numbers"]
    if special_chars:
        available_chars += char_sets["special_chars"]

    if not available_chars:
        raise ValueError("You must select at least one character set.");

    def generate_code():
        return prefix + "".join(random.choice(available_chars) for _ in range(length)) + suffix

    return [generate_code() for _ in range(count)]

# Example usage
print(generate_random_code(10, 5, "PRE-", "-SUF", uppercase=True, lowercase=False, special_chars=False))

Example Output

PRE-ZND394FQW-SUF
PRE-DKJ382FPL-SUF
PRE-LFJ920ZQR-SUF
PRE-XAP348NDF-SUF
PRE-QWL738DFX-SUF

3. Random Code Generator in Go

Development Environment

To run Go code, make sure you have Go installed and set up your environment.

Go Code Snippet

package main

import (
    "crypto/rand"
    "fmt"
    "math/big"
)

func generateRandomCode(length int, count int, prefix string, suffix string, uppercase bool, lowercase bool, numbers bool, specialChars bool) []string {
    charSets := map[string]string{
        "uppercase": "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
        "lowercase": "abcdefghijklmnopqrstuvwxyz",
        "numbers":   "0123456789",
        "specialChars": "!@#$%^&*()-_=+[]{}<>?",
    }

    availableChars := ""
    if uppercase {
        availableChars += charSets["uppercase"]
    }
    if lowercase {
        availableChars += charSets["lowercase"]
    }
    if numbers {
        availableChars += charSets["numbers"]
    }
    if specialChars {
        availableChars += charSets["specialChars"]
    }

    if len(availableChars) == 0 {
        panic("You must select at least one character set.")
    }

    generateCode := func() string {
        code := ""
        for i := 0; i < length; i++ {
            randIndex, _ := rand.Int(rand.Reader, big.NewInt(int64(len(availableChars))))
            code += string(availableChars[randIndex.Int64()])
        }
        return prefix + code + suffix
    }

    codes := make([]string, count)
    for i := 0; i < count; i++ {
        codes[i] = generateCode()
    }
    return codes
}

func main() {
    codes := generateRandomCode(10, 5, "PRE-", "-SUF", true, true, true, false)
    for _, code := range codes {
        fmt.Println(code)
    }
}

Example Output

PRE-FKL29JD73-SUF
PRE-ZPL08FND3-SUF
PRE-XJF27DL93-SUF
PRE-WQL38FJP4-SUF
PRE-9DFXZL728-SUF

4. Random Code Generator in C#

Development Environment

Use Visual Studio or Visual Studio Code with the .NET SDK.

C# Code Snippet

using System;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        var codes = GenerateRandomCode(10, 5, "PRE-", "-SUF", true, true, true, false);
        foreach (var code in codes)
        {
            Console.WriteLine(code);
        }
    }

    static string[] GenerateRandomCode(int length = 10, int count = 1, string prefix = "", string suffix = "", bool uppercase = true, bool lowercase = true, bool numbers = true, bool specialChars = true)
    {
        string availableChars = "";
        if (uppercase) availableChars += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        if (lowercase) availableChars += "abcdefghijklmnopqrstuvwxyz";
        if (numbers) availableChars += "0123456789";
        if (specialChars) availableChars += "!@#$%^&*()-_=+[]{}<>?";

        if (string.IsNullOrEmpty(availableChars)) throw new ArgumentException("You must select at least one character set.");

        var random = new Random();
        string GenerateCode()
        {
            var code = new StringBuilder();
            for (int i = 0; i < length; i++)
            {
                code.Append(availableChars[random.Next(availableChars.Length)]);
            }
            return prefix + code + suffix;
        }

        var codes = new string[count];
        for (int i = 0; i < count; i++)
        {
            codes[i] = GenerateCode();
        }
        return codes;
    }
}

Example Output

PRE-DFJ83WPL7-SUF
PRE-KLZ92FJD8-SUF
PRE-QWP38DJF2-SUF
PRE-FJL49XZQ7-SUF
PRE-DJX37FPL8-SUF

5. Random Code Generator in Java

Development Environment

Make sure you have the JDK installed and use an IDE like IntelliJ IDEA or Eclipse.

Java Code Snippet

import java.util.Random;

public class RandomCodeGenerator {
    public static void main(String[] args) {
        String[] codes = generateRandomCode(10, 5, "PRE-", "-SUF", true, true, true, false);
        for (String code : codes) {
            System.out.println(code);
        }
    }

    public static String[] generateRandomCode(int length, int count, String prefix, String suffix, boolean uppercase, boolean lowercase, boolean numbers, boolean specialChars) {
        String availableChars = "";
        if (uppercase) availableChars += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        if (lowercase) availableChars += "abcdefghijklmnopqrstuvwxyz";
        if (numbers) availableChars += "0123456789";
        if (specialChars) availableChars += "!@#$%^&*()-_=+[]{}<>?";

        if (availableChars.isEmpty()) throw new IllegalArgumentException("You must select at least one character set.");

        Random random = new Random();
        String[] codes = new String[count];
        for (int i = 0; i < count; i++) {
            StringBuilder code = new StringBuilder();
            for (int j = 0; j < length; j++) {
                code.append(availableChars.charAt(random.nextInt(availableChars.length())));
            }
            codes[i] = prefix + code.toString() + suffix;
        }
        return codes;
    }
}

Example Output

PRE-XJP92FQL3-SUF
PRE-DFL38WZP7-SUF
PRE-ZPQ48JFL2-SUF
PRE-FQL72XD93-SUF
PRE-JWP83XZL9-SUF

Conclusion

In this guide, we have seen how to create a random code using different programming languages: JavaScript, Python, Go, C#, and Java. Each language offers specific tools to generate random codes cleanly and professionally. Now you can choose the language that best suits your needs and integrate this function into your projects!


Additional Resources

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top