This repository was archived by the owner on Jan 8, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph.cs
More file actions
68 lines (63 loc) · 1.81 KB
/
Graph.cs
File metadata and controls
68 lines (63 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using System.Collections.Generic;
using System.Numerics;
using System.Xml.Linq;
namespace Alcorithms
{
internal class Graph<V, E> where V : notnull, IEquatable<V> where E : struct, IAdditionOperators<E, E, E>
{
public static readonly Func<IEnumerable<int?>, int?> DEFAULT_PRED = col => !col.Any() ? null : col.Min();
public Dictionary<V, Node<V, E>> Nodes { get; init; } = [];
public E? Trace(V start, V finish, HashSet<V> allowed, Func<IEnumerable<E?>, E?> predicate, E? sum = null, params V[] passed)
{
E? res = sum;
HashSet<V> _passed= [.. passed, start];
var node = Nodes[start];
if (start.Equals(finish))
{
return sum;
}
else
{
res = Sum(res, predicate(node.Edges.Where(e => !_passed.Contains(e.Target) && (allowed.Contains(e.Target) || e.Target.Equals(finish)))
.Select(e => Trace(e.Target, finish, allowed, predicate, e.Value, [.. _passed]))));
return res;
}
static E? Sum(E? a, E? b)
{
if (a is E aVal)
{
if (b is E bVal)
{
return aVal + bVal;
}
else
{
return null;
}
}
else
{
return b;
}
}
}
public static Graph<V, E> Parse(string input, char partDelimiter = ';', char groupDelimiter = ',', char innerDelimiter = '-')
{
Graph<V, E> res = new();
var parts = input.Split(partDelimiter);
(var nodes, var edges) = (parts[0], parts[1]);
foreach (var n in nodes.Split(groupDelimiter))
{
res.Nodes.Add(Parse<V>(n!), new());
}
foreach (var e in edges.Split(groupDelimiter))
{
var edgeData = e.Split(innerDelimiter);
(var from, var to, var value) = (Parse<V>(edgeData[0]),Parse<V>(edgeData[1]),Parse<E>(edgeData[2]));
res.Nodes[from].Edges.Add(new(value, to));
}
return res;
static T Parse<T>(string s) => (T)Convert.ChangeType(s, typeof(T));
}
}
}