views:

580

answers:

2

I have searched for an elegant solution, without luck. Ultimately, I need to create a number of unique id's (on a single machine) of a fixed length (of 3 characters) that begin with a letter, and contains only numbers or uppercase letters. (e.g. AXX, where X can be a number or letter)

I am using the mktemp utility to generate the unique ids. The problem: mktemp creates temporary filenames which are case sensitive.

Currently, I store each temporary file generated in a diretory, "GeneratedFile". I then create a case insensitive version of the file, and store it in a directory, "ExistingID". Each time I call mktemp, I check to see if the generated file has a case insensitive counterpart in the ExistingID directory. If it does, I continue to call mktemp until I generate a filename that isn't currently in use as a unique ID.

Is there a better way to do this?

A: 

You don't mention how unique it has to be - unique on a single machine? On a network? Does it have to have letters? If numbers only is okay then a simple approach might be to use the current system timestamp, as long as you don't need more than one unique string at one particular instance in time. Maybe even run it through md5 to convert it to a fixed-length alphanumeric string.

Marc Novakowski
Unique on a single machine. It has to begin with a letter.
Then how about a fixed-letter ("A") followed by a timestamp? You don't mention what language this is in - Java? Bash script?
Marc Novakowski
This is in a Bash script.Could the timestamp generate a two character result?
That wouldn't be very unique, then!
Marc Novakowski
Yeah, that is what I assumed, and why I didn't use the system timestamp.
A: 

This almost seems too easy,

mktemp AXX | tr 'a-z' 'A-Z'

Update

The point that this could generate non-unique names after the tr is a good one, but look, is there any reason hey need to be unique and random? Why not just generate them in lexicographic order?

 # pseudobash, untested
 digit1=0
 digit2=0
 chars="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 function nextName {
      str= "A" chars[digit2] chars[digit1]
      ((digit1++))
      if digit1 > 35
      then
          ((digit2++))
          digit1=0
      fi
      return str
  }
Charlie Martin
The problem with this is, the next time I call mktemp it may generate a duplicate. E.g. it generates ACa then the next time, it generates AcA. mktemp thinks it has generated a new, unique result. But because I need all uppercase letters (ACA) they are the same result for my specifications.