[Kotlin] Korean Coding Test - Programmers - Carpet
Kotlin2023-10-26 19:56 (KST)
Question
Leo went to buy a carpet and saw a grid-shaped carpet painted yellow in the center and a row of borders brown, as shown in the picture below.
![carpet.png](https://file.dico.me/2023/10/20231017155000_000.png)
Leo came home and remembered the number of yellow and brown colored gratings on the carpet he had seen earlier, but not the size of the whole carpet.
When the number brown of brown grids and the number yellow of yellow grids are given as parameters in the carpet, write the solution function so that the width and length of the carpet are arranged in order and returned.
Restrictions
The brown number in the brown lattice is a natural number that is not less than 8 but not more than 5,000.
Yellow in the yellow grid is a natural number of 1 or more and less than 2,000,000.
The horizontal length of the carpet is equal to or longer than the vertical length.
Input/Output Example
Input/Output Example #1
- Input
- brown: 10
- yellow: 2
- Output: [4, 3]
Input/Output Example #2
- Input
- brown: 8
- yellow: 1
- Output: [3, 3]
Input/Output Example #3
- Input
- brown: 24
- yellow: 24
- Output: [8, 6]
Solve
Total area = width × length = brown + yellow
circumference half = width + length = brown / 2 + 2
Yellow area = (width - 2) x (length - 2)
Brown Area = Total Area - Yellow Area
Code
class Solution {
fun solution(brown: Int, yellow: Int): IntArray {
val answer = IntArray(2)
val totalArea = brown + yellow // width * height
val halfLap = brown / 2 + 2 // width + height
// Reduce the length of "width + length" by 1 and check only the size that satisfies "width >= height".
for (width in halfLap - 1 downTo halfLap / 2) {
// Dividing the entire area by the horizontal length yields a vertical length.
if (totalArea % width != 0) continue
// Verification
val height = halfLap - width
val yellowArea = (width - 2) * (height - 2)
val brownArea = totalArea - yellowArea
if (brownArea == brown && yellowArea == yellow) {
answer[0] = width
answer[1] = height
break
}
}
return answer
}
}
TEST 1 〉 Pass (0.01ms, 61.4MB)
TEST 2 〉 Pass (0.01ms, 61.8MB)
TEST 3 〉 Pass (0.02ms, 62.4MB)
TEST 4 〉 Pass (0.01ms, 61.8MB)
TEST 5 〉 Pass (0.01ms, 60.4MB)
TEST 6 〉 Pass (0.02ms, 60.6MB)
TEST 7 〉 Pass (0.02ms, 61.4MB)
TEST 8 〉 Pass (0.04ms, 60.9MB)
TEST 9 〉 Pass (0.02ms, 60.4MB)
TEST 10 〉 Pass (0.04ms, 59.7MB)
TEST 11 〉 Pass (0.01ms, 57.6MB)
TEST 12 〉 Pass (0.01ms, 59.2MB)
TEST 13 〉 Pass (0.01ms, 62MB)