Computer Science/Coding Test

[HackerRank] Sales by Match

Nomad Lee 2025. 4. 15. 15:28

https://www.hackerrank.com/challenges/sock-merchant/problem

 

Sales by Match | HackerRank

How many pairs of socks can Alex sell?

www.hackerrank.com

[문제 ]

There is a large pile of socks that must be paired by color. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.

당신에게는 다양한 색상의 양말이 무작위로 섞인 큰 양말 더미가 있습니다.

각 양말의 색상은 정수로 표시되며, 배열로 제공됩니다.

이 배열에서 각 색상의 양말이 몇 개씩 있는지 파악한 후,

같은 색상의 양말이 몇 쌍(pair)이나 만들어질 수 있는지를 계산해야 합니다.

[입력값]

Example

There is one pair of color and one of color. There are three odd socks left, one of each color. The number of pairs is.

Function Description

Complete the sockMerchant function in the editor below.

sockMerchant has the following parameter(s):

  • int n: the number of socks in the pile
  • int ar[n]: the colors of each sock

한 색깔의 쌍이 한 켤레 있습니다. 색깔마다 한 쌍씩, 세 개의 홀수 양말이 남았습니다. 양말의 쌍 개수입니다.

sockMerchant 함수를 완성하시오.

인자에는 각 양말의 색상을 나타내는 n개의 정수와 배열 ar이 주어집니다. 각 배열의 정수는 특정 색상을 나타냅니다.

[출력값]

Returns

  • int: the number of pairs

같은 색상의 양말이 몇 쌍이나 만들어질 수 있는지를 나타내는 정수 값을 출력합니다.

[예시]

Sample Input

9
10 20 20 10 10 30 50 10 20

위에서 짝이 맞는 쌍은 : [10, 10], [20, 20], [10, 10]

짝이 안 맞는 양말은 : 30, 50, 20

3쌍을 만들 수 있다.

Sample Output

 

3

 

[python 코드]

 

def sockMerchant(n, ar):
    dic = {}
    for i in ar:
        try:
            dic[i] = dic[i] + 1
        except:
            dic[i] = 1
    result = 0
    for j in dic:
        result = result + dic[j]//2
    return result

 

Counter 사용

from collections import Counter

def sockMerchant(n, ar):
    count_dict = Counter(ar)
    dict_result = dict((k, v // 2) for k, v in count_dict.items() if v > 1)
    return sum(dict_result.values())

'Computer Science > Coding Test' 카테고리의 다른 글

[HackerRank] The Minion Game  (2) 2025.04.21
[HackerRank]Repeated String  (0) 2025.04.19
[HackerRank] Jumping on the Clouds  (0) 2025.04.16
[HackerRank] Counting Valleys  (0) 2025.04.15