/********************************************************************************************
02-28.cpp
Jim Millard
for CO311
********************************************************************************************/
#include <iostream>
#include <string>
using namespace std;
#include <time.h>
void FillWithRand(int [], const int size, const int used);
void SetupArray(int array[], const int size);
int SearchArray(const int array[], const int size, const int key);
void DisplayResults(const int position);
void main()
{
const int MaxSize = 20;
int Array[MaxSize];
SetupArray(Array, MaxSize); //setup the array with X numbers
cout << "A random list of 20 numbers ranging from 0 to 99 has been created." << endl
<< "See if you can guess one of them!" << endl;
int guess;
cout << "Enter a number (0..99, ctrl-d to end): ";
while (cin >> guess)
{
DisplayResults(SearchArray(Array, MaxSize, guess));
cout << "Enter a number (0..99, ctrl-d to end): ";
}
}
void SetupArray(int array[], const int size)
{
FillWithRand(array, size, size);
}
int SearchArray(const int array[], const int size, const int key)
{
int position = -1; //pre set for error/not found message
for (int i = 0; i < size; i++)
{
if (array[i] == key)
{
position = i;
break; //no sense in looking further!
}
}
return position;
}
void DisplayResults(const int position)
{
if (position > -1)
{
cout << "Good guess! The value was found at position "
<< position << " of the array." << endl;
}
else
{
cout << "Bad luck! The value is not in the list!" << endl;
}
return;
}
void FillWithRand(int Array[], const int maxsize, const int count)
{
time_t t;
srand((unsigned) time(&t));
for (int i = 0; (i < count) && (i < maxsize); i++)
{
//generate the new number
int newNumber = rand() % 100;
//check for duplicates (we don't want any)
bool found = false;
for (int j = 0; (j < count) && (j < maxsize); j++)
if (Array[j] == newNumber)
found = true;
//if there were no duplicates, save the number, otherwise redo the position
if (!found)
Array[i] = newNumber;
else
i--;
}
return;
}