A
A
Alexey2017-11-10 11:58:40
JavaScript
Alexey, 2017-11-10 11:58:40

How to check all possible options?

Good afternoon,
There are columns that can expand, but I think no more than five.
The lines will keep growing.
The values ​​will always be different.
For example:
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Each line must be compared with the result (let's say: "count"), but in a special way.
I want the program to take into account all possible options.
For example, first compare each column with "score",
then columns 1 2, 1 3, 1 4, 1 5, 1 6, 1 7, 1 8, 1 9, 1 10 with "score"
2 1, 2 3, 2 4 , 2 5, 2 6, 2 7, 2 8, 2 9, 2 10 with "count"
...
1 2 3, 1 2 4, 1 2 5, 1 2 6, 1 2 7, 1 2 8, 1 2 9, 1 2 10 with "count"
1 3 2, 1 3 4, 1 3 5, 1 3 6, 1 3 7, 1 3 8, 1 3 9,
and so on up to
1 2 3 4 5 6 7 8 9 10 with "count"
Each possible option, I then have to save the result of the comparison, For example (true / false)
Next, the result of all possible options for each line, I want to compare and catch the best option , suitable for the result "score"
In order to put one of the most effective conditions for these columns)
So, the essence of the question, advise how can I automatically check all possible combinations of checks?
(manually do with the help of many constructions if ((1) && (2) && (3) === count) all possible options, an extremely thankless job. I can’t think of an algorithm how best to use loops ((
For anyone, there is a simpler elegant way to check with fewer lines of code, but I can’t figure out how)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2017-11-10
@sergiks

It seems that such a simple algorithm will suit you: iterate over all numbers in binary notation from 1 to 2 n , and take those elements of the string that correspond to 1.
I outlined a function that selects a combination from these elements that gives the closest sum to the given one:

function nearest(arr, total) {
  var len = arr.length
    , i
    , bit
    , sum
    , n = Math.pow(2, len)
    , currDist
    , index = undefined
    , dist = undefined
    , result = []
  ;
  
  for( i = 1; i < n; i++) {
    sum = 0;
    for( bit = 0; bit < len; bit++) {
      if( i & (1 << bit)) sum += arr[bit];
    }
    
    currDist = Math.abs(total - sum);
    if( typeof dist === 'undefined' || dist > currDist) {
      index = i;
      dist = currDist;
      if( dist === 0) break;
    }
  }
  
  for(bit = 0; bit < len; bit++) {
    if( index & (1 << bit)) result.push(arr[bit]);
  }
  
  return result;  
}

nearest([1,3,4,6,8], 12) // [1,3,8]
nearest([1,2,4,6,8], 12) // [2,4,6]
nearest([7,9,13,19,28], 12) // [13] dist = 1
nearest([7,9,13,19,28], 28) // [9,19] не [28] т.к. останавливается на первом найденном варианте

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question