I was (yet again!) inspired by a previous question to post some code to solve the same problem. In this case, the problem in question is the Anagram challenge on HackerRank. The basic idea is that you're given some number of lines of input. Each line of input represents two strings (with no delimiter between them), each being as close to half the length of the line as possible (and if it's odd, the first is the shorter of the two, not that it matters much).
You're to find how many characters in the first need to be changed to make it an anagram of the second (or -1 if they can't be made anagrams of each other). For each line of input (other than the number specifying the length) you're to produce one line of output containing that number).
My code for this was as follows:
#include <iostream>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>
int anagram_check(std::string &line) {
// If the length is odd, they can't be anagrams
if (line.length() % 2 != 0)
return -1;
size_t len = line.length() / 2;
auto mid = line.begin() + len;
// sort each half
std::sort(line.begin(), mid);
std::sort(mid, line.end());
// find number of characters that are different:
std::string diffs;
std::set_difference(line.begin(), mid, mid, line.end(), std::back_inserter(diffs));
return diffs.size();
}
int main() {
int num;
// Read number of test cases:
std::cin >> num;
// Clear remainder of line from input buffer:
std::string ignore;
std::getline(std::cin, ignore);
std::string line;
for (int i = 0; i < num; i++) {
std::getline(std::cin, line);
std::cout << anagram_check(line) << "\n";
}
}