سؤال

In my android app I need to generate random numbers,

My app will be running on many android devices in LAN and using random numbers to communicate with each other, I want to generate such a random and unique number that should never be same in any of the app in LAN.

It should be unique every time any user will generate it ,in his device and in the whole LAN.

Any ideas, I shall be grateful ???

هل كانت مفيدة؟

المحلول 3

I actually find your requirements contradictory. A valid random sequence will not generate unique values otherwise it is not random. What I mean is you don't need anything random at all you just need the numbers to be unique.

To generate a unique number per network node is pretty easy combine machine ip or mac address with time. To get time simply do System.currentTimeMillis(); to get your ip address then use the example here how to get mac address in Java. Combining these two numbers will buy you uniqueness.

نصائح أخرى

Given the clarifications in the question comments, here's what I'd do: build a (deterministic) scheme that swaps bits in a 32 bit integer. Swap as many as you want. Call this the 'scrambler'.

Then just count through the integers; calling the 'scrambler' on each one.

Uniqueness is guaranteed, will be fast but not crytographically secure due to the deterministic nature of the swapping scheme. But note that in general this will have poor statistical randomness properties so don't ever use it when uniformly distributed random numbers are required (such as Monte Carlo). But I think it should satisfy your requirements.

I am not familiar with Android. However, your problem seems to be addressed by UUID, or Universally Unique Identifier. A quick google yields this page.

In particular, you are looking for the method randomUUID(), which generates a variant 2, version 4 (randomly generated number) UUID as per RFC 4122.

This is how you generate a random number:

Random r = new Random();
int random = r.nextInt(100); // returns a value between 0 (incl) and 100 (excl)

Random r = new Random();
int random = r.nextInt(100) + 20; // returns a value between 20 (incl) and 120 (excl)

Concerning your issue that the numbers should be unique, you could probably save each generated number somehow. Then, when drawing a new Random number check the saved numbers if the new random number has already been generated. If so, redraw.

Java Random doc: http://docs.oracle.com/javase/6/docs/api/java/util/Random.html

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top