Venkata
Venkata

Reputation: 513

Generating unique number

I have three variables of int32 data type in C++. I want to generate unique number for combination of three int32 numbers in C++. For example I have int iVal1, int iVal2, and int iVal3. Is there any algorithm to do this?

In order to avoid confusion in question I will rephrase the question. Basically I want to generate a unique number with three integers because I want to store this number as a key in map to retrieve the data.

Any suggestions? Thanks.

Upvotes: 1

Views: 2186

Answers (5)

user503194
user503194

Reputation: 21

You can use a good hash function.

Upvotes: 2

pmg
pmg

Reputation: 108968

concatenate the numbers together for a number with 3 times as many bits as a int has (96 bits)

number 1: 0xDEADFACE; number 2: 0xF00BA4; number 3: 42

result: 0xDEADFACE00F00BA40000002A


Edit: example usage that returns composes the new number to a string

#include <stdio.h>

/* writes a, b, c into dst
** dst must have enough space for the result */
char *concat3(char *dst, unsigned a, unsigned b, unsigned c) {
    sprintf(dst, "%08x%08x%08x", a, b, c);
    return dst;
}

/* usage */
int main(void) {
    char n3[25]; /* 25 = 3*8 for each integer + 1 for terminating null */
    concat3(n3, 0xDEADFACE, 0xF00BA4, 42);
    printf("result is 0x%s\n", n3);
    return 0;
}

Sample run

$ ./a.out
result is 0xdeadface00f00ba40000002a

Upvotes: 1

Kane
Kane

Reputation: 13

I think i understand. Venkata has a three numbers collection. Ex: 42, 35, 127. For each combination of these he needs a unique number. Ex:

int a[2] = {25, 63, 12};
int b[2] = {149, 28, 56};
GetNumber(a) != GetNumber(b)

and GetNumber(a) will always == GetNumber(a), so no random generators.

Upvotes: 0

Alex Reynolds
Alex Reynolds

Reputation: 96927

#include <stdint.h>
#include <time.h>
#include <limits.h>

int main (int argc, char **argv) {
    uint32_t firstInt, secondInt, thirdInt;

    srandom(time(NULL)); /* seed RNG */

    firstInt = random(UINT32_MAX);
    secondInt = random(UINT32_MAX);
    thirdInt = random(UINT32_MAX);

    /* do something with unsigned ints */

    return 0;
}

gregor is correct that you will not get a unique value from an algebraic combination of three (or even two) integers. But it's difficult to know what you're really after from the wording of your question. If you really want a unique number, look into a UUID.

Upvotes: 0

Peter Stuifzand
Peter Stuifzand

Reputation: 5104

For a computational method you could look here: Linear congruential generator

Another method for generating a unqiue number from three other numbers is addition (works at least once).

int n = x1 + x2 + x3

Now n is a new unique number.

Upvotes: 0

Related Questions