Write a function that guarantees to never return the same value twice

Technology CommunityCategory: ConcurrencyWrite a function that guarantees to never return the same value twice
VietMX Staff asked 3 years ago
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.

  1. Just toss a simple (threadsafe) counter behind some communication endpoint:
    long x = long.MinValue;
    public long ID(){
       return Interlocked.Increment(ref x);
    }
  2. 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?
  3. 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.