Last active
February 5, 2024 03:56
-
-
Save cdmunoz/9bc6441f91b616d402f3a8806a7a52bd to your computer and use it in GitHub Desktop.
Turnstile hackerrank's problem solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun getTimes(times: Array<Int>, directions: Array<Int>): Array<Int> { | |
val result: Array<Int> = Array(times.size) { 0 } | |
val endTime: Int = times.max() ?: 0 | |
if (endTime == 0) return result | |
val inQueue: Queue<Int> = LinkedList() | |
val outQueue: Queue<Int> = LinkedList() | |
var currentIndex = 0 | |
var turnstile = 0 | |
for (time in 0 until endTime + 1) { | |
while (times[currentIndex] == time) { | |
if (directions[currentIndex] == 0) { | |
inQueue.add(currentIndex) | |
} | |
if (directions[currentIndex] == 1) { | |
outQueue.add(currentIndex) | |
} | |
currentIndex++ | |
if (currentIndex == times.size) break | |
} | |
val noPersonOnTurn = inQueue.size + outQueue.size == 0 | |
if (noPersonOnTurn) turnstile = 0 | |
if (turnstile == 1 || outQueue.size == 0) { | |
if (inQueue.size > 0) { | |
val next = inQueue.poll() | |
result[next] = time | |
turnstile = 1 | |
} else { | |
if (outQueue.size > 0) { | |
val next = outQueue.poll() | |
result[next] = time | |
turnstile = 2 | |
} | |
} | |
} else { | |
if (outQueue.size > 0) { | |
val next = outQueue.poll() | |
result[next] = time | |
turnstile = 2 | |
} | |
} | |
} | |
if (inQueue.size > 0) { | |
var newEndTime = endTime | |
for(time in 0 until inQueue.size) { | |
val next = inQueue.poll() | |
result[next] = newEndTime + 1 | |
newEndTime++ | |
} | |
} | |
return result | |
} | |
fun main(args: Array<String>) { | |
val timeCount = readLine()!!.trim().toInt() | |
val time = Array<Int>(timeCount, { 0 }) | |
for (i in 0 until timeCount) { | |
val timeItem = readLine()!!.trim().toInt() | |
time[i] = timeItem | |
} | |
val directionCount = readLine()!!.trim().toInt() | |
val direction = Array<Int>(directionCount, { 0 }) | |
for (i in 0 until directionCount) { | |
val directionItem = readLine()!!.trim().toInt() | |
direction[i] = directionItem | |
} | |
val result = getTimes(time, direction) | |
println(result.joinToString("\n")) | |
} |
Can you please post the approach also.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@FiratShahverdiyev Question link here