How to generate random string of numbers and letters ,In form (2 letters + 4 numbers + 2 letters) Example AD1256Cv
Use this-
private string RandomString()
{
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var numbers = "0123456789";
var stringChars = new char[8];
var random = new Random();
for (int i = 0; i < 2; i++)
{
stringChars[i] = chars[random.Next(chars.Length)];
}
for (int i = 2; i < 6; i++)
{
stringChars[i] = numbers[random.Next(numbers.Length)];
}
for (int i = 6; i < 8; i++)
{
stringChars[i] = chars[random.Next(chars.Length)];
}
var finalString = new String(stringChars);
return finalString;
}
Random string generation with upper case letters and digits
Answer in one line:
''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))
or even shorter starting with Python 3.6 using random.choices()
:
''.join(random.choices(string.ascii_uppercase + string.digits, k=N))
A cryptographically more secure version: see this post
''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))
In details, with a clean function for further reuse:
>>> import string
>>> import random
>>> def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
... return ''.join(random.choice(chars) for _ in range(size))
...
>>> id_generator()
'G5G74W'
>>> id_generator(3, "6793YUIO")
'Y3U'
How does it work ?
We import string
, a module that contains sequences of common ASCII characters, and random
, a module that deals with random generation.
string.ascii_uppercase + string.digits
just concatenates the list of characters representing uppercase ASCII chars and digits:
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'
>>> string.ascii_uppercase + string.digits
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
Then we use a list comprehension to create a list of 'n' elements:
>>> range(4) # range create a list of 'n' numbers
[0, 1, 2, 3]
>>> ['elem' for _ in range(4)] # we use range to create 4 times 'elem'
['elem', 'elem', 'elem', 'elem']
In the example above, we use [
to create the list, but we don't in the id_generator
function so Python doesn't create the list in memory, but generates the elements on the fly, one by one (more about this here).
Instead of asking to create 'n' times the string elem
, we will ask Python to create 'n' times a random character, picked from a sequence of characters:
>>> random.choice("abcde")
'a'
>>> random.choice("abcde")
'd'
>>> random.choice("abcde")
'b'
Therefore random.choice(chars) for _ in range(size)
really is creating a sequence of size
characters. Characters that are randomly picked from chars
:
>>> [random.choice('abcde') for _ in range(3)]
['a', 'b', 'b']
>>> [random.choice('abcde') for _ in range(3)]
['e', 'b', 'e']
>>> [random.choice('abcde') for _ in range(3)]
['d', 'a', 'c']
Then we just join them with an empty string so the sequence becomes a string:
>>> ''.join(['a', 'b', 'b'])
'abb'
>>> [random.choice('abcde') for _ in range(3)]
['d', 'c', 'b']
>>> ''.join(random.choice('abcde') for _ in range(3))
'dac'
Generate Unique Random String With Letters And Numbers In Lower Case
If you are using ruby 1.9.2 you can use SecureRandom:
irb(main):001:0> require 'securerandom'
=> true
irb(main):002:0> SecureRandom.hex(13)
=> "5bbf194bcf8740ae8c9ce49e97"
irb(main):003:0> SecureRandom.hex(15)
=> "d2413503a9618bacfdb1745eafdb0f"
irb(main):004:0> SecureRandom.hex(32)
=> "432e0a359bbf3669e6da610d57ea5d0cd9e2fceb93e7f7989305d89e31073690"
Generate random string/characters in JavaScript
I think this will work for you:
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
console.log(makeid(5));
php Random string generation with letters and numbers
Use the below code.
For digits and characters
$length = 10;
echo substr(str_shuffle('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'),1,$length);
For only characters
$length = 10;
echo substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ'),1,$length);
For only digits
$length = 10;
echo substr(str_shuffle('0123456789'),1,$length);
How can I generate random alphanumeric strings?
I heard LINQ is the new black, so here's my attempt using LINQ:
private static Random random = new Random();
public static string RandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
(Note: The use of the Random
class makes this unsuitable for anything security related, such as creating passwords or tokens. Use the RNGCryptoServiceProvider
class if you need a strong random number generator.)
Unique random string with alphanumberic required in Ruby
down = ('a'..'z').to_a
up = ('A'..'Z').to_a
digits = ('0'..'9').to_a
all = down + up + digits
[down.sample, up.sample, digits.sample].
concat(7.times.map { all.sample }).
shuffle.
join
#=> "TioS8TYw0F"
[Edit: The above reflects a misunderstanding of the question. I'll leave it, however. To have no characters appear more than once:
def rnd_str
down = ('a'..'z').to_a
up = ('A'..'Z').to_a
digits = ('0'..'9').to_a
[extract1(down), extract1(up), extract1(digits)].
concat(((down+up+digits).sample(7))).shuffle.join
end
def extract1(arr)
i = arr.size.times.to_a.sample
c = arr[i]
arr.delete_at(i)
c
end
rnd_str #=> "YTLe0WGoa1"
rnd_str #=> "NrBmAnE9bT"
down.sample.shift
(etc.) would have been more compact than extract1
, but the inefficiency was just too much to bear.
If you do not want to repeat random strings, simply keep a list of the ones you generate. If you generate another that is in the list, discard it and generate another. It's pretty unlikely you'll have to generate any extra ones, however. If, for example, you generate 100 random strings (satisfying the requirement of at least one lowercase letter, uppercase letter and digit), the chances that there will be one or more duplicate strings is about one in 700,000:
t = 107_518_933_731
n = t+1
t = t.to_f
(1.0 - 100.times.reduce(1.0) { |prod,_| prod * (n -= 1)/t }).round(10)
#=> 1.39e-07
where t = C(62,10)
and C(62,10)
is defined below.
An alternative
There is a really simple way to do this that turns out to be pretty efficient: just sample without replacement until a sample is found that meets the requirement of at least lowercase letter, one uppercase letter and one digit. We can do that as follows:
DOWN = ('a'..'z').to_a
UP = ('A'..'Z').to_a
DIGITS = ('0'..'9').to_a
ALL = DOWN + UP + DIGITS
def rnd_str
loop do
arr = ALL.sample(10)
break arr.shuffle.join unless (DOWN&&arr).empty? || (UP&&arr).empty? ||
(DIGITS&&arr).empty?
end
end
rnd_str #=> "3jRkHcP7Ge"
rnd_str #=> "B0s81x4Jto
How many samples must we reject, on average, before finding a "good" one? It turns out (see below if you are really, really interested) that the probability of getting a "bad" string (i.e, selecting 10 characters at random from the 62 elements of all
, without replacement, that has no lowercase letters, no uppercase letters or no digits, is only about 0.15. (15%). That means that 85% of the time no bad samples will be rejected before a good one is found.
It turns out that the expected number of bad strings that will be sampled, before a good string is sampled, is:
0.15/0.85 =~ 0.17
The following shows how the above probability was derived, should anyone be interested.
Let n_down
be the number of ways a sample of 10 can be drawn that has no lowercase letters:
n_down = C(36,10) = 36!/(10!*(36-10)!)
where (the binomial coefficient) C(36,10)
equals the number of combinations of 36 "things" that can be "taken" 10 at a time, and equals:
C(36,10) = 36!/(10!*(36-10)!) #=> 254_186_856
Similarly,
n_up = n_down #=> 254_186_856
and
n_digits = C(52,10) #=> 15_820_024_220
We can add these three numbers together to obtain:
n_down + n_up + n_digits #=> 16_328_397_932
This is almost, but not quite, the number of ways to draw 10 characters, without replacement, that contains no lowercase letters characters, uppercase letters or digits. "Not quite" because there is a bit of double-counting going on. The necessary adjustment is as follows:
n_down + n_up + n_digits - 2*C(26,10) - 3
#=> 16_317_774_459
To obtain the probability of drawing a sample of 10 from a population of 62, without replacement, that has no lowercase letter, no uppercase letter or no digit, we divide this number by the total number of ways 10 characters can be drawn from 62 without replacement:
(16_317_774_459.0/c(62,10)).round(2)
#=> 0.15
Generate shortest possible random unique letters-only string in a table
Turn the integer primary key into a base 26 number... aka letters.
0 becomes a
1 becomes b
25 becomes z
26 becomes aa
27 becomes ab
There's no need to store this representation in the database, store it as an integer and convert it to letters at the display level.
Because the primary key increments this isn't particularly secure, it can be guessed.
If you wish to have the code expire, but not the associated data, create a second table which stores the code, when it was created, and a foreign key back to the data. Use an INSERT trigger to add a code.
CREATE TABLE user_codes (
code INTEGER PRIMARY KEY AUTO_INCREMENT,
uid INTEGER FOREIGN KEY users(id),
created TIMESTAMP
);
As above, turn that integer code into base 26 where the digits are all letters.
This also protects the user's primary key, someone might be able to do something malicious with that maybe, better to not leak it.
This also isn't particularly secure and can be guessed. You can improve on it by using the technique in this answer to pick unique random numbers.
If it must be random and unique, consider using a UUID_SHORT()
call to generate a unique 64 bit number, which is basically the time plus a server ID. Then convert that to base 26 and there to letters. Unfortunately this will require something like 14 letters.
...but because it's based on time this also isn't particularly secure and can be guessed.
Finally, ask yourself if the code must be globally unique, or if it's enough for the person to know the code for a particular account. For example, a verification code.
Related Topics
How to Submit Polymorphic Comments on Feed? [Error]
Understanding the Fibonacci Sequence
Manually Retry Job in Delayed_Job
Extract Links (Urls), with Nokogiri in Ruby, from a Href HTML Tags
Ruby - Can't Modify Frozen String (Typeerror)
Rails: How to Access Restful Helpers
How to Select Option in Drop Down Using Capybara
How to Save Settings as a Hash in a External File
How to List All Files in an S3 Folder Using Aws-Sdk Gem in Ruby on Rails
Ruby Shoes Gui: Continually Updating Paragraphs
How to Use Ruby for Shell Scripting
Capistrano Asks for Password When Deploying, Despite Ssh Keys
How to List the Currently Available Objects in the Current Scope in Ruby
In Ruby, What Is the Cleanest Way of Obtaining the Index of the Largest Value in an Array
How to Customize Gemfile Per Developer
How to Convert an Array of Strings into a Comma-Separated String