0
0

More than 1 year has passed since last update.

[Ruby] AtCoder過去問 B - Picture Frame

Posted at

はじめに

AtCoder過去問をRubyで解いてみました。
よろしくお願いします。

問題はこちらから確認してください↓

B - Picture Frame

まずは入力を受け取ります。

h, w = gets.split.map(&:to_i)
pics = readlines.map(&:chomp)

2行目以降は文字列を配列として受け取っています。
入力例1で言うと、picsは["abc", "arc"]となっているはずです。

続いてフレームの一番上(1行目)と一番下を作ります。
つまり#だけの行を作ります。

これはw+2の#の数を用意します。
私は配列を用意してtimesをw+2回、回して配列に#を入れていきます。

h, w = gets.split.map(&:to_i)
pics = readlines.map(&:chomp)

top_bottom = []
(w+2).times do
  top << "#"
end

出力するときはtop_bottom.joinで配列の中の#を結合して一つの文字列にしてくれます。

h, w = gets.split.map(&:to_i)
pics = readlines.map(&:chomp)

top_bottom = []
(w+2).times do
  top << "#"
end

puts top_bottom.join

続いて写真の中身を出力していきます。
picsの中の文字列にそれぞれ先頭と最後に#を足してあげて出力します。

each文を回して式展開を利用して#を付け加えます。

h, w = gets.split.map(&:to_i)
pics = readlines.map(&:chomp)

top_bottom = []
(w+2).times do
  top << "#"
end

puts top_bottom.join
pics.each do |pic|
  puts "##{pic}#"
end

そして最後にもう一度top_bottomを出力して完成です。

h, w = gets.split.map(&:to_i)
pics = readlines.map(&:chomp)

top_bottom = []
(w+2).times do
  top << "#"
end

puts top_bottom.join
pics.each do |pic|
  puts "##{pic}#"
end
puts top_bottom.join
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