2015年8月14日金曜日

開発環境

  • OS X Yosemite - Apple (OS)
  • Emacs (Text Editor)
  • JavaScript (プログラミング言語)
  • SpiderMonkey, Node.js(V8) (JavaScript engine)

Data Structures and Algorithms With Javascript (Michael McMillan(著)、O'Reilly Media)のChapter 8(Hashing)、Exercises 3.(No. 5324)を解いてみる。

Exercises 3.(No. 5324)

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  : true
*/

/*global print, read, readline */
var HashTable,
    word_count,
    words,
    word,
    i,
    max;

HashTable = function () {
    this.table = new Array(137);
};
HashTable.prototype = {
    constructor: HashTable,
    betterHash: function (string) {
        var H = 31,
            total = 0,
            i,
            max;

        for (i = 0, max = string.length; i < max; i += 1) {
            total += H * total + string.charCodeAt(i);
        }
        total = total % this.table.length;
        if (total < 0) {
            total += this.table.length + 1;
        }
        return parseInt(total, 10);
    },
    showDistro: function () {
        var i,
            max;

        for (i = 0, max = this.table.length; i < max; i += 1) {
            if (this.table[i] !== undefined) {
                print(i + ': ' + this.table[i]);
            }
        }
    },
    put: function (key) {
        var pos = this.betterHash(key);
        
        if (this.table[pos] === undefined) {
            this.table[pos] = 1;
        } else {
            this.table[pos] += 1;
        }
    },
    get: function (key) {
        var hash = this.betterHash(key);

        if (this.table[hash] !== undefined) {
            return  this.table[hash];
        }
        return 0;
    }
};

word_count = new HashTable();
words = read('blog.txt').match(/\b\w+\b/g);
for (i = 0, max = words.length; i < max; i += 1) {
    word_count.put(words[i]);
}
while (true) {
    word = readline();
    if (word === 'quit') {
        break;
    }
    print(word_count.get(word));    
}

出力結果(Terminal, shell, SpiderMonkey)

$ jslint sample3.js

sample3.js is OK.
$ js sample3.js
JavaScript
31
javascript
137
div
1035
body
107
quit
$ 

0 コメント:

コメントを投稿