Skip to content

Instantly share code, notes, and snippets.

@alphaKAI
Last active August 29, 2015 14:22
Show Gist options
  • Select an option

  • Save alphaKAI/5c3c83ec84f019d54255 to your computer and use it in GitHub Desktop.

Select an option

Save alphaKAI/5c3c83ec84f019d54255 to your computer and use it in GitHub Desktop.
Console Grapher - コンソールにsinやcos, log10などあらゆるグラフを描画します(関数値にしたがって点をプロット)。 ただし、実装の都合上x,y平面のx,yが反転して描画されます。
/**
Console Grapher
Copyright (C) alphaKAI 2015 http://alpha-kai-net.info
The MIT License
*/
import std.algorithm,
std.range,
std.stdio,
std.conv,
std.math;
string repeat(string p, int n){
return n.iota.map!(x => p).join;
}
string whites(int n){
return repeat("-", n);
}
real sinRad(real x){
return sin((x / 180) * PI);
}
real cosRad(real x){
return cos((x / 180) * PI);
}
real tanRad(real x){
return tan((x / 180) * PI);
}
void drawGraph(real sorceX, int origin = 1, real ratio = 1, bool rFlag = false){
// origin 原点のx座標を指定(コンソールの左端から1文字分を1とする)
// ratio 表示倍率
// rFlag 関数値が常に負を取ることが分かる場合にグラフを反転させるかどうかを指定
sorceX *= -1;
int x_ = (sorceX * ratio).to!int;
int x = origin - x_;
string line;
if(x < origin){
line = x.whites ~ "*" ~ whites(origin - x - 1) ~ "|" ~ origin.whites;
if(rFlag)
line.split("").reverse.join.writeln;
else
line.writeln;
} else if(x > origin){
line = origin.whites ~ "|" ~ whites(x - origin - 1) ~ "*" ~ whites(2 * origin - x);
if(rFlag)
line.split("").reverse.join.writeln;
else
line.writeln;
} else {
line = x.whites ~ "*" ~ origin.whites;
if(rFlag)
line.split("").reverse.join.writeln;
else
line.writeln;
}
}
void main(){
writeln("Console Grapher");
writeln("Copyright (C) alphaKAI 2015 http://alpha-kai-net.info");
writeln("The MIT License");
writeln;
writeln("Example graphs");
writeln;
writeln(repeat("=", 20));
writeln("y = sin(x) graph (x = sin(y))");
writeln(repeat("=", 20));
361.iota.each!((int e){
if(e % 5 == 0)
drawGraph(sinRad(e), 50, 50);
});
writeln;
writeln(repeat("=", 20));
writeln("y = cos(x) graph (x = cos(y))");
writeln(repeat("=", 20));
361.iota.each!((int e){
if(e % 5 == 0)
drawGraph(cosRad(e), 50, 50);
});
writeln;
writeln(repeat("=", 20));
writeln("y = log10(x) graph (x = cos(y))");
writeln(repeat("=", 20));
100.iota.each!((int e){
if(e % 5 == 0)
if(e > 0)
drawGraph(log10(e), 1, 10);
});
writeln;
writeln(repeat("=", 20));
writeln("y = x graph (y = x)");
writeln(repeat("=", 20));
foreach(e; -10..11){
drawGraph(e, 10, 1);
}
writeln;
writeln(repeat("=", 20));
writeln("y = x^2 graph (x = y^2)");
writeln(repeat("=", 20));
foreach(e; -10..11){
drawGraph(e * e, 1, 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment