2017-07-04 6 views
0

私はInterview Cakeに関する質問をしており、新しい値を挿入すると計算が行われます。私の本能はゲッターメソッドにそのロジックを置くことでした。私はベストプラクティスに関するいくつかの洞察を期待していました。Rubyクラスの挿入メソッドまたはゲッターメソッド内で計算を行う必要がありますか?

その解決:私が最初に書いた

# Write a class TempTracker with these methods: 
# 
# insert()—records a new temperature 
# getMax()—returns the highest temp we've seen so far 
# getMin()—returns the lowest temp we've seen so far 
# getMean()—returns the mean of all temps we've seen so far 
# getMode()—returns a mode of all temps we've seen so far 

class TempTracker 
    def initialize 
    # for mode 
    @occurrences = [0] * 111 # array of 0s at indices 0..110 
    @max_occurrences = 0 
    @mode = nil 

    # for mean 
    @total_numbers = 0 
    @total_sum = 0.0 # mean should be float 
    @mean = nil 

    # for min and max 
    @min_temp = nil 
    @max_temp = nil 
    end 

    def insert(temperature) 
    # for mode 
    @occurrences[temperature] += 1 
    if @occurrences[temperature] > @max_occurrences 
     @mode = temperature 
     @max_occurrences = @occurrences[temperature] 
    end 

    # for mean 
    @total_numbers += 1 
    @total_sum += temperature 
    @mean = @total_sum/@total_numbers 

    # for min and max 
    @max_temp = temperature if @max_temp.nil? || temperature > @max_temp 
    @min_temp = temperature if @min_temp.nil? || temperature < @min_temp 
    end 

    def get_max 
    @max_temp 
    end 

    def get_min 
    @min_temp 
    end 

    def get_mean 
    @mean 
    end 

    def get_mode 
    @mode 
    end 
end 

挿入とgetterメソッド:

// ... 

    def insert(temp) 
    @max = temp if @max.nil? || @max < temp 
    @min = temp if @min.nil? || @min > temp 

    @total_sum += temp 
    @total_numbers += 1 

    @occurrences[temp] += 1 
    end 

// ... 

    def get_mean 
    @total_sum/@total_numbers 
    end 

    def get_mode 
    @occurrences.each_with_index.max[1] 
    end 
end 

任意のヘルプの理解場合/ insertメソッドで計算ロジックを持つ理由は非常に参考になります!

+1

アクセサーメソッドで「get」を含むRubyでは、お勧めできません。なぜ '@max.max'を[' max'](https://ruby-doc.org/core-2.4.1/Enumerable.html#method-i-max)を使ってしないのですか?これにより、これらのフィールドを最新の状態に保つ必要がなくなります。 – tadman

答えて

2

挿入は状態を変更する操作です。その場ですべての変更を反映させるのは理にかなっています。一方、状態を変更しないでください、それは単にそれを読み込みます。

1回の挿入と100回の読み取りを行うとします。前回よりも結果が変わることはないので、各getで計算を繰り返すことはあまり効率的ではありません。リソースの無駄ですが、いくらかクリーンなコードを作ることができます。


私はちょうど私が読み取り重いワークロードを想定していることに気づきました。あなたが読んでいる以上のものを書いている書き込みの重いワークロードでは、それは別の方法です。効率は、ゲッターに計算を入れることを指示します。本当の答えはありません。それは常にトレードオフです。私が言っていることです。

関連する問題