2015年5月28日木曜日

開発環境

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

Exercises 3.(No. 1820)

JavaScript(Emacs)

var weekTemps = function () {
        this.dataStore = [],
        this.add = add,
        this.average = average;
    },    
    add = function (temp) {
        this.dataStore.push(temp);
    },
    average = function () {
        var total = 0,
            i,
            max;

        for (i = 0, max = this.dataStore.length; i < max; i += 1) {
            total += this.dataStore[i];
        }
        return total / max;
    },
    monthTemps = function () {
        this.monthDataStore = [],
        this.monthAdd = monthAdd,
        this.monthAverage = monthAverage;
    },
    monthAdd = function (weekTemps) {        
        this.monthDataStore.push(weekTemps.dataStore);
    },
    monthAverage = function () {
        var total = 0,
            i,
            j,
            max_i,
            max_j,
            weekTemps;

        for (i = 0, max_i = this.monthDataStore.length; i < max_i; i += 1) {
            weekTemps = this.monthDataStore[i];            
            for (j = 0, max_j = weekTemps.length; j < max_j; j += 1) {
                total += weekTemps[j];
            }
        }

        return total / max_i + max_j;
    },
    firstWeek = new weekTemps(),
    secondWeek = new weekTemps(),
    thisMonth = new monthTemps(),    
    i;

for (i = 1; i <= 10; i += 2) {
    firstWeek.add(i);
}

for (i = 2; i <= 10; i += 2) {
    secondWeek.add(i);
}

thisMonth.monthAdd(firstWeek);
thisMonth.monthAdd(secondWeek);

print(thisMonth.monthAverage());

出力結果(Terminal, shell, SpiderMonkey)

$ js sample3.js
32.5
$

0 コメント:

コメントを投稿