-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathReturnsAndJumps.kt
81 lines (66 loc) · 2.47 KB
/
ReturnsAndJumps.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
import kotlin.math.absoluteValue
class ReturnsAndJumps {
private val obstacles = arrayOf(Pair(1, 1), Pair(2, 0), Pair(1, -5))
fun test() {
println("Break and Continue Labels")
val position = Pair(0, 0)
move1(position, Pair(3, -5))
move2(position, Pair(3, -5))
}
private fun move1(position: Pair<Int, Int>, steps: Pair<Int, Int>): Pair<Int, Int> {
var newPos = position
val moveForward = steps.first > 0
val turnRight = steps.second > 0
val x = if (moveForward) 1 else -1
val y = if (turnRight) 1 else -1
moving@ while (true) {
horizontal@ for (upOrDown in 1..steps.first.absoluteValue) {
newPos = Pair(newPos.first + x, newPos.second)
print("$newPos")
}
vertical@ for (leftOrRight in 1..steps.second.absoluteValue) {
newPos = Pair(newPos.first, newPos.second + y)
print("$newPos")
}
break@moving
}
println("")
return newPos
}
private fun move2(position: Pair<Int, Int>, steps: Pair<Int, Int>): Pair<Int, Int> {
var newPos = position
val moveForward = steps.first > 0
val turnRight = steps.second > 0
val x = if (moveForward) 1 else -1
val y = if (turnRight) 1 else -1
moving@ while (true) {
horizontal@ for (upOrDown in 1..steps.first.absoluteValue) {
if (hasObstacle(Pair(newPos.first + x, newPos.second))) {
print("Oops,${Pair(newPos.first + x, newPos.second)} is not allowed")
break@horizontal
}
newPos = Pair(newPos.first + x, newPos.second)
print("$newPos")
}
vertical@ for (leftOrRight in 1..steps.second.absoluteValue) {
if (hasObstacle(Pair(newPos.first, newPos.second + y))) {
print("Oops,${Pair(newPos.first, newPos.second + y)} is not allowed")
break@vertical
}
newPos = Pair(newPos.first, newPos.second + y)
print("$newPos")
}
break@moving
}
println("")
return newPos
}
private fun hasObstacle(pos: Pair<Int, Int>): Boolean {
obstacles.forEach {
if (it.first == pos.first && it.second == pos.second) {
return true
}
}
return false
}
}