Random String Generator Javascript - While Loop - javascript

Trying to create a random letter generator with a "while" loop. It's return one value into the randomString and then quits the loop.
var alpha = "abcdefghijklmnopqrstuvwxyz";
var randomString = "";
while (randomString.length < 6) {
console.log(randomString += alpha.charAt(Math.floor(Math.random() * alpha.length)));
randomString++;
}
Returns one value from alpha string to randomString and then quits the loop instead of going on for 4 more loops - condition set at (randomString.length < 6).

Incrementing a string results in NaN, which doesn't have a length property, so the loop ends after one iteration.
Don't increment your randomString:
var alpha = "abcdefghijklmnopqrstuvwxyz";
var randomString = "";
while (randomString.length < 6) {
console.log(randomString += alpha.charAt(Math.floor(Math.random() * alpha.length)));
}

create a variable and set is an empty string. Then, create a while loop that will continually add new random letters to this string, as long as the string length is less than 6 or any length you choose. += operator to add a new letter to the end of the string.
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var randomString = "" // first, create an empty string
while (randomString.length < 6) {
console.log(randomString += alphabet[Math.floor(Math.random() * alphabet.length)]);
randomString++;
}

Related

How to split String, convert to Numbers and Sum

I have a function that I have modified to get a string (which consists of zeros and ones only).
The string (timesheetcoldata):
100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000
The string items (the numbers one and zero) will change every time the function is run.
It will always be the same length.
I have made the string above easier to see what I am trying to achieve.
I want to return the first character and then every 24th character (as in the variable colsCount in the function).
so, in the example above, it would return something like: 111111
I then want to convert these characters to numbers (something like [1, 1, 1, 1, 1, 1]).
I then want to sum these number together (so it would return, in the example: 6).
I then want to check if the returned number matches the variable: rowsCount
or true if it does, false if it does not.
My function:
$("#J_timingSubmit").click(function(ev){
var sheetStates = sheet.getSheetStates();
var rowsCount = 6;
var colsCount = 24;
var timesheetrowsdata = "";
var timesheetcoldata = "";
for(var row= 0, rowStates=[]; row<rowsCount; ++row){
rowStates = sheetStates[row];
timesheetrowsdata += rowStates+(row==rowsCount-1?'':',');
}
timesheetcoldata = timesheetrowsdata.replace(/,/g, '');
console.log(timesheetcoldata);
});
Thank you very much to both Rajesh and MauriceNino (and all other contributers).
With their code I was able to come up with the following working function:
$("#J_timingSubmit").click(function(ev){
var sheetStates = sheet.getSheetStates();
var rowsCount = 6;
var timesheetrowsdata = "";
var timesheetcoldata = "";
for(var row= 0, rowStates=[]; row<rowsCount; ++row){
rowStates = sheetStates[row];
timesheetrowsdata += rowStates+(row==rowsCount-1?'':',');
}
timesheetcoldata = timesheetrowsdata.replace(/,/g, '');
var count = 0;
var list = [];
for(var i = 0; i< timesheetcoldata.length; i+=24) {
const num1 = Number(timesheetcoldata.charAt(i));
list.push(num1);
count += num1;
}
let isSameAsRowsCount = count == rowsCount;
console.log('Is Same? ', isSameAsRowsCount);
});
You can always rely on traditional for for such action. Using functional operations can be more readable but will be more time consuming(though not by much).
You can try this simple algo:
Create a list that will hold all numbers and a count variable to hold sum.
Loop over string. As string is fixed, you can set the increment factor to the count(24).
Convert the character at given index and save it in a variable.
Push this variable in list and also compute sum at every interval.
At the end of this loop, you have both values.
var string = '100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000';
var count = 0;
var list = [];
for(var i = 0; i< string.length; i+=24) {
const num1 = Number(string.charAt(i));
list.push(num1);
count += num1;
}
console.log(list, count)
Here is a step by step explanation, on what to do.
Use match() to get every nth char
Use map() to convert your array elements
Use reduce() to sum your array elements
Everything needed to say is included in code comments:
const testData = '100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000';
// Step 1) Create array of numbers from string
const dataArr = testData.match(/.{1,24}/g) // Split on every 24th char
.map(s => Number(s[0])) // Only take the first char as a Number
console.log(dataArr);
// Step 2) Sum array Numbers
let dataSum = dataArr.reduce((a, b) => a + b); // Add up all numbers
console.log(dataSum);
// Step 3) Compare your variables
let rowsCount = 123; // Your Test variable
let isSameAsRowsCount = dataSum == rowsCount;
console.log('Is Same? ', isSameAsRowsCount);
As #Jaromanda mentioned, you can use the following to done this.
const string = '100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000';
const value = string.split('').filter((e,i)=> !(i%24)).reduce((acc,cur)=> acc+ (+cur), 0);
console.log(value);

Sum the number equivalent of alphabets in a word until it's single digit? [duplicate]

This question already has answers here:
Sum up a number until it becomes 1 digit JS
(16 answers)
Closed 3 years ago.
I am trying to solve a problem where a user gives a text input then I have to convert the text into given numeric values, add them together unless the answer is a single digit number.
So far, I have been able to get input, transform them into given numbers and store them in an array. But I cannot figure out what I will do next. How I will add the values together until it is left a single digit number.
var values = {a:1,b:2,c:3,d:4,e:5,f:6,g:7,h:8,i:9,j:10,k:11,l:12,m:13,n:14,o:15,p:16,q:17,r:18,s:19,t:20,u:21,v:22,w:23,x:24,y:25,z:26};
var someText = prompt('');
someText = someText.trim();
someText = someText.match(/\S/g);
var result = "";
for (i = 0; i < someText.length; i++) {
result += values[someText[i]];
}
alert(result);
For Example if input is "action" then numeric values will be
=>1.3.20.9.15.14.
-Add these values together.
1+3+20+9+15+14 answer will be 62.
-As the Answer is a 2 digit number, we add the numbers again
e.g 62 = 6+2= 8.
Note:
If answer is more then 1 digits: e.g 199 => 1+9+9 => 19 => 1+9 => 10 = 1+0 = 1.
Answer must always be a single digit number.
You can use reduce() to get the sum of all the digits of string. If the result is single digit then return the the number otherwise call the function recursively.
You also don't need to hard code the object with letter values. Just use reduce() and chatCodeAt to make a string of numbers.
var someText = prompt('').trim().toLowerCase().match(/\S/g)
let result = someText.reduce((ac,a) => ac + (a.charCodeAt(0) - 96),'');
function findSum(num){
if(num.length === 1) return num;
else return findSum(String(num.split('').reduce((ac,a) => ac + +a,0)))
}
console.log(findSum(result))
Here's how you can do it:
var values = {a:1,b:2,c:3,d:4,e:5,f:6,g:7,h:8,i:9,j:10,k:11,l:12,m:13,n:14,o:15,p:16,q:17,r:18,s:19,t:20,u:21,v:22,w:23,x:24,y:25,z:26};
var someText = prompt('');
someText = someText.trim();
someText = someText.match(/\S/g);
var result = "";
for (i = 0; i < someText.length; i++) {
result += values[someText[i]];
}
// While the result is >9, which means that there's more than 1 digit
while(result > 9) {
// Cast result as String, so we can use charAt()
var stringedResult = String(result);
// Reset our result var, because we're going to recalculate it
result = 0;
// For each int in our result, we add them up (ex. 621 = 6+2+1)
for(var i=0; i<stringedResult.length; i++) {
// Cast the stringed result back to a number, and add it to our result variable
result += Number(stringedResult.charAt(i));
}
}
alert(result);
You should use a function to sum the values and return the value when it's one digit or call itself otherwise:
var values = {a:1,b:2,c:3,d:4,e:5,f:6,g:7,h:8,i:9,j:10,k:11,l:12,m:13,n:14,o:15,p:16,q:17,r:18,s:19,t:20,u:21,v:22,w:23,x:24,y:25,z:26};
var someText = prompt('');
someText = someText.match(/\S/g);
var result = 0;
function getSum(string) {
for (i = 0; i < string.length; i++) {
if (isNaN(string[i])) {
result += values[string[i]];
} else {
result += parseInt(string[i]);
}
}
if (result.toString().length > 1) {
var aux = result.toString();
result = 0;
return getSum(aux);
} else {
return result;
}
}
alert(getSum(someText));

