1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby 配列の平均値に最も近い値を取り出すアルゴリズム

Last updated at Posted at 2020-04-17

こんにちは、おすしです。

ary = [2, 3, 4, 23, 9, 15, 11]

def min_search(ary)
  for i in 1..(ary.count - 1) do
    if ary[0] > ary[i]
      min = ary[i]
    else
      min = ary[0]
    end
  end
  return min
end

def search(ary)
  absolute_val = []
  adds = 0
  ary.count.times {|i| adds += ary[i]}
  center = adds/ary.count

  for i in 0..(ary.count - 1) do
    n = 0
    m = 0

    if ary[i] <= center
      m = center - ary[i]
    else 
      n = ary[i] - center
    end

    if n <= m
      l = m
    else
      l = n
    end
    
    absolute_val.push(l)
  end
  
  min_absolute = min_search(absolute_val)

  for i in 0..(absolute_val.count - 1) do
    if absolute_val[i] == min_absolute
      p "配列の平均値である #{center} に最も近い値は #{ary[i]} です"
    end
  end
end

search(ary)

↑をコピペして実行してください。

配列の平均値に最も近い値を取り出します(正の数)

ご覧いただきありがとうございます!

追記

コメントでいただきました!
私が作成したアルゴリズムをたったの2行で完結させる美しいコードです。

ary = [2, 3, 4, 23, 9, 15, 11]

avg = ary.sum.fdiv(ary.size)
near=ary.min_by{|n| (n - avg).abs }

puts "配列の平均値である #{avg} に最も近い値は #{near} です"
1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?