How to swap two numbers using javascript function with one parameter - javascript

My Requirement is
I want to display this output when I gave a(0) the output should come 5 and when I gave a(5) the output should come 0.
a(0) = 5
a(5) = 0
like this
Hint:
Using this function
function A(num){}
like this
Please Help me how to do this I'm new in JS
Please give me different kind of solutions its more useful to my career.

function swap (input) {
if( input == 0)
return 5;
return 0;
}
i think there is no description needed

I think I see what you are getting at.
You want to input one variable into a function, and return another variable that is not defined yet. Then you want to define that variable by inputting it into the same function, and get the first input as the output. And so you should end up with 2 outputs.
Now this is technically impossible, because there are undefined variables at play. However, programming is about imagination and I think I have a solution (it's technically a hack but it will work):
var i = 1;
var output1;
var output2;
function swap(input) {
function func1(input) {
output2 = input;
i++;
}
function func2(input) {
output1 = input;
i = 1;
alert(String(output1) + "\n" + String(output2));
}
if (i === 1) {
func1(input);
}
else if (i === 2) {
func2(input);
}
}
while(true) {
swap(prompt("Enter your first input (this will be your second output):"));
swap(prompt("Enter your second input (this will be your first output):"));
}
The swap function goes back and forth between the values 1 and 2 in the variable i. That is how it keeps track of first or second inputs and their exact opposite outputs. The input, or parameter of the swap function is whatever the user types into the prompt boxes. Feel free to make it user-friendly, this is just the dirty code behind it. The reason they are outputted together is because the second input is undefined, and so the machine cannot guess what you were going to input. So first my little program collects all the data and just reverses the order when it is time to output. But to the user who knows nothing about JavaScript and what is going on underneath the hood, this would work perfectly in my opinion.
This should work for any data types inputted, I tested it myself with objects, strings, numbers, and arrays. Hope this helps!!

Shorter alternative to #mtizziani's answer:
let swap = x => !x * 5 // yes this is all
console.log(swap(0));
console.log(swap(5));
We toggle the input, so x is now 1 or 0
We multiple by 5.
Job done.

Related

basic Javascript While loop and boolean value questions

I would ask my instructor, but whenever I do, he gives me an even more vague answer to my questions, so I'm asking yall for help. We "learned" (i.e. watched videos) about for and while loops and I get it, I feel like I do, but whenever it comes to doing the assignments given, I feel like they don't make sense. Like back in math class in high school, they'd teach you about the problems, but then when it came time to do your homework, the problems were completely different from what you just learned about. For instance, it says the basic while loop structure is:
while(condition is true) {
//do something
}
But then in this assignment, it gives me:
// Another way to write a while loop is to have a boolean variable
// where the condition goes and then test every time if you need to
// change the boolean to false.
// Below we have a variable lessThan5 and it is set to true.
// Create a loop that tests if our variable 'j' is less than 5.
// If it is less than 5 then Increment it by 1. If it is not
// less than 5 then set our lessThan5 variable to be false.
let lessThan5 = true;
let j = 0;
while(lessThan5) {
}
We didn't learn anything about using boolean values in while loops and I feel like I'm meant to infer what to do, and what structure to use and I just have no idea. Aside from the fact I feel like the instructions to many of these questions are poorly worded, which only confuses me more!
So then there's this third one:
// Example of what the number game would look like:
// Couple things to note:
// Math is a built in object in javascript.
// Math.round() will round a decimal number to a whole number.
// Math.random() returns a decimal number between 0 to 1.
// (But not including 1)
function guessNumberGame(guess) {
let guessing = true;
let number = Math.round(Math.random() * 100);
while(guessing) {
if(guess === number) {
guessing = false;
} else {
guess = Number(prompt("That number didn't work. Try again: "));
}
}
}
// Problem 3
// We will give you a number through the 'num' parameter
// Create a while loop that will loop 'num' amount of times.
// For example if num is 3 then your while loop should loop 3 times
// If num is 20 then the loop should loop 20 times.
// Increment k every loop.
let k = 0;
function keepLooping(num) {
}
If this Problem 3 is meant to be related somehow to the number game example, I can't see it. I don't even know what it is I need to be asking. Does this make any sense to anyone? And nobody else is publicly asking questions about any of this, and it's making me feel stupid and like I am the only one too dumb to get what's going on. I was doing really well and ahead of schedule with all this until this point, but just none of this is making any sense to me.
Welcome to programming, JavaScript (JS), and StackOverflow (SO)!
Let's dive into this a little deeper. First, a quick JavaScript primer: in JavaScript, everything can be classified as either an expression or a statement. At a super high and not-technical level:
expression: something that produces a value
statement: an instruction to the computer
(For a much longer explanation, see here)
Often, statements have slots that can take expressions. Loops are a great example of that.
For example, 1 + 1 is an expression, since it produces the value 2. Even more simply, 1 on its own is also an expression, since it produces the value 1. while(/*some expression here*/) is a statement that has a slot for an expression. for(s1, e2, e3) is also a statement that has slots for statements and slots.
So, the while loop acts on an expression, and will continue to loop as long as the value returned by that expression is truthy. truthy and falsey is an interesting concept in JavaScript and can be a whole essay on it's own, but the tl;dr of it is that anything that == true is truthy, and anything that == false is falsey
So for your first question, 0 < 5 == true, while 5 < 5 == false. Thus, if you make the value of j be greater than or equal to 5, the loop will break.
let lessThan5 = true;
let j = 0;
while(lessThan5) {
// For each cycle of the loop, check if `j` is less than 5
if (j < 5) {
// If `j` is less than 5, increment it
j++; // This is equivalent to saying j = j + 1, or j += 1
} else {
// If `j` is not less than 5, set `lessThan5` to `false`
// Not when the loop goes to iterate again, `false == false`, and it stops
lessThan5 = false;
}
}
I think given the above you should be able to solve the third problem. Please let us know if you have trouble with it, show us what you try, and we'll be happy to help some more :)
Let's take a deep breath and relax. I'm a very senior developer and can't tell -- from your examples -- what's going on here. Maybe that's because your instructor is terrible, maybe it's because you've missed some context in your class, and so it's omitted from the question.
I can answer the two questions you've been given. Hopefully it'll be helpful.
First:
I do not know why your materials claim that a while loop might be written this way. I've completed the assignment, but it seems very odd. But if they want you to complete it, here's a solution.
// Another way to write a while loop is to have a boolean variable
// where the condition goes and then test every time if you need to
// change the boolean to false.
// Below we have a variable lessThan5 and it is set to true.
// Create a loop that tests if our variable 'j' is less than 5.
// If it is less than 5 then Increment it by 1. If it is not
// less than 5 then set our lessThan5 variable to be false.
let lessThan5 = true;
let j = 0;
while(lessThan5) {
if (j >= 5) {
lessThan5 = false;
} else {
j++;
}
}
Moving on to the second snippet, the second snippet does not, to me, appear to be related to guessNumberGame in any way.
And the solution to "Problem 3" seems useless to me. A loop that doesn't do anything is not useful in real life.
That said, the solution to "Problem 3" is as follows:
// Problem 3
// We will give you a number through the 'num' parameter
// Create a while loop that will loop 'num' amount of times.
// For example if num is 3 then your while loop should loop 3 times
// If num is 20 then the loop should loop 20 times.
// Increment k every loop.
let k = 0;
function keepLooping(num) {
while(k < num) {
k++;
}
}

In school and trying to create the classic guess a number game. What did I do wrong?

This code is supposed to be a guess the number game. The object is to get JS to display an alert box that asks the user to guess a number. When they guess a number, the code is supposed to return the values of what they have guessed until they get it correct.
When I run the play key, an alert box does pop up, and says:
"Enter a guess between 1 and 100"
After that, even if I enter all 100 numbers, the box re-loads forever.
Here's what I have:
const game = {
title: 'Guess the Number!',
biggestNum: 100,
smallestNum: 1,
playerChoice: null,
secretNum: null,
//1. Add a prevGuesses property to the game object initialized to an empty array.
prevGuesses: [],
//2. Add a getGuess method to game that prompts the player to enter a guess with a message formatted as: Enter a guess between [smallestNum] and [biggestNum]: Hint- Use a template literal for the prompt message.
//3. Ensure that the getGuess method returns a value that is:
//-is a number, not a string
// -is between smallestNum and biggestNum, inclusive
// -Hints: This is a great use case for a while loop. parseInt returns NaN if the string cannot be parsed into a number
getGuess: function() {
while (this.playerChoice !== this.secretNum) {
var playerChoice = prompt(`Enter a guess between ${this.smallestNum} and ${this.biggestNum}: `);
var wholeNumber = parseInt(this.playerChoice);
if (this.wholeNumber > this.biggestNum) {
var wholeNumber = 100;
}
if (this.wholeNumber < this.smallestNum) {
var wholeNumber = 1;
}
if (typeof this.wholeNumber !== "number")) {
var wholeNumber = Math.floor(Math.random() * 100)
}
}
},
//4. From within the play method, invoke the getGuess method and add the new guess to the prevGuesses array
play: function() {
this.secretNum = Math.floor(Math.random() *
(this.biggestNum - this.smallestNum + 1)) + this.smallestNum;
game.getGuess();
this.prevGuesses.push(this.wholeNumber);
//6 the play method should end(return) when the guess matches the secretNum
if (typeof(this.wholeNumber) === "number" && this.wholeNumber !== this.secretNum) {
game.render();
}
},
// 5. Add a render method to game that play will call after a guess has been made that alerts:
// -if the secret has been guessed: "Congrats! you guessed the number in [x] guesses!"
// otherwise
// -"Your guess is too [high|low]"
// "Previous guesses: x, x, x, x"
// Hints: render wont be able to access any of play's local variables, e.g., guess, so be sure to pass render any arguments as needed. Template literals not only have interpolation, they honor whitespace - including line breaks! The list of previous guesses can be generated using the array join method.
render: function() {
if (this.wholeNumber === secretNum) {
alert(`Congrats! You guessed the number in ${game.prevGuesses.length} guesses!
Previous guesses: ${prevGuesses}`);
} else if (this.wholeNumber > this.secretNum) {
alert(`Your guess is too high!
Previous guesses: ${this.prevGuesses}`);
game.guess();
} else if (this.wholeNumber < this.secretNum) {
alert(`Your guess is too low!
Previous guesses: ${this.prevGuesses}`);
game.guess();
}
}
};
game.play();
/*
Allow the player to continually be prompted to enter their guess of what the secret number is until they guess correctly
If the player has an incorrect guess, display an alert message that informs the player:
Whether their guess is too high, or too low, and...
A list of all the previously guessed numbers (without showing the square brackets of an array)
If the player has guessed the secret number:
Display an alert message that congrats the player and informs them of how many guesses they took
End the game play*/
/*
Bonus: when play is run, immediately prompt the player to enter the smallest and biggest numbers instead of having them pre-set*/
The research that I've done: I've googled as many pages as I could find and youtube tutorials on functions, play object, loops within arrays, anything that I could think of that's related to the types of objects in this code.
the comment text is from the assignment. While I was working on it, I put the comments next to the code that I was working on.
I really am only a few weeks into coding and appreciate any feedback.
This is the original code that I was provided:
const game = {
title: 'Guess the Number!',
biggestNum: 100,
smallestNum: 1,
secretNum: null,
play: function() {
this.secretNum = Math.floor(Math.random() *
(this.biggestNum - this.smallestNum + 1)) + this.smallestNum;
}
};
There are several issues with your code:
this.wholeNumber never receives a value, so that will not work. Also, it does not seem the purpose of this exercise to have such a property. You should not have to store the user's guess in a new property this.wholeNumber. See next point:
The goal of getGuess is to return a number, but there is no return statement. You seem to want to store the number in a property, but that is not the assignment.
Related to this: in play you should get the guessed number as a return value from the call to getGuess
The goal of getGuess is not to wait for the user to guess right, only for the user to make a valid guess (within range and not NaN). So the condition of your while loop is not correct.
getGuess does not verify that parseInt returned NaN. Note that the type of NaN is "number", so the last if's condition will never be true. You should use the isNaN function, or better Number.isNaN.
play should always call render, not only when the guess is right.
render should be called by passing it an argument (the guessed number), and thus the render method should define a parameter for it.
The render method should not call game.guess(). That is not its job.
The play method should not put a new value in secret, otherwise the user will be playing against a moving target :) The secret should be set once in the main program
The main program -- where you currently just have game.play() -- should have the looping logic, which you had tried to implement elsewhere. Here is where you should repeat calling game.play() until the guess is right. It is also here where you should display alert messages about guesses that are too low, too high, ...etc.
There is no clear instruction where the main program should get the latest guess from. It can get it from game.prevGuesses, but I would suggest that the play method also returns the latest guess, just like getGuess should do.
Take note of the other instructions that are given in comments for the main program. For instance, when the user has guessed right you should alert after how many attempts they got it right. Think of which property can help you to know this number of attempts. Hint: length.
I will not provide the corrected code here, as I think with the above points you have enough material to bring this exercise to a good end. Happy coding.
Use parentheses to invoke the play function.
game.play();

If Else Statements in Javascript for LiveCycle

I am creating a form on Adobe LiveCycle that adds the numbers in different fields. I need to have the final field (Eligible Assets) add all the previous fields but exclude the sum of three of them and one in specific but only if it is greater than 60000. I've written the script as follows for the first part (to sum all the fields) this is in a field I've titled TotalAssets:
this.rawValue =Cash.rawValue+SavingsAccount.rawValue+ChildrensSavings.rawValue+CheckingAccount.rawValue+ValueHome1.rawValue+ValueHome2.rawValue+ValueVehicle1.rawValue+ValueVehicle2.rawValue+ValueVehicle3.rawValue+BusinessAccount.rawValue+BusinessAssets.rawValue+StocksBonds.rawValue+Retirement.rawValue+CDs.rawValue+OtherInvestments.rawValue+OtherAssets.rawValue;
This has worked fine, but the Retirement value if it is greater than 60000 should not be added into the calculation. This is what I've written (EligibleAssets):
if (Retirement.rawValue > 60000) {
Retirement.rawValue = 0;
} else {
Retirement.rawValue == Retirement.rawValue ;
}
this.rawValue = TotalAssets.rawValue - (ValueHome1.rawValue+ValueVehicle1.rawValue +Retirement.rawValue);
When I save the form as a PDF the first total of the fields calculates correctly but the second field comes up blank.
If you can spot what I'm missing or doing wrong I would really appreciate any feedback. Thank you!
There are two simple problems that I see here.
First problem is that you are using == when you should be using =.
== - check if the left side is equal to the right side. Example: if(x == 5) {
= - set the left side to the value of the right side. Example: x = 5
In the first example we leave x alone, but in the second example we change x to 5.
So your code should look like:
} else {
Retirement.rawValue = Retirement.rawValue;
}
However, when you think about this, this code doesn't actually do anything. Retirement.rawValue will not change.
This leads us to the second mistake in the code, at least, it looks to me like a mistake.
if(Retirement.rawValue > 60000) {
Retirement.rawValue = 0;
}
This actually changes Retirement.rawValue, which might potentially change what's inside the Retirement field of your form. Worse, its possible that the form would look the same, but act differently when some other field calculates, since you've changed its rawValue. That would be a very tough bug to catch.
The solution is to create a new variable: http://www.w3schools.com/js/js_variables.asp
So now we can create a new variable, set that variable to either the retirement amount or nothing, and then add that variable to the other rawValues at the end:
var retirementOrZero;
if(Retirement.rawValue > 60000) {
retirementOrZero = 0;
} else {
retirementOrZero = Retirement.rawValue;
}
this.rawValue = TotalAssets.rawValue - (ValueHome1.rawValue + ValueVehicle1.rawValue + retirementOrZero);
Now we have a number that we can name anything we want, and we can change it however we want, without affecting any code but our own. So we start by checking if our retirement value is greater than 60000. If it is greater, we set our variable to 0. Otherwise, we set our variable to the retirement value. Then we add that variable we made, to the home and value cost.
As a final question, is it supposed to do
if(Retirement.rawValue > 60000) {
retirementValueOrZero = 0;
}
or is it supposed to do
if(Retirement.rawValue > 60000) {
retirementValueOrZero = 60000;
}
Of course, if you are setting it to 60000 instead of setting it to zero, you probably want to name your variable cappedRetirementValue or something like that -- just make sure you rename it everywhere its used!
Hopefully that helps!
Edit: You said you're only adding retirement value if it is greater than 60k, so what you want is this:
if(RetirementValue.rawValue > 60000) {
retirementValueOrZero = RetirementValue.rawValue;
} else {
retirementValueOrZero = 0;
}

How to write a generic function that passes one argument to then function then called multiple times

I have been stuck on this homework:
Create a generic function that outputs one line of the countdown on
the web page, followed by an alert, and receives the data to output as
an input parameter.
Use that function to output each line of the countdown, and an alert.
Please note that you are outputting the countdown to the browser
window this time, not to an alert!
The alert is only being used to signal when to output the next line
I need help in how to come up with a generic function that passes only one argument and then can be called 13 times. To write a for loop that output the numeric part of a countdown.
I think the key here is that they're asking for "Generic".
That means one function that doesn't have to know anything but what it's doing.
It also usually means that it shouldn't remember anything about what it did last time, or what it's going to do next time it's called (unless you're writing a generic structure specifically for remembering).
Now, the wording of the specification is poor, but a generic function which:
takes (input) data to write
writes the input to the page
calls an alert
is much simpler than you might think.
var writeInputAndAlert = function (input) {
// never, ever, ***ever*** use .write / .writeLn in the real world
document.writeLn(input);
window.alert("next");
};
If I was your teacher, I would then rewrite window.alert to handle the non-generic portion.
It's non-generic, because it knows the rules of the program, and it remembers where you are, and where you're going.
var countFrom = 100,
currentCount = countFrom,
countTo = 0;
var nextCount = function () {
currentCount -= 1;
if (currentCount >= countTo) { writeInputAndAlert(currentCount); }
};
window.alert = nextCount;
edit
var countdownArray = ["ten", "nine", "eight", "Ignition Start", "Lift Off", "We have Lift Off"],
i = 0, end = countdownArray.length, text = "",
printAndAlert = function (item) {
alert();
document.write(item);
};
for (; i < end; i += 1) {
text = countdownArray[i];
printAndAlert(text);
}
This really doesn't need to be any harder than that.
printAndAlert is a generic function that takes one input, writes that input and triggers an alert.
You call it inside of a for loop, with each value in your array.
That's all there is to it.
If I understand correctly, you want to create a function that will allow you to pass the data once, and then you can call that function to output the data line by line.
To do this exactly that way isn't possible, but this method is almost the same:
function createOutputFunction(dataArray)
{
return function() {
document.write(dataArray.shift()); // This writes the first element of the dataArray to the browser
};
}
//It can then be used like this
outputFunction = createOutputFunction(["Banana", "Mango", "Apple"]);
outputFunction();
outputFunction();
outputFunction();
The "createOutputFunction" function returns a function that can read the "dataArray" variable and print its first element every time it is called.

