добавлен исходный код и ссылки

This commit is contained in:
Alexander Zhirov 2023-01-22 15:43:59 +03:00
parent c83ed6cf42
commit 4be7b9c4ce
15 changed files with 438 additions and 1 deletions

View file

@ -0,0 +1,16 @@
import std.stdio;
void main()
{
// Зна­че­ния, ко­то­рые ни­ко­гда не из­ме­нят­ся
immutable inchesPerFoot = 12;
immutable cmPerInch = 2.54;
// Пе­ре­би­ра­ем и пи­шем
foreach (feet; 5 .. 7)
{
foreach (inches; 0 .. inchesPerFoot)
{
writeln(feet, "'", inches, "''\t", (feet * inchesPerFoot + inches) * cmPerInch);
}
}
}

View file

@ -0,0 +1,12 @@
import std.stdio;
void main()
{
// Зна­че­ния, ко­то­рые ни­ко­гда не из­ме­нят­ся
immutable inchesPerFoot = 12;
immutable cmPerInch = 2.54;
// Пе­ре­би­ра­ем и пи­шем
foreach (feet; 5 .. 7)
foreach (inches; 0 .. inchesPerFoot)
writeln(feet, "'", inches, "''\t", (feet * inchesPerFoot + inches) * cmPerInch);
}

View file

@ -0,0 +1,15 @@
import std.stdio;
void fun(ref uint x, double y)
{
x = 42;
y = 3.14;
}
void main()
{
uint a = 1;
double b = 2;
fun(a, b);
writeln(a, " ", b);
}

View file

@ -0,0 +1,19 @@
import std.stdio, std.string;
import std.algorithm;
void main()
{
size_t [string] dictionary;
foreach (line; stdin.byLine())
{
// Раз­бить стро­ку на сло­ва
// До­ба­вить ка­ж­дое сло­во стро­ки в сло­варь
foreach (word; line.strip.splitter)
{
if (word in dictionary) continue; // Ни­че­го не де­лать
auto newID = dictionary.length;
dictionary[word.idup] = newID;
writeln(newID, '\t', word);
}
}
}

View file

@ -0,0 +1,35 @@
import std.array;
bool binarySearch(T)(T[] input, T value)
{
while (!input.empty)
{
auto i = input.length / 2;
auto mid = input[i];
if (mid > value) input = input[0 .. i];
else if (mid < value) input = input[i + 1 .. $];
else return true;
}
return false;
}
// рекурсивная версия
bool binarySearchR(T)(T[] input, T value)
{
if (input.empty) return false;
auto i = input.length / 2;
auto mid = input[i];
if (mid > value) return binarySearch(input[0 .. i], value);
if (mid < value) return binarySearch(input[i + 1 .. $], value);
return true;
}
unittest
{
assert(binarySearch([ 1, 3, 6, 7, 9, 15 ], 6));
assert(!binarySearch([ 1, 3, 6, 7, 9, 15 ], 5));
assert(binarySearchR([ 1, 3, 6, 7, 9, 15 ], 6));
assert(!binarySearchR([ 1, 3, 6, 7, 9, 15 ], 5));
// Ука­зать T яв­но (на­при­мер, для на­деж­но­сти)
assert(binarySearch!(int)([ 1, 3, 6, 7, 9, 15 ], 6));
}

View file

@ -0,0 +1,28 @@
import std.algorithm, std.stdio, std.string;
void main()
{
// Рас­счи­тать таб­ли­цу час­тот
uint[string] freqs;
foreach (line; stdin.byLine())
{
foreach (word; line.strip.splitter)
{
++freqs[word.idup];
}
}
// На­пе­ча­тать таб­ли­цу час­тот
foreach (key, value; freqs)
{
writefln("%6u\t%s", value, key);
}
// На­пе­ча­тать таб­ли­цу час­тот с сортировкой
string[] words = freqs.keys;
sort!((a, b) { return freqs[a] > freqs[b]; })(words);
foreach (word; words)
{
writefln("%6u\t%s", freqs[word], word);
}
}

View file

@ -0,0 +1,68 @@
import std.algorithm, std.conv, std.regex, std.range, std.stdio, std.string, std.ascii;
struct PersonaData
{
uint totalWordsSpoken;
uint[string] wordCount;
}
void addParagraph(string line, ref PersonaData[string] info)
{
// Вы­де­лить имя пер­со­на­жа и его ре­п­ли­ку
line = strip(line);
// auto sentence = std.algorithm.find(line, ". ");
auto sentence = line.find(". ");
if (sentence.empty)
{
return;
}
auto persona = line[0 .. $ - sentence.length];
sentence = toLower(strip(sentence[2 .. $]));
// Вы­де­лить про­из­не­сен­ные сло­ва
auto words = split(sentence, regex("[ \t,.;:?]+"));
// Вставка или обновление информации
if (!(persona in info))
{
// Пер­вая ре­п­ли­ка пер­со­на­жа
info[persona] = PersonaData();
}
info[persona].totalWordsSpoken += words.length;
foreach (word; words)
{
++info[persona].wordCount[word];
}
}
void printResults(PersonaData[string] info)
{
foreach (persona, data; info)
{
writefln("%20s %6u %6u", persona, data.totalWordsSpoken, data.wordCount.length);
}
}
void main()
{
// На­ка­пл­и­ва­ет ин­фор­ма­цию о глав­ных ге­ро­ях
PersonaData[string] info;
// За­пол­нить info
string currentParagraph;
foreach (line; stdin.byLine())
{
// 4 символа отступа
if (line.startsWith(" ") && line.length > 4 && isAlpha(line[4]))
{
// Пер­со­наж про­дол­жа­ет вы­ска­зы­ва­ние
currentParagraph ~= line[3 .. $];
}
// 2 символа отступа
else if (line.startsWith(" ") && line.length > 2 && isAlpha(line[2]))
{
// Пер­со­наж толь­ко что на­чал го­во­рить
addParagraph(currentParagraph, info);
currentParagraph = to!string(line[2 .. $]);
}
}
// За­кон­чи­ли, те­перь на­пе­ча­та­ем со­б­ран­ную ин­фор­ма­цию
printResults(info);
}

View 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());
}
}

View 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;
}
}
}

View 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());
}
}

View file

@ -0,0 +1,48 @@
module stats;
interface Stat
{
void accumulate(double x);
void postprocess();
double result();
}
class Min : Stat
{
private double min = double.max;
void accumulate(double x)
{
if (x < min)
{
min = x;
}
}
void postprocess() {} // Ни­че­го не де­лать
double result()
{
return min;
}
}
class Max : Stat
{
private double max = double.min_normal;
void accumulate(double x)
{
if (x > max)
{
max = x;
}
}
void postprocess() {} // Ни­че­го не де­лать
double result()
{
return max;
}
}

View file

@ -0,0 +1,25 @@
import std.stdio;
struct MyStruct
{
int data;
}
class MyClass
{
int data;
}
void main()
{
// Иг­ра­ем с объ­ек­том ти­па MyStruct
MyStruct s1;
MyStruct s2 = s1;
++s2.data;
writeln(s1.data); // Пе­ча­та­ет 0
// Иг­ра­ем с объ­ек­том ти­па MyClass
MyClass c1 = new MyClass;
MyClass c2 = c1;
++c2.data;
writeln(c1.data); // Пе­ча­та­ет 1
}

View file

@ -0,0 +1,6 @@
import std.stdio;
void main()
{
writeln("Hello, world!");
}

File diff suppressed because it is too large Load diff