Conditional Statements JavaScript - javascript

So I have a very basic conditional statement but I am trying to get a different answer. I want to have a default command of else that if a user is inputting something greater than 10 that they get an alert of "the numbers are only from 1-10" what is a way I can do this?
var number = 7;
var stringGuess = prompt("guess a number");
var guess = Number(stringGuess);
if (guess === number) {
alert("you got it");
}
else if(guess > 10) {
alert(" Too High Guess Lower");
}
else if (guess < number) {
alert("Too low guess higher!");
}
else {
}

Modified a little bit of your code:
I used switch for the conditions which basically judge if guess is matching the number or below or above. Then add txt as extra information if the guess is out of 1-10.
var number = 7;
var stringGuess = prompt("guess a number");
var guess = Number(stringGuess);
switch ( true ) {
case ( guess === number ):
alert('You got it!');
break;
case ( guess > number ):
var txt = ( guess > 10 ) ? ' and the number is smaller than 10' : '';
alert( 'Too high' + txt );
break;
case ( guess < number ):
var txt = ( guess < 1 ) ? ' and the number greater than 1' : '';
alert( 'Too low' + txt );
break;
}
You can try this and they do exactly the same thing by using IF ELSE.
var number = 7;
var stringGuess = prompt("guess a number");
var guess = Number(stringGuess);
var txt = ( guess > 10 ) ? ' and the number is smaller than 10' : '';
if ( guess < 1 ) txt = ' and the number greater than 1';
if ( guess === number ) {
alert('You got it!');
} else if ( guess > number ) {
alert( 'Too high' + txt );
} else {
alert( 'Too low' + txt );
}

You have a good case for breaking things into functions, in order to hide the how, and talk about the what it is you're trying to accomplish.
function isInBounds (low, x, high) { return low <= x && x <= high; }
function isAnswer (x, number) { return x === number; }
function gt (x, number) { return x > number; }
function generateRandomInt (floor, ceiling) {
return Math.floor(Math.random() * (ceiling - floor)) + floor;
}
var lowerBound = 1;
var upperBound = 10;
// the +1 is because Random will never, ever be equal to the high number
// so a random number between 1 and 10 really means between 1 and 11
var answer = getRandomInt(lowerBound, upperBound + 1);
var successMessage = "You got it!";
var failureMessage = "Guess again!";
var errorMessage = "Error: guess must be a number between "
+ lowerBound + " and " + upperBound + ".";
function checkGuess (x) {
var message = "";
if (isInBounds(lowerBound, x, upperBound)) {
message = isAnswer(x, answer) ? successMessage : failureMessage;
} else {
message = errorMessage;
}
alert(message);
}
I'm using ternary assignment to set the value of message.
var x = isTrue ? truthyValue : falseyValue;
You can even nest these on the truthy or falsey paths.
var result = a ? x : b ? y : z;
// if a == true, x, else if b == true, y, else z
That said, you may want to be careful with that setup.

Related

Multiplying Combinations Array

So I need a tiny bit of help with this code, Some background information: The user inputs a number, the code takes the number and outputs various combinations of numbers that multiply to it.
For example:
Input: 7
Output: (1,7)(7,1).
*But what really happens:
*
Input: 7
Output: (7,1)
I want my code to reverse the numbers as well, so it makes can look like it has two combinations
var input= parseInt(prompt("Please enter a number larger than 1"));
var arr = [];
if(input <= 1) {
console.log("Goodbye!")
}
while(input > 0) {
var arr = [];
var input = parseInt(prompt("Please enter a number larger than 1"));
for (var i = 0; i < input; ++input) {
var r = ((input / i) % 1 === 0) ? (input / i) : Infinity
if(isFinite(r)) {
arr.unshift(r + ", " + i)
}
}
console.log("The multiplicative combination(s) are: " + "(" + arr.join("), (") + "). ");
}
My code just need this tiny bit of problem fixed and the rest will be fine!
Your code has 2 infinite loop because you never change i and always increase input.
also in this line for (var i = 0; i < input; ++input) you never let i to be equal to the input so in your example (input=7) you can not have (7,1) as one of your answers. I think this is what you looking for:
var input = 1;
while(input > 0) {
input = parseInt(prompt("Please enter a number larger than 1"));
if(input > 1) {
var arr = [];
for (var i = 0; i <= input; ++i) {
var r = ((input / i) % 1 === 0) ? (input / i) : Infinity
if(isFinite(r)) {
arr.unshift(r + ", " + i)
}
}
console.log("The multiplicative combination(s) are: " + "(" + arr.join("), (") + "). ");
continue;
}
else{
console.log("Goodbye!");
break;
}
}

Why is my javascript recursion code not calculating the number of lines words and characters in a text file

Need help on why my recursion program in javascript is not working. It is supposed to take the words from the text file and display the number of words, lines and characters in it. Please help me modify my code or tell me where my mistake is because I do not know where. Here is the javascript code:
var fs = require("fs");
var text = fs.readFileSync("text.txt", "utf8");
function countLines(text) {
if (text == "") {
return 0;
} else {
return 1 + countLines(text.substring(text.indexOf("\n") + 1));
}
}
function countWords(text) {
if (text == "") {
return 0;
} else {
return 1 + countWords(text.substring(text.indexOf(" ") + 1));
}
}
function countCharacters(text) {
if (text == "") {
return 0;
} else {
return 1 + countCharacters(text.substring(1));
}
}
var lineCount = countLines(text);
var wordCount = countWords(text);
var characterCount = countCharacters(text);
console.log(
"There are " +
lineCount +
" lines, " +
wordCount +
" words, and " +
characterCount +
" characters in the file."
);
This is the text.txt file:
I was running to the zoo.
If we are counting lines, the base case is not if (text == ""), it is when no \n is found in text. Changing the base case can result in a new way to think about the problem and a simplification of our code.
Given i is the position of \n in the string text -
If i is less than zero, text is the last line. Return 1.
(inductive) i is 0 or greater, text has more than one line. Return 1 plus the result of the sub-problem.
function countLines(text) {
const i = text.indexOf("\n")
if (i < 0) return 1 // 1
else return 1 + countLines(text.substring(i + 1)) // 2
}
console.log(countLines(`Hello`))
console.log(countLines(`Hello
World,`))
console.log(countLines(`Hello
World,
We don't deserve you.`))
We could be less verbose with a ternary expression -
function countLines(text) {
const i = text.indexOf("\n")
return (i < 0) ? 1 : 1 + countLines(text.substring(i + 1))
}
Your issue is blindly recursing without checking the result of indexOf, which is -1 when the target isn't found
so
text.substring(text.indexOf(" ") + 1)
becomes
text.substring(-1 + 1)
in other words
text.substring(0)
So, you infinitely recurse the last word (and line, for that matter)
If .indexOf returns -1, you should return 1
Note: I removed the unnecessary else in your code - no need for else when the if returns a value - this make for cleaner code (in my opinion, you're welcome to use else if you must
I've shown two different ways to test indexOf
var text = "I was running to the zoo.";
function countLines(text) {
if (text == "") {
return 0;
}
const index = text.indexOf("\n");
if (index < 0) {
return 1;
}
return 1 + countLines(text.substring(index + 1));
}
function countWords(text) {
if (text == "") {
return 0;
}
const index = text.indexOf(" ") + 1;
if (index) { // since we've added 1, a "not found" -1 would be 0 here, and be falsey
return 1 + countWords(text.substring(index));
}
return 1;
}
function countCharacters(text) {
if (text == "") {
return 0;
}
return 1 + countCharacters(text.substring(1));
}
var lineCount = countLines(text);
var wordCount = countWords(text);
var characterCount = countCharacters(text);
console.log(
"There are " +
lineCount +
" lines, " +
wordCount +
" words, and " +
characterCount +
" characters in the file."
);

How to calculate the factorial of a number entered by user in Javascript, using, do-loop, while-loop?

Quick follow-up question on my previous question. I'd like to add the code to the following to calculate the factorial of a number entered by user in Javascript.
<!DOCTYPE html>
<html>
<head>
<title>Sum of Numbers</title>
<script>
var numbers = prompt("Enter a number 1-100");
while (numbers!=null && (isNaN(parseInt(numbers)) || parseInt(numbers) >100 || parseInt(numbers) <1)) {
numbers = prompt("Try again.Enter a number 1-100");
}
if (numbers !=null){
alert("Finally you entered a correct number");
var sum = 0;
var numOfLoops = numbers;
var counter = 1;
do {
sum+=counter;
counter++;
}
while (counter<=numOfLoops)
alert ("The sum of numbers from 1 to " + numbers + "is =" +sum);
}
</script>
</head>
<body>
<script>
document.write("<h1>Sum of Numbers</h1>");
document.write("The sum of numbers from 1 to = " + numbers + " is = " +
+ sum + "<br><br>");
</script>
</body>
</html>
If you are trying to sum up the numbers, consider using arithmetic series formula. If you're trying to get the factorial, the approach is shown below.
If you want to sum using the loop, just change the *= to +=.
While Loop Approach
const fact = (n) => {
let res = 1;
while (n > 0) {
res *= n;
n--;
}
return res;
}
fact(5) // 120
Do While Approach
const fact = (n) => {
let res = 1;
do {
res *= n;
n--;
} while (n > 0)
return res;
}
fact(3) // 6
That should do the trick. :)
Maybe also considering checking for edge cases like if the n is negative.
Good luck.
While Loop:
const fact=n=>
{
if(n<0) throw 'factorial error on a negative number!'
let r = 1
while(n) r *= n--
return r
}
Do While:
const fact=n=>
{
if(n<0) throw 'factorial error on a negative number!'
let r = 1
do r *= n || 1 // in case of n == 0
while (n--)
return r;
}
complete code
const
msgPrompt_1 = 'Please enter a number from 0 to 100',
msgPrompt_n = 'Try again.... Enter a number 0-100',
fact = n =>
{
let r = 1
while(n) r *= n--
return r
}
let numValue = parseInt(window.prompt(msgPrompt_1, ''), 10)
while(isNaN(numValue) || numValue > 100 || numValue < 0)
{
numValue = parseInt(window.prompt(msgPrompt_n, ''), 10)
}
alert(`factorial value of ${numValue} is = ${fact(numValue)}` )

Check for perfect number and print out divisors?

My goal is to create a program that checks whether the user input is a perfect number or not. It has validation for the numbers entered. If the input IS a perfect number, I'd like to print out each of the divisors. I tried using this method:
{
for(int number=2; number <= 10000 ; number++)
perfect(number);
return 0;
}
void perfect(int number)
{
int total = 0;
for (int i = 1; i < number; i++)
{
if (number % i == 0)
total += i;
}
if (number == total)
{
for (int x = 1; x < number; x++)
{
if (number % x == 0)
cout << x << " + ";
}
cout << " = " << number << endl;
}
}
However, I was unable to get the desired effect. I am very new to javascript and am struggling with inserting code in the correct way. Does anyone have a suggestion for how I can get the desired effect? Here is the code I have already written:
function check_prime() {
var input = document.getElementById("enteredNumber").value;
var number = parseInt(input);
if (isNaN(number)) {
alert("Oops! Please enter a valid number.");
document.getElementById("enteredNumber").value="";
document.getElementById("result").innerHTML = "";
document.getElementById("enteredNumber").focus();
}
else if (input.length === 0) {
alert("Please enter a number.");
document.getElementById("enteredNumber").focus();
}
else if (!isNaN(number)) {
if (is_perfect(number)) {
document.getElementById("answer").innerHTML = "Congratulations! " + number + " is a perfect number." ;
}
else {
document.getElementById("answer").innerHTML = "I'm sorry. " + number + " is not a perfect number. Try Again.";
}
}
else {
document.getElementById("answer").innerHTML = "Please enter a number.";
}
}
function is_perfect(number)
{
var temp = 0;
for(var i=1;i<=number/2;i++)
{
if(number%i === 0)
{
temp += i;
}
}
if(temp === number)
{
return true;
}
else
{
return false;
}
}
function clear_textbox(){
document.getElementById("answer").innerHTML = "";
document.getElementById("enteredNumber").value="";
document.getElementById("enteredNumber").focus();
}
I'd suggest revising your is_perfect() function to return an array of divisors if the number is perfect and null if the number is not perfect. Then the calling code has the divisors available for display when the input is a perfect number.
function is_perfect(number) {
var temp = 0;
var divisors = [];
for(var i=1;i<=number/2;i++) {
if (number%i === 0) {
divisors.push(i);
temp += i;
}
}
return temp === number ? divisors : null;
}
Then:
var divisors = is_perfect(number);
if (divisors) {
document.getElementById("answer").innerHTML = "Congratulations! " + number + " is a perfect number.";
// display the divisors somewhere; the alert is just for show
alert("Divisors: " + divisors.toString());
} else {
...
}
[Note: In an earlier version of this answer, I had initialized temp to 1 and divisors to [1] and had started the loop at 2, on the theory that 1 is always a divisor. Unfortunately, that's wrong, since 1 is not a proper divisor of 1. The revised version of is_perfect() now returns null for an argument of 1 instead of [1]. An alternative fix would have been to test explicitly for the case number === 1, but that's uglier (if perhaps a tiny bit more efficient, since it avoids one % evaluation).]
so I use 2^(n-1)*(2^n -1) formula (to generate a perfect number) and checking if last digit is 6 or 8 to check if x is perfect number.
Note: It's not perfect 100%
function pn(x) {
x = '' + x
for (var i = 0; i < Infinity; i++) {
perfnumgen = Math.pow(2, i - 1) * (Math.pow(2, i) - 1)
if (x === "" + perfnumgen && (perfnumgen % 10 === 8 || perfnumgen % 10 === 6))
return true
else if (perfnumgen > x)
return false
console.log("" + perfnumgen)
}
}

