TCreopargh
书山有路搞为径,学海无涯机作舟。
乱搭的站

螺旋填数(Kotlin)

螺旋填数的Kotlin实现。

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
import java.util.Scanner
import java.util.Vector

fun main() {
    val n = Scanner(System.`in`).nextInt()
    val canvas = Vector<Vector<Int>>()
    for (i in 0 until n) {
        val line = Vector<Int>()
        line.setSize(n)
        canvas.add(line)
    }
    var direction = Direction.RIGHT
    var i = 0
    var j = 0
    for (k in 1..n * n) {
        canvas[i][j] = k
        when (direction) {
            Direction.RIGHT -> if (j + 1 >= n || canvas[i][j + 1] != null) direction = direction.next()
            Direction.DOWN -> if (i + 1 >= n || canvas[i + 1][j] != null) direction = direction.next()
            Direction.LEFT -> if (j - 1 < 0 || canvas[i][j - 1] != null) direction = direction.next()
            Direction.UP -> if (i - 1 < 0 || canvas[i - 1][j] != null) direction = direction.next()
        }
        when (direction) {
            Direction.RIGHT -> j++
            Direction.DOWN -> i++
            Direction.LEFT -> j--
            Direction.UP -> i--
        }
    }
    for (line in canvas) {
        for (num in line) {
            print("$num ")
        }
        println()
    }
}

enum class Direction {
    RIGHT,
    DOWN,
    LEFT,
    UP;

    fun next(): Direction {
        return if (this.ordinal == 3) RIGHT else values()[this.ordinal + 1]
    }
}

可以看到Kotlin对于Vector和List的操作比Java简单不少,尤其是二维Vector或List,想要给某个元素赋值在Java还得写成vector.get(i).set(j, newValue)这种繁琐的写法,而Kotlin甚至可以直接像二维数组一样用。

真香!

赞赏

发表回复

textsms
account_circle
email

乱搭的站

螺旋填数(Kotlin)
螺旋填数的Kotlin实现。 import java.util.Scanner import java.util.Vector fun main() { val n = Scanner(System.`in`).nextInt() val canvas = Vector() for (i in 0…
扫描二维码继续阅读
2019-02-01