-3

I'm trying to write code that prints a number input by a user in a right triangle. For example, if 8 is entered, it should look as below:

*
**
* *
*  *
*   *
*    *
*     *
********
1
12
123
1234
12345
123456
1234567
123345678

I'm trying to get this to work:

puts " Enter a number: "
number = gets.to_i
puts "*" * number
count = 0
while count < number - 2
  print "*"
  print " " * (number - 2)
  puts "*"
  count += 1
end
puts "*" * number

The result comes out as a square. This is what I get:

*****
*   *
*   *
*   *
*****

Where am I going wrong?

sawa
  • 165,429
  • 45
  • 277
  • 381
CJ15
  • 29
  • 6

2 Answers2

2

The top side of your accidental square is coming from this line

puts " Enter a number: "
number = gets.to_i
--> puts "*" * number <--

And your right side doesnt slant because the value of number doesnt change. You should be using count instead

Katajun
  • 435
  • 3
  • 14
  • OK thank you Katamari and @luker both comments/answers helped me with the first part of the triangles now but now the issues is if a user enters 1 it prints 2 stars instead of one am i over looking something. – CJ15 Jan 31 '18 at 20:04
1

Below is an alternative approach where you have decoupled logic of creating rows and what should be present in that rows

def run(how_many_rows, &display_block)
  how_many_rows.times do |row_index|
    to_display = display_block.call(row_index)

    puts(to_display)
  end
end

how_many_rows = gets.to_i

run(how_many_rows) do |row|
  Array.new(row + 1) do |idx|
    is_first_char = idx == 0
    is_last_char  = idx == row
    is_last_row   = (row + 1) == how_many_rows

    show_star = is_first_char || is_last_char || is_last_row

    if show_star
      '*'
    else
      ' '
    end
  end.join
end

run(how_many_rows) do |row|
  (1..(row + 1)).to_a.join
end
djaszczurowski
  • 4,385
  • 1
  • 18
  • 28