Created
October 7, 2023 20:42
-
-
Save fj1/3ab850abfff3da5d3761f21bf2864bb4 to your computer and use it in GitHub Desktop.
Cassidoo #320
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
/** | |
* https://buttondown.email/cassidoo/archive/perseverance-is-failing-19-times-and-succeeding/ | |
* | |
* Given two integers source and target, | |
* add operators in the source number to make it equal target, if possible. | |
* You can return just one, or all possibilities for this! | |
* | |
* Example: | |
* > addOperators(123, 6) | |
* > ["1*2*3", "1+2+3"] | |
* | |
* > addOperators(3456237490, 9191) | |
* > [] // none possible | |
*/ | |
var addOperators = function (source, target) { | |
if (source === target) { | |
return 'The source and target values are equal.' | |
} | |
// split the source into individual pieces, | |
// then find the sum total for all the individual integers within source | |
var sourceStringArray = source.toString().split(""); | |
var sourceAdditionTotal = sourceStringArray.reduce(function (acc, curr) { return acc + Number(curr); }, 0); | |
// find the multiplication total for all the individual integers within source | |
var sourceMultiplicationTotal = sourceStringArray.reduce(function (acc, curr) { return acc * Number(curr); }, 1); | |
var result = []; | |
if (sourceAdditionTotal === target) { | |
result.push(sourceStringArray.join('+')); | |
} | |
if (sourceMultiplicationTotal === target) { | |
result.push(sourceStringArray.join("*")); | |
} | |
return result; | |
}; | |
console.log(addOperators(123, 6)); // [ '1+2+3', '1*2*3' ] | |
console.log(addOperators(3456237490, 9191)); // [] | |
console.log(addOperators(1, 9)); // [] | |
console.log(addOperators(0, 0)); // The source and target values are equal. | |
console.log(addOperators(123, -6)); // [] | |
console.log(addOperators(234, 24)); // [ '2*3*4' ] | |
console.log(addOperators(234, 9)); // [ '2+3+4' ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment