random generator function javascript - javascript

I'm making a guessing game for class. I pretty much have it done, but the biggest problem I've had was making the string randomize itself after the game ends. It picks a random letter if the page refreshes but the objective is to keep track of stats so refreshing is out.
Here's my javascript code:
var lettersChar = ["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"];
function randomFunc() {
var randomMath = lettersChar[Math.floor(Math.random() *
lettersChar.length)];
return randomMath;
}
//variables
var randomChar = randomFunc();
//array where user input will be stored
var userChoices = [];
var wins = 0;
var losses = 0;
var guesses = 9;
//keypress event
document.onkeyup = function (event) {
var userGuess = event.key;
var userOptions = ["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"];
//if guess is correct, +1 to win and refresh game and generate new letter
if (userOptions.indexOf(userGuess) > -1) {
if (userGuess === randomChar) {
wins++;
guesses = 9;
randomFunc();
console.log(wins);
}
//if guess is incorrect, then print wrong guess and -1 to guesses left
else if (userGuess !== randomChar) {
guesses--;
userChoices.push(userGuess);
}
//If guess reaches to 0 add +1 to loss and restarts game
if (guesses === 0) {
losses++;
guesses = 9;
userChoices = [];
randomChar;
}
}
I've tried invoking the function and it doesn't appear to work for me at this moment. Any help is appreciated!

See the last line you posted:
randomChar;
You're just declaring randomChar again and not doing anything with it. If you want to randomize it after the game ends, you should call randomFunc again:
randomChar = randomFunc();
Same for when the user wins: replace with
if (userGuess === randomChar) {
wins++;
guesses = 9;
randomChar = randomFunc();
console.log(wins);
}

Related

How to scroll forwards and backwards in a javascript array

I am new to javascript and would really appreciate some help. The javascript below is connected to two buttons in an an html documented called "next" and "previous". The buttons are intended to allow a user to scroll forwards and backwards through an array that contains the letters of the alphabet. The code is almost working, but has one bug. Clicking the "next" button will display the next letter in alphabet (i.e. B will switch to C). However, clicking the "previous" button will display the next letter in the alphabet before changing directions. For example, if the letter "C" is displayed, clicking "previous" will display "D" and then "C", "B", "A", "Z", etc...
What changes need to be made to the code below to fix this problem? If a letter is displayed, I would like for the function "next" to return the next letter and for the function "previous" to return the letter that comes immediately before the letter being displayed.
function next(){
let upperCase = ["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"];
document.querySelector(".item-2").innerHTML = upperCase[index++];
if(index > upperCase.length - 1)
index = 0;
}
function previous(){
let upperCase = ["A","B", "C", "D", "E","F", "G", "H", "I","J", "Q", "L", "M","N", "O", "P", "Q","R", "S", "T", "U","F", "W", "X", "Y","Z"];
document.querySelector(".item-2").innerHTML = upperCase[index--];
if(index < 0)
index = upperCase.length - 1;
}
You need to set ++ and -- before the index variable in order to return its value after incrementing it:
let index = 0;
const previousButton = document.getElementById('previous');
const nextButton = document.getElementById('next');
previousButton.addEventListener('click', previous);
nextButton.addEventListener('click', next);
const upperCase = ["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"];
function next(){
if(++index > upperCase.length - 1)
index = 0;
document.querySelector(".item-2").innerHTML = upperCase[index];
}
function previous(){
if(--index < 0)
index = upperCase.length - 1;
document.querySelector(".item-2").innerHTML = upperCase[index];
}
<div class="item-2"></div>
<button id="previous">Previous</button>
<button id="next">Next</button>

How to push to an array given that the character is not already present in the array in javascript

I'm trying to push to an initially empty array with the condition that the content at two different indexes of two different non-empty arrays don't have the same character and the initially empty array has not already pushed that character earlier
I've tried using the not operator, contains, includes, but nothing seems to work.
var pushToArray = [];
for (var i = 0; i < 5; i++) {
var characters = ["M", "U", "S", "I", "C"];
var moreCharacters = ["F", "R", "I", "E", "N", "D", "L", "Y"];
randomIndex = Math.floor(Math.random() * moreCharacters.length);
// && push to 'pushToArray' if the character is not in 'pushToArray'
if (characters[i] != moreCharacters[randomIndex] && !pushToArray.includes(moreCharacters[randomIndex])) {
pushToArray.push(moreCharacters[randomIndex]);
}
if(arrayContent1("I") == arrayContent2("I")) then don't push
Sample expected results for pushToArray:
["F", "R", "E", "D", "L"]
Sample actual results for pushToArray:
["I", "F", "R", "D", "Y"] I don't want that letter 'I' in there
The test
if (characters[i] != moreCharacters[randomIndex]
will fail only if characters[i] is the picked character - it sounds like you want to make sure that none of the characters match the picked character:
if (!characters.includes(moreCharacters[randomIndex])
If you're only conditionally pushing to the array, then change the for loop to
while (pushToArray.length < 5) {
var pushToArray = [];
while (pushToArray.length < 5) {
var characters = ["M", "U", "S", "I", "C"];
var moreCharacters = ["F", "R", "I", "E", "N", "D", "L", "Y"];
randomIndex = Math.floor(Math.random() * moreCharacters.length);
// && push to 'pushToArray' if the character is not already in there
if (!characters.includes(moreCharacters[randomIndex]) && !pushToArray.includes(moreCharacters[randomIndex])) {
pushToArray.push(moreCharacters[randomIndex]);
}
}
console.log(pushToArray);
But, the logic would be easier to follow if you filtered the characters out of moreCharacters beforehand:
const excludeChars = ["M", "U", "S", "I", "C"];
const inputChars = ["F", "R", "I", "E", "N", "D", "L", "Y"]
.filter(char => !excludeChars.includes(char));
const result = [];
for (let i = 0; i < 6; i++) {
const randIndex = Math.floor(Math.random() * inputChars.length);
const [char] = inputChars.splice(randIndex, 1);
result.push(char);
}
console.log(result);
This code does this:
I would like array3 to only have letters from array2 that are not in array1. I basically don't want any letters that exist in array1
var characters = ["M", "U", "S", "I", "C"];
var moreCharacters = ["F", "R", "I", "E", "N", "D", "L", "Y"];
var pushToArray = [];
var i, l = characters.length;
for (i = 0; i < l; i++) {
randomIndex = Math.floor(Math.random() * moreCharacters.length);
// && push to 'pushToArray' if the character is not in 'pushToArray'
if (!characters.includes(moreCharacters[randomIndex]) && !pushToArray.includes(moreCharacters[randomIndex])) {
pushToArray.push(moreCharacters[randomIndex]);
}
}
console.log(pushToArray);
This can be simply achieved by doing:
var characters = ["M", "U", "S", "I", "C"];
var moreCharacters = ["F", "R", "I", "E", "N", "D", "L", "Y"];
var pushedToArray = [...characters].filter(x => moreCharacters.indexOf(x) === -1);
var finalArray = pushedToArray.filter((item, index) => pushedToArray.indexOf(item) === index);

Simple Password Encryption with Javascript

This is what I currently have but it is only printing the first Letter in the encryption. Where am I going wrong?
function crypto(){
var password = "Pizza2Day";
var flag = 0;
var encryptedPassword= "";
var originalValues = ["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 encryptedValues = ["m", "h","t","f","g","k","b","p","j","w","e","r","q","s","l","n","i","u","o","x","z","y","v","d","c","a"];
for (var i=0; i < password.length; i++){
flag=0;
for (var r = 0; r < originalValues.length; r++){
if (originalValues[r] == password.charAt(i)){
encryptedPassword = encryptedPassword + encryptedValues[r];
flag = 1;
break;
} else if (originalValues[r].toUpperCase() == password.charAt(i)) {
encryptedPassword = encryptedPassword +
encryptedValues[r].toUpperCase();
flag = 1;
break;
}
}
if (flag == 0) {
encryptedPassword = encryptedPassword + password.charAt(i);
}
return encryptedPassword;
}
}
console.log("New Password: " + crypto());
You need to put the return statement outside the for loop:
function crypto() {
var password = "Pizza2Day";
var flag = 0;
var encryptedPassword = "";
var originalValues = ["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 encryptedValues = ["m", "h", "t", "f", "g", "k", "b", "p", "j", "w", "e", "r", "q", "s", "l", "n", "i", "u", "o", "x", "z", "y", "v", "d", "c", "a"];
for (var i = 0; i < password.length; i++) {
flag = 0;
for (var r = 0; r < originalValues.length; r++) {
if (originalValues[r] == password.charAt(i)) {
encryptedPassword = encryptedPassword + encryptedValues[r];
flag = 1;
break;
} else if (originalValues[r].toUpperCase() == password.charAt(i)) {
encryptedPassword = encryptedPassword +
encryptedValues[r].toUpperCase();
flag = 1;
break;
}
}
if (flag == 0) {
encryptedPassword = encryptedPassword + password.charAt(i);
}
}
return encryptedPassword;
}
console.log("New Password: " + crypto());
You could take another aproach by using strings instead of arrays for the characters and take String#indexOf for getting the index of the given string.
A check if the index is -1, the value for a missing character in the string ins not necessary, because this value is taken as index for the the encrypted string. This returns either a character or undefined, which is a falsy. In combination with a following logical OR ||, the next value is taken, in this case the original character of the string to encode.
After a check if the original character is an upper case character, the character is converted to uppercase and then added to the result string.
function crypto() {
var password = "Pizza2Day",
encryptedPassword = "",
original = "abcdefghijklmnopqrstuvwxyz",
encrypted = "mhtfgkbpjwerqslniuoxzyvdca",
i, character;
for (i = 0; i < password.length; i++) {
character = encrypted[original.indexOf(password[i].toLowerCase())] || password[i];
if (password[i] === password[i].toUpperCase()) {
character = character.toUpperCase();
}
encryptedPassword += character;
}
return encryptedPassword;
}
console.log("New Password: " + crypto());

manually sorting a paragraph by made-up alphabet with javascript

I'm trying to sort a paragraph alphabetically, not according to the normal ABC but a made-up one (var order).
I wrote this function and it works great, but only for the first letter of each word - not in-word sorting as well (for example, in correct ABC 'banana' would come before 'birthday').
I'm not sure where to go from here.
$("#send").click(function () {
var text = $("#text").val().replace(/[^A-Za-z0-9_\s]/g, "").toUpperCase().split(" ");
var order = ["Q", "B", "K", "D", "H", "V", "Z", "E", "F", "O", "G", "L", "M", "S", "N", "P", "I", "X", "A", "R", "W", "U", "C", "J", "T", "Y"];
var i, t, j;
var newText = []; // will hold the new alphabet
// function to sort the words:
for (i = 0; i < order.length; i++) {
for (t = 0; t < text.length; t++) {
var firstChar = text[t][0];
if (order[i] == firstChar) {
newText.push(text[t]);
}
}
}
console.log(newText.join(','));
});
EDIT:
An example input can be: "Hi dan don't you think that this is awesome",
and I want the output to be: "don't dan hi is awesome this think that you".
You could use an object with the index of the letters and use Array#sort with a callback which looks for every letter adn calculates the order.
function foo(text) {
var text = text.replace(/[^A-Za-z0-9_\s]/g, "").toUpperCase().split(" "),
order = "QBKDHVZEFOGLMSNPIXARWUCJTY",
ref = {};
order.split('').forEach(function (a, i) { ref[a] = i + 1; });
text.sort(function (a, b) {
var i = 0, v;
do {
v = (ref[a[i]] || 0) - (ref[b[i]] || 0);
i++;
} while (!v)
return v;
});
console.log(text.join(', '));
}
foo('a aa ab b ba bb');
foo('banana birthday');
The problem with your algorithm is that it only compares the first letter in each word, but if the letters are the same the algorithm needs to compare the next letter in each word. Here's a solution that uses recursion:
function doSort(inputArr) {
var words = inputArr.slice(0);
var alphabet = ["Q", "B", "K", "D", "H", "V", "Z", "E", "F", "O", "G", "L", "M", "S", "N", "P", "I", "X", "A", "R", "W", "U", "C", "J", "T", "Y"];
words.sort(function(item1, item2) {
return sortRecursive(item1, item2, 0);
});
function sortRecursive(item1, item2, idx) {
if (item1.length <= idx && item2.length <= idx) {
return 0;
} else if (item1.length <= idx) {
return -1;
} else if (item2.length <= idx) {
return 1;
} else if (item1[idx] == item2[idx]) {
return sortRecursive(item1, item2, idx+1);
} else {
return alphabet.indexOf(item1[idx].toUpperCase()) - alphabet.indexOf(item2[idx].toUpperCase());
}
}
return words;
}
var arr = ["banana", "quebec", "bird", "birthday", "birdman", "bird"];
var sortedArr = doSort(arr);
console.log('unsorted',arr);
console.log('sorted', sortedArr);
https://jsfiddle.net/2qgaaozo/

Append Div with Multiple Child Divs Using For Loop

I realize that this has been asked a million times... but sorting through all the ones I've found, I haven't found one that really explains it well.
HTML:
<div id="alphabet"></div>
JS:
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 target = document.getElementById('alphabet');
for (i = 0; i < 26; i++) {
var newLink = document.createElement('div');
target.appendChild = newLink;
newLink.innerHTML = alphabet[i];
}
alert(alphabet);
alert(newLink);
alert(target);
Obviously there is something I'm missing... With such a simple example I can't believe I'm having this much trouble. Any help is much appreciated, thanks in advance!
Basically node.appendChild(node) is a function.
target.appendChild(newLink);
And your full code would be,
for (i = 0; i < 26; i++) {
var newLink = document.createElement('div');
newLink.innerHTML = alphabet[i];
target.appendChild(newLink);
}

Categories

Resources