Execute the loop until the condition met - javascript

I need this code to execute the loop until I get result 1. I want to make this code to calculate depending on the inputNum if inputNum is even, the inputNum is divided by 2 and if the inputNum is odd, then multiple by 3 and plus one. I have done this so far but I have lost how to loop this function the condition is until I get result 1 as final. I really need your help Please teach me
const inputNum = 5;
let i = inputNum;
while (i == 1) {
calculateNum();
}
function calculateNum() {
if (inputNum % 2 == 0) {
console.log('Input number : ' + inputNum + ' (even number!)');
let result = inputNum / 2;
console.log('Result: ' + result);
} else {
console.log('Input number : ' + inputNum + ' (odd number!)');
let result = inputNum * 3 + 1;
console.log('Result: ' + result);
}
}

Something like this?:
const inputNum = 5;
let i = inputNum;
while (i !== 1) {
calculateNum();
}
function calculateNum() {
if (i % 2 == 0) {
console.log("Input number : " + i + " (even number!)");
i = i / 2;
console.log("Result: " + i);
} else {
console.log("Input number : " + i + " (odd number!)");
i = i * 3 + 1;
console.log("Result: " + i);
}
}
result:
Input number : 5 (odd number!)
Result: 16
Input number : 16 (even number!)
Result: 8
Input number : 8 (even number!)
Result: 4
Input number : 4 (even number!)
Result: 2
Input number : 2 (even number!)
Result: 1
EDIT:
So the main issue with your code is that you don't update the value of i, so actually you have an endless loop.
Instead of using the result, update the value of i.

You need to return a result from calculateNum:
function calculateNum() {
if (inputNum % 2 == 0) {
console.log('Input number : ' + inputNum + ' (even number!)');
let result = inputNum / 2;
console.log('Result: ' + result);
return result;
} else {
console.log('Input number : ' + inputNum + ' (odd number!)');
let result = inputNum * 3 + 1;
console.log('Result: ' + result);
return result;
}
}
Then in your loop capture (and test) the result:
while (i != 1) {
i = calculateNum();
}

Put the while loop in your function.
let inputNum = 5;
function calculateNum(inputNum) {
while(inputNum !== 1) {
if (inputNum % 2 == 0) {
console.log('Input number : ' + inputNum + ' (even number!)');
inputNum = inputNum / 2;
console.log('Result: ' + inputNum);
} else {
console.log('Input number : ' + inputNum + ' (odd number!)');
inputNum = inputNum * 3 + 1;
console.log('Result: ' + inputNum);
}
}
return inputNum
}
calculateNum(inputNum)

Related

How to make triangle with '&' and '+' symbol in JavaScript?

How to make a pyramid like this one in javascript?
👇
&
+++
&&&&&
+++++++
I've tried this one but didn't get the exact output.
function pyramid(n) {
for (let i = 1; i <= n; i++) {
let str = ' '.repeat(n - i);
let symb1 = '&'.repeat(i * 2 - 1);
let symb2 = '+'.repeat(i * 2 - 1);
console.log(str + symb1 + str);
console.log(str + symb2 + str);
}
}
pyramid(4)
You could do something like this:
Declare a variable res which gonna store in it, lines.
loop over number of lines and in each one switch between two symbols by using modulo %
function pyramid(n) {
let res = '';
for (let i = 1; i <= n; i++) {
let str = ' '.repeat(n - i);
let line = ['+', '&'][i % 2].repeat(i * 2 - 1);
res += str + line + "\n";
}
return res;
}
console.log(pyramid(4));
Note: \n character for a line break to add a new line into result string.
You're outputting both lines on every iteration of the loop:
let symb1 = '&'.repeat(i * 2 - 1);
let symb2 = '+'.repeat(i * 2 - 1);
console.log(str + symb1 + str);
console.log(str + symb2 + str);
Instead, conditionally output one or the other. You can check whether i is even or odd for the condition:
if (i % 2 == 1) {
let symb1 = '&'.repeat(i * 2 - 1);
console.log(str + symb1 + str);
} else {
let symb2 = '+'.repeat(i * 2 - 1);
console.log(str + symb2 + str);
}
(You can of course refactor this into something shorter, reduce repetition, etc. The point here is to demonstrate the goal of outputting one or the other instead of both.)
Use a ternary and test for even using remainder
You can push into an array and join with newlines
function pyramid(n) {
const lines = [];
for (let i = 1; i <= n; i++) {
let str = ' '.repeat(n - i);
let symb = (i%2===0 ? '+' : '&').repeat(i * 2 - 1);
lines.push(str + symb + str);
}
console.log(lines.join("\n"));
}
pyramid(4)

Prefix notation string calculator Javascript problem

I'm making a calculator for a prefix notation string and it has covered all the normal tests that I've added to it. But I've come across one that it doesn't seem to be getting the right answer for and I'm unsure of why it seems to be having a problem with this.
I think it might have something to do with the division and subtraction when it comes to the numbers, because apart of the problem was I needed to assume that all inputs were valid, so there wouldn't be negative numbers nor would there be bad inputs IE not formatted correctly.
Here is the code and some of the test problems I inputted into it.
"+ / * 1 3 + 12 16 * 10 4" = 40.107142857142854
"+ * / - 5 3 / 1 3 + 2 2 / 3 * + 12 16 * 10 4" = 24.00267857142857 --- This is the one it doesn't like
"/ 300000 * + 12 16 * 10 40"= 26.785714285714285
function prefixEval(expression) {
let temp = expression.split(' ')
let expr = temp.reverse()
let stack = []
for (let i = 0; i < expr.length; i++) {
if (
expr[i] === '+' ||
expr[i] === '-' ||
expr[i] === '/' ||
expr[i] === '*'
) {
let j = stack.pop()
let k = stack.pop()
let temp = checkOperator(parseInt(j), parseInt(k), expr[i])
stack.push(temp)
} else {
stack.push(expr[i])
}
}
return stack
}
function checkOperator(a, b, op) {
switch (op) {
case '+':
console.log('adding' + ' ' + a + ' ' + op + ' ' + b)
console.log(a + b)
return a + b
case '-':
console.log('subtracting' + ' ' + a + ' ' + op + ' ' + b)
console.log(a - b)
return a - b
case '/':
console.log('dividing' + ' ' + a + ' ' + op + ' ' + b)
console.log(a / b)
return a / b
case '*':
console.log('multiplying' + ' ' + a + ' ' + op + ' ' + b)
console.log(a * b)
return a * b
default:
return 'this is not correct'
}
}
console.log(prefixEval('+ * / - 5 3 / 1 3 + 2 2 / 3 * + 12 16 * 10 4'))
You are using parseInt and dividing 2 by 0 which produces Infinity . To fix,
Change,
let temp = checkOperator(parseInt(j), parseInt(k), expr[i])
to
let temp = checkOperator(parseFloat(j), parseFloat(k), expr[i])
This is give you the expected answer

I want to write javascript code to get a addition countdown

so basically this the prompt:
Addition countdown
you enter a number and the code should be adding a number while countingdown, for example if the user enter 10, then the result should be:
10 + 9 + 8 + 7 + 6 + 5 + 4 +3 +2 +1=55.
This is what I have so far:
var num = Number(prompt("Enter a Number Greater than zero"));
while (num > 0){
first = num;
second = num-=1;
document.write(first + " +" + second + " +");
value = first + num;
document.write(value)
num--;
}
but I keep on getting something like this:
4 +3 +72 +1 +3 (let's say 4 is the number the user inputs)
I'm stuck can someone please help me????!!
You can keep total in one variable outside of while loop.
var num = Number(prompt("Enter a Number Greater than zero"));
var total = 0;
while (num > 0) {
total += num;
document.body.innerHTML += (num == 1 ? num + ' = ' + total : num + ' + ');
num--;
}
You could change the algorithm a bit, because for the first value, you need no plus sign for the output.
var num = Number(prompt("Enter a Number Greater than zero")),
value = 0;
document.body.appendChild(document.createTextNode(num));
value += num;
num--;
while (num > 0) {
document.body.appendChild(document.createTextNode(' + ' + num));
value += num;
num--;
}
document.body.appendChild(document.createTextNode(' = ' + value));

Validate decimal in javascript

hi i want to know how to write a validation code for a number with two decimal places for example 45.80
function submitform4()
{
var min=00.01;
var max = 100.00;
var num = parseInt(document.getElementById('valid').value);
console.log(num);
if (min > num || max < num) {
alert(num + ' is not between ' + min + ' and ' + max);
return false;
}
}
this is something i copied from my work and thought i could change it but didnt really work.
Well, this is what I'd do, If I understand correctly.
This addresses a few issues:
JavaScript doesn't like the numeric value 00.01. Use 0.01 instead
use parseFloat on your input value. parseInt will round to an integer
return true if successful (not undefined)
function submitform4() {
var MIN = 0.01;
var MAX = 100.00;
var input = document.getElementById('AgeGrade');
var inputValue = parseFloat(input.value);
var is_valid = (MIN > inputValue || MAX < inputValue);
if (is_valid) {
input.value = inputValue.toFixed(2); // set to 2 decimal places
return true
} else {
alert(inputValue + ' is not between ' + MIN + ' and ' + MAX);
return false;
}
}
You could do something like this:
function submitForm(numberToEvaluate){
var min = 0.0;
var max = 100;
//Instead of being passed in
//This would be grabbed from DOM element
var num = numberToEvaluate;
console.log(num);
if (min > num || max < num) {
alert(num + ' is not between ' + min + ' and ' + max);
return false;
}
}
submitForm(-1);
submitForm(37);
The code looks fine (almost), depending on how you intend to use i the function.
If you are using the function as a validation before you submit, like if(submitform4()) then you need to add return true; to the end of the function to return true unless the answer is false.
I would try parseFloat() :
function submitform4()
{
var min = parseFloat("00.01");
var max = parseFloat("100.00");
var num = parseFloat("200.20");
console.log(num);
if (min > num || max < num) {
alert(num + ' is not between ' + min + ' and ' + max);
console.log('false');
}
}
submitform4();
See Feedle
Else you certainly have error :
Uncaught SyntaxError: Unexpected number
See not working Feedle

javascript - How to reverse bitwise shift?

This is my Function. In this function there is two parameter value and how many bits shift.
function test(Value, ShiftBits) {
return (Value << ShiftBits) | (Value >>> (32 - ShiftBits));
};
Now i want to make reverse of this function. In this test() function if i put
test(105748,7);
it returns 13535744;
Now i need to make a function like, if i put
rev_test(13535744,7);
it returns 105748;
Any help Appreciated.
Why not reverse the logic? I spelled it out below:
Number.prototype.zeroFillBin = function() {
var s = this.toString(2);
while (s.length < 32) s = '0' + s;
return s;
}
function test(val, bits) {
return (val << bits) | (val >>> (32 - bits));
};
function rev_test(val, bits) {
return (val >>> bits) | (val << (32 - bits));
};
x = 105748;
y = test(x, 7); // return 13535744
console.log(x + ' = ' + x.zeroFillBin())
console.log(y + ' = ' + y.zeroFillBin() + '\n');
x = 13535744;
y = rev_test(x, 7); // return 105748
console.log(x + ' = ' + x.zeroFillBin())
console.log(y + ' = ' + y.zeroFillBin() + '\n');
Results:
105748 = 00000000000000011001110100010100
13535744 = 00000000110011101000101000000000
13535744 = 00000000110011101000101000000000
105748 = 00000000000000011001110100010100
105748 << 1 // 13535744
13535744 >> 1 // 105748

Categories

Resources