How I do alphanumeric in-sequence order using javascript - javascript

I'm using the following JavaScript. The final result is display sequence character.
But I want to display alphanumeric in-sequence order. How do I do that?
var disp = '';
var string = '';
var i;
var chars = "0123456789abcdefghiklmnopqrstuvwxyz";
var ran_unrounded;
var ran_number;
var rnum;
for (i = 0; i < 5; i++) {
rnum = Math.floor(Math.random() * chars.length);
string += chars.substring(rnum, rnum + 1);
ran_unrounded = Math.random() * 3;
ran_number = Math.floor(ran_unrounded);
//document.write(chars.substring(rnum, rnum + 1));
// alert('rnum', rnum, '--', rnum + 1);
disp = chars.substring(rnum, rnum + 8);
}

OK, so from the clarification in the comments above the requirement is to generate a string that contains two random "words", where each "word" has four characters selected at random from a predefined set of available characters.
Following is one way to do that:
var chars = "0123456789abcdefghiklmnopqrstuvwxyz";
function getWord(numChars) {
var word = "",
i;
for (i = 0; i < numChars; i++)
word += chars.charAt(Math.floor(Math.random() * chars.length));
return word;
}
function getWords(numWords, numCharsPerWord) {
var words = [],
i;
for (i = 0; i < numWords; i++)
words.push(getWord(numCharsPerWord));
return words.join(" ");
}
console.log( getWords(2, 4) ); // "a8ak 1wp9"
console.log( getWords(3, 4) ); // "7ua1 zh80 yy3r"
console.log( getWords(2, 5) ); // "j5ms2 e4xn8"
Demo: http://jsfiddle.net/dgnwh/

Related

How to make a random password that doesn't start with "-", "_", or "0"?

function randomPassword() {
let length = 15,
password = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_",
space = "";
for (let i = 0, mu = password.length; i < length; ++i) {
space += password.charAt(Math.random() * mu)
}
return space;
}
console.log(randomPassword());
I'm new at javascript. I finally made this code but i don't want it to create a password that starts with "-", "_", "0". How can i do that?
We keep the _, - and 0 away from the character string while we generate the first character for the password. After generating the first character, we add the _, - and 0 back to the character string and generate the rest of the characters for the password.
function randomPassword() {
let length = 15;
// Initial characters without -, _ or 0
let characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
// Generate first character
let password = characters.charAt(Math.floor(Math.random() * characters.length + 1));
// Add the symbols now
characters += "-_0";
let n = characters.length;
// Generate rest
for (let i = 0; i < length - 1; i++) {
password += characters.charAt(Math.floor(Math.random() * n));
}
// Return
return password;
}
console.log(randomPassword());
Another approach can be something like this :
function generatePassword() {
var length = 15,
charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_",
retVal = "";
for (var i = 0, n = charset.length; i < length; ++i) {
let charOne = charset.charAt(Math.floor(Math.random() * n));
if (i == 0) {
while (charOne == "-" || charOne == "_" || charOne == "0")
charOne = charset.charAt(Math.floor(Math.random() * n));
}
retVal += charOne
}
return retVal;
}
console.log(generatePassword())
https://jsfiddle.net/40fa5neo/

Javascript RegExp Generate string with 4 lower case letters, 4 upper case letters & 4 numbers

How to generate random numbers with below criteria in Javascript
String should contain at least 4 lower case letters from [a-z]
String should contain at least 4 upper case letters from [A-Z]
String should contain at least 4 numbers from [0-9]
Note: I don't want to use any JS library due to leagacy reasons
I tried below code but it doesn't match above criteria for example sometimes it does not contain numbers at all....
function randomString(length, chars) {
var mask = '';
if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
if (chars.indexOf('#') > -1) mask += '0123456789';
var result = '';
for (var i = length; i > 0; --i) result += mask[Math.round(Math.random() * (mask.length - 1))];
return result;
}
document.write(randomString(12, 'aA#'));
Is there any better approach to do it?
Here's how you can do it: generate an array which represents your criteria, shuffle it and fill the array.
Example:
function makeRandomString(criteria) {
// From http://stackoverflow.com/q/2450954/3371119
function shuffle(array) {
var currentIndex = array.length,
temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
// Choose a random character from a string
function chooseRandom(str) {
return str[Math.floor(Math.random() * str.length)];
}
// Shuffle the criteria
shuffle(criteria);
var result = "";
// Build the resulting string by choosing a random character from each part
for (var i = 0; i < criteria.length; ++i) result += chooseRandom(criteria[i]);
return result;
}
Example usage:
// Some constants explaining the criteria
var lowercase = "abcdefghijklmnopqrstuvwxyz";
var uppercase = lowercase.toUpperCase();
var numbers = "0123456789";
// Note: if you don't like typing all that, change the names to L, N, and U
var criteria = [lowercase, lowercase, lowercase, lowercase, // 4 lowercase
numbers, numbers, numbers, numbers, // 4 numbers
uppercase, uppercase, uppercase, uppercase // 4 uppercase
];
console.log(makeRandomString(criteria));
Or even better (much less typing):
function repeat(elem, n) {
var result = [];
for (var i = 0; i < n; ++i) result.push(elem);
return result;
}
var criteria = repeat(lowercase, 4)
.concat(repeat(uppercase, 4))
.concat(repeat(numbers, 4));
console.log(makeRandomString(criteria));
Following your same philosophy, you could try something like this. You will generate a random string with 4 characters of each group at least (so at least 12 characters), and up to the number of characters you specify as the parameter.
var LOWER_CASE_MASK = 'abcdefghijklmnopqrstuvwxyz';
var UPPER_CASE_MASK = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var NUMBER_MASK = '0123456789';
var ALL_MASK = LOWER_CASE_MASK + UPPER_CASE_MASK + NUMBER_MASK;
function randomString(length) {
var result = '';
for (var i = 0; i < 4; i++) {
result += randomise(LOWER_CASE_MASK);
result += randomise(UPPER_CASE_MASK);
result += randomise(NUMBER_MASK);
}
for (var j = 0; j < length - 12; j++) {
result += ALL_MASK[Math.round(Math.random() * (ALL_MASK.length - 1))];
}
return shuffle(result);
}
function randomise(string) {
return string[Math.round(Math.random() * (string.length - 1))];
}
function shuffle(string) {
var parts = string.split('');
for (var i = parts.length; i > 0;) {
var random = parseInt(Math.random() * i);
var temp = parts[--i];
parts[i] = parts[random];
parts[random] = temp;
}
return parts.join('');
}
document.write(randomString(20));
The shuffle function is an implementation of the Fisher-Yates shuffle.
Plunker here.
Hope this helps.
Here is my solution :
var text = " ";
var numChars = "0123456789";
var upCaseChars="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var lowCaseChars="abcdefghijklmnopqrstuvwxyz";
for( var i=0; i < 4; i++ )
{
text += numChars.charAt(Math.floor(Math.random() * numChars.length));
text += upCaseChars.charAt(Math.floor(Math.random() * upCaseChars.length));
text += lowCaseChars.charAt(Math.floor(Math.random() * lowCaseChars.length));
}
console.log(text);
I think it should do the trick, you can test it here.

Javascript Loto Game

How can I check for matching numbers in this script, stuck here, I need to compare the array of user numbers with the array of lotto numbers and display how many numbers they got correct if any along with their prize value.
function numbers() {
var numbercount = 6;
var maxnumbers = 40;
var ok = 1;
r = new Array(numbercount);
for (var i = 1; i <= numbercount; i++) {
r[i] = Math.round(Math.random() * (maxnumbers - 1)) + 1;
}
for (var i = numbercount; i >= 1; i--) {
for (var j = numbercount; j >= 1; j--) {
if ((i != j) && (r[i] == r[j])) ok = 0;
}
}
if (ok) {
var output = "";
for (var k = 1; k <= numbercount; k++) {
output += r[k] + ", ";
}
document.lotto.results.value = output;
} else numbers();
}
function userNumbers() {
var usersNumbers = new Array(5);
for (var count = 0; count <= 5; count++) {
usersNumbers[count] = window.prompt("Enter your number " + (count + 1) + ": ");
}
document.lotto.usersNumbers.value = usersNumbers;
}
Here is a lotto numbers generator and a scoring system. I'm going to leave it to you to validate the user input.
function lottoGen(){
var lottoNumbers = [];
for(var k = 0; k<6; k++){
var num = Math.floor(Math.random()*41);
if(lottoNumbers.indexOf(num) != -1){
lottoNumbers.push(num);
}
}
return lottoNumbers;
}
function scoreIt(){
var usersNumbers = document.getElementsByName('usersNumbers').item(0);
usersNumbers = String(usersNumbers)
usersNumbers = usersNumbers.split(' ');
var matches = 0;
for(var i = 0; i<6; i++){
if(lottoNumbers.indexOf(usersNumbers[i]) != -1){matches++;}
}
return matches;
}
Hi I'm new to this and trying to learn off my own back so obviously I'm no expert but the code above makes a lot of sense to me, apart from the fact I can't get it to work.. I tried to console.log where it says RETURN so I could see the numbers but it just shows an empty array still. I assumed this was to do with it being outside the loop..
I've tried various ways but the best I get is an array that loops the same number or an array with 6 numbers but some of which are repeated..
function lottoGen(){
var lottoNumbers = [];
for(var k = 0; k<6; k++){
var num = Math.floor(Math.random()*41);
if(lottoNumbers.indexOf(num) != -1){
lottoNumbers.push(num);
}
}
return lottoNumbers;
}
Lotto JS: CODEPEN DEMO >> HERE <<
(function(){
var btn = document.querySelector("button");
var output = document.querySelector("#result");
function getRandom(min, max){
return Math.round(Math.random() * (max - min) + min);
}
function showRandomNUmbers(){
var numbers = [],
random;
for(var i = 0; i < 6; i++){
random = getRandom(1, 49);
while(numbers.indexOf(random) !== -1){
console.log("upps (" + random + ") it is in already.");
random = getRandom(1, 49);
console.log("replaced with: (" + random + ").");
}
numbers.push(random);
}
output.value = numbers.join(", ");
}
btn.onclick = showRandomNUmbers;
})();

JQuery string 'randomizer' clustering characters

I'm trying to create a password generator based on the options provided by the user. My current script allows users to select uppercase, lowercase, numeric and special characters. This works perfectly and strings are generated to to the user's required length however upon generation, numbers cluster at the string with letters clustering at the beginning. A single special character parts the two. Do you have any suggestions on how to improve the process?
$('document').ready(function() {
$('button').click(function() {
var lower = "";
var upper = "";
var numeric = "";
var special = "";
var string_length = "";
if($('#12').is(':checked')) { string_length = 12; };
if($('#16').is(':checked')) { string_length = 16; };
if($('#18').is(':checked')) { string_length = 18; };
if($('#22').is(':checked')) { string_length = 22; };
if($('#24').is(':checked')) { string_length = 24; };
if($('#custom').is(':checked')) { $('#custom').show(); $('#custom').val(); } else { $('#custom').hide(); };
if($('#ch1').is(':checked')) { lower = "abcdefghijklmnopqrstuvwxyz"; } else { lower = ""; };
if($('#ch2').is(':checked')) { upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; } else { upper = ""; };
if($('#ch3').is(':checked')) { numeric = "0123456789"; } else { numeric = ""; };
if($('#ch4').is(':checked')) { special = "!£$%^&*()_-+={};:#~#?/"; } else { special = ""; };
var chars = lower + upper + numeric + special;
var randomstring = '';
var charCount = 0;
var numCount = 0;
for (var i=0; i<string_length; i++) {
if((Math.floor(Math.random() * 2) == 0) && numCount < 3 || charCount >= 5) {
var rnum = Math.floor(Math.random() * 10);
randomstring += rnum;
numCount += 1;
} else {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
charCount += 1;
}
}
$('span.string').html(randomstring);
});
});
The options 16 length, lowercase, uppercase, numeric and special characters returns something like e046pzw%65760294.
This line is your culprit:
if((Math.floor(Math.random() * 2) == 0) && numCount < 3 || charCount >= 5) {
It says:
The first 3 characters have a bit over 50/50 chance of being numbers. The "then" is always a number and the "else" is a number sometimes depending on options.
After you have 5 "else" selected chars (which means after col 8), you will always have a number.
This is because the "&&" takes precedence over the "||". I suggest using some parentheses to surround the OR clause if you want to have a 50/50 plus chance of using the digit. I also included an alternate way to do 50/50.
if ((Math.random() < 0.5) && (numCount < 3 || charCount >= 5)) {
I'm not sure why you want numbers to have precedence.
An alternative solution. Just my five cents:
$(function(){
$('input, select').change(function(){
var s = $('input[type="checkbox"]:checked').map(function(i, v){
return v.value;
}).get().join(''),
result = '';
for(var i=0; i < $('#length').val(); i++)
result += s.charAt(Math.floor(Math.random() * s.length));
$('#result').val(result);
});
});
Just to give you some ideas. I'm fully aware of that this doesn't take any "type count" in to consideration.
http://jsfiddle.net/m5y3e/

Generating unique 6 digit code js

I am trying to generate 6 digit code using JS.
it must contains 3 digits and 3 chars.
here is my code
var numbers = "0123456789";
var chars = "acdefhiklmnoqrstuvwxyz";
var string_length = 3;
var randomstring = '';
var randomstring2 = '';
for (var x = 0; x < string_length; x++) {
var letterOrNumber = Math.floor(Math.random() * 2);
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum, rnum + 1);
}
for (var y = 0; y < string_length; y++) {
var letterOrNumber2 = Math.floor(Math.random() * 2);
var rnum2 = Math.floor(Math.random() * numbers.length);
randomstring2 += numbers.substring(rnum2, rnum2 + 1);
}
var code = randomstring + randomstring2;
the code result will be 3chars + 3 numbers .. I want to just rearrange this value to be random value contains the same 3 chars and 3 numbers
http://jsfiddle.net/pgDFQ/101/
You could shuffle your current codes with a function like this (from this answer)
//+ Jonas Raoni Soares Silva
//# http://jsfromhell.com/array/shuffle [v1.0]
function shuffle(o){ //v1.0
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
You could use it like this:
alert(shuffle("StackOverflow".split('')).join(''));
Here is an updated demo with this code.
Here is the code for you
function(count){
var chars = 'acdefhiklmnoqrstuvwxyz0123456789'.split('');
var result = '';
for(var i=0; i<count; i++){
var x = Math.floor(Math.random() * chars.length);
result += chars[x];
}
return result;
}
what you can do is use a dingle loop from 6 times and use random character and random number function one by one while also incrementing by 1, Although not that a good option but this may also offer some flexibility
Try this:
var numbers = "0123456789";
var chars= "acdefhiklmnoqrstuvwxyz";
var code_length = 6;
var didget_count = 3;
var letter_count = 3;
var code = '';
for(var i=0; i < code_length; i++) {
var letterOrNumber = Math.floor(Math.random() * 2);
if((letterOrNumber == 0 || number_count == 0) && letter_count > 0) {
letter_count--;
var rnum = Math.floor(Math.random() * chars.length);
code += chars[rnum];
}
else {
number_count--;
var rnum2 = Math.floor(Math.random() * numbers.length);
code += numbers[rnum2];
}
}
I might note that such a code should not be considered truly random as the underlying functions could be predictable depending on the javascipt engine running underneath.

Categories

Resources