Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

เครื่องคิดเลข Prefix ใช้สแท็กใน JavaScript


เราต้องทำเครื่องคิดเลขด้วยวิธีอินพุท RPN (reverse polish notation) ใช้ Stacks ใน JavaScript

พิจารณาอินพุทอาร์เรย์ดังนี้

const arr = [1, 5, '+', 6, 3, '-', '/', 7, '*'];

กระบวนการ

  • 1 เป็น operand, push เข้า Stack

  • 5 เป็น operand, push เข้า Stack

  • '+' เป็น operator, pop 1 และ 5 คำนวณและ push ผลลัพธ์เข้า Stack

  • 6 เป็น operand, push เข้า Stack

  • 3 เป็น operand, push เข้า Stack

  • '-' เป็น operator, pop 6 และ 3 ลบกันและ push ผลลัพธ์เข้า Stack

  • '/' เป็น operator, pop 6 และ 3 หารกันและ push ผลลัพธ์เข้า Stack

  • 7 เป็น operand, push เข้า Stack

  • '*' เป็น operator, pop 2 และ 7 คูณกันและ push ผลลัพธ์เข้า Stack

และสุดท้าย ผลลัพธ์ควรเป็น

const output = 14;

ตัวอย่างโค้ด

โค้ดสำหรับการทำงานนี้จะเป็นดังนี้

const arr = [1, 5, '+', 6, 3, '-', '/', 7, '*']; 
const stackCalculator = (arr = []) => { 
  const options = { 
    '+': (a, b) => a + b, 
    '-': (a, b) => a - b, 
    '*': (a, b) => a * b, 
    '/': (a, b) => a / b 
  }; 
  const stack = []; 
  arr.forEach(value => { 
    stack.push(value in options 
      ? options[value](...stack.splice(-2)) 
      : value 
    ); 
  }); 
  return stack; 
}; 
console.log(stackCalculator(arr));

ผลลัพธ์

ผลลัพธ์ในคอนโซลจะเป็นดังนี้

[14]