How to create random string in Javascript? [duplicate] - javascript

This question already has answers here:
javascript password generator
(34 answers)
Generate random string/characters in JavaScript
(93 answers)
Closed 5 years ago.
I would like to create random strings. But I am not get a right way. any one can help me please?
my try :
var anysize = 3;//the size of string
var charset = "abcdefghijklmnopqrstuvwxyz"; //from where to create
console.log( Math.random( charset ) * anysize ); //getting bad result
Is it possible to correct me? or any other elegant way to fix this?
Thanks in advance.

You should use .length property of your string of possible characters(charset).
Also, use Math.floor method in order to get integer positions of your chars array.
You can get a random item from charset string using its array index:
charset[Math.floor(Math.random() * charset.length)]
var anysize = 3;//the size of string
var charset = "abcdefghijklmnopqrstuvwxyz"; //from where to create
result="";
for( var i=0; i < anysize; i++ )
result += charset[Math.floor(Math.random() * charset.length)];
console.log(result);

function randomString(anysize, charset) {
var res = '';
while (anysize--) res += charset[Math.random() * charset.length | 0];
return res;
}
Something like that

You could get the n-index char of string charset and append to a new string many times as you need, see following please:
var anysize = 3;//the size of string
var charset = "abcdefghijklmnopqrstuvwxyz"; //from where to create
var i=0, ret='';
while(i++<anysize)
ret += charset.charAt(Math.random() * charset.length)
console.log(ret);

The first thing you will want to do is create a helper function that can grab a random value from an array.
getRandomValue(array) {
const min = 0; // an integer
const max = array.length; // guaranteed to be an integer
/*
Math.random() will return a random number [0, 1) Notice here that it does not include 1 itself
So basically it is from 0 to .9999999999999999
We multiply this random number by the difference between max and min (max - min). Here our min is always 0.
so now we are basically getting a value from 0 to just less than array.length
BUT we then call Math.floor on this function which returns the given number rounded down to the nearest integer
So Math.floor(Math.random() * (max - min)) returns 0 to array.length - 1
This gives us a random index in the array
*/
const randomIndex = Math.floor(Math.random() * (max - min)) + min;
// then we grab the item that is located at that random index and return it
return array[randomIndex];
}
You could use this helper function with no regard for changing the length of the string, like this:
var randomString = getRandomValue(charset) + getRandomValue(charset) + getRandomValue(charset);
However, you may want to create another function that contains a loop based on how long you want the random string to be:
function getRandomString(charset, length) {
var result = '';
for (var i = 0; i <= length; i++) {
result += getRandomValue(charset);
}
return result;
}
And that function would be used like this
var randomString = getRandomString(charset, 3);

Related

TypeScript: How to replace a particular number in a string, and then update its value?

I am very new to TypeScript, and I can't wrap my head around how to replace a particular number in a string, and then update its value.
I have a column that is full of 10-digits string (e.g. 3345678901)
I would like to be able to:
Input an index number X
Locate the corresponding number in the string
Add or subtract a particular number A to/from that number to update the string
Update the string
A complete example below:
Input index number "4"
The corresponding number is 6
Increase that number by +2 to 8
Update the string to 3345878901
I know that since string is immutable, I need to create a new string and replace necessary characters. Also in order to be able to add/subtract certain values from a value, I need to convert it to an integer first .. a bit lost here.
Any help would be greatly appreciated!
Try something like this.
Below code takes care of carry.
const givenStr = "3345678901";
let givenStrArray = givenStr.split('').map(Number);
const inputIndex = 4;
const increaseAmount = 2;
let givenStrNumber = 0;
for (let i = 0; i < givenStrArray.length; i++) {
givenStrNumber += givenStrArray[i] * Math.pow(10, givenStrArray.length - i - 1)
}
givenStrNumber += increaseAmount * Math.pow(10, givenStrArray.length - inputIndex - 1)
console.log(givenStrNumber);
const inputStr = "3345678901";
const inputIndex = 4;
const increaseAmount = 2;
let x = Number(inputStr[inputIndex]) + increaseAmount
const result = inputStr.substring(0,inputIndex) + x + inputStr.substring(inputIndex + 1)
console.log(result);

Fastest way to generate a lot of unique small random numbers in JavaScript

Wondering how to quickly generate lots of unique, small random numbers. When I implemented it like this it slows down exponentially it seems like, to the point where it never finishes, or will take hours to complete. Probably because it creates tons of duplicates toward the end.
var intsmap = {}
var intsarray = []
var i = 100000
while (i--) {
var int = randominteger(6)
if (intsmap[int]) i++
else {
intsmap[int] = true
intsarray.push(int)
}
}
// return intsarray
function randominteger(exp) {
var string = rand(exp)
return pad(string, exp)
}
function pad(num, size) {
var s = rand(9) + num
return s.substr(s.length - size)
}
function rand(exp) {
var integer = Math.random() * Math.pow(10, exp) << 0
var string = toString(integer, '0123456789')
return string
}
function toString(value, code) {
var digit
var radix = code.length
var result = ''
do {
digit = value % radix
result = code[digit] + result
value = Math.floor(value / radix)
} while (value)
return result
}
Wondering how to accomplish that but the code works within a few seconds if possible.
Update
I would like for the set of numbers to be distributed evenly over an arbitrary range (in this example 1000000 strings, not necessarily from 0-1000000, eg maybe 5050000 is in there).
I would like for the numbers to not necessarily be valid numbers, just a string of integers. So for example they can include 01010101 as a valid string, even though that's not a valid number.
You can use an object as a look up and only insert unique random number
var intsmap = {};
var i = 100000;
while (i--) {
var int = Math.random() * Math.pow(10, 6) << 0;
if(intsmap[int])
continue;
else
intsmap[int] = true;
}
console.log(Object.keys(intsmap));
You can use also use Durstenfeld shuffle after generating number in the given range.
var arr = Array.from({length:1000000}, (_,i) => (i+1));
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
shuffleArray(arr);
console.log(arr);
Just try to shuffle the array of numbers 1 to maxNum
First create an array
var maxNum = 1000000;
var arr = Array(maxNum).fill().map((e,i)=>i+1);
Now shuffle the array
arr.sort(function() {
return .5 - Math.random();
});
Now you have the array of unique random numbers
Demo
var startTime = new Date().getTime();
var maxNum = 1000000;
var arr = Array(maxNum).fill().map((e, i) => i + 1);
arr.sort(function() {
return .5 - Math.random();
});
var endTime = new Date().getTime();
console.log( "Time taken to get " + maxNum + " size random unique number is " + ( endTime - startTime ) + " ms");
I can propose this approach:
generate a random number
cast it to a string (0.1234567812345678)
and extract 6 substrings of length of 10
Code:
var res = {},
s = "";
for (let i=0; i<1000000; ++i) {
s = Math.random().toString();
for (let j=0; j<6; ++j) {
res[s.substring(2+j, 12+j)] = true; // extract 10 digits
}
}
After 1,000,000 iterations, you have computed 6,000,000 numbers with very little collisions (1,800 in average). So you have your 1,000,000 numbers and more in few seconds.
If you need unique big array try to think in other way. Just create range 0 ... 100000 and shuffle it and apply you function that you need for this array.
var acc = 0;
const result = [];
for(var i = 0; i < 100000; i++)
result.push(acc += Math.floor(Math.random() * 10) + 1);
I think the most expensive operation is the hashtable lookup/insertion, so simply do it without it.
One place where you might loose performances is in the Math.random call.
It's a quite expensive call, and you are calling it a huge number of times to generate your strings.
One solution to leverage it is to grab the whole string from a single result of Math.random().
var intsmap = {}
var intsarray = []
var i = 100000
while (i--) {
var int = randominteger(6)
if (intsmap[int]) {
i++
} else {
intsmap[int] = true
intsarray.push(int)
}
}
console.log(intsarray);
// It takes the whole string from a single call to 'random'.
// The maximum length is 16.
function randominteger(length){
return (Math.random() + '').substr(2,length);
}

How to add a common string in every randomly generated string Javascript

I am generating random strings using the below function in node.js. I wanted to know if there is any way to create text strings appropriately with a common string within every randomly generated string.
EDIT: The common string can be in any location of the generated string
For example:
Randomly generated string - Cxqtooxyy4
Can I add 'abc' or 'ABC' within that string like this - Cxqtoabcoxyy4 or CxqtoABCoxyy4 respectively.
My Code -
var randomTextArrayGeneration = function(size)
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for(var i=0;i<size;i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
Can anyone tell me how do I do this? Any help is really helpful.
var n = text.length; //The size of your random string
var randomPosition = Math.floor((Math.random() * n) + 1); //Generate a random number between 1 and the size of your string
//Separate your string in 2 strings
var text1 = text.substring(1, randomPosition);
var text2 = text.substring(randomPosition, n);
//Create your final string by adding the common string between your two halves
var textFinal = text1 + commonString + text2;
return textFinal;
I don't remember how exactly works .substring(), you may want to change 1 by 0 in some places.
A rough sketch of the algorithm is this:
create random string of length size - <FIXED_STRING>.length
append <FIXED_STRING> to the end of generated string
Done.
A corner case is if size < <FIXED_STRING>.length, here you would need to provide some more discussion on what should happen.
You can use String.prototype.slice() to select 0-n characters from possible to insert into random index within string returned from randomTextArrayGeneration. If 0 is passed to randomTextArrayGeneration the selected string from possible will be set as result
var randomTextArrayGeneration = function(size, from, to) {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < size; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length))
};
var len = Math.floor(Math.random() * text.length - 3);
var res = text.slice(0, len) + possible.slice(from, to).toLowerCase() + text.slice(len);
return res
}

How to build a binary-array from hex strings

I'm new to the concept of working with data on the binary level and am hoping someone can give me a hand here...
I'd like to build a binary buffer out of a series of hex numbers that are represented as strings.
For example,
suppose I have "xFCx40xFF" and I want to turn this into an array that looks like: 111111000100000011111111.
What's the best way to do this?
My best attempt seems to not be working:
var raw = "xFCx40xFF"
var end = raw.length-2;
var i = 1;
var j = 0;
var myArray = new Uint8Array(raw.len);
while (i < end) {
var s = raw.substr(i,2);
var num = parseInt(s,16);
i += 3;
myArray[j] = num;
j += 8;
}
Each 3 characters in string will represent 1 number in Uint8Array. Each number in Uint8Array will represent 8 bits. Your code was creating Uint8Array larger than needed and then placing values are wrong locations.
I have simplified the code to use a singe index i which represents the location in the Uint8Array. Corresponding location in string can be easily computed from i.
var raw = "xFCx40xFF"
var myArray = new Uint8Array(raw.length / 3);
for (var i = 0; i < raw.length / 3; i++) {
var str = raw.substr(3 * i + 1, 2);
var num = parseInt(str, 16);
myArray[i] = num;
}
Remove the 'x' character of your hex string and call parseInt() with the radix 16 and toString() with the radix 2 to get the binary string.
var raw = "xFCx40xFF";
var bin = parseInt(raw.split('x').join(''), 16).toString(2);
document.body.textContent = bin;
and if you need an array, just add .split('') at the end.
parseInt(raw.split('x').join(''), 16).toString(2).split('');
or iterate through each character.

JavaScript random password with specific format

I would like to generate a random password respecting the following format:
at least one uppercase character
at least one lowercase character
at least one digit
the length should be at least 6 characters
I thought about it and the only thing I could think of is some function that is quite long and ugly. Could you guys offer me a simpler, more efficient way of doing this?
PS: I'm using this function not on the client side, but on the server side, on my Node.js web application.
Here is my solution:
/**
* sets of charachters
*/
var upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
var lower = 'abcdefghijklmnopqrstuvwxyz'
var digit = '0123456789'
var all = upper + lower + digit
/**
* generate random integer not greater than `max`
*/
function rand (max) {
return Math.floor(Math.random() * max)
}
/**
* generate random character of the given `set`
*/
function random (set) {
return set[rand(set.length - 1)]
}
/**
* generate an array with the given `length`
* of characters of the given `set`
*/
function generate (length, set) {
var result = []
while (length--) result.push(random(set))
return result
}
/**
* shuffle an array randomly
*/
function shuffle (arr) {
var result = []
while (arr.length) {
result = result.concat(arr.splice(rand[arr.length - 1]))
}
return result
}
/**
* do the job
*/
function password (length) {
var result = [] // we need to ensure we have some characters
result = result.concat(generate(1, upper)) // 1 upper case
result = result.concat(generate(1, lower)) // 1 lower case
result = result.concat(generate(1, digit)) // 1 digit
result = result.concat(generate(length - 3, all)) // remaining - whatever
return shuffle(result).join('') // shuffle and make a string
}
console.log(password(6))
How about we place the formats into strings and we can place than into an array, then randomly chose one and randomly chose and item in that sub-array item:
var uppers = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var lowers = "abcdefghijklmnopqrstuvwxyz";
var digits = "01234567890";
var all = uppers + lowers + digits;
var choices = [uppers,lowers,digits];
var checks = [];
var password = "";
var ranLength = Math.ceil(Math.random()*10)+3;
for(var i=0; i<ranLength; i++){
var choice = choices[Math.ceil(Math.random()*3)-1];
var choiceItem = choice[Math.ceil(Math.random()*(choice.length))-1]
password += choiceItem;
}
for(var i=0; i<3; i++){ // Append needed values to end
var choice = choices[i];
var choiceItem = choice[Math.ceil(Math.random()*(choice.length))-1]
password += choiceItem;
}
password = password.split('').sort(function(){
return 0.5 - Math.random();
}).join('');
alert(password);
Edited: Sorry made a small mistake. Fixed.
Try this...
var randomstring = Math.random().toString(36).slice(-8);

Categories

Resources