добавлен исходный код и ссылки
This commit is contained in:
parent
c83ed6cf42
commit
4be7b9c4ce
15 changed files with 438 additions and 1 deletions
26
01-знакомство-с-языком-d/src/chapter-1-6-1/app.d
Normal file
26
01-знакомство-с-языком-d/src/chapter-1-6-1/app.d
Normal file
|
@ -0,0 +1,26 @@
|
|||
import std.stdio : writeln, stdin;
|
||||
import std.exception : enforce;
|
||||
import stats;
|
||||
|
||||
void main(string[] args)
|
||||
{
|
||||
Stat[] stats;
|
||||
foreach (arg; args[1 .. $])
|
||||
{
|
||||
auto newStat = cast(Stat) Object.factory("stats." ~ arg);
|
||||
enforce(newStat, "Invalid statistics function: " ~ arg);
|
||||
stats ~= newStat;
|
||||
}
|
||||
for (double x; stdin.readf(" %s ", &x) == 1;)
|
||||
{
|
||||
foreach (s; stats)
|
||||
{
|
||||
s.accumulate(x);
|
||||
}
|
||||
}
|
||||
foreach (s; stats)
|
||||
{
|
||||
s.postprocess();
|
||||
writeln(s.result());
|
||||
}
|
||||
}
|
76
01-знакомство-с-языком-d/src/chapter-1-6-1/stats.d
Normal file
76
01-знакомство-с-языком-d/src/chapter-1-6-1/stats.d
Normal file
|
@ -0,0 +1,76 @@
|
|||
module stats;
|
||||
|
||||
interface Stat
|
||||
{
|
||||
void accumulate(double x);
|
||||
void postprocess();
|
||||
double result();
|
||||
}
|
||||
|
||||
class IncrementalStat : Stat
|
||||
{
|
||||
protected double _result;
|
||||
abstract void accumulate(double x);
|
||||
void postprocess() {}
|
||||
|
||||
double result()
|
||||
{
|
||||
return _result;
|
||||
}
|
||||
}
|
||||
|
||||
class Min : IncrementalStat
|
||||
{
|
||||
this()
|
||||
{
|
||||
_result = double.max;
|
||||
}
|
||||
|
||||
override void accumulate(double x)
|
||||
{
|
||||
if (x < _result)
|
||||
{
|
||||
_result = x;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class Max : IncrementalStat
|
||||
{
|
||||
this()
|
||||
{
|
||||
_result = double.min_normal;
|
||||
}
|
||||
|
||||
override void accumulate(double x)
|
||||
{
|
||||
if (x > _result)
|
||||
{
|
||||
_result = x;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class Average : IncrementalStat
|
||||
{
|
||||
private uint items = 0;
|
||||
|
||||
this()
|
||||
{
|
||||
_result = 0;
|
||||
}
|
||||
|
||||
override void accumulate(double x)
|
||||
{
|
||||
_result += x;
|
||||
++items;
|
||||
}
|
||||
|
||||
override void postprocess()
|
||||
{
|
||||
if (items)
|
||||
{
|
||||
_result /= items;
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue