Created
January 10, 2012 03:14
-
-
Save zmaril/1586654 to your computer and use it in GitHub Desktop.
isMeasureable
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
//Increase the list by one and does carry over between digits. | |
var increaseByOne = function(listOfWeights){ | |
var newList = listOfWeights; | |
newList[newList.length-1] += 1; | |
for(var i = listOfWeights.length-1; i>0; i--){ | |
var newWeight= listOfWeights[i]; | |
if(newWeight==2){ | |
newWeight=-1; | |
newList[i-1]+= 1; | |
} | |
newList[i]=newWeight; | |
} | |
if(newList[0]==2) | |
newList[0]=-1; | |
return newList; | |
}; | |
//Testing to see if two arrays are equal. | |
var equalArraysTest = function(a,b){ | |
if(a.length != b.length) | |
return false; | |
for(var i = 0; i<a.length; i++){ | |
if(a[i] != b[i]){ | |
return false; | |
} | |
} | |
return true; | |
}; | |
// Takes in a target and a set of weights and goes through to check if any possible combination works. | |
var isMeasureable = function(target, weights){ | |
var testEqual = function(secondWeights){ | |
var sum = 0; | |
for(var i = 0; i < weights.length; i++ ){ | |
sum += weights[i]*secondWeights[i]; | |
} | |
return target==sum; | |
}; | |
//Simple test case | |
if(target ==0){ | |
return true; | |
} | |
//Set up weighting to be a list of -1's. | |
var weighting = new Array(weights.length); | |
var startingOut= new Array(weights.length); | |
for(var j = 0; j< weights.length; j++){ | |
weighting[j]= -1; | |
startingOut[j] =-1; | |
} | |
//While loop boolean | |
var finished = false; | |
var possible = false; | |
//While loop to do the testing and check whether we are done yet. | |
while(!finished){ | |
if(testEqual(weighting)){ | |
possible=true; | |
} | |
weighting= increaseByOne(weighting); | |
if(equalArraysTest(startingOut,weighting) || possible){ | |
finished=true; | |
} | |
} | |
return possible; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment