Recursive Stackoverflow Error - recursion

Alright, so I'm trying to make a Java program to solve a picross board, but I keep getting a Stackoverflow error. I'm currently just teaching myself a little Java, and so I like to use the things I know rather than finding a solution online, although my way is obviously not as efficient. The only way I could think of solving this was through a type of brute force, trying every possibility. The thing is, I know that this function works because it works for smaller sized boards, the only problem is that with larger boards, I tend to get errors before the function finishes.
so char[][] a is just the game board with all the X's and O's. int[][] b is an array with the numbers assigned for the picross board like the numbers on the top and to the left of the game. isDone() just checks if the board matches up with the given numbers, and shift() shifts one column down. I didn't want to paste my entire program, so if you need more information, let me know. Thanks!
I added the code for shift since someone asked. Shift just moves all the chars in one row up one cell.
Update: I'm thinking that maybe my code isn't spinning through every combination, and so it skips over the correct answer. Can anyone verify is this is actually trying every possible combination? Because that would explain why I'm getting stackoverflow errors. On the other hand though, how many iterations can this go through before it's too much?
public static void shifter(char[][] a, int[][] b, int[] clockwork)
{
boolean correct = true;
correct = isDone(a, b);
if(correct)
return;
clockwork[a[0].length - 1]++;
for(int x = a[0].length - 1; x > 0; x--)
{
if(clockwork[x] > a.length)
{
shift(a, x - 1);
clockwork[x - 1]++;
clockwork[x] = 1;
}
correct = isDone(a, b);
if(correct)
return;
}
shift(a, a[0].length - 1);
correct = isDone(a, b);
if(correct)
return;
shifter(a, b, clockwork);
return;
}
public static char[][] shift(char[][] a, int y)
{
char temp = a[0][y];
for(int shifter = 0; shifter < a.length - 1; shifter++)
{
a[shifter][y] = a[shifter + 1][y];
}
a[a.length - 1][y] = temp;
return a;
}

Check Recursive call.and give the termination condition.
if(terminate condition)
{
exit();
}
else
{
call shifter()
}

Related

Program returns 0 but only to "one up" in recursion, but I want it to go to the "very top"? Is this possible?

I'm new to using recursion and I'm trying to get my palindrome program to work. This is what I am trying to do: if a character is not equal, I return 0. If not, I keep recursing while increasing the i and decreasing the j. If the i is no longer less than the j, i want to say that the recursion is done, so I want to return that the word is a palindrome (=1).
But when I input a word that is not a palindrome, I correctly return a 0. (I can see this when I debug). But-- then at the end, it also returns a 1. I assume this has something to do with the fact that recursion means that the program keeps going, and the 0 gets returned to something I had previously been doing before. But- I want the 0 to go to the very top.
Is there some way around this problem? Or am I doing something wrong? Sorry if this is really basic.
Thanks in advance. Here is my code:
public static int checkIfPalindrome(String s, int i, int j) {
if (i<j) {
if (s.charAt(i) == s.charAt(j)) {
checkIfPalindrome(s, i+1, j-1);
}
else {
return 0;
}
}
return 1;
}
Once you know your pointers haven't collided, and the characters they point to are the same, then the return value of this method is the return value of the recursive call. I've fixed your code to do this below but I have also reorganized it a different way, as there are other ways to go about the problem:
public static int checkIfPalindrome(String s, int i, int j) {
if (i >= j) {
return 1;
}
if (s.charAt(i) != s.charAt(j)) {
return 0;
}
return checkIfPalindrome(s, i + 1, j - 1);
}

what is the difference of these two implementations of a recursion algorihtm?

I am doing a leetcode problem.
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
So I tried this implementation first and got a "exceeds runtime" (I forgot the exact term but it means the implementation is slow). So I changed it version 2, which use a array to save the results. I honestly don't know how the recursion works internally and why these two implementations have different efficiency.
version 1(slow):
class Solution {
// int res[101][101]={{0}};
public:
int uniquePaths(int m, int n) {
if (m==1 || n==1) return 1;
else{
return uniquePaths(m-1,n) + uniquePaths(m,n-1);
}
}
};
version2 (faster):
class Solution {
int res[101][101]={{0}};
public:
int uniquePaths(int m, int n) {
if (m==1 || n==1) return 1;
else{
if (res[m-1][n]==0) res[m-1][n] = uniquePaths(m-1,n);
if (res[m][n-1]==0) res[m][n-1] = uniquePaths(m,n-1);
return res[m-1][n] + res[m][n-1];
}
}
};
Version 1 is slower beacuse you are calculating the same data again and again. I'll try to explain this on different problem but I guess that you know Fibonacci numbers. You can calculate any Fibonacci number by following recursive algorithm:
fib(n):
if n == 0 then return 0
if n == 1 then return 1
return fib(n-1) + fib(n-1)
But what actually are you calculating? If you want to find fib(5) you need to calculate fib(4) and fib(3), then to calculate fib(4) you need to calculate fib(3) again! Take a look at the image to fully understand:
The same situation is in your code. You compute uniquePaths(m,n) even if you have it calculated before. To avoid that, in your second version you use array to store computed data and you don't have to compute it again when res[m][n]!=0

Calculating the average of Sensor Data (Capacitive Sensor)

