LoginSignup
2
0

More than 3 years have passed since last update.

Ruby と Python で解く AtCoder ARC080 D シミュレーション

Last updated at Posted at 2020-05-28

はじめに

AtCoder Problems の Recommendation を利用して、過去の問題を解いています。
AtCoder さん、AtCoder Problems さん、ありがとうございます。

今回のお題

AtCoder Regular Contest D - Grid Coloring
Difficulty: 855

今回のテーマ、シミュレーション

内容は難しいところはないと思いますが、実装に手間がかかりそうな問題です。

1 2 2 3 3
4 4 4 4 3
5 5 5 5 5

与えられた数値で上から順に左右に塗りつぶせばOKです。

Ruby Array

ruby.rb
h, w = gets.split.map(&:to_i)
_ = gets.to_i
a = gets.split.map(&:to_i)
m = Array.new(h){Array.new(w, 0)}
y, x, lr = 0, 0, 1
a.each_with_index do |n, v|
  n.times do
    m[y][x] = v + 1
    x += lr
    if x == w
      y += 1
      x = w - 1
      lr = -1
    elsif x < 0
      y += 1
      x = 0
      lr = 1
    end
  end
end
h.times do |i|
  puts m[i].join(' ')
end
join.rb
  puts m[i].join(' ')

  puts m[i] * ' '

最近知ったのですが、joinは上記の様に書くこともできます。

Ruby Class

ruby.rb
class MASS
  def initialize(h, w)
    @h = h
    @w = w
    @m = Array.new(@h){Array.new(@w, 0)}
    @x = 0
    @y = 0
    @LR = 1
  end
  def draw(v, n)
    n.times do
      @m[@y][@x] = v + 1
      @x += @LR
      if @x == @w
        @y += 1
        @x = @w - 1
        @LR = -1
      elsif @x < 0
        @y += 1
        @x = 0
        @LR = 1
      end
    end
  end
  def out
    @h.times do |i|
      puts @m[i].join(' ')
    end
  end
end

h, w = gets.split.map(&:to_i)
_ = gets.to_i
a = gets.split.map(&:to_i)
m = MASS.new(h, w)
a.each_with_index do |v, i|
  m.draw(i, v)
end
m.out

今回の問題では、あまり有効ではないのですが、学習を兼ねてclassを使用してみました。
コード長が倍近くになりましたが、実行時間は変わらないようです。

Python

python.py
from sys import stdin

def main():
    input = stdin.readline
    h, w = map(int, input().split())
    _ = int(input())
    a = list(map(int, input().split()))
    m = [[0] * w for _ in range(h)]
    x, y, LR, v = 0, 0, 1, 0
    for n in a:
        v += 1
        for _ in range(n):
            m[y][x] = str(v)
            x += LR
            if x == w:
                y += 1
                x = w - 1
                LR = -1
            elif x < 0:
                y += 1
                x = 0
                LR = 1
    for i in range(h):
        print(" ".join(m[i]))
main()

Python のコード長が長いのは、半角スペースもカウントしているからでしょうか。

Ruby Array Ruby Class Python
コード長 (Byte) 392 631 603
実行時間 (ms) 17 18 25
メモリ (KB) 2428 3836 3828

まとめ

  • ARC 080 D を解いた
  • Ruby に詳しくなった
  • Python に詳しくなった
2
0
4

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