-
Notifications
You must be signed in to change notification settings - Fork 0
/
Give me a Diamond.js
63 lines (50 loc) · 1.54 KB
/
Give me a Diamond.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// 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"
function diamond(n){
if ((n % 2 === 0) || (n < 0)) {
return null
} else {
let diamondLine = ""
for (let i = 1; i <= n; i += 2){
let whitespace = " ".repeat((n - i) / 2);
let stars = "*".repeat(i);
let line = whitespace + stars + "\n"
diamondLine += line;
}
for (let i = n - 2; i > 0; i -= 2){
let whitespace = " ".repeat((n - i) / 2);
let stars = "*".repeat(i);
let line = whitespace + stars + "\n"
diamondLine += line;
}
return diamondLine
}
}
// top solution on codewars
function diamond (n) {
if (n <= 0 || n % 2 === 0) return null
str = ''
for (let i = 0; i < n; i++) {
let len = Math.abs((n-2*i-1)/2)
str += ' '.repeat(len)
str += '*'.repeat(n-2*len)
str += '\n'
}
return str
}