forked from igorwojda/kotlin-coding-challenges
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.kt
62 lines (52 loc) · 1.69 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
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
}
}
// simplified iterative solution
private object Solution3 {
private fun generatePyramid(n: Int): MutableList<String> {
val list = mutableListOf<String>()
val maxRowLen = n * 2 - 1
for (i in 1..n) {
val rowLen = i * 2 - 1
val sideString = " ".repeat((maxRowLen - rowLen) / 2)
val hashString = "#".repeat(rowLen)
list.add("$sideString$hashString$sideString")
}
return list
}
}