An error with my javascript function, not sure what I'm doing wrong to calculate an stv equation

All this suppose to do is to check 3 boxes for values, if 'v' or 's' is not empty for example, it will calculate 't', problem is it calculates 's' no matter which boxes I fill, it checks first if you've filled all textboxes (you're supposed to fill just two) if 'v' or 's' are not empty, it will check the next 'if' won't it? it seems to randomly pick 'ifs' and also on some occasion return NaN as the answer.
Thanks ahead.
var count = 0;
function stv()
{
var v = parseFloat(document.getElementById("Text1").value);
var s = parseFloat(document.getElementById("Text2").value);
var t = parseFloat(document.getElementById("Text3").value);
if (v != "" && t != "" && s != "") {
"Don't be stupid..."
count++
}
if (v!="" && s!=""){
document.getElementById("result").innerHTML = "time= " + s / v + "hours, or " + (s / v) * 60 + "minutes";
count++;
}
if (s != "" && t != "") {
document.getElementById("result").innerHTML = "velocity= " + s / t + "kph";
count++;
}
if (v != "" && t != "") {
document.getElementById("result").innerHTML = "displacement= " + (v * t) + "kilometers";
count++;
}
if (count == 0){
document.getElementById("result").innerHTML = "Fill in at least two parameters...";
}
count = 0;
document.getElementById("Text1").value = "";
document.getElementById("Text2").value = "";
document.getElementById("Text3").value = "";
}
Your if checks are "failing" because parseFloat of "" is NaN and not equal to "". So you should be checking to see if it is not a number and not equal to an empty string.
var a = parseFloat("")
if ( isNaN(a) ) console.log("I am not a number");
if ( a!="" ) console.log("I am not an empty string");

Categories

Resources