make a name unique

Hi

I need a way of making a name unique (i.e. making it a unique ID) but still retaining some features of the name to make it recognisable. The code below works by appendix a random suffix to the name:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <ctype.h>
#include <stdlib.h>

std::vector<std::string> existing;


std::string generateID(std::string nm) {
    const int ID_NM_MAX_SZ = 7, ID_TARGET_SZ = 10;
    std::string ID;
    
    for(char c : nm) {  
        if (isalnum(c) && ID.size() < ID_NM_MAX_SZ) {  // extract up to ID_NM_MAX_SZ alphanumeric characters
            ID += toupper(c);  //convert to upper and add to ID
        }
    }

    static const char alphanum[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    while (true) {
        std::string rand_suffix;
        for(int i = 0; i < ID_TARGET_SZ - ID.size(); i++) {  // generate remaining chars for ID...
            rand_suffix += alphanum[rand() % (sizeof(alphanum) - 1)]; // randomly
        }
        if (std::find(existing.begin(),existing.end(),ID + rand_suffix) == existing.end()) {  // keep looping until we find an available ID
            ID+= rand_suffix;
            
            existing.push_back(ID); // add to register of unique IDs
            return ID;
        }
    }
}

int main () {
 
 std::cout << generateID("Microsoft Inc.") <<std::endl;
  std::cout << generateID("Microsoft Inc.");


}


I think this works but I just wondered if there are any other common approaches to this problem?

Thanks
Last edited on
What's wrong with just appending an incrementing integer?
As Salem says, some kind of incrementing integer is a pretty common way. Make it static so that the value is retained between calls to the function, and you can also make it atomic if you need different threads to be able to make use it. Something like:

1
2
3
4
5
6
std::string generateID(std::string nm) 
{
  static std::atomic<int> serialNumber;
 
  return (nm + to_string(serialNumber++));
}


If you worry about going all the way round the numbers and repeating, well, if you use a 64 bit value and you do a billion a second, you'll die long before you run out of numbers and it won't be your problem anymore.
Topic archived. No new replies allowed.