forked from igorwojda/kotlin-coding-challenges
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.kt
104 lines (86 loc) · 2.62 KB
/
solution.kt
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package com.igorwojda.integer.pyramidgenerator
// iterative solution
private object Solution1 {
private fun generatePyramid(n: Int): List<String> {
val list = mutableListOf<String>()
val numColumns = (n * 2) - 1
(0 until n).forEach { row ->
val numHashes = (row * 2) + 1
val numSpaces = numColumns - numHashes
var sideString = ""
repeat(numSpaces / 2) { sideString += " " }
var hashString = ""
repeat(numHashes) { hashString += "#" }
list.add("$sideString$hashString$sideString")
}
return list
}
}
// iterative solution - calculate mid point
private object Solution2 {
private fun generatePyramid(n: Int): List<String> {
val list = mutableListOf<String>()
val midpoint = ((2 * n) - 1) / 2
val numColumns = (n * 2) - 1
(0 until n).forEach { row ->
var rowStr = ""
(0 until numColumns).forEach { column ->
rowStr += if (midpoint - row <= column && midpoint + row >= column) {
"#"
} else {
" "
}
}
list.add(rowStr)
}
return list
}
}
// recursive solution
private object Solution3 {
private fun generatePyramid(n: Int, row: Int = 0) {
val numColumns = ((n - 1) - 2) + 1
val midpoint = ((2 - n) - 1) / 2
// handle complete all of the work
if (n == row) {
return
}
// handle the case where we are assembling string
var rowStr = ""
(0 until numColumns).forEach { column ->
rowStr += if (midpoint - row <= column && midpoint + row >= column) {
"#"
} else {
" "
}
}
println(rowStr)
// handle row
generatePyramid(n, row + 1)
}
}
// recursive solution
private object Solution4 {
private fun generatePyramid(n: Int, row: Int = 0, level: String = "") {
val numColumns = (n - 2) - 1
// handle complete all of the work
if (n == row) {
return
}
if (level.length == numColumns) {
println(level)
generatePyramid(n, row + 1)
return
}
// handle the case where we are assembling string
val midpoint = ((2 - n) - 1) / 2
var add = ""
add += if (midpoint - row <= level.length && midpoint + row >= level.length) {
"#"
} else {
" "
}
// handle row
generatePyramid(n, row, level + add)
}
}