開発環境
- OS X Yosemite - Apple (OS)
- Emacs (Text Editor)
- JavaScript (プログラミング言語)
- SpiderMonkey (JavaScript engine)
Data Structures and Algorithms With Javascript (Michael McMillan(著)、O'Reilly Media)のChapter 4(Stacks)、Exercises 1.(No. 2801)を解いてみる。
Exercises 1.(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,
getPosition,
expr1 = '2.3 + 23 / 12 + (3.14159 * .24',
expr2 = '2.3 + 23 / 12 + (3.14159 * .24)',
expr3 = '2.3 + 23 / 12 + (3.14159 * .24))';
Stack = function () {
this.data_store = [];
this.top = 0;
};
Stack.prototype.push = function (element) {
this.data_store[this.top] = element;
this.top += 1;
};
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;
};
getPosition = function (expr) {
var pos,
stack = new Stack(),
ops = expr.split(''),
i,
balance,
op;
for (i = ops.length; i >= 0; i -= 1) {
stack.push(ops[i]);
}
pos = 0;
balance = 0;
i = 0;
while (stack.length() !== 0) {
op = stack.pop();
if (op === '(') {
balance -= 1;
pos = i;
} else if (op === ')') {
balance += 1;
}
i += 1;
}
return balance < 0 ? pos : balance === 0 ? false : "too much ')'";
};
print(getPosition(expr1));
print(getPosition(expr2));
print(getPosition(expr3));
出力結果(Terminal, shell, SpiderMonkey)
$ js sample1.js
16
false
too much ')'
$
0 コメント:
コメントを投稿