示例#1
0
void Instruction::insert_after_this( Instruction *inst ) {
    //
    for( Transition &p : next ) {
        inst->next << p;
        for( Transition &t : p.inst->prev ) {
            if ( t.inst == this and t.rcitem == p.rcitem ) {
                t.inst = inst;
                break;
            }
        }
    }
    next.clear();
    next << Transition( inst, range_vec( unsigned( cx.pos.size() ) ) );
    inst->prev << Transition( this, range_vec( unsigned( cx.pos.size() ) ) );
}
示例#2
0
// 更新
void CSceneManager::Update(){
	Transition();
	while (LaunchCondition() && m_now_scene == m_scene->Update()){
		Draw();
	}
	Finalize();
}
示例#3
0
// 更新
void CSceneManager::Update(){
	SceneUpdate();
	Transition();

	FadeIn();
	FadeOut();
}
示例#4
0
文件: main.cpp 项目: CCJY/coliru
 virtual Transition find_alpha_transition(C alpha) {
     auto it = g.find(alpha);
     if (g.end() == it) {
         return Transition(MappedSubstring(0, 0, -1), nullptr);
     }
     return it->second;
 }
void ScreenManager::Update(ALLEGRO_EVENT ev)
{
    if(!startTransition)
        currentScreen->Update(ev);
    else
        Transition();
}
示例#6
0
文件: main.cpp 项目: CCJY/coliru
 // update performs the heart of an iteration:
 // It walks the border path from the active point to the end point
 // and adds the required Transitions brought by the insertion of
 // the string's i-th character.
 //
 // It returns the end point.
 ReferencePoint update(Node *s, MappedSubstring ki) {
     Node *oldr = &tree.root;
     Node *r = nullptr;
     bool is_endpoint = false;
     MappedSubstring ki1 = ki;
     auto ref_str_it = haystack.find(ki.ref_str);
     S w = ref_str_it->second;
     ReferencePoint sk(s, std::pair<int,int>(ki.ref_str, ki.l));
     ki1.r = ki.r-1;
     is_endpoint = test_and_split(s, ki1, w[ki.r], w, &r);
     while (!is_endpoint) {
         Leaf *r_prime = new Leaf();
         r->g.insert(std::pair<C,Transition>(
           w[ki.r], Transition(MappedSubstring(
           ki.ref_str, ki.r, std::numeric_limits<int>::max()), r_prime)));
         if (&tree.root != oldr) {
             oldr->suffix_link = r;
         }
         oldr = r;
         sk = canonize(sk.first->suffix_link, ki1);
         ki1.l = ki.l = sk.second.second;
         is_endpoint = test_and_split(sk.first, ki1, w[ki.r], w, &r); 
     }
     if (&tree.root != oldr) {
         oldr->suffix_link = sk.first;
     }
     return sk;
 }
示例#7
0
Expression::Expression(const std::wstring& s, NfaStates& states, TransitionSet& symbols) : m_ch(0)
{
  m_LiteralString = s;

  //  m_Type = ExpressionTypeSingle;
  m_Left = nullptr;
  m_Right = nullptr;

  //(start) -a-> () -b-> ....() -c-> (end)
  //cria uma cadeia de "ands" com cada caracteres o start e end sao as extremidades

  m_StartState = states.New();
  m_EndState = 0;
  NfaState* state = m_StartState;

  for (size_t i = 0 ; i < s.size(); i++)
  {
    if (i == 0)
      m_ch = Transition(s[i]);

    NfaState* pNew = states.New();
    Transition ch(s[i]);
    symbols.insert(ch);
    AddTransition(state, ch, pNew);
    state = pNew;
  }

  m_EndState = state;
  //AddTransition(state, m_EndState);

}
示例#8
0
void TopParser::next(TypeDef::Atom *atom,TypeDef::TopRule *rule)
 {
  TypeDef::State *state=topState();
  
  TypeDef::Rule *bottom_rule=Find(state->final->actions,atom);
  
  if( rule->bottom!=bottom_rule )
    {
     Printf(Exception,"App::TopParser::next(...) : rule mismatch");
    }
  
  auto args=rule->args.getRange();
  
  auto *ptr=topElements(args.len);

  for(auto p=args; +p ;++p,++ptr)
    {
     if( !IsSame(ptr->element,*p) )
       {
        Printf(Exception,"App::TopParser::next(...) : bad stack");
       }
    }
  
  pop(args.len);
  
  TypeDef::Kind *result=rule->result;
  
  push(result,Transition(topState()->transitions,result));
 }
void CameraTransitionExample::EarlyUpdate(float dt)
{
	if (!m_transitioner.IsTransitioning())
	{
		Transition();
	}
	m_transitioner.Update(dt);
}
示例#10
0
Transition Autom_State::getTr(unsigned int c) const {
  int sgc = c;
  for(int i=0; i<cap; i++) {
    if(tr[i].c == sgc)
      return tr[i];
  }
  return Transition(-1);
}
示例#11
0
void VSliderControl::Init(void)
{
    m_oMutex.Acquire();
   
    if (!m_bUsesStateBitmapRects) {
        for (int row = 0; row < m_iNumThumbStates; row++) {
            for (int i = 0; i < m_iNumFrames; i++) {
                int iFrameWidth, iFrameHeight;
                Rect oFrameRect;

                if (m_bHorizontalBitmap) {
                    iFrameWidth = (m_oBitmapRect.Width() + 1) / 3;
                    iFrameHeight = (m_oBitmapRect.Height() + 1) /
                                   m_iNumThumbStates;
                    oFrameRect = m_oBitmapRect;
                    oFrameRect.x1 += i * iFrameWidth;
                    oFrameRect.x2 = oFrameRect.x1 + iFrameWidth - 1;
                    oFrameRect.y1 += row * iFrameHeight;
                    oFrameRect.y2 = oFrameRect.y1 + iFrameHeight - 1;
                }
                else {
                    iFrameHeight = (m_oBitmapRect.Height() + 1) / 3;
                    iFrameWidth = (m_oBitmapRect.Width() + 1) /
                                  m_iNumThumbStates;
                    oFrameRect = m_oBitmapRect;
                    oFrameRect.x1 += row * iFrameWidth;
                    oFrameRect.x2 = oFrameRect.x1 + iFrameWidth - 1;
                    oFrameRect.y1 += i * iFrameHeight;
                    oFrameRect.y2 = oFrameRect.y1 + iFrameHeight - 1;
                }

                switch (i) {
                    case 0:
                        SetStateBitmap(m_pBitmap, oFrameRect, CS_Normal, row);
                        break;
                    case 1:
                        SetStateBitmap(m_pBitmap, oFrameRect, CS_MouseOver, row);
                        SetStateBitmap(m_pBitmap, oFrameRect, CS_Dragging, row);
                        break;
                    case 2:
                        SetStateBitmap(m_pBitmap, oFrameRect, CS_Disabled, row);
                        break;
                    default:
                        break;
                }
           }
        }
    }

    m_iThumbHeight = m_oStateBitmapRect[0][CS_Normal].Height(); 
    m_iRange = m_oRect.Height() - m_iThumbHeight;

    m_oMutex.Release();
    
    Transition(CT_None, NULL);
}
示例#12
0
void Instruction::insert_before_this( Instruction *inst, Instruction *&init ) {
    if ( init == this )
        init = inst;

    // p.inst -[a b c]-> this
    // p.inst -[a b c]-> inst -[0 1 2]-> this
    for( Transition &p : prev ) {
        inst->prev << p;
        for( Transition &t : p.inst->next ) {
            if ( t.inst == this and t.rcitem == p.rcitem ) {
                t.inst = inst;
                break;
            }
        }
    }
    prev.clear();
    prev << Transition( inst, range_vec( unsigned( cx.pos.size() ) ) );
    inst->next << Transition( this, range_vec( unsigned( cx.pos.size() ) ) );
}
示例#13
0
void ButtonControl::Init(void)
{
    m_oMutex.Acquire();

    m_eCurrentState = CS_Normal;

    if (!m_bUsesStateBitmapRects) {
        for (int i = 0; i < 4; i++) {
           int iFrameWidth;
           Rect oFrameRect;
           
           if (m_bHorizontalBitmap) {
               iFrameWidth = (m_oBitmapRect.Width() + 1) / 4;
               oFrameRect = m_oBitmapRect;
               oFrameRect.x1 += i * iFrameWidth;
               oFrameRect.x2 = oFrameRect.x1 + iFrameWidth - 1;
           }
           else {
               iFrameWidth = (m_oBitmapRect.Height() + 1) / 4;
               oFrameRect = m_oBitmapRect;
               oFrameRect.y1 += i * iFrameWidth;
               oFrameRect.y2 = oFrameRect.y1 + iFrameWidth - 1;
           }

           switch (i) {
               case 0:
                   SetStateBitmap(m_pBitmap, oFrameRect, CS_Normal);
                    break;
               case 1:
                   SetStateBitmap(m_pBitmap, oFrameRect, CS_MouseOver);
                    break;
               case 2:
                   SetStateBitmap(m_pBitmap, oFrameRect, CS_Pressed);
                    break;
               case 3:
                   SetStateBitmap(m_pBitmap, oFrameRect, CS_Disabled);
                    break;
                default:
                   break;
            }
        }
    }

    if (m_oRect.x2 == -1 && m_oRect.y2 == -1)
    {
        m_oRect.x2 = m_oRect.x1 + m_oStateBitmapRect[0][CS_Normal].x2 - 
                     m_oStateBitmapRect[0][CS_Normal].x1;
        m_oRect.y2 = m_oRect.y1 + m_oStateBitmapRect[0][CS_Normal].y2 -
                     m_oStateBitmapRect[0][CS_Normal].y1;
    }    
    m_oMutex.Release();

    Transition(CT_None, NULL);
}
void CameraTransitionExample::EarlyUpdate(float dt)
{
	if (!m_transitioner.IsTransitioning())
	{
        // Do not update touch events or the globe controller if the transition controller is working
        GetGlobeCameraController().Update(dt);
        
		Transition();
	}
	m_transitioner.Update(dt);
}
//-----------------------------------------------------------------------------------------------------------------------------------
void MainMenuScreen::AddInitialUI()
{
	BaseScreen::AddInitialUI();

	Button* beginButton = new Button(GetScreenCentre(), L"Begin", "Button.png");
	beginButton->SetClickFunction([this]()
	{
		Transition(new SelectLoadoutScreen(GetScreenManager(), "SelectLoadoutScreen.xml"));
	});

	AddScreenUIObject(beginButton);
}
示例#16
0
void Instruction::repl_in_preds( Instruction *inst ) {
    for( Transition &p : prev ) {
        for( Transition &t : p.inst->next ) {
            if ( t.inst == this ) {
                t.inst = inst;
                break;
            }
        }
        inst->prev << Transition( p.inst, p.rcitem );
    }
    prev.clear();
}
示例#17
0
void Instruction::remove( bool update_rcitem ) {
    for( Transition &p : prev ) {
        HPIPE_ASSERT( p.inst != this, "..." );

        unsigned ind = p.inst->next.index_first_checking( [&]( Transition &t ) {
                return t.inst == this;
    } );
        p.inst->next.remove( ind );
        for( Transition &t : next ) {
            Vec<unsigned> rcitem;
            if ( update_rcitem ) {
                rcitem.reserve( t.rcitem.size() );
                for( unsigned ind : t.rcitem )
                    rcitem << p.rcitem[ ind ];
            }

            p.inst->next.insert( p.inst->next.begin() + ind, Transition( t.inst, rcitem, t.freq ) );
        }
    }

    for( Transition &t : next ) {
        HPIPE_ASSERT( t.inst != this, "..." );

        unsigned ind = t.inst->prev.index_first_checking( [&]( Transition &p ) {
            return p.inst == this;
        } );
        t.inst->prev.remove( ind );
        for( Transition &p : prev ) {
            Vec<unsigned> rcitem;
            if ( update_rcitem ) {
                rcitem.reserve( t.rcitem.size() );
                for( unsigned ind : t.rcitem )
                    rcitem << p.rcitem[ ind ];
            }

            t.inst->prev.insert( t.inst->prev.begin() + ind, Transition( p.inst, rcitem ) );
        }
    }
}
示例#18
0
void GameSystem::registerTransitions(FSMTransitions &oTransitions)
{
	// TODO pause the game by pausing all game related systems on pause event and add grey overlay to show that the game is paused
	World& theWorld = _world;
	oTransitions[Event_t::MainMenu][GameState::Initializing] = Transition(GameState::MainMenu, [&](){theWorld._mainMenu->enable(true);  }, nullptr);
	oTransitions[Event_t::MainMenu][GameState::Pause] = Transition(GameState::MainMenu, [&](){ theWorld._inGameMenu->enable(false); theWorld._gameOverMenu->enable(false); theWorld.cleanAllEntities(); theWorld._mainMenu->enable(true); }, nullptr);
	oTransitions[Event_t::EndGame][GameState::Pause] = Transition(GameState::MainMenu, [&](){ theWorld._inGameMenu->enable(false); theWorld._gameOverMenu->enable(false); theWorld.cleanAllEntities(); }, nullptr);
	oTransitions[Event_t::StartGame][GameState::MainMenu] = Transition(GameState::InGame, [&](){ theWorld._systemManager.resume(); theWorld._mainMenu->enable(false);  theWorld.createLevel("Level1.txt"); }, nullptr);
	oTransitions[Event_t::GameOver][GameState::InGame] = Transition(GameState::Pause, [&](){ theWorld._systemManager.pause(); theWorld._gameOverMenu->enable(true); }, nullptr);
	oTransitions[Event_t::Pause][GameState::InGame] = Transition(GameState::Pause, [&](){ theWorld._systemManager.pause(); theWorld._inGameMenu->enable(true); }, nullptr);
	oTransitions[Event_t::Resume][GameState::Pause] = Transition(GameState::InGame, [&](){ theWorld._systemManager.resume(); theWorld._inGameMenu->enable(false); }, nullptr);
}
示例#19
0
//移进-规约搜索
void CDecoder::Search(string &result, float &maxscore)
{
	m_vState.clear();

	//初始化状态栈
	CState ini;
	InitState(ini);
	m_vState.push_back(ini);

	//移进规约2N-1步
	int steps = 2 * int(m_vToken.size()) - 1;
	for (int i = 0; i < steps; ++i)
	{
		vector<CState> buf;

		for (size_t j = 0; j < m_vState.size(); ++j)
		{
			map<string, double> scores;
			GetScores(m_vState[j], scores);	

			vector<string> ops;
			GetOps(m_vState[j], ops);

			for (size_t k = 0; k < ops.size(); ++k)
			{
				CState next;
				Transition(m_vState[j], scores, ops[k], next);
				
				buf.push_back(next);
			}
		}
	
		sort(buf.begin(), buf.end());

		//选出最好的N个状态
		m_vState.clear();

		int p = int(buf.size()) - 1;
		int cnt = 0;

		while (p >= 0 && cnt < m_nBeam)
		{
			m_vState.push_back(buf[p]);
			--p;
			++cnt;
		}
	}
    maxscore = m_vState[0].score;
	GetResult(m_vState[0], result);
}
示例#20
0
void
SpeechRecognition::ProcessEvent(SpeechEvent* aEvent)
{
  SR_LOG("Processing %s, current state is %s",
         GetName(aEvent),
         GetName(mCurrentState));

  if (mAborted && aEvent->mType != EVENT_ABORT) {
    // ignore all events while aborting
    return;
  }

  Transition(aEvent);
}
示例#21
0
void TopParser::next(TypeDef::Atom *atom)
 {
  TypeDef::State *state=topState();
  
  TypeDef::Rule *rule=Find(state->final->actions,atom);
  
  if( rule )
    {
     Printf(Exception,"App::TopParser::next(...) : rule mismatch");
    }
  
  if( atom ) 
    push(atom,Transition(state->transitions,atom));
  else
    check_result();
 }
/***********************************************************************
 *  Method: RobotController::cb_dumpSub
 *  Params: const global_planner::DumpMsg &msg
 * Returns: void
 * Effects: callback for dump messages
 ***********************************************************************/
bool RobotController::cb_dumpSub(global_planner::DumpSrv::Request  &req,
                                 global_planner::DumpSrv::Response &res)
{
    ROS_INFO("::::::::::::::: Received dump");
    DumpWrapper dumpWrapper;
    global_planner::DumpMsg dumpMsg = req.msg;
    dumpWrapper.SetData(dumpMsg);
    res.result = -1;
    // id = 0 if not a match, 1 if robot1 and 2 if robot 2
    int id = dumpWrapper.GetRobot1() == m_status.GetID() ? 1 : dumpWrapper.GetRobot2() == m_status.GetID() ? 2 : 0;

    //Check if this message is for you!
    if (id > 0)
    {
        ROS_DEBUG_STREAM("Received dump for me:\n"<<dumpWrapper.ToString());

        switch(m_status.GetState())
        {
            case RobotState::NAVIGATING:
                ROS_ERROR_STREAM("Currently navigating to waypoint, canceling waypoint.");
                SendWaypointFinished(TaskResult::FORCE_STOP);
                // continue on and do add new task also
            case RobotState::WAITING:
                m_moveBaseGoal = Conversion::PoseToMoveBaseGoal(id == 1 ? dumpWrapper.GetPose1() : dumpWrapper.GetPose2());
                ROS_INFO_STREAM("Received command to go to dump ("<<dumpWrapper.GetID()<<")");
                m_status.SetTaskID( dumpWrapper.GetID() );
                Transition(RobotState::DUMPING);
                res.result = 0;
            break;
            case RobotState::DUMPING:
                ROS_ERROR_STREAM("Currently navigating to dump, ignoring given new dump.");
                res.result = -1;
                //TODO: Cancel
            break;
            break;
            default:
                ROS_ERROR_STREAM("Dump hit: Robot is in state: " << RobotState::ToString(m_status.GetState()) <<", which should not be sent a dump message");
                res.result = -1;
            break;

        }
    }
    return true;
}
//-----------------------------------------------------------------------------------------------------------------------------------
void ChooseDrivingLessonScreen::AddInitialUI()
{
  MenuScreen::AddInitialUI();

  m_racetrackDescriptionContainer = new DescriptionUIContainer(GetDevice(), PlayerData::GetInstance().GetCurrentLicenseLevel());
  AddScreenUIObject(m_racetrackDescriptionContainer);

  for (size_t index = 0, licenseLevel = PlayerData::GetInstance().GetCurrentLicenseLevel(); index <= licenseLevel; index++)
  {
    RacetrackDescriptionUI* racetrackUI = new RacetrackDescriptionUI(GetDevice(), m_lessons[index].second);
    m_racetrackDescriptionContainer->AddDescriptionUI(racetrackUI);
  }

  Button* playButton = new Button(Vector2(GetScreenCentre().x, GetScreenDimensions().y * 0.9f), L"Go Race");
  playButton->SetClickFunction([this]()
  {
    std::string racetrackName(m_lessons[m_racetrackDescriptionContainer->GetCurrentUIIndex()].first);
    Transition(RacetrackScreenFactory::CreateRacetrack(GetScreenManager(), racetrackName));
  });
  AddScreenUIObject(playButton);
}
示例#24
0
文件: gogame.cpp 项目: kota7/gogamer
void Gogame::RemoveChain(unsigned int x, unsigned int y)
{
  // remove all stones connected to (x, y) and of the same color

  unsigned int color = board[y][x];

  // do nothing if the color is neither black nor white
  if (color != BL && color != WH) return;

  // remove this point
  board[y][x] = EM;
  if (color == BL) {
    b_captured++;
  } else {
    w_captured++;
  }

  // and record it in the transition field
  transitions.push_back(Transition(movenumber, x, y, -color, currentnode, false));


  // loop over the four adjacent point
  unsigned int xx;
  unsigned int yy;
  int increment;
  for (int k = 0; k < 4; k++)
  {
    increment = 2*(k % 2) - 1;
    if (k < 2) {
      xx = x + increment;
      yy = y;
    } else {
      xx = x;
      yy = y + increment;
    }

    if (board[yy][xx] == color) RemoveChain(xx, yy);
  }
}
/***********************************************************************
 *  Method: RobotController::cb_SetTrash
 *  Params:
 * Returns: void
 * Effects: Called to set the amount of storage used by robot
 ***********************************************************************/
bool RobotController::cb_SetTrash(global_planner::SetTrashSrv::Request  &req,
                                  global_planner::SetTrashSrv::Response &res)
{
    // If robot can hold requested trash, set it.
    if (m_status.GetStorageCapacity() >= req.storage)
    {
        m_status.SetStorageUsed(req.storage); // Set storage to requested storage

        // Horrible Hack due to service issues, need to have a binbot transition to waiting state once trash is transferred
        if (m_status.GetState() == RobotState::DUMPING_FINISHED && m_status.GetType() == RobotState::BIN_BOT)
        {
            ROS_INFO("TEMPORARY : Transition from DUMPING_FINISHED to WAITING due to trash loading");
            Transition(RobotState::WAITING);
        }

        res.result = 0; // Success
    }
    else
    {
        res.result = -1; // Failure
        return false;
    }
    return true;
}
/***********************************************************************
 *  Method: RobotController::cb_waypointSub
 *  Params: global_planner::WaypointSrv::Request &req, global_planner::WaypointSrv::Response &res
 * Returns: void
 * Effects: callback for waypoint messages
 ***********************************************************************/
bool RobotController::cb_waypointSub(global_planner::WaypointSrv::Request  &req,
                                     global_planner::WaypointSrv::Response &res)
{
    WaypointWrapper wpWrapper;
    global_planner::WaypointMsg wm= req.msg;
    wpWrapper.SetData(wm);
	// return -1 if not in valid state when this message is received
    res.result = -1;

    //Check if this message is for you!
    if (wpWrapper.GetRobot() == m_status.GetID())
    {
        ROS_DEBUG_STREAM("Received waypoint for me:\n"<<wpWrapper.ToString());

        switch(m_status.GetState())
        {
            case RobotState::DUMPING_FINISHED:
            case RobotState::WAITING:
                m_moveBaseGoal = Conversion::PoseToMoveBaseGoal(wpWrapper.GetPose());
                ROS_INFO_STREAM("Move to new waypoint ("<<wpWrapper.GetID()<<")");
                m_status.SetTaskID( wpWrapper.GetID() );
                Transition(RobotState::NAVIGATING);
                res.result = 0;
            break;
            case RobotState::WAITING_TAG_SPOTTED:
            case RobotState::NAVIGATING_TAG_SPOTTED:
                res.result = -1;
                ROS_ERROR_STREAM("Currently processing april tag... do not accept waypoint");
            break;
            default:
                ROS_ERROR_STREAM("Waypoint hit: Robot is in state: "<<RobotState::ToString(m_status.GetState())<<", which should not be sent a waypoint message");
                res.result = -1;
            break;
        }
    }
}
示例#27
0
static void merge( Instruction **init, const Vec<Instruction *> &l ) {
    if ( not l.size() )
        return;

    // predecessors
    for( unsigned n = 1; n < l.size(); ++n ) {
        for( const Transition &p : l[ n ]->prev ) {
            l[ 0 ]->prev << Transition( p.inst, p.rcitem );
            for( Transition &t : p.inst->next ) {
                if ( t.inst == l[ n ] ) {
                    t.inst = l[ 0 ];
                    break;
                }
            }
        }
    }

    // transitions
    for( unsigned n = 1; n < l.size(); ++n ) {
        for( const Transition &t : l[ n ]->next ) {
            t.inst->prev.remove_first_checking( [&]( const Transition &p ) {
                return p.inst == l[ n ];
            } );
        }
    }

    //
    if ( init and l.contains( *init ) )
        *init = l[ 0 ];

    // simplifications
    //    for( Transition &pp : res->predecessors )
    //        pp.inst->merge_transitions( false );
    //    res->merge_transitions( false );
    // res->merge_predecessors( init );
}
示例#28
0
文件: main.cpp 项目: CCJY/coliru
 virtual Transition find_alpha_transition(C alpha) override {
     return Transition(MappedSubstring(0, 0, 0), this->suffix_link);
 }
