Monthly Archives: September 2013

The Beauty of Unique Alphanumeric Random Codes

My challenge was to generate random codes of variable length and size. The codes should be all unique and build of alphanumeric symbols. I wrote the following function using the build-in function sample():

alpha.rnd <- function(length, size) {
	if(size > 36^length) stop("\n size cannot be greater than 36^length")
	b <- NULL
	repeat {
		a <- NULL	
		for (i in 1:length) {
			a <- paste0(sample(c(letters, 0:9), size, replace = TRUE), a)
		}
		b <- c(a,b)
		if(sum(duplicated(b)) == 0) break
	  	size = sum(duplicated(b))
		b <- b[!duplicated(b)]		
	}
	return(b)
}

Example:

> set.seed(77)
> alpha.rnd(3,5)
[1] "5qk" "94z" "f45" "au8" "qq0"

Enjoy!