2015年6月28日日曜日

開発環境

Data Structures and Algorithms With Javascript (Michael McMillan(著)、O'Reilly Media)のChapter 4(Stacks)、Exercises 2.(No. 2801)を解いてみる。

Exercises 2.(No. 2801)

JavaScript(Emacs)

/*jslint         browser : true, continue : true,
  devel  : true, indent  : 4,    maxerr   : 50,
  newcap : true, nomen   : true, plusplus : false,
  regexp : true, sloppy  : true, vars     : false,
  white  : false
*/

/*global print */
var Stack,
    infixToPostfix,
    calc,
    expr1 = '5 + 10',
    expr2 = '5 * 20',
    result;

Stack = function () {
    this.data_store = [];
    this.top = 0;
};
Stack.prototype.push = function (element) {
    this.data_store[this.top] = element;
    this.top += 1;
    return this;
};
Stack.prototype.peak = function () {
    return this.data_store[this.top - 1];
};
Stack.prototype.pop = function () {
    this.top -= 1;
    return this.data_store[this.top];
};
Stack.prototype.clear = function () {
    this.top = 0;
    this.data_store.length = 0;
};
Stack.prototype.length = function () {
    return this.top;
};

infixToPostfix = function (infix) {
    var post_fix = '',
        expr = infix.split(' '),
        operands = new Stack(),
        operators = new Stack();

    operands.push(expr[1]).push(expr[2]);
    operators.push(expr[2]);
    post_fix = operands.pop() + ' ' + operators.pop() + ' ' + operands.pop();
    return post_fix;
};
calc = function (post_fix) {
    var operands = new Stack(),
        operators = new Stack(),
        expr = post_fix.split(' '),
        a,
        b,
        op;

    operands.push(expr[0]).push(expr[1]);
    operators.push(expr[2]);
    a = Number(operands.pop());
    b = Number(operands.pop());
    op = operators.pop();

    return op === '+'
        ? a + b : op === '-'
        ? a - b : op === '/'
        ? a / b : op === '*'
        ? a * b : 'Unknown operator: ' + op;
};

result = infixToPostfix(expr1);
print(result);
print(calc(result));
result = infixToPostfix(expr2);
print(result);
print(calc(result));

出力結果(Terminal, shell, SpiderMonkey)

$ js sample2.js
10 10 +
20
20 20 *
400
$

0 コメント:

コメントを投稿