JavaScript if answer is correct, generate new string - javascript

I have a program that randomly generates two numbers (x and y) and asks the user to multiply them. Once they multiply them, it will tell them if they get it right or wrong. The thing I'm having problems with is that if they get the answer correct, it should then generate a new set of numbers. I'm not sure how to make the program perform that function again. Also it has to clear the answer field no matter if they get it right or wrong. Thanks!
var x, y; // global variables for randomly generated numbers
var correct = ['Very good!', 'Excellent!', 'Correct - Nice work!', 'Correct - Keep up the good work!'];
var incorrect = ['No. please try again.', 'Wrong. Try once more.', 'Incorrect - Dont give up!', 'No - Keep trying.'];
// getting two random numbers between 1-12 then assigning them to x and y
function generateNumbers() {
function aNumber() {
return Math.floor((Math.random() * 12) + 1);
}
x = aNumber();
y = aNumber();
}
// generating the question that will be used with the random numbers x and y
function genQuestion() {
generateNumbers();
document.getElementById('question').value = x + " times " + y;
}
// function that is performed when the button "check answer" is clicked. It will generate one of 4 answers depending
//if it's right or wrong and will add 1 to the value of total. If it's incorrect it won't add anything
function buttonPressed() {
var correctans = correct[Math.floor(Math.random() * 4)]; // randomly selecting an answer if it's correct
var incorrectans = incorrect[Math.floor(Math.random() * 4)]; // randomly selecting an answer if it's incorrect
var answer = document.getElementById('answer').value;
if (answer == x * y) // correct
{
function genQuestion() {
generateNumbers();
document.getElementById('question').value = x + " times " + y;
}
window.alert(correctans);
var total = document.getElementById('total').value++;
}
else { // incorrect
window.alert(incorrectans);
}
}

You're not calling the genQuestion function, and it makes little sense to redefine it.
// function that is performed when the button "check answer" is clicked. It will generate one of 4 answers depending
//if it's right or wrong and will add 1 to the value of total. If it's incorrect it won't add anything
function buttonPressed() {
var correctans = correct[Math.floor(Math.random() * 4)]; // randomly selecting an answer if it's correct
var incorrectans = incorrect[Math.floor(Math.random() * 4)]; // randomly selecting an answer if it's incorrect
var answer = document.getElementById('answer').value;
if (answer == x * y) // correct
{
//call genQuestion to create new question
genQuestion();
window.alert(correctans);
var total = parseInt(document.getElementById('total').value)++;
}
else { // incorrect
window.alert(incorrectans);
}
//clear 'answer' field
document.getElementById('answer').value = '';
}

Related

How to find if an array has a random number [Math.floor((Math.random() * 10) + 1)] or not in it in js

I am trying to create a hangman game in html,css,js.
So i am now to give it a randomisation on based how the question will be displayed -
Create the Random number - Math.floor((Math.random() * 10) + 1)
First of all check if the array(this array contains which questions are already done) has the random number
if not
if yes
then allow the below statement to happen
then let the function run again and agiin until random number is not there in th array
First question based on the random number and second olso and so on
But actually i cannot figure out how to check in the array has the random number. I tried:-
this works
function NextQuestion() {
let done = ['1','2'];
let random = Math.floor((Math.random() * 10) + 1);
let include = done.includes('1');
if (include == true) {
alert('true');// this works
}
}
this doesn't
function NextQuestion() {
let done = ['1','2'];
let random = Math.floor((Math.random() * 10) + 1);
let include = done.includes(random);
if (include == true) {
alert('true');// this does not works
}
}
The difference is that in the first one it has includes('1'); but in second it has includes(random);
Do you know why this happens if you do please let me know and please give the solution to this problem
Thanks in advance.
This will explain why
let random = Math.floor((Math.random() * 10) + 1);
console.log(random)
console.log(
["1","2","3","4","5","6","7","8","9","10"].includes(random)
);
console.log(
[1,2,3,4,5,6,7,8,9,10].includes(random)
);
So your hangman will work if you store the random as they are created
#mplungian correctly answered the question you raised in your title. But I believe you are going the wrong way about it if want to ask a given number of questions in a random sequence. For this you should simply step through the questions array with a for loop. But before you do that the array should be shuffled:
function shfl(a){
// Durstenfeld shuffle:
for(let i=a.length;i>1;){
j=Math.floor(Math.random()*i--);
if (i!=j) [a[i],a[j]]=[a[j],a[i]]
}
return a
}
const q=[1,2,3,4,5,6,7,8,9,10];
shfl(q);
q.forEach((n,i)=>console.log(i+1+". Q"+n));

Generate a new random number each time function is called in Javascript

I am trying to learn javascript, I am playing with a game that picks a random number.
I would like to have 2 functions, random and guess. Random generates a new number between 1-10. Guess is where it checks if the number was guessed, if not re-runs the random function and generates a new number to try.
var x;
function random(){
let x = Math.floor((Math.random() * 10) + 1);
guess();
}
function guess(x){
if(x === 3){
alert('you are correct!');
}else{
alert('try again');
random();
}
}
random();
This just alerts try again every time, i'm guessing because it's not generating a new number each time the function is called?
How can you create the random function so it generates a new number each time its called?
***** Correction, it appears to generate a new number but x is undefined within the guess function**
The x in the guess() is the x that gets passed to it as a parameter. I would remove the var x; declaration and pass a value when calling like guess(x)
function random(){
const x = Math.floor((Math.random() * 10) + 1);
guess(x);
}
function guess(x){
if(x === 3){
alert('you are correct!');
}else{
alert('try again');
random();
}
}
random();
The guess function's signature says that it takes a parameter x, but you're not passing any value to the function when it's called, so it's assigning undefined to x when it runs guess, which will never equal 3. You can take 2 approaches to fix this. First, you could make x a global variable by getting rid of the let where you define x in the random function and removing x from guess's function signature, like so:
var x;
function random() {
x = Math.floor((Math.random() * 10) + 1);
guess();
}
function guess() {
if (x === 3) {
alert(x + '- you are correct!');
}
else {
alert(x + '- try again');
random();
}
}
random();
Or, you could use x as a parameter for the guess function by removing the var x; global declaration and passing x to guess when you call it in the random function, like so:
function random() {
let x = Math.floor((Math.random() * 10) + 1);
guess(x);
}
function guess(x) {
if (x === 3) {
alert(x + '- you are correct!');
}
else {
alert(x + '- try again');
random();
}
}
random();
I personally wouldn't even have a random function. I'd just define x within guess and call guess from within itself. And, I'd use randojs.com to make the randomness more readable. Here's how I'd do it:
function guess() {
let x = rando(1, 10);
if (x === 3) return alert(x + '- you are correct!');
alert(x + '- try again');
guess();
}
guess();
<script src="https://randojs.com/1.0.0.js"></script>
Note that the return statement would stop the execution of the function right then and there, so it wouldn't progress to the "try again" alert if the number was guessed correctly.
Here's some detailed code that will help you understand how to run such a game in the browser.
See the comments for explanation of how it works (and search for information on MDN to learn more about any particular topic.)
Happy coding!
// Identifies HTML elements
const
guessInput = document.getElementById("guessInput"),
outputParagraph = document.getElementById("outputParagraph");
// Makes a global variable that all functions can access
let globalNum;
// Invokes the main function
playGame();
function playGame(){
// Invokes the randomizer function and stores the result in the global variable
globalNum = getRandomNumber();
//console.log(globalNum);
// Invokes the output function
setOutput("Guess a number from 1 to 10");
// Assigns a function that will be invoked whenever the user changes the input field
guessInput.addEventListener("change", respondToGuess);
// Puts the focus in the input element
guessInput.focus();
}
// Defines a listener function that can automatically see the triggering event
function respondToGuess(event){
// Gets the `target` element of the event and stores it in a local variable
const localReferenceToInputElement = event.target
// The text of an `<input>` element lives in its "value" property
const inputText = localReferenceToInputElement.value;
// Tries to convert the text string to an integer (and store it locally as 'guess')
let guess = parseInt(inputText);
// If the conversion failed, changes the output accordingly
if(!guess){ setOutput("Please enter a valid number"); }
// If the number is out of range, changes the output
else if(guess < 1 || guess > 10){ setOutput("Only numbers from 1 to 10 are allowed"); }
// If the guess doesn't match the stored number, changes the output
else if(guess !== globalNum){ setOutput("Try again..."); }
// If we got this far, the guess was correct, so changes output and ends game
else{
setOutput("You guessed it!");
reset();
}
}
function getRandomNumber(){
// Returns a random number into whatever function called this function
const x = Math.floor((Math.random() * 10) + 1);
return x;
}
function setOutput(outputText){
// The text of a paragraph element lives in its `innerHTML` property
outputParagraph.innerHTML = outputText;
}
function reset(){
// Clears the input and stops listening for changes
guessInput.value = "";
guessInput.removeEventListener("change", respondToGuess);
}
<input id="guessInput" />
<p id="outputParagraph"></p>
I have done some changes to your code.
You have problem with the concept of function calling function.
In real code it will kill your memory.. your function calls function the function not close and call the function again and again... and its fill the memory .
var x;
// flag correct will close the loop when you have right umber
var correct = false;
function random() {
x = Math.floor((Math.random() * 10) + 1);
guess(x);
}
function guess(x) {
if (x === 3) {
alert('you are correct!');
// if number is right flag is up
correct = true;
} else {
alert('the number is ' + x + ' try again');
}
}
// loop until the number is right
while (correct != true) {
random();
}

Why does it only sums the last two numbers?

I am trying to make a program that sums every number given as parameter. To do so, I wrote the following code:
var x = 0;
var i = 2;
while (isNaN(+process.argv[i + 1]) == false){
x = +process.argv[i] + +process.argv[i + 1];
i++;
}
console.log(x);
The problem is that the code I wrote sums only the 2 last parameter.
I launch my code using node sumArgs.js 1 2 3
and it returns 5.
What is the problem with my code and why isn't it working as planned ?
What is happening every time you loop through, it is taking the current parameter, and the next, and setting x to equal the sum of those.
x needs to be added to, not set. You can do this either:
x += process.argv[i]
or
x = x + process.argv[i]
I'm also not sure why you are adding 2 arguments each loop, as this will cause the sum to be incorrect at the end (unless you increment i twice each loop).
I should note that map reducing it, as in another comment, wouldn't work as the first 2 arguments would not be parameters passed to the program, they would be "node" and "program.js".
var x = 0;
var i = 2;
while (isNaN(+process.argv[i]) == false){
x = x + process.argv[i];
i++;
}
console.log(x);
However, what you could do is use slice:
var sum = process.argv.slice(2).reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
});

JavaScript Help(It's pretty simple im a beginner)

function mathProb() {
var x = parseInt(prompt("Enter first integer", ""));
var y = parseInt(prompt("Enter the second integer", ""));
var operand = prompt("Enter type of operation", "");
if (operand == "+" || "add") {
var sum = x + y;
document.write("Your sum is " + sum);
} else if (operand == "-") {
var difference = x - y;
document.write("Your difference is " + difference);
} else if (operand == "*") {
var product = x * y;
document.write("Your product is " + product);
} else if (operand == "/") {
var quotient = x / y;
document.write("Your quotient is " + quotient);
} else {
document.write("Oops something went wrong");
}
}
Well to start I am reading a book on JavaScript and have been doing pretty well, I am now on functions and was getting those until parameters were introduced can someone explain what a parameter is in a clear simple way?
Why does this function work when named function mathProb() and function mathProb(x,y,operand)?
And a third question off of the previous one is why when I call the function in html
(<input type="button" value="Calculator" onclick="mathProb()"/>)
I have to use mathProb() even if its named mathProb(x,y,operand). If I call it using that name it wont work. Please help?
First, the line:
if(operand=="+"||"add")
Will always be true, as the expression "add" will always return a true-ish value. You probably mean to use:
if(operand=="+" || operand=="add")
Your question about parameters is probably a pretty broad topic. Basically, a parameter is a variable given to a function so that the function can be generalized to work with any data. For example, if you wanted to write a function that can add two numbers, the function must know which two numbers to add. These numbers would be supplied as parameters:
function add(x, y)
{
return x + y; // x and y are variables known within this function
}
You'd then call your function as so:
var oneplusone = add(1, 1); // Adds 1 and 1
Using this knowledge, you could rewrite your code as this:
function mathProb(x, y, operand)
{
// No need for var x, etc as these can now be passed in..
}
Then call your function:
mathProb(
parseInt(prompt("Enter first integer","")), // This is x
parseInt(prompt("Enter the second integer","")), // This is y
prompt("Enter type of operation","") // This is operand
);
Keep in mind you could still call your function mathProb without the parameters:
mathProb();
...if you really wanted to. JavaScript does allow this (unlike many other languages). However, within your function, the variables x, y and operand will be undefined which might cause unexpected results if you don't account for that.
You need call and pass function like mathProb(1,2,'+')
HTML:
<input type="button" value="Calculator" onclick="mathProb(1,2,'+')"/>
Javacript:
function mathProb(x,y,operand)
{
//var x = parseInt(prompt("Enter first integer",""));
//var y = parseInt(prompt("Enter the second integer",""));
//var operand = prompt("Enter type of operation","");
if(operand=="+"|| operand=="add")
{
var sum = x+y;
document.write("Your sum is " +sum);
}
else if(operand=="-")
{
var difference = x-y;
document.write("Your difference is " +difference);
}
else if(operand=="*")
{
var product = x*y;
document.write("Your product is " +product);
}
else if(operand=="/")
{
var quotient = x/y;
document.write("Your quotient is " +quotient);
}
else
{
document.write("Oops something went wrong");
}
}

Random Number with javascript or jquery

I am trying to make a script to pick random number between two numbers . but it picks same number sometimes. i donot want to repeat same number until array is finished .
Here is my code
$(document).ready(function () {
abc();
test = array();
function abc() {
res = randomXToY(1, 10, 0);
$('#img' + res).fadeTo(1200, 1);
//$(this).addClass('activeImg');
//});
setTimeout(function () {
removeClassImg(res)
}, 3000);
}
function removeClassImg(res) {
$('#img' + res).fadeTo(1200, 0.1);
//$('#img' + res).removeClass('activeImg');
abc();
}
function randomXToY(minVal, maxVal, floatVal) {
var randVal = minVal + (Math.random() * (maxVal - minVal));
return typeof floatVal == 'undefined' ? Math.round(randVal) : randVal.toFixed(floatVal);
}
});
Does Anybody have idea about this ...
You'll have to maintain a list of numbers that have already been generated, and check against this list. Re-generate a new number if you find a dupe.
If you do not want the random numbers repeating themselves you have to keep track of the some way.
If you have the range you are dealing with is relatively small, you can create an array with all possible results and simply randomly pick out of it.
function Randomizer(minVal, maxVal, floatVal){
var possible_results = []; // for larger arrays you can build this using a loop of course
var randomization_array = [];
var count = minVal;
var incrementor = floatVal || 1; // set the distance between possible values (if floatVal equals 0 we round to 1)
while (count <= maxVal) {
possible_results.push(count);
count += incrementor;
}
this.run = function(){
// if randomization_array is empty set posssible results into it
randomization_array = randomization_array.length ? randomization_array : $.merge(randomization_array, possible_results);
// pick a random element within the array
var rand = Math.floor(Math.random()*randomization_array.length);
// return the relevant element
return randomization_array.splice(rand,1)[0];
}
}
and in order to use it (it creates a specialized object for each possible range):
rand = new Randomizer(1,10,0);
rand.run();
note that this approach does not work well for very large ranges

Categories

Resources