Beispiel #1
0
/**
 * Callback event for page redirection
 *
 * @param embed - the mozilla object
 * @param uri - the new URL passed to the engine
 * @param parent - the parent instance for this callback
 *
 * @return true to stop redirection event, otherwise false
 */
gint GeckoEmbed::open_uri_cb(GtkMozEmbed *embed, const char *uri, GeckoEmbed& parent) {
	string target = uri;
	Rules *handler;
	// Determine which rules to run
	if (target.find("http:") == 0 
			|| target.find("https:") == 0 
			|| target.find("about:") == 0 
			|| target.find("ftp:") == 0) {
		cout << "applying remote rules" << endl;
		handler = new RemoteRules(parent.getConfig());
	}
	else if (target.find("file:") == 0) {
		cout << "applying local rules" << endl;
		handler = new LocalRules(parent.getConfig());
	}
	else if (target.find("javascript:") == 0) {
		cout << "applying javascript rules" << endl;
		handler = new JavascriptRules(parent.getConfig());
	}
	else {
		// URL support is limited to what the rules understand
		cout << "an unsupported url was passed to the rules engine" << endl;
		cout << "url string was: " << target << endl;
		exit(1);
	}
	handler->runRules(target);
	bool redirect = handler->isRedirectAllowed();
	delete handler;
	return !redirect;
}
Beispiel #2
0
// Construct the H-Curve of order k
LSystem::LSystem(Rules rules, std::string ax, uint k) : _order(k), _rules(rules), _axiom(ax) {
    
    // The production string begins as the axiom
    _production = _axiom;
    
    // For each Rule append the LHS to the nonTerminals String
    for (Rules::iterator R = rules.begin(); R != rules.end(); R++) {
        // (duplicates don't matter)
        _nonTerminals.append(1,R->first);
    }
    
    // Do exactly 'k' rewrites of the L-System
    for (int rewrites = 0; rewrites < _order; rewrites++) {
        rewrite(_production);
    }

    // Remove all occurrences of bad commands 
    while (findAndRemove(_production, "+-"));
    while (findAndRemove(_production, "-+"));
    while (findAndRemove(_production, "A"));
    while (findAndRemove(_production, "B"));
    
    // Slightly modify the user's L-System to work with a DawBug
    while (findAndReplace(_production, "F", "W$"));
    while (findAndReplace(_production, "$+", "+"));
    while (findAndReplace(_production, "$-", "-"));
}
Beispiel #3
0
bool Codeword::conforming(const Rules &rules) const
{
	if (!rules)
		return false;

	// Check pegs.
	for (int p = 0; p < rules.pegs(); ++p)
	{
		if (_digit[p] < 0)
			return false;
	}
	for (int p = rules.pegs(); p < MM_MAX_PEGS; ++p)
	{
		if (_digit[p] >= 0)
			return false;
	}

	// Check colors.
	if (!rules.repeatable())
	{
		for (int c = 0; c < rules.colors(); ++c)
		{
			if (_counter[c] > 1)
				return false;
		}
	}
	for (int c = rules.colors(); c < MM_MAX_COLORS; ++c)
	{
		if (_counter[c] > 0)
			return false;
	}
	return true;
}
Beispiel #4
0
void openInitial(Possibilities &possib, Rules &rules)
{
    for (Rules::iterator i = rules.begin(); i != rules.end(); i++) {
        Rule *r = *i;
        if (r->applyOnStart())
            r->apply(possib);
    }
}
bool Player:: checkWithRules(const int &index, const int &buttonX, const int &buttonY,const bool &playerNr,Pieces *gamePlane[][8]){
    Rules regler;
    return regler.checkRulesForType(pieces ,index, buttonX, buttonY,playerNr,gamePlane);


    //sedan skall regler kolla regler för pjäsen om den får flytta till buttonX och buttonY
    //om den får göra det retunera true annars false
}
void MainWindow::on_actionRules_triggered()
{
    if (Rules::opened)
        Rules::rulesDlg->activateWindow();
    else
    {
        Rules dlg;
        dlg.exec();
    }
}
Beispiel #7
0
Rules HPDBSCAN::localDBSCAN(const Space& space, const float epsilon, const size_t minPoints)
{
    const float      EPS2    = std::pow(epsilon, 2);
    
    const size_t lower = 0;
    const size_t upper = this->m_points.size();
    
    Rules rules;
    // local dbscan
    
    size_t cell = NOT_VISITED;
    std::vector<size_t> neighborPoints;
    
    
    #pragma omp parallel for schedule(dynamic, 500) private(neighborPoints) firstprivate(cell) reduction(merge: rules)
    for (size_t point = lower; point < upper; ++point)
    {
        size_t pointCell = this->m_points.cell(point);
        if (pointCell != cell)
        {
            neighborPoints = space.getNeighbors(pointCell);
            cell = pointCell;
        }
        std::vector<size_t> minPointsArea;
        ssize_t clusterId = NOISE;
        if(neighborPoints.size() >= minPoints)
        {
            clusterId =space.regionQuery(point, neighborPoints, EPS2, minPointsArea);
        }

        if (minPointsArea.size() >= minPoints)
        {
            this->m_points.cluster(point, clusterId, true);

            for (size_t other : minPointsArea)
            {
                ssize_t otherClusterId = this->m_points.cluster(other);
                if (this->m_points.corePoint(other))
                {
                    const std::pair<Cluster, Cluster> minmax = std::minmax(otherClusterId, clusterId);
                    rules.update(minmax.second, minmax.first);
                }
                this->m_points.cluster(other, clusterId, false);
            }
        }
        else if (this->m_points.cluster(point) == NOT_VISITED)
        {
            this->m_points.cluster(point, NOISE, false);
        }
    }
    
    
    return rules;
}
Beispiel #8
0
void RulesList::load()
{
    foreach(const QString filename, m_filenames.split(',') ) {
        qDebug() << "Loading rules from:" << filename;
        Rules *rules = new Rules(filename);
        m_rules.append(rules);
        rules->load();
        m_allrepositories.append(rules->repositories());
        QList<Rules::Match> matchRules = rules->matchRules();
        m_allMatchRules.append( QList<Rules::Match>(matchRules));
    }
}
Beispiel #9
0
void getHintsQty(Rules &rules, int &vert, int &horiz)
{
    vert = 0;
    horiz = 0;

    for (Rules::iterator i = rules.begin(); i != rules.end(); i++) {
        Rule::ShowOptions so = (*i)->getShowOpts();
        switch (so) {
            case Rule::SHOW_VERT: vert++; break;
            case Rule::SHOW_HORIZ: horiz++; break;
            default: ;
        }
    }
}
Beispiel #10
0
// Don't change this.  Make Read conform to it.
ostream &PylosBoard::Write(ostream &os) const {
   Rules rls = mRules;
   list<Move *>::const_iterator itr;
   int mvCount = EndianXfer((int)mMoveHist.size());

   rls.EndSwap();
   os.write((char *)&rls, sizeof(rls));

   os.write((char *)&mvCount, sizeof(mvCount));
   for (itr = mMoveHist.begin(); itr != mMoveHist.end(); itr++)
      os << **itr;

   return os;
}
Beispiel #11
0
ostream &CheckersBoard::Write(ostream &os) const { 
   Rules rules = mRules;
   list<Move *>::const_iterator iter;
   int moveCount = EndianXfer((int)mMoveHist.size());

   rules.EndSwap();
   os.write((char *)&rules, sizeof(rules));

   os.write((char *)&moveCount, sizeof(moveCount));
   for (iter = mMoveHist.begin(); iter != mMoveHist.end(); iter++)
      os << **iter;

   return os;
}
bool Player:: CanIMoveKing(bool lose, Pieces *gamePlane[][8], const bool &playerNr){
    int kingX = 0;
    int kingY = 0;
    int index = 0;
    Rules haveILost;
    getKingsXAndYPos(kingX,kingY);
    index = getPieceIndexWithValues(kingX,kingY);
    // om den är innanför spelplanen
    lose = true;
    if(kingX+1 < 8){
        //kolla om han kan gå dit om
        if(haveILost.checkRulesForType(pieces,index,kingX+1,kingY,playerNr,gamePlane)){
            lose = false;
        }
    }
    if(kingX-1 >= 0){
        if(haveILost.checkRulesForType(pieces,index,kingX-1,kingY,playerNr,gamePlane)){
            lose = false;
        }
    }
    if(kingY+1 < 8){
        if(haveILost.checkRulesForType(pieces,index,kingX,kingY+1,playerNr,gamePlane)){
            lose = false;
        }
    }
    if(kingY-1 >= 0){
        if(haveILost.checkRulesForType(pieces,index,kingX,kingY-1,playerNr,gamePlane)){
            lose = false;
        }
    }
    if(kingX+1 < 8 && kingY < 8){
        if(haveILost.checkRulesForType(pieces,index,kingX+1,kingY+1,playerNr,gamePlane)){
            lose = false;
        }
    }
    if(kingX+1 < 8 && kingY-1 >= 0){
        if(haveILost.checkRulesForType(pieces,index,kingX+1,kingY-1,playerNr,gamePlane)){
            lose = false;
        }
    }
    if(kingX-1 >= 0 && kingY+1 < 8){
        if(haveILost.checkRulesForType(pieces,index,kingX-1,kingY+1,playerNr,gamePlane)){
            lose = false;
        }
    }
    if(kingX-1 >= 0 && kingY-1 >= 0){
        if(haveILost.checkRulesForType(pieces,index,kingX-1,kingY-1,playerNr,gamePlane)){
            lose = false;
        }
    }
    return lose;
}
Beispiel #13
0
/**
 * Internal Operations
 */
void HPDBSCAN::applyRules(const Rules& rules)
{
    #pragma omp parallel for
    for (size_t i = 0; i < this->m_points.size(); ++i)
    {
        const bool core    = this->m_points.corePoint(i);
        ssize_t    cluster = this->m_points.cluster(i);
        ssize_t    found   = rules.rule(cluster);
        
        while (found < NOISE)
        {
            cluster = found;
            found   = rules.rule(found);
        }
        this->m_points.overrideCluster(i, cluster, core);
    }
}
Beispiel #14
0
static void removeRules(SolvedPuzzle &puzzle, Rules &rules)
{
    bool possible;
    
    do {
        possible = false;
        for (Rules::iterator i = rules.begin(); i != rules.end(); i++) {
            Rule *rule = *i;
            Rules excludedRules = rules;
            excludedRules.remove(rule);
            if (canSolve(puzzle, excludedRules)) {
                possible = true;
                rules.remove(rule);
                delete rule;
                break;
            }
        }
    } while (possible);
}
Beispiel #15
0
TEST(Rules, reference) {
    Rules r { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, { 358, 288, 2 } };

    ASSERT_EQ(r[0], (Rule {1, 2, 3}));
    ASSERT_EQ(r[1], (Rule {4, 5, 6}));
    ASSERT_EQ(r[2], (Rule {7, 8, 9}));
    ASSERT_EQ(r.size(), size_t(4));

    swap(r[0], r[1]);
    ASSERT_EQ(r[0], (Rule {4, 5, 6}));
    ASSERT_EQ(r[1], (Rule {1, 2, 3}));

    std::sort(r.begin(), r.end(), rule_compare {});

    ASSERT_EQ(r[0], (Rule {1, 2, 3}));
    ASSERT_EQ(r[1], (Rule {4, 5, 6}));
    ASSERT_EQ(r[2], (Rule {7, 8, 9}));
    ASSERT_EQ(r.size(), size_t(4));

}
Beispiel #16
0
int Rules::loadAllRules()
{
    vector<string> rulesFiles = JFileSystem::GetInstance()->scanfolder("rules");
    for (size_t i = 0; i < rulesFiles.size(); ++i)
    {
        Rules * rules = NEW Rules();
        if (rules->load(rulesFiles[i]))
        {
            RulesList.push_back(rules);
        }
        else
        {
            SAFE_DELETE(rules);
        }
    }
    //Kind of a hack here, we sort Rules alphabetically because it turns out to be matching
    // The historical order of Game modes: Classic, Momir Basic, Random 1, Random 2, Story
    std::sort(RulesList.begin(),RulesList.end(),RulesMenuCmp_);
    return 1;
}
int main(int argc, char* argv[])
{
    int topK;
	if (argc != 5 || sscanf(argv[4], "%d", &topK) != 1) {
        cerr << argc << endl;
        for (int i = 1; i < argc; ++ i) {
            cerr << argv[i] << endl;
        }
		fprintf(stderr, "[usage] <training/testing data, csv format> <selected rules> <new training/testing data, csv format> <top-K>\n");
		return -1;
	}
	//cerr << "top-K = " << topK << endl;
	int dimension = loadFeatureMatrix(argv[1]);
	Rules rules;
	rules.load(argv[2]);

    rules.resize(topK);

	FILE* out = tryOpen(argv[3], "w");
	fprintf(out, "label");
	for (int i = 0; i < rules.size(); ++ i) {
	    fprintf(out, ",rule_%s", rules[i].showup().c_str());
	}
	fprintf(out, "\n");
	vector<int> sum(rules.size(), 0);
	for (int i = 0; i < train.size(); ++ i) {
	    fprintf(out, "%d", (int)trainY[i]);
	    for (int j = 0; j < rules.size(); ++ j) {
            int sat = rules[j].isSatisfiedBy(train[i]);
	        fprintf(out, ",%d", sat);
	        sum[j] += sat;
	    }
	    fprintf(out, "\n");
	}
	fclose(out);

    string filename = argv[1];
	if (filename.find("train") != -1) {
        bool flag = false;
        for (int i = 0; i < rules.size(); ++ i) {
            if (rules[i].satisfiedTrainings.size() != sum[i]) {
                fprintf(stderr, "[Warning] rule %d, %d v.s. %d\n", i, rules[i].satisfiedTrainings.size(), sum[i]);
                flag = true;
            }
        }
        if (!flag) {
            //fprintf(stderr, "Self-check passed!\n");
			;
        } else {
            fprintf(stderr, "Oooooooooooooooooops! You found some troubles!\n");
        }
    }

	return 0;
}
Beispiel #18
0
static void genRules(SolvedPuzzle &puzzle, Rules &rules)
{
    bool rulesDone = false;

    do {
        Rule *rule = genRule(puzzle);
        if (rule) {
            std::wstring s = rule->getAsText();
            for (std::list<Rule*>::iterator i = rules.begin(); 
                    i != rules.end(); i++) 
                if ((*i)->getAsText() == s) {
                    delete rule;
                    rule = NULL;
                    break;
                }
            if (rule) {
//printf("adding rule %s\n", rule->getAsText().c_str());
                rules.push_back(rule);
                rulesDone = canSolve(puzzle, rules);
            }
        }
    } while (! rulesDone);
}
Beispiel #19
0
TEST(Rules, iterator) {
    Rules             a { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, { 358, 288, 2 } };
    std::vector<Rule> b { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, { 358, 288, 2 } };

    Rule r { 0, 0, 0 };

    {
        int ra = a.end() - a.begin();
        int rb = b.end() - b.begin();
        ASSERT_EQ(ra, rb);
    };

    {
        auto ra = a.end() - 1;
        auto rb = b.end() - 1;
        ASSERT_EQ((Rule { 358, 288, 2}), *ra);
        ASSERT_EQ((Rule { 358, 288, 2}), *rb);
    };

    {
        for (Rules::reference x : a) {
            x = r;
        }
        for (Rule& x : b) {
            x = r;
        }

        for (Rules::reference x : a) {
            ASSERT_EQ(x, r);
        }
        for (Rule& x : b) {
            ASSERT_EQ(x, r);
        }
    };

}
Beispiel #20
0
static bool canSolve(SolvedPuzzle &puzzle, Rules &rules)
{
    Possibilities pos;
    bool changed = false;
    
    do {
        changed = false;
        for (Rules::iterator i = rules.begin(); i != rules.end(); i++) {
            Rule *rule = *i;
            if (rule->apply(pos)) {
                changed = true;
                if (! pos.isValid(puzzle)) {
std::cout << "after error:" << std::endl;
pos.print();
                    throw Exception(L"Invalid possibilities after rule " +
                        rule->getAsText());
                }
            }
        }
    } while (changed);

    bool res = pos.isSolved();
    return res;
}
Beispiel #21
0
std::pair<Validity, std::string>
checkValidity(HashRouter& router,
    STTx const& tx, Rules const& rules,
        Config const& config)
{
    auto const allowMultiSign =
        rules.enabled(featureMultiSign);

    auto const id = tx.getTransactionID();
    auto const flags = router.getFlags(id);
    if (flags & SF_SIGBAD)
        // Signature is known bad
        return {Validity::SigBad, "Transaction has bad signature."};

    if (!(flags & SF_SIGGOOD))
    {
        // Don't know signature state. Check it.
        auto const sigVerify = tx.checkSign(allowMultiSign);
        if (! sigVerify.first)
        {
            router.setFlags(id, SF_SIGBAD);
            return {Validity::SigBad, sigVerify.second};
        }
        router.setFlags(id, SF_SIGGOOD);
    }

    // Signature is now known good
    if (flags & SF_LOCALBAD)
        // ...but the local checks
        // are known bad.
        return {Validity::SigGoodOnly, "Local checks failed."};

    if (flags & SF_LOCALGOOD)
        // ...and the local checks
        // are known good.
        return {Validity::Valid, ""};

    // Do the local checks
    std::string reason;
    if (!passesLocalChecks(tx, reason))
    {
        router.setFlags(id, SF_LOCALBAD);
        return {Validity::SigGoodOnly, reason};
    }
    router.setFlags(id, SF_LOCALGOOD);
    return {Validity::Valid, ""};
}
Beispiel #22
0
const sMinMaxResult		MinMax<T>::eval(IBoard &board, const Rules &rules, const sMinMaxState &minMaxState, const IEval &evalFunction)
{

	if (minMaxState.depth == 0
		|| rules.gameEnded(board, minMaxState.lastStroke, minMaxState.captures[0], minMaxState.captures[1]) != common::eCell::E_CELL)
		return (((sMinMaxResult)
			{
				minMaxState.lastStroke
				, evalFunction.eval(board, rules, minMaxState)
			}));

	uint8_t					nCaptures(0);
	uint16_t				captures(0);
	sMinMaxResult			result;

	result.value = T::initialValue;

	uint8_t		alpha(minMaxState.alphaBeta[0]);
	uint8_t		beta(minMaxState.alphaBeta[1]);

	// Use iterator instead
	uint8_t		size = board.getSize();
	for (uint8_t i = 0; i < size; ++i)
	{
		for (uint8_t j = 0; j < size; ++j)
		{
			if (board.getHitBoard({i, j}) == false
				|| !rules.isValid(board, {i, j}, minMaxState.currentPlayer))
				continue ;

			board.setCell({i, j}, minMaxState.currentPlayer);
			nCaptures = rules.applyCapture(board, {i, j}, captures);

			const auto &next = T::search(
				board, rules
				, {
					(uint8_t)(minMaxState.depth - 1), !minMaxState.maximizing, OPPONENT(minMaxState.currentPlayer)
					, {i, j}
					, {
						(uint8_t)(minMaxState.currentPlayer == common::eCell::P1 ? minMaxState.captures[0] + nCaptures : minMaxState.captures[0])
						, (uint8_t)(minMaxState.currentPlayer == common::eCell::P1 ? minMaxState.captures[1] : minMaxState.captures[1] + nCaptures)
					}
					, {alpha, beta}
				}
				, evalFunction);

			rules.undoCapture(board, {i, j}, captures, OPPONENT(minMaxState.currentPlayer));
			board.setCell({i, j}, common::eCell::NONE);

			if (T::compareValues(next.value, result.value))
			{
				result.coord = {i, j};
				result.value = next.value;
			}

			if (T::alphaBetaComp(result.value, alpha, beta))
				return (result);
			T::setAlphaBeta(result.value, alpha, beta);
		}
	}
	return (result);
};
bool Player:: CanISaveKing(bool lose, Pieces *gamePlane[][8], const bool &playerNr, Player &enemy){
    int myKingX;
    int myKingY;
    getKingsXAndYPos(myKingX, myKingY);
    Rules lastTimeToCheck;
    //dags att kolla typeId på platsen i gamePlane så vi vet hur och vad vi ska kolla om det är ett torn
    //tex så kan man ta tornet eller ställa sig ivägen skippar att kolla om en bonde gjorde schack drag eftersom
    //Då kan kungen bara gå och ta den
    if(typeid(*gamePlane[this->schackedFromX][this->schackedFromY]) == typeid(Tower)){
        //om det är ett torn kan någon gå till hans posetion eller någon posetion där imellan för att avbryta schack
        for(int i = 0; i<16; i++){
            bool heCanLose = false;
            if(pieces[i] != NULL && typeid(pieces[i]) != typeid(King)){
                if(lastTimeToCheck.checkRulesForType(pieces,i,this->schackedFromX,this->schackedFromY,playerNr,gamePlane)){
                    //om någon pjäs kan gå till pjäsens posetion som gjorde schackdraget så är det inte lose
                    pieces[i]->setRestrictMovment(true);//då kan denna pjäs röra på sig
                    heCanLose = true;
                    //return false;
                }
                else{
                    //annars kolla om någon pjäs kan gå imellan sin egen kung och andra spelarens torn
                    if(myKingX < this->schackedFromX){
                    //så om min kungs x och y värde är mindre än enemy tornets x och y värden
                    //Dvs att tornet går nerifrån och upp
                        for(int j = myKingX+1; j<this->schackedFromX; j++){//kolar alla steg från kungens X+1 upp till tornets X-1
                            // om en pjäs kan gå mellan kungens x värde eller tornetsX värde så lose = false;
                            if(lastTimeToCheck.checkRulesForType(pieces, i,j,myKingY,playerNr,gamePlane)){
                                pieces[i]->setRestrictMovment(true);//då kan denna pjäs röra på sig
                                heCanLose = true;
                                //return false;
                            }
                        }
                    }
                    if(myKingX > this->schackedFromX){
                        for(int j = myKingX-1; j>this->schackedFromX; j--){//kolar alla steg från kungens X-1 upp till tornets X-1
                            // om en pjäs kan gå mellan kungens x värde eller tornetsX värde så lose = false;
                            if(lastTimeToCheck.checkRulesForType(pieces, i,j,myKingY,playerNr,gamePlane)){
                                pieces[i]->setRestrictMovment(true);//då kan denna pjäs röra på sig
                                heCanLose = true;
                                //return false;
                            }
                        }
                    }
                    if(myKingY < this->schackedFromY){
                        for(int j = myKingY+1; j<this->schackedFromY; j++){//kolar alla steg från kungens y+1 upp till tornets X-1
                            // om en pjäs kan gå mellan kungens x värde eller tornetsX värde så lose = false;
                            if(lastTimeToCheck.checkRulesForType(pieces, i,myKingX,j,playerNr,gamePlane)){
                                pieces[i]->setRestrictMovment(true);//då kan denna pjäs röra på sig
                                heCanLose = true;
                                //return false;
                            }
                        }
                    }
                    if(myKingY > this->schackedFromY){
                        for(int j = myKingY-1; j>this->schackedFromY; j--){//kolar alla steg från kungens y-1 upp till tornets X-1
                            // om en pjäs kan gå mellan kungens x värde eller tornetsX värde så lose = false;
                            if(lastTimeToCheck.checkRulesForType(pieces, i,myKingX,j,playerNr,gamePlane)){
                                pieces[i]->setRestrictMovment(true);//då kan denna pjäs röra på sig
                                heCanLose = true;
                                //return false;
                            }
                        }
                    }
                    if(heCanLose != true && typeid(pieces[i]) != typeid(King)){
                        lose = true;//om man inte lyckas rädda kungen om ett torn satte dig i shack lose = true
                        pieces[i]->setRestrictMovment(false);//då kan denna pjäs röra på sig
                    }
                }
            }
            else{
                lose = true;
            }
        }
        for(int i=0; i<16; i++){
            if(pieces[i] != NULL){
                if(pieces[i]->isItRestrictedOrNot()){
                    return false;
                }
            }
        }
        return lose;
    }
    else if(typeid(*gamePlane[this->schackedFromX][this->schackedFromY]) == typeid(Horse)){
        for(int i = 0; i<16; i++){
            if(pieces[i] != NULL && typeid(pieces[i]) != typeid(King)){
                if(lastTimeToCheck.checkRulesForType(pieces,i,this->schackedFromX,this->schackedFromY,playerNr,gamePlane)){
                    //om någon pjäs kan gå till pjäsens posetion som gjorde schackdraget så är det inte lose
                    pieces[i]->setRestrictMovment(true);//då kan denna pjäs röra på sig
                    //return false;
                }
                else{
                    lose = true;
                    pieces[i]->setRestrictMovment(false);//då kan denna pjäs röra på sig
                }
            }
            else{
                lose = true;
            }
        }
        for(int i=0; i<16; i++){
            if(pieces[i] != NULL){
                if(pieces[i]->isItRestrictedOrNot()){
                    return false;
                }
            }
        }
        return lose;
    }
    else if(typeid(*gamePlane[this->schackedFromX][this->schackedFromY]) == typeid(Bishop)){
        for(int i = 0; i<16; i++){
            bool heCanMove = false;
            if(pieces[i] != NULL && typeid(pieces[i]) != typeid(King)){
                if(lastTimeToCheck.checkRulesForType(pieces,i,this->schackedFromX,this->schackedFromY,playerNr,gamePlane)){
                    //om någon pjäs kan gå till pjäsens posetion som gjorde schackdraget så är det inte lose
                    pieces[i]->setRestrictMovment(true);//då kan denna pjäs röra på sig
                    heCanMove = true;
                    //return false;
                }
                else{
                    if(myKingX > this->schackedFromX && myKingY > this->schackedFromY){
                        // <--------- och upp i spelplanen
                        int y = myKingY-1;
                        for(int j = myKingX-1; j>schackedFromX; j--){
                            if(lastTimeToCheck.checkRulesForType(pieces,i,j,y,playerNr,gamePlane)){
                                pieces[i]->setRestrictMovment(true);//då kan denna pjäs röra på sig
                                heCanMove = true;
                                //return false;
                            }
                            y--;
                        }
                    }
                    if(myKingX > this->schackedFromX && myKingY < this->schackedFromY){
                        //<---------- ner i spelplanen
                        int y = myKingY+1;
                        for(int j = myKingX-1; j>schackedFromX; j--){
                            if(lastTimeToCheck.checkRulesForType(pieces,i,j,y,playerNr,gamePlane)){
                                pieces[i]->setRestrictMovment(true);//då kan denna pjäs röra på sig
                                heCanMove = true;
                                //return false;
                            }
                            y++;
                        }
                    }
                    if(myKingX < this->schackedFromX && myKingY > this->schackedFromY){
                        //-----------> och upp i spelplanen
                        int y = myKingY-1;
                        for(int j = myKingX+1; j<schackedFromX; j++){
                            if(lastTimeToCheck.checkRulesForType(pieces,i,j,y,playerNr,gamePlane)){
                                pieces[i]->setRestrictMovment(true);//då kan denna pjäs röra på sig
                                heCanMove = true;
                                //return false;
                            }
                            y--;
                        }
                    }
                    if(myKingX < this->schackedFromX && myKingY < this->schackedFromY){
                        //-----------> och ner i spelplanen
                        int y = myKingY+1;
                        for(int j = myKingX+1; j<schackedFromX; j++){
                            if(lastTimeToCheck.checkRulesForType(pieces,i,j,y,playerNr,gamePlane)){
                                pieces[i]->setRestrictMovment(true);//då kan denna pjäs röra på sig
                                heCanMove = true;
                                //return false;
                            }
                            y++;
                        }
                    }
                    if(heCanMove != true && typeid(pieces[i]) != typeid(King))
                        lose = true;
                        pieces[i]->setRestrictMovment(false);//då kan denna pjäs röra på sig
                    }
                }//if NULL
            else{
                lose = true;
            }
        }//for
        for(int i=0; i<16; i++){
            if(pieces[i] != NULL){
                if(pieces[i]->isItRestrictedOrNot()){
                    return false;
                }
            }
        }
        return lose;
    }
    else if(typeid(*gamePlane[this->schackedFromX][this->schackedFromY]) == typeid(Queen)){
        for(int i = 0; i<16; i++){
            bool heCanMove = false;
            if(pieces[i] != NULL && typeid(pieces[i]) != typeid(King)){
                if(lastTimeToCheck.checkRulesForType(pieces,i,this->schackedFromX,this->schackedFromY,playerNr,gamePlane)){
                    //om någon pjäs kan gå till pjäsens posetion som gjorde schackdraget så är det inte lose
                    pieces[i]->setRestrictMovment(true);//då kan denna pjäs röra på sig
                    heCanMove = true;
                    //return false;
                }
                else{
                    if(myKingX < this->schackedFromX){
                        //så om min kungs x och y värde är mindre än enemy tornets x och y värden
                        //Dvs att tornet går nerifrån och upp
                        for(int j = myKingX+1; j<this->schackedFromX; j++){//kolar alla steg från kungens X+1 upp till tornets X-1
                            // om en pjäs kan gå mellan kungens x värde eller tornetsX värde så lose = false;
                            if(lastTimeToCheck.checkRulesForType(pieces, i,j,myKingY,playerNr,gamePlane)){
                                pieces[i]->setRestrictMovment(true);//då kan denna pjäs röra på sig
                                heCanMove = true;
                                //return false;
                            }
                        }
                    }
                    if(myKingX > this->schackedFromX){
                        for(int j = myKingX-1; j>this->schackedFromX; j--){//kolar alla steg från kungens X-1 upp till tornets X-1
                            // om en pjäs kan gå mellan kungens x värde eller tornetsX värde så lose = false;
                            if(lastTimeToCheck.checkRulesForType(pieces, i,j,myKingY,playerNr,gamePlane)){
                                pieces[i]->setRestrictMovment(true);//då kan denna pjäs röra på sig
                                heCanMove = true;
                                //return false;
                            }
                        }
                    }
                    if(myKingY < this->schackedFromY){
                        for(int j = myKingY+1; j<this->schackedFromY; j++){//kolar alla steg från kungens y+1 upp till tornets X-1
                            // om en pjäs kan gå mellan kungens x värde eller tornetsX värde så lose = false;
                            if(lastTimeToCheck.checkRulesForType(pieces, i,myKingX,j,playerNr,gamePlane)){
                                pieces[i]->setRestrictMovment(true);//då kan denna pjäs röra på sig
                                heCanMove = true;
                                //return false;
                            }
                        }
                    }
                    if(myKingY > this->schackedFromY){
                        for(int j = myKingY-1; j>this->schackedFromY; j--){//kolar alla steg från kungens y-1 upp till tornets X-1
                            // om en pjäs kan gå mellan kungens x värde eller tornetsX värde så lose = false;
                            if(lastTimeToCheck.checkRulesForType(pieces, i,myKingX,j,playerNr,gamePlane)){
                                pieces[i]->setRestrictMovment(true);//då kan denna pjäs röra på sig
                                heCanMove = true;
                                //return false;
                            }
                        }
                    }
                    if(myKingX > this->schackedFromX && myKingY > this->schackedFromY){
                        // <--------- och upp i spelplanen
                        int y = myKingY-1;
                        for(int j = myKingX-1; j>schackedFromX; j--){
                            if(lastTimeToCheck.checkRulesForType(pieces,i,j,y,playerNr,gamePlane)){
                                pieces[i]->setRestrictMovment(true);//då kan denna pjäs röra på sig
                                heCanMove = true;
                                //return false;
                            }
                            y--;
                        }
                    }
                    if(myKingX > this->schackedFromX && myKingY < this->schackedFromY){
                        //<---------- ner i spelplanen
                        int y = myKingY+1;
                        for(int j = myKingX-1; j>schackedFromX; j--){
                            if(lastTimeToCheck.checkRulesForType(pieces,i,j,y,playerNr,gamePlane)){
                                pieces[i]->setRestrictMovment(true);//då kan denna pjäs röra på sig
                                heCanMove = true;
                                //return false;
                            }
                            y++;
                        }
                    }
                    if(myKingX < this->schackedFromX && myKingY > this->schackedFromY){
                        //-----------> och upp i spelplanen
                        int y = myKingY-1;
                        for(int j = myKingX+1; j<schackedFromX; j++){
                            if(lastTimeToCheck.checkRulesForType(pieces,i,j,y,playerNr,gamePlane)){
                                pieces[i]->setRestrictMovment(true);//då kan denna pjäs röra på sig
                                heCanMove = true;
                                //return false;
                            }
                            y--;
                        }
                    }
                    if(myKingX < this->schackedFromX && myKingY < this->schackedFromY){
                        //-----------> och ner i spelplanen
                        int y = myKingY+1;
                        for(int j = myKingX+1; j<schackedFromX; j++){
                            if(lastTimeToCheck.checkRulesForType(pieces,i,j,y,playerNr,gamePlane)){
                                pieces[i]->setRestrictMovment(true);//då kan denna pjäs röra på sig
                                heCanMove = true;
                                //return false;
                            }
                            y++;
                        }
                    }
                    if(heCanMove != true && typeid(pieces[i]) != typeid(King)){
                     pieces[i]->setRestrictMovment(false);//då kan denna pjäs röra på sig
                     lose = true;
                    }
                }//else
            }
            else{
                lose = true;
            }
        }//for
        for(int i=0; i<16; i++){
            if(pieces[i] != NULL){
                if(pieces[i]->isItRestrictedOrNot()){
                    return false;
                }
            }
        }
        return lose;
    }//queen
    else{
        for(int i=0; i<16; i++){
            if(pieces[i] != NULL){
                if(pieces[i]->isItRestrictedOrNot()){
                    return false;
                }
            }
        }
        lose = true;
        return lose;
    }
}
Beispiel #24
0
ItemTreePtr AtomIntroductionSolver::compute()
{
	const auto nodeStackElement = app.getPrinter().visitNode(decomposition);

	assert(decomposition.getChildren().size() == 1);
	Decomposition& childNode = **decomposition.getChildren().begin();
	ItemTreePtr childResult = childNode.getSolver().compute();
	ItemTreePtr result;

	if(childResult) {
		result = extendRoot(childResult);
		assert(childResult->getChildren().empty() == false);

		// Find out which rules are satisfied by setting introducedAtom to true or false, respectively, and which disappear from the reduct by setting introducedAtom to true.
		// TODO unordered_set?
		Rules rulesSatisfiedByTrue;
		Rules rulesSatisfiedByFalse;
		Rules rulesDisappearingByTrue;
		for(String bagElement : decomposition.getNode().getBag()) {
			AtomsInRule::const_iterator it = heads.find(bagElement);
			if(it != heads.end() && it->second.find(introducedAtom) != it->second.end())
				rulesSatisfiedByTrue.insert(bagElement);
			it = positiveBody.find(bagElement);
			if(it != positiveBody.end() && it->second.find(introducedAtom) != it->second.end())
				rulesSatisfiedByFalse.insert(bagElement);
			it = negativeBody.find(bagElement);
			if(it != negativeBody.end() && it->second.find(introducedAtom) != it->second.end()) {
				rulesSatisfiedByTrue.insert(bagElement);
				rulesDisappearingByTrue.insert(bagElement);
			}
		}

		// Guess node to extend at depth 1
		for(const ItemTreePtr& childCandidate : childResult->getChildren()) {
			// Make introducedAtom false
			ItemTreeNode::Items candidateItems = childCandidate->getNode()->getItems();
			ItemTreeNode::Items candidateAuxItems = childCandidate->getNode()->getAuxItems();
			// Add satisfied rules
			candidateAuxItems.insert(rulesSatisfiedByFalse.begin(), rulesSatisfiedByFalse.end());
			ItemTreePtr candidate = extendCandidate(std::move(candidateItems), std::move(candidateAuxItems), childCandidate);

			for(const ItemTreePtr& childCertificate : childCandidate->getChildren()) {
				ItemTreeNode::Items certificateItems = childCertificate->getNode()->getItems();
				ItemTreeNode::Items certificateAuxItems = childCertificate->getNode()->getAuxItems();
				// Add satisfied rules
				certificateAuxItems.insert(rulesSatisfiedByFalse.begin(), rulesSatisfiedByFalse.end());
				candidate->addChildAndMerge(extendCertificate(std::move(certificateItems), std::move(certificateAuxItems), childCertificate));
			}
			result->addChildAndMerge(std::move(candidate));

			// Make introducedAtom true
			candidateItems = childCandidate->getNode()->getItems();
			candidateItems.insert(introducedAtom);
			candidateAuxItems = childCandidate->getNode()->getAuxItems();
			// Add satisfied rules
			candidateAuxItems.insert(rulesSatisfiedByTrue.begin(), rulesSatisfiedByTrue.end());
			candidate = extendCandidate(std::move(candidateItems), std::move(candidateAuxItems), childCandidate);

			for(const ItemTreePtr& childCertificate : childCandidate->getChildren()) {
				// Make introducedAtom false in certificate (and add "smaller" flag)
				ItemTreeNode::Items certificateItems = childCertificate->getNode()->getItems();
				ItemTreeNode::Items certificateAuxItems = childCertificate->getNode()->getAuxItems();
				certificateAuxItems.emplace("smaller");
				certificateAuxItems.insert(rulesDisappearingByTrue.begin(), rulesDisappearingByTrue.end());
				certificateAuxItems.insert(rulesSatisfiedByFalse.begin(), rulesSatisfiedByFalse.end());
				candidate->addChildAndMerge(extendCertificate(std::move(certificateItems), std::move(certificateAuxItems), childCertificate));

				// Make introducedAtom true in certificate
				certificateItems = childCertificate->getNode()->getItems();
				certificateItems.insert(introducedAtom);
				certificateAuxItems = childCertificate->getNode()->getAuxItems();
				certificateAuxItems.insert(rulesSatisfiedByTrue.begin(), rulesSatisfiedByTrue.end());
				candidate->addChildAndMerge(extendCertificate(std::move(certificateItems), std::move(certificateAuxItems), childCertificate));
			}

			result->addChildAndMerge(std::move(candidate));
		}

		assert(!decomposition.isRoot());
		if(result->finalize(app, false, app.isPruningDisabled() == false || decomposition.isRoot()) == false)
			result.reset();
	}

	app.getPrinter().solverInvocationResult(decomposition, result.get());

	return result;
}
/**
 * Estimates an obvious lower-bound of the cost of making a non-possible
 * guess against a set of remaining possibilities. If such a lower-bound
 * is found, returns the minimum steps, depth, and worst count. If no
 * lower-bound can be found easily, returns zero.
 */
StrategyCost estimate_obvious_lowerbound(
	const Rules &rules,
	CodewordConstRange possibilities)
{
	// We are only concerned with a handful of remaining possibilities.
	// If there are too many, we won't make an attempt.
	int p = rules.pegs();
	int n = (int)possibilities.size();
	if (n > p*(p+3)/2)
		return StrategyCost();

	// Partition the possibilities by the colors they contain. Only the
	// size of the partitions matter; the particular colors don't.
	// @todo Since we will only be processing with MM_MAX_PEGS+1 groups,
	// we can return -1 if there are more secret groups.
	const int M = MM_MAX_PEGS * (MM_MAX_PEGS + 3) / 2;
	bool visited[M] = { false };
	int group[M] = { 0 };
	int ngroup = 0;
	for (int i = 0; i < n; ++i)
	{
		if (!visited[i])
		{
			for (int j = i + 1; j < n; ++j)
			{
				if (!visited[j] && contain_same_colors(possibilities[i], possibilities[j]))
				{
					++group[ngroup];
					visited[j] = true;
				}
			}
			++ngroup;
		}
	}

	// Now we have classified the remaining possibilities into ngroup groups
	// according to the colors they contain. For any given guess, the secrets
	// in the same group must have the same number of common colors with
	// this guess.

	// We next classify the possible feedback values by the number of common
	// colors, like below:
	//   0: 0A0B
	//   1: 0A1B 1A0B
	//   2: 0A2B 1A1B 2A0B
	//   3: 0A3B 1A2B 2A1B 3A0B
	//   4: 0A4B 1A3B 2B2B - -
	// Note that 3A1B is impossible and 4A0B is excluded because the guess is
	// assumed to be outside the remaining possibilities.

	// Next, we assign each secret group a feedback group. Note that multiple
	// secret groups may be assigned the same feedback group, but two secrets
	// in the same secret group may not be split into different feedback groups.
	// We try to find a simple assignment that is guaranteed to minimize the
	// total number of steps needed to reveal all secrets. If a simple
	// assignment cannot be found easily, we give up and return failure.

	// The algorithm is to assign each secret group, in order of decreasing
	// size, the largest remaining feedback group if this feedback group is
	// no larger than the secret group. If this can be done, the resulting
	// assignment is guaranteed (??? proof needed) to yield a lower bound
	// of the total number of steps.
	if (ngroup > p + 1)
		return StrategyCost();

	std::sort(group + 0, group + ngroup, std::greater<int>());
	int extra = 0;
	for (int i = 0; i < ngroup; ++i)
	{
		int avail = p - i - ((i < 2)? 1 : 0);
		if (group[i] >= avail)
		{
			extra += (group[i] - avail);
		}
		else
		{
			return StrategyCost();
		}
	}
	return StrategyCost(
		extra + n * 2,          // total steps
		extra > 0 ? 3 : 2,      // max depth
		(unsigned short)(extra > 0 ? extra : n)); // worst count
}