forked from igorwojda/kotlin-coding-challenges
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.kt
68 lines (57 loc) · 2.27 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
package com.igorwojda.matrix.spiralmatrixgenerator
private object Solution1 {
private fun generateSpiralMatrix(n: Int): List<MutableList<Int?>> {
val list = MutableList(n) {
MutableList<Int?>(n) { null }
}
var direction = MatrixDirection.RIGHT
var rowIndex = 0
var columnIndex = 0
val maxNumber = n * n
val lastIndex = n - 1
(1..maxNumber).forEach {
list[rowIndex][columnIndex] = it
when (direction) {
MatrixDirection.RIGHT -> {
val rightValue = if (columnIndex == lastIndex) null else list[rowIndex][columnIndex + 1]
if (rightValue == null && columnIndex < lastIndex) {
columnIndex++
} else {
direction = MatrixDirection.DOWN
rowIndex++
}
}
MatrixDirection.DOWN -> {
val downValue = if (rowIndex == lastIndex) null else list[rowIndex + 1][columnIndex]
if (downValue == null && rowIndex < lastIndex) {
rowIndex++
} else {
columnIndex--
direction = MatrixDirection.LEFT
}
}
MatrixDirection.LEFT -> {
val leftValue = if (columnIndex == 0) null else list[rowIndex][columnIndex - 1]
if (leftValue == null && columnIndex > 0) {
columnIndex--
} else {
rowIndex--
direction = MatrixDirection.UP
}
}
MatrixDirection.UP -> {
val upValue = if (rowIndex == 0) null else list[rowIndex - 1][columnIndex]
if (upValue == null && rowIndex > 0) { // rowIndex == 0
rowIndex--
} else {
columnIndex++
direction = MatrixDirection.RIGHT
}
}
}
}
return list
}
private enum class MatrixDirection { UP, DOWN, LEFT, RIGHT }
}
private object KtLintWillNotComplain