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

Last updated at Posted at 2023-05-03

はじめに

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

A - Five Integers

a-268.rb
puts gets.split.uniq.size

解説

uniqメソッドで重複を取り除いた後の大きさを出力すればOKです。

B - Prefix?

b-268.rb
# 修正前
s = gets.chomp.chars
t = gets.chomp.chars

s.each_with_index do |factor, index|
  if factor != t[index]
    puts "No"
    exit
  end
end
puts "Yes"
b-268.rb
# 修正後
s = gets.chomp
t = gets.chomp[0, s.size]
puts s == t ? "Yes" : "No"
別解
s = gets.chomp
t = gets.chomp
puts t.start_with?(s) ? "Yes" : "No" 

解説

先頭から順にsとtが一致しているか調べていき、途中で一致しないものがあればNoを出力して終了、すべて一致していればYesを出力します。

C - Chinese Restaurant

c-268.rb
n = gets.to_i
m = gets.split.map(&:to_i)

count = Array.new(n, 0)
n.times do |i|
  j = m[i] - i
  count[(j - 1) % n] += 1
  count[j % n] += 1
  count[(j + 1) % n] += 1
end
puts count.max

解説

公式解説を参考にしました)

演算数を減らしてより高速にしています。

0
0
2

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?