Problem
Write a function that is guaranteed to never return the same value twice. Assume that this function will be accessed by multiple machines concurrently.
- Just toss a simple (threadsafe) counter behind some communication endpoint:
long x = long.MinValue; public long ID(){ return Interlocked.Increment(ref x); }
- Let interviewer be the one that follow up with those problems:
- Does it need to survive reboots?
- What about hard drive failure?
- What about nuclear war?
- Does it need to be random?
- How random?
- If they made it clear that it has to be unique across reboots and across different machines, I’d give them a function that calls into the standard mechanism for creating a new GUID, whatever that happens to be in the language being used. This is basically the problem that guids solve. Producing a duplicate Guid, no matter its format, is the most difficult lottery on the planet.