📑

コード書きの練習 二日目(四分位範囲と四分位偏差の実装)

2023/04/27に公開

やってみた

``````# 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

# 四分位範囲
def quartile_range(a_n)
q2 = median(a_n)

q1 = median(a_n.select { |n| n < q2 })
q3 = median(a_n.select { |n| n > q2 })

q3 - q1
end

# 四分位偏差
def quartile_deviation(a_n)
quartile_range(a_n) / 2.0
end

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

context do
let(:a_n) { [0, 10, 30, 30, 50, 60, 80, 90, 100] }

it { is_expected.to eq 50 }
end

context do
let(:a_n) { [0, 10, 30, 30] }

it { is_expected.to eq 20 }
end

context do
let(:a_n) { [60, 80, 90, 100] }

it { is_expected.to eq 85 }
end
end

describe '#quartile_range' do
subject { quartile_range(a_n) }

context do
let(:a_n) { [0, 10, 30, 30, 50, 60, 80, 90, 100] }

it { is_expected.to eq 65 }
end

context do
let(:a_n) { [0, 1, 1, 2, 3, 5, 8, 9, 9, 10] }

it { is_expected.to eq 8 }
end
end

describe '#quartile_deviation' do
subject { quartile_deviation(a_n) }

context do
let(:a_n) { [0, 10, 30, 30, 50, 60, 80, 90, 100] }

it { is_expected.to eq 32.5 }
end

context do
let(:a_n) { [0, 1, 1, 2, 3, 5, 8, 9, 9, 10] }

it { is_expected.to eq 4 }
end
end
end
``````