Thursday, July 5, 2012

Near random–Converting a sequence no to random no

Q: so the statement of the problem is as follows. I want to generate unique numbers from 1 to Max (say max is Long.MAX_LONG). The generated sequence should not be predictable. SO it means we need to generate uniq random nubers and ensuer they dont repeate. Remember we cannot use current time stamp + some increment number as we have limited range and we need to use it as affectively as possible.

So i wrote a func that transforms a function to (seemingly) random number. Its as follows.

public class NearRandomIncrements {
private static final long salt = 0xABCDEF12345628ACL;
private static final long salt2 = 0xeE72CC072837198DL;

public static void main(String[] s) {
long prev = 0;
for (long i = 1L; i > 0 && i < Long.MAX_VALUE; i++) {
long withSalt = Long.reverseBytes(Long.rotateLeft(i, 31) ^ salt);
long withSalt2 = Long.rotateLeft(withSalt, 17) ^ salt2;
long variation = withSalt2 - prev;
prev = withSalt2;
System.out.println(i + " " + withSalt2 + " variation:" + Math.abs(variation));
}
}
}



This genates the output as follows

1 4835434266867286493 variation:4835434266867286493
2 4763378871852614109 variation:72055395014672384
3 4835436465890542045 variation:72057594037927936
4 4763381070875869661 variation:72055395014672384
5 4835438664913797597 variation:72057594037927936
6 4763383269899125213 variation:72055395014672384
7 4835440863937053149 variation:72057594037927936
8 4763367876736336349 variation:72072987200716800
9 4835425470774264285 variation:72057594037927936
10 4763370075759591901 variation:72055395014672384

So if u closely observe based on variation we see a pattern; and we can predict the next number. But if u see the i=8 part; we see a new variation creeping in. So even if a person gets hold of the sequence he may predict only limited number of numbers only. The solution may not be perfect, but i think its a gud start. What do u think?

No comments:

Post a Comment