Help us understand the problem. What is going on with this article?

[Ruby基礎学習] パターンの表示③

More than 5 years have passed since last update.

はじめに

章末問題まできた。章末問題1つ目。

問題

以下を表示する。

########
 ######
  ####
   ##

解答

#が下に行くごとに2個ずつ減っていって、
逆に空白は2個ずつ増えている。

最初はとりあえず無理やり表示できるようにした。

hash_count = 8
space_count = 0
4.times do
   print " " * (space_count / 2)
   print "#" * hash_count
   print " " * (space_count / 2)
   puts ""

   hash_count -= 2
   space_count += 2
 end

ちょっとすっきりさせた。

sharp = 8
space = 0
4.times do |i|
    space_text = " " * (space / 2)
    puts space_text + ("#" * sharp) + space_text
    sharp -= 2
    space += 2
end

もっとシンプルにしたいなぁと考えてる時に、
今以下のように表示させようとしているけど、
右端に空白をひっつける必要はないのでは?と思った。

########
□######□
□□####□□
□□□##□□□

そうやって色々考えたらこうなった。
シンプルになったなぁ。

[*1..4].reverse.each.with_index{ |c, i| puts (" " * i) + ("#" * c * 2) }

問題の出典

  • プログラマの考え方がおもしろいほど身につく本 問題解決能力を鍛えよう!
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした