Last active
October 27, 2016 11:05
-
-
Save kundzi/d5208458fd0370dd9f39a1ece512fa4f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // bac cab cba | |
| bool isAnagram(string str1, string str2) { | |
| if (str1.empty() && str2.empty()) return true; | |
| if (str1.size() != str2.size()) return false; | |
| sort(str1.begin(), str1.end()); | |
| sort(str2.begin(), str2.end()); | |
| return str1 == str2; | |
| } | |
| EXPECT_EQ(isAnagram("",""), true) | |
| EXPECT_EQ(isAnagram("aa",""), false) | |
| EXPECT_EQ(isAnagram("aa","aaa"), false) | |
| EXPECT_EQ(isAnagram("bac","abc"), true) | |
| EXPECT_EQ(isAnagram("bac","abd"), true) | |
| // 2 threds | |
| int findMax(vector<int> v) { | |
| auto itStart1 = v.begin(); | |
| auto itEnd1 = itStart1 + (v.size() >> 1); | |
| auto itStart2 = itEnd1; | |
| auto itEnd2 = v.end(); | |
| int result2; | |
| thread t([&result2, &itStart1, &itStart2](){ | |
| resul2 = *max_element(itStart2, itEnd2); | |
| }); | |
| auto result1 = *max_element(itStart1, itEnd2); | |
| t.join(); | |
| return max(result1, result2); | |
| } | |
| // multiple threads | |
| int findMax(vector<int> v) { | |
| const size_t concurency = 16; | |
| const size_t cuncurencySizeMin = concurency*1000; | |
| if (v.size() < cuncurencySizeMin) | |
| return *max_element(v.begin(), v.end()); | |
| vector<thread> threads(concurency-1); | |
| vector<int> result(concurency); | |
| size_t batchSize = v.size() / concurency; | |
| auto itBatchStart = v.begin(); | |
| auto itBatchEnd = itBatchStart + batchSize; | |
| for (size_t threadNum = 0; threadNum < concurency-1; ++threadNum, itBatchEnd) { | |
| int *resultLocal = &result[threadNum]; | |
| threads[threadNum] = thread([resultLocal, itBatchStart, itBatchEnd](){ | |
| result = *max_element(itBatchStart, itBatchEnd); | |
| }); | |
| itBatchStart = itBatchEnd; | |
| itBatchEnd = (itBatchStart == v.end()) ? itBatchStart + batchSize : itBatchStart; | |
| } | |
| result[results.size() - 1] = *max_element(v.begin() + batchSize*(concurency-1), v.end()); | |
| for(auto &th: t) th.join(); | |
| return *max_element(result.begin(), result.end()); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment