Skip to content

Instantly share code, notes, and snippets.

@jerryOkafor
Forked from cdmunoz/Turnstile.kt
Created August 12, 2020 12:32
Show Gist options
  • Save jerryOkafor/035b4c6f3ca19c562b68f560075d03e8 to your computer and use it in GitHub Desktop.
Save jerryOkafor/035b4c6f3ca19c562b68f560075d03e8 to your computer and use it in GitHub Desktop.
Turnstile hackerrank's problem solution
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"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment