I created a function in javascript to generate a random string with a certain length in either uppercase/lowercase or both.
function randomString(max, option) {
var rNum = [];
if (option.toLowerCase() === "lowercase") {
for (let i = 0; i < max; i++) {
var randomNumber = Math.floor(Math.random() * (122 - 97) + 97);
rNum.push(randomNumber);
}
} else if (option.toLowerCase() === "uppercase") {
for (let i = 0; i < max; i++) {
var randomNumber = Math.floor(Math.random() * (90 - 65) + 65);
rNum.push(randomNumber);
}
} else if (option.toLowerCase() === "both") {
for (let i = 0; i < max; i++) {
var n = Math.floor(Math.random() * (122 - 65) + 65);
while ([91, 92, 93, 94, 95, 96].includes(n)) {
//If the random number is between 90 and 97 then we keep generating new numbers:
n = Math.floor(Math.random() * (122 - 65) + 65);
}
rNum.push(n);
}
} else {
return "Second parameter not valid, please type 'lowercase','uppercase' or 'both'";
}
var word = "";
for (let i = 0; i < rNum.length; i++) {
var letter = String.fromCharCode(rNum[i]);
word += letter;
}
return word;
}
Now I wanted to create a second function that given any string from the user, it checks whether that word appears in the randomly generated string.
I started it and honestly I simply have no idea how to do it. How do I check where in that long string there is indeed the word which I don't know how long it is. I guess it can see if it does exist or not, but how do i find its position? I tried using array.indexOf(userString)
, but it only returns the first time it appears.
function findWordsByChance(letters) {
var myString = randomString(999999, "both");
var splited = myString.split("");
if (splited.includes(letters)) {
console.log("this combination exists");
} else {
console.log("it doesnt");
}
for (let i = 1; i < splited.length - 1; i++) {
//check where it is (??)
}
}
findWordsByChance("Hi");
I'm still quite new to programming, so give me a break if I made any stupid mistakes :) btw, if you guys got any tips on how to do something I already did but in a more efficient way, I'd appreciate.
Aucun commentaire:
Enregistrer un commentaire