D solutions (#305)

* Added 1 and 2 chapters

for D lang

* [D] Added recursion code

All examples were ported from the Python code directly to D.
Naming convention of Dlang is not allowing to run code files, which started with numbers. To run examples rename the files

* [D] quicksort code

* [D] Added hashtable example

Based on the Python code

* Create 01_breadth_first_search.d

Added D example for breadth-first search

* Create 01_filesystem_dfs.d

Filesystem example in D

* Create 01_dijkstras_algorithm.d

Added Dijkstras algorithm implementation for D

* Create 01_set_covering.d

Added greedy algorythm for D

* Create 01_longest_common_sub.d

Added dynamic programming example for D language.
The code is based on Rust example

* Added modules definition

Required to run code with names starting with numbers

* Fixed proper unsigned handling
This commit is contained in:
Serg Gini
2025-05-02 02:24:42 +03:00
committed by GitHub
parent df180e6f7b
commit 9ff7468e9e
22 changed files with 544 additions and 0 deletions

View File

@@ -0,0 +1,63 @@
module app;
import std;
alias Costs = double[string];
alias Graph = Costs[string];
Graph graph;
string[] processed;
string find_lowest_cost_node(const Costs costs)
{
double lowestCost = double.infinity;
string lowestCostNode;
foreach(node; costs.byPair)
{
auto cost = node.value;
if (cost < lowestCost && (!processed.canFind(node.key)))
{
lowestCost = cost;
lowestCostNode = node.key;
}
}
return lowestCostNode;
}
void main()
{
graph["start"] = ["a": 6, "b": 2];
graph["a"] = ["finish": 1];
graph["b"] = ["a": 3, "finish": 5];
graph["finish"] = new Costs;
Costs costs;
costs["a"] = 6;
costs["b"] = 2;
costs["finish"] = double.infinity;
string[string] parents;
parents["a"] = "start";
parents["b"] = "start";
auto node = find_lowest_cost_node(costs);
while (!node.empty)
{
double cost = costs[node];
auto neighbors = graph[node];
foreach(n; neighbors.byKey())
{
double newCost = cost + neighbors[n];
if (costs[n] > newCost)
{
costs[n] = newCost;
parents[n] = node;
}
}
processed ~= node;
node = find_lowest_cost_node(costs);
}
writeln("Cost from the start to each node:");
writeln(costs);
}