So I am starting to mess around with Capacitive sensors and all because its some pretty cool stuff.
I have followed some tutorials online about how to set it up and use the CapSense library for Arduino and I just had a quick question about this code i wrote here to get the average for that data.
void loop() {
long AvrNum;
int counter = 0;
AvrNum += cs_4_2.capacitiveSensor(30);
counter++;
if (counter = 10) {
long AvrCap = AvrNum/10;
Serial.println(AvrCap);
counter = 0;
}
}
This is my loop statement and in the Serial it seems like its working but the numbers just look suspiciously low to me. I'm using a 10M resistor (brown, black, black, green, brown) and am touching a piece of foil that both the send and receive pins are attached to (electrical tape) and am getting numbers around about 650, give or take 30.
Basically I'm asking if this code looks right and if these numbers make sense...?
The language used in the Arduino environment is really just an unenforced subset of C++ with the main() function hidden inside the framework code supplied by the IDE. Your code is a module that will be compiled and linked to the framework. When the framework starts running it first initializes itself then your module by calling the function setup(). Once initialized, the framework enters an infinite loop, calling your modules function loop() on each iteration.
Your code is using local variables in loop() and expecting that they will hold their values from call to call. While this might happen in practice (and likely does since that part of framework's main() is probably just while(1) loop();), this is invoking the demons of Undefined Behavior. C++ does not make any promises about the value of an uninitialized variable, and even reading it can cause anything to happen. Even apparently working.
To fix this, the accumulator AvrNum and the counter must be stored somewhere other than on loop()'s stack. They could be declared static, or moved to the module outside. Outside is better IMHO, especially in the constrained Arduino environment.
You also need to clear the accumulator after you finish an average. This is the simplest form of an averaging filter, where you sum up fixed length blocks of N samples, and then use that average each Nth sample.
I believe this fragment (untested) will work for you:
long AvrNum;
int counter;
void setup() {
AvrNum = 0;
counter = 0;
}
void loop() {
AvrNum += cs_4_2.capacitiveSensor(30);
counter++;
if (counter == 10) {
long AvrCap = AvrNum/10;
Serial.println(AvrCap);
counter = 0;
AvrNum = 0;
}
}
I provided a setup(), although it is redundant with the C++ language's guarantee that the global variables begin life initialized to 0.
your line if (counter = 10) is invalid. It should be if (counter == 10)
The first sets counter to 10 and will (of course) evaluate to true.
The second tests for counter equal to 10 and will not evaluate to true until counter is, indeed, equal to 10.
Also, kaylum mentions the other problem, no initialization of AvrNum
This is What I ended up coming up with after spending some more time on it. After some manual calc it gets all the data.
long AvrArray [9];
for(int x = 0; x <= 10; x++){
if(x == 10){
long AvrMes = (AvrArray[0] + AvrArray[1] + AvrArray[2] + AvrArray[3] + AvrArray[4] + AvrArray[5] + AvrArray[6] + AvrArray[7] + AvrArray[8] + AvrArray[9]);
long AvrCap = AvrMes/x;
Serial.print("\t");
Serial.println(AvrCap);
x = 0;
}
AvrArray[x] = cs_4_2.capacitiveSensor(30);
Serial.println(AvrArray[x]);
delay(500);

Making smaller lower-higher console game

So im a pretty new programmer so forgive me if i make any mistakes.
I need to make a higher or lower game for my class but im a little bit stuck now.
The purpose of this whole game is to guess the number which is random generated by the computer. But here's the tricky part, the user only needs to get 8 chances to guess the number right. If not the game must end and print something like: you lost, the number was.....
I came this far;
public static void main(String[] args) {
int timesGuessed = 0;
int randomNummer = (int)(Math.random()*100);
int number;
boolean won = true;
Scanner input = new Scanner(System.in);
do{
System.out.print("Guess the number: ");
number = input.nextInt();
timesGuessed++;
if(timesGuessed == 8){
won = false;
}
if(number > randomNummer){
System.out.println("Lower!");
}
else if(number < randomNummer){
System.out.println("Higher!");
}
}
while(number != randomNummer);
if(won == true){
System.out.println("The number is guessed right in " + timesGuessed + " attemts.");
}
else{
System.out.println("You lost. The number was " + randomNummer + ".");
}
}
Now the game lets you finish even though you already had 8 chances. Thats what i want to change. It needs to stop when you failed the eight time.
Thank you for the help, it would be very appreciated.
You also need to check your won variable in the condition of your loop. You may also want to add an else so it doesn't print "Higher" or "Lower" after the final try.

Recursive Sudoku Solver- Segmentation Fault (C++)

I'm attempting to make a sudoku solver for the sake of learning to use recursion. I seem to have gotten most of the code to work well together, but when I run the program, I get a windows error telling me that the program has stopped working. A debug indicates a segmentation fault, and I saw elsewhere that this can be caused by too many recursions. I know this is a brute-force method, but again, I'm more worried about getting it to work than speed. What can I do to fix this to a working level?
struct Playing_grid {
//Value of cell
int number;
//wether the number was a clue or not
bool fixed;
}
grid[9][9];
void recursiveTest(int row, int column, int testing)
{
//first, check to make sure it's not fixed
if(grid[row][column].fixed == false)
{
if((checkRow(testing, row) | checkColumn(testing, column) | checkBox(testing,boxNumber(row,column)) | (testing > 9)) == 0)
{
grid[row][column].number = testing;
moveForward(row,column,testing);
recursiveTest(row, column, testing);
}
else if(testing < 9)
{
testing ++;
recursiveTest(row, column, testing);
}
else if(testing == 9)
{
while(testing == 9)
{
moveBack(row,column,testing);
while(grid[row][column].fixed == true)
{
{
moveBack(row,column,test);
}
}
testing = grid[row][column].number;
recursiveTest(row,column,testing);
}
}
}
else
{
moveForward(row,column,testing);
recursiveTest(row,column,testing);
}
}
void moveForward(int& row, int& column, int& test)
{
if(column < 8)
{
column ++;
}
else if((column == 8) & (row != 8))
{
column = 0;
row ++;
}
else if((column == 8) & (row == 8))
{
finishProgram();
}
test = 1;
}
void moveBack(int& row, int& column, int& test)
{
grid[row][column].number = 0;
if(column > 0)
{
column --;
}
else if((column == 0) & (row > -1))
{
column = 8;
row --;
}
else
{
cout << "This puzzle is unsolveable!" << endl;
}
test++;
}
I tried to include all the relevant pieces. I essentially create a 9x9 matrix, and by this point it is filled with 81 values, where empty slots are written as 0. After confirming the test value is valid in the row, column and box, it fills in that value and moves onto the next space. Whenever it runs to 9 and has no possible values, it returns to the previous value and runs through values for that one.
So as to not overwrite known values, the recursive function checks each time that the value of the grid[row][column].fixed is false.
I'd appreciate any insight as to cleaning this up, condensing it, etc. Thanks in advance!
Edit: To exit the recursive loop, when the function is called to move forward, if it has reached the last cell, it completes (saves + outputs) the solution. The code has been adjusted to reflect this.
I'd normally try to fix your code, but I think in this case it's fundamentally flawed and you need to go back to the drawing board.
As a general rule, the pseudocode for a recursive function like this would be
For each possible (immediate) move
Perform that move
Check for win state, if so store/output it and return true.
Call this function. If it returns true then a win state has been found so return true
Otherwise unperform the move
Having tried every move without finding a win state, return false.

Resources