Skip to content

Instantly share code, notes, and snippets.

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 craigmichaelmartin/a9820ffd6cde7a977ff9 to your computer and use it in GitHub Desktop.
Save craigmichaelmartin/a9820ffd6cde7a977ff9 to your computer and use it in GitHub Desktop.
Any z number of integers in an array add to some value.
/*
* In javascript: Write a function that, given an array of integers (x),
* and an integer (y), returns true if any two of the integers in x add up to y.
* (Optional) Now, write a function that, given the above arguments and an
* additional integer (z), returns true if any z of the integers in x add up to y.
*/
/*
* Some notes on my solution:
* This approach is assuming ES6 support for tail recursion.
* It could be optimized if the use case warranted it, eg:
* Unique-ify the array down to z elements;
* Sort the array first and slice the array to the AddToValue at the top end,
* or AddToValue minus largest element in array at the bottom end;
* Look to take shortcuts like add the z largest values
* and seeing if they even equal the AddToValue,
* or likewise add the z smallest values to
* see if they are larger than the AddToValue
*/
// Returns true if any z numbers in an array add to a value
var anyZIntegersAddToValue = (function() {
// Adds two numbers
var addTwo = function(a,b) {
return a + b;
};
// Returns true if first z indexes plus roving index
// (minus roving index's orginal place) add to value.
var situatedWithOneVariableIndexEqualValue = function(arr, value, z, residentIndex, index) {
index = index || z;
if (index >= arr.length) {return false;}
if (arr.slice(0, z).reduce(addTwo,0) - arr[residentIndex] + arr[index] === value) {return true;}
return situatedWithOneVariableIndexEqualValue(arr, value, z, residentIndex, index+1);
};
// Returns true if any of the first z indexes sequentially
// roving through an array add to a value
var firstZIndexesIterativelyRovingEqualValue = function(arr, value, z, variableIndex) {
variableIndex = variableIndex || 0;
if (variableIndex === z) {return false;}
if (arr.slice(0, z).reduce(addTwo,0) === value) {return true;}
return situatedWithOneVariableIndexEqualValue(arr, value, z, variableIndex)
|| firstZIndexesIterativelyRovingEqualValue(arr, value, z, variableIndex+1);
};
// Returns true if any z numbers in an array add to a value
return function anyZIntegersAddToValue(arr, value, z) {
if (arr.length === 0 || z <= 0 || z > arr.length) {return false;}
return firstZIndexesIterativelyRovingEqualValue(arr, value, z)
|| anyZIntegersAddToValue(arr.slice(1), value, z);
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment