File: run.cpp | Size: 1,440 bytes | Download file | Back to directory listing | BWPOW's homepage
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include "ts.h"
 
using namespace std;
 
extern map<INSTR,INSTR> instr;
extern vector<string> state;
extern vector<char> pr,pl;
extern INFO info;
extern char chars[256];
 
int run_get_p(int pos)
{
  if(pos>=0){
    if(info.cr){
      if(pos>=info.maxmemory) return '<';
    }
    if(pos>=pr.size()) return info.zero;
    return pr[pos];
  }
  else{
    pos=abs(pos)-1;
    if(info.cl){
      return '>';      
    }
    if(pos>=pl.size()) return info.zero;
    return pl[pos];
  }
  return info.zero;
}  
 
void run_write_p(int pos,int c)
{
  if(pos>=0){
    if(info.cr){
      if(pos>=info.maxmemory) return;
    }
    if(pos>=pr.size()+1) return;
    if(pos==pr.size()){pr.push_back(c); return; }
    pr[pos]=c;
  }
  else{
    pos=abs(pos)-1;
    if(info.cl) return;
    if(pos>=pl.size()+1) return;
    if(pos==pl.size()){pl.push_back(c); return; }
    pl[pos]=c;
  }
}  
 
int run(void)
{
  int pos=0;
  INSTR a,b;
  a.m=0;
  info.state=0;
  info.steps=0;
  while(1){
    if(info.steps>info.maxsteps) return -1;
 
    a.s=info.state;
    a.p=run_get_p(pos);
 
    if(instr.count(a)<=0) break;
    b=instr[a];
 
    run_write_p(pos,b.p);
    info.state=b.s;
 
    if(b.m==MOVE_LEFT) pos--;
    if(b.m==MOVE_RIGHT) pos++;
 
    if(pr.size()+pl.size()>info.maxmemory) return -2;
    info.steps++;
  }  
  return 0;
}