A PHP class, forked from http://code.google.com/p/unique-code-generator/, used to generate random codes, given a character set to choose from, code length, and number of codes to use. It uses a MySQL database to check and store the codes.
Original author: Darren Inwood, Chrometoaster New Media Ltd (lucidtone at gmail.com)
Original source taken from http://code.google.com/p/unique-code-generator/
Primary change is the inclusion of a write buffer that limits the number of calls to count() function. This may create some problems when duplicate codes are found, but this is acceptable for our requirements of creating a fuzzy total amount of cards.
I need to generate a nine digit numeric code (random preferably) which is unique for a given day (same number cannot be generated again on the same day). I was thinking of using HHMMSSmmm (hours, minutes, seconds and milliseconds) to generate the unique code but is not really random. This code generation method can be accessed by multiple methods at the same time so I will have to put a lock on the method. But will this ensure that the number is unique as it is possible that number generation may take less than a millisecond and two threads get the same number?
Is there a better way to generate a random unique numeric code which is unique for a given day? The number of digits can be from 6 to 9 digits.
Edit: The number of random numbers to be generated depends on the number of transactions. Initially the number could be lower but over a period of time it can become very high (multiple transactions per second). Hence, I would not like to compare the number against a used list as this could have performance issues.
Randomness is needed as this number will be entered by the user on the phone. This number is the only way to link the online transaction with the phone transaction so I don't want user to enter a different number by mistake.
The random number generation needs to take place in a ASP.NET MVC application.
13 Answers
If you start from a random number with 6 digits, then keep adding random, but small enough numbers, you may be abled to do that. You can use the filesystem as the locking storage if you want.. but I think you should use a DB for production!
Here is the sample of what I am talking about:
This sample is a console application, that uses a file to control concurrency, and to store the last used number and date it was generated.
If you run it multiple times you will see what happens. Both will have their own unique numbers.
It will NOT store all generated numbers, like you required!
This sample can generate for about 999000 random numbers per day, in the range of 6 and 9 digits inclusive. That is about 11 numbers per second.
I think that this fulfills your requirements.. am I wrong?
If I am, just tell and I'll try to help more.
Does it only have to be unique within the process?
Any reason not to just keep a counter which you increment atomically each time, and then reset it if the date rolls over?
I would
Generate a set of unique random numbers at the beginning of each day, or rather, before each day in adequate time
Sequentially take a number from the stack every time one is needed
If all the calls are within the same JVM, I think all you'd need is to create a static to hold the last number assigned, write a single function to increment the number and return the new value, and then synchronize on it. Like:
If there are multiple JVMs, the easiest thing to do would be to store the number on a database and use database locking to keep the numbers unique.
Update
I see you've added a requirement that the numbers be random. If you want the numbers to be random AND unique, I don't see any alternative to keeping a list of all previously assigned numbers. You could keep them in some sort of hash table so you don't have to search the entire list each time. If you're assigning a lot of these the size of the hash table may begin to be a problem, even if you don't have to sequentially search it.
Depending on what you're trying to accomplish, you could come up with a scheme that assigns numbers non-sequentially but in a rigid sequence, so for some purposes they would appear random. For example, you could increment by a number that is very large with respect to the maximum and relatively prime with the maximum, and then every time the next increment would go over, subtract the maximum. Like just to scale it down, suppose you were assigning 2 digit numbers instead of 9 digit. Increment by 37. Then you'd assign 37, 74, 111 wraps to 11, 48, 85, 122 wraps to 22, etc.
EDIT: This answer doesn't make sense when I realised the requirement to have multiple unique codes per day, but that they can repeat the next day. If you were looking for a single unique code per day (for whatever reason), then this answer is useful :)
so if the code is just required to be unique per day, then just use the date as the code..
maybe YYYYmmdd, which would give you (for today's date) 20110505, and tomorrow would be 20110506.
You CAN'T ensure than random numbers will not repeat. (because, they're random)
Without a comparison with already generated numbers, you can have:
- random number OR
- unique number.
You need unique number with some random-look. If the milliseconds from the beginning of the day has not enough random look, try combine it with another unique number.
For example:
- combine number of milliseconds, and
- atomic counter (what is increment by one every time you generate a number)
for example when you sum them, you can generate:999999999-86400000 = 913599999 unique numbers per one day.
While they will be not random, they will be unique - and predictable only at 00:00.
Here are variations for this, for example not resetting the counter at 00:00.
How about a modified version of Shuffle Bag. Here's how it would work -
- before your Start of day, you put N distinct numbers satisfying your criterion in a shuffle bag
- during the course of day, you request a number from shuffle bag.
- Shuffle bag gives you a random number from bag and discard it - i.e. will not return the same number again.
- at the end of the day it would clear the bag, ready for next day.
Benefits
- Ensures number is not reused, without checking with existing list
- Numbers would be random, without any sequence
- Apply simple sanity rules to initialize Shuffle Bag, for e.g. no common / repeating sequences allowed (1111111 or 123456789)
- Simple to initialize shuffle bag - use random sequential numbers. i.e. start from six digit number keep on adding a small random number to initialize bag.
- Easy to modify the size of bag based upon historical usage.
- Very simple thread safe implementation in c#.
Original source is here - modified version might serve your purpose.
Append a thread id to the end of the code to deal with concurrency.
Use Guid.NewGuid() to get something like:
0f8fad5b-d9cb-469f-a165-70867728950e
Then, get rid of the '-'s, and convert the letters to their ASCII counterparts. (where a=97)
Then convert to a number.
The suitable code generator depends on how much numbers should be generated in period.Consider following patterns:
HHMMSS+NNN- gives you space for 999 random numbers in a second.
HH+NNNNNNN - gives you space for 9999999 random numbers in a hour. Etc.
If number generation method call distribution in time is uniform, then any pattern is almost equal.
Anyway, considering random number lenght restriction there is always a limit for number of method calls before clashes will apper. E.g. if method is called > 1000 times per second.
I continued your idea to use current time, I just added multi-thread synchronization, and storing used randoms to compare all next randoms with them to provide uniqueness.
public double GetRandomNumber() {object operation = new object(); lock(operation) { return new Random().NextDouble(); } }
would do.
This does not depend on the day/time hence its even more random then your requirement.Now the fact that the number is less then 1 I'll leave to you as an exercise ..
Also, if you like to keep track of all number generated for a given day - keep a list of them and regenerate if duplicate is generated. But that I will not write for you as you are the programmer in your situation ..
Depending on just how much randomness is required, a linear congruential generator with the appropriate parameters may be what you are looking for. For example, following the guidelines given on the Wikipedia entry about period length, a set of parameters that might work for you is: M=1000000000, a=21, c=3, then use any initial seed X0 in [0.999999999], and compute Xn+1=(a*Xn+c)%M. This generates a sequence of Xn with period M, i.e., the sequence generates all numbers in [0.999999999] exactly once before starting to repeat.
Not the answer you're looking for? Browse other questions tagged c#.netalgorithmrandom or ask your own question.
The barcode generator allows you to create a barcode graphic by providing barcode symbology and data. The Barcode Generator is futher down this page!
Unique Code Generator C#
Barcode and Label Design Consulting
While the free tool is a good place to start, the right label is critical to your overall business. Our Labeling & Printing team will help you get the right labels for your unique business requirements.
“It’s not just a label; it’s your business!”
Barcode and Label Design Software
Design basic barcode labels in minutes with our easy-to- use label designer. Use Microsoft Excel as a simple database and spend less time designing and maintaining barcode label formats. Guaranteed reliability and accuracy for your business comes with barcode generation software.
Reasons to Buy a Barcode
If you plan on selling goods, you need to register your products with the GS1. You will be assigned your own unique barcode that identifies your company as the maker of the product, which is necessary in order to do business.
Where to Buy a Barcode
The simplest way to buy a barcode is from buyabarcode.com. All barcodes must originate from the U.C.C., but they require a minimum of 100 barcode be purchased at a time. Buyabarcode.com’s barcodes originate from the GS1. They are purchased in bulk and then sold individually in order to accommodate smaller quantities of barcodes and simplify the buying process.
Barcode Types
Barcode Generator
The barcode generator allows you to create a barcode graphic by providing barcode symbology and data. Click on the Generate Barcode to create a graphic containing your barcode. Right click to copy or save the barcode, then paste or insert the barcode into your document. The Barcode Generator is a free service, but does not include any sort of guarantee or technical support.
This question already has an answer here:
- How to create a GUID/UUID in Python 5 answers
I need to generate a unique ID based on a random value.
marked as duplicate by Unihedron, Anton Savin, rlms, KurzedMetal, AddileMay 19 '15 at 13:13
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
9 Answers
Perhaps uuid.uuid4()
might do the job. See uuid for more information.
You might want Python's UUID functions:
eg:
7d529dd4-548b-4258-aa8e-23e34dc8d43d
unique and random are mutually exclusive. perhaps you want this?
Usage:
no two returned id is the same (Unique) and this is based on a randomized seed value
here you can find an implementation :
hope it helps !
This will work very quickly but will not generate random values but monotonously increasing ones (for a given thread).
It is thread safe and working with tuples may have benefit as opposed to strings (shorter if anything). If you do not need thread safety feel free remove the threading bits (in stead of threading.local, use object() and remove tid altogether).
Hope that helps.
On my system, time.time() seems to offer 6 significant figures after the decimal point. With a brief sleep it should be guaranteed unique with at least a moderate amount of randomness down in the last two or three digits.
You could hash it as well if you're worried.
Not the answer you're looking for? Browse other questions tagged pythonrandomunique-id or ask your own question.
Microsoft Excelhas been anefficient tool for daily engineering work. Its usage can range fromsimple calculations to graph plotting for data analysis. This articleintroduces another useful aspect of Excel, which makes use of string processing functions forcodegeneration. We will explore several functions with examples of when andhow to use them.
Accessing IO ports is quite common for embedded programming. Forexample, we can output pin by pin (bit-level assignment) or output thewhole port (byte-level assignment). Figure1 below shows how we can achieve this with Excel.
Figure1: Code generation for port pin settings |
Those inred colorare the inputs for we need to set,and those in blue color arethe generated code we can copy out and use right away. The formulaentered at D3 is $B$1 &'_'&A3&'='&B3&';' . Herewe make use of the &operator for string concatenation. After entering the formula for D3,simply drag down to copy the formula for D4 to D10. Refer to [1] for the tip on how to generatethe sequence of number for the Bitindex column.
The formula entered at D13 is B1&'=0x'&BIN2HEX (B3&B4&B5&B6&B7&B8&B9&B10,2) &';'. Thistime another function is used, bin2hex[2], which simply converts abinary number (in text format) to a hex number.
The above spreadsheet can help us automate some tedious tasks, suchas to generate the bit assignment statements, or to calculate theequivalent hex number from a string of binaries.
As another example, typically before we can use p9 as an output port, portdirection register pd9 has tobe configured. By simply entering pd9into B1, and enter the bit values accordingly in B3 to B10, we can getthe generated code for pd9settings.
As another example, Figure 2 belowshows a description of registers U0MRand U1MR of 2 UART modules ontheRenesas R8C/23 [3].Configurations for these registers can be done at bit level or at bytelevel.
Figure2: U0MR and U1MR register description |
By applying the same concept, we can generate the bit-levelassignment as well as the byte-level assignment to configure theseregisters. Comments for individual assignments can also be generated,as illustrated in Figure 3 below.
Figure3: Code generation for register U0MR configuration |
The formula used at F3 is B3&'_'&$B$1 &'='&C3&';'&$H$3&D3& $I$3. The formula is thencopy for F4 to F9. At F12, the formula entered is $B$1&'=0x'&BIN2HEX( C10&C9&C8&C7&C6&C5&C4&C3,2) &';'. To generate similar codefor U1MR register, simply enter 'U1MR' into the cell B1. Kamus bahasa malaysia.
Figure 4 below shows anotherscenario which is often encountered. Suppose we have only the function send_char() which simply sends outa character through UART. Now, we need to send a string over, e.g.'Hello world.'
Figure4: Code generation using the Excel mid function |
In this case, another Excel function can be used, the mid[4] function. The function simply extracts out a substring froma string, given a specified location and the number of characters. Theformula used for D2 is $F$2&MID($A$2,C2,1) &$G$2, and from here it can becopied for cells D3 to D13.
In the following last example, we take a look at the referencesource code of the open-source RTOS uT-Kernel [5]. The code relies on some Perlscripts (Perl is well-known regularexpression handling) which will read in a template code as shownin Listing 1 below.
Listing1: Code template used in uT-Kernel |
The Perl scripts are based on the template code and replace those ${func} and TFN_${func} with correspondingfunction names and macro names. There are well 99 functions required tobe generated from the template above. By making use of Excel substitute[6] function, we can achieve similarresults, which is especially useful when there is no Perl interpreteravailable. This is illustrated in Figure5 below.
Unique Code Generator
Figure5: Code generation with Excel substitute function |
Unique Code Generator Excel
At C4, the formula used is SUBSTITUTE($B$1,'${func}',A4). And at D4, the formula usedis SUBSTITUTE(C4,'TFN_${Func}',B4). Coping C4 and D4 down willgenerate all the required code.
The use of Excel in this case can help developers generate codeefficiently and speed up the development time. Besides the functionsgiven in the example above, other functions are worth exploring aswell, such as the IFELSE which can be used for generating morecomplicated code. If you do not have Excel, other alternative such asOpen Office (Calc) or the Google Docs Spreadsheet fromGoogle couldoffer similar functionalities.
The Excel template I used for to create the above examples canaccessed by downloading thiszip file or by going totheEmbedded.com sourcecode archive.
Bao Anh Tran Nguyen is a seniorengineer at Renesas Technology Singapore. Heholds a BS in Computer Engineering and is completing his MSC inEmbedded Systems (part-time) at Nanyang Technological University,Singapore. He can be reached at [email protected].
References
[1] Excel bin2hex function, http://office.microsoft.com/en-us/excel/HP052090031033.aspx?pid=CH062528241033
[2] Excel tip forautomatically numbering rows, http://office.microsoft.com/en-us/excel/HP011542321033.aspx?pid=CH010006321033
[3] Renesas R8C/23 hardwaremanual http://documentation.renesas.com/eng/products/mpumcu/rej09b0251_r8c2223hm.pdf
[4] Excel mid function, http://office.microsoft.com/en-us/excel/HP052091751033.aspx?pid=CH062528321033
[5]uT-Kernel reference source codedownload (subscription required) http://www.t-engine.org/T-Kernel/tkernel_e.html
[6] Excel substitute function, http://office.microsoft.com/en-us/excel/HP052092861033.aspx?pid=CH062528321033