Samir
Samir

Reputation: 79

Generate an unique identifier such as a hash every N minutes. But they have to be the same in N minutes timeframe without storing data

I want to create a unique identifier such as a small hash every N minutes but the result should be the same in the N timeframe without storing data.

Examples when the N minute is 10:

0 > 10  = 25ba38ac9
10 > 20 = 900605583
20 > 30 = 6156625fb
30 > 40 = e130997e3
40 > 50 = 2225ca027
50 > 60 = 3b446db34

Between minute 1 and 10 i get "25ba38ac9" but with anything between 10 and 20 i get "900605583" etc.

I have no start/example code because i have no idea or algorithm i can use to create the desired result.

I did not provide a specific tag or language in this question because i am interested in the logic and not the final code. But i appreciate documented code as a example.

Upvotes: 2

Views: 212

Answers (1)

Stef
Stef

Reputation: 15525

Pick your favourite hash-function h. Pick your favourite string sugar. To get a hash at time t, append the euclidean quotient of t divided by N to sugar, and apply h to it.

Example in python:

h = lambda x: hex(abs(hash(x)))
sugar = 'Samir'

def hash_for_N_minutes(t, N=10):
  return h(sugar + str(t // N))

for t in range(0, 30, 2):
  print(t, hash_for_N_minutes(t, 10))

Output:

0 0xeb3d3abb787c890
2 0xeb3d3abb787c890
4 0xeb3d3abb787c890
6 0xeb3d3abb787c890
8 0xeb3d3abb787c890
10 0x45e2d2a970323e9f
12 0x45e2d2a970323e9f
14 0x45e2d2a970323e9f
16 0x45e2d2a970323e9f
18 0x45e2d2a970323e9f
20 0x334dce1d931e5da8
22 0x334dce1d931e5da8
24 0x334dce1d931e5da8
26 0x334dce1d931e5da8
28 0x334dce1d931e5da8

Weakness of this hash method, and suggested improvement

Of course, nothing stops you from inputting a time in the future. So you can easily answer the question "What will the hash be in exactly one hour ?".

If you want future hashes to be unpredictable, you can combine the value t // N with a real-world value that's dependent on the time, not known in advance, but for which we keep records.

There are two well-known time-series that fit this criterion: values related to the meteo, and values related to the stock market.

See also this 2008 xkcd comic: https://xkcd.com/426/

Upvotes: 2

Related Questions