開発環境
- 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 3.(No. 2801)を解いてみる。
Exercises 3.(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,
pez_dispenser,
temp_stack,
colors,
len,
i,
elem;
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;
};
Stack.prototype.display = function () {
var result = '',
i,
max = this.length();
for (i = 0; i < max; i += 1) {
result += this.data_store[i] + ' ';
}
print(result);
};
pez_dispenser = new Stack();
colors = ['red', 'yellow', 'white'];
len = colors.length;
for (i = 0; i < 10; i += 1) {
pez_dispenser.push(colors[Math.floor(Math.random() * len)]);
}
pez_dispenser.display();
temp_stack = new Stack();
while (pez_dispenser.length() !== 0) {
elem = pez_dispenser.pop();
if (elem !== 'yellow') {
temp_stack.push(elem);
}
}
while (temp_stack.length() !== 0) {
pez_dispenser.push(temp_stack.pop());
}
pez_dispenser.display();
出力結果(Terminal, shell, SpiderMonkey)
$ js sample3.js
white red white red red yellow yellow red white yellow
white red white red red red white
$ js sample3.js
white white white red yellow white red red yellow red
white white white red white red red red
$ js sample3.js
yellow red yellow white red red yellow yellow yellow red
red white red red red
$ js sample3.js
yellow white white yellow red red red white yellow red
white white red red red white red
$ js sample3.js
white red yellow yellow yellow yellow red red red yellow
white red red red red
$
0 コメント:
コメントを投稿