Skip to content

Instantly share code, notes, and snippets.

@OmarKRostom
Last active August 17, 2019 12:36
Show Gist options
  • Save OmarKRostom/247f74f549f66a0f560ab3acae8d605e to your computer and use it in GitHub Desktop.
Save OmarKRostom/247f74f549f66a0f560ab3acae8d605e to your computer and use it in GitHub Desktop.
Solution to minimum bribes in Kotlin (https://bit.ly/2OsT2F4)
var totalBribes = 0
fun minimumBribes(arr: Array<Int>): Unit {
var currentPerson = 1
var bribeArr = arr.clone()
var bribeMap = HashMap<Int, Int>().apply {
var index = 0
bribeArr.forEach {
put(it, index++)
}
}
for (currentIndex in 0 until arr.size) {
val currentPerson = arr[currentIndex]
val properIndex = currentPerson - 1
if (properIndex - currentIndex > 2) {
println("Too Chaotic")
return
}
}
while (currentPerson <= arr.size) {
val currentIndex = bribeMap.indexOf(currentPerson)!!
val correctIndex = currentPerson - 1
if (currentIndex == correctIndex) {
currentPerson++
continue
} else if (currentIndex - correctIndex > 0) {
bribeArr = hasBribed(currentPerson, bribeArr, bribeMap)
}
}
println(totalBribes)
totalBribes = 0
return
}
fun hasBribed(
person: Int,
arr: Array<Int>,
bribeMap: HashMap<Int, Int>
): Array<Int> {
val currentIndex = bribeMap.indexOf(person)!!
val correctIndex = person - 1
return if (currentIndex > correctIndex) {
arr[currentIndex] = arr[currentIndex - 1]
arr[currentIndex - 1] = person
bribeMap[person] = currentIndex - 1
bribeMap[arr[currentIndex]] = currentIndex
totalBribes++
hasBribed(person, arr, bribeMap)
} else {
arr
}
}
fun HashMap<Int, Int>.indexOf(key: Int) = get(key)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment