Skip to content

Instantly share code, notes, and snippets.

@hamannjames
Last active July 26, 2017 22:16
Show Gist options
  • Save hamannjames/d477771ff0b41681584e3937aa51171b to your computer and use it in GitHub Desktop.
Save hamannjames/d477771ff0b41681584e3937aa51171b to your computer and use it in GitHub Desktop.
Given a set of possibilities, determine the maximum reward in the possibilities given a certain constraint.
/*
For this particular example the constraint is you cannot take two possibilities
that are next to each other. A real world example might be that you cannot invest multiple months
in a row and want to have the best chance at the best ROI. Kind of dumb but the point is
if there are constraints you want to track the best possible values for every sequence of moves,
only keeping track of the best possible outcomes
*/
const bestOutcome = (arr) => {
// We want arr to be an array of possibilities
if (!Array.isArray(arr) || arr.length === 0) {
console.log('Argument is not array or array is empty');
return;
}
/*
We want to take care of a few important conditions here. We don't want to run an expensive
iterative function if we don't have to, so if arr is only 1 or 2 indices long we know exactly
what value we want
*/
const length = arr.length;
let nodeArr = []; // We will map out the indices of the possibilities array we choose to take.
let totalsArr = []; // We calculate our totals here, allowing us to only pass through the possiblities array once.
let i;
if (arr.length === 1) {
totalsArr[0] = arr[0];
nodeArr[0] = 0;
}
if (arr.length === 2) {
totalsArr[0] = Math.max(arr[0], arr[1]);
nodeArr[0] = (arr[0] > arr[1]) ? 0 : 1;
}
totalsArr[0] = arr[0];
totalsArr[1] = arr[1];
let evenTrack;
let lastTaken = true;
for (i = 2; i < length; i++) {
totalsArr[i] = Math.max((arr[i] + totalsArr[i-2]), totalsArr[i -1]);
takeThis = (arr[i] + totalsArr[i-2] > totalsArr[i-1]);
if (takeThis) {
evenTrack = isEven(i);
if (evenTrack) {
if (evenTrack === lastTaken) {
nodeArr.push('e');
}
else {
nodeArr.pop();
nodeArr.push('s', i);
lastTaken = evenTrack;
}
}
else {
if (evenTrack === lastTaken) {
nodeArr.push('o');
}
else {
nodeArr.pop();
nodeArr.push('s', i);
lastTaken = evenTrack;
}
}
}
}
return [nodeArr, totalsArr, Math.max(totalsArr[length-1], totalsArr[length-2])];
}
const isEven = (a) => a % 2 === 0;
@hamannjames
Copy link
Author

hamannjames commented Jul 26, 2017

Work in progress, trying to get the node array to come out right. Right now I am getting the indexes of where the program decided to switch tracks, which is progress

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment