SHARE
TWEET

Untitled

a guest Mar 24th, 2019 58 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import std.stdio;
  2.  
  3. class Graph
  4. {
  5.     size_t capacity;
  6.     Node[] nodes;
  7.     Edge[] edges;
  8.     double[] values;
  9.  
  10.     this(int capacity)
  11.     {
  12.         this.capacity = capacity;
  13.     }
  14.  
  15.     void add_node()
  16.     {
  17.         auto node = new Node(this.nodes.length);
  18.         this.nodes ~= node;
  19.         foreach (i; 0 .. this.capacity)
  20.         {
  21.             this.values ~= 0.0;
  22.         }
  23.  
  24.     }
  25.  
  26.     void add_edge(uint from, uint to, uint shift, double weight)
  27.     {
  28.         auto edge = new Edge(from, to, shift, weight);
  29.  
  30.         this.nodes[from].edges ~= this.edges.length;
  31.         this.edges ~= edge;
  32.     }
  33.  
  34.     double eval(double[] input, uint i)
  35.     {
  36.         auto res = 0.0;
  37.         foreach (node; this.nodes)
  38.         {
  39.             auto val = node.id == 0 ? input[node.id] : this.values[node.id * this.capacity + i];
  40.             if (node.id == 1) {
  41.                 res = val;
  42.             }
  43.             foreach (edgeID; node.edges)
  44.             {
  45.                 auto edge = this.edges[edgeID];
  46.                 auto idx = edge.to * this.capacity + (i + edge.shift) % this.capacity;
  47.                 this.values[idx] += val * edge.weight;
  48.             }
  49.             this.values[node.id * this.capacity + i] = 0.0;
  50.         }
  51.         return res;
  52.     }
  53. }
  54.  
  55. class Node
  56. {
  57.     size_t id;
  58.     size_t[] edges;
  59.     this(size_t id)
  60.     {
  61.         this.id = id;
  62.     }
  63. }
  64.  
  65. class Edge
  66. {
  67.     size_t from;
  68.     size_t to;
  69.     size_t shift;
  70.     double weight;
  71.  
  72.     this(size_t from, size_t to, size_t shift, double weight)
  73.     {
  74.         this.from = from;
  75.         this.to = to;
  76.         this.shift = shift;
  77.         this.weight = weight;
  78.     }
  79. }
  80.  
  81. void main()
  82. {
  83.     auto g = new Graph(2);
  84.     g.add_node();
  85.     g.add_node();
  86.     g.add_edge(0, 1, 0, 0.5);
  87.     g.add_edge(1, 1, 1, 0.5);
  88.    
  89.     writeln(g.eval([1.0], 0));
  90.     writeln(g.eval([1.0], 1));
  91.     writeln(g.eval([1.0], 0));
  92.     writeln(g.eval([1.0], 1));
  93.     writeln(g.eval([1.0], 0));
  94.     writeln(g.eval([1.0], 1));
  95. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top