👻

コード書きの練習 一日目(中央値の実装)

2023/04/23に公開約900字

プログラミングに苦手意識があります。。。ということで、練習することにしました。一日目の題材は、中央値の実装です。

定義は https://mathlandscape.com/quartile/ を参考にしました。

やってみた

# frozen_string_literal: true

require 'rspec'

def median(a_n)
  length = a_n.length

  if length.even?
    ((a_n[length / 2 - 1] + a_n[length / 2]) / 2.0).round(2)
  else
    a_n[length / 2]
  end
end

RSpec.describe 'コード書きの練習' do
  describe '#median' do
    subject { median(a_n) }

    context '要素の個数が1個の場合' do
      let(:a_n) { [1] }

      it { is_expected.to eq 1 }
    end

    context '要素の個数が2個の場合' do
      let(:a_n) { [1, 2] }

      it { is_expected.to eq 1.5 }
    end

    context '要素の個数が3個の場合' do
      let(:a_n) { [1, 2, 3] }

      it { is_expected.to eq 2 }
    end

    context '要素の個数が4個の場合' do
      let(:a_n) { [1, 2, 3, 4] }

      it { is_expected.to eq 2.5 }
    end

    context '要素の個数が5個の場合' do
      let(:a_n) { [1, 2, 3, 4, 5] }

      it { is_expected.to eq 3 }
    end
  end
end

雑記

明日は、四分位数の実装をする予定です。

Discussion

ログインするとコメントできます