せかいや

いまいるここを、おもしろく http://sekai-in-the-box.appspot.com/

【アルゴリズム】【Ruby】 後置if文 ~ネストを浅くする

師匠に、もうこれ以上リファクタできないっす。お手上げっす

とメールをしたら返事が来た。

後置ifでネストを一つ減らせるよ

なるほど!やってみよう

 
■現在のコード全量

a =(0...10000).to_a
p a =( a.sample(4) << -1).sample(5)
min = 10000
max = -1
min_doko = 0
max_doko = 0

raise "ikinari dame na kazu" if a[0]<0 or a[0]>9999

i=0
while i < a.size
  if a[i]<0 or a[i]>9999
  	break
  else
    if min >a[i]
      min = a[i]
      min_doko = i
    end
    if max < a[i]
      max = a[i]
      max_doko = i
    end
  end
  i += 1
end

p "min " + min.to_s
p "max " + max.to_s
p "min_doko " + min_doko.to_s
p "max_doko " + max_doko.to_s


重複処理をメソッド化

def err? i
	true if i<0 or i>9999
end
raise "ikinari dame na kazu" if err? a.first

i=0
while i < a.size

 ⇒同じ判定処理をerr?メソッドにまとめる


 

ネストを浅くする

■修正前

while i < a.size
  if err? a[i]
  	break
  else
    if min >a[i]
      min = a[i] …


■修正後

while i < a.size
	break if err? a[i]
  if min >a[i]
    min = a[i] …

Javaではよくやってる手法なのに、言われるまで気がつかなかった><。
こういう感じで、異常系はreturnすることによってネストを浅くする↓

int method1(int a){
	if (a == 1) then
		return a
	end

	hogehogehoge・・・・
}


なるほどー。
だいぶ分かってきた!


■修正後コード全量

a =(0...10000).to_a
p a =( a.sample(4) << -1).sample(5)
min = 10000
max = -1
min_doko = 0
max_doko = 0

def err? i
	true if i<0 or i>9999
end

raise "ikinari dame na kazu" if err? a.first

i=0
while i < a.size
	break if err? a[i]
  if min >a[i]
    min = a[i]
    min_doko = i
  end
  if max < a[i]
    max = a[i]
    max_doko = i
  end
  i += 1
end

p "min " + min.to_s
p "max " + max.to_s
p "min_doko " + min_doko.to_s
p "max_doko " + max_doko.to_s