Abelian sandpile model/Identity: Difference between revisions

(→‎{{header|C++}}: refactoring)
Line 69:
constexpr size_t sp_columns = 3;
constexpr size_t sp_cells = sp_rows * sp_columns;
constexpr size_tint sp_limit = 4;
 
class abelian_sandpile {
friend boolstd::ostream& operator==<<(const abelian_sandpilestd::ostream&, const abelian_sandpile&);
 
public:
abelian_sandpile();
Line 78 ⟶ 80:
bool is_stable() const;
void topple();
abelian_sandpile& operator+=(const abelian_sandpile& other);
bool operator==(const abelian_sandpile& a, const abelian_sandpile& b) {;
void print(std::ostream&) const;
 
private:
int& cell_value(size_t row, size_t column) {
Line 93 ⟶ 96:
return cell_index % sp_columns;
}
 
friend bool operator==(const abelian_sandpile&, const abelian_sandpile&);
std::array<int, sp_cells> cells_;
};
Line 111 ⟶ 114:
stabilize();
return *this;
 
bool abelian_sandpile::operator==(const abelian_sandpile& other) {
return a.cells_ == bother.cells_;
}
 
Line 140 ⟶ 147:
while (!is_stable())
topple();
 
bool operator==(const abelian_sandpile& a, const abelian_sandpile& b) {
return a.cells_ == b.cells_;
}
 
Line 152 ⟶ 155:
}
 
void abelian_sandpilestd::printostream& operator<<(std::ostream& out), const abelian_sandpile& as) {
for (size_t i = 0; i < sp_cells; ++i) {
if (i > 0)
out << (as.column_index(i) == 0 ? '\n' : ' ');
out << as.cells_[i];
}
return out << '\n';
}
 
Line 167 ⟶ 170:
abelian_sandpile sp{4,3,3, 3,1,2, 0,2,3};
while (!sp.is_stable()) {
sp.print(std::cout << sp << "stable? " << sp.is_stable() << "\n\n";
std::cout << "stable? " << sp.is_stable() << "\n\n";
sp.topple();
}
sp.print(std::cout << sp << "stable? " << sp.is_stable() << "\n\n";
std::cout << "stable? " << sp.is_stable() << "\n\n";
 
std::cout << "Commutativity:\n";
Line 180 ⟶ 181:
abelian_sandpile sum2(s2 + s1);
std::cout << "s1 + s2 equals s2 + s1? " << (sum1 == sum2) << "\n\n";
std::cout << "s1 + s2 = \n" << sum1;
sum1.print(std::cout) << "\ns2 + s1 = \n" << sum2;
std::cout << "\ns2 + s1 = \n";
sum2.print(std::cout);
std::cout << '\n';
 
std::cout << "Identity:\n";
abelian_sandpile s3{3,3,3, 3,3,3, 3,3,3};
Line 193 ⟶ 192:
std::cout << "s3 + s3_id equals s3? " << (sum3 == s3) << '\n';
std::cout << "s3_id + s3_id equals s3_id? " << (sum4 == s3_id) << "\n\n";
std::cout << "s3 + s3_id = \n" << sum3;
sum3.print(std::cout) << "\ns3_id + s3_id = \n" << sum4;
 
std::cout << "\ns3_id + s3_id = \n";
sum4.print(std::cout);
return 0;
}</lang>
Anonymous user