0
0

More than 3 years have passed since last update.

【Ruby】行単位、列単位で合計値を求めるプログラムを作ってみた!

Last updated at Posted at 2021-07-14

アウトプットのネタに困ったらこれ!?
 上記の記事で出題してある、「行単位、列単位で合計値を求めるプログラム」の問題を解いてみました。「minitest」もしくは「Rspec」を用いた実装を求められているのかもしれませんが、一旦そこは後回しにすることにしました。

col1 col2 col3 col4 sum
row1 9 85 92 20 206
row2 68 25 80 55 228
row3 43 96 71 73 283
row4 43 19 20 87 169
row5 95 66 73 62 296
sum 258 291 336 297 1182

「Ruby力向上のための基礎トレーニング」をテストコード付きで解いてみた
 この上記の記事で紹介されているような「module」を使った実装を理解するにはまだまだ知識が不足していたため、ひとまず行と列の数字はランダムに出力されて、以下のような出力結果になるプログラムを作ればいいという考えで問題を解くことにしました。

  89|  75|  55|  78| 297|
  79|  67|   4|  29| 179|
  75|  59|  57|  73| 264|
  48|  29|  14|  78| 169|
  66|  47|  16|  17| 146|
 291| 230| 130| 258| 909|

 リファクタリングの余地は大いにありますが、初めはあまり時間をかけずに、このようなコードで意図した出力結果を得られるようになりました。

def sum_matrix
  num = (0..99).to_a
  input = []
  5.times do
    row = num.sample(4)
    row_sum = row.sum
    input << row
    row.insert(4,row_sum)
  end

  col_sum = []
  5.times do |count|
    col_sum << input[0][count] + input[1][count] + input[2][count] + input[3][count]
  end
  input << col_sum

  6.times do |count|
    5.times do |num|
      printf("%4d", input[count][num])
      print "|"
    end
    puts "\n"
  end
end

sum_matrix

 繰り返し処理を頻繁に利用しているところは美しくないですね。コメントをいただけるととても勉強になります。


0
0
0

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
0
0