How to generate unique 10 digit alpha numeric values in Android? - android

How to generate unique id in android.. Any help will be appreciated

Let's see, you'll need 10 digit alphanumeric, so that's around 60 bits?
UUID random = UUID.randomUUID();
long first64 = random.getLeastSignificantBits();
long last64 = random.getMostSignificantBits();
And there you have 128 random bits, which you can turn into an alpha-string.

Take a look at the UUID Class of Android Documentation.
You may find useful the following to use: UUIrandomUUID()

Related

How can we Generate Unique Number in android/Kotlin?

I was working on a project where we needed to generate a unique number for the Firebase Realtime Database. Now I want to generate a random 8- to 12-digit number that will be unique. Can anyone provide a suitable method/algorithm for obtaining the number, or can it be combined with string?
If you truly need a random number with NN digits you should use Kotlin's Random:
val random = abs((0..999999999999).random())
Of course, in this, 0 is a valid number in this sequence. So what do you do in in the 111 billion chances you get 0? well, that's up to you. You could change the range (but less numbers = less randomness)
You could "pad" 0s to your number so 123 becomes 000000000123 (as a String, that is). Ultimately what you do with the random number is up 2 you.
Keep in mind Random also takes a Seed.
So you could become more fancy by using the time at UTC as the seed (which is constantly changing every instant):
val random = abs(Random(LocalDateTime.now().toEpochSecond(ZoneOffset.UTC)).nextLong())
This will likely give you HUGE numbers so you should convert to string and take the last NN digits
If you get for eg.:
2272054910131780911
You can take: 910131780911
I have created a simple playground where you can see this in action. Please understand I made this in 10 minutes, so there may be optimizations all over the place, I don't have the Kotlin standard library in my head and the Playground's autocomplete is not the same as Android Studio.
Possibly look into SecureRandom -- Cryptographically strong random number generator (RNG): https://docs.oracle.com/javase/8/docs/api/java/security/SecureRandom.html
Also, see this post regarding how long of a random number to generate by using SecureRandom: How to generate a SecureRandom string of length n in Java?
You can use Current Milli Second as Unique Number as follows
/**
* #param digit is to define how many Unique digit you wnat
* Such as 8, 10, 12 etc
* But digit must be Min 8 Max 12
*/
fun getUID(digit:Int):Long{
var currentMilliSeconds:String = ""+Calendar.getInstance().timeInMillis
var genDigit:Int = digit
if(genDigit<8)
genDigit = 8
if(genDigit>12)
genDigit = 12
var cut = currentMilliSeconds.length - genDigit
currentMilliSeconds = currentMilliSeconds.substring(cut);
return currentMilliSeconds.toLong()
}
Call it like
var UID = getUID(12)//parameter value can be 8-12

Generate only not generated random numbers in a certain range android studio? [duplicate]

This question already has answers here:
How to generate a random permutation in Java?
(3 answers)
Closed 1 year ago.
Hi in my Android application I need to generate all numbers(not together but when I call the function say generateAnyRandom()) in a certain range.
For example, say my range is 1 to 1000 and when I call generateAnyRandom() it should give a random number within the range. In this way, if again I call the function it should give me another random number which must be different from the existing one. And more importantly, I will call the function maximum of 1000 times as the range is 1 to 1000 and it should give me always a number that was not generated yet. That means I want to generate all the numbers from 1 to 1000 not in one shot but only when I call it.
Please help. It is a critical question for me?
This is a known problem.
Put the numbers 1..1000 into some container; an array, list, or whatever.
Shuffle the contents of the container into random order.
Retrieve the numbers from the shuffled container in order.
As you correctly point out, this will only work 1000 times before the container is exhausted. You should pick a type of container that allows you to easily perform a random shuffle. Check the various built-in functions for the different container types.

android, how to generate shorter version of uuid (13 chars) an app side

