as a beginner project i try to translate this python code into lua code https://eli.thegreenplace.net/2018/elegant-python-code-for-a-markov-chain-text-generator/ . I have problems with translating pythons "random.choices" right. The markov matrix itself should work. I would be thankful for any help with generating a markov chain with this lua code. this is the output of the markov matrix for markov order 3 and this input "1111111111111110000006000000000006600".
600 0 1
111 1 12
111 0 1
060 0 1
660 0 1
006 6 1
006 0 1
100 0 1
000 6 2
000 0 11
110 0 1
066 0 1
with that information i need to calculate the next step, but i do not know how to do that with lua. for the sequence 600 the 0 follows with 100%, for the sequence 111 the 1 follows with 12/13 and the 0 with 1/13, for the sequence 060 the 0 follows with 100 % and so on.
here is my lua code:
math.randomseed(os.time()- os.clock() * 1000);
-- make dictionary;
function defaultdict(default_value_factory);
local t = {};
local metatable = {};
metatable.__index = function(t, key);
if not rawget(t, key) then;
rawset(t, key, default_value_factory(key));
end;
return rawget(t, key);
end;
return setmetatable(t, metatable);
end;
;
;
-- make markov matrix;
STATE_LEN = 3;
model = defaultdict(function() return {} end)
data = "1111111111111110000006000000000006600";
print("datasize: ", #data)
print('Learning model...')
for i = 1, (#data - STATE_LEN) do;
state = data:sub(i, i + STATE_LEN-1);
print("state: ", state)
local next = data:sub(i + STATE_LEN, i + STATE_LEN);
print("next: ", next);
model[state][next] = (model[state][next] or 0)+1;
end;
;
;
-- make markov chain;
print('Sampling...');
;
-- make key list;
local keyset={};
local n=0;
for k,v in pairs(model) do;
n=n+1;
keyset[n]=k;
end;
-- make random key;
local randomKey = keyset[math.random(#keyset)];
print("RandomKey: ", randomKey)
state = randomKey;
;
-- make table from random key;
local str = state;
local stateTable = {};
for i = 1, #str do;
stateTable[i] = str:sub(i, i);
end;
;
out = stateTable;
print ("random key as table: ", table.unpack(stateTable));
;
-- make value list;
local valueset={};
local n=0;
for key, value in pairs(model) do;
for k, v in pairs(value) do;
n=n+1;
valueset[n]=v;
end;
end;
;
print("Keys: ", table.unpack(keyset));
print("Vals: ", table.unpack(valueset));
;
for key, value in pairs(model) do;
for k, v in pairs(value) do;
print(key, k, v);
end;
end;
;
;
-- make markov chain;
for i = 1, 400 do;
table.insert(out, #out + 1, math.random(10));
state = string.sub(state, 2, #state) .. out[#out];
end;
-- print markov chain;
print(table.concat(out));
;