javascript generating random characters [duplicate] - javascript

This question already has answers here:
Generate random string/characters in JavaScript
(93 answers)
Closed 6 years ago.
I am trying to program a password generator. However, I find that my code is unreliable. I want each run of my function to return 20 random characters. This works most times, however if I spam the function enough times then I sometimes get a result that's below my criteria (eg: 2 strings, none, etc).
var longth = 20,
allc = "!##$%^&*()_+~`|}{[]\:;?><,./-=0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
passgen = '';
for (var i = 0; i < longth; i++) {
passgen += allc.charAt(Math.floor(Math.random() * allc.length));
}
Not sure if the problem is with logic in my code, or if there's a break in one of the characters in my allc variable that's causing problems. Maybe I'm not expressing the variable correctly.

I don't see any problem with your code. I have modified it slightly to take a direct index out of the array, rather than using charAt but that shouldn't matter.
This code is tested by creating 1,000,000 strings and logs how many failed the creation criteria. It doesn't seem to fail.
function makePassword(){
var longth = 20,
allc = "!##$%^&*()_+~`|}{[]\:;?><,./-=0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
passgen = '';
for (var i = 0; i < longth; i++) {
passgen += allc[Math.floor(Math.random() * allc.length)];
}
return passgen;
}
// Test
var failed = [];
var result = "";
for(var x = 0; x < 1000000; ++x){
result = makePassword();
if(result.length !== 20){
failed.push(result);
}
}
console.log("Incorrect strings generated: " + failed.length, failed);

Related

Printing in Javascript

i have a question that seems basic but i can't seem to figure it out.
Write a program that takes the value of a variable called “input” (declared as any whole number at the top of your program) and outputs a square made of asterisks () as large as the number (input). For example, if the “input” is declared with the value 5, your program would display a square made of 25 asterisks() – ie ; 5 asterisks () high, by 5 asterisks () long.
The code i've come up with so far is below. I don't really understand how to make a string continuously print. If i did star = i then it turns into numbers and will print the numbers. So how do i make it so they connect? I also can't figure out where i should put the new line. console.log(star "\n"); gives me an error. Please help :)
var input = 2;
var star = "*";
var i = 0;
do {
console.log(star);
i++;
} while (i < input);
You can use String.repeat() (ES6 only) along with \r\n to add new line
var input = 5,
star = "*",
str = [],
i = 0;
do {
str.push( Array(input).join(star) ); // use array(length).join
i++;
} while (i < input);
str = str.join("\r\n"); // add breaklines
console.log(str);
console.log Will output a single line to the console containing whatever you pass it as an argument. You are trying to print a line of n asterisks n times.
The first step you should take is constructing the string of asterisks. You can concatenate a string to another with the + operator:
var input = 2;
var star = "*";
var line = "";
for(var i = 0; i < input; i++) {
line = line + star;
}
Once you have constructed line you can then print it n times:
for(var i = 0; i < input; i++) {
console.log(line);
}
Hint: You could create an empty array and then create a loop ending at your wanted number of asterisks after which you will join all the members of the array together. (Writing the code here wouldn't help you much since you mentioned it's an homework).
You could approach this in two ways. If we call your input value n, then we can log either n strings each consisting of n stars, or we can log a single string, containing (n * n) stars, with line breaks after every nth star.
Below is an example of a function that could do this task.
function stars (input) {
var output = ''
for (var i = 0; i < input; i++) {
for (var j = 0; j < input; j++) {
output += '*'
}
output += '\n'
}
return output
}
You can use the repeat-function to print a character multiple times.
var input = 2;
var star = "*";
var i = 0;
while(i++ < input){
console.log(star.repeat(input));
}
This repeats the * character input times in input lines.

Javascript Random Name Guesser: Unresponsive Script Issues

This is my first post here and I am having trouble wording a question, so please bear with me as I have been on this issue for hours.
My friend and I have thought of a fun little function that is supposed to guess the user's name (through an <input> tag) in a certain amount of trials using the random number function to access string letters from an alphabet array numbered 0-25. The function is also supposed to give the user the number of trials it took to guess their name.
I keep getting a non-responsive script, (line 33 - The line containing the second "for loop").
var goal = document.getElementById("your_Name").value;
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 goalArray = goal.split("");
var trials = 0;
var guessArray = new Array();
var i;
var n;
for (i = 0; i < goalArray.length; i++){
guessArray.push(alphabet[Math.floor(Math.random()*26)]);
}
while (goalArray != guessArray){
trials++;
guessArray = [];
for (n = 0; n < goalArray.length; n++){
guessArray.push(alphabet[Math.floor(Math.random()*26)]);
}
}
document.getElementById("appendomatic").innerHTML = "It took " + guessArray + " trials to guess correctly";
Any help or attempt to help would be immensely appreciated!
In case anyone was wondering: This little idea of ours was to test the randomness of Javascript's random function through trials (he made the same program in MatLab, so we are going to compare results of the random functions from both languages).
goalArray != guessArray is always true since they are two separate arrays; even if they contain the same elements.
Since they appear to just be arrays of individual letters in a-z you could compare them with something like goalArray + '' != guessArray, because the toString() of the arrays will compare correctly.
This is how I eventually got it to work (by nesting the while loop and second for loop in another for loop):
var goal = document.getElementById("your_Name").value;
var goalArray = goal.split("");
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 trials = 0;
var guessArray = [];
for (i = 0; i < goalArray.length; i++){
guessArray.push(alphabet[Math.floor(Math.random()*26)]);
}
for (x = 0; x < goalArray.length; x++){
while (goalArray[x] != guessArray[x]){
trials++;
guessArray = [];
for (n = 0; n < goalArray.length; n++){
guessArray.push(alphabet[Math.floor(Math.random()*26)]);
}
}
document.getElementById("appendomatic").innerHTML = "It took " + trials + " trials to guess correctly";
}
}

A method that takes 2 integer values and returns an array. JavaScript [duplicate]

This question already has answers here:
Does JavaScript have a method like "range()" to generate a range within the supplied bounds?
(88 answers)
Closed 7 years ago.
I want to know if it is possible to make a method that takes two integer values as parameters and returns them and all the numbers between then in an array.
So for example if my method is
function getNumberRange(first, last)
And i call it
getNumberRanger(10, 13)
Is there a way for me to have the answer returned as the following array value
[10, 11, 12, 13]
Thanks in advance and sorry if this is badly worded.
Of course it is.
function getNumberRange(first, last) {
var arr = [];
for (var i = first; i <= last; i++) {
arr.push(i);
}
return arr;
}
You may even want to add a check to make sure first is indeed last than greatest though to avoid errors. Maybe something like this:
if (first > last) {
throw new Error("first must be less than last");
}
Similar answer that handles sorting high and low
function makeArray(n1, n2) {
var high = n1;
var low = n2;
if (n1 < n2) {
high = n2;
low = n1;
}
var myArray = [];
for(var i=0; i < (high - low) + 1; i++) {
myArray.push(low + i);
}
return myArray;

Generate 5 digit random code which is not in the list [duplicate]

This question already has answers here:
Unique Random Number Generator Javascript
(4 answers)
Closed 8 years ago.
My requirement is to generate 5 digit unique code which is not in the list already.
For example if I have [12345, 54321, 13245, 11234], I would like to generate 34522 etc.. I am using below code for it
function id(){
var text = "", can = "12345";
for( var i = 5; i--; text += can.charAt(Math.floor(Math.random() * can.length)));
return text;
}
var list = [12345, 54321, 13245, 11234];
var generated;
while(!generated){
var t = makeid();
if(list.indexOf(t) == -1){
generated = t;
}
}
This works fine, but when list grows, this would take more time(?). Are there any other ways to write this mechanism.
As #elclanrs said, better use a hash approach
var obj = {};
for(var i=0; i<list.length; ++i) { obj[list[i]] = true; }
and then check
obj.hasOwnProperty(t);
Better use hasOwnProperty and not in to avoid searching in the prototype chain.
However, you can simplify it using ES6 Set:
var set = Set(list);
and then check
set.has(t)
Note not all browsers support it yet.
Be aware that id returns a string, but list is an array of numbers!
To fix that, convert the id to a number (e.g. with unary +), or use something like
function id() {
var num = 0, len = 5;
for(var i=0; i<len; ++i) {
num *= 10;
num += Math.floor(Math.random() * len) + 1;
}
return num;
}

Comparing 2 arrays to output total integer

I have 2 arrays of numbers. I want to go through each array and find the number of times 1 number from each array adds up to the particular amount x.
If the particular amount x is reached as many times as another set number n then the function should print 'YES'. If x does not reach the set number of n then the function should print 'NO'.
The values of x , n and both arrays are in a string input. These values have been split into arrays as seen below in the code.
I have set up 2 for loops to run through each array and an if statement that checks for the condition of x meeting n.
The arrays I'm using in this code should print out the result of 'YES' however every time I run the code I'm getting 'NO' ? I've tried tinkering with the code but nothing has worked.
Any idea on where this code is broke and how to fix the problem?
Thanks :)
code:
var input = '2\n3 10\n2 1 3\n7 8 9';
function processData(input) {
var inputArray = input.split('\n');
var n = inputArray[1][0];
var x = inputArray[1].split(' ')[1];
var arrayA = inputArray[2].split(' ');
var arrayB = inputArray[3].split(' ');
var total = 0;
for(var i = 0; i < arrayA.length; i++) {
for(var j = 0; j < arrayB.length; j++) {
if(arrayA[i] + arrayB[j] == x) {
total = total + 1;
} if (total == n) {
return 'YES';
}
}
}
return 'NO';
}
console.log(processData(input));
arrayA[i] and arrayB[j] are strings, so arrayA[i] + arrayB[j] will be the concatenation of them (ex: '2' + '3' === '23').
If your logic is correct (i didn't quite understand what you are trying to do), it should be enough to convert them to numbers before adding them, using parseInt or some other method:
if(+arrayA[i] + (+arrayB[j]) == +x) { // used unary + to convert to number
total = total + 1;
} if (total == n) {
return 'YES';
}
PS: A cleaner version would be to convert each string in the array to number, but that involves more than adding 3 characters to your code.
PS2: You have a weird way of getting the input data. If you get it from another place in your JS code, you could simply pass it as an object with the relevant structure, otherwise you could pass it around in a more ... common format, like JSON.

Categories

Resources