From b1048a5abcbd109f4147f5969f4e45934a655927 Mon Sep 17 00:00:00 2001 From: Joscha Date: Thu, 3 Nov 2016 20:15:44 +0000 Subject: [PATCH] Add MarkovMatrix class --- Makefile | 2 +- src/MarkovMatrix.cpp | 47 ++++++++++++++++++++++++++++++++++++++++++++ src/MarkovMatrix.hpp | 23 ++++++++++++++++++++++ 3 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 src/MarkovMatrix.cpp create mode 100644 src/MarkovMatrix.hpp diff --git a/Makefile b/Makefile index f37cc6c..c464341 100644 --- a/Makefile +++ b/Makefile @@ -7,7 +7,7 @@ RM = rm -f SRCDIR = src TMPDIR = build TARGET = trumpotron -FILES = main Markov +FILES = main Markov MarkovMatrix #SOURCES = $(patsubst %,$(SRCDIR)/%.cpp,$(FILES)) OBJECTS = $(patsubst %,$(TMPDIR)/%.o,$(FILES)) diff --git a/src/MarkovMatrix.cpp b/src/MarkovMatrix.cpp new file mode 100644 index 0000000..0765fec --- /dev/null +++ b/src/MarkovMatrix.cpp @@ -0,0 +1,47 @@ +#include "MarkovMatrix.hpp" + +#include // for std::max + + +MarkovMatrix::MarkovMatrix(int length) +{ + this->length = length; +} + + +MarkovMatrix::~MarkovMatrix() +{ + // do nothing +} + + +void MarkovMatrix::feed(std::string line) +{ + for (int i=0; i<=int(line.size()); ++i) { + int pos = std::max(i-this->length, 0); + int len = i - pos; + std::string before = line.substr(pos, len); + std::string current = line.substr(i, 1); + this->matrix[before][current] += 1; + } +} + + +void MarkovMatrix::reset(int length) +{ + this->matrix.clear(); + + if (length>0) { + this->length = length; + } +} + + +std::map MarkovMatrix::hiccup(std::string& previous) +{ + int size = previous.size(); + int pos = std::max(size-this->length, 0); + int len = size - pos; + std::string before = previous.substr(pos, len); + return this->matrix[before]; +} diff --git a/src/MarkovMatrix.hpp b/src/MarkovMatrix.hpp new file mode 100644 index 0000000..9c6869e --- /dev/null +++ b/src/MarkovMatrix.hpp @@ -0,0 +1,23 @@ +#ifndef MARKOVMATRIX_HPP +#define MARKOVMATRIX_HPP + +#include +#include + + +class MarkovMatrix +{ +public: + MarkovMatrix(int length); + ~MarkovMatrix(); + + void feed(std::string line); + void reset(int length=0); // reset the matrix, length>0 -> set a new length + std::map hiccup(std::string& previous); + +private: + int length; + std::map > matrix; +}; + +#endif