You are on page 1of 4

/******************************************

* File Name: coinrow.cpp


*
* Abstract: this program creates does the *
*
coin row problem using the algorithm *
*
*
*
*
* ID:3007
*
* Author: Dean Cowart
*
*******************************************/
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
using namespace std;
int
int
int
int

maxcoins(int, int);
change(string);
max(int, int);
coins_r(int[], int);

int const MAX = 20;


int main()
{
string filen;
cout << "Enter a file name: ";
cin >> filen;
int countCoins = 0;
int coins[MAX];
int count = 0;
//Retrieve values from external file. First line is size and
second line is heap values;
ifstream file(filen);
string line;
// check for open file.
if (file.is_open())
{
// get number of coins
countCoins = change(line);
string buf;
// gets values
while (file >> buf)
{
coins[count+1] = change(buf);

count++;
}
file.close();
//Check if numbers match
if (countCoins != count)
{
cerr << "Actual number of coins and first line don't
match. Closing program." << endl;
system("pause.exe");
exit(1);
}
}
else
{
cerr << "Unable to open file. Closing program." << endl;
system("pause.exe");
exit(1);
}
int maxVal = coins_r(coins, countCoins);
cout << "Max Value: " << maxVal << endl;
return 0;
}
int maxcoins(int a, int b)
{
if (a > b)
{
return 0;
}
return 1;
}
int change(string str)
{
// code from cplusplus
int num;
istringstream convert(str);
if (!(convert >> num))
{
num = -1;
}

return num;
}
int max(int a, int b)
{
if (a > b)
{
return a;
}
return b;
}
int coins_r(int coins[], int numCoins)
{
int coinsp[20];
int set[20];
int numbers[20];
int vindex[20];
int location;
int index = numCoins;
int count = 0;
int temp = -1;
vindex[0] = -1;
vindex[1] = -1;
coinsp[0] = 0;
coinsp[1] = 1;
numbers[0] = 0;
numbers[1] = coins[1];
for (int i = 2; i <= numCoins; i++)
{
numbers[i] = max(coins[i] + numbers[i - 2], numbers[i - 1]);
location = maxcoins(coins[i] + numbers[i - 2], numbers[i 1]);
if (location ==
{
vindex[i] =
coinsp[i] =
}
else
{
vindex[i] =
coinsp[i] =
}
}

0)
i - 2;
i;

i - 1;
0;

while (vindex > 0)


{
temp = coinsp[index];
if (temp != 0)
{
set[count] = temp;
index = index[vindex];
count++;
}
else
{
index = index[vindex];
}
}
//output picked coins
cout << "Best set: ";
for (int n = count -1; n >= 0; n--)
{
cout << set[n];
if (n > 0)
{
cout << ", ";
}
}
cout << endl;
return numbers[numCoins];
}

You might also like