forked from mouredev/retos-programacion-2023
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
31 additions
and
0 deletions.
There are no files selected for viewing
31 changes: 31 additions & 0 deletions
31
Retos/Reto #38 - LAS SUMAS [Media]/javascript/marcode24.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
/* | ||
* Crea una función que encuentre todas las combinaciones de los números | ||
* de una lista que suman el valor objetivo. | ||
* - La función recibirá una lista de números enteros positivos | ||
* y un valor objetivo. | ||
* - Para obtener las combinaciones sólo se puede usar | ||
* una vez cada elemento de la lista (pero pueden existir | ||
* elementos repetidos en ella). | ||
* - Ejemplo: Lista = [1, 5, 3, 2], Objetivo = 6 | ||
* Soluciones: [1, 5] y [1, 3, 2] (ambas combinaciones suman 6) | ||
* (Si no existen combinaciones, retornar una lista vacía) | ||
*/ | ||
|
||
const getCombinations = ({ values, target }) => { | ||
const combinations = []; | ||
const find = (index, sum, combination) => { | ||
if (sum === target) { | ||
combinations.push(combination); | ||
return; | ||
} | ||
if (sum > target || index >= values.length) { | ||
return; | ||
} | ||
find(index + 1, sum, combination); | ||
find(index + 1, sum + values[index], [...combination, values[index]]); | ||
}; | ||
find(0, 0, []); | ||
return combinations; | ||
}; | ||
|
||
// Visita mi repo en GitHub para ver y correr los tests de este código --> https://github.com/marcode24/weekly-challenges |