JSFiddle - React, Tailwind, and code Playground
by nate
JavaScript
Array.prototype.compare = function (array) {
// if the other array is a falsy value, return
if (!array)
return false;
// compare lengths - can save a lot of time
if (this.length != array.length)
return false;
for (var i = 0, l=this.length; i < l; i++) {
// Check if we have nested arrays
if (this[i] instanceof Array && array[i] instanceof Array) {
// recurse into the nested arrays
if (!this[i].compare(array[i]))
return false;
}
else if (this[i] != array[i]) {
// Warning - two different object instances will never be equal: {x:20} != {x:20}
return false;
}
}
return true;
}
Array.prototype.shuffle = function() {
var i = this.length, j, temp;
if ( i == 0 ) return this;
while ( --i ) {
j = Math.floor( Math.random() * ( i + 1 ) );
temp = this[i];
this[i] = this[j];
this[j] = temp;
}
return this;
}
function sum(arr) {
var total = 0;
for (var i = 0, length = arr.length; i < length; i += 1) {
total += arr[i];
}
return total;
}
function factorial(num) {
var total = 1;
for (var i = num; i > 0; i -= 1) {
total *= i;
}
return total;
}
function ArrayAddition(arr) {
// code goes here
var sortedArray = arr.sort();
var largestNumber = sortedArray[sortedArray.length - 1];
sortedArray.pop();
var totalCombinations = factorial(sortedArray.length);
console.log(totalCombinations);
var testedCombinations = [];
function testCombination() {
var newCombination = sortedArray.shuffle();
for (var i = 0, length = testedCombinations.length; i < length; i += 1) {
if (testedCombinations[i].compare(newCombination)) {
return testCombination();
}
}
testedCombinations.push(newCombination);
if (sum(sortedArray) === largestNumber) {
return true;
} else {
if (testedCombinations.length <...