Skip to content

Instantly share code, notes, and snippets.

@fj1
Created October 7, 2023 20:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fj1/3ab850abfff3da5d3761f21bf2864bb4 to your computer and use it in GitHub Desktop.
Save fj1/3ab850abfff3da5d3761f21bf2864bb4 to your computer and use it in GitHub Desktop.
Cassidoo #320
/**
* 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