Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

closes #2#3

Merged
mgechev merged 1 commit into
mgechev:mastermgechev/javascript-algorithms:masterfrom
yocontra:patch-1yocontra/javascript-algorithms:patch-1Copy head branch name to clipboard
Feb 12, 2014
Merged

closes #2#3
mgechev merged 1 commit into
mgechev:mastermgechev/javascript-algorithms:masterfrom
yocontra:patch-1yocontra/javascript-algorithms:patch-1Copy head branch name to clipboard

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

mgechev commented Feb 12, 2014

Copy link
Copy Markdown
Owner

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

Morty Proxy This is a proxified and sanitized view of the page, visit original site.