for loop string each word

if this type character '這' = NonEnglish each will take up 2 word space, and English will take up 1 word space, Max length limit is 10 word space; How to get the first 10 space.
for below example how to get the result This這 is?
I'm trying to use for loop from first word but I don't know how to get each word in string...
string = "This這 is是 English中文 …";
var NonEnglish = "[^\u0000-\u0080]+",
Pattern = new RegExp(NonEnglish),
MaxLength = 10,
Ratio = 2;
If you mean you want to get that part of the string where it's length has reached 10, here's the answer:
var string = "This這 is是 English中文 …";
function check(string){
// Length of A-Za-z characters is 1, and other characters which OP wants is 2
var length = i = 0, len = string.length;
// you can iterate over strings just as like arrays
for(;i < len; i++){
// if the character is what the OP wants, add 2, else 1
length += /\u0000-\u0080/.test(string[i]) ? 2 : 1;
// if length is >= 10, come out of loop
if(length >= 10) break;
}
// return string from the first letter till the index where we aborted the for loop
return string.substr(0, i);
}
alert(check(string));
Live Demo
EDIT 1:
Replaced .match with .test. The former returns a whole array while the latter simply returns true or false.
Improved RegEx. Since we are checking only one character, no need for ^ and + that were before.
Replaced len with string.length. Here's why.
I'd suggest something along the following lines (assuming that you're trying to break the string up into snippets that are <= 10 bytes in length):
string = "This這 is是 English中文 …";
function byteCount(text) {
//get the number of bytes consumed by a string
return encodeURI(text).split(/%..|./).length - 1;
}
function tokenize(text, targetLen) {
//break a string up into snippets that are <= to our target length
var result = [];
var pos = 0;
var current = "";
while (pos < text.length) {
var next = current + text.charAt(pos);
if (byteCount(next) > targetLen) {
result.push(current);
current = "";
pos--;
}
else if (byteCount(next) == targetLen) {
result.push(next);
current = "";
}
else {
current = next;
}
pos++;
}
if (current != "") {
result.push(current);
}
return result;
};
console.log(tokenize(string, 10));
http://jsfiddle.net/5pc6L/

How to make a .replace loop in javascript?

