Monkeyai——是啥必用的AI吗?
注:大部分代码由deepseek完成
又注:~蕉蕉蕉,睡蕉小猴没烦恼
一、这是什么?
一只伪装成 AI 的猴子万一比豆包聪明点呢。你问它任何问题,它从自己随机敲出的乱码里捞出一个英文单词回你,和问题毫无关系。
二、它是怎么工作的?
三步循环:
随机打字:从 26 个小写字母里随机抽字符,先生成 50 万个
捞单词:用非重叠最长匹配扫描乱码,把恰好构成英文单词的片段收进“单词池”
随机回答:从池子里随机抽 1 个词回你,然后继续打字扩充池子
词库优先读 /usr/share/dict/words,没有就用内嵌常用词表。
三、它有什么用?
暂时不知道,可以当答案之书用。
四、怎么用?
复制代码运行。
五、代码呢?
#include <iostream>
#include <fstream>
#include <random>
#include <string>
#include <vector>
#include <unordered_set>
#include <unordered_map>
#include <algorithm>
#include <cmath>
#include <cctype>
#include <chrono>
#include <thread>
#include <cstdint>
// ================= 可调参数 =================
static const int INITIAL_CHARS = 500000; // 初始让猴子打多少字符
static const size_t REFILL_CHARS = 5000; // 每次回答后继续打多少字符
static const size_t POOL_LIMIT = 200000; // 单词池上限
static const std::string ALPHABET = "abcdefghijklmnopqrstuvwxyz";
static const int MIN_LEN = 3; // 词库最小长度:3
static const int MIN_ANSWER_WORDS = 1; // 每次只回答 1 个词
static const int MAX_ANSWER_WORDS = 1;
static const bool FAKE_THINK = true; // 回答前假装思考
static const bool ADD_PUNCT = false; // 单字回答时是否加标点
// ===========================================
static std::string toLower(std::string s) {
for (char& c : s) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
return s;
}
// 兼容旧版 MinGW:random_device 可能是假的,再混入时钟和地址熵
static std::uint32_t makeSeed() {
std::random_device rd;
const std::uint64_t t = static_cast<std::uint64_t>(
std::chrono::high_resolution_clock::now().time_since_epoch().count());
const std::uint64_t addr = static_cast<std::uint64_t>(
reinterpret_cast<std::uintptr_t>(&rd));
std::seed_seq seq{
static_cast<std::uint32_t>(rd()),
static_cast<std::uint32_t>(rd()),
static_cast<std::uint32_t>(t),
static_cast<std::uint32_t>(t >> 32),
static_cast<std::uint32_t>(addr)
};
std::uint32_t s = 0;
seq.generate(&s, &s + 1);
return s;
}
// 内嵌常用词表(长度 >= MIN_LEN 的会被收录),没有系统词典时使用
// 注意:为 MIN_LEN=3 补入了大量 3 字母常用词
static void loadBuiltinDict(std::unordered_set<std::string>& dict) {
static const char* words[] = {
// -------- 3 字母 --------
"act","add","age","ago","aid","aim","air","all","and","ant","any","ape","apt","are","arm",
"art","ash","ask","ate","awe",
"bad","bag","ban","bar","bat","bay","bed","bee","beg","bet","bid","big","bin","bit","bow",
"box","boy","bud","bug","bun","bus","but","buy",
"cab","can","cap","car","cat","cop","cot","cow","coy","cry","cup","cut",
"dad","dam","day","den","dew","did","die","dig","dim","din","dip","dog","dot","dry","due",
"ear","eat","egg","ego","elf","elm","end","era","err","eve","eye",
"fad","fan","far","fat","fax","fed","fee","few","fig","fin","fir","fit","fix","fly","fog",
"for","fox","fry","fun","fur",
"gag","gap","gas","gel","gem","get","got","gum","gun","gut","guy","gym",
"had","ham","has","hat","hay","hen","her","hid","him","his","hit","hoe","hog","hop","hot",
"how","hub","hue","hug","hum","hut",
"ice","icy","ill","ink","inn","ion","its","ivy",
"jab","jam","jar","jaw","jay","jet","job","jog","joy","jug","jut",
"keg","key","kid","kin","kit",
"lab","lad","lap","law","lay","led","leg","let","lid","lie","lip","lit","log","lot","low",
"mad","man","map","mat","may","men","met","mid","mix","mob","mom","mop","mow","mud","mug",
"nab","nap","net","new","nil","nip","nod","nor","not","now","nut",
"oak","oar","oat","odd","ode","off","oil","old","one","opt","orb","ore","our","out","owe",
"owl","own",
"pad","pal","pan","pat","paw","pay","pea","peg","pen","per","pet","pie","pig","pin","pit",
"pop","pot","pro","pub","pun","pup","put",
"rag","ram","ran","rap","rat","raw","ray","red","rib","rid","rig","rim","rip","rob","rod",
"rot","row","rub","rug","rum","run","rut","rye",
"sad","sag","sap","sat","saw","say","sea","see","set","sew","she","shy","sin","sip","sir",
"sit","six","ski","sky","sly","sob","son","sow","soy","spa","spy","sub","sue","sum","sun",
"tab","tag","tan","tap","tar","tax","tea","ten","the","tie","tin","tip","toe","ton","too",
"top","tot","tow","toy","try","tub","tug","two",
"urn","use",
"van","vat","vet","vex","via","vie","vow",
"wad","wag","wan","war","was","wax","way","web","wed","wee","wet","who","why","wig","win",
"wit","woe","won","woo","wow","wry",
"yak","yam","yap","yaw","yea","yen","yes","yet","you",
"zag","zap","zen","zip","zoo",
// -------- 4 字母及以上 --------
"able","about","above","accept","across","action","after","again","against","agree",
"almost","alone","along","already","always","among","amount","animal","answer","anyone",
"appear","apple","area","around","arrive","article","artist","assume","attack","author","avoid",
"baby","back","balance","ball","band","bank","base","basket","beach","bear","beautiful",
"because","become","before","begin","behind","believe","below","benefit","beside","best",
"better","between","beyond","bird","birth","black","blame","blank","blind","block","blood",
"blue","board","boat","body","bone","book","border","born","both","bottle","bottom","brain",
"branch","brave","bread","break","breath","bridge","bright","bring","broad","brother","brown",
"brush","build","burn","business","butter","button",
"cabin","cable","cake","call","calm","camera","camp","cancel","candle","candy","capital",
"captain","card","care","career","careful","carry","case","cash","castle","catch","cause",
"cell","center","century","certain","chain","chair","challenge","chance","change","channel",
"chapter","character","charge","chart","chase","cheap","check","cheese","chicken","chief",
"child","choice","choose","church","circle","city","civil","claim","class","clean","clear",
"climb","clock","close","cloth","cloud","club","coach","coast","coat","code","coffee","cold",
"collect","college","color","come","comfort","command","comment","common","company","compare",
"complete","computer","concern","condition","confirm","connect","consider","contain","continue",
"control","cook","cool","copy","corner","correct","cost","cotton","count","country","couple",
"course","court","cover","create","credit","crew","crime","cross","crowd","culture","current","custom",
"daily","damage","dance","danger","dark","data","date","daughter","dead","deal","dear","death",
"debate","decade","decide","deep","defend","define","degree","deliver","demand","depend","describe",
"design","desire","desk","detail","develop","device","diet","differ","difficult","dinner","direct",
"discover","discuss","disease","dish","distance","divide","doctor","dollar","door","double","doubt",
"down","draw","dream","dress","drink","drive","drop","drug","during",
"each","early","earn","earth","east","easy","edge","education","effect","effort","eight","either",
"else","employ","empty","enemy","energy","enjoy","enough","enter","entire","environment","equal",
"escape","especially","even","evening","event","ever","every","evidence","exact","example","except",
"exchange","excite","expect","experience","explain","express","extra",
"face","fact","factor","fail","fair","fall","family","famous","farm","fast","father","fear",
"feature","feed","feel","female","field","fight","figure","file","fill","film","final","find",
"fine","finger","finish","fire","first","fish","five","flag","flat","floor","flow","flower",
"focus","follow","food","foot","force","foreign","forest","forget","form","former","forward",
"four","free","fresh","friend","front","fruit","full","fund","future",
"game","garden","gather","general","girl","give","glass","goal","gold","good","govern","grand",
"great","green","ground","group","grow","guess","guide",
"hair","half","hall","hand","hang","happen","happy","hard","hate","have","head","health","hear",
"heart","heat","heavy","help","here","herself","high","hill","history","hold","home","hope",
"horse","hospital","hotel","hour","house","however","huge","human","hundred","hungry","hunt",
"hurry","husband",
"idea","identify","image","imagine","impact","important","improve","include","increase","indeed",
"indicate","industry","information","inside","instead","interest","invest","involve","issue",
"item","itself",
"join","just","keep","kill","kind","king","kitchen","knee","know",
"lack","lady","land","language","large","last","late","later","laugh","lead","learn","least",
"leave","left","less","letter","level","life","light","like","line","list","listen","little",
"live","local","long","look","lose","loss","love",
"machine","main","maintain","major","make","manage","many","market","marriage","material",
"matter","maybe","mean","measure","meat","media","meet","member","memory","mention","message",
"method","middle","might","military","million","mind","minute","miss","mission","model","modern",
"moment","money","month","more","morning","most","mother","mouth","move","movie","much","music",
"name","nation","natural","nature","near","necessary","need","network","never","news","next",
"nice","night","none","north","note","nothing","notice","number",
"occur","offer","office","officer","often","once","only","open","operation","opportunity",
"option","order","organization","other","outside","over","own",
"page","pain","paint","paper","parent","part","particular","partner","party","pass","past",
"patient","pattern","peace","people","perform","perhaps","period","person","phone","physical",
"pick","picture","piece","place","plan","plant","play","player","point","police","policy",
"poor","popular","position","possible","power","practice","prepare","present","president",
"press","pressure","pretty","prevent","price","private","probably","problem","process","produce",
"product","program","project","property","protect","prove","provide","public","pull","purpose","push",
"quality","question","quickly","quite",
"race","radio","raise","range","rate","rather","reach","read","ready","real","reality","realize",
"really","reason","receive","recent","recognize","record","reduce","reflect","region","relate",
"relationship","religious","remain","remember","remove","report","represent","require","research",
"resource","respond","response","rest","result","return","reveal","rich","right","rise","risk",
"road","rock","role","room","rule",
"safe","same","save","scene","school","science","score","season","seat","second","section",
"security","seek","seem","sell","send","senior","sense","series","serious","serve","service",
"seven","several","shake","share","shoot","short","should","shoulder","show","side","sign",
"significant","similar","simple","simply","since","sing","single","sister","site","situation",
"size","skill","skin","small","smile","social","society","soldier","some","song","soon","sort",
"sound","source","south","space","speak","special","specific","speech","spend","sport","spring",
"staff","stage","stand","standard","star","start","state","station","stay","step","still",
"stock","stop","store","story","strategy","street","strong","structure","student","study","stuff",
"style","subject","success","suddenly","suffer","suggest","summer","support","sure","surface","system",
"table","take","talk","task","teach","team","technology","tell","term","test","than","thank",
"that","their","themselves","then","theory","there","these","they","thing","think","third",
"this","those","though","thought","thousand","threat","three","through","throughout","throw",
"thus","time","today","together","tonight","top","total","tough","toward","town","trade",
"traditional","training","travel","treat","treatment","tree","trial","trip","trouble","true",
"truth","turn","type",
"under","understand","unit","until","upon","usually",
"value","various","very","victim","view","violence","visit","voice","vote",
"wait","walk","wall","want","watch","water","weapon","wear","week","weight","well","west",
"what","whatever","when","where","whether","which","while","white","whole","whom","whose",
"wide","wife","will","wind","window","wish","with","within","without","woman","wonder","word",
"work","world","worry","would","write","wrong",
"yard","yeah","year","your","yourself"
};
for (const char* w : words) {
std::string s(w);
if (static_cast<int>(s.size()) >= MIN_LEN) dict.insert(s);
}
}
// ================= monkeyai 引擎 =================
class MonkeyEngine {
public:
MonkeyEngine() : rng_(makeSeed()) {
loadDict();
harvestWords(randomChars(INITIAL_CHARS));
}
void rebuild() {
wordPool_.clear();
distinct_.clear();
harvestWords(randomChars(INITIAL_CHARS));
}
// 从单词池里随机抽 1~10 个词(当前配置为 1 个)
std::string answerString() {
if (wordPool_.empty()) replenish();
if (wordPool_.empty()) return "...";
std::uniform_int_distribution<int> countDist(MIN_ANSWER_WORDS, MAX_ANSWER_WORDS);
size_t n = static_cast<size_t>(countDist(rng_));
n = std::min(n, wordPool_.size());
std::vector<std::string> picked;
picked.reserve(n);
std::unordered_set<size_t> used;
std::uniform_int_distribution<size_t> idxDist(0, wordPool_.size() - 1);
int guard = 0;
while (picked.size() < n && used.size() < wordPool_.size() && guard++ < 10000) {
size_t k = idxDist(rng_);
if (used.insert(k).second) picked.push_back(wordPool_[k]);
}
std::string s;
for (size_t i = 0; i < picked.size(); ++i) {
if (i) s += ' ';
s += picked[i];
}
if (ADD_PUNCT) {
std::uniform_int_distribution<int> punc(0, 9);
int p = punc(rng_);
if (p == 0) s += '.';
else if (p == 1) s += '!';
else if (p == 2) s += '?';
}
// 单词数 >1 时偶尔首字母大写
std::uniform_int_distribution<int> cap(0, 4);
if (picked.size() > 1 && !s.empty() && cap(rng_) == 0) {
s[0] = static_cast<char>(std::toupper(static_cast<unsigned char>(s[0])));
}
totalSpoken_ += static_cast<int>(picked.size());
++rounds_;
replenish();
return s;
}
int thinkDelayMs() {
std::uniform_int_distribution<int> d(150, 600);
return d(rng_);
}
size_t dictSize() const { return dict_.size(); }
size_t poolSize() const { return wordPool_.size(); }
size_t distinctCount() const { return distinct_.size(); }
int roundsDone() const { return rounds_; }
int totalSpoken() const { return totalSpoken_; }
private:
std::unordered_set<std::string> dict_;
size_t maxWordLen_ = 0;
std::vector<std::string> wordPool_;
std::unordered_set<std::string> distinct_;
std::mt19937 rng_;
int rounds_ = 0;
int totalSpoken_ = 0;
void loadDict() {
const char* dictPaths[] = { "/usr/share/dict/words", "/usr/share/dict/american-english" };
for (const char* p : dictPaths) {
std::ifstream fin(p);
if (!fin) continue;
std::string w;
while (fin >> w) {
w = toLower(w);
if (static_cast<int>(w.size()) >= MIN_LEN) dict_.insert(w);
}
if (!dict_.empty()) break;
}
if (dict_.empty()) loadBuiltinDict(dict_);
for (const auto& w : dict_) maxWordLen_ = std::max(maxWordLen_, w.size());
}
std::string randomChars(size_t n) {
std::string s;
s.reserve(n);
std::uniform_int_distribution<int> d(0, static_cast<int>(ALPHABET.size()) - 1);
for (size_t i = 0; i < n; ++i) s.push_back(ALPHABET[d(rng_)]);
return s;
}
void harvestWords(const std::string& segment) {
for (size_t i = 0; i + MIN_LEN <= segment.size(); ) {
size_t lim = std::min(maxWordLen_, segment.size() - i);
bool matched = false;
for (size_t L = lim; L >= static_cast<size_t>(MIN_LEN); --L) {
std::string sub = segment.substr(i, L);
if (dict_.count(sub)) {
wordPool_.push_back(sub);
distinct_.insert(sub);
i += L;
matched = true;
break;
}
}
if (!matched) ++i;
}
}
void replenish() {
if (wordPool_.size() >= POOL_LIMIT) return;
harvestWords(randomChars(REFILL_CHARS));
}
};
// ================= 界面 =================
static void printBanner() {
std::cout <<
"============================================================\n"
" monkeyai v0.2 —— 一只被伪装成 AI 的猴子\n"
"------------------------------------------------------------\n"
" 它看不懂你的问题,只会随机吐出一个单词。\n"
" 词库最短 3 字母,回答永远只有一个词。\n"
"------------------------------------------------------------\n"
" 命令: /exit 退出\n"
" /stats 查看统计\n"
" /rebuild 让猴子重新打一遍字(重置单词池)\n"
"============================================================\n\n";
}
static void printStats(const MonkeyEngine& e) {
std::cout << "\n [monkeyai 统计]\n"
<< " 已对话轮数 : " << e.roundsDone() << "\n"
<< " 累计说出单词 : " << e.totalSpoken() << "\n"
<< " 单词池大小 : " << e.poolSize() << "(含重复)\n"
<< " 不同单词数 : " << e.distinctCount() << "\n\n";
}
static std::string trim(const std::string& s) {
size_t a = s.find_first_not_of(" \t\r\n");
if (a == std::string::npos) return "";
size_t b = s.find_last_not_of(" \t\r\n");
return s.substr(a, b - a + 1);
}
int main() {
std::ios::sync_with_stdio(false);
MonkeyEngine engine;
printBanner();
std::cout << " 词库规模: " << engine.dictSize()
<< " 个单词 (长度 >= " << MIN_LEN << ")\n";
std::cout << " 初始单词池: " << engine.poolSize() << " 个(含重复)\n\n";
// 猴子先主动打个招呼
std::cout << "monkeyai> " << engine.answerString() << "\n\n";
std::string line;
while (true) {
std::cout << "You: " << std::flush;
if (!std::getline(std::cin, line)) break;
std::string cmd = trim(line);
if (cmd.empty()) continue;
if (cmd == "/exit" || cmd == "/quit" || cmd == "exit" || cmd == "quit") break;
if (cmd == "/stats") {
printStats(engine);
continue;
}
if (cmd == "/rebuild") {
engine.rebuild();
std::cout << "monkeyai> (猴子重新打了一遍字,单词池: "
<< engine.poolSize() << " 个)\n";
continue;
}
if (FAKE_THINK) {
std::cout << "monkeyai> " << std::flush;
std::this_thread::sleep_for(std::chrono::milliseconds(engine.thinkDelayMs()));
} else {
std::cout << "monkeyai> ";
}
std::cout << engine.answerString() << '\n';
}
std::cout << "\nmonkeyai> bye\n";
return 0;
}