### [AI]strange bug problem at c++

I am trying to make a BotClean Partially Observable,but there is a bug in between line 21 to line 36,Although at debuging j<=newposy but at the watches window j exceed new_posy by 1.
for example when I entire this input

0
1
-b---
-d---
---d-
---d-
--d-d

input 0 1 are for the position of the bot"b","d" is for dirty position
,at watches window =>

i=> 0 0 0 0 1 1
j=> 0 1 2 3 0 1
new_posx=1
new_posy=2

at the fourth iteration i=0 and j=3,why j=3 it exceed new_posy by 1 ,any help please !!??

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118`` ``````#include #include using namespace std; /* Head ends here */ void next_move(int posx, int posy, vector board) { int p_pos,found=0,m_pos,turn=0,i=posx-1,j=posy-1,count=1,line_turn=1,loop_turn=1; while(i<0) {i++;} while(j<0) {j++;} while(i>4) {i--;} while(j>4) {j--;} int counter_i = i; int counter_j = j; int new_posx = posx+1; int new_posy = posy+1; for(i=counter_i;i<=new_posx;i++) { for(j=counter_j;j<=new_posy;j++) { if(board[i].at(j)=='d') { found = 1; break; } } if(found==1) { break; } } if(iposx&&turn==0&&found==1) { cout<<"DOWN"<< endl; turn=1; posx++; } if(jposy&&turn==0&&found==1) { cout<<"RIGHT"<< endl; turn=1; posy++; } if(i == posx && j == posy && turn == 0 && found == 1) { cout<<"CLEAN"<< endl; board[i].at(j) = '-'; turn = 1; } if(found == 0) { if(posx!=4&&posy!=4) { if(posx+1 < 5 && line_turn == 1&&loop_turn==1) { posx++; cout<<"RIGHT"<< endl; loop_turn=0; } if(posx+1 == 5 && line_turn ==1&&loop_turn==1) { posy++; cout<<"DOWN"<< endl; line_turn = 0; loop_turn=0; } if(posx-1 > -1 && line_turn == 0&&loop_turn==1) { posx--; cout<<"LEFT"<< endl; loop_turn=0; } if(posx-1 == -1 && line_turn == 0&&loop_turn==1) { posy++; cout<<"DOWN"<< endl; line_turn = 1; loop_turn=0; } next_move(posx,posy,board); } else{return;} } else{next_move(posx,posy,board);} } /* Tail starts here */ int main(void) { int pos[2]; vector board; cin>>pos[0]>>pos[1]; for(int i=0;i<5;i++) { string s;cin >> s; board.push_back(s); } next_move(pos[0], pos[1], board); return 0; } ``````
Last edited on
 at the fourth iteration i=0 and j=3,why j=3 it exceed new_posy by 1 ,any help please !!??

Because that's the way for loops work. In order for a for loop to not be executed, the loop condition must evaluate to false. It will only do so when j is greater than new_posy.

 ``12345678`` `````` while(i<0) {i++;} while(j<0) {j++;} while(i>4) {i--;} while(j>4) {j--;}``````

could be written as:

 ``12345678`` `````` if (i<0) i = 0; if (j<0) j = 0; if (i>4) i = 4; if (j>4) j = 4;``````

On lines 18 and 19 new_posx and new_posy may be greater than 4, which means that on lines 21 and 23, both i and j may be out of bounds causing an exception to be thrown on line 25.

Topic archived. No new replies allowed.