Hackerrank – Popis problému
Celý popis zadania sa nacháza – Hackerrank.
Riešenie
Pozrieť implementáciu. Postup je daný v zadaní
Vytvoril som riešenie v týchto programovacích jazykoch:
Všetky riešenia sú dostupné aj na mojom GitHub profile.
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import scala.io.Source object Solution extends App { val lines = Source.stdin.getLines().toList val birds = lines.tail.head.split(" ").map(_.toInt) val birdGroups = birds.groupBy(b => b).map(group => (group._1, group._2.length)) val biggestGroup = birdGroups.foldLeft((0, 0))((maxBirdCountType, group) => { val birdType = group._1 val birdTypeCount = group._2 if(maxBirdCountType._2 < birdTypeCount) { (birdType, birdTypeCount) } else { maxBirdCountType } }) println(biggestGroup._1) } |
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 30 31 32 33 34 |
import java.util.*; public class MigratoryBirds { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int tests = stdin.nextInt(); int[] birdTypes = new int[tests]; for(int i = 0; i < tests; i++) { birdTypes[i] = stdin.nextInt(); } Map<Integer, Integer> birdTypeCount = new HashMap<>(); for(int i = 0; i < tests; i++) { int birdType = birdTypes[i]; birdTypeCount.put(birdType, birdTypeCount.getOrDefault(birdType, 0) + 1); } Map.Entry<Integer, Integer> max = null; for(Map.Entry<Integer, Integer> birdCount : birdTypeCount.entrySet()) { int actualMax; if(max == null) { actualMax = 0; } else { actualMax = max.getValue(); } if(birdCount.getValue() > actualMax) { max = birdCount; } } System.out.println(max.getKey()); stdin.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 27 28 29 30 31 32 |
'use strict'; const processData = input => { const lines = input.split('\n'); const birds = lines[1].split(' ').map(i => parseInt(i)); const birdsCounts = []; for(let i = 0; i < birds.length; i++) { if(birdsCounts[birds[i]]) { birdsCounts[birds[i]] = ++birdsCounts[birds[i]]; } else { birdsCounts[birds[i]] = 1 } } let maxBirdType = 0; let maxBirdTypeCount = 0; for(let i = 0; i < birds.length; i++) { if(birdsCounts[birds[i]] > maxBirdTypeCount) { maxBirdTypeCount = birdsCounts[birds[i]]; maxBirdType = birds[i] } } console.log(maxBirdType); }; process.stdin.resume(); process.stdin.setEncoding("ascii"); let _input = ""; process.stdin.on("data", input => _input += input); process.stdin.on("end", () => processData(_input)); |