Created
May 25, 2015 23:15
-
-
Save maripiyoko/724f6a1cf5c21800c186 to your computer and use it in GitHub Desktop.
Matrix-like Computation in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
class MatrixSum | |
def self.sumup_numbers(input) | |
# 行の合計を計算 | |
input_with_row_sum = input.map do |list| | |
append_sum_to_last(list) | |
end | |
# 列の合計を計算 | |
input_with_row_sum.transpose.map do |list| | |
append_sum_to_last(list) | |
end.transpose | |
end | |
def self.format_numbers(result) | |
result.map do |line| | |
line.map { |num| "%5d"%num } | |
end | |
end | |
def self.generate_input(n) | |
Array.new(n) { Array.new(n) { [*1..100].sample } } | |
end | |
def self.append_sum_to_last(list) | |
sum = list.inject(&:+) | |
list + [sum] | |
end | |
end | |
describe MatrixSum do | |
describe "#sumup_numbers" do | |
input = [ | |
[52, 96, 15, 20], | |
[86, 22, 35, 45], | |
[45, 78, 54, 36], | |
[16, 86, 74, 55] | |
]; | |
output = [ | |
[52, 96, 15, 20, 183], | |
[86, 22, 35, 45, 188], | |
[45, 78, 54, 36, 213], | |
[16, 86, 74, 55, 231], | |
[199, 282, 178, 156, 815] | |
]; | |
let(:n) { input.size } | |
let(:result) { MatrixSum.sumup_numbers(input) } | |
let(:formatted_result) { MatrixSum.format_numbers(result) } | |
let(:table) { numbers.map { |s| s.split(' ') } } | |
let(:numbers_by_col) do | |
end | |
it '何らかのデータが出力されること' do | |
p result | |
expect(result.size).to be > 1 | |
end | |
it '結果値はoutputに一致すること' do | |
p result | |
p output | |
expect(result).to eq output | |
end | |
it '各数値は5桁になっていること' do | |
formatted_result.each do |line| | |
line.each do |n| | |
expect(n.size).to eq 5 | |
end | |
end | |
end | |
it '各数値は右寄せになっていること' do | |
formatted_result.each do |line| | |
line.each do |n| | |
p n | |
expect(n).to match(/^\s+\d+$/) | |
end | |
end | |
end | |
it 'n+1行になっていること' do | |
expect(result.size).to eq n+1 | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment