// Classe ESTRAZIONE - 2013-15 di Aldo Carpanelli
// versione 1.0.0 - 09/07/2013
// versione 1.0.1 - 22/01/2015
#include "estrazione.h"
#include <stdlib.h>
#include <windows.h>
static int srand_invocata = 0;
static const char ESTRAZIONE_kErrMemInsuff[] = "memoria insufficiente";
ESTRAZIONE::ESTRAZIONE() {
v = 0;
inizializza( 2 ); // se son meno non e' possibile estrarre!
}
ESTRAZIONE::ESTRAZIONE( short nEl ) {
v = 0;
inizializza( nEl );
}
ESTRAZIONE::~ESTRAZIONE() {
if( v ) delete[] v;
}
ESTRAZIONE::ESTRAZIONE(const ESTRAZIONE& other) {
short i, *ptr_nuovo, *ptr_other;
v = 0;
inizializza( other.qv );
ptr_nuovo = v;
ptr_other = other.v;
for( i=0; i<qv; ++i )
*ptr_nuovo++ = *ptr_other++;
qv = other.qv;
ue = other.ue;
de = other.de;
}
ESTRAZIONE& ESTRAZIONE::operator=(const ESTRAZIONE& rhs) {
short i, *ptr_nuovo, *ptr_rhs;
if (this == &rhs) return *this; // gestisce l'autoassegnamento
inizializza( rhs.qv );
ptr_nuovo = this->v;
ptr_rhs = rhs.v;
for( i=0; i<de; ++i )
*ptr_nuovo++ = *ptr_rhs++;
ue = rhs.ue;
de = rhs.de;
return *this;
}
void ESTRAZIONE::inizializza( short nEl ) {
if( !srand_invocata )
{ srand(GetTickCount()); srand_invocata = 1; }
qv = nEl;
if( qv < 0 ) qv = -qv;
if( qv < 2 ) qv = 2; // se son meno non e' possibile estrarre!
if( v ) delete[] v;
v = new short[qv];
if( !v ) throw ESTRAZIONE_kErrMemInsuff;
reset();
ue = -1;
de = qv;
}
void ESTRAZIONE::reset( void ) {
short i, *ptr = v;
for( i=0; i<qv; ++i )
*ptr++ = i;
de = qv;
}
short ESTRAZIONE::estrai( void ) {
short posizione, estratto;
short *ptr, *stop;
if( !de ) reset();
do {
posizione = rand() % de;
estratto = *(v+posizione);
} while( estratto == ue );
stop = v + de - 1;
ptr = v + posizione;
while( ptr != stop )
{ *ptr = *(ptr+1); ++ptr; }
ue = estratto;
--de;
return estratto;
}
short ESTRAZIONE::ultimo_estratto( void ) {
return ue;
}