A
A
Alexey2017-11-16 08:22:49
JavaScript
Alexey, 2017-11-16 08:22:49

How to correct the cycle?

It is necessary to save all possible combinations with variables, for example:
There is a, b , c
It should turn out like this
combo 1: a arr[0] = [a]
combo 2: b arr[1] = [b]
combo 3: c arr[2 ] = [c]
combo 4: ab arr[3] = [a, b]
combo 5: ac arr[4] = [a, c]
combo 6: bc arr[5] = [b, c]
combo 7: abc arr[6] = [a, b, c]

function nearest(arr) {

var len = arr.length
    , i
    , bit
    , n = Math.pow(2, len)
    , result = []
  ;

for( i = 1; i < n; i++) {
        
        for( bit = 0; bit < len; bit++) {
            if( i & (1 << bit)) {
                result.push(arr[bit]);
            }
        }
}

It’s hard for me to understand how this code works)
Now this cycle simply writes down all possible combinations in a row. I can’t figure out how to make them split into unique arrays?)
arr[0] [a]
arr[1] [b]
arr[2] [c]
arr[3] [a, b]
arr[4 ] [a, c]
arr[5] [b, c]
arr[6] [a, b, c]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stalker_RED, 2017-11-16
@Evelate

Create a subarray in the outer loop, fill it in the inner loop, then add it to result.
https://jsfiddle.net/mh0tq8hd/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question