-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcustom christmas tree.js
73 lines (64 loc) · 2.23 KB
/
custom christmas tree.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
64
65
66
67
68
69
70
71
72
73
// Task
// Christmas is coming, and your task is to build a custom Christmas tree with the specified characters and the specified height.
// Inputs:
// chars: the specified characters.
// n: the specified height. A positive integer greater than 2.
// Output:
// A multiline string. Each line is separated by \n. A tree contains two parts: leaves and trunks.
// The leaves should be n rows. The first row fill in 1 char, the second row fill in 3 chars, and so on. A single space will be added between two adjust chars, and some of the necessary spaces will be added to the left side, to keep the shape of the tree. No space need to be added to the right side.
// The trunk should be at least 1 unit height, it depends on the value of the n. The minimum value of n is 3, and the height of the tree trunk is 1 unit height. If n increased by 3, and the tree trunk increased by 1 unit. For example, when n is 3,4 or 5, trunk should be 1 row; when n is 6,7 or 8, trunk should be 2 row; and so on.
// Still not understand the task? Look at the following example ;-)
// Examples
// For chars = "*@o" and n = 3,the output should be:
// *
// @ o
// * @ o
// |
// For chars = "*@o" and n = 6,the output should be:
// *
// @ o
// * @ o
// * @ o *
// @ o * @ o
// * @ o * @ o
// |
// |
// For chars = "1234" and n = 6,the output should be:
// 1
// 2 3
// 4 1 2
// 3 4 1 2
// 3 4 1 2 3
// 4 1 2 3 4 1
// |
// |
// For chars = "123456789" and n = 3,the output should be:
// 1
// 2 3
// 4 5 6
// |
function customChristmasTree(chars,n){
let result = ''
let trunk = Math.floor(n/3)
let tempTreeSymbol = 0
let space = n - 1
//tree
for (let i = 1; i<=n; i++) {
result += ' '.repeat(space)
for (let j = 1; j <= i; j++) {
if (tempTreeSymbol >= chars.length) {
tempTreeSymbol = 0
}
result += i==j ? chars[tempTreeSymbol] : chars[tempTreeSymbol] + " "
tempTreeSymbol++
}
result += '\n'
space--
}
//trunk
for (let i = 1; i <=trunk; i++){
result += i == trunk? ' '.repeat(n-1) + '|' : ' '.repeat(n-1) + '|\n'
}
console.log(result)
return result
}