I have an unordered set of digits and a set of weights, I want to match the digits to the weights in such a way that the weighted sum is a given number. Now I do it so that I put these digits into some first arrangement and check the weighted sum, then I swap the first digit with the second, if the weighted sum is closer to the expected one, then I leave it, if I don’t undo it. Then I check all the numbers one by one.
How do you find these numbers faster? There are many such comparisons, and sometimes the weighted sum of numbers resulting from a given arrangement of digits differs by 1 from the expected one and to correct it you have to change places by more than 2 digits, so my algorithm does not work, then I draw a new arrangement of digits and do everything again , the problem is that here a lot depends on the draw, if the new initial setting is favorable, the number will be found quickly, and if not, there may be a lot of such draws.
Can me use artificial intelligence or a neural network or something?
2
Answers
I know you tagged your answer C#, but I did not feel like opening visual studio and python should help you grasp it just as well.
I have simply done what I suggested in my comments: Run a brute-force algorithm:
And when I run it with six weights, it is quick enough for me not having to wait:
So I say just stick with the simple approach of brute-forcing it.
When I run it with nine numbers and nine weights, it takes about 2seconds though. So this approach really depends on the number of numbers you have.
An approach to solve this problem is to use a hybrid solution of gradient descent and a genetic algorithm.
Here I am starting with a ordered set of factors (
double[][]
) and filtering those so that I keep the bestweights.Length
. I then generate from those best solutions so far a set of mutations where I swap one element from each position with a randomly chosen position in the array. So if I start with a singledouble[]
of length 24 then I end up with 24double[]
arrays of length 24 where each array differs by having two elements of each array swapped. This creates a larger number of guesses and I then loop doing this process until one solution is within adelta
that is acceptably close to the answer.The figure I’ve used for
goal
is the minimum possible weighted average. In this example the code effectively has to reverse the order of the originalfactors
array. It does that in 0.019 seconds on my pc.