I have a problem with this function I created, the function should return the number of characters entered in the array. but always return 20 that its the limit of the array itself.
Code:
int LongitudCadena (char *pcadena) {
// cantidad its the counter of chars that in the array
int cantidad=0;
//M its a constant equals 20, that its the limit of the array
for(int a=0;a<M;a++){
if(pcadena!=0){
pcadena++;
cantidad++;
} else {
return 0;
}
}
return cantidad;
}
Replace if(pcadena!=0) by if(*pcadena!='\0').
Also, change the else condition to either
else
{
return cantidad;
}
or
else
{
break;
}
pcadena, the pointer, is never going to be 0 (NULL)... what you meant that the character it points to is '\0'
if (*pcadena)
Another problem is once you find the terminator, you return 0. You should return cantidad there.
Note: cantidad == a
There are several problems with the code. First of all, you should test the content of the address the pointer points at.
...
if(*pacadena!=0) {
....
Secondly, why do you return 0 in the while loop when pcadena is 0? Shouldn't you return the current length? Assuming your data always terminate with \0, then your for loop should look something like this:
for(int a=0;a<M;a++){
if(*pcadena){
pcadena++;
cantidad++;
} else {
return cantidad;
}
}
Further, if your data is indeed terminated by \0, then you should just use the strlen function instead. There's no need to rewrite this.
Related
I have been having a problem with this code for a while. The placement of recursive call of the function does not seem right.
i tried running the code and yes it does run into a infinite loop.
// I DEFINE HEAP STRUCTURE AS :
struct heap_array
{
int *array; // heap implementation using arrays(note : heap is atype of a tree).
int capacity; // how much the heap can hold.
int size; //how much size is currently occupied.
void MaxHeapify(struct heap_array *h,int loc) // note : loc is the location of element to be PERCOLATED DOWN.
{
int left,right,max_loc=loc;
left=left_loc_child(h,loc);
right=right_loc_child(h,loc);
if(left !=-1 && h->array[left]>h->array[loc])
{
max_loc=left;
}
if(right!=-1 && h->array[right]>h->array[max_loc])
{
max_loc=right;
}
if(max_loc!=loc) //i.e. if changes were made:
{
//swap the element at max_loc and loc
int temp=h->array[max_loc];
h->array[max_loc]=h->array[loc];
h->array[loc]=temp;
}
MaxHeapify(h,max_loc); // <-- i feel that this recursive call is misplaced. I have seen the exact same code in almost all the online videos and some books i referred to. ALSO I THINK THAT THE CALL SHOULD BE MADE WITHIN THE SCOPE OF condition if(max_loc!=loc).
//if no changes made, end the func right there.
}
In your current implementation, it looks like you don't have a base case for recursion to stop.
Remember that you need a base case in a recursive function (in this case, your MaxHeapify function), and it doesn't look like there is one.
Here is an example of MaxHeap which may be resourceful to look at
// A recursive function to max heapify the given
// subtree. This function assumes that the left and
// right subtrees are already heapified, we only need
// to fix the root.
private void maxHeapify(int pos)
{
if (isLeaf(pos))
return;
if (Heap[pos] < Heap[leftChild(pos)] ||
Heap[pos] < Heap[rightChild(pos)]) {
if (Heap[leftChild(pos)] > Heap[rightChild(pos)]) {
swap(pos, leftChild(pos));
maxHeapify(leftChild(pos));
}
else {
swap(pos, rightChild(pos));
maxHeapify(rightChild(pos));
}
}
}
Here, you can see the basecase of:
if (isLeaf(pos))
return;
You need to add a base case to your recursive function.
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);
}
Wikipedia states:
In mathematics and computer science, a higher-order function (also
functional form, functional or functor) is a function that does at
least one of the following:
takes one or more functions as an input
outputs a function
Also,
A recursive function is a function that calls itself during its
execution.
Does this mean a recursive function could be classified as a very special case of higher-order function?
Please refer this case:
int foo(int i)
{
if(i>10)
{
return 10;
}
cout<<i;
return foo(++i);
}
I do not want opinions. Please state your answer with specific premises.
Imagine your Algol dialect didn't support recursion but supported higher order functions. Could we implement your example still? Sure you can!
int foo_aux(int i, Func cont)
{
if( i>10 ) {
return 10;
} else {
cout<<i; // side effect bad!
return cont(i+1, cont); // no recursion
}
}
int foo(int i)
{
return foo_aux(i, [] (int i, Func cont) -> int { return foo_aux(i,cont) });
}
Imagine you try to do the same but your language doesn't support higher order functions nor recursion. Is it possible to emulate it? Everything is possible:
std::stack<int> args; // integers can be castable pointers or numbers!
int cont = 2;
while( cont ) {
if( cont == 2 ) { // main
args.push(1)
cont=1; // continuation == foo_aux
} else if ( cont == 1 ) { // foo_aux
int tmp = args.pop();
if( tmp > 10 ) {
args.push(10);
cont=0; // continuation == return/exit
} else {
cout << tmp;
args.push(tmp+1);
// not setting cont == recursion
}
}
}
// do something with the result
return args.pop();
This is a way of doing recursion like in your initial example. Perhaps you could make a preprocessor (macro) to do the conversion from something fancy like your example to become this for compilation. If you wanted to pass the function as an argument you just push the number and your receiving function would need to set f.
std::stack<int> args; // integers can be castable pointers or numbers!
args.push(2) // bootstrap
int cont = 0;
while( cont = args.pop() ) {
if( cont == 2 ) { // main / foo
args.push(1) // push argument
args.push(1) // push function
} else if ( cont == 1 ) { // foo_aux
int tmp = args.pop();
if( tmp > 10 ) {
args.push(10); // push result
args.push(0); // push exit as continuation
} else {
cout << tmp;
args.push(tmp+1); // push argument
args.push(1); // push self as argument
}
}
}
// do something with the result
return args.pop();
This does not support so called upwards funarg since then you need to have another structure for closed over variable no longer in scope.
So is recursion a special case of higher order functions? Since functions can be emulated using a function index it's possible to implement functions, recursion and higher order functions at the same time from a compiler view point. This only means functions can be modeled the same way. It's perfectly possible to make a compiler that uses assembly functions that do not support higher order functions but support recursion and it's possible to make a language without recursion that support higher order functions that will enable a way of doing recursion with something like a Y combinator. Other than that they are completely different things.
No. "Outputting" a function in this context means returning a function, not returning the result of calling a function. That is, the return value is itself callable. Recursive functions in general do not necessarily do this. For example:
def factorial(n: int) -> int:
if n == 0:
return 1
else:
return n*factorial(n-1)
This code returns an integer. You cannot call an integer, so it is not a higher-order function.
No.
outputs a function means functions can be used as return value of a function, like this (code in Lua):
function foo()
return function(a,b) return a + b end
end
In your example of recursive function, the return value is the result of the expresion foo(++i), not the function foo itself.
A higher order function is a function that can take conditions or functions as arguement. And it can optionally output a function as the return statement .
therefore ,recursive functions are not all higher level functions.
Also, higher level functions are not all recursive, because some just use conditions as arguements .
The function gets an integer and a digit, and should return true
if the digit appears an even number of times in the integer, or false if not.
For example:
If digit=1 and num=1125
the function should return true.
If digit=1 and num=1234
the function should return false.
bool isEven(int num, int dig)
{
bool even;
if (num < 10)
even = false;
else
{
even = isEven(num/10,dig);
This is what I've got so far, and I'm stuck...
This is homework so please don't write the answer but hint me and help me get to it by myself.
To set up recursion, you need to figure out two things:
The base case. What is are the easy cases that you can handle outright? For example, can you handle single-digit numbers easily?
The rule(s) that reduce all other cases towards the base case. For example, can you chop off the last digit and somehow transform the solution for the remaning partial number into the solution for the full number?
I can see from your code that you've made some progress on both of these points. However, both are incomplete. For one thing, you are never using the target digit in your code.
The expression num%10 will give you the last digit of a number, which should help.
Your base case is incorrect because a single digit can have an even number of matches (zero is an even number). Your recursive case also needs work because you need to invert the answer for each match.
This funtion isEven() takes a single integer and returns the true if the number of occurence of numberToCheck is even.
You can change the base as well as the numberToCheck which are defined globally.
#include <iostream>
using std::cout;
using std::endl;
// using 10 due to decimal [change it to respective base]
const int base = 10;
const int numberToCheck = 5;
//Checks if the number of occurence of "numberToCheck" are even or odd
bool isEven(int n)
{
if (n == 0)
return 1;
bool hasNumber = false;
int currentDigit = n % base;
n /= base;
if (currentDigit == numberToCheck)
hasNumber = true;
bool flag = isEven(n);
// XOR GATE
return ((!hasNumber) && (flag) || (hasNumber) && (!flag));
};
int main(void)
{
// This is the input to the funtion IsEven()
int n = 51515;
if (isEven(n))
cout << "Even";
else
cout << "Odd";
return 0;
}
Using XOR Logic to integrate all returns
// XOR GATE
return ((!hasNumber) && (flag) || (hasNumber) && (!flag));
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.