[Kotlin] Korean Coding Test - Programmers - Parallel
KotlinQuestion
The two-dimensional array dots containing the coordinates of the four points are given as parameters as follows:
[[x1, y1], [x2, y2], [x3, y3], [x4, y4]]
Complete the solution function by connecting two of the four points given, and if two straight lines are parallel, return zero if there is no one.
Restrictions
dots
length = 4
The elements of dots
are in the form [x, y] and x, y are integers.(0 ≤ x, y ≤ 100)
Two or more different points do not overlap.
Return 1 even if the two straight lines overlap (if they match).
Not given if the straight line connecting any two points is parallel to the x-axis or y-axis.
Input/Output Example
Input/Output Example #1
- Input: [[1, 4], [9, 2], [3, 8], [11, 6]]
- Output: 1
- Description: Connect the points [1, 4], [3, 8] and [9, 2], [11, 6], and the two lines are parallel.
Input/Output Example #2
- Input: [[3, 5], [4, 1], [2, 4], [5, 10]]
- Output: 0
- Description: No matter how the points are connected, they are not parallel.
Solve
To know if it is parallel, you need to calculate the slope of the line that is created after the point.
- Slope = increase in y value / increase in x value
The y-intercept is not considered because it is judged to be parallel even if the two straight lines overlap.
It must be parallel so that each point is not connected.
If there is a line segment with the same slope, the calculation is terminated because only parallel lines exist.
Code
class Solution {
fun solution(dots: Array<IntArray>): Int {
// 1 if parallel lines exist, 0 if not
var answer = 0
// Record slope - key: slope, value: point 1 coordinate, point 2 coordinate
val slopes = mutableMapOf<Double, Pair<IntArray, IntArray>>()
// Set repeat statements to avoid comparison between identical points
for (i in 0 until dots.size - 1) {
if (answer == 1) break
// Exclude the i-th coordinate already calculated.
for (j in i + 1 until dots.size) {
// Slope = increase in y value / increase in x value
val x = dots[i][0] - dots[j][0]
val y = dots[i][1] - dots[j][1]
val slope = y.toDouble() / x.toDouble()
// 동일한 기울기가 없는 경우 기록합니다.
if (!slopes.containsKey(slope)) slopes[slope] = Pair(dots[i], dots[j])
else {
slopes.filter { it.key == slope }
.forEach {
// Except where each point is connected
if (dots[i][0] == it.value.first[0] || dots[i][1] == it.value.first[1]) return@forEach
if (dots[i][0] == it.value.second[0] || dots[i][1] == it.value.second[1]) return@forEach
if (dots[j][0] == it.value.second[0] || dots[j][1] == it.value.second[1]) return@forEach
if (dots[j][0] == it.value.first[0] || dots[j][1] == it.value.first[1]) return@forEach
answer = 1
}
}
}
}
return answer
}
}