I am currently trying to make a .replace function loop in javascript. What I am trying to do is replace a random character with a hyphen, but the part that I am struggling with is how to make it loop the replacing of the character to hyphen. Here is the code that I have so far:
var randHold;
var randomWord;
var randLetHold;
var dispWord;
var repLetHold;
var myWords = new Array("Spectrometer", "Bandwagonjghvyjh", "jvjyvyvilvyjlvyv",
"fruitjjyvtyvjv", "seventctcvtv", "weathertfhtcthc",
"undercfxdtfv"); // random letters to make words that have more than 10 letters
function level() {
randHold = parseInt((Math.random() * 6) + 1);//code to randomly pick a word from the above array
randomWord = myWords[randHold]; //code to call the random word from the array
randLetHold = (Math.random() * randomWord.length);//code to randomly pick a character from the random word chosen
repLetHold = randomWord.charAt(randLetHold);//code to call the random character
for (i = 1; i <= 3; i++) //loop to replace three random characters with a hyphen
{
dispWord = randomWord.replace(repLetHold," - ");//code to replace a random character with a hyphen
document.write(dispWord);//But all this does is display the word(with ONE hypenated character)three times.
}
}
Your code actually seems fine, the main issue is that you're declaring your random variables outside of your for loop. Doing this will only generate them once for the entire loop. Try this instead:
var dispWord;
var myWords = new Array("Spectrometer", "Bandwagonjghvyjh", "jvjyvyvilvyjlvyv",
"fruitjjyvtyvjv", "seventctcvtv", "weathertfhtcthc",
"undercfxdtfv"); // random letters to make words that have more than 10 letters
function level() {
for (i = 1; i <= 3; i++) //loop to replace three random characters with a hyphen
{
var randHold = parseInt((Math.random() * 6) + 1);//code to randomly pick a word from the above array
var randomWord = myWords[randHold]; //code to call the random word from the array
var randLetHold = (Math.random() * randomWord.length);//code to randomly pick a character from the random word chosen
var repLetHold = randomWord.charAt(randLetHold);//code to call the random character
dispWord = randomWord.replace(repLetHold," - ");//code to replace a random character with a hyphen
document.write(dispWord);//But all this does is display the word(with ONE hypenated character)three times.
}
}
For 3 random characters to be hyphenated in the word, you want something like this.
<div id="result"></div>
var myWords = ["Spectrometer", "Bandwagonjghvyjh", "jvjyvyvilvyjlvyv",
"fruitjjyvtyvjv", "seventctcvtv", "weathertfhtcthc",
"undercfxdtfv"]; // random letters to make words that have more than 10 letters
var randomWord;
var dispWord;
var repLetHold = [];
function uniqueCount(str) {
var unique = [];
Array.prototype.forEach.call(str, function (value) {
if (unique.indexOf(value) === -1) {
unique.push(value);
}
});
return unique.length;
}
function level() {
var randHold = Math.floor(Math.random() * myWords.length);
dispWord = randomWord = myWords[randHold];
if (uniqueCount(randomWord) > 2) {
var count = 0,
temp1,
temp2;
while (count < 3) {
temp1 = Math.floor(Math.random() * dispWord.length);
temp2 = dispWord.charAt(temp1);
if (temp2 !== "-" && repLetHold.indexOf(temp2) === -1) {
dispWord = dispWord.replace(new RegExp(temp2, "g"), "-");
repLetHold[count] = temp2;
count += 1;
}
}
}
document.getElementById("result").textContent = dispWord;
}
level();
console.log(randomWord, repLetHold);
on jsfiddle
If you use a regular expression, you can replace all instances at once with the g (global) flag. For example:
var str = "this is a mass Spectrometer, which is a Spectrometer to detect the spectra of different masses";
var replaced = str.replace(/Spectometer/g, 'something');
// "this is a mass something, which is a something to detect the spectra of different masses";
Just keep in mind that some characters must be escaped inside regular expressions.
http://jsfiddle.net/zt8mp/
If i got the question right:
randomWord.replace(new RegExp(repLetHold,'g')," - ")
replaces all occurences of repLetHold (as long as it is not made of special regex characters)

Sum of a string of one-digit numbers in javascript?

I'm trying to write a script that adds the left side of a string and validates it against the right side.
For example:
var left = "12345"
var right = "34567"
I need to do some sort of sum function that adds 1+2+3+4+5 and checks if it equals 3+4+5+6+7.
I just don't have a clue how to do it.
I think I need to use a for loop to iterate through the numbers such as
for (var i = 0, length = left.length; i < length; i++)
But I'm not sure how to add each number from there.
EDIT the var is actually being pulled in from a field. so var left = document.blah.blah
DEMO
var left = "12345"
var right = "12345"
function add(string) {
string = string.split(''); //split into individual characters
var sum = 0; //have a storage ready
for (var i = 0; i < string.length; i++) { //iterate through
sum += parseInt(string[i],10); //convert from string to int
}
return sum; //return when done
}
alert(add(left) === add(right));​
Find the length of the string
then in a temp Variable store the value pow(10,length-1)
if you apply module function (left%temp) you will ge the Last significant digit
you can use this digit to add
repeat the process till the length of the string left is 0
6 Repeat all the steps above for the right as well and then compare the values
Note: convert the string to int using parseInt function
var sum = function(a,b){return a+b}
function stringSum(s) {
var int = function(x){return parseInt(x,10)}
return s.split('').map(int).reduce(sum);
}
stringSum(a) == stringSum(b)

Categories