Hackerrank – Problem Statement A description of the problem can be found on Hackerrank. Solution Look at the implementation. I created solution in: Scala Java Javascript All solutions are also available on my GitHub profile. Scala
|
import scala.io.Source object Solution{ def countingSort(arr: Array[Int]): Array[Int] = { val countsOfNumbers = arr.sorted.groupBy(i => i).map(a => (a._1, a._2.length)) (0 until 100).map(countsOfNumbers.getOrElse(_, 0)).toArray } def main(args: Array[String]) { val lines = Source.stdin.getLines().toList val arr = lines.tail.head.split(" ").map(_.toInt) val result = countingSort(arr) println (result.mkString(" ")) } } |
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
import java.util.*; public class Solution { static int[] countingSort(int[] arr) { int[] counts = new int[100]; for(int i = 0; i < arr.length; i++) { counts[arr[i]]++; } return counts; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] arr = new int[n]; for(int arr_i = 0; arr_i < n; arr_i++){ arr[arr_i] = in.nextInt(); } int[] result = countingSort(arr); for (int i = 0; i < result.length; i++) { System.out.print(result[i] + (i != result.length - 1 ? " " : "")); } System.out.println(""); in.close(); } } |
Javascript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
'use strict'; const counting = (arr) => { const counts = [] for(let i = 0; i < 100; i++) { counts[i] = 0; } for(let i = 0; i < arr.length; i++) { counts[arr[i]]++; } console.log(counts.join(' ')); } const processData = input => { const lines = input.split('\n'); const arr = lines[1].split(' ').map(i => parseInt(i)); counting(arr); }; process.stdin.resume(); process.stdin.setEncoding("ascii"); let _input = ""; process.stdin.on("data", input => _input += input); process.stdin.on("end", () => processData(_input)); |