So with the following code, I'm supposed to be able to read in an array, choose a starting point (usually array[0], and then add or substract the value at the given index to move around in the array. The purpose of the puzzle is to get to the last element of the array using a recursive function. My problem right now is that it always tells me that it is solvable (which is what I want), but not in the case that it actually isn't a solvable array. When I pass it the array
int array[] = { 3, 6, 4, 1, 3, 4, 2, 5, 3, 0 };
bool solved = IsSolvable(0, array, 10);
It works fine as it should. But when I pass it
int arraytest[] = { 3, 1, 2, 3, 0 };
bool solved2 = IsSolvable(0, arraytest, 5);
it does not say return false as it should. It should not be possible because when it gets to arraytest[4] where the value is three, it will infinitely go between 3 and 3. I fixed this in my code so there wouldn't be a loop, but I still want it to return that the array is unsolvable. Can anyone see why it doesn't?
bool IsSolvable(int index, int array[], int size){
if (index == size - 1){ return true; }
else if (index > size - 1 || index < 0){
return false;
}
else if (array[index] == -1) { cout << "here i am" << endl; return false; }
else {
int temp = array[index];
array[index] = -1;
bool found = IsSolvable(index + array[index], array, size) || IsSolvable(index - array[index], array, size);
array[index] = temp;
return found;
}
}
I'll attach a photo so that it's more easily understood.
Aucun commentaire:
Enregistrer un commentaire