图灵机
66xyyd
·
·
科技·工程
#include<iostream>
#include<vector>
#include<map>
#include<graphics.h>
#include<cmath>
using namespace std;
struct TuringMachine{
int n;//状态数
struct perunit{
int jmpto;//-1表示停机
bool setto;//将当前状态设置成false表示0,true表示1
bool mov;//false表示左移,true表示右移
};
vector<pair<perunit,perunit>> a;//i表示第i个状态,存储依次为0,1
TuringMachine(int _n=0,const vector<pair<perunit,perunit>> &_a=vector<pair<perunit,perunit>>()):n(_n),a(_a){}
};
struct RunMachine{
TuringMachine machine;
map<int,bool> paper;//纸带
int pos=0,feel=0;//位置;状态
RunMachine(const TuringMachine &mac):machine(mac),pos(0),feel(0){}
vector<bool> now(int range){//[pos-range,pos+range]共2*range+1格
vector<bool> res;
for(int i=pos-range;i<=pos+range;++i){
res.push_back(paper[i]);
}
return res;
}
bool next(){//返回true表示未终止,返回false表示已中止
TuringMachine::perunit cur=paper[pos]?machine.a[feel].second:machine.a[feel].first;
paper[pos]=cur.setto;
feel=cur.jmpto;
if(cur.mov) ++pos;
else --pos;
return feel!=-1;
}
};
RunMachine run(RunMachine(TuringMachine(
5,
vector<pair<TuringMachine::perunit,TuringMachine::perunit>>({make_pair(TuringMachine::perunit({1,0,0}),TuringMachine::perunit({1,0,0})),
make_pair(TuringMachine::perunit({2,1,1}),TuringMachine::perunit({2,1,1})),
make_pair(TuringMachine::perunit({3,0,1}),TuringMachine::perunit({3,0,1})),
make_pair(TuringMachine::perunit({3,1,1}),TuringMachine::perunit({4,0,0})),
make_pair(TuringMachine::perunit({3,0,1}),TuringMachine::perunit({4,0,0}))
})
)));
int steps=0;
void draw_arrow(float sx, float sy,
float ex, float ey,
float r, float len) {
float c = cos(r), s = sin(r);
float dx = sx - ex, dy = sy - ey;
ege_line(sx, sy, ex, ey);
ege_point points[3] = {
ex, ey,
len * ( dx * c + dy * s) + ex,
len * (-dx * s + dy * c) + ey,
len * ( dx * c - dy * s) + ex,
len * ( dx * s + dy * c) + ey
};
ege_fillpoly(3, points);
}
void show(){
static const int lrrange=21;//左右一共21个格子
vector<bool> papers=run.now((lrrange-1)>>1);
double perbarwidth=860.0/lrrange;
setlinewidth(1);
setcolor(BLACK);
setfillcolor(BLACK);
cleardevice();
ege_drawtext((string("step=")+to_string(steps)+string(" state=")+to_string(run.feel)+string(" pos=")+to_string(run.pos)).c_str(),0,50);
for(int i=0;i<lrrange;i++){
ege_rectangle(1.0*i*perbarwidth,550,perbarwidth,70);
if(papers[i]){
bar(1.0*i*perbarwidth,550,1.0*(i+1)*perbarwidth,620);
}
}
int arrowpos=(lrrange-1)>>1;
setlinewidth(5);
draw_arrow(1.0*arrowpos*perbarwidth+0.5*perbarwidth,450,1.0*arrowpos*perbarwidth+0.5*perbarwidth,530,PI/8.0,0.2);
}
int main(){
initgraph(860,680);
setcaption("turing machine");
setfont(50,0,"微软雅黑");
settextjustify(CENTER_TEXT,CENTER_TEXT);
setbkcolor(WHITE);
setcolor(BLACK);
setfillcolor(BLACK);
setlinewidth(1);
for(int i=1;i<=20;i++){
run.paper[3*i-1]=1;
}
run.pos=0;
while(true){
++steps;
show();
getch();
if(!run.next()) break;
}
show();
getch();
closegraph();
return 0;
}