How to Generate 6 Digit Random Number Elixir?

Hello Friends Today, through this tutorial, I will tell you how to generate a 6 digit Unique random number in Elixir.

Here are two ways to generate a 6-digit random number in Elixir.

Method 1: Using `:rand.uniform` and string manipulation:-

defmodule RandomNumber do
def generate_6_digit_number do

# Generate a random integer between 100000 and 999999 (inclusive)
random_number = :rand.uniform(900000) + 100000

# Convert the integer to a string
string_number = Integer.to_string(random_number)

# Ensure the string has 6 digits by prepending leading zeros if necessary
pad_length = 6 - String.length(string_number)
padded_number = List.duplicate("0", pad_length) ++ string_number

# Convert the padded string back to an integer
padded_number |> String.to_integer
end
end

# Example usage
number = RandomNumber.generate_6_digit_number()
IO.puts "Generated 6-digit number: #{number}"

Explanation:-

1. The `generate_6_digit_number` function uses `:rand.uniform(900000)` to generate a random integer between 1 and 900000 (inclusive).
2. It adds 100000 to the random number to ensure it falls within the range of 100000 to 999999.
3. The integer is converted to a string using `Integer.to_string`.
4. The function calculates the padding length by subtracting the string length from 6.
5. It creates a list with the required number of zeros using `List.duplicate` and concatenates it with the string number.
6. Finally, the padded string is converted back to an integer using `String.to_integer`.