Created
February 14, 2018 12:51
-
-
Save ranafarhanakram/0da01e9387bdff1ffb39fcebb2625f8d to your computer and use it in GitHub Desktop.
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
var input = [[1, 3], [9,10], [13, 15]]; //input array | |
try { | |
// Iterate through array and complete series, i.e [1, 5] would generate [1, 5, 3, 4, 2] | |
input.forEach(tuple => { | |
if(tuple.length && tuple[0] != tuple[1]){ | |
// making sure the code works even when the tuple is not sorted. | |
var minimumValue = tuple[0] < tuple[1] ? tuple[0] : tuple[1]; | |
var maximumValue = tuple[0] > tuple[1] ? tuple[0] : tuple[1]; | |
// completing series by looping from first tuple - last tuple | |
while(minimumValue < maximumValue && (maximumValue - minimumValue != 1)){ | |
tuple.push(++ minimumValue); | |
} | |
}else{ | |
//If empty or same, throw an exception | |
throw "empty tuple found or duplicate values in tuple."; | |
} | |
}); | |
// Input array with completed series i.e [1, 3, 2], [9, 10], [13, 15, 14] | |
console.log(input); | |
var stringifiedResult = getCombinations(input, ''); | |
var finalResult = []; | |
// Converting conncatinated string to arrays | |
stringifiedResult.forEach(tuple => { | |
finalResult.push(tuple.split(",")); | |
}); | |
console.log(finalResult); | |
}catch(err) { | |
console.log(err); | |
} | |
function getCombinations(array, prefix) { | |
prefix = prefix || ''; | |
if (!array.length) { | |
return prefix; | |
} | |
//Iterate through each element and concatinate while iterating through every array from input array recursively. | |
var result = array[0].reduce((result, value) => { | |
return result.concat(getCombinations(array.slice(1), prefix ? prefix + ',' + value : prefix + value)); | |
}, []); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment