Math.random and mixture of letters abcd etc - javascript

I'm generating a random number with the code below:
Math.floor((Math.random() * 9999) * 7);
Some of the results I'm getting:
45130,
2611,
34509,
36658
How would I get results like this(with 2 letters included):
TT45130,
PO2611,
KL34509,
GH36658
Side question:
What is the range of numbers that Math.random() carries? Can I set a specific range of values? Not necessary to answer but just curious.

You can use a function like below to get a random uppercase character:
function getRandomUppercaseChar() {
var r = Math.floor(Math.random() * 26);
return String.fromCharCode(65 + r);
}
So to generate a code as you specified with a two-letter prefix:
function generateCode() {
var prefix = new Array(2).fill().map(() => getRandomUppercaseChar()).join(""),
integer = Math.floor((Math.random() * 9999) * 7);
return prefix + integer;
}
NOTE: The above generateCode function uses modern ES6 and ES5 javascript, which is perfectly fine in a modern environment (such as Node.js or a current browser). However, if you wanted greater compatibility (for example, to ensure that it works in old browsers), you could rewrite it like so:
function generateCode() {
var integer = Math.floor((Math.random() * 9999) * 7);
for (var i = 0, prefix = ""; i < 2; ++i)
prefix += getRandomUppercaseChar();
return prefix + integer;
}

Try the simpler answer
var randomNumber = function () {
return Math.floor((Math.random() * 9999) * 7);
}
var randomChar = function () {
return String.fromCharCode(64 + Math.floor((Math.random() * 26)+1));
}
console.log(randomChar()+randomChar()+randomNumber());
//Sample outputs
HB10527 DR25496 IJ12394

Or you can use Number#toString for this purpose with radix = 36.
function getRChar() {
return (Math.random() * 26 + 10 | 0).toString(36).toUpperCase();
}
var s = getRChar() + getRChar() + Math.floor((Math.random() * 9999) * 7);
document.write(s);

If you need to generate a random string with JS, the most common way is to define an alphabet and pick random indices from that:
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var numbers = "0123456789";
var randomString = "";
// Pick two random chars
for (var i = 0; i < 2; i++) {
var rand = Math.floor(Math.random()*alphabet.length);
randomString = randomString + alphabet.charAt(rand);
}
// Pick four random digits
for (var i = 0; i < 4; i++) {
var rand = Math.floor(Math.random()*numbers.length);
randomString = randomString + numbers.charAt(rand);
}
// randomString now contains the string you want
Sample strings:
OJ8225
YL5053
BD7911
ES0159

You could use String.fromCharCode() with a random integer between 65 and 90 to get an uppercase letter, i.e.
String.fromCharCode(Math.random() * 26 + 65) + String.fromCharCode(Math.random() * 26 + 65) + Math.floor((Math.random() * 9999) * 7);
gives med the results: "SH21248", "BY42401", "TD35918".
If you want to guarantee that the string always has the same length, you could also use
String.fromCharCode(Math.random() * 26 + 65) + String.fromCharCode(Math.random() * 26 + 65) + Math.floor(Math.random() * 59993 + 10000);
Math.random() always returns a number between 0 and 1, but never 0 or 1 exactly.

An array of the alphabet, a random number is generated to get a random letter, repeated to get a second random letter and then joined to the random number generated as in your code:
var alphabet=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
var ranletter1 = alphabet[Math.floor(Math.random() * alphabet.length)];
var ranletter2 = alphabet[Math.floor(Math.random() * alphabet.length)];
var ranNum = Math.floor((Math.random() * 9999) * 7);
var ranCode = ranletter1 + ranletter2+ ranNum;

Related

How to make a list of numbers that perfectly divide with 6000 or the most approach to 6000

I need to Make an program that calculate the perfect way of cut bars of 6000milimeters to Make indoor doors and Windows and i need to waste less I can everytime I cut there ia 2 mm that is wasted because of blade. So for example i Have this inputs: 2x1450 2x1600 3x1004 And neeed to show me how can i sort to give me perfect 6000 or the most aproach for example cut 1600+2x1450 And the next one cut 1600+3x1004 with 2 mm cut error at every input.So IT s like sort every inputs in grids of 6000mm.
function bign(){
var bignumber;
var nr1;
var nr2;
var nr3;
var bara = 6000;
var nrbuc1;
var nrbuc2;
var nrbuc3;
var bucx1;
var bucx2;
var bucx3;
nr1=parseInt(document.getElementById("no1").value)
nrbuc1=parseInt(document.getElementById("buc1").value);
nr2=parseInt(document.getElementById("no2").value);
nrbuc2=parseInt(document.getElementById("buc2").value)
nr3=parseInt(document.getElementById("no3").value);
nrbuc3=parseInt(document.getElementById("buc3").value)
bucx1=nr1 * nrbuc1;
bucx2=nr2 * nrbuc2;
bucx3=nr3 * nrbuc3; '
var total1 = bucx1+bucx2;
var total2 = bucx2+bucx3;
var total3 = bucx1+bucx2+bucx3;
var rezultat1= document.getElementById("VERIFICAT").innerHTML = nr1 + " plus " + nr2 + " result";
var rezultat2= document.getElementById("VERIFICAT").innerHTML = nr2 + " plus " + nr3 + " rusult";
var rezultat3= document.getElementById("VERIFICAT").innerHTML = nr1 + " plus " + nr2 + " plus" + nr3;
var gresit = document.getElementById("VERIFICAT").innerHTML = "GRESIT";
if (total1 % bara == 0){
alert (rezultat1);
}
if (total2 % bara == 0){
alert (rezultat2);
}
if (total3 % bara == 0){
alert (rezultat3);
}
else (total1%bara != 0 || total2%bara != 0 || total3%bara !=0 )
alert(gresit);
}
Details are commented in example
/**
* Given a constant width and one or more smaller
* widths, find how many of the smaller widths can
* be combined to get as close as possible to the
* constant width (but not exceed it)
* #param {number} sheet - The width limit that
* cannot be exceeded
* #param {rest<string>} ...points - The points to
* to cut widths to.
*/
class Chop {
constructor(sheet, ...points) {
this.sheet = sheet;
this.points = [...points];
}
/**
* A utility method that formats text
* #param {any} data - Any input a JSON can handle
* #param {boolean} noConsole - Determine whether
* data is to display in console or
* returned. #default is false
* #return {any} any output a JSON can handle
*/
static log(data, noConsole = false) {
if (noConsole) {
return JSON.stringify(data).trim();
}
console.log(JSON.stringify(data));
}
/**
* Given an array of number-strings, convert them
* into a simple format. Each formatted number is
* a width to be "cut"
* # return {array} - An array of numbers used to
* cut the widths
*/
mark() {
this.points = this.points.flatMap(str => {
/**
* If a string has a space...
* ...split the string at every space
*/
if (str.includes(' ')) {
let y = str.split(' ');
y[0] = +y[0] + 2;
y[1] = +y[1] + 2;
return y;
}
/**
* If a string has a "x"...
* ...split string at every "x"...
* ...each number to the left of "x" determines...
* ...how many times the number on the right of "x" is
* repeated
*/
if (str.includes('x')) {
let x = str.split('x');
x.splice(-1, 1, ' ' + (+x[1] + 2));
return x[1]
.repeat(x[0])
.split(' ')
.map(n => +n);
}
return (parseInt(str) + 2);
});
let order = this.points.sort((a, b) => a - b);
Chop.log(order);
return order;
}
/**
* Separates the numbers that fit within the limit
* and those that don't.
* #return {array<array>} - An array of arrays
*/
cut() {
let sum = 0, cutoff, index;
for (const [idx, num] of this.points.entries()) {
if (num + sum > this.sheet) {
cutoff = `Cutoff is ${num}mm at index: ${idx}`;
index = idx;
break;
} else {
sum = num + sum;
}
}
let done = this.points.slice(0, index);
let notDone = this.points.slice(index);
Chop.log(
`Sum of cut sections: ${sum}mm
${cutoff}`);
return [done, notDone];
}
}
let z = new Chop(6000, '2x1140', '1000', '3x500', '3000 5000');
Chop.log(z.mark());
Chop.log(z.cut());

How to get a for loop create a string of 9 random 1digit number?

I need to create a random number generator with 9 total digit created from a random 1 digit number generated thru a for loop .
This one works but i need to use a for loop for it :
var random1 = Math.floor(Math.random() * 9) + 1 ;
var random2 = Math.floor(Math.random() * 9) + 1 ;
var random3 = Math.floor(Math.random() * 9) + 1 ;
var random4 = Math.floor(Math.random() * 9) + 1 ;
var random5 = Math.floor(Math.random() * 9) + 1 ;
var random6 = Math.floor(Math.random() * 9) + 1 ;
var random7 = Math.floor(Math.random() * 9) + 1 ;
var random8 = Math.floor(Math.random() * 9) + 1 ;
var random9 = Math.floor(Math.random() * 9) + 1 ;
// ... and then dump the random number into our random-number div.
$("#random-number").text(""+ random1 + random2 + random3 + random4 + random5 + random6 + random7 + random8 + random9);
var results = ""+ random1 + random2 + random3 + random4 + random5 + random6 + random7 + random8 + random9 ;
$("#results").prepend(results + " <br>");
the above code works in creating a random 9 digit number but i need to use a for loop to make my code concise .
You can use for loop. Create a string and in each loop concentrate the new random number with that string.
let random = '';
for(let i =0;i<9;i++){
random += Math.floor(Math.random() * 9) + 1 ;
}
$("#random-number").text(random);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="random-number"></div>
Another way can be using map() and join()
let random = [...Array(9)].map(x => Math.floor(Math.random() * 9) + 1).join('')
$("#random-number").text(random);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="random-number"></div>
You can try this way with all digits is in range [0, 9] and you should relize that first digit can be zero:
var digits = [];
for (let i=0; i<9; i++) {
let n = Math.floor(Math.random()*10);
digits.push( n );
}
var number = digits.join('')
Construct a new array where the items are random numbers and then join the array with an empty string.
const random = length => Array.from(Array(length), _ => Math.floor(Math.random() * 9) + 1).join('');
console.log(random(9));
console.log(random(9));
console.log(random(9));
console.log(random(9));
console.log(random(9));
In case you want to have all the 9 number to be unique you can use a object to keep track of added previously added numbers and if it is not included add a it to random number as well as object
let random = '';
let included = {}
for(let i =0;i<9;i++){
let temp = true
while(temp){
let num = Math.floor(Math.random() * 9) + 1 ;
if(included[num] === undefined){
temp = false
random += num
included[num] = num
}
}
}
$("#random-number").text(random);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="random-number"></div>

Generate random number between 000 to 999, and a single digit can only occur maximum of two times

How can I generate numbers that range from 000 to 999? Also, a single digit can only occur maximum of two times in the same number.
Examples of numbers I'd like to generate:
094
359
188
900
004
550
Examples of numbers I don't want to generate:
000
999
444
What I've got so far:
function randomNumbers () {
var one = Math.floor(Math.random() * 9) + 0;
var two = Math.floor(Math.random() * 9) + 0;
var three = Math.floor(Math.random() * 9) + 0;
return '' + one + two + three;
};
I know the code can be improved a lot, I just don't know how. Current function isn't checking if the same number occurs three times (should only occur a maximum of two).
I can use jQuery in the project.
Here is a solution that will never have to retry. It returns the result in constant time and spreads the probability evenly among the allowed numbers:
function randomNumbers () {
var val = Math.floor(Math.random() * 990);
val += Math.floor((val+110)/110);
return ('000' + val).substr(-3);
};
// Test it:
var count = new Array(1000).fill(0);
for (i=0; i<100000; i++) {
count[+randomNumbers()]++;
}
// filter out the counters that remained zero:
count = count.map((v,i) => [i,v]).filter( ([i,v]) => !v ).map( ([i,v]) => i );
console.log('numbers that have not been generated: ', count);
You could count the digits and check before return the value.
function getRandom() {
var count = {};
return [10, 10, 10].map(function (a) {
var v;
do {
v = Math.floor(Math.random() * a);
} while (count[v] && count[v] > 1)
count[v] = (count[v] || 0) + 1;
return v;
}).join('');
}
var i = 1000;
while (i--) {
console.log(getRandom());
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
Try this :
$(document).ready(function() {
for(var i=0; i<50;i++)
console.log(randomNumbers ());
function randomNumbers () {
var one = Math.floor(Math.random() * 9);
var two = Math.floor(Math.random() * 9);
var three = Math.floor(Math.random() * 9);
if( one == two && two == three && one == three )
randomNumbers();
else
return (""+one + two + three);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
The following should give you the expected result:
function getRandom() {
var randomNo = Math.floor(Math.random() * 999);
var splitted = randomNo.toString().split("");
var res = [];
splitted.filter(v => {
res.push(v);
if (res.filter(x => x == v).length > 2) return false;
return true;
});
while (splitted.length < 3) {
var ran = Math.floor(Math.random() * 9);
if (splitted.indexOf(ran) < 0) splitted.push(ran);
}
console.log(splitted.join(""))
return splitted.join("");
}
for (x = 0; x<100;x++) {getRandom()}
Keeps track of what you started.
function randomNumbers () {
var one = Math.floor(Math.random() * 10);
var two = Math.floor(Math.random() * 10);
var three = Math.floor(Math.random() * 10);
return one==two && two==three ? randomNumbers(): '' + one + two + three;
};
Here the function call itself recursively up to the point where it result
meets the requirements. The probability of generating three equal numbres is 1/100 so be sure that it will recurse nearly to never.
If, it were me, to be more flexible, I'd write a function I could pass parameters to and have it generate the numbers like the below:
function getRandoms(min, max, places, dupes, needed) {
/**
* Gets an array of random numbers with rules applied
* #param min int min Minimum digit allowed
* #param mas int min Maximum digit allowed
* #param dupes int Maximum duplicate digits to allow
* #param int needed The number of values to return
* #return array Array of random numbers
*/
var vals = [];
while (vals.length < needed) {
var randomNum = Math.floor(Math.random() * max) + min;
var digits = randomNum.toString().split('');
while (digits.length < places) {
digits.push(0);
}
var uniqueDigits = digits.removeDupes();
if ((places - uniqueDigits.length) <= dupes) vals.push(digits.join(''));
}
return vals;
}
// for convenience
Array.prototype.removeDupes = function() {
/**
* Removes duplicate from an array and returns the modified array
* #param array this The original array
* #return array The modified array
*/
var unique = [];
$.each(this, function(i, item) {
if ($.inArray(item, unique)===-1) unique.push(item);
});
return unique;
}
var randomNumbers = getRandoms(0, 999, 3, 2, 10);
console.log(randomNumbers);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How do I replace every dash (-) with a random number in javascript?

I have have some codes like ABCDE-----ABCD----ABC--, where each (-) needs to be a random number.
I have no problem using the replace function to change a single dash to a random number, but I have no clue how to make each dash a random number. Note: each number doesn't need to be unique.
Here is where I am now, but I need the numbers to not all be the same. http://jsfiddle.net/oqrstsdm/
var minNumber = 1;
var maxNumber = 9;
randomNumberFromRange(minNumber, maxNumber);
function randomNumberFromRange(min, max) {
var number = (Math.floor(Math.random() * (max - min + 1) + min));
var str = "ABCDE-----FGABC--";
var res = new RegExp("-", "g");
var code = str.replace(res, number);
document.getElementById("ccode").innerHTML = "Code: " + code;
}
You could use a function as second argument in String.prototype.replace().
var str = "ABCDE-----FGABC--";
var code = str.replace(/-/g, function() {
return Math.floor(Math.random() * (max - min + 1)) + min;
});
Do it in a while loop. Also you don't actually need a regular expression since you're just looking for a string. If you did want a regexp change str.indexOf("-") !== -1 by str.match(regexp) !== null. You also wont need the g flag with this approach.
var str = "ABCDE-----FGABC--";
var number;
while (str.indexOf("-") !== -1) {
number = Math.floor(Math.random() * 10);
str = str.replace("-", number);
}
return str;
Output:
ABCDE92136FGABC38
As an alternative to the replace method, you can use the String split method to tokenize the code, and then apply an Array reduce method to re-join the values with the appropriate numbers substituted in.
function randomNumberFromRange(min, max) {
var str = "ABCDE-----FGABC--";
return str.split("-").reduce(function(prev, val) {
return prev + rand(min, max) + val;
});
}
function rand(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
// Demo code
document.getElementById("random").onclick = function() {
document.getElementById("code").innerHTML = randomNumberFromRange(1, 9);
};
<div id="code"></div>
<div>
<button id="random">Get Code</button>
</div>

generate 4 digit random number using substring

I am trying to execute below code:
var a = Math.floor(100000 + Math.random() * 900000);
a = a.substring(-2);
I am getting error like undefined is not a function at line 2, but when I try to do alert(a), it has something. What is wrong here?
That's because a is a number, not a string. What you probably want to do is something like this:
var val = Math.floor(1000 + Math.random() * 9000);
console.log(val);
Math.random() will generate a floating point number in the range [0, 1) (this is not a typo, it is standard mathematical notation to show that 1 is excluded from the range).
Multiplying by 9000 results in a range of [0, 9000).
Adding 1000 results in a range of [1000, 10000).
Flooring chops off the decimal value to give you an integer. Note that it does not round.
General Case
If you want to generate an integer in the range [x, y), you can use the following code:
Math.floor(x + (y - x) * Math.random());
This will generate 4-digit random number (0000-9999) using substring:
var seq = (Math.floor(Math.random() * 10000) + 10000).toString().substring(1);
console.log(seq);
I adapted Balajis to make it immutable and functional.
Because this doesn't use math you can use alphanumeric, emojis, very long pins etc
const getRandomPin = (chars, len)=>[...Array(len)].map(
(i)=>chars[Math.floor(Math.random()*chars.length)]
).join('');
//use it like this
getRandomPin('0123456789',4);
$( document ).ready(function() {
var a = Math.floor(100000 + Math.random() * 900000);
a = String(a);
a = a.substring(0,4);
alert( "valor:" +a );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Your a is a number. To be able to use the substring function, it has to be a string first, try
var a = (Math.floor(100000 + Math.random() * 900000)).toString();
a = a.substring(-2);
You can get 4-digit this way .substring(startIndex, length), which would be in your case .substring(0, 4). To be able to use .substring() you will need to convert a to string by using .toString(). At the end, you can convert the resulting output into integer by using parseInt :
var a = Math.floor(100000 + Math.random() * 900000)
a = a.toString().substring(0, 4);
a = parseInt(a);
alert(a);
https://jsfiddle.net/v7dswkjf/
The problem is that a is a number. You cannot apply substring to a number so you have to convert the number to a string and then apply the function.
DEMO: https://jsfiddle.net/L0dba54m/
var a = Math.floor(100000 + Math.random() * 900000);
a = a.toString();
a = a.substring(-2);
$(document).ready(function() {
var a = Math.floor((Math.random() * 9999) + 999);
a = String(a);
a = a.substring(0, 4);
});
// It Will Generate Random 5 digit Number & Char
const char = '1234567890abcdefghijklmnopqrstuvwxyz'; //Random Generate Every Time From This Given Char
const length = 5;
let randomvalue = '';
for ( let i = 0; i < length; i++) {
const value = Math.floor(Math.random() * char.length);
randomvalue += char.substring(value, value + 1).toUpperCase();
}
console.log(randomvalue);
function getPin() {
let pin = Math.round(Math.random() * 10000);
let pinStr = pin + '';
// make sure that number is 4 digit
if (pinStr.length == 4) {
return pinStr;
} else {
return getPin();
}
}
let number = getPin();
Just pass Length of to number that need to be generated
await this.randomInteger(4);
async randomInteger(number) {
let length = parseInt(number);
let string:string = number.toString();
let min = 1* parseInt( string.padEnd(length,"0") ) ;
let max = parseInt( string.padEnd(length,"9") );
return Math.floor(
Math.random() * (max - min + 1) + min
)
}
I've created this function where you can defined the size of the OTP(One Time Password):
generateOtp = function (size) {
const zeros = '0'.repeat(size - 1);
const x = parseFloat('1' + zeros);
const y = parseFloat('9' + zeros);
const confirmationCode = String(Math.floor(x + Math.random() * y));
return confirmationCode;
}
How to use:
generateOtp(4)
generateOtp(5)
To avoid overflow, you can validate the size parameter to your case.
Numbers don't have substring method. For example:
let txt = "123456"; // Works, Cause that's a string.
let num = 123456; // Won't Work, Cause that's a number..
// let res = txt.substring(0, 3); // Works: 123
let res = num.substring(0, 3); // Throws Uncaught TypeError.
console.log(res); // Error
For Generating random 4 digit number, you can utilize Math.random()
For Example:
let randNum = (1000 + Math.random() * 9000).toFixed(0);
console.log(randNum);
This is quite simple
const arr = ["one", "Two", "Three"]
const randomNum = arr[Math.floor(Math.random() * arr.length)];
export const createOtp = (): number => {
Number(Math.floor(1000 + Math.random() * 9000).toString());
}

Categories