So I know c# and java and c++ isn't that different. The following program is meant to solve the postage stamp problem. If you have three stamps and D denominations what should the denominations be so you can make any change from 1 to as high as possible. One thing I was wanting to do is see if I could extend this as to four stamps and D denominations. g_nLevels = D. I found out the weird stuff in the do loop is duff's device to copy memory. I tried to convert it to using memcpy to see the speed difference, but I couldn't get it to not reference bad memory.
Code:
#include <iostream>
using std::cout;
long g_buf[1024];
int g_arrValues[25];
int g_arrBest[25];
int g_nLevels;
int g_nBest;
void Step(int nLevel)
{
int nVal = g_arrValues[nLevel++];
if(nLevel == g_nLevels)
{
while(g_buf[nVal++] != 0);
if(nVal > g_nBest)
{
for(int i = 0; i < nLevel; i++)
g_arrBest[i] = g_arrValues[i];
g_nBest = nVal;
}
}
else
{
do
{
++g_buf[nVal++];
long* pFrom = g_buf;
long* pTo = g_buf + nVal;
int nCount = (nVal + 7) / 8;
switch (nVal & 7)
{
case 0:
do
{
*pTo++ += short(*pFrom++) << 8; *pTo++ += short(*pFrom++) << 8;
case 7: *pTo++ += short(*pFrom++) << 8; *pTo++ += short(*pFrom++) << 8;
case 6: *pTo++ += short(*pFrom++) << 8; *pTo++ += short(*pFrom++) << 8;
case 5: *pTo++ += short(*pFrom++) << 8; *pTo++ += short(*pFrom++) << 8;
case 4: *pTo++ += short(*pFrom++) << 8; *pTo++ += short(*pFrom++) << 8;
case 3: *pTo++ += short(*pFrom++) << 8; *pTo++ += short(*pFrom++) << 8;
case 2: *pTo++ += short(*pFrom++) << 8; *pTo++ += short(*pFrom++) << 8;
case 1: *pTo++ += short(*pFrom++) << 8; *pTo++ += short(*pFrom++) << 8;
}
while(--nCount > 0);
}
g_arrValues[nLevel] = nVal;
Step(nLevel);
pFrom = g_buf + nVal * 2 - 1;
pTo = g_buf + nVal * 3 - 1;
nCount = (nVal + 7) / 8;
switch (nVal & 7)
{
case 0:
do
{
*pTo-- -= short(*pFrom--) << 8; *pTo-- -= short(*pFrom--) << 8;
case 7: *pTo-- -= short(*pFrom--) << 8; *pTo-- -= short(*pFrom--) << 8;
case 6: *pTo-- -= short(*pFrom--) << 8; *pTo-- -= short(*pFrom--) << 8;
case 5: *pTo-- -= short(*pFrom--) << 8; *pTo-- -= short(*pFrom--) << 8;
case 4: *pTo-- -= short(*pFrom--) << 8; *pTo-- -= short(*pFrom--) << 8;
case 3: *pTo-- -= short(*pFrom--) << 8; *pTo-- -= short(*pFrom--) << 8;
case 2: *pTo-- -= short(*pFrom--) << 8; *pTo-- -= short(*pFrom--) << 8;
case 1: *pTo-- -= short(*pFrom--) << 8; *pTo-- -= short(*pFrom--) << 8;
}
while(--nCount > 0);
}
}
while(--g_buf[nVal-1] != 0);
}
}
int main(int argc, char* argv[])
{
g_nBest = 0;
g_arrValues[0] = 1;
g_buf[0] = 0x00000001;
g_buf[1] = 0x00000100;
g_buf[2] = 0x00010000;
g_nLevels = 9;
Step(0);
cout << "Max sum: " << g_nBest - 1 <<'\n';
for (int i = 0; i < g_nLevels; ++i)
cout << g_arrBest[i] << ' ';
cout << '\n';
return 0;
}