Hackerrank – Problem Statement
A description of the problem can be found on Hackerrank.
Solution
Until the sticks
array is empty:
- print the length of sticks array
- sort the array
- get the minimum value as first element of the array
- cut the array filtering only values greater than minimum
I created solution in:
All solutions are also available on my GitHub.
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 |
import java.util.*; public class CutTheSticks { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int tests = stdin.nextInt(); List<Integer> sticks = new LinkedList<>(); for(int i = 0; i < tests; i++) { sticks.add(stdin.nextInt()); } while(!sticks.isEmpty()) { System.out.println(sticks.size()); Collections.sort(sticks); int min = sticks.get(0); List<Integer> filtered = new LinkedList<>(); for(int j = 0; j < sticks.size(); j++) { if(sticks.get(j) > min) { filtered.add(sticks.get(j)); } } sticks = filtered; } stdin.close(); } } |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
'use strict'; const processData = input => { const lines = input.split('\n'); let sticks = lines[1].split(' ').map(i => parseInt(i)); while(sticks.length > 0) { console.log(sticks.length); sticks.sort((a, b) => a - b); const min = sticks[0]; sticks = sticks.filter(i => i > min); } }; process.stdin.resume(); process.stdin.setEncoding("ascii"); let _input = ""; process.stdin.on("data", input => _input += input); process.stdin.on("end", () => processData(_input)); |
Scala
1 2 3 4 5 6 7 8 9 10 11 |
import scala.io.Source object CutTheSticks extends App { var sticks = Source.stdin.getLines().toList.tail.head.split(" ").map(_.toInt) while (!sticks.isEmpty) { println(sticks.length) val sortedSticks = sticks.sorted val min = sortedSticks(0) sticks = sortedSticks.filter(_ > min) } } |
Ruby
1 2 3 4 5 6 7 8 |
n = gets.to_i sticks = gets.split.map(&:to_i) while(sticks.size > 0) do puts sticks.size sticks.sort!{|a, b| a <=> b} min = sticks[0] sticks = sticks.filter {|i| i > min} end |