Created
January 27, 2015 05:37
-
-
Save abdulapopoola/fe8acc93066fc99b054a to your computer and use it in GitHub Desktop.
PowerSet of a set in 16 lines of JavaScript
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
function powerSet(s) { | |
if(s.length === 0){ | |
return [[]]; | |
} | |
var headOfList = s.splice(0,1)[0]; | |
var powerSetOfListTail = powerSet(s); | |
var powerSetOfListTailWithHead = powerSetOfListTail.map(function(p) { | |
var cpy = p.slice(); | |
cpy.push(headOfList); | |
return cpy; | |
}); | |
return powerSetOfListTail.concat(powerSetOfListTailWithHead); | |
} | |
powerSet([1,2,3]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment