As an expert kotlin developer, write an optimal function to calculate the number of…
- User
As an expert kotlin developer, write an optimal function to calculate the number of inversions in a fifteen puzzle
- Assistant
Sure, here's a simple function in Kotlin to calculate the number of inversions in a fifteen puzzle.
Please note that in a fifteen puzzle, an inversion is any pair of blocks with numbers that are out of order.
fun countInversions(puzzle: Array<Array<Int>>): Int { val linear = puzzle.flatten() var inversions = 0 for (i in linear.indices) { for (j in i + 1 until linear.size) { if (linear[i] != 0 && linear[j] != 0 && linear[i] > linear[j]) { inversions++ } } } return inversions }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.