gpt-3.5-turbo-0301· openai
Suzhen/CodeChat
write a c++ function to convert each array in a 2d array of integers into a hashmaps…
- User
write a c++ function to convert each array in a 2d array of integers into a hashmaps with the values of the arrays as keys and set of the indexes of the keys in the array as the value of each key. for example, convert [[1,2,5,3],[9,3,3,9]] into [{1:{0}, 2:{1}, 3: {3}, 5: {2}},{3: {1,2},9:{0,3}}]
- Assistant
#include <iostream> #include <unordered_map> #include <vector> using namespace std; vector<unordered_map<int, vector<int>>> convertToHashMap(vector<vector<int>> arr) { int rows = arr.size(); int cols = arr[0].size(); vector<unordered_map<int, vector<int>>> hashMap(rows, unordered_map<int, vector<int>>()); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { int key = arr[i][j]; if (hashMap[i].find(key) == hashMap[i].end()) { // Key not found, create new vector and add index vector<int> indexes{ j }; hashMap[i][key] = indexes; } else { // Key already exists, add index to existing vector hashMap[i][key].push_back(j); } } } return hashMap; } void printHashMap(vector<unordered_map<int, vector<int>>> hashMap){ int rows = hashMap.size(); int cols = hashMap[0].size(); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { unordered_map<int, vector<int>> map = hashMap[i]; int key = j+1; if (map.find(key) != map.end()) { cout << key << ": {"; for (auto index : map[key]) { cout << index << ","; } cout << "}, "; } } cout << endl; } } int main() { vector<vector<int>> arr{{1,2,5,3},{9,3,3,9}}; vector<unordered_map<int, vector<int>>> hashMap = convertToHashMap(arr); printHashMap(hashMap); return 0; }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.