Home > Enterprise >  Make a function that autodetects when unique
Make a function that autodetects when unique

Time:12-16

I need to have a function in c that gets an element from a vector of strings as soon as the input is unique.

For example, my vector contains {"DELETE", "HELP", "GO FORWARD", "GO BACKWARDS"}.

If my input is then "H", the function should output "HELP" If the input is "H 55", it should ignore the 55 and still output "HELP".

However, when I add a new element "HELLO" to my vector, it should return "NOT UNIQUE".

I already tried a bunch of things, but I am not really getting anywhere.

I think a 2 dimensional vector would be a possible solution, but I have not been able to make it work:

["DELETE", "D"]
["DELETE", "DE"]
["DELETE", "DEL"]
["DELETE", "DELE"]
["DELETE", "DELET"]
["DELETE", "DELETE"]
["HELP", "HELP"]
["HELLO", "HELL"]
["HELLO", "HELLO"]
...

CodePudding user response:

Make a function that autodetects when unique

One possible way of doing this is as shown below:

#include <iostream>
#include <vector>
#include <string>
std::string checkUnique(const std::string& searchString, const std::vector<std::string>& inputVector)
{
    int count = 0;
    std::string foundString;
    for(const std::string &element: inputVector)
    {
        if(element.at(0) == searchString.at(0))
        {
            foundString = element;
              count; //increment count
        }
    }
    if(count == 0)
    {
        return "NOT FOUND";
    }
    else if(count == 1)
    {
        return foundString;
    }
    else 
    {
        return "NOT UNIQUE";
    }
}
int main()
{
  
    std::vector<std::string> inputVector{"DELETE", "HELP", "GO FORWARD", "GO BACKWARDS"};
    
    std::string searchString = "H";
    
    //call the function for different cases 
    
    std::cout << checkUnique(searchString, inputVector) <<std::endl;;//prints HELP
    
    std::cout << checkUnique("H", inputVector) << std::endl;  //prints HELP
    
    std::cout << checkUnique("H 55", inputVector) << std::endl; //prints HELP 
    
    //add "HELLO" into the vector 
    inputVector.push_back("HELLO");
    
    std::cout << checkUnique("H", inputVector) << std::endl;  //prints NOT UNIQUE 

    std::cout << checkUnique("H 55", inputVector) << std::endl;  //prints NOT UNIQUE
    return 0;
}

The output of the program can be seen here.

  • Related