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 ABC281(A, B, C)を解いてみた

Last updated at Posted at 2023-04-13

はじめに

Webエンジニアを目指して、RubyやRailsをいじってます。
今回は、RubyでAtCoder ABC281のA, B, Cを解きました。備忘録として解き方をまとめていきたいと思います。

A - Count Down

a-281.rb
n = gets.to_i
array = *(0..n)
puts array.reverse

解説

reverseメソッドを使って配列を逆転させることができます。

B - Sandwich Number

b-281.rb
s = gets.chomp
n = s[1..-2].to_i
if s.size != 8
  puts "No"
else
  array = *"A".."Z"
  if !array.include?(s[0]) || !array.include?(s[-1])
    puts "No"
    exit
  end
  
  if 100_000 <= n && n <= 999_999
    puts "Yes"
  else
    puts "No"
  end
end

<追記>
コメントでいただいた別解になります。

別解
s = gets.chomp

a, b, c = s.partition(/\d+/)
judge = ->(chr) { chr&.length == 1 && /[A-Z]/.match(chr) }
f = b.length == 6 && b.to_i.between?(100_000, 999_999)
puts judge.(a) && f && judge.(c) ? "Yes" : "No"

解説

問題文の条件を満たしているかを順に調べていき、1つでも満たさなければNo、すべて満たせばYesを出力します。

C - Circular Playlist

c-281.rb
n, t = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
sum = a.sum
t %= sum
i = 0
while t > 0
  if t <= a[i]
    puts "#{i + 1} #{t}"
    exit
  end
  t -= a[i]
  i += 1
end

解説

N<=10^5と大きいので、modを利用して操作回数を減らしています。そして、余りをもとにどの曲で終わるかを調べています。

0
0
1

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?