開発環境
- OS X Yosemite - Apple (OS)
- Emacs (Text Editor)
- JavaScript (プログラミング言語)
- SpiderMonkey (JavaScript engine)
Data Structures and Algorithms With Javascript (Michael McMillan(著)、O'Reilly Media)のChapter 5(Queues)、Exercises 1.(No. 3595)を解いてみる。
Exercises 1.(No. 3595)
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 Queue = function () {
this.data_store = [];
},
Deque = function () {
this.data_store = [];
},
deque,
i;
Queue.prototype.enqueue = function (element) {
this.data_store.push(element);
};
Queue.prototype.dequeue = function () {
return this.data_store.shift();
};
Queue.prototype.front = function () {
return this.data_store[0];
};
Queue.prototype.back = function () {
return this.data_store[this.data_store.length - 1];
};
Queue.prototype.toString = function () {
var result = '',
i,
max;
for (i = 0, max = this.data_store.length; i < max - 1; i += 1) {
result += this.data_store[i] + ',';
}
result += this.data_store[i];
return result;
};
Queue.prototype.isEmpty = function () {
return this.data_store.length === 0 ? true : false;
};
Queue.prototype.count = function () {
return this.data_store.length;
};
Deque.prototype = new Queue();
Deque.constructor = Deque;
Deque.prototype.addFirst = function (element) {
this.data_store.unshift(element);
};
Deque.prototype.addLast = function (element) {
this.enqueue(element);
};
Deque.prototype.removeFirst = function () {
return this.dequeue();
};
Deque.prototype.removeLast = function () {
return this.data_store.pop();
};
Deque.prototype.getFirst = function () {
return this.front();
};
Deque.prototype.getLast = function () {
return this.back();
};
deque = new Deque();
for (i = 0; i < 10; i += 1) {
deque.addLast(i);
}
print(deque);
for (i = 0; i < 10; i += 1) {
deque.addFirst(i);
}
print(deque);
print(deque.removeFirst());
print(deque);
print(deque.removeLast());
print(deque);
print(deque.count());
print(deque.isEmpty());
print((new Deque()).count());
print((new Deque()).isEmpty());
出力結果(Terminal, shell, SpiderMonkey)
$ js sample1.js
0,1,2,3,4,5,6,7,8,9
9,8,7,6,5,4,3,2,1,0,0,1,2,3,4,5,6,7,8,9
9
8,7,6,5,4,3,2,1,0,0,1,2,3,4,5,6,7,8,9
9
8,7,6,5,4,3,2,1,0,0,1,2,3,4,5,6,7,8
18
false
0
true
$
0 コメント:
コメントを投稿