Unique alphanumeric String with a fixed length - java

How can generate an unique alphanumeric String with a fixed length of 8 characters. I want base it in an Id + current time.
I tried with MD5 but it make a string too long
Thanks!

The problem is that 8 alphanumeric characters is most likely too few to guarantee uniqueness ... using that approach.
You just need to do some arithmetic. Multiply the number of ids that your application could generate per second by the expected number of seconds that your application is expected to "live". Now figure out how many alphanumeric characters you need to encode that number ... and that gives you how large the "timestamp" part of your id would need to be. Then add the characters for the "id" part of your string.
IMO, the best approach (if you have to use short strings) is to generate partially or fully random strings, and then check them against a (big) table of all previously issued id strings. If you get a collision, generate another string, and repeat.
If you also want your ids to be hard to predict (per your comment), then the "random number" approach is best. Make sure that you use a cryptographic-quality RNG or PRNG. The problem with a timestamp-based approach is that the resulting ids will be much easier to predict ... or guess.

Use java.util.UUID.
UUID uuid = UUID.randomUUID();
String id = uuid.toString().substring(0, 8);

Strings can't be unique: uniqueness refers to an item in the context of a collection without duplicates, called a set. Given a set of symbols (you said alphanumeric in you question) and a string length (in your example 8) there's a known number of possible combinations which may or may not be enough for your needs.
Your requirements can't be satisfied (at least, not with the information you provided). If you really want the token to be unique and the given input (id, timestamp) is guaranteed to be the key (ie for each given ID you'll never have two or more identical timestamps), just put the ID and the timestamp side by side.
The size of the ID columns will be the maximum size for the username + the fixed size for the timestamp.

Related

Create mapping of different unique string values into unique integer values with specified range

I am facing one issue in which I want to map list of string from one application to unique integer but with specified range (like 0 to 99999).
Example:
"Input_str_1" should (for example) mapped to 5423 each time
"Input_str_2" should (for example) mapped to 4829 each time
Here important consideration is that for same input string I should get same number from given range each time. My input string will not be more than 1,00,000. So I have specified this range.
I am unable to get starting pointer on how to approach this problem. If any of you can help me in this direction that will be grateful.
My both application are in java.
Is your goal to produce a unique number, or simply a random-looking number? If the latter, any hash function will suffice. Otherwise, if there are N possible inputs, and all other inputs are invalid, look at perfect hash functions.

Comparing sets of randomly assigned codes in Java to assign a name

Good day,
I honestly do not know how to phrase the problem in the title, thus the generic description. Actually I have a set of ~150 codes, which are combined to produce a single string, like this "a_b_c_d". Valid combinations contain 1-4 code combinations plus the '-' character if no value is assigned, and each code is only used once( "a_a..." is not considered valid). These sets of codes are then assigned to a unique name. Not all combinations are logical, but if a combination is valid then the order of the codes does not matter (if "f_g_e_-" is valid, then "e_g_f_-","e_f_-_ g_" is valid, and they all have the same name). I have taken the time and assigned each valid combination to its unique name and tried to create a single parser to read these values and produce the name.
I think the problem is apparent. Since the order does not matter, I have to check for every possible combination. The codes cannot be strictly orderd, since there are some codes who have meaning in any position.So, this is impossible to accomplish with a simple parser. Is there an optimal way to do this, or will I have to force the user to use some kind of order against the standard?
Try using TreehMap to store the code (string) and and its count (int). increment the count for the code every time it is encountered in the string.
After processing the whole string if you find the count for any code > 1 then string has repeated codes and is invalid, else valid.
Traversing TreeMap will be sorted based on key value. Traverse the TreeMap to generate code sequence that will be sorted.

How do I hash strings to RandomAccessFile

I'm having trouble understand how my teacher wants us to do the second part of this project. The first part was easy getting the employees and putting it in a r.a.f, but I dont understand how i can hash ssn which is a string. Can someone please explain it. I put the directions just in case.Thanks
ssn: String(9 characters),
fullname : string of 50 characters,
salary: float, and
age: int
1.The program writes at least 20 Employees and stores them sequentially on the random access, and then sequentially reads and prints all Employees in a readable format.
2.Redo the previous part assuming the employees are stored based on hashing the ssn( non-sequentially)
You can create a hash of pretty much any type. If I understand correctly, we want to use a distinct data value, an SSN, to make a hash that is used for keying into some random-access store.
My first thought is, if you need a strong hash based on more than just the String itself, to wrap the SSN in a Class, and use that to both store and fetch the SSN value, as well as provide a hashCode() implementation based on one or more fields along with a seed. This is described a bit in Block's "Effective Java", where a HashCodeUtil class is introduced.
A working example is discussed here: http://www.javapractices.com/topic/TopicAction.do?Id=28
It looks to me like you are trying to implement your own hash table using RandomAccessFile. If that is true what you need to do is take a hashcode and turn it into a slot number. To do this modulo divide the hashcode() of the SSN string by some prime number close to double the number of entries you expect in the table. In your case maybe 41. Each slot in the RandomAccessFile is the size of an entry. In you case 9+50+4+4 = 67. Multiply the slot number by the entry size to give you the offset of the location in the RandomAccessFile to read and write.
Note that this, as in all hash tables, may lead to collisions. A real world implementation would then handle some kind of entry chaining.

strategy to create 4 bytes unique Id in java

Our java application has a 4 bytes size restriction to hold unique id.
We are forced to implement a strategy to create unique ids which are 4 bytes in size.
Does any one know a strategy to create it
Yes, start with a random 32 bit integer and increment it.
Anything else will be too demanding as you scale up (e.g. if you have 1 billion already created ids and need to randomly generate a new one, you have to have a 1 billion entry table to check for existence inside... ouch!).
But if it absolutely has to be random and unique, the two strategies you can take are:
1) Have a big HashSet of every id used so far and check for existence in the set whenever you generate a new random ID. If it is, discard and try again.
2) Store all randomly used IDs in the database, and do a SELECT to see if your newly generated random ID exists. If it does, discard and try again.
If the unique ID was larger, you could use a Guid (also known as uuid), which are generated large enough and in such a way that you'll never see two Guids have the same value ever, anywhere, without needing to check.
For Guids/UUIDs in java, see http://docs.oracle.com/javase/7/docs/api/java/util/UUID.html
I think int can meet your demands.
you can try like this
private static byte[] synhead = {(byte)0xAA,0x55,0x7E,0x0B};

Generating unique reference number

Tech Stack: Java 1.6, JPA (Hibernate 3), Spring 3, Oracle 11g
I am working on a project where one of the requirement is to give back the customers a ‘ReferenceNumber’.
One option is to return the row ID, but for that to work, it must not be sequential. Otherwise, you can guess the next number etc.
I can generate a number in Java and store it in a separate column, but then I’ll have make sure there are no collisions.
There are ways to generate such number in database, but not sure if it will guarantee uniqueness.
Is there a best practice for such a requirement from the database point of view?
UPDATE 1
Current I am using the following in Java to generrate the number:
private static SecureRandom random = new SecureRandom();
public static BigInteger getNew() {
return new BigInteger(60, random);
}
public static BigInteger getNew(int numBits) {
return new BigInteger(numBits, random);
}
UPDATE 2: Requirement
Allowing sequential number would allow:
customer to guess the next number.
Find out how many numbers (orders) were there between two number. etc
It is preferable for this reference to be a number, but say a three letter prefix follwed by number is also fine.
If your table has a sequence generated primary key (e.g. the customer_id) then you could reverse the digits and then convert that to an octal representation. Thus it still looks like a decimal number, but it is definitely no longer consecutive and hard to guess any ranges.
The process is even reversable if you can find a way how to deal with trailing zeros in the original value (because they'd become a leading zero in the reversed number and thus will be "dropped" during the conversion).
How about prefixing the number with a customer abbreviation or name abbreviation or something (or 3 letters assigned when the customer is created, checked for uniqueness) and then just have a value stored that you increment sequentially for just that customer? That way they can't tell what the order numbers are in the rest of the system, but they can for themselves, which shouldn't really matter as they know how many orders they have placed anyway.
Why not take a SHA1 or MD5 Hash of a couple of pertinent fields (say the user's name and the time of record creation, etc.)? In many respects, if the strategy is well known, your services external to the Database will be able to recreate the reference number without having to query the database.

Categories

Resources