blob: ec1fc4e6189c11b5d249511879581e0fd970d723 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
|
/*
* NO NOT ADAPT THIS FILE
*/
#include "NumberGuessGame.h"
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <iostream>
#define INITRANDOM 100
///////////////////////////////////////////////////////////////////////////////
// constructors / destructor
NumberGuessGame::NumberGuessGame()
{
initialize( unsigned(::time(nullptr)) );
}
NumberGuessGame::NumberGuessGame( unsigned uSeed )
{
initialize( uSeed );
}
NumberGuessGame::~NumberGuessGame()
{
}
///////////////////////////////////////////////////////////////////////////////
// create new game + boundaries
void
NumberGuessGame::createNewNumber()
{
double dInterval = ::pow( 20.0, 1.0 + 2.0*uniform() );
m_uLowerBound = unsigned( dInterval * uniform() );
m_uUpperBound = unsigned( m_uLowerBound + dInterval );
m_uNumberToGuess = m_uLowerBound + unsigned( dInterval * uniform() );
m_uNumberOfGuesses = 0;
}
unsigned
NumberGuessGame::getLowerBound() const
{
return m_uLowerBound;
}
unsigned
NumberGuessGame::getUpperBound() const
{
return m_uUpperBound;
}
///////////////////////////////////////////////////////////////////////////////
// guessing process
enum NumberGuessGame::RESULT
NumberGuessGame::guess( unsigned uValue )
{
m_uNumberOfGuesses += 1;
if ( uValue == m_uNumberToGuess )
{
std::cout << std::setw(3) << m_uNumberOfGuesses << ": number guessed : " << uValue << std::endl;
return FOUND;
}
if ( uValue < m_uNumberToGuess )
{
std::cout << std::setw(3) << m_uNumberOfGuesses << ": number too low : " << uValue << std::endl;
return TOOLOW;
}
else
{
std::cout << std::setw(3) << m_uNumberOfGuesses << ": number too high: " << uValue << std::endl;
return TOOHIGH;
}
}
unsigned
NumberGuessGame::numberOfGuesses() const
{
return m_uNumberOfGuesses;
}
///////////////////////////////////////////////////////////////////////////////
// private members
void
NumberGuessGame::initialize( unsigned uSeed )
{
m_uLowerBound = 0;
m_uUpperBound = 1;
m_uNumberToGuess = unsigned( -1 );
m_uNumberOfGuesses = unsigned( -1 );
::srand( uSeed );
for (unsigned n=0; n<INITRANDOM; n++ )
::rand();
}
double
NumberGuessGame::uniform() const
{
return ::rand() / double(RAND_MAX);
}
|