示例#29
0
文件: fsm.cpp 项目: jackscan/parlucid
template<typename T, typename O> void Fsm<T, O>::reduce()
{
	// remove transitions without output and to states without outgoing transitions
	/*for (int changed = 1; 0 < changed; --changed)
		for (size_t i = 0; i < transition_table.size(); ++i)
		{
			std::map<Char, Transition> new_transitions;
			for (typename std::map<Char, Transition>::const_iterator itt = transition_table[i].begin(); itt != transition_table[i].end(); ++itt)
				if (!this->transition_table[itt->second.nextState].empty() || !itt->second.output.empty())
					new_transitions.insert(*itt);
				else changed = 2;
			transition_table[i].swap(new_transitions);
		}*/

	//std::map<State,State> curr_map;
	std::vector<State> curr_map(this->transition_table.size());
	std::map<std::vector<bool>,std::set<State> > final_output_map;
	//typename std::map<State,std::map<T,State> >::const_iterator itt;
	//for(itt = transition_table.begin(); itt != transition_table.end(); itt = transition_table.upper_bound(itt->first))
	//	if(!this->final(itt->first))
	//		curr_map[itt->first] = 0;

	for(size_t i = 0; i < transition_table.size(); ++i)
		curr_map[static_cast<State>(i)] = 0;

	State state_counter = 1, last_state_counter = 0;

	// p = part state; t = terminal; n = new part state
	std::map<std::pair<State,std::map<Char,Transition> >,State> ptpn;
	typename std::map<std::pair<State,std::map<Char,Transition> >,State>::const_iterator iptpn;
	//std::vector<std::map<Char,Transition> > ptp;
	//std::vector<State> ptp_newpart;
	std::vector<State> next_map(this->transition_table.size());

	//const State invalidState = static_cast<State>(transition_table.size());

	while( state_counter != last_state_counter )
	{
		ptpn.clear();
		//ptp.clear();
		//ptp.resize(transition_table.size());

		//ptp.assign(transition_table.size(), std::map<Char,Transition>());
		//ptp_newpart.assign(transition_table.size(), invalidState);

		last_state_counter = state_counter;
		state_counter = 0;

		//typename std::map<State,State>::const_iterator isp;

		// build up part-transition table into ptpn
		//for(isp = curr_map.begin(); isp != curr_map.end(); ++isp)
		for(State state = 0; state < static_cast<State>(curr_map.size()); ++state)
		{
			std::pair<std::pair<State,Transitions>,State> ptp;
			ptp.first.first = curr_map[state];
			ptp.second = state_counter;
			//State part = curr_map[state];
			// building up transition table for this part
			//std::map<Char,Transition> tp;
			typename std::map<Char,Transition>::const_iterator its;
			for(its = transition_table[state].begin(); its != transition_table[state].end(); ++its)
				ptp.first.second[its->first] = Transition(curr_map[its->second.nextState], its->second.output);

			// looking for part with same outgoing transitions
			std::pair<typename std::map<std::pair<State,Transitions>,State>::iterator, bool> insResult =
				ptpn.insert(ptp);
			//if( (iptpn = ptpn.find(ptp)) != ptpn.end() )
			if (!insResult.second)
				// create state-new-part mapping in next map for this state
				next_map[state] = insResult.first->second;
				//next_map[state] = iptpn->second;
			else
				// insert new part-transition pair and assign new part
				next_map[state] = state_counter++;
				//ptpn[ptp] = next_map[state] = state_counter++;

		}

		// swap state->part mapping with new partitions
		curr_map.swap(next_map);
	}

	TransitionTable new_transition_table(state_counter);
	for(iptpn = ptpn.begin(); iptpn != ptpn.end(); ++iptpn)
		new_transition_table[iptpn->first.first] = iptpn->first.second;
		//transition_table.insert( iptpn->first );

	//ptp.resize(state_counter);

	transition_table.swap(new_transition_table);
	//transition_table.swap(ptp);
}
示例#30
0
文件: fsm.cpp 项目: jackscan/parlucid
template<typename T, typename O> void Fsm<T, O>::mergeDemux(const std::vector<Fsm<Char, Token> >& fsms)
{
	// todo: find way to make all alphabets equal
	this->alphabet = fsms.empty() ? Alphabet<Char>(): fsms[0].alphabet;
	// todo: handle different outputs
	this->tokenRange = Interval<Token>(1, 0);
	for (typename std::vector<Fsm<Char, Token> >::const_iterator iFsm = fsms.begin(); iFsm != fsms.end(); ++iFsm)
		if (this->tokenRange.empty()) this->tokenRange = iFsm->tokenRange;
		else
		{
			minimize(this->tokenRange.first, iFsm->tokenRange.first);
			maximize(this->tokenRange.last, iFsm->tokenRange.last);
		}

	//this->emptyOutput.reset();
	//this->emptyOutput.resize(this->tokenRange.last - this->tokenRange.first + 1, false);

	this->transition_table.clear();

	std::vector<std::map<State,State> > curr_map(fsms.size());

	State startStates = static_cast<State>(fsms.size());
	State state_counter = startStates;

	for(State f = 0; f < startStates; ++f)
		curr_map[f][static_cast<State>(0)] = f;

	for(State f = 0; f < startStates; ++f)
		for(State i = 1; i < fsms[f].getNumberOfStates(); ++i)
			curr_map[f][static_cast<State>(i)] = startStates;

	// p = part state; t = terminal; n = new part state
	std::map<std::pair<State,std::map<Char,Transition> >,State> ptpn;
	typename std::map<std::pair<State,std::map<Char,Transition> >,State>::const_iterator iptpn;

	//std::vector<bool> tmpOutput;

	bool partsChanged = true;
	do
	{
		ptpn.clear();
		state_counter = startStates;
		partsChanged = false;

		typename std::map<State,State>::const_iterator isp;

		// build up part-transition table into ptpn
		for(size_t f = 0; f < fsms.size(); ++f)
		{
			std::map<State,State> next_map;
			for(isp = curr_map[f].begin(); isp != curr_map[f].end(); ++isp)
			{
				State state = isp->first;
				State part = isp->second;
				// building up transition table for this part
				std::map<Char,Transition> tp;
				typename std::map<Char,Transition>::const_iterator its;
				for(its = fsms[f].transition_table[state].begin(); its != fsms[f].transition_table[state].end(); ++its)
					tp[its->first] = Transition(curr_map[f][its->second.nextState], its->second.output);
					//tp[its->first] = Transition(curr_map[f][its->second.nextState], transformOutput(its->second.output, fsms[f].getMinOutput() - this->getMinOutput(), tmpOutput));

				// looking for part with same outgoing transitions
				if( (iptpn = ptpn.find(std::make_pair(part,tp))) != ptpn.end() )
					// create state-new-part mapping in next map for this state
					next_map[state] = iptpn->second;
				else
				{
					// insert new part-transition pair and assign new part
					State newPart = state > 0 ? state_counter++ : static_cast<State>(f);
					ptpn[std::make_pair(part,tp)] = next_map[state] = newPart;
					partsChanged = partsChanged || newPart != part;
				}
			}
			// swap state->part mapping with new partitions
			curr_map[f].swap(next_map);
		}
	}
	while(partsChanged);

	this->transition_table.resize(state_counter);
	for(iptpn = ptpn.begin(); iptpn != ptpn.end(); ++iptpn)
		this->transition_table[iptpn->first.first] = iptpn->first.second;
}