jeudi 20 février 2020

Linear Search on Vector

I have tests to pass online using my created methods. I have a feeling there is an issue with one of the tests. The final one i cannot pass. Here is the test-

TEST_CASE ("Linear Search With Self-Organization 3") {
  int searchKey = 191;

  vector<int> searchArray(500);
  for (int i = 0; i < 500; i++) {
    searchArray[i] = i + 1;
  }
  random_shuffle(searchArray.begin(), searchArray.end());

  bool result, result2;
  result = linearSearchSO(searchArray, searchKey);
  int searchKey2 = 243;
  result2 = linearSearchSO(searchArray, searchKey2);

  REQUIRE (result == true);
  REQUIRE (result2 == true);
  REQUIRE (verifySearchArray(searchArray) == true);
  REQUIRE (searchArray[0] == searchKey2);
  REQUIRE (searchArray[1] == searchKey);
  REQUIRE (searchArray.size() == 500);
}

The method in question here is linearSearchSO.

bool linearSearchSO(vector<int> & inputArr, int searchKey) {
   printArray(inputArr);
   for(int i=0; i < inputArr.size(); i++) {
      int temp = inputArr[0];
      if (inputArr[i] == searchKey) {
         inputArr[0] = inputArr[i];
         inputArr[i] = temp;
         printArray(inputArr);
         return true;
      }
   }
   return false; 
}

Worth noting that this method has passed all 3 of the other tests required. As you can see in the test, my tutor has called this method twice passing two different values.The idea is that there is a vector of 500 numbers.. In this instance he randomises the numbers. The best way for me to explain what is happening is that if he didn't randomise and the numbers were simply listed 1-500. The method gets called and I begin with the requested number 191, I move this to front of the vector. Now it reads 191, 2, 3, 4 etc. 190, 1, 192 etc. So he then calls the method again, and wants 243 to be moved to the front. His test wants the result to be 243, 191, 2, 3, 4. However what my code does is swap 191 to 243's position. My result now reads 243, 2, 3, 4 etc. 242, 191, 244, 245 etc.

Every other test is simply taking one number and moving it to the front, the test then checks that each number is in the correct position. My question is, is there a way for me to achieve 243, 191, 2, 3.. without messing up every other test I've passed only using this one linearSearch function? or is there a problem with the test, and hes simply made a mistake.

EDIT- The actual question asked for this test. Question 4 A self-organising search algorithm is one that rearranges items in a collection such that those items that are searched frequently are likely to be found sooner in the search. Modify the learning algorithm for linear search such that every time an item is found in the array, that item is exchanged with the item at the beginning of the array.

Aucun commentaire:

Enregistrer un commentaire