From a vector of float numbers
std::vector<float> v { 0.32, 0.0004, 12.78, -9.2, 1.1 };
I am trying to find out what series of "+" and "-" one can place in front of each float number to get a result that is as close as possible as the value GOAL
. Note that no number can be left out (all values must be used).
float GOAL = 4.9;
For this example, I think the best possible solution is
+ 0.32 - 0.0004 + 12.78 + (-9.2) + 1.1 = 4.9996
Let true
mean "+" and false
mean "-", the best possible solution could be represented as
std::vector<bool> solution { true, false, true, true, true }
One could just iterate through all possible combinations. If n
is the size of v
, then there are 2^n possible combinations. As n
grows large, the process becomes quickly very slow (2^1000 ≈ 10^301).
How could I go about writing a search algorithm that would output not the best but a descent solution in polynomial time?
FYI, I have only basic understanding of search algorithms. I understand the concepts of heuristic, greedy algorithm, hill climbing, search tree, minimax game tree and others for examples.