Search code examples
c++arraysalgorithmlistverification

Algorithm - Checking if number is already on list


I'm trying to create a kind of supermarket software and I came up with a problem.

When I add a client I immediately say it's ID is the next one on the list, however if the list was manually altered it will create duplicate IDs so I was trying to find a way for the ID to be the next available ID. However if the IDs list is like this:

6

5

1

2

It will attribute the ID 6 which is not available...

How can I only change it's ID if a full run of the vector finds no equal number?

ID = clientsV.size() + 1;
for (unsigned int g = 0; i < clientsV.size(); g++)
    {
        if (ID == clientsV.at(g).getClientID)
        ID++;
    };

Solution

  • first, using the size for ID is indeed not fault tolerant.

    a neat concept is to use random IDs, if your random field is big enough the chances for collisions are extremely small.

    for example, one could use the timestamp's MD5 or uuid as IDs. beside being much more efficient than re-searching the (hopefully very large) list of your clients, it also has an enormous advantage when scaling: you don't have one authority that issues new IDs that all components rely on so that you could distribute the creation of new clients over many isolated servers.

    this may be addressing an issue you don't yet have but it's a nice future proof approach