JavaScript: an if statement is changing outcomes of a random generator?

Basically I'm creating a program similar to a blackjack program where two cards are dealt according to a random number generator, with the possibility of the same card being dealt twice at the same time (i.e. two Queen of hearts showing up at once) and I want to create a counter of how many times that event occurs, but when I implement an if statement, it affects the outcome so that the two cards are ALWAYS the exact same...can someone tell me what I'm doing wrong here? The code is as follows:
function dealHand() {
var randomCardOne = Math.floor ((Math.random() *13) +2);
var randomCardTwo = Math.floor ((Math.random() *13) +2);
if (randomCardOne = randomCardTwo) {identicalCards()};
}
var identicalPairs = 0;
function identicalCards(){
document.getElementById("identical").value=++identicalPairs;
}
You are assigning the value of one card to another
if (randomCardOne = randomCardTwo) {identicalCards()};
should be
if (randomCardOne == randomCardTwo) {identicalCards()};
In the first case you are simply evaluating if randomCardOne is "truthy" after being asigned the value of randomCardTwo.
Consider if you might want to use === instead of == since
2 == '2' // yields true
2 === '2' // yields false
It's not an issue in this case but it might be in others so it's good to be aware of this. I try to stick with === since it is more strict.
You're using =, that's an assignment operator in JavaScript. You should be using ==
e.g.
if (randomCardOne == randomCardTwo) {identicalCards()};

Categories

Resources