Unique random alpha num string

Hi Guys,
I have a unique question.
I need to generate a unique random Alpha Num string.
I cannot use 0,5,8 and 0,S,B in the generated output string.
The string generated should be no more than length 7 max
Pls help.

Following solution generates random unique strings combinations
from any given base set. Here is a sample output.
$ java UniqueStringGenerator 7 100 10
FCT2RYT
2M31BU8
VV8FU4Z
BON2MKE
OKUJZT0
68E8X8S
YTNLZAY
CPEKPFP
C176M24
GQB9QE9The idea is quite simple.
Pre-work:
1. The base set is first mixed to increase entropy.
2. All possible combinations are divide up into random buckets.
Work for every unique string:
1. Pick a bucket at random.
2. Get next number in bucket.
3. Convert the number to a unique string token.
It is possible to adjust how much entropy you want in your
sequence of generated combinations by choosing how many buckets
the generator contains. However, every bucket will take up some
memory.
import java.util.*;
import java.math.*;
public class UniqueStringGenerator {
    public static String[] ALPHA_NUM =
     {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P",
      "Q","R","S","T","U","V","X","Y","Z",
      "0","1","2","3","4","5","6","7","8","9"};
    private List _parts = null;
    private List _buckets = null;
    private int _length;
    private BigInteger _range = null;
    public UniqueStringGenerator(String[] parts, int length,
                     int numberOfBuckets) {
     _length = length;
     // mixing the base set to increase entropy
     _parts = new Vector();
     List all = new Vector();
     for (int i = 0;i < parts.length;i++) {
         all.add(parts);
     while (all.size()>0) {
     int p = (int)(((double)all.size())*Math.random());
     _parts.add(all.get(p));
     all.remove(p);
     // dividing all possible numbers into given number of buckets
     BigInteger numParts = BigInteger.valueOf(parts.length);
     _range = BigInteger.ONE;
     for (int i = 0;i<_length;i++) {
     range = range.multiply(numParts);
     TreeSet starts = new TreeSet();
     Random rand = new Random();
     while (starts.size()<numberOfBuckets-1) {
     BigInteger bi = new BigInteger(_range.bitLength(), rand);
     if (bi.compareTo(_range)<=0) {
          starts.add(bi);
     _buckets = new Vector();
     Bucket last = new Bucket(BigInteger.ZERO);
     _buckets.add(last);
     for (Iterator i = starts.iterator();i.hasNext();) {
     Bucket next = new Bucket((BigInteger)i.next());
     _buckets.add(next);
     last.setTo(next.getStart());
     last = next;
     last.setTo(_range);
private class Bucket {
     private BigInteger _start;
     private BigInteger _next;
     private BigInteger _to;
     public Bucket(BigInteger start) {
     _start = start;
     _next = start;
     public void setTo(BigInteger to) {
     _to = to;
     public BigInteger getStart() {
     return _start;
     public boolean hasNext() {
     return next.compareTo(to)<0;
     public BigInteger next() {
     BigInteger ret = _next;
     next = next.add(BigInteger.ONE);
     return ret;
     public String toString() {
     return "["+start+", "+next+", "+_to+"]:"+hasNext();
public String nextUnique() {
     // getting next big integer
     BigInteger left = null;
     while (left==null) {
     Bucket b = (Bucket)
          buckets.get((int)(Math.random()*buckets.size()));
     if (b.hasNext()) {
          left = b.next();
     // converting it to a combination
     StringBuffer unique = new StringBuffer();
     BigInteger base = BigInteger.valueOf(_parts.size());
     for (int i = 0;i<_length;i++) {
     BigInteger[] resRem = left.divideAndRemainder(base);
     left = resRem[0];
     unique.append(_parts.get(resRem[1].intValue()));
     return unique.toString();
public static void main(String[] args) {
     if (args.length!=3) {
     System.out.println("Usage: UniqueStringGenerator "+
               "[string size] [# buckets] [# prints]");
     return;
     int length = Integer.parseInt(args[0]);
     int numBuckets = Integer.parseInt(args[1]);
     int num = Integer.parseInt(args[2]);
     UniqueStringGenerator usg = new UniqueStringGenerator
     (UniqueStringGenerator.ALPHA_NUM, length, numBuckets);
     for (int i=0;i<num;i++) {
     System.out.println(usg.nextUnique());

Similar Messages

  • Generating Random Alpha numeric Salt String using MD5 or other algorithm

    Hello,
    I have a requirement where i need to generate a random alpha numeric salt for MD5 algorithm. Is there a best way to generate this salt ?
    The alpha numerics should confine to 5 digits with possible values for each digit being (a-z), (0-9), (A-Z).
    Any good random generator for salt would be appreciated.
    Thanks.

    Hi there,
    I think the book you read is the book "Java Security", I have that one too.
    Please read all those pages before this code.........
    In this code, it used the RSA algorithm to do the encryption and JDK DOES NOT support
    RSA algorithm....
    Beside, this line
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");It implies the BouncyCastle security provider is in use.... so
    www.bouncycastle.org might be a good place to start with....
    Good luck!

  • Array of unique random numbers - help?

    basically, i'm trying to create a BINGO card.
    i stared learning Java a week ago and am finding it easy to learn and use....at least so far.
    my instructor gave me the assignment to created a BINGO card. so i used the system.out.format command to make 5 tab fields, 8 spaces each ("%8s %8s %8s %8s %8s", "B", "I", "N", "G", "O"). although the assignment only wanted me to think numbers out of thin air, just to use as examples, i went above and beyond with the idea to make a BINGO card generator that could actually function.
    then i started the random number sequences, using the Math.random() command. all told, there are 24 of these in the program, one for each number on a bingo card. the field in the middle is the FREE space, so it has no Math.random command.
    in BINGO, each letter (one of my five tab fields) can have a number in ranges of 15. B is 1 to 15, I is 16 to 30, etc. it looks similar to this:
    B I N G O
    9 19 39 57 66
    3 28 32 51 74
    3 29 FREE 46 70
    14 28 43 55 67
    9 24 35 59 62
    as you can tell, i'm having trouble with actually making unique random numbers so that none repeat.
    is there a command or string or something to help me accomplish this?

    The best way I've come up with is to use an object to store the numbers that implements Collection--like ArrayList...
    Then you load it with the range of numbers that you want and call, shuffle() on the object, that will randomize your range of numbers and then you can choose the quantity you want from the storage object. So let's say you need 25 number in the range of 1 to 100:
    Add the numbers (you have to use classes so I would do Integers) 1 to 100;
    call shuffle()
    pull back the first 25 numbers
    This will guarantee that each number is distinct and in a random order.
    If you need multiple sheets populated, you can just call shuffle() between population of each sheet.
    package Junk;
    import java.util.ArrayList;
    import java.util.Collections;
    class Junk{
      private ArrayList<Integer> l;
      Junk(){
        l = new ArrayList<Integer>();
      public void loadList(int s, int e){
        for(int i=s; i<=e; i++){
          l.add(new Integer(i));
      public void randomizeList(){
        Collections.shuffle(l);
      public void printList5(){
        for(int i=0; i<5; i++){
          System.out.println(l.get(i));
      public static void main(String[] args){
        Junk j = new Junk();
        j.loadList(10,99);
        j.randomizeList();
        j.printList5();
        System.out.println();
        j.randomizeList();
        j.printList5();
    }

  • Random alpha numeric generation.

    i have a requiremnt where i need to generate a random alpha numeric values with the combination of
    a - z (lower case)
    A - Z (Upper case)
    0-9
    with out using the dbms_random.string
    please help me to get the complete script
    Prashant K

    i used dbms_random.string('X',6) statement but it generates the alphanumeric with upper case. i wanted the combination of lower,upper and digits. as shown below.
    e.g aB3cdFE88
    to get the above i did some thing like this.
    select dbms_random.string('L',4)||dbms_random.string('X',6) as rand_alphanumeric from dual
    here i am concatinating the two strings.
    i want to know is there any way other than this to geneate random alphanumeric values ?

  • How to generate a unique random number in a MySQL db

    I'm creating a volunteer and also a separate vendor application form for an airshow. The volunteer and vendor info is stored in separate tables in a MySQL db, one row per volunteer or vendor. There will be about 100 volunteers and 50 vendors. When the application is submitted it should immediately be printed by the applicant, then signed and mailed in. This past year we had problems with some people who didn't immediately print their application so I'd like to still give them the option to immediately print but also send them an e-mail with a link to their specific row in the MySQL db. I have an autoincrement field as the primary key for each table, but I think sending this key to the applicant in an e-mail would be too easy for them to guess another id and access other people's info.
    I'm thinking I should add a column to each table which would contain a unique random number and I would then send this key in the e-mail to the applicant. So, can anyone suggest a simple way to do this or suggest a better way of giving the applicant a way to access their own application and no-one elses after they have submitted their form?
    Thanks all.
    Tony Babb

    Thanks so much, that was very helpful. I added the code you suggested to create and display the random number - I called it "vollink" and that worked fine. Then I added the hidden field toward the bottom of the form - it shows at line 311 when I do a "View Source in Int Explorer and then tried adding the code to add it to the table and when I tested it failed with "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1" . The test version of the page is here www.hollisterairshow.com/volunteerapp2.php . The changes I made to add it to the table is shown below , I must be missing something blindingly obvious, if you could suggest a fix I'd really appreciate it. I did add the field to the MySQL table also.
    Thanks again
    Tony
    $editFormAction = $_SERVER['PHP_SELF'];
    if (isset($_SERVER['QUERY_STRING'])) {
      $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
    if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
      $insertSQL = sprintf("INSERT INTO volunteers (firstname, lastname, email, thursday, friday, saturday, sunday, monday, activity, talents, specialrequests, tshirt, phone, street, city, st, zip, updatedby, vollink) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, $s)",
                           GetSQLValueString($_POST['firstname'], "text"),
                           GetSQLValueString($_POST['lastname'], "text"),
                           GetSQLValueString($_POST['email'], "text"),
                           GetSQLValueString($_POST['thursday'], "text"),
                           GetSQLValueString($_POST['friday'], "text"),
                           GetSQLValueString($_POST['saturday'], "text"),
                           GetSQLValueString($_POST['sunday'], "text"),
                           GetSQLValueString($_POST['monday'], "text"),
                           GetSQLValueString($_POST['activity'], "text"),
                           GetSQLValueString($_POST['specialtalents'], "text"),
                           GetSQLValueString($_POST['specialrequests'], "text"),
                           GetSQLValueString($_POST['tshirt'], "text"),
                           GetSQLValueString($_POST['phone'], "text"),
                           GetSQLValueString($_POST['street'], "text"),
                           GetSQLValueString($_POST['city'], "text"),
                           GetSQLValueString($_POST['st'], "text"),
                           GetSQLValueString($_POST['zip'], "text"),
            GetSQLValueString($_POST['vollink'], "text"),
                           GetSQLValueString($_POST['lastname'], "text"));
      mysql_select_db($database_adminconnection, $adminconnection);
      $Result1 = mysql_query($insertSQL, $adminconnection) or die(mysql_error());

  • Check numbers in alpha numeric string

    Hi All
    Is there any direct command or function module which will find numbers in alpha numeric string or it will check that the string contains only numbers ?
    Regards
    Yogesh

    hi,
    data: fvalue(4) type c,
          nvalue(4) type n.
    fvalue = 'ABC1'.
    nvalue = fvalue.
    if fvalue cn nvalue .                                      
    message i000(zz) with 'fvalue contains not Only numbers'.  
    else.                                                      
    message i000(zz) with 'fvalue containsOnly numbers'.       
    endif.                                                     
    Regards,
    Sailaja.

  • Reconnaiss​ance caractère alpha numérique bureau

    Bonjour
    Pour faire simple, un de mes amis est pisciculture et je souhaiterai automatiser sa pisciculture afin qu'il ne subisse plus de pertes économique pour cause d'inondation, bacs de rétention bouchés ou tous autres pb.
    La pisciculture dispose de  5 sondes de niveaux d'eau, une à l'entrée, une autre à la sortie d'eau de sa pisciculture, et 3 dans des bacs de rétention.  Les résultats de ces sondes sont  visibles directement sur l'écran de son ordinateur par le biais d un programme (dont je ne connais pas le langage).
    Deux petits barrages en amont et en aval sont motorisés et pilotable depuis le PC avec le même programme, qui permettent d augmenter le débits d eau à l entrée ou à la sortie
    Je souhaiterai savoir si il est possible de déterminer une zone de l'écran de cet ordinateur, de faire une reconnaissance alpha numérique, ensuite je ferai le programme de gestion et d'alarme, et à la fin, mon programme "claquerai" dans la zone souhaiter pour faire varier l'ouverture et la fermeture des petits barrages.
    Dites moi si tout cela est possible.
    Ci joint un croquis pour expliquer plus simplement
    Merci
    JP
    Attachments:
    labview.png ‏31 KB

    Bonjour,
    C'est plus une question de faisabilité qu'un problème de code ou de programmation.
    Ce que je ferai à votre place, je partirai sur un screenshot de votre écran à l'aide de cet exemple :
    Screenshot in .NET with LabVIEW
    https://decibel.ni.com/content/docs/DOC-14217
    Puis il faudrait que vous ayez les drivers IMAQ afin d'utiliser touts ce qui est fonctionalité de reconnaissance de forme.
    Programmatically Generate an Optical Character Recognition (OCR) .abc File Using Software Fonts
    https://decibel.ni.com/content/docs/DOC-26398
    Use Vision Assistant to Find Matched Patterns
    https://decibel.ni.com/content/docs/DOC-32828
    En espérant que cela vous aide,
    Cordialement,
    Matthieu RICORD
    National Instruments France
    #adMrkt{text-align: center;font-size:11px; font-weight: bold;} #adMrkt a {text-decoration: none;} #adMrkt a:hover{font-size: 9px;} #adMrkt a span{display: none;} #adMrkt a:hover span{display: block;}
    Été de LabVIEW 2014
    12 présentations en ligne, du 30 juin au 18 juillet

  • 7 digit unique random number

    I would like to generate 7 digit unique random number. I have it something like this :
    Random generator = new Random();
              generator.setSeed(System.currentTimeMillis());
              //generates seven digit random number.
              return generator.nextInt(9999999) + 999999;
    But it generates 8 digit numbers sometimes. I am giving the Max limit in the braces and min limit after the "+" sign. Could anybody help me figure out what is wrong.

    This is not a horrible solution but an intelligent &
    easy solution ;)Actually this would be the easy and intellegent solution to the problem "give a random 7 digit integer."
    Random generator = new Random();
    //generates seven digit random number.
    return generator.nextInt(10000000);Though the orginal post does not specify this as part of the problem others have assumed (probably correctly) that in fact the poster wants a number between 1000000 and 9999999 (inclusive) which can easily be produced with the following modification to the above.
    Random generator = new Random();
    //generates seven digit random number.
    return generator.nextInt(9000000) + 1000000;I am confused by your response. Are you saying the becasue the original question was asking why flawed code doesn't work, that makes your solution good?

  • Unique Random numbers

    How to get unique random numbers every time in AS3
    I have searched but not able to get satisfactory results

    var rand :Number;
    rand = Number(movXml.movie.length());
    for(var n:uint = 0 ; n<5 ; n++)
    num1 = Number(Math.round(Math.random()* ((rand-1) - 0) + 0 ) );
    if(tempArray.indexOf(num1) == -1)
    tempArray.push(num1);
    //trace(tempArray);
    num2  = Number (tempArray[0]);
    //trace("num1:"+num2);
    trace(tempArray);
    some time this produce more than 5 numbers
    and some time less than 3
    I want 4 random numbers , but different
    the above loop runs 4 times , so if number is repeated , it will not add to Array , hence i will not able to get 4 Required numbers

  • Unique random

    Hi all I need algorithm to generate unique random number.

    but i need it all of them as digit number
    and i need it it unique, if i have saved it before in a
    DB , and i need to re-generate again i need unique number.I'll have to make a guess at what you mean...
    Just use a cyclic random number generator, and save the "current position" somewhere.

  • Randomly Generate alpha-numeric strings?

    Hi, can somebody help me to randomly generate strings such as A1, B5, E 2, etc. The range for the values I need generated are [A-E][1-5]. I looked at lots of code for Random generating numbers, but found nothing related to what I need. I hope somebody can help me out here. Thanks!

    nevermind, i figured it out! thanks anyway

  • GL Group Account customizations - alpha-num range in "natural" segment

    OBIEE 11g
    BIA 7.9.6.3
    EBS 12.1.3
    Trying to configure custom GL Group Accounts per the BIA documentation and not all of our custom groups are being populated in w_gl_group_account_d. Basically none of the out of the box group numbers are meaningful to us, so we configured the 3 csv files with 29 custom group accounts - only 10 are being populated in the group account table, and I am still looking for the relevant log file to determine why only the 10 (a few of them do have alpha-numeric values).
    Chart of accounts is 9 segments. Segment 4 ("Category") is set up in EBS as the "natural" segment - however, it has both numeric and alpha-numeric values, i.e.:
    101,140,140,FED REV
    101,199,199,FED REV
    101,F101,F108,FED REV
    101,F110,F115,FED REV
    101,212,212,FIXED CHARGES
    101,213,213,FOOD SRVC
    101,203,203,INSTR
    101,B120,B142,LOC REV
    Question 1: Will mapping non-numeric ranges in the file_group_acct_codes csv file even work? Has anyone done this successfully?
    Question 2: If it is not possible to use alpha-numeric ranges in this csv file, that forces us to use another gl segment - will using another segment that is not set up as the "natural" segment in EBS work? Segment 7 ("Object") is numeric, and can also be mapped to custom gl group names.
    Thanks in advance for any assistance.
    Rhonda

    As it turns out, the main problem we had was that the account ranges have leading zeros, and those leading zeros got stripped when the csv files were opened in Excel then saved to the server. The account ranges now look like this:
    101,0140,0140,FED REV
    101,0199,0199,FED REV
    101,F101,F108,FED REV
    101,F110,F115,FED REV
    101,0212,0212,FIXED CHARGES
    101,0213,0213,FOOD SRVC
    101,0203,0203,INSTR
    101,B120,B142,LOC REV
    After re-running a full load it looks like things are populated correctly in both the dim and fact tables. We are still in the process of verifying that the alpha-numeric codes are working properly but at first glance it appears so.
    I'd still like to know the answer to my second question though, whether you can map gl account nums to a segment that is not the "natural" segment in EBS.
    Thanks for the assistance.
    Rhonda

  • Unique random array

    i need to make a method that fills an array with random integers from 0 to 51, every integer may only appear once. can someone please give me some tips? here is what I have so far:
    import java.util.*;
    public class tryout
         public static void main(String[] args)
              int deck [] = new int [52];
              deck = shuffleDeck();
              for(int i = 0; i < 52; i++)
                   System.out.println(deck);
         private static int[] shuffleDeck()
              Random rand = new Random();
              int[] card = new int[52];
              for(int i = 0; i < 52; i++)
                   card[i] = rand.nextInt(51);
              return card;
    Edited by: skine1 on Mar 16, 2008 5:29 AM

    import java.util.*;
    import java.util.Collections.*;
    public class tryout
    public static void main(String[] args)
    int deck [] = new int [52];
    deck = shuffleDeck();
    for(int i = 0; i < 52; i++)
    System.out.println(deck);
    private static int[] shuffleDeck()
    Random rand = new Random();
    int[] card = new int[52];
    for(int i = 0; i < 52; i++)
    card[i] = i;
    List deck = Arrays.asList(card);
    List.shuffle(deck);
    * card = List.toArray(deck);*
    return card;
    the compiler message said ther were symbols missing for the two lines i put in bold

  • TSP: Generating N unique random indices in tricky set

    Hi! I'm working on a type of the euclidian travelling salesman problem, and I'm going to try to solve it using an Genetic Algorithm.
    One solution may be a route like this: 1-2-4-3-7-6-5. This means travel from town 1 to 2 etc up to city number 5 and also implies travelling
    back to town 1 after town 5. Since the distances between cities are symmetrical, the above given solution is equal to the solution
    1-5-6-7-3-2 (since the route 1-2-4-3-7-6-5-1 is equal (in travelling distance) to 1-5-6-7-3-4-2-1 due to symmetry).
    I need to create an initial population of N solutions. These need to be unique, preferrably totally random solutions in the set of possible
    solutions (wich is this case does not consist of all possible permutations!). Is there a way of doing this without running the risk of
    getting stuck in a loop (generating the same solutions many times and retrying)? I don't want to risk this, since speed is an issue.
    I've thought about ranking solutions and unranking them, but this involves computing faculties, and that may be very time consuming
    and does not seem to be the optimal solution, although i've seen some implementations running in time complexity O(N).
    Note: the number of cities may vary.
    Any thoughts?
    Regards
    Alex

    Generating a random order of indices is not that difficult.
    int[] arr = new int[n];
    for (int i = 0; i < n; i++)
        arr[i] = i;
    for (int i = 0; i < n; i++) {
         int k = (int) (Math.random() * n);
         int x = arr[k];
         arr[k] = arr;
    arr[i] = x;
    However, when dealing with a graph this approach probably doesn't
    make that much sense, since it's unlikely there is an edge between
    every node.
    You probably want to generate an initial population where sequential
    indices are adjacent nodes.
    An alternative to GA is to determine the minimum spanning tree, and
    traverse that. The MST appoach is within a factor of 2 of optimal. If
    you're stuck on GA for this problem, then I think the hardest part is to
    determine a good appoach for combining two solutions.

  • Removing Non-numeric characters from Alpha-numeric string

    Hi,
    I have one column in which i have Alpha-numeric data like
    COLUMN X
    +91 (876) 098 6789
    1-567-987-7655
    so on.
    I want to remove Non-numeric characters from above (space,'(',')',+,........)
    i want to write something generic (suppose some function to which i pass the column)
    thanks in advance,
    Mandip

    This variation uses the like operators pattern recognition to remove non alphanumeric characters. It also
    keeps decimals.
    Code Snippet
    CREATE FUNCTION dbo.RemoveChars(@Str varchar(1000))
    RETURNS VARCHAR(1000)
    BEGIN
    declare @NewStr varchar(1000),
    @i int
    set @i = 1
    set @NewStr = ''
    while @i <= len(@str)
    begin
    --grab digits or (| in regex) decimal
    if substring(@str,@i,1) like '%[0-9|.]%'
    begin
    set @NewStr = @NewStr + substring(@str,@i,1)
    end
    else
    begin
    set @NewStr = @NewStr
    end
    set @i = @i + 1
    end
    RETURN Rtrim(Ltrim(@NewStr))
    END
    GO
    Code to validate:
    Code Snippet
    declare @t table(
    TestStr varchar(100)
    insert into @t values ('+91 (8.76) \098 6789');
    insert into @t values ('1-567-987-7655');
    select dbo.RemoveChars(TestStr)
    from @t

Maybe you are looking for

  • Xorg.conf - hal

    Hi, I have been using arch for quite a long time. Some time ago, when I was installing gnome and x11 I had to generate the xorg.conf using hwd. Hwd is now only in AUR and it is completely useless. I am using HAL configuration now and I want to make s

  • Properties missing from Organize Bookmarks

    I'm unable to access the properties in Organize Bookmarks even though I'm able to access them in Bookmarks sidebar. I prefer using Organize Bookmarks vs Bookmarks sidebar. I'm not sure how soon after upgrading to Firefox 3 I started having this probl

  • Adobe ohotoshop 7.0 stoped working

    I upgraded to leopard 10.5 and now my adobe photoshop 7.0 program has stoped working. It starts to load and the I get a message: An unexpected and unrecoverable problem has occurred because of a program error. Photoshop will now exit. I deleted the p

  • Multiple Tax Registration Numbers per Customer

    Hi, we have EBS 11i (11.5.10.2) and I am not a financial expert, but just struggling with some technical details of TAX implementation. The situation is that we have certain customers which have an office site in one European country, let's say Franc

  • Control center being weird

    My control center used to let me control my music without leaving an app. Now if I want to skip, pause, or anything else, I have to actually go into the music app. Help me fix please?