tags:

views:

189

answers:

3
#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;

int twoify(int num, int times)
{
    num *= 2;
    if (times > 0)
    {
     times--;
     return twoify(num, times);
    }
    return num;
}

int main()
{
    srand(time(NULL));
    const int BET = 1;
    const int TIMES = 100000;
    const int CHANCE = 50;

    int wins = 0;
    int losses = 0;
    int wstreak = 0;
    int lstreak = 0;
    int cwstreak = 0;
    int clstreak = 0;

    for (int i = 0; i < TIMES; i++)
    {
     int num = rand() % 100 + 1;
     if (num <= CHANCE) // win?
     {
      wins++;
      cwstreak++;
      clstreak = 0;
      if (cwstreak > wstreak)
       wstreak = cwstreak;
     }
     else
     {
      losses++;
      clstreak++;
      cwstreak = 0;
      if (clstreak > lstreak)
       lstreak = clstreak;
     }

    }

    cout << "Wins: " << wins << "\tLosses: " << losses << endl;
    cout << "Win Streak: " << wstreak << "\tLoss Streak: " << lstreak << endl;
    cout << "Worst lose bet: " << twoify(BET, lstreak) << endl;

    system("PAUSE");
    cout << endl << endl;
    return main();
}

In particular, the twoify() function seems noobis. This is a martingale bet pattern, and basically every loss you double your previous bet until you win.

+4  A: 
int twoify(int num, int times) {
    return num << (times + 1);  // num * 2**(times+1)
}
Grandpa
MATH! twoify(5,3) = 2(2(2(5))) = (2^3)*5Grandpa, your twoify(5,0) = 10. Should be just (times) not (times + 1).
codebliss
@codebliss: you're wrong, it's times+1 if you want the function to output the same as the OP's function.
JRL
The OP's twoify(5,0) is also 10.
Grandpa
+1  A: 

It's unclear why twoify is a recursive method. Maybe this was used during the class to introduce or illustrate recursion, but clearly this could be replaced by a function which multiplies num by 2^times. This can be expressed with the exponentiation mathematical operator of the C language or, as shown in other response, by doing a left shift operation, shifting by as many bits as the exponent (the "times" argument, here)

mjv
OP wanted to "un-noobify" though. To me that entails, among other things, eliminating excess recursion.
Chris
+5  A: 

First, avoid the useless recursion, turn it into iteration:

int twoify(int num, int times)
{
    do {
      num *= 2;
      --times;
    } while (times >= 0);
    return num;
}

But, you can do better (if times > 0 is guaranteed, which would also simplify the version above by allowing you to use a while instead of the do/while, but, anyway...):

int twoify(int num, int times)
{
    return num << (times + 1);
}

The reason this works is that it's equivalent to multiplying num by 2 raised to the (times + 1)th power, which is what the recursive and iterative versions both do.

Alex Martelli