Created
November 8, 2012 08:58
-
-
Save jason-s13r/4037648 to your computer and use it in GitHub Desktop.
My attempt at some sort of string builder for a chat thing.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// http://stackoverflow.com/questions/5306729/how-do-markov-chain-chatbots-work | |
// Following this answer to try and make something. | |
function Chat(dict) { | |
var dictionary = dict || {}; | |
var add_words = function(str, dict) { | |
var i = 0; | |
var words = str.split(" "); | |
var first = words[i++]; | |
var second = words[i++]; | |
while (i < words.length) { | |
var third = words[i++]; | |
var key = first + " " + second; | |
if (typeof dict[key] == 'undefined') { dict[key] = []; } | |
dict[key].push(third); | |
first = second; | |
second = third; | |
} | |
return dict; | |
}; | |
var build_string = function(dict, length) { | |
var dict_keys = []; | |
for (var k in dict) { dict_keys.push(k); } | |
var start_key = Math.round(Math.random()*dict_keys.length)%dict_keys.length; | |
var key = dict_keys[start_key]; | |
var str = key; | |
while (str.split(" ").length < length) { | |
var value_index = Math.round(Math.random()*dict[key].length)%dict[key].length; | |
var value = dict[key][value_index]; | |
str = str + " " + value; | |
key = key.split(" ")[1] + " " + value; | |
if (typeof dict[key] == 'undefined') { break; } | |
} | |
return str; | |
}; | |
return { | |
add: function(text) { | |
return dictionary = add_words(text, dictionary); | |
}, | |
str: function(length) { | |
return build_string(dictionary, length); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment