mercredi 26 septembre 2018

cpp strange behaviour in this function

I am trying to write a function that calculates the gap heursitic. Below is my code:

#include <iostream>
using namespace std;
#include <vector>
#include <map>
#include <string>
using namespace std;
int main(int argc, char const *argv[])
{
    string direction = "backward";
    string state_string = "012345";
    string goal_state_string = "125430";
    int n = 3;

    string ignored_pancakes;
    int gap = 0;
    state_string += to_string(state_string.length());
    unsigned int goal_state_index;
    goal_state_string += to_string(goal_state_string.length());
    if (direction == "forward")
    {
        for (unsigned int i = 0; i < n; i++)
        {
            ignored_pancakes += goal_state_string[i];
        }
    }
    else
    {
        for (unsigned int i = 0; i < n; i++)
        {
            ignored_pancakes += state_string[i];
        }

    }

    for (int i = 0; i < state_string.length(); i++)
    {

        if ((ignored_pancakes.find(state_string[i + 1]) != string::npos) or (ignored_pancakes.find(state_string.at(i)) != string::npos))
        {
            continue;
        }

        if (abs(goal_state_string.find(state_string[i])-goal_state_string.find(state_string[i+1])!=1)){
            gap++;
        }


        cout << state_string.at(i) << "\t" << state_string.at(i + 1) << endl;
    }
    // cout << state_string << endl;
    cout << ignored_pancakes << endl;
    cout << gap << endl; 
 }

The output that I expect is as follows:

3       4
4       5
5       6
012
2

But what is being printed out is:

3       4
4       5
5       6

Strangely when I comment out the line that says :

cout << state_string.at(i) << "\t" << state_string.at(i + 1) << endl;

The output is:

012
2

Why is it printing out something completely different depending on that line which seems irrelevant.

Aucun commentaire:

Enregistrer un commentaire