Prefix notation string calculator Javascript problem - javascript

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

Related

Execute the loop until the condition met

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)

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)

I am having trouble with a few javascript do while loops

I am writing a code guessing program to test the security of some iPhone passwords (This is not in anyway connected to anything illegal or is used to break into actual iPhones). The do/while loops just end all response once they occur and the last two lines don't print to the console.
print("Hi!");
print("I am a password security tester.");
var tries = 0
var guess1 = 0
var guess2 = 0
var guess3 = 0
var guess4 = 0
var guess = (guess1 * 1000) + (guess2 * 100) + (guess3 * 10) + guess4;
var password1 = (Math.floor(Math.random()*9));
var password2 = (Math.floor(Math.random()*9));
var password3 = (Math.floor(Math.random()*9));
var password4 = (Math.floor(Math.random()*9));
var password = (password1 * 1000) + (password2 * 100) + (password3 * 10) + password4;
print("This is the randomly genorated password: " + password);
print("And now begins the guessing");
do{
guess1 + 1;
tries + 1;
}while (password1 != guess1);
do{
guess2 + 1;
tries + 1;
}while (password2 != guess2);
do{
guess3 + 1;
tries + 1;
}while (password3 != guess3);
do{
guess4 + 1;
tries + 1;
}while (password4 != guess4);
print("Complete in " + tries + " tries");
print("The answer is: " + guess);
Jacob Ewing's answer is correct, but another problem is that guess will still be 0 at the end, because it doesn't automatically update. You'll need to do:
var guess = (guess1 * 1000) + (guess2 * 100) + (guess3 * 10) + guess4;
Before:
print("Complete in " + tries + " tries");
print("The answer is: " + guess);
You need to be using a += operator instead of just +
Saying guess1 + 1 returns the value of guess1 + 1, but does not increment that value directly, so you get an infinite loop.

Trying to display javascript number with commas [duplicate]

This question already has answers here:
How to format a number with commas as thousands separators?
(50 answers)
Closed 9 years ago.
<SCRIPT language="JavaScript">
height = screen.height;
width = screen.width;
document.write( width*height + " pixels");
</SCRIPT>
I would like my answer to return with commas separating the numbers rather than one full number.
Here's a fun way to do it:
function format(num) {
return ("" + num).split("").reverse().reduce(function(acc, num, i, orig) {
return num + (i && !(i % 3) ? "," : "") + acc;
}, "");
}
format(777782374);
Prints:
"777,782,374"
Or, if you want to support decimals:
function format(num, fix) {
var p = num.toFixed(fix).split(".");
return p[0].split("").reduceRight(function(acc, num, i, orig) {
var pos = orig.length - i - 1
return num + (pos && !(pos % 3) ? "," : "") + acc;
}, "") + (p[1] ? "." + p[1] : "");
}
format(777782374, 4);
Prints:
"777,782,374.0000"
Than you shouldn't multiply them?
document.write( width + ", " + height + " pixels");

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