Sierpinski square curve: Difference between revisions

m
Refactored C++ code
(Add Factor)
m (Refactored C++ code)
Line 13:
#include <string>
 
class sierpinski_square {
std::string rewrite(const std::string& s) {
public:
void write(std::ostream& out, int size, int length, int order);
private:
static std::string rewrite(const std::string& s) {;
void line(std::ostream& out);
void execute(std::ostream& out, const std::string& s);
double x_;
double y_;
int angle_;
int length_;
};
 
void sierpinski_square::write(std::ostream& out, int size, int length, int order) {
length_ = length;
constx_ int= (size = 635,- length = 5)/2;
y_ = length;
angle_ = 0;
out << "<svg xmlns='http://www.w3.org/2000/svg' width='"
<< size << "' height='" << size << "'>\n";
out << "<rect width='100%' height='100%' fill='white'/>\n";
out << "<path stroke-width='1' stroke='black' fill='none' d='";
std::string s = "F+XF+F+XF";
for (int i = 0; i < order; ++i)
s = rewrite(s);
execute(out, s);
out << "'/>\n</svg>\n";
}
 
std::string sierpinski_square::rewrite(const std::string& s) {
std::string t;
for (char c : s) {
Line 24 ⟶ 53:
}
 
void sierpinski_square::line(std::ostream& out, double& x, double& y, double length, int angle) {
constexpr double pitheta = (3.14159265359 * angle_)/180.0;
double thetax_ += (pilength_ * anglestd::cos(theta)/180.0;
xy_ += lengthlength_ * std::cossin(theta);
yout +=<< length" *L" std::sin(theta)<< x_ << ',' << y_;
out << 'L' << x << ',' << y << '\n';
}
 
void sierpinski_square::execute(std::ostream& out, const std::string& s,) double x, double y,{
out << 'M' << x_ << double length',' int angle)<< {y_;
out << 'M' << x << ',' << y << '\n';
for (char c : s) {
ifswitch (c) == 'F'){
case 'F':
line(out, x, y, length, angle);
else if (c == '+'line(out);
angle = (angle + 90) % 360break;
else if (c ==case '-+'):
angleangle_ = (angleangle_ -+ 90) % 360;
break;
case '-':
angle_ = (angle_ - 90) % 360;
break;
}
}
}
 
int main() {
const int size = 635, length = 5;
const int order = 5;
std::ofstream out("sierpinski_square.svg");
if (!out) {
Line 53 ⟶ 83:
return 1;
}
sierpinski_square s;
out << "<svg xmlns='http://www.w3.org/2000/svg' width='"
s.write(out, 635, 5, 5);
<< size << "' height='" << size << "'>\n";
out << "<rect width='100%' height='100%' fill='white'/>\n";
out << "<path stroke-width='1' stroke='black' fill='none' d='";
std::string s = "F+XF+F+XF";
for (int i = 0; i < order; ++i)
s = rewrite(s);
execute(out, s, (size - length)/2, length, length, 0);
out << "'/>\n</svg>\n";
return 0;
}</lang>
 
{{out}}
See: [https://slack-files.com/T0CNUL56D-F016R68SKR9F01H50B6NLR-a10c02c762042402f38c sierpinski_square.svg] (offsite SVG image)
 
=={{header|Factor}}==
1,777

edits