I am trying to randomize each characters casing in a string. My code so far goes as following:
var message = 'This message is for testing'
for (var i = 0; i < message.length; i++) {
var random_number = Math.round(Math.random() * 10 + 1);
if(random_number % 2 == 0) {
message.charAt(i).toUpperCase();
}
}
console.log(message)
Problem is that even when giving out the letters and numbers via console.log it shows that the numbers would result in an uppercase, but the letters stay low
You just need to store your changes, in for example a different string.
var message = 'This message is for testing';
var newMessage = '';
for (var i = 0; i < message.length; i++) {
var random_number = Math.round(Math.random() * 10 + 1);
if(random_number % 2 == 0) {
newMessage += message.charAt(i).toUpperCase();
}else{
newMessage += message.charAt(i);
}
}
console.log(newMessage);
Build a new string with adding char for char in randomly upper-/lowercase to it.
var message = 'This message is for testing'
let result ="";
for (var i = 0; i < message.length; i++) {
var random_number = Math.round(Math.random() * 10 + 1);
if(random_number % 2 == 0) {
result += message.charAt(i).toUpperCase();
} else {
result += message.charAt(i);
}
}
console.log(result)
Ciao, concat char to a string like this example:
var message = 'This message is for testing'
let stringresult = "";
for (var i = 0; i < message.length; i++) {
var random_number = Math.round(Math.random() * 10 + 1);
if(random_number % 2 == 0) {
stringresult += message.charAt(i).toUpperCase();
}
else stringresult += message.charAt(i);
}
console.log(stringresult)
Related
Hi Everyone I am New Here Basically i want to generate a array with the help of nodejs means i want to generate an array which keeps on generating alphabets like this
array = ["A","B","C"..."Z","AA","BB",..."ZZ","AAA","BBB",..."ZZZ"]
After googling i came across this one
function columnToLetter(column)
{
var temp, letter = '';
while (column > 0)
{
temp = (column - 1) % 26;
letter = String.fromCharCode(temp + 65) + letter;
column = (column - temp - 1) / 26;
}
return letter;
}
But can't understand it still new to the language
I think my method can meet your requirements
function columnToLetter(column) {
var letter = [],
newLetter = [],
merchant = Math.floor(column / 26),
remainder = column % 26;
if (merchant === 0) {
for (let i = 0; i < remainder; i++) {
newLetter.push(String.fromCharCode(i + 65));
}
return newLetter;
} else if (merchant > 0) {
for (let j = 0; j < 26; j++) {
let str = String.fromCharCode(j + 65);
letter.push(str)
}
for (let i = 1; i <= merchant; i++) {
newLetter.push(...letter);
letter = letter.map(item => item + item.split('')[0])
}
newLetter.push(...letter.slice(0, remainder));
return newLetter;
}
}
console.log(columnToLetter(28));
I'm trying to build a password generator which creates passwords conforming to:
Minimum 8 characters in length, Maximum 40 characters in length
Must contain at least 1 uppercase, lowercase, number and symbol
I'm avoiding Math.random out of choice, I prefer the crypto option.
I've been through loads of articles to try and get this working, but I'm having the following issues:
Random spaces seem to occur in the output string, often on the end.
Output values are sometimes not conforming to the min 8 char rule.
I realize I probably have far too many additional if statements double checking things, but I'm struggling to see where it's going wrong.
This is to go into another system, so I'm creating it as modular and functional as possible. Apologies for the large snippet below, I couldn't get it working in jsfiddle.
function cryptoPassword(){
var minFieldNum = 8; //Minimum char size of desired output
var maxFieldNum = 40; //X defines their fields as 40 as the max_length
var outputValue = ''; //Output for field/overall function
var fieldRandom = getRandomInt(minFieldNum, maxFieldNum); //Generate length of password
if (fieldRandom < minFieldNum || fieldRandom > maxFieldNum) {
fieldRandom = getRandomInt(minFieldNum, maxFieldNum); //Regenerate if length doesn't conform - Not working?
}
else {
for (i = 0; outputValue.length < fieldRandom; i++) {
var mask = getRandomMask(); //Get mask selection
var randomChar = mask.charAt(getRandomInt(0,mask.length)); //Pick random char in mask
if (randomChar == " ") { //I don't know where the spaces come from
var randomChar = mask.charAt(getRandomInt(0,mask.length)); //Pick random char in mask
}
outputValue += randomChar; //Add to output
}
if (passwordChecker(outputValue, minFieldNum)) {
return outputValue + " " + passwordChecker(outputValue, minFieldNum);
}
else {
return cryptoPassword();
}
}
}
function getRandomInt(min, max) {
var byteArray = new Uint8Array(1);
window.crypto.getRandomValues(byteArray);
var range = (max - min + 1);
return min + (byteArray[0] % range);
}
function getRandomMask() {
var maskLcaseChar = 'abcdefghijklmnopqrstuvwxyz';
var maskUcaseChar = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var maskNumeric = '0123456789';
var maskSpecial = '!"$%^&*(){}[];#,./:#~<>?|_+-=';
var maskRandomNo = getRandomInt(0, 3);
var selectMask = [maskLcaseChar, maskUcaseChar, maskNumeric, maskSpecial];
return selectMask[maskRandomNo];
}
function passwordChecker(output, minSize){
var checkChars = '!"$%^&*(){}[];#,./:#~<>?|_+-=';
if (output.length < minSize){
return false
}
else if((output.toUpperCase() != output) && (output.toLowerCase() != output)) {
for (var i = 0; i < output.length; i++) {
if (checkChars.indexOf(output.charAt(i)) != -1) {
return true;
}
}
}
return false;
}
So the issue seems to have been with the getRandomInt function which would return an int between 0 and the length of the mask. As you're dealing with arrays you really want it to be between 0 and length of array -1.
You were getting empty strings back from the charAt function as you were asking for a position out side the array.
I've fixed that and also optimised the generating section a bit. It always adds one char from each of the masks, then takes them randomly after that. I then shuffle the string, moving the initial 4 around. It's not using crypto to shuffle but I don't think it's necessary there.
function cryptoPassword(){
var maskLcaseChar = 'abcdefghijklmnopqrstuvwxyz';
var maskUcaseChar = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var maskNumeric = '0123456789';
var maskSpecial = '!"$%^&*(){}[];#,./:#~<>?|_+-=';
var maskAll = maskLcaseChar + maskUcaseChar + maskNumeric + maskSpecial;
var mask = '';
var minFieldNum = 8; //Minimum char size of desired output
var maxFieldNum = 40; //X defines their fields as 40 as the max_length
var outputValue = ''; //Output for field/overall function
var fieldRandom = getRandomInt(minFieldNum, maxFieldNum); //Generate length of password
if (fieldRandom < minFieldNum || fieldRandom > maxFieldNum) {
console.log("error length", fieldRandom)
fieldRandom = getRandomInt(minFieldNum, maxFieldNum); //Regenerate if length doesn't conform - Not working?
}
else {
var randomChar = '';
var rnd;
randomChar = maskLcaseChar.charAt(getRandomInt(0,maskLcaseChar.length)); //Pick random lower case
outputValue += randomChar; //Add to output
randomChar = maskUcaseChar.charAt(getRandomInt(0,maskUcaseChar.length)); //Pick random upper case
outputValue += randomChar; //Add to output
randomChar = maskNumeric.charAt(getRandomInt(0,maskNumeric.length)); //Pick random numeric
outputValue += randomChar; //Add to output
randomChar = maskSpecial.charAt(getRandomInt(0,maskSpecial.length)); //Pick random special
outputValue += randomChar; //Add to output
mask = maskAll;
for (var i = 3; i < fieldRandom; i++) {
randomChar = mask.charAt(getRandomInt(0,mask.length)); //Pick random char
outputValue += randomChar;
}
outputValue = shuffleString(outputValue); //shuffle output
if (passwordChecker(outputValue, minFieldNum)) {
return outputValue + passwordChecker(outputValue, minFieldNum);
}
else {
console.log("error password", outputValue);
}
}
}
function shuffleString(inputString) {
var array = inputString.split('');
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array.join('');
}
function getRandomInt(min, max) {
var byteArray = new Uint8Array(1);
window.crypto.getRandomValues(byteArray);
var range = (max - min);
var output = min + (byteArray[0] % range);
return output
}
function passwordChecker(output, minSize){
var checkChars = '!"$%^&*(){}[];#,./:#~<>?|_+-=';
if (output.length < minSize){
console.log("too short")
return false
}
else if((output.toUpperCase() != output) && (output.toLowerCase() != output)) {
for (var i = 0; i < output.length; i++) {
if (checkChars.indexOf(output.charAt(i)) != -1) {
if(output.indexOf(' ') === -1){
return true;
}
}
}
}
console.log("doesn't meet standards")
return false;
}
for(j=0; j<10000; j++){
cryptoPassword()
}
console.log("done")
I've added a quick test at the bottom. It'll generate 10,000 passwords. It'll only output them to console if they fail your test. You'll probably want to remove that and some of the console.logs and tidy it up a bit.
My results for numbers between 1 and 28321 (limit)
sum of all numbers: 395465626
sum of all abundant numbers: 392188885
sum of all non abundant numbers: 3276741 (correct answer is 4179871)
var divisors = function(number){
sqrtNumber = Math.sqrt(number);
var sum = 1;
for(var i = 2; i<= sqrtNumber; i++)
{
if (number == sqrtNumber * sqrtNumber)
{
sum += sqrtNumber;
sqrtNumber--;
}
if( number % i == 0 )
{
sum += i + (number/i);
}
}
if (sum > number) {return true;}
else {return false;}
};
var abundent = [], k = 0;
var upperLimit = 28123;
for (var i = 1; i <= upperLimit; i++)
{
if (divisors(i))
{abundent[k] = i; k++};
}
var abundentCount = abundent.length;
var canBeWrittenAsAbundant = [];
for (var i = 0; i < abundentCount; i++){
for (var j = i; j < abundentCount; j++){
if (abundent[i] + abundent[j] <= upperLimit){canBeWrittenAsAbundant[abundent[i]+abundent[j]] = true;}
else {
break;
}
}
}
for (i=1; i <= upperLimit; i++){
if (canBeWrittenAsAbundant[i] == true){continue;}
else {canBeWrittenAsAbundant[i] = false;}
}
var sum = 0;
for (i=1; i <= upperLimit; i++)
{
if (!canBeWrittenAsAbundant[i]){
sum += i;
}
}
console.log(sum);
I'm using http://www.mathblog.dk/project-euler-23-find-positive-integers-not-sum-of-abundant-numbers/ as guidance, but my results are different. I'm a pretty big newb in the programming community so please keep that in mind.
You do not need to calculate the sum of all numbers using a cycle, since there is a formula, like this:
1 + 2 + ... + number = (number * (number + 1)) / 2
Next, let's take a look at divisors:
var divisors = function(number){
sqrtNumber = Math.sqrt(number);
var sum = 1;
for(var i = 2; i<= sqrtNumber; i++)
{
if (number == sqrtNumber * sqrtNumber)
{
sum += sqrtNumber;
sqrtNumber--;
}
if( number % i == 0 )
{
sum += i + (number/i);
}
}
if (sum > number) {return true;}
else {return false;}
};
You initialize sum with 1, since it is a divisor. However, I do not quite understand why do you iterate until the square root instead of the half of the number. For example, if you call the function for 100, then you are iterating until i reaches 10. However, 100 is divisible with 20 for example. Aside of that, your function is not optimal. You should return true as soon as you found out that the number is abundant. Also, the name of divisors is misleading, you should name your function with a more significant name, like isAbundant. Finally, I do not understand why do you decrease square root if number happens to be its exact square and if you do so, why do you have this check in the cycle. Implementation:
var isAbundant = function(number) {
var sum = 1;
var half = number / 2;
for (var i = 2; i <= half; i++) {
if (number % i === 0) {
sum += i;
if (sum > number) {
return true;
}
}
}
return false;
}
Note, that perfect numbers are not considered to be abundant by the function.
You do not need to store all numbers, since you are calculating aggregate data. Instead, do it like this:
//we assume that number has been initialized
console.log("Sum of all numbers: " + ((number * (number + 1)) / 2));
var abundantSum = 0;
var nonAbundantSum = 0;
for (var i = 0; i <= number) {
if (isAbundant(i)) {
abundantSum += i;
} else {
nonAbundantSum += i;
}
}
console.log("Sum of non abundant numbers: " + nonAbundantSum);
console.log("Sum of abundant numbers: " + abundantSum);
Code is not tested. Also, beware overflow problems and structure your code.
Below is the Corrected Code for NodeJS..
var divisors = function (number) {
sqrtNumber = Math.sqrt(number);
var sum = 1;
var half = number / 2;
for (var i = 2; i <= half; i++) {
if (number % i === 0) { sum += i; }
}
if (sum > number) { return true; }
else { return false; }
};
var abundent = [], k = 0;
var upperLimit = 28123;
for (var i = 1; i <= upperLimit; i++) {
if (divisors(i)) { abundent[k] = i; k++ };
}
var abundentCount = abundent.length;
var canBeWrittenAsAbundant = [];
for (var i = 0; i < abundentCount; i++) {
for (var j = i; j < abundentCount; j++) {
if (abundent[i] + abundent[j] <= upperLimit) { canBeWrittenAsAbundant[abundent[i] + abundent[j]] = true; }
else {
break;
}
}
}
for (i = 1; i <= upperLimit; i++) {
if (canBeWrittenAsAbundant[i] == true) { continue; }
else { canBeWrittenAsAbundant[i] = false; }
}
var sum = 0;
for (i = 1; i <= upperLimit; i++) {
if (!canBeWrittenAsAbundant[i]) {
sum += i;
}
}
console.log(sum);
First day of school, we're supposed to make a hangman game. I've been staring at the logic in my while loop for hours now. I can't get my loop to say yes, the word(newWord) does contain the guess. I always get the prompt that it is incorrect, and then all heck breaks loose. I've tried 25 different ways. I know it's all busted beyond repair now, but if anyone can get me going the right direction, I'd be eternally grateful.
let words = ["skate", "guitar", "laugh", "party", "shirt"]
let wordValue = Math.floor(Math.random() * 4) + 1;
let newWord = words[wordValue];
let misses = 0;
let rightGuess = 0;
let wrongGuess = 0;
var answerLines = [];
for (let i = 0; i < newWord.length; i++) {
answerLines[i] = "_";
}
let remainingLetters = newWord.length;
while (remainingLetters > 0 && misses < 6) {
alert(answerLines.join(" "));
let guess = prompt("Guess a letter, any letter!");
for(let j = 0; j < newWord.length; j++) {
if (newWord[j] === guess) {
rightGuess++
}
else { wrongGuess++ }
if (rightGuess != 0) {
answerLines[j] = guess;
remainingLetters--;
}
else {
misses++
(alert("That was is incorrect. You have " + misses + " of 6 misses."));
Your logic for processing the guess is a little off. Try this:
var words = ["skate", "guitar", "laugh", "party", "shirt"]
var wordValue = Math.floor(Math.random() * 4) + 1;
var newWord = words[wordValue];
console.log("Word is: " + newWord);
var misses = 0;
var answerLines = [];
for (var i = 0; i < newWord.length; i++) {
answerLines[i] = "_";
}
var remainingLetters = newWord.length;
while (remainingLetters > 0 && misses < 6) {
alert(answerLines.join(" "));
var guess = prompt("Guess a letter, any letter!");
var matchesNone = true; //boolean to track if guess matched any letters
for (var j = 0; j < newWord.length; j++) {
if (newWord[j] === guess) {
answerLines[j] = guess;
remainingLetters--;
matchesNone = false; //the guess matched atleast one letter
}
}
if (matchesNone) { //the guess matched none of the letters
misses ++;
alert("That was is incorrect. You have " + misses + " of 6 misses.");
}
}
if(remainingLetters>0) {
alert("You failed to guess the word: " + newWord);
}else{
alert("You guessed the word! It was: " + newWord);
}
Seeing all the people talking about longest substring in alphabetical order in Python, I have decided to try it in JS.
The function should look for the longest substring inside a given string, where letters are ordered alphabetically.
Here is what I have:
var s = 'azcbobobegghakl'
function substringChecker(s) {
var longestSub = "";
for (var i = 0; i < s.length; i++) {
var count = 0;
var currSub = "";
while((i+count)<=s.length){
var curr = i+count;
var next = curr+1;
var prev = curr-1;
if(curr !== s.length-1) {
if(s[curr] <= s[next]){
currSub += s[curr]
} else {
break;
}
} else {
if(s[curr]>s[prev]) {
currSub += s[curr];
}
}
count++;
}
if(currSub.length >= longestSub.length) {
longestSub = currSub;
}
};
return longestSub;
}
var result = substringChecker(s);;
console.log(result);
The funny thing it works great for all test cases I can come up with, but this one. The result should be "beggh" but it is "begg" instead. Why is the h not showing up, what am I missing?
The algorithm can be linear, I think you are overcomplicating it placing loops inside loops.
I would use something like
function substringChecker(s) {
var longestSub = "",
length = 0,
start = 0,
prev = s[0];
for (var i = 1; i <= s.length; ++i) {
if(i == s.length || s[i] < prev) {
if(length < i-start) {
longestSub = s.substring(start, i);
length = i-start;
}
start = i;
}
prev = s[i];
};
return longestSub;
}
document.write(substringChecker('azcbobobegghakl'));
first I made list of A-z
then check each letter and compare it with the next letter and save it in subString and...
function longest(str) {
//handle the case str is just one letter
if (str.length === 1) return str;
// create a list of alphabet A to Z
const alphabets = [...Array(26)].map(_ => String.fromCharCode(i++), (i = 97));
let longString = "";
let subSting = "";
for (let x = 0; x < str.length; x++) {
let char = str.charAt(x);
const nextChar = str.charAt(x + 1);
let charIndex = alphabets.findIndex(alphabet => alphabet === char);
let nextCharIndex = alphabets.findIndex(alphabet => alphabet === nextChar);
if (nextCharIndex >= charIndex) {
subSting = subSting + nextChar;
} else {
if (!subSting.length) {
subSting = subSting + char;
}
longString = subSting.length > longString.length ? subSting : longString;
subSting = "";
}
}
return longString;
}
console.log(longest("zyba"));