|
| 1 | +/* |
| 2 | +* Author:- Rahul Malhotra |
| 3 | +* Source:- Programming Vidya |
| 4 | +* Description:- Solution for HackerRank Sales by Match problem |
| 5 | +* Problem Link:- https://www.hackerrank.com/challenges/sock-merchant/problem |
| 6 | +* Website:- www.programmingvidya.com |
| 7 | +*/ |
| 8 | + |
| 9 | +#include <bits/stdc++.h> |
| 10 | + |
| 11 | +using namespace std; |
| 12 | + |
| 13 | +vector<string> split_string(string); |
| 14 | + |
| 15 | +// Complete the sockMerchant function below. |
| 16 | +int sockMerchant(int n, vector<int> ar) { |
| 17 | + |
| 18 | + // * Initializing variables |
| 19 | + int socksCount[101] = {0}, totalPairs = 0; |
| 20 | + |
| 21 | + /* |
| 22 | + * For each color, increment the number of socks |
| 23 | + * for that color by 1 |
| 24 | + */ |
| 25 | + for(int a : ar) { |
| 26 | + socksCount[a]++; |
| 27 | + } |
| 28 | + |
| 29 | + /* |
| 30 | + * Counting the pair of socks for each color |
| 31 | + * and adding it to the total pairs |
| 32 | + */ |
| 33 | + for(int i=1; i<=100; i++) { |
| 34 | + totalPairs += socksCount[i]/2; |
| 35 | + } |
| 36 | + |
| 37 | + // * Returning the total pair of socks |
| 38 | + return totalPairs; |
| 39 | +} |
| 40 | + |
| 41 | +int main() |
| 42 | +{ |
| 43 | + ofstream fout(getenv("OUTPUT_PATH")); |
| 44 | + |
| 45 | + int n; |
| 46 | + cin >> n; |
| 47 | + cin.ignore(numeric_limits<streamsize>::max(), '\n'); |
| 48 | + |
| 49 | + string ar_temp_temp; |
| 50 | + getline(cin, ar_temp_temp); |
| 51 | + |
| 52 | + vector<string> ar_temp = split_string(ar_temp_temp); |
| 53 | + |
| 54 | + vector<int> ar(n); |
| 55 | + |
| 56 | + for (int i = 0; i < n; i++) { |
| 57 | + int ar_item = stoi(ar_temp[i]); |
| 58 | + |
| 59 | + ar[i] = ar_item; |
| 60 | + } |
| 61 | + |
| 62 | + int result = sockMerchant(n, ar); |
| 63 | + |
| 64 | + fout << result << "\n"; |
| 65 | + |
| 66 | + fout.close(); |
| 67 | + |
| 68 | + return 0; |
| 69 | +} |
| 70 | + |
| 71 | +vector<string> split_string(string input_string) { |
| 72 | + string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { |
| 73 | + return x == y and x == ' '; |
| 74 | + }); |
| 75 | + |
| 76 | + input_string.erase(new_end, input_string.end()); |
| 77 | + |
| 78 | + while (input_string[input_string.length() - 1] == ' ') { |
| 79 | + input_string.pop_back(); |
| 80 | + } |
| 81 | + |
| 82 | + vector<string> splits; |
| 83 | + char delimiter = ' '; |
| 84 | + |
| 85 | + size_t i = 0; |
| 86 | + size_t pos = input_string.find(delimiter); |
| 87 | + |
| 88 | + while (pos != string::npos) { |
| 89 | + splits.push_back(input_string.substr(i, pos - i)); |
| 90 | + |
| 91 | + i = pos + 1; |
| 92 | + pos = input_string.find(delimiter, i); |
| 93 | + } |
| 94 | + |
| 95 | + splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); |
| 96 | + |
| 97 | + return splits; |
| 98 | +} |
0 commit comments