Implement UnionFind, just without ranks.

This commit is contained in:
Alexander McCord 2024-05-18 15:49:06 -07:00
parent 2338185296
commit b235faf489
2 changed files with 35 additions and 0 deletions

View file

@ -1,12 +1,22 @@
// This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details
#pragma once
#include "Luau/Id.h"
#include <vector>
namespace Luau::EqSat
{
/// See <https://dl.acm.org/doi/pdf/10.1145/321879.321884>.
struct UnionFind
{
Id makeSet();
Id find(Id id) const;
void merge(Id a, Id b);
private:
std::vector<Id> parents;
};
} // namespace Luau::EqSat

View file

@ -1,9 +1,34 @@
// This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details
#include "Luau/UnionFind.h"
#include "Luau/Common.h"
namespace Luau::EqSat
{
Id UnionFind::makeSet()
{
Id id{parents.size()};
parents.push_back(id);
return id;
}
Id UnionFind::find(Id id) const
{
LUAU_ASSERT(size_t(id) < parents.size());
while (id != parents[size_t(id)])
id = parents[size_t(id)];
return id;
}
void UnionFind::merge(Id a, Id b)
{
LUAU_ASSERT(size_t(a) < parents.size());
LUAU_ASSERT(size_t(b) < parents.size());
parents[size_t(b)] = a;
}
} // namespace Luau::EqSat