1

I want to find x number exist inside given below array or not. For finding x number inside, any element of the array can make given x number. This is based on the element's have an inside array and check it exist or not. It's not like promotion and combination.

let arrr = [
    4,
    7,
    6,
    2,
    7,
    6
];
  • Example : If X=16 then result should be [4,6,6] = 16 (true)
  • Example : If X=11 then result should be [4,7] = 11 (true)
  • Example : If X=18 then result should be [4,6,6,2] = 18 (true)
Chandan Kumar
  • 799
  • 7
  • 23
  • For `X = 16` you can have next results that both meet the condition: `[7,7,2]` or `[4,6,6]`, is there any reason you prefer `[4,6,6]` or any of the results is ok? Also, have you tried something? In that case, please add it to the question. – Shidersz May 27 '19 at 02:57
  • Yes -> Any of the results are ok. I tried but not working ```for(let i=0; i temp) { console.log("match", temp) } } }``` – Chandan Kumar May 27 '19 at 02:59
  • Also, I want to know the best approach to achieve a given algorithm – Chandan Kumar May 27 '19 at 03:00
  • 1
    https://en.wikipedia.org/wiki/Subset_sum_problem – user3386109 May 27 '19 at 04:30
  • @PhamTrung Question is not duplicate, the given URL is more abt combination of coins, mine is checking sum of number exist inside an array or not. – Chandan Kumar May 27 '19 at 05:31
  • 2
    Your question is a simpler version of the other. Just a simple modification and your problem is solved. – Pham Trung May 27 '19 at 05:36

1 Answers1

1

It's not optimized but it works:

    function Contains(array, value) {
        const str = array.reduce((p, c) => p + c.toString(), "");
        const fn = function (active, rest, a) {
            const sum = rest.split("").reduce((p, c) => p + Number(c), 0);
            if (sum === value) return true;
            if (!active && !rest) return;
            if (!rest) {
                a.push(active);
            } else {
                if (fn(active + rest[0], rest.slice(1), a) === true) return true;
                if (fn(active, rest.slice(1), a) === true) return true;
            }
            return a;
        }
        const result = fn("", str, []) === true;
        return result === true;
    }
    Contains(array, value)
Ziv Ben-Or
  • 1,149
  • 6
  • 15