Reputation:
Ive been able to come up with one that is a completely solid star triangle but I'm having trouble creating a "hollow one" and a number one that both increments by whatever the number the user enters. Any help?
Upvotes: 2
Views: 172
Reputation: 11183
Other options, just for fun.
Hollow
n, cat, hyp = 4, "š±", "š±"
n.times do |n|
a = Array.new(n+1){' '}
a[0], a[-1] = cat, hyp
puts a.join
end
It returns:
# š±
# š±š±
# š± š±
# š± š±
n = 10
r = [*0..9, *'a'..'z']
n.times do |n|
puts r[0..n].join
end
It returns
# 0
# 01
# 012
# 0123
If you shuffle the array r.shuffle[0..n].join
, you could get random output:
# t
# 26
# ce0
# zqiw
some_emotics = (0..9).each_with_object([]) { |n, o| o << "1F96#{n}".to_i(16) }.pack 'U*'
n.times do |n|
puts some_emotics.split("").shuffle[0..n].join
end
to get:
# š„”
# š„¦š„”
# š„¤š„„š„
# š„©š„£š„¦š„„
Upvotes: 0
Reputation: 110665
def bt(n)
1.upto(n) do |i|
puts case i
when 1
'*'
when n
'*'*n
else
"*#{' '*(i-2)}*"
end
end
end
bt 8
*
**
* *
* *
* *
* *
* *
********
ROW = [*1..9, *'A'..'Z'].join
#=> "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def lt(n)
1.upto(n) { |i| puts ROW[0,i] }
end
lt 8
1
12
123
1234
12345
123456
1234567
12345678
lt 22
1
12
123
1234
12345
123456
1234567
12345678
123456789
123456789A
123456789AB
123456789ABC
123456789ABCD
123456789ABCDE
123456789ABCDEF
123456789ABCDEFG
123456789ABCDEFGH
123456789ABCDEFGHI
123456789ABCDEFGHIJ
123456789ABCDEFGHIJK
123456789ABCDEFGHIJKL
123456789ABCDEFGHIJKLM
ROW = 'š'*10
lt 6
š
šš
ššš
šššš
ššššš
šššššš
Upvotes: 1
Reputation: 22295
You could create a simple method with two loops, for the second triangle:
def print_numbers_right_triangle(height)
1.upto(height) do |row|
1.upto(row) do |i|
print i
end
puts
end
end
print "Plese enter the height of the triangle:"
print_numbers_right_triangle(gets.strip.to_i)
Example Usage:
Plese enter the height of the triangle: 8
1
12
123
1234
12345
123456
1234567
12345678
Upvotes: 0
Reputation: 356
This is my solution:
class RightTriangle
class << self
def draw_border(size:, char: '*')
validate(size)
1.upto(size) do |n|
1.upto(n) do |o|
break if n == size
o == 1 || o == n ? print(char) : print(' ')
end
n.times { print char } if n == size
puts if n > 0
end
end
def draw_numbers(size:)
validate(size)
1.upto(size) do |n|
1.upto(n) { |o| print o }
puts
end
end
private
def validate(size)
raise 'SizeError: `size` must be greater than 1' if size <= 1
end
end
end
# For the triangle border
RightTriangle.draw_border(size: 8) # character will be '*'
RightTriangle.draw_border(size: 8, char: 'a') # character will be 'a'
# For the numbers triangle
RightTriangle.draw_numbers(size: 8)
Upvotes: 1
Reputation: 13425
1st. iterate the lines
2nd. put "*" only in boundaries of the line: [0, i], filling " " inside:
3rd: exceptions for the 1st and last (n) case
n = 8
puts '*'
(n-2).times do |i|
puts '*' + ' ' * (i) + '*'
end
puts '*' * n if n > 1
Upvotes: 1