顺时针打印数组
2022-08-19 本文已影响0人
MIRROR1217
之前面试的时候这样一道算法:
给你一个正整数N,且N > 0,得到一个从1到N*N大小的数组,按照顺时针打印它
eg:n = 3,arr=[1,2,3,4,5,6,7,8,9]
期望结果:
[1, 2, 3]
[8, 9, 4]
[7, 6, 5]
当时有个思路,用三位数组做,arr[x][y]=arr[i],控制x和y的边界条件,但是时间比较紧张,没有完成,今天抽时间完成它,代码如下:
class Test1 {
// 1 2 3 4 5
// 16 17 18 19 6
// 15 24 25 20 7
// 14 23 22 21 8
// 13 12 11 10 9
companion object {
@JvmStatic
fun main(args: Array<String>) {
println("Test")
val num = 3
val arr = getArrNum(num)
println("arr = "+ arr.contentToString())
sort(arr, num)
}
fun sort(array: IntArray,num: Int) {
val arrs = Array(num){IntArray(num)}
var x = 0
var y = 0
var index = 0
var right = true
var down = false
var left = false
var up = false
var len = 1
while (index < num * num && x < num && y < num && x >= 0 && y >= 0) {
// println("x = $x,y = $y")
arrs[y][x] = array[index]
if (right) {
x += 1
if (x == (num - len)) {
right = false
down = true
}
} else if(down) {
y += 1
if (y == (num - len)) {
down = false
left = true
}
} else if (left) {
x -= 1
if (x == (len - 1)) {
left = false
up = true
}
} else if (up) {
y -= 1
if (y == len) {
up = false
right = true
len++
}
}
index++
}
// arrs[0][0] = 1
// arrs[1][0] = 2
for (arr in arrs) {
println(arr.contentToString())
}
}
fun getArrNum(num:Int):IntArray {
val length = num.times(num)
val arr = IntArray(length)
for(i in 0..length) {
if (i != length) {
arr[i] = i+1
}
}
return arr
}
}
}
结果:
image.png