X Tutup
Skip to content

closes #2#3

Merged
mgechev merged 1 commit intomgechev:masterfrom
yocontra:patch-1
Feb 12, 2014
Merged

closes #2#3
mgechev merged 1 commit intomgechev:masterfrom
yocontra:patch-1

Conversation

@yocontra
Copy link
Copy Markdown
Contributor

Taken from an implementation I did

// weighted quick union
function Findable(n) {
    this.components = n;
    this.sizes = [];
    this.items = [];

    // fill
    for (var i = 0; i < n; i++) {
        this.sizes[i] = 1;
        this.items[i] = i;
    }
}

Findable.prototype.union = function (p, q) {
    var pf = this.find(p);
    var qf = this.find(q);
    if (pf == qf) return this; // already linked
    var psz = this.sizes[qf];
    var qsz = this.sizes[pf];

    if (psz < qsz) {
        this.items[pf] = qf;
        this.sizes[qf] += psz;
    } else {
        this.items[qf] = pf;
        this.sizes[pf] += qsz;
    }
    this.components--;
    return this;
};

Findable.prototype.find = function (p) {
    // walk up the tree
    while (p != this.items[p]) {
        p = this.items[p];
    }
    return p;
};

Findable.prototype.connected = function (p, q) {
    // share same parent node
    return this.find(p) === this.find(q);
};

// now a quick demo
var finder = new Findable(10);

var input = "4-2 1-0 2-0 5-7 6-2 7-3 7-9 9-8 8-1";
input = input.split(' ').map(function (v) {
    return v.split('-').map(function (v) {
        return parseInt(v);
    });
});

input.forEach(function (pair) {
    finder.union(pair[0], pair[1]);
});

console.log(finder.items.join(' '));

mgechev added a commit that referenced this pull request Feb 12, 2014
@mgechev mgechev merged commit 4a32651 into mgechev:master Feb 12, 2014
@mgechev
Copy link
Copy Markdown
Owner

mgechev commented Feb 12, 2014

Thanks for the PR!

@yocontra yocontra deleted the patch-1 branch February 12, 2014 19:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

X Tutup