From 6c44a50650527ba85c1dc90a78134dcb75d8cb7a Mon Sep 17 00:00:00 2001 From: Ricardo Hernandez Date: Thu, 28 Sep 2023 17:41:04 -0600 Subject: [PATCH] Reto #38 - JavaScript --- .../javascript/ricardo-fdz.js | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Retos/Reto #38 - LAS SUMAS [Media]/javascript/ricardo-fdz.js diff --git a/Retos/Reto #38 - LAS SUMAS [Media]/javascript/ricardo-fdz.js b/Retos/Reto #38 - LAS SUMAS [Media]/javascript/ricardo-fdz.js new file mode 100644 index 0000000000..e676d718ed --- /dev/null +++ b/Retos/Reto #38 - LAS SUMAS [Media]/javascript/ricardo-fdz.js @@ -0,0 +1,41 @@ + +const convertToBinary = (num)=>{ + let binary = [] + while (num!==0){ + let remainder = parseInt(num%2) + num = Math.floor(num/2); + binary.push(remainder); + } + return binary +} + +const getSumsArray=(array, target )=>{ + let sumsArray = []; + const combinations = Math.pow(2,array.length); + console.log(combinations); + for (var i = 1; i < combinations; i++) { + let positions = convertToBinary(i); + positions = positions.map((pos,index)=>pos!==0? index:null) + positions = positions.filter(pos=>pos !== null) + let currentSum = 0; + let curreSumArray= []; + positions.forEach(pos=>{ + currentSum += array[pos]; + curreSumArray.push(array[pos]); + }) + if(currentSum===target){ + sumsArray.push(curreSumArray) + } + } + return sumsArray +} + +let res = getSumsArray([1, 5, 3, 2,1],7); +console.log(res); + + + + + + +