0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

RubyでAtCoder ABC305(A, B, C)を解いてみた

Last updated at Posted at 2023-06-11

今回は、RubyでAtCoder ABC305のA, B, Cを解きました。備忘録として解き方をまとめていきたいと思います。

A - Water Station

a-305.rb
- puts (gets.to_f / 5).round * 5
+ puts gets.to_i.quo(5).round * 5

解説

与えられた整数を5で割ったものを小数点で四捨五入し、そこに5をかけたものが答えとなります。

B - ABCDEFG

b-305.rb
x, y = gets.split.sort.map{ |i| i.ord - 65 }
z = [3, 1, 4, 1, 5, 9]
puts z[x...y].sum

解説

ordメソッドを使って、与えられた文字を数値に変換し、それらに対応する距離を求めることで解くことができます。

C - Snuke the Cookie Picker

c-305.rb
h, w = gets.split.map(&:to_i)

top = left = Float::INFINITY
buttom = right = 0
array = Array.new(h){ gets.chomp }

h.times do |i|
  w.times do |j|
    if array[i][j] == "#"
      top = [top, i].min
      buttom = [buttom, i].max
      left = [left, j].min
      right = [right, j].max
    end
  end
end

top.upto(buttom) do |i|
  left.upto(right) do |j|
    if array[i][j] == "."
      puts "#{i + 1} #{j + 1}"
      exit
    end
  end
end
別解
h, w = gets.split.map(&:to_i)

array = Array.new(h){ gets.chomp }
no_cookie = "." * w
top = array.index{ _1 != no_cookie }
buttom = array.rindex{ _1 != no_cookie }
left = Float::INFINITY
- right = 0

h.times do |i|
  w.times do |j|
-   if array[i][j] == "#"
-     left = [left, j].min
-     right = [right, j].max
-   end

+   left = [left, j].min if array[i][j] == "#"
  end
end

- top.upto(buttom) do |i|
-   left.upto(right) do |j|
-     if array[i][j] == "."
-       puts "#{i + 1} #{j + 1}"

+ left.upto(w - 1) do |i|
+   top.upto(buttom) do |j|
+     if array[j][i] == "."
+       puts "#{j + 1} #{i + 1}"
        exit
      end
    end
  end

解説

最初に、#となっている最小・最大の行および列を求めます。このとき答えは、その範囲で.となっている部分の行・列の値となります。

0
0
5

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?