Power Set

by Andrew Poes

CSS

.print {
    position: relative;
    display: inline-block;
    background-color: black;
    color: white;
    font-family: Helvetica, Helvetica-Neue, sans-serif;
    font-weight: bold;
    font-size: 24px;
    letter-spacing: -1.5px;
    padding: 4px 8px;
}

body {
    background-color: #eeeeee;
}
}

JavaScript

$(document).ready(function() {
    var dict = {}
	var perms = perm("123")
    for (var i = 0; i < perms.length; ++i) {
        var str = perms[i]
        var set = powerSet(str)
        for (var j = 0; j < set.length; ++j) {
            var s = set[j]
            dict[s] = 1
        }
    }
    print(Object.keys(dict))
})

function perm(str) {
    var found = []
	var recurse = function(a, s) {
        if (s.length == 0) {
            found.push(a)
        }
        else {
            for (var i = 0; i < s.length; ++i) {
				var x = a + s.charAt(i)
                var y = ""
                for (var j = 0; j < s.length; ++j) {
                    if (i != j) {
                        y += s.charAt(j)
                    }
                }
                recurse(x, y)
            }
        }
    }
    recurse("", str)
    return found
}

function powerSet(str) {
    var ret = []
    var len = str.length
    var combis = Math.pow(2, len) // total combinations
    for (var i = 1; i < combis; ++i) {
        var s = ""
        for (var j = 0; j < len; ++j) {
			var a = i & Math.pow(2, j)
            if (a) {
                s += str.charAt(j)
            }
        }
        ret.push(s)
    }
    return ret
}

function print() {
    var args = Array.prototype.slice.apply(arguments)
    var str = ""
    for (arg of args) {
        str += arg + ", "
    }
    str = str.substring(0, str.length - 2)
    var el = newel(str)
    $("body").append(el)
    $("body").append("</br>")
}

function newel(str) {
    var el = document.createElement("div")
    $(el).html(str)
    $(el).addClass("print")
    return el
}