Comment detail

コード中の文字の頻度分析 (Nested Flatten)
JavaScriptの代表例ということで、prototype.jsを対象としました。
ついでにファイルの読み込みをAjaxで。

試すときは、以下をfreq.htmlなどの名前で保存し、prototype.jsを同じところに置いて、htmlを開くだけです。
IEで見る場合は、11行目をコメントにし、代わりに16行目をコメント解除してください。

<結果>
文字 Code 数 頻度
' ' 20 24616 0.19183441267466236
e 65 10917 0.08507703457788791
t 74 8301 0.06469034203820168
n 6e 6215 0.048433980938130755
r 72 4873 0.03797567000989721
o 6f 4204 0.03276210070215634
(省略)

結果は、・・・普通です。
プログラム言語は全般的に「 t 」をよく使うのでしょうか。
記号で多いのは、丸括弧が2616個、ドットが2534個、セミコロン1779個で、
以下、「=」1498、「,」1396、「-」1067、「’」1058、波括弧937と続きます。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<html>
<head>
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript">
function log(s) {
    $('resultArea').innerHTML += (new Date().toString() + " " + s + '<br>\n');
}
/* 対象ファイルを要求する */
function init() {
    var ajax = new Ajax.Request(
       'prototype.js',   // 頻度分析対象ファイル
       /* IEの場合、XMLHttpRequestでローカルファイルにアクセスできないため
        * 自前のサーバに設置するか、
        * 以下のコメントを外して本家からお借りして下さい。
        *  (こっちはFirefoxでは動きません。。。) */
       // 'http://www.prototypejs.org/assets/2007/11/6/prototype.js',
       {
           method: 'get',
           onComplete: function(req) {
               log("Request completed");
               freq(req.responseText);
           }
       });
    log("Request sent");
}
/* 文字列中の文字頻度を測定し、結果を表示する */
function freq(s) {
    // 頻度の集計
    var hist = {};
    for (var i = 0; i < s.length; i++) {
        var ch = s.charCodeAt(i);
        if (hist[ch] == undefined)
            hist[ch] = { moji: ch, count:1 };
        else
            hist[ch].count++;
    }
    
    var report = "<table border=\"1\">\n<tr>"
               + "<td>文字</td>"
               + "<td>Code</td>"
               + "<td>数</td>"
               + "<td>頻度</td>\n";
    // 頻度を出現回数の昇順でならびかえ、表で表示
    Object.values(hist)
        .sort(function(a, b) { return b.count - a.count; })
        .each(function(o) {
            report += "<tr><td>" + String.fromCharCode(o.moji) + "</td>";
            report += "<td>" + o.moji.toString(16) + "</td>";
            report += "<td style=\"text-align: right;\">" + o.count + "</td>";
            report += "<td>" + (o.count / s.length)  + "</td></tr>\n";
        });
    report += "</table>";
    log(report);
}
</script></head>
<body onload="init();">
<div id="resultArea"></div>
</body>

Index

Feed

Other

Link

Pathtraq

loading...