android app needs to generate uuid with 13 chars. But that may increase the chance of clashing.
Come up with this function, idea was adding the uuid's most/least SignificantBits, and then get the string from the Long. and then figure out the 13 byte length part from the result. Test run seems not seeing clash on single machine (+100,000 uuids).
But not sure the clashing possibility across machines.
is there a better way which generates 13 chars uuid and reasonable low classing rate?
val random = Random()
fun generateUUID() {
val uuid: UUID = UUID.randomUUID()
val theLong = if (random.nextBoolean()) {
uuid.mostSignificantBits + uuid.leastSignificantBits
} else {
uuid.leastSignificantBits + uuid.mostSignificantBits
}
return java.lang.Long.toString(theLong, Character.MAX_RADIX)
}
It won't be an UUID in the strict sense anymore; UUID describes a very specific data structure. Using the low bits of a proper UUID is generally a bad idea; those were never meant to be unique. Single machine tests will be inconclusive.
EDIT: now that I think of it, what exactly is "char" in the question? A decimal digit? A hex digit? A byte? An ASCII character? A Unicode character? If the latter, you can stuff a full proper UUID there. Just represent it as binary, not as a hexadecimal string. A UUID is 128 bits long. A Unicode codepoint is 20 bits, ergo 13 of those would cover 260 bits, that's well enough.
The Java char datatype is, effectively, slightly less than 16 bits. If by "13 chars" you mean a Java string of length 13 (or an array of 13 chars), you can still stuff a UUID there, with some trickery to avoid reserved UTF-16 surrogate pair values.
All that said, for globally unique ID generation, they usually use a combination of current time, a random number, and some kind of device specific identifier, hashed together. That's how canonical UUIDs work. Depending on the exact nature of the size limit (which is vague in the question), a different hash algorithm would be advisable.
EDIT: about using the whole range of Unicode. First things first: you do realize that both "du3d2t5fdaib4" and "8efc9756-70ff-4a9f-bf45-4c693bde61a4" are hex strings, right? They only use 16 characters, 0-9 and a-f? The dashes in case of the second one can be safely omitted, they're there just for readability. Meanwhile, a single Java char can have one of 63488 possible values - any codepoint from 0 to 0xFFFF, except for the subrange 0xD800..0xDFFF, would do. The string with all those crazy characters won't be nice looking or even printable; it could look something like "芦№Π║ثЯ"; some of the characters might not display in Android because they're not in the system font, but it will be unique all right.
Is it a requirement that the unique string displays nicely?
If no, let's see. A UUID is two 64-bit Java longs. It's a signed datatype in Java; would've been easier if it was unsigned, but there's no such thing. We can, however, treat two longs as 4 ints, and make sure the ints are positive.
Now we have 4 positive ints to stuff into 13 characters. We also don't want to mess with arithmetic that straddles variable boundaries, so let's convert each integer into a 3 character chunk with no overlap. This wastes some bits, but oh well, we have some bits to spare. An int is 4 bytes long, while 3 Java characters are 6 bytes long.
When composing the chars, we would like to avoid the area between D800 and DFFF. Also, we would want to avoid the codepoints from 0 to 1F - those are control characters, unprintable by design. Also, let's avoid character 0x20 - that's space. Now, I don't know exactly how will the string be used; whether or not it will be used in a text format that doesn't allow for escaping and therefore if certain other characters should be avoided to make things simpler downstream.
A contiguous character range is easier to work with, so let's completely throw away the range upwards from 0xD800, too. That leaves us with 0xD7DF distinct codepoints, starting from 0x21. Three of those is plenty enough to cover a 32-bit int. The rule for converting an int into a character triple is straightforward: divide the int by 0xD7DF twice, take the remainders, add the remainders to the base codepoint (which is 0x21). This algorithm is your vanilla "convert an int to a string in base N", with the knowledge that there can be no more than three digits.
All things considered, here goes Java:
public static String uuidToWeirdString(UUID uuid)
{
//Description of our alphabet: from 021 to 0xD7FF
final int ALPHA_SIZE = 0xD7DF, ALPHA_BASE = 0x21;
//Convert the UUID to a pair of signed, potentially negative longs
long low = uuid.getLeastSignificantBits(),
high = uuid.getMostSignificantBits();
//Convert to positive 32-bit ints, represented as signed longs
long []parts = {
(high >> 32) & 0xffffffff,
high & 0xffffffff,
(low >> 32) & 0xffffffff,
low & 0xffffffff
};
//Convert ints to char triples
int nPart, pos = 0;
char []c = new char[12];
for(nPart=0;nPart<4;nPart++)
{
long part = parts[nPart];
c[pos++] = (char)(ALPHA_BASE + part / (ALPHA_SIZE*ALPHA_SIZE));
c[pos++] = (char)(ALPHA_BASE + (part / ALPHA_SIZE ) % ALPHA_SIZE);
c[pos++] = (char)(ALPHA_BASE + part % ALPHA_SIZE);
}
return new String(c);
}
Feast your eyes on the beauty of the Unicode.
A UUID is a 128-bit data type, commonly shown in a 36-character hexadecimal representation, or about 4 bits per character.
Your example is "du3d2t5fdaib4". That only uses lower case Latin letters and Arabic numerals, which gives you about 5 bits per character, or 13×5=65 bits. If you also allow upper case Latin letters, that gives you about 6 bits per character, or 13×6=78 bits.
You cannot fit a 128-bit value into a 65- or 78-bit data type without throwing away nearly half of the bits, which will radically increase the odds of collision—perhaps even guarantee it depending on how the UUIDs were generated and which bits you throw away.

Generate unique ID per user

I am developing a cross platform game for which I needs to generate unique identifier (User ID) for each user. I known some platform (Android or iOS) specific approaches to get device related identifiers but I am looking for a solution independent of the device identifiers.
User ID Requirements:
Independent of the device's platform
Offline implementation (no communication with any servers)
Without sign-up process
I have implemented one approach to create User IDs where I store the system time when the game was launched for the first time on the device.
I have following questions:
Are there any other approaches to generate User IDs (which will meet the above requirements)?
What are the common approaches to create unique identifiers with taking any information from the user?
Are there any third party plug-ins to implement User IDs?
I would appreciate any suggestions and thoughts on this topic.
EDIT:
There are lot of responses to use UUID/GUID. Generally, this approach looks fine but I am looking for a solution which can generate same User ID even if the user reinstall the game.
Have you looked at UUID from Java?
https://docs.oracle.com/javase/7/docs/api/java/util/UUID.html
EDIT: The following links might help using UUID for unique identifiers.
Best practices for permissions & Identifiers
Instance ID
When you say user id, are you talking about a public id such as an username, or a database id?
If you are talking about a database id, go for a GUID/UUID. T-sql for example have the NEWID() method that will return a GUID that doesn't exist in the database yet. I am sure that whichever database you go for you will find some way to use a GUID.
https://learn.microsoft.com/en-us/sql/t-sql/functions/newid-transact-sql
As per my opinion your System current time is the best method for generating Unique User Id.
For Android :
System.currentTimeMillis() returns you the unique 13 digit number which can be used as User Id.
But When you get current time in iOS then it is 10 digit number which generates. So you can multiply it by 1000 to make User Id platform Independent.
Happy Coding...
Assuming that your usernames are unique, you could simply takje the md5 hash of your usernames to get an unique ID (string). e.g. in php:
$userID = md5($username);
because m5 hash functions exist in nearly every programming language you should be able to use this ID on all possible plattforms.
And if you arer looking for a numeric ID, you even can calculate a qunique number from md5.
See represent md5-hash as an integer - stack question for more details
Just generate a long string of random characters. For example, generates a 10 long string of alphanumerics ...
private String GetId(){
String[] chars = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"};
StringBuilder s = new StringBuilder(10);
for(int i = 0;i<10;i++){
int pos = (int) (Math.random() * 62);
String c = "";
if (pos > chars.length-1){
pos = pos - chars.length;
c = chars[pos].toUpperCase();
}else{
c = chars[pos];
}
s.append(c);
}
return s.toString();
}

How to add two 40 digit numbers in Objective-C and Android

I want to know how to add two 40 digit numbers both in Objective C and Android.
Example:
4000000000000000000000000000000000000000000000000000000000
+5000000000000000000000000000000000000000000000000000000000
How to store and where to store these values?
What is the solution for this?
In Android you can use the BigInteger class for arbitrary sized integers. As for storing them, depends on what you need to store them for, but android has a number of storage options described here that should be able to store these large integers.
in case of objective-c, following code is been used to do the calculation
NSDecimalNumber *aNumber = [NSDecimalNumber decimalNumberWithString:#"4000000000000000000000000000000000000000"];
NSDecimalNumber *bNumber = [NSDecimalNumber decimalNumberWithString:#"2000000000000000000000000000000000000000"];
NSDecimalNumber *cNumber = [aNumber decimalNumberByAdding:bNumber];
NSLog(#"%#", cNumber);
here we use the NSDecimalNumber.

Categories

Resources