Advertisement
VergeoPaw

Vergeo Valentino Gunawan 9.A - HackerRank (Simple Array Sum)

Mar 3rd, 2021
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.66 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. vector<string> split_string(string);
  6.  
  7. /*
  8.  * Complete the simpleArraySum function below.
  9.  */
  10. int simpleArraySum(vector<int> ar, int n) {
  11.     int sums = 0;
  12.     for (int count = 0; count < n; count++) {
  13.         sums = sums + ar[count];
  14.     }
  15.     return sums;
  16.  
  17. }
  18.  
  19. int main()
  20. {
  21.     ofstream fout(getenv("OUTPUT_PATH"));
  22.  
  23.     int ar_count;
  24.     cin >> ar_count;
  25.     cin.ignore(numeric_limits<streamsize>::max(), '\n');
  26.  
  27.     string ar_temp_temp;
  28.     getline(cin, ar_temp_temp);
  29.  
  30.     vector<string> ar_temp = split_string(ar_temp_temp);
  31.  
  32.     vector<int> ar(ar_count);
  33.  
  34.     for (int ar_itr = 0; ar_itr < ar_count; ar_itr++) {
  35.         int ar_item = stoi(ar_temp[ar_itr]);
  36.  
  37.         ar[ar_itr] = ar_item;
  38.     }
  39.  
  40.     int result = simpleArraySum(ar,ar_count);
  41.  
  42.     fout << result << "\n";
  43.  
  44.     fout.close();
  45.  
  46.     return 0;
  47. }
  48.  
  49. vector<string> split_string(string input_string) {
  50.     string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) {
  51.         return x == y and x == ' ';
  52.     });
  53.  
  54.     input_string.erase(new_end, input_string.end());
  55.  
  56.     while (input_string[input_string.length() - 1] == ' ') {
  57.         input_string.pop_back();
  58.     }
  59.  
  60.     vector<string> splits;
  61.     char delimiter = ' ';
  62.  
  63.     size_t i = 0;
  64.     size_t pos = input_string.find(delimiter);
  65.  
  66.     while (pos != string::npos) {
  67.         splits.push_back(input_string.substr(i, pos - i));
  68.  
  69.         i = pos + 1;
  70.         pos = input_string.find(delimiter, i);
  71.     }
  72.  
  73.     splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));
  74.  
  75.     return splits;
  76. }
  77.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement