Add markov chain class
authorEugene Petkevich <nasedil.genio.code@gmail.com>
Mon, 15 Aug 2022 15:20:34 +0000 (18:20 +0300)
committerEugene Petkevich <nasedil.genio.code@gmail.com>
Mon, 15 Aug 2022 15:20:34 +0000 (18:20 +0300)
extensions/classes/markov.sc [new file with mode: 0644]

diff --git a/extensions/classes/markov.sc b/extensions/classes/markov.sc
new file mode 100644 (file)
index 0000000..677b003
--- /dev/null
@@ -0,0 +1,24 @@
+MarkovModel {
+  var <numStates, <>states, <>curIndex, <>weights;
+
+  *new {|states, startIndex, weights=nil|
+    ^super.newCopyArgs(states.size, states, startIndex, weights).init;
+  }
+
+  init {
+    if (weights.isNil) {
+      weights = Array2D(numStates, numStates);
+      numStates.do{|i|
+        numStates.do{|j|
+          weights[i, j] = 5.rand;
+        };
+      };
+    };
+  }
+
+  next {
+    var prevIndex = curIndex;
+    curIndex = weights.rowAt(prevIndex).normalizeSum.windex;
+    ^states[prevIndex];
+  }
+}
\ No newline at end of file