Ruby solution
require "minitest/autorun" class DiamondGenerator def initialize width @width = width end def generate return nil if invalid_width? number_of_asterisks.map { |n| number_to_asterisks(n) }.join("\n") end private def invalid_width? @width.even? or @width.negative? end def number_to_asterisks number ("*" * number).center(@width).rstrip end def number_of_asterisks steps = (1...@width).step(2).to_a steps + [@width] + steps.reverse end end class DiamondGeneratorTest < MiniTest::Test def test_valid_diamond expected_diamond = <<~DIAMOND.chomp * *** ***** ******* ********* *********** ********* ******* ***** *** * DIAMOND assert_equal expected_diamond, DiamondGenerator.new(11).generate end def test_diamond_with_even_width assert_nil DiamondGenerator.new(6).generate end def test_diamond_with_negative_width assert_nil DiamondGenerator.new(-2).generate end end
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Ruby solution