ptmdmusique

CLB_CodingChallenge_23_3_2018

Mar 23rd, 2018
343
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.46 KB | None | 0 0
  1. /*Problem description
  2.     Given a collection of number and sums, determine whether there is a pair of numbers that sums up to the given sum
  3.     Print out "True" or "False" as the result
  4. */
  5. #include <iostream>
  6. #include <vector>
  7. #include <fstream>
  8. using namespace std;
  9.  
  10. int main() {
  11. /*Test file name: in.txt
  12. Test file explain:
  13.     n m
  14.     i1 i2 i3 ... in
  15.     j1 j2 j3 ... jm
  16.    
  17. Where:
  18.     n               : number of numbers in the array
  19.     m               : number of "sum" we need to find
  20.     ik (1 <= k <= n): elements in the array
  21.     jk'(1 <= k'<= m): the sums we need to find
  22.  
  23. Sample:    
  24.     7 9
  25.     2 3 4 5 7 8 20
  26.     10 19 100 5 9 10 9 22 29
  27. */
  28.     //Read from file
  29.     ifstream inFile("in.txt");
  30.     int numOfItem = 0, findVal = 0, numToFind = 0;
  31.  
  32.     inFile >> numOfItem >> numToFind;   //Read in important values
  33.     vector<int> value(numOfItem);   //Create a container based on given size
  34.     //Read in array values
  35.     for (int indx = 0; indx < numOfItem; indx++) {
  36.         inFile >> value[indx];
  37.     }
  38.        
  39.     for (int indx = 0; indx < numToFind; indx++) {
  40.         inFile >> findVal;
  41.         bool found = false;
  42.         for (unsigned int lowIndx = 0, highIndx = value.size() - 1; lowIndx < highIndx;) {
  43.             int curVal = value[lowIndx] + value[highIndx];
  44.             if (curVal == findVal) {
  45.                 //Found :D
  46.                 found = true;
  47.                 break;
  48.             }
  49.             if (curVal > findVal) {
  50.                 //Too big
  51.                 highIndx--;
  52.             }
  53.             else {
  54.                 //Too small
  55.                 lowIndx++;
  56.             }
  57.         }
  58.  
  59.         //Output appropriately
  60.         cout << (found == true ? "True" : "False") << endl;
  61.     }
  62.  
  63.     return 0;
  64. }
Add Comment
Please, Sign In to add comment