Created
March 18, 2020 03:14
-
-
Save syntacticsugar/2092815c85e729cf06eaec8a129f5f8f to your computer and use it in GitHub Desktop.
"Give me a Diamond"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
=begin | |
https://www.codewars.com/kata/5503013e34137eeeaa001648/train/ruby | |
Give me a Diamond | |
Jamie is a programmer, and James' girlfriend. She likes diamonds, and wants a diamond string from James. Since James doesn't know how to make this happen, he needs your help. | |
Task | |
You need to return a string that looks like a diamond shape when printed on the screen, using asterisk (*) characters. Trailing spaces should be removed, and every line must be terminated with a newline character (\n). | |
Return null/nil/None/... if the input is an even number or negative, as it is not possible to print a diamond of even or negative size. | |
Examples | |
A size 3 diamond: | |
* | |
*** | |
* | |
...which would appear as a string of " *\n***\n *\n" | |
A size 5 diamond: | |
* | |
*** | |
***** | |
*** | |
* | |
...that is: " *\n ***\n*****\n ***\n *\n" | |
A size 7 diamond: | |
* | |
*** | |
***** | |
******* | |
***** | |
*** | |
* | |
=end | |
def diamond(n) | |
# Make some diamonds! | |
if (n.even? || n <= 0) | |
nil | |
else | |
counter = n | |
whitespace = 1 | |
middle = ("*" * n) + "\n" | |
results = [] | |
results.push middle | |
until counter.eql? 1 | |
counter = counter - 2 | |
step = (" " * whitespace) + ("*" * counter ) + "\n" | |
whitespace = whitespace + 1 | |
results.push(step) | |
results.unshift(step) | |
end | |
results.join("") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment