explanation of this recursive function [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
hey there can anyone tell me how this function work ?!
for function and void function :
int countoccu(int array[],int value,int lower,int upper)
{
int counter=0;
if(lower==upper)
if (array[lower]==value)
return 1;
else
return 0;
else
counter = counter + countoccu(array, value, lower+1, upper);
if (array[lower]==value)
counter++;
return counter;
};
can anyone explain this for me
the output will be 3
void main()
{
int array[5]={3,7,3,3,11};
cout << countoccu(array,3,0,4) << endl;
}

It's a very stupid way to count number of value occurrences, for a given array, in given [upper, lower] range, using recurrence.
(If I understood it good.)
This looks like a homework, so I'll leave figuring it how it happens to you. My hint would be analyze code line by line, with a paper-sheet-pencil debugger.

int countoccu(int array[],int value,int lower,int upper){
int counter=0;
// Check if the end of the array is reached
if(lower==upper)
// Is the last element the "value" we are looking for?
if (array[lower]==value)
// Yes, so count it
return 1;
// No, don't count it
else return 0;
// Not the end of the array
else
// Move the position to the next item in the array and count it and all the following values that equals "value"
counter=counter+countoccu(array,value,lower+1,upper);
// Is the current item equal to the value being counted?
if (array[lower]==value)
// Yes, so count it
counter++;
return counter;
In your example you will get these calls:
countoccu(array,3,0,4) = 1+0+1+1+0 = 3
countoccu(array,3,1,4) = 0+1+1+0 = 2
countoccu(array,3,2,4) = 1+1+0 = 2
countoccu(array,3,3,4) = 1+0 = 1
countoccu(array,3,4,4) = 0 = 0

Though the function is written badly its principle of the work is simple. It checks whether the element with lower index is equal to the given value. If so it increases the count and adds the count for the array starting from the next index after index lower that is lower + 1 (calling itself at this time with lower + 1).
I would rewrite the function the following way
/* constexpr */ size_t count( const int a[], size_t n, int value )
{
return ( n == 0 ? 0 : ( ( a[0] == value ) + count( a + 1, n - 1, value ) ) );
}
I commented specifier constexpr because I think you do not know its meaning. So it may be omited.

Related

Expected Primary expression before int inside a function [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 12 months ago.
Improve this question
I am very aware that a lot of the formatting of this code is likely to be completely wrong. I am attempting to create a function GenPathByNumber which itself calls a function Binary. The GenPathBynumber attempts to (for integer x values from 0 through to 2^N - 1) create an array Path for each x value, with entries corresponding to each digit of x's binary representation. Binary converts each x to its binary reresentation, and GenPathByNumber puts binary through a loop.
When trying to build this, the logs keep saying "Expected Primary expression before int" for the Binary function (line 10 in the code below). Please can someone tell me what the problem(s) are?
void GenPathByNumber(int x,int N,int *Path)
{
//Create the array Path of length N, with all entries set to 0
Path[N] = {0};
//runs a for loop of all x values up to 2^N - 1
//and generates a binary path corresponding to each number
// of length N, then stores each digit of this in array Path.
for (int x = 0; x < pow(2,N)-1; x++)
{
binary(int x, int* Path);
}
}
void binary(int x, int* Path) {
if (x == 0) {
printf("%s\n", Path);
} else {
Path[x-1]='0';
binary(x-1);
Path[x-1] = '1';
binary(x-1);
}
}
Inside the for loop in GenPathByNumber you have:
for (int x = 0; x < pow(2,N)-1; x++)
{
binary(int x, int* Path);
}
You don't need the argument type specifiers when you call a function, only when you define it. Remove those and the error goes away.
binary(x, Path);
You have other errors inside the binary function where you're calling it with only one argument, like binary(x - 1);. You probably mean to provide Path in those calls as well.

Find sum of bits of a char [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 12 months ago.
Improve this question
I need a queue of size about 8 booleans. Every push should destroy an item from the tail. This can be achieved by a char in the resource limited application.
However I only care about the sum of those "flags", not their individual status. How can I find the sum of the set bits of an 8 bit char?
I come up with two methods.
A method is using a varible to count the sum, whenever you push, you maintain the varible, the change of the varible depends on what you push and what will pop.
Another method is an algorithm called "lowbit"
int lowbit(int x) {
return x & -x;
}
it will return the last 1 int the binary representation of the x.
So this can get the number of '1' in the binary representation of x.
for example, code like this.
int sum_of_1(int x) {
int res = 0;
while (x != 0) res++, x -= lowbit(x);
return res;
}
Counting bits set, Brian Kernighan's way
// count the number of bits set in v
unsigned char sum( unsigned char v )
{
unsigned int c; // c accumulates the total bits set in v
for (c = 0; v; c++)
{
v &= v - 1; // clear the least significant bit set
}
return v;
}
unsigned char push( unsigned char v, bool in )
{
v << 1;
if( in )
{
v |= 1;
}
return v;
}

Unexpected changing of C++ constant integer [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
The variable steady_counter is intialized as a constant integer.
cout << steady_counter;
So long as i have the above statement anywhere before the following code, the function runs as expected and checks if an integer input is or is not a runaround number.
The problem is that when the cout line is not present, the constant integer changes within the below if statements. I tested this by printing steady_counter before entering the if-else, and then after the if-else.
Without the cout line, steady_counter changes to a 4 digit number.
for (int i = 0; i < 10; i++)
{
if (CheckArr[i])
{
num_of_unique++;
}
}
if ((steady_counter == num_of_unique) & (final == NumArr[0]) )
{
return true;
}
else
{
return false;
}
}
Any idea what's going on? Why do I require a cout line to maintain the constant integer steady_counter?
One obvious problem:
for (int i = counter; i > 0; i --)
NumArr[i] = -1;
This covers values from 1 to counter inclusive; while valid indexes for NumArr are from 0 to counter-1 inclusive. So you write outside the array, corrupting something else; possibly another local variable.
Either correct the off-by-one error in the index
NumArr[i-1] = -1;
or use a more canonical loop
for (int i = 0; i < counter; ++i)
or, for more of a C++ flavour,
std::fill(NumArr, NumArr+counter, -1);
There are likely to be further errors, which are better found by using your debugger than by asking people to read through all your code.

C++ total beginner needs guidance [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
yesterday,we had to solve problems at the codeforces contest
I couldn't solve this problem since I am a total beginner.
http://codeforces.com/contest/353/problem/A
I used this algorithm, but something is wrong with it. I think it should print s or f, however it prints nothing. it just auto closes. Even when I added an input to stop instant close
#include <cstdlib>
#include <iostream>
using namespace std;
int main(){
int y=0;
int x=0;
int f;
int a;
cin >> a;
int s;
s = 0;
int number [a][a];
for(int i = 0;i<a;i++){
cin >> number[i][0] >> number[i][1];
x += number[i][0];
y += number[i][1];
}
for(int i = 0;i<a;i++){
if(x%2==0 && y%2==0){
return s;
}else if(y%2!=0 && x%2==0){
f = -1;
return f;
}else if(y%2==0 && x%2!=0){
f = -1;
return f;
}else{
y+= number[i][0];
x+= number[i][1];
s++;
}
}
int g;
if(f!=-1){
cout << s;
}else{
cout << f;
}
}
As Angew said, the return statements are incorrect and causing you to exit your main. You want to replace this by a break; to exit the loop but not the function.
I have not spent effort in trying to understand your algorithm, but at first glance it looks more complicated than it should be.
From my understanding of the problem, there are 3 possibilities:
the totals of the upper halves and the lower halves are already even (so nothing needs to be done)
the totals of the upper halves and the lower halves cannot be made even (so no solution exists)
just one Domino needs to be rotated to get the totals of the upper halves and the lower halves to be even (so the time needed is 1 second)
I base this on the fact that adding only even numbers always gives an even result, and adding an even number of odd numbers also always gives an even result.
Based on this, instead of having a 2-dimensional array like in your code, I would maintain 2 distinct arrays - one for the upper half numbers and the other for the lower half numbers. In addition, I would write the following two helper functions:
oddNumCount - takes an array as input; simply returns the number of odd numbers in the array.
oddAndEvenTileExists - takes 2 arrays as input; returns the index of the first tile with an odd+even number combination, -1 if no such tile exists.
Then the meat of my algorithm would be:
if (((oddNumCount(upper_half_array) % 2) == 0) && ((oddNumCount(lower_half_array) % 2) == 0))
{
// nothing needs to be done
result = 0;
}
else if (((oddNumCount(upper_half_array) - oddNumCount(lower_half_array)) % 2) == 0)
{
// The difference between the number of odd numbers in the two halves is even, which means a solution may exist.
// A solution really exists only if there exists a tile in which one number is even and the other is odd.
result = (oddAndEvenTileExists(upper_half_array, lower_half_array) >= 0) ? 1 : -1;
}
else
{
// no solution exists.
result = -1;
}
If you wanted to point out exactly which tile needs to be rotated, then you can save the index that "oddAndEvenTileExists" function returns.
You can write the actual code yourself to test if this works. Even if it doesn't, you would have written some code that hopefully takes you a little above "total beginner".

sorting arrays in C++ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
1.
const int nSize=6;
int anArray[nSize]={ 30, 60, 20, 50, 40, 10 };
for(int nStartIndex=0;nStartIndex<nSize;nStartIndex++)
{
int nSmallestIndex=nStartIndex;
for(int nCurrentIndex=nStartIndex+1;nCurrentIndex<nSize;nCurrentIndex++)
{
if(anArray[nCurrentIndex]<anArray[nStartIndex])
nSmallestIndex=nCurrentIndex;
}
swap(anArray[nStartIndex],anArray[nSmallestIndex]);
}
2.
const int nSize=6;
int anArray[nSize]={ 30, 60, 20, 50, 40, 10 };
for(int nStartIndex=0;nStartIndex<nSize;nStartIndex++)
{
int nSmallestIndex=nStartIndex;
for(int nCurrentIndex=nStartIndex+1;nCurrentIndex<nSize;nCurrentIndex++)
{
if(anArray[nCurrentIndex]<anArray[nSmallestIndex])
nSmallestIndex=nCurrentIndex;
}
swap(anArray[nStartIndex],anArray[nSmallestIndex]);
}
why do they give different results although nSmallestIndex equals to nStartIndex?
first code results {10,30,20,40,50,60}
second code results {10,20,30,40,50,60}
The logic in code sampe 1 is wrong and that's why it gives the wrong answer. In your second loop, you want to find the smallest element from [nStartIndex, nSize). But you only compare the current one with anArray[nStartIndex]. At the end you get nSmallestIndex equal to the last element smaller than anArray[nStartIndex].
For code sample two, the logic is right. You save the current smallest index in nSmallestIndex and use the updated version to compare in the if statement,
if(anArray[nCurrentIndex]<anArray[nSmallestIndex])
btw, the sorting method in this code is O(N^2) which is not good generally. It is also noted by others here C++ STL has facilities to do this better and portable.
There is a wrong condition inside your inner loop in the first example: if(anArray[nCurrentIndex]<anArray[nStartIndex]). Use nSmallestIndex instead of nStartIndex.
But in C++ you can do it in one line:
std::sort( anArray, anArray + nSize, std::less<int>() );
If you want to do it in C just use this code:
const int nSize=6;
int anArray[nSize]={ 30, 60, 20, 50, 40, 10 };
int Compare(const void* a ,const void* b)
{
return ( *(int*)a > *(int*)b ) ? 1 : ( ( *(int*)a < *(int*)b ) ? -1 : 0 );
}
...
qsort( anArray, nSize, sizeof( int ), &Compare );
Because nSmallestIndex equals to nStartIndex only at the begining of the second for, after some iteration nSmallestIndex can change but nSmallestIndex won't change because there are not the same variable
The idea behind selection sort is to find the smallest/largest element and position it to a proper index
Clearly your first algo's inner for loop
for(int nCurrentIndex=nStartIndex+1;nCurrentIndex<nSize;nCurrentIndex++)
{
if(anArray[nCurrentIndex]<anArray[nStartIndex])
nSmallestIndex=nCurrentIndex;
}
Never compares with new smaller index, it just compares the iterating number with original smaller value.
Whereas in 2nd algo's inner loop
for(int nCurrentIndex=nStartIndex+1;nCurrentIndex<nSize;nCurrentIndex++)
{
if(anArray[nCurrentIndex]<anArray[nSmallestIndex])
nSmallestIndex=nCurrentIndex;
}
It updates the smallestIndex and hence correctly find the smallest value for a swap.
why do they give different results although nSmallestIndex equals to nStartIndex?
The only difference betweent the two pieces of code:
< if(anArray[nCurrentIndex]<anArray[nStartIndex])
---
> if(anArray[nCurrentIndex]<anArray[nSmallestIndex])
So the conditional is different on nSmallestIndex and nStartIndex. But these values are not the same in the two pieces of code:
See the lines:
if(anArray[nCurrentIndex]<anArray[<VALUE>])
nSmallestIndex=nCurrentIndex;
// ^^^^^^^^^^^^^^^ Assignment changes the value.