I need a random number which I will be storing in the database per record and that (the generated random number)too should not repeat in future. So is Math.random() function is good for that?
Thanks in advance
I need a random number which I will be storing in the database per record and that (the generated random number)too should not repeat in future. So is Math.random() function is good for that?
Thanks in advance
Random is random and statistically it will repeat somewhere in the future. What you can do is combine something unique with a random part - for example use the unix timestamp with a random number.
function getRand(){
return new Date().getTime().toString() + Math.floor(Math.random()*1000000);
}
Math.random()
will not give you a unique number, in general it will not even give you a real random number.
You can try to use a datetime-based random algorythm, or go for a random number and then check if it's already in your database, but both approaches are not 100% save. There is pretty much only one way to ensure the number you store is unique, which is on database level.
You can see here for GUID generator for unique keys for your DB. Also there you can find a lot of good information about random mechanisms
time + increment + random:
var newGuid = (function() {
var guid = parseInt(Math.random() * 36);
return function newGuid() {
return Date.now().toString(36) + (guid++ % 36).toString(36) + Math.random().toString(36).slice(2, 4);
};
})();
If you look at the specs of math.random, you will see that is defined as quasi-random number generator, meaning, it is not REALLY random. Moreover, a real random number generator will for sure repeat a result somewhere along the line BUT, when this happens, the series following this repetition will not resemble the series that followed the first appearance of the number.
Now, you mentioned that you need to store this in a database. Why don't you use a SEQUENCE (in Oracle; other DBMS have different mechanisms for this)? This will warrant that any used number will NEVER be reused. Moreover, if you don't want to use numbers in a sequence, you can using the value of this sequence as the seed for a random number (or a hashing). This will give you uniqueness to quite many digits.