Skip to content

Instantly share code, notes, and snippets.

@cdmunoz
Created June 28, 2019 22:47
Show Gist options
  • Save cdmunoz/380a5cc454f98e8d22772c1366ada279 to your computer and use it in GitHub Desktop.
Save cdmunoz/380a5cc454f98e8d22772c1366ada279 to your computer and use it in GitHub Desktop.
Output Format Output the number of times every number from through appears in as a list of space-separated integers on one line.
//Hackerrank's counting sort problem:
// https://www.hackerrank.com/challenges/countingsort1/problem
//Challenge
//Given a list of integers, count and output the number of times each value appears as a list of space-separated integers.
//Function Description:
//Complete the countingSort function in the editor below. It should return an array of integers where each value is the number of occurrences of the element's index value in the original array.
//countingSort has the following parameter(s):
// arr: an array of integers
//Output Format
//Output the number of times every number from 0 through 99 appears in arr as a list of space-separated integers on one line.
// Complete the countingSort function below.
fun countingSort(arr: Array<Int>): Array<Int> {
val size = arr.size
val result = IntArray(size)
for (i in 0 until size) {
val counter = result[arr[i]]
if (counter == 0) result[arr[i]] = 1
else result[arr[i]]++
}
return result.take(100).toTypedArray()
}
fun main(args: Array<String>) {
val scan = Scanner(System.`in`)
val n = scan.nextLine().trim().toInt()
val arr = scan.nextLine().split(" ").map { it.trim().toInt() }.toTypedArray()
val result = countingSort(arr)
println(result.joinToString(" "))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment