Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generate random letter and fixed number combination

Tags:

random

rust

I need to generate a random sequence of a single letter and 6 digit combination, example: F841257

I was looking into rand crate, but something doesn't quite work.

extern crate rand;

fn main() {
    println!("{:?}", rand::random::<char>());
}

prints something like '\u{6ae02}' and println!("{}", rand::random::<char>()); produces some weird glyph.

Can someone point me in the right direction of how I could achieve this?

like image 495
Caballero Avatar asked Dec 24 '22 18:12

Caballero


1 Answers

First, a working program:

extern crate rand;

use rand::Rng;

fn main() {
    let mut rng = rand::thread_rng();
    let letter: char = rng.gen_range(b'A', b'Z') as char;
    let number: u32 = rng.gen_range(0, 999999);
    let s = format!("{}{:06}", letter, number);
    println!("{}", s);
}

Next, an explanation.

rand::random::<char>() returns a random value from the whole char range, that is, it may return arbitrary Unicode code point. That's why you see weird glyphs - these are likely values from upper Unicode planes.

You need to define boundaries of what you need to generate. First, you need a letter, then you need six digits. A letter is any character between 'A' and 'Z', and six digits can be represented by a number from 0 to 999999 which is padded with zeros when printing.

So, first, we generate a u8 which corresponds to a letter in ASCII and convert it to char (unfortunately, rand crate does not provide range distribution for chars, so we have to use such indirection).

Second, we generate a u32 between 0 and 999999.

Then we print them in the desired format. Here are a few values which this program generates: V285490, Y865809, A704620.

like image 163
Vladimir Matveev Avatar answered Dec 31 '22 00:12

Vladimir Matveev