Add MarkovMatrix class

This commit is contained in:
Joscha 2016-11-03 20:15:44 +00:00
parent c0e84ee194
commit b1048a5abc
3 changed files with 71 additions and 1 deletions

View file

@ -7,7 +7,7 @@ RM = rm -f
SRCDIR = src SRCDIR = src
TMPDIR = build TMPDIR = build
TARGET = trumpotron TARGET = trumpotron
FILES = main Markov FILES = main Markov MarkovMatrix
#SOURCES = $(patsubst %,$(SRCDIR)/%.cpp,$(FILES)) #SOURCES = $(patsubst %,$(SRCDIR)/%.cpp,$(FILES))
OBJECTS = $(patsubst %,$(TMPDIR)/%.o,$(FILES)) OBJECTS = $(patsubst %,$(TMPDIR)/%.o,$(FILES))

47
src/MarkovMatrix.cpp Normal file
View file

@ -0,0 +1,47 @@
#include "MarkovMatrix.hpp"
#include <algorithm> // 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<std::string, int> 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];
}

23
src/MarkovMatrix.hpp Normal file
View file

@ -0,0 +1,23 @@
#ifndef MARKOVMATRIX_HPP
#define MARKOVMATRIX_HPP
#include <map>
#include <string>
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<std::string, int> hiccup(std::string& previous);
private:
int length;
std::map<std::string, std::map<std::string, int> > matrix;
};
#endif