staircase child always getting a 0? - c++

Hi I am a beginner in recursions.
Question:
A child is running up a staircase he can hop 1, 2 or 3 steps at a time I need to find and return the number of ways he can climb a certain stair number?
My approach:
I am trying to divide the problem into smaller base cases and add 1 when a correct ans is reached.
My code:
void helper(int n ,int& a){
if(n==0){
a = a+1;
return;
}
if(n<0)
return;
helper(n-1,a);
helper(n-2,a);
helper(n-3,a);
}
int staircase(int n){
int ans = 0;
helper(n,ans);
return ans;
}
Problem:
I seem to be getting only 0 as answer?

I dont see why your code won't work. Here is a demo of it working with some changes: Live Demo
It is recommended that you don't pass in a reference and rather make each sub-problem which is either step 1, 2 or 3 self contained problems where you combine the results and that is the final answer similar to:
int staircase_without_reference(int n)
{
if(n == 0) return 1;
if(n < 0) return 0;
return staircase(n - 1) + staircase(n - 2) + staircase(n - 3);
}
This returns the similar to your program without the reference parameter.

Related

min cost of climbing stairs dynamic programming

I am trying to solve the following problem on leetcode:
On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).
Once you pay the cost, you can either climb one or two steps.
You need to find minimum cost to reach the top of the floor, and you can either start
from the step with index 0, or the step with index 1.
My solution is shown below:
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
return helper(cost, cost.size() - 1);
}
int helper(vector<int>& cost, int currStair) {
static vector<double> minCost(cost.size(), 0);
minCost[0] = cost[0];
minCost[1] = cost[1];
if (minCost[currStair] > 0) {
return minCost[currStair];
}
return minCost[currStair] = min(helper(cost, currStair - 1), helper(cost, currStair - 2)) + cost[currStair];
}
};
When I try to submit, I get the following run-time error. Why?
AddressSanitizer: heap-buffer-overflow on address 0x603000000008 at pc 0x0000004089af bp 0x7ffdd02dcaa0 sp 0x7ffdd02dca98
EDITED SOLUTION:
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
return helper(cost, cost.size() - 1);
}
int helper(vector<int>& cost, int currStair) {
if (currStair < 0 || cost.size() <= 1) {
return 0;
}
static vector<double> minCost(cost.size(), 0);
minCost[0] = cost[0];
minCost[1] = cost[1];
if (minCost[currStair] > 0) {
return minCost[currStair];
}
minCost[currStair] = min(helper(cost, currStair - 1), helper(cost, currStair - 2)) + cost[currStair];
return min(minCost[cost.size()-1], minCost[cost.size()-2]);
}
};
As you can see I made changes in the end of the code
The problem is a missing base case for the recursion. currStair keeps decrementing by -1 or -2 in each recursive call, but there's no condition to check if it went below 0 and cut off the recursion, resulting in an illegal memory access like minCost[-1].
Add the precondition
if (currStair < 0) return 0;
and you're back on track, although the algorithm still has correctness issues to resolve.
Here's a hint that might help you get unstuck:
The instructions say: "You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1."

I don't understand why I need to put two lines in a specific order for it to work (recursion)

I just started to learn about recursion.
This program is supposed to calculate n! and store the result into an output parameter.
void factorial(int n, int &f)
{
if (n == 0)
{
f = 1;
}
else
{
factorial(n - 1, f);
f *= n;
}
}
int main()
{
int f;
factorial(5, f);
cout << f;
}
This way it works perfectly. In my first attempt, the else condition looked like this
else
{
f *= n;
factorial(n - 1, f);
}
and the program didn't output anything but 1.
I really can't understand why it works in the first way but in the second it doesn't. Can you explain to me?
In your code, factorial(0, f) will set f = 1. If you modify f before the call to factorial, it will be overwritten.
Note that this problem is not possible if you return int instead of taking int & as an argument.
For anyone wondering:
Using #ForceBru's suggestion I ran it on a piece of paper and I got it. If I do it in the second way, the last thing called will be factorial(0) which will return 1, even if I already calculated to be n!.
f is getting over written to 1 in your last call f(0). If you switch the statements then f gets initialized to 1 in the last call f(0) followed by It's modification before return of each function call

Vector changes value unexpected

I am making a little game (just console) and my vectors don't act like I think they have to. One Value of the vector just changes and I don't know why. The Code shown below is part where this bug come from, I have deleted the rest of the code where these 2 vectors show up and the bug still appears and I DONT KNOW WHY!!
This part of the code is responsible for letting the Enemy spread to a random direction.
/**in this part the first value of the 2 vectors are created
(only once, I've tested it)**/
if(moves == 0){
int randomNum1 = (rand() % HEIGHT)+1;
int randomNum2 = (rand() % WIDTH)+1;
_EnemysY.push_back(randomNum1);
_EnemysX.push_back(randomNum2);
}
/**_Enemy vectors have normal values. For instance: _EnemysX[0]
is 23 and _EnemysY[0] is 12**/
/**In this part, the Enemy spreads in a random direction**/
if (moves > 3){
//save Enemys at the border here (those who can move)
std::vector<int> topX;
std::vector<int> topY;
std::vector<int> botX;
std::vector<int> botY;
std::vector<int> rigX;
std::vector<int> rigY;
std::vector<int> lefX;
std::vector<int> lefY;
/**here, I wanna save all Fields of the Enemy where it can spread to:**/
for (Uint it = 0; it < _EnemysY.size(); it++){
/**_EnemysY is still normal, but _EnemysX is like: 86BF163E0**/
if (_map[_EnemysY[it]-1][_EnemysX[it]] == _Grenade || _map[_EnemysY[it]-1][_EnemysX[it]] == _Field){
topY.push_back(_EnemysY[it]);
topX.push_back(_EnemysX[it]);
}
if (_map[_EnemysY[it]+1][_EnemysX[it]] == _Grenade || _map[_EnemysY[it]+1][_EnemysX[it]] == _Field){
botY.push_back(_EnemysY[it]);
botX.push_back(_EnemysX[it]);
}
if (_map[_EnemysY[it]][_EnemysX[it]-1] == _Grenade || _map[_EnemysY[it]][_EnemysX[it]-1] == _Field){
lefX.push_back(_EnemysX[it]);
lefY.push_back(_EnemysY[it]);
}
if (_map[_EnemysY[it]][_EnemysX[it]+1] == _Grenade || _map[_EnemysY[it]][_EnemysX[it]+1] == _Field){
rigX.push_back(_EnemysX[it]);
rigY.push_back(_EnemysY[it]);
}
}
/**and here is a random direction created and the programm
chooses which Field it will spread to: **/
for (;;){
int ranDir = (rand() % 4)+1;
if (ranDir == 1 && !topY.empty()){
int temp = (rand() % topY.size())+1;
_EnemysY.push_back(topY[temp]);
_EnemysX.push_back(topX[temp]);
return true;
}
if (ranDir == 2 && !botY.empty()){
int temp = (rand() % botY.size())+1;
_EnemysY.push_back(botY[temp]);
_EnemysX.push_back(botX[temp]);
return true;
}
if (ranDir == 3 && !lefY.empty()){
int temp = (rand() % lefY.size())+1;
_EnemysY.push_back(lefY[temp]);
_EnemysX.push_back(lefX[temp]);
return true;
}
if (ranDir == 4 && !rigY.empty()){
int temp = (rand() % rigY.size())+1;
_EnemysY.push_back(rigY[temp]);
_EnemysX.push_back(rigX[temp]);
return true;
}
}
}
First off, why not have a struct describing the "enemy", including its position (via two fields X and Y)? It would improve the code a bit and avoid the need for two vectors that are meaningless if separated.
On topic:
int temp = (rand() % rigY.size())+1;
_EnemysY.push_back(rigY[temp]);
rand() % rigY.size() will give you a number in the interval [0, rigY.size() ). You then add 1 to both sides so temp would be in the interval [1, rigY.size() ].
But rigY[rigY.size()] is not a valid element in the vector...
First of all: thank you Andrei and PaulMcKenzie for your time, your answers didn't solve the problem, but they were still usefull. :)
Now to the answer of the problem:
Alright! I'm a complete douchebag! Because what I didn't print in the code above, was my std::cout s for my variables and I accidentally wrote: "std::cout << ... << std:cout << ... std::endl" and for some reason the second "std::cout" caused a bug, where it printed out an ridiculously high number. So my code in general (without the cout s) works fine, but I still changed some things which you said.

Unhandled exception in C++ program

I'm trying to answer this question from my C++ book that says: There are n people in a room, where n is an integer greater than or equal to 2. Each person shakes hands once with every other person. What is the total number of handshakes in the room? Write a recursive function to solve this problem.
I've written a program, but nothing is being outputted from the function. I'm pretty sure my stuff inside the handshake function is correct, but nothing is being outputted by the function inside the main function. It keeps giving me an error:
Unhandled exception at 0x00c01639 in Problem2.exe: 0xC00000FD: Stack overflow.
Thank you for your help in advance!
#include <iostream>
#include <conio.h>
using namespace std;
int handshake(int n);
int main()
{
int i, n;
cout<<"How many people are in the room? ";
cin>>i;
for (n = 1; n = i; n++)
{
handshake(n);
}
cout<<"There are "<<handshake(n)<<" in the room"<<endl;
getche();
return 0;
}
int handshake(int n)
{
if (n == 1)
{
return 0;
}
else if (n == 2)
{
return 1;
}
else
{
return (handshake(n) + (n - 1));
}
}
Your problem is here:
return (handshake(n) + (n - 1));
Notice you're returning handshake(n) on a call of handshake(n), throwing you into infinite recursion land (and causing the call stack to overflow, hence your error).
This sounds like homework so I won't give any specific solution. I will make the following remarks:
Recursive functions need to have a base case (which you have) and a recursive step (which you need to fix). In particular, if f(x) is a recursive function, its result should depend on f(x-e), where e is strictly greater than 0.
You only need to call a recursive function once in your main code; it will take care of calling itself when needed.
The problem is because of stackoverflow which happens because the call to handshake(n) is making a recursive call to handshake(n) again and this infinite recursive calls causes the stack to explode.
Recursive calls should be called with arguments that are closer to the values that lead to base conditions, 0 and 1 in your case.
In your case the correct recursive call is:
return (handshake(n-1) + (n - 1));
As the recursive formula for number of hand shakes in a party is:
H(n) = H(n-1) + n-1
with the base condition of H(1) = 0 and H(2) = 1 where n is the number of people in the party and H(n) is the number of handshakes when every person in the party shakes hand with every other person in the party.
Also the condition in your for loop:
for (n = 1; n = i; n++)
will assign i to n. But what you want is to compare the value as:
for (n = 1; n <= i; n++)

Custom sorting, always force 0 to back of ascending order?

Premise
This problem has a known solution (shown below actually), I'm just wondering if anyone has a more elegant algorithm or any other ideas/suggestions on how to make this more readable, efficient, or robust.
Background
I have a list of sports competitions that I need to sort in an array. Due to the nature of this array's population, 95% of the time the list will be pre sorted, so I use an improved bubble sort algorithm to sort it (since it approaches O(n) with nearly sorted lists).
The bubble sort has a helper function called CompareCompetitions that compares two competitions and returns >0 if comp1 is greater, <0 if comp2 is greater, 0 if the two are equal. The competitions are compared first by a priority field, then by game start time, and then by Home Team Name.
The priority field is the trick to this problem. It is an int that holds a positve value or 0. They are sorted with 1 being first, 2 being second, and so on with the exception that 0 or invalid values are always last.
e.g. the list of priorities
0, 0, 0, 2, 3, 1, 3, 0
would be sorted as
1, 2, 3, 3, 0, 0, 0, 0
The other little quirk, and this is important to the question, is that 95% of the time, priority will be it's default 0, because it is only changed if the user wants to manually change the sort order, which is rarely. So the most frequent case in the compare function is that priorities are equal and 0.
The Code
This is my existing compare algorithm.
int CompareCompetitions(const SWI_COMPETITION &comp1,const SWI_COMPETITION &comp2)
{
if(comp1.nPriority == comp2.nPriority)
{
//Priorities equal
//Compare start time
int ret = comp1.sStartTime24Hrs.CompareNoCase(comp2.sStartTime24Hrs);
if(ret != 0)
{
return ret; //return compare result
}else
{
//Equal so far
//Compare Home team Name
ret = comp1.sHLongName.CompareNoCase(comp2.sHLongName);
return ret;//Home team name is last field to sort by, return that value
}
}
else if(comp1.nPriority > comp2.nPriority)
{
if(comp2.nPriority <= 0)
return -1;
else
return 1;//comp1 has lower priority
}else /*(comp1.nPriority < comp2.nPriority)*/
{
if(comp1.nPriority <= 0)
return 1;
else
return -1;//comp1 one has higher priority
}
}
Question
How can this algorithm be improved?
And more importantly...
Is there a better way to force 0 to the back of the sort order?
I want to emphasize that this code seems to work just fine, but I am wondering if there is a more elegant or efficient algorithm that anyone can suggest. Remember that nPriority will almost always be 0, and the competitions will usually sort by start time or home team name, but priority must always override the other two.
Isn't it just this?
if (a==b) return other_data_compare(a, b);
if (a==0) return 1;
if (b==0) return -1;
return a - b;
You can also reduce some of the code verbosity using the trinary operator like this:
int CompareCompetitions(const SWI_COMPETITION &comp1,const SWI_COMPETITION &comp2)
{
if(comp1.nPriority == comp2.nPriority)
{
//Priorities equal
//Compare start time
int ret = comp1.sStartTime24Hrs.CompareNoCase(comp2.sStartTime24Hrs);
return ret != 0 ? ret : comp1.sHLongName.CompareNoCase(comp2.sHLongName);
}
else if(comp1.nPriority > comp2.nPriority)
return comp2.nPriority <= 0 ? -1 : 1;
else /*(comp1.nPriority < comp2.nPriority)*/
return comp1.nPriority <= 0 ? 1 : -1;
}
See?
This is much shorter and in my opinion easily read.
I know it's not what you asked for but it's also important.
Is it intended that if the case nPriority1 < 0 and nPriority2 < 0 but nPriority1 != nPriority2 the other data aren't compared?
If it isn't, I'd use something like
int nPriority1 = comp1.nPriority <= 0 ? INT_MAX : comp1.nPriority;
int nPriority2 = comp2.nPriority <= 0 ? INT_MAX : comp2.nPriority;
if (nPriority1 == nPriority2) {
// current code
} else {
return nPriority1 - nPriority2;
}
which will consider values less or equal to 0 the same as the maximum possible value.
(Note that optimizing for performance is probably not worthwhile if you consider that there are insensitive comparisons in the most common path.)
If you can, it seems like modifying the priority scheme would be the most elegant, so that you could just sort normally. For example, instead of storing a default priority as 0, store it as 999, and cap user defined priorities at 998. Then you won't have to deal with the special case anymore, and your compare function can have a more straightforward structure, with no nesting of if's:
(pseudocode)
if (priority1 < priority2) return -1;
if (priority1 > priority2) return 1;
if (startTime1 < startTime2) return -1;
if (startTime1 > startTime2) return 1;
if (teamName1 < teamName2) return -1;
if (teamName1 > teamName2) return -1;
return 0; // exact match!
I think the inelegance you feel about your solution comes from duplicate code for the zero priority exception. The Pragmatic Programmer explains that each piece of information in your source should be defined in "one true" place. To the naive programmer reading your function, you want the exception to stand-out, separate from the other logic, in one place, so that it is readily understandable. How about this?
if(comp1.nPriority == comp2.nPriority)
{
// unchanged
}
else
{
int result, lowerPriority;
if(comp1.nPriority > comp2.nPriority)
{
result = 1;
lowerPriority = comp2.nPriority;
}
else
{
result = -1;
lowerPriority = comp1.nPriority;
}
// zero is an exception: always goes last
if(lowerPriority == 0)
result = -result;
return result;
}
I Java-ized it, but the approach will work fine in C++:
int CompareCompetitions(Competition comp1, Competition comp2) {
int n = comparePriorities(comp1.nPriority, comp2.nPriority);
if (n != 0)
return n;
n = comp1.sStartTime24Hrs.compareToIgnoreCase(comp2.sStartTime24Hrs);
if (n != 0)
return n;
n = comp1.sHLongName.compareToIgnoreCase(comp2.sHLongName);
return n;
}
private int comparePriorities(Integer a, Integer b) {
if (a == b)
return 0;
if (a <= 0)
return -1;
if (b <= 0)
return 1;
return a - b;
}
Basically, just extract the special-handling-for-zero behavior into its own function, and iterate along the fields in sort-priority order, returning as soon as you have a nonzero.
As long as the highest priority is not larger than INT_MAX/2, you could do
#include <climits>
const int bound = INT_MAX/2;
int pri1 = (comp1.nPriority + bound) % (bound + 1);
int pri2 = (comp2.nPriority + bound) % (bound + 1);
This will turn priority 0 into bound and shift all other priorities down by 1. The advantage is that you avoid comparisons and make the remainder of the code look more natural.
In response to your comment, here is a complete solution that avoids the translation in the 95% case where priorities are equal. Note, however, that your concern over this is misplaced since this tiny overhead is negligible with respect to the overall complexity of this case, since the equal-priorities case involves at the very least a function call to the time comparison method and at worst an additional call to the name comparator, which is surely at least an order of magnitude slower than whatever you do to compare the priorities. If you are really concerned about efficiency, go ahead and experiment. I predict that the difference between the worst-performing and best-performing suggestions made in this thread won't be more than 2%.
#include <climits>
int CompareCompetitions(const SWI_COMPETITION &comp1,const SWI_COMPETITION &comp2)
{
if(comp1.nPriority == comp2.nPriority)
if(int ret = comp1.sStartTime24Hrs.CompareNoCase(comp2.sStartTime24Hrs))
return ret;
else
return comp1.sHLongName.CompareNoCase(comp2.sHLongName);
const int bound = INT_MAX/2;
int pri1 = (comp1.nPriority + bound) % (bound + 1);
int pri2 = (comp2.nPriority + bound) % (bound + 1);
return pri1 > pri2 ? 1 : -1;
}
Depending on your compiler/hardware, you might be able to squeeze out a few more cycles by replacing the last line with
return (pri1 > pri2) * 2 - 1;
or
return (pri1-pri2 > 0) * 2 - 1;
or (assuming 2's complement)
return ((pri1-pri2) >> (CHAR_BIT*sizeof(int) - 1)) | 1;
Final comment: Do you really want CompareCompetitions to return 1,-1,0 ? If all you need it for is bubble sort, you would be better off with a function returning a bool (true if comp1 is ">=" comp2 and false otherwise). This would simplify (albeit slightly) the code of CompareCompetitions as well as the code of the bubble sorter. On the other hand, it would make CompareCompetitions less general-purpose.