新手问题 如何用 ruby 打印半菱形,具体如下图

LPFpengfei · February 14, 2019 · Last by luikore replied at February 19, 2019 · 2008 hits

用 ruby 打印下面的图形,要求先递增在递减,循环往复

*
**
***
****
*****
****
***
**
*
**
***
****
*****
****
***
**
*
.......
def puts_abc(num)
  return '请输入大于0的数' if num <= 0
  array_1 = Array.new(num){|index| index + 1 }
  array_2 = []
  array_1.in_groups_of(4, false) {|group| array_2 << group}
  array_2.each_with_index do |array_3, index|
    if index.even?
      m = 1
      array_3.size.times do |a|
        puts '*' * m
        m = m + 1
      end
    else
      m = 5
      array_3.size.times do |n|
        puts '*' * m
        m = m - 1
      end
    end
  end
end

puts_abc(20)

还有没有更优雅点的

2 Floor has deleted
str = '*
**
***
****
*****
****
***
**
*
'
puts str

拿去用吧,清晰明了。绝对不存在看不懂的问题


def itoa(num)
    arr = (1...2*num).map do |e|
        i = e > num ? 2 * num - e : e
    end
    arr.shift
    arr.cycle

end
arrr = itoa 5
counter = 0

str = "*"
puts str
loop do
    counter += 1
    puts str * arrr.next     
    break if counter == 20
end
def print_half_diamond(lines, width: 5)
  cycle = width * 2 - 2
  return lines.times { puts '*' } if cycle.zero?
  lines.times do |line|
    index = line % cycle + 1
    count = index <= width ? index : width * 2 - index
    puts '*' * count
  end
end

输入是什么?输出是什么?你别光给输出不给输入啊。

如果只是要输出一个宽度为输入的半菱形的话

num = 4
row_sizes = 2.upto(num).to_a + (num-1).downto(1).to_a
puts '*' # 第一行
row_sizes.each {|width| puts '*' * width} # 重复多遍来反复输出

# => *
#**
#***
#****
#***
#**
#*

厉害了。。。。

Reply to msg7086

这本身就是打印菱形的一个变种编程题,要求输入一个行数,打印宽度不超过 5 的半菱形。。。。。。。。。。。

3 行代码搞定:

i=5
loop do
   i=0 if i > 9
   puts '*' * (1+(i%10-5).abs)
   i+=1
end
10 Floor has deleted
def f n
  [*(1..n), *(1...n).reverse_each].cycle {|n| puts '*' * n }
end
LPFpengfei closed this topic. 29 Jan 16:38
You need to Sign in before reply, if you don't have an account, please Sign up first.