Hackerrank – Popis problému
Celý popis zadania sa nacháza – Hackerrank.
Riešenie
Vytvoril som množiny ponožiek rovnakej farby. Pre každú množinu som vytvoril počet párov: number_of_socks / 2
. Výsledok je celkový počet párov.
Vytvoril som riešenie v týchto programovacích jazykoch:
Všetky riešenia sú dostupné aj na mojom GitHub profile.
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 |
import java.util.*; public class SockMerchant { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int sockCount = stdin.nextInt(); Map<Integer, Integer> sockGroupsCount = new HashMap<>(); for(int i = 0; i < sockCount; i++) { int color = stdin.nextInt(); if(sockGroupsCount.containsKey(color)) { int count = sockGroupsCount.get(color); sockGroupsCount.put(color, count + 1); } else { sockGroupsCount.put(color, 1); } } int pairs = 0; for(int count : sockGroupsCount.values()) { pairs += count / 2; } System.out.println(pairs); 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 |
'use strict'; const processData = input => { const lines = input.split('\n'); const socks = lines[1].split(' ').map(i => parseInt(i)); const sockGroupsCount = new Map(); for(let i = 0; i < socks.length; i++) { const color = socks[i]; if(sockGroupsCount.get(color)) { const count = sockGroupsCount.get(color); sockGroupsCount.set(color, count + 1); } else { sockGroupsCount.set(color, 1); } } let pairs = 0; const groups = Array.from(sockGroupsCount.values()); for(let i = 0; i < groups.length; i++) { const count = groups[i]; pairs += Math.floor(count / 2); } console.log(pairs); }; 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 SockMerchant extends App { val lines = Source.stdin.getLines().toList val socks = lines(1).split(" ").map(_.toInt) val sockGroups = socks.groupBy(c => c) val sockGroupPairs = sockGroups.map(group => group._2.length / 2) val pairs = sockGroupPairs.sum println(pairs) } |
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
n = gets.to_i socks = gets.split(" ") sock_groups = Hash.new socks.each do |s| if !sock_groups.include?(s) sock_groups[s] = 1 else count = sock_groups[s] sock_groups[s] = count + 1 end end pairs = 0 sock_groups.values.each { |v| pairs += v / 2} puts pairs |