コード例 #1
0
void RandomSequence(int *seq, int number) {
	static int reservation[2*SENSOR_MAX_NUM];
    static int firstRun = 1;
    int devCount[SENSOR_MAX_NUM];

	int	idx, i, tmp;

	if (number > numOfSensors(0)) {
		printf("sequence: too many devices\n");
		exit(0);
	}

    if (firstRun == 1) {
        firstRun = 0;
        for (i = 0; i < numOfSensors(0); i++)
            devCount[i] = 0;
        idx = 0;
	    while (idx < number) {
		    i = intRand(0, number-1);
		    if (devCount[i] < overlap) {
                devCount[i]++;
			    reservation[idx] = i;
			    idx++;
		    }
	    }
    }

	for (i = 0; i < number; i++)
        devCount[i] = 0;

    for (i = 0; i < number; i++) {
        reservation[i+number] = reservation[i];
        devCount[reservation[i]]++;
    }

    idx = 0;
	while (idx < number) {
		i = intRand(0, number-1);
		if (devCount[i] < 2) {              // if not yet twice in list
            if (devCount[i] < 1) {          //    if not in list
                devCount[i]++;
			    reservation[idx] = i;
			    idx++;
            }
            else {
                tmp = intRand(0, 9);        //    if in list 
                if (tmp > 6) {              //        do only for 5%
                    devCount[i]++;
			        reservation[idx] = i;
			        idx++;
                }
            }
		}
	}

    for (i = 0; i < number; i++) {          
			*seq = reservation[i+number];
			seq++;
    }
}
コード例 #2
0
ファイル: organic.cpp プロジェクト: fxiangyi/lmms
void organicInstrument::randomiseSettings()
{

	for( int i = 0; i < m_numOscillators; i++ )
	{
		m_osc[i]->m_volModel.setValue( intRand( 0, 100 ) );

		m_osc[i]->m_detuneModel.setValue( intRand( -5, 5 ) );

		m_osc[i]->m_panModel.setValue( 0 );

		m_osc[i]->m_oscModel.setValue( intRand( 0, 5 ) );
	}

}
コード例 #3
0
ファイル: misiones.cpp プロジェクト: vnportnoy/Taller
void Misiones::agregarBandera() {
	bool done=false;
	int cont=0;
	int x,y; //posiciones de la bandera
	int w,h; //dimensiones del mapa
	mapa.getSize(&w, &h);
	while (!done && cont<999) {
		x=intRand(0,w-1);
		y=intRand(0,h-1);
		if(mapa.getTile(x, y)->isCaminable() && !this->hayBandera(x,y)) {
			done = true;
		}
		cont++;
	}
	//Agrego la nueva bandera a la lista
	banderas.push_back(std::make_pair(x,y));
}
コード例 #4
0
void DataProvider::randomWord(int& wordId, std::string& word) {
  int N = int2word_.size();
  int id = intRand(0, N);
  wordId = restrictedVocab1_[id];
  word = getWord(id);
}
コード例 #5
0
/*
  Randomized Rounding Heuristic
  Returns 1 if solution, 0 if not
*/
int
CbcHeuristicRandRound::solution(double & solutionValue,
                                double * betterSolution)
{
    // rlh: Todo: Memory Cleanup

    //  std::cout << "Entering the Randomized Rounding Heuristic" << std::endl;

    setWhen(1);  // setWhen(1) didn't have the effect I expected (e.g., run once).

    // Run only once.
    //
    //    See if at root node
    bool atRoot = model_->getNodeCount() == 0;
    int passNumber = model_->getCurrentPassNumber();
    //    Just do once
    if (!atRoot || passNumber > 1) {
        // std::cout << "Leaving the Randomized Rounding Heuristic" << std::endl;
        return 0;
    }

    std::cout << "Entering the Randomized Rounding Heuristic" << std::endl;
    typedef struct {
        int numberSolutions;
        int maximumSolutions;
        int numberColumns;
        double ** solution;
        int * numberUnsatisfied;
    } clpSolution;

    double start = CoinCpuTime();
    numCouldRun_++; //
#ifdef HEURISTIC_INFORM
    printf("Entering heuristic %s - nRuns %d numCould %d when %d\n",
	   heuristicName(),numRuns_,numCouldRun_,when_);
#endif
    // Todo: Ask JJHF what "number of times
    // the heuristic could run" means.

    OsiSolverInterface * solver = model_->solver()->clone();
    double primalTolerance ;
    solver->getDblParam(OsiPrimalTolerance, primalTolerance) ;
    OsiClpSolverInterface * clpSolver = dynamic_cast<OsiClpSolverInterface *> (solver);
    assert (clpSolver);
    ClpSimplex * simplex = clpSolver->getModelPtr();

    // Initialize the structure holding the solutions for the Simplex iterations
    clpSolution solutions;
    // Set typeStruct field of ClpTrustedData struct to 1 to indicate
    // desired behavior for  RandRound heuristic (which is what?)
    ClpTrustedData trustedSolutions;
    trustedSolutions.typeStruct = 1;
    trustedSolutions.data = &solutions;
    solutions.numberSolutions = 0;
    solutions.maximumSolutions = 0;
    solutions.numberColumns = simplex->numberColumns();
    solutions.solution = NULL;
    solutions.numberUnsatisfied = NULL;
    simplex->setTrustedUserPointer(&trustedSolutions);

    // Solve from all slack to get some points
    simplex->allSlackBasis();

    // Calling primal() invalidates pointers to some rim vectors,
    // like...row sense (!)
    simplex->primal();

    // 1. Okay - so a workaround would be to copy the data I want BEFORE
    // calling primal.
    // 2. Another approach is to ask the simplex solvers NOT to mess up my
    // rims.
    // 3. See freeCachedResults() for what is getting
    // deleted. Everything else points into the structure.
    // ...or use collower and colupper rather than rowsense.
    // ..store address of where one of these

    // Store the basic problem information
    // -Get the number of columns, rows and rhs vector
    int numCols = clpSolver->getNumCols();
    int numRows = clpSolver->getNumRows();

    // Find the integer variables (use columnType(?))
    // One if not continuous, that is binary or general integer)
    // columnType() = 0 continuous
    //              = 1 binary
    //              = 2 general integer
    bool * varClassInt = new bool[numCols];
    const char* columnType = clpSolver->columnType();
    int numGenInt = 0;
    for (int i = 0; i < numCols; i++) {
        if (clpSolver->isContinuous(i))
            varClassInt[i] = 0;
        else
            varClassInt[i] = 1;
        if (columnType[i] == 2) numGenInt++;
    }

    // Heuristic is for problems with general integer variables.
    // If there are none, quit.
    if (numGenInt++ < 1) {
        delete [] varClassInt ;
        std::cout << "Leaving the Randomized Rounding Heuristic" << std::endl;
        return 0;
    }


    // -Get the rows sense
    const char * rowSense;
    rowSense = clpSolver->getRowSense();

    // -Get the objective coefficients
    double *originalObjCoeff = CoinCopyOfArray(clpSolver->getObjCoefficients(), numCols);

    // -Get the matrix of the problem
    // rlh: look at using sparse representation
    double ** matrix = new double * [numRows];
    for (int i = 0; i < numRows; i++) {
        matrix[i] = new double[numCols];
        for (int j = 0; j < numCols; j++)
            matrix[i][j] = 0;
    }

    const CoinPackedMatrix* matrixByRow = clpSolver->getMatrixByRow();
    const double * matrixElements = matrixByRow->getElements();
    const int * matrixIndices = matrixByRow->getIndices();
    const int * matrixStarts = matrixByRow->getVectorStarts();
    for (int j = 0; j < numRows; j++) {
        for (int i = matrixStarts[j]; i < matrixStarts[j+1]; i++) {
            matrix[j][matrixIndices[i]] = matrixElements[i];
        }
    }

    double * newObj = new double [numCols];
    srand ( static_cast<unsigned int>(time(NULL) + 1));
    int randNum;

    // Shuffle the rows:
    // Put the rows in a random order
    // so that the optimal solution is a different corner point than the
    // starting point.
    int * index = new int [numRows];
    for (int i = 0; i < numRows; i++)
        index[i] = i;
    for (int i = 0; i < numRows; i++) {
        int temp = index[i];
        int randNumTemp = i + intRand(numRows - i);
        index[i] = index[randNumTemp];
        index[randNumTemp] = temp;
    }

    // Start finding corner points by iteratively doing the following:
    // - contruct a randomly tilted objective
    // - solve
    for (int i = 0; i < numRows; i++) {
        // TODO: that 10,000 could be a param in the member data
        if (solutions.numberSolutions  > 10000)
            break;
        randNum = intRand(2);
        for (int j = 0; j < numCols; j++) {
            // for row i and column j vary the coefficient "a bit"
            if (randNum == 1)
                // if the element is zero, then set the new obj
                // coefficient to 0.1 (i.e., round up)
                if (fabs(matrix[index[i]][j]) < primalTolerance)
                    newObj[j] = 0.1;
                else
                    // if the element is nonzero, then increase the new obj
                    // coefficient "a bit"
                    newObj[j] = matrix[index[i]][j] * 1.1;
            else
                // if randnum is 2, then
                // if the element is zero, then set the new obj coeffient
                // to NEGATIVE 0.1 (i.e., round down)
                if (fabs(matrix[index[i]][j]) < primalTolerance)
                    newObj[j] = -0.1;
                else
                    // if the element is nonzero, then DEcrease the new obj coeffienct "a bit"
                    newObj[j] = matrix[index[i]][j] * 0.9;
        }
        // Use the new "tilted" objective
        clpSolver->setObjective(newObj);

        // Based on the row sense, we decide whether to max or min
        if (rowSense[i] == 'L')
            clpSolver->setObjSense(-1);
        else
            clpSolver->setObjSense(1);

        // Solve with primal simplex
        simplex->primal(1);
        // rlh+ll: This was the original code. But we already have the
        // model pointer (it's in simplex). And, calling getModelPtr()
        // invalidates the cached data in the OsiClpSolverInterface
        // object, which means our precious rowsens is lost. So let's
        // not use the line below...
        /******* clpSolver->getModelPtr()->primal(1); */
        printf("---------------------------------------------------------------- %d\n", i);
    }
    // Iteratively do this process until...
    // either you reach the max number of corner points (aka 10K)
    // or all the rows have been used as an objective.

    // Look at solutions
    int numberSolutions = solutions.numberSolutions;
    //const char * integerInfo = simplex->integerInformation();
    //const double * columnLower = simplex->columnLower();
    //const double * columnUpper = simplex->columnUpper();
    printf("there are %d solutions\n", numberSolutions);

    // Up to here we have all the corner points
    // Now we need to do the random walks and roundings

    double ** cornerPoints = new double * [numberSolutions];
    for (int j = 0; j < numberSolutions; j++)
        cornerPoints[j] = solutions.solution[j];

    bool feasibility = 1;
    // rlh: use some COIN max instead of 1e30 (?)
    double bestObj = 1e30;
    std::vector< std::vector <double> > feasibles;
    int numFeasibles = 0;

    // Check the feasibility of the corner points
    int numCornerPoints = numberSolutions;

    const double * rhs = clpSolver->getRightHandSide();
    // rlh: row sense hasn't changed. why a fresh copy?
    // Delete next line.
    rowSense = clpSolver->getRowSense();

    for (int i = 0; i < numCornerPoints; i++) {
        //get the objective value for this this point
        double objValue = 0;
        for (int k = 0; k < numCols; k++)
            objValue += cornerPoints[i][k] * originalObjCoeff[k];

        if (objValue < bestObj) {
            // check integer feasibility
            feasibility = 1;
            for (int j = 0; j < numCols; j++) {
                if (varClassInt[j]) {
                    double closest = floor(cornerPoints[i][j] + 0.5);
                    if (fabs(cornerPoints[i][j] - closest) > primalTolerance) {
                        feasibility = 0;
                        break;
                    }
                }
            }
            // check all constraints satisfied
            if (feasibility) {
                for (int irow = 0; irow < numRows; irow++) {
                    double lhs = 0;
                    for (int j = 0; j < numCols; j++) {
                        lhs += matrix[irow][j] * cornerPoints[i][j];
                    }
                    if (rowSense[irow] == 'L' && lhs > rhs[irow] + primalTolerance) {
                        feasibility = 0;
                        break;
                    }
                    if (rowSense[irow] == 'G' && lhs < rhs[irow] - primalTolerance) {
                        feasibility = 0;
                        break;
                    }
                    if (rowSense[irow] == 'E' && (lhs - rhs[irow] > primalTolerance || lhs - rhs[irow] < -primalTolerance)) {
                        feasibility = 0;
                        break;
                    }
                }
            }

            if (feasibility) {
                numFeasibles++;
                feasibles.push_back(std::vector <double> (numCols));
                for (int k = 0; k < numCols; k++)
                    feasibles[numFeasibles-1][k] = cornerPoints[i][k];
                printf("obj: %f\n", objValue);
                if (objValue < bestObj)
                    bestObj = objValue;
            }
        }
    }
    int numFeasibleCorners;
    numFeasibleCorners = numFeasibles;
    //find the center of gravity of the corner points as the first random point
    double * rp = new double[numCols];
    for (int i = 0; i < numCols; i++) {
        rp[i] = 0;
        for (int j = 0; j < numCornerPoints; j++) {
            rp[i] += cornerPoints[j][i];
        }
        rp[i] = rp[i] / numCornerPoints;
    }

    //-------------------------------------------
    //main loop:
    // -generate the next random point
    // -round the random point
    // -check the feasibility of the random point
    //-------------------------------------------

    srand ( static_cast<unsigned int>(time(NULL) + 1));
    int numRandomPoints = 0;
    while (numRandomPoints < 50000) {
        numRandomPoints++;
        //generate the next random point
        int randomIndex = intRand(numCornerPoints);
        double random = CoinDrand48();
        for (int i = 0; i < numCols; i++) {
            rp[i] = (random * (cornerPoints[randomIndex][i] - rp[i])) + rp[i];
        }

        //CRISP ROUNDING
        //round the random point just generated
        double * roundRp = new double[numCols];
        for (int i = 0; i < numCols; i++) {
            roundRp[i] = rp[i];
            if (varClassInt[i]) {
                if (rp[i] >= 0) {
                    if (fmod(rp[i], 1) > 0.5)
                        roundRp[i] = floor(rp[i]) + 1;
                    else
                        roundRp[i] = floor(rp[i]);
                } else {
                    if (fabs(fmod(rp[i], 1)) > 0.5)
                        roundRp[i] = floor(rp[i]);
                    else
                        roundRp[i] = floor(rp[i]) + 1;

                }
            }
        }


        //SOFT ROUNDING
        // Look at original files for the "how to" on soft rounding;
        // Soft rounding omitted here.

        //Check the feasibility of the rounded random point
        // -Check the feasibility
        // -Get the rows sense
        rowSense = clpSolver->getRowSense();
        rhs = clpSolver->getRightHandSide();

        //get the objective value for this feasible point
        double objValue = 0;
        for (int i = 0; i < numCols; i++)
            objValue += roundRp[i] * originalObjCoeff[i];

        if (objValue < bestObj) {
            feasibility = 1;
            for (int i = 0; i < numRows; i++) {
                double lhs = 0;
                for (int j = 0; j < numCols; j++) {
                    lhs += matrix[i][j] * roundRp[j];
                }
                if (rowSense[i] == 'L' && lhs > rhs[i] + primalTolerance) {
                    feasibility = 0;
                    break;
                }
                if (rowSense[i] == 'G' && lhs < rhs[i] - primalTolerance) {
                    feasibility = 0;
                    break;
                }
                if (rowSense[i] == 'E' && (lhs - rhs[i] > primalTolerance || lhs - rhs[i] < -primalTolerance)) {
                    feasibility = 0;
                    break;
                }
            }
            if (feasibility) {
                printf("Feasible Found.\n");
                printf("%.2f\n", CoinCpuTime() - start);
                numFeasibles++;
                feasibles.push_back(std::vector <double> (numCols));
                for (int i = 0; i < numCols; i++)
                    feasibles[numFeasibles-1][i] = roundRp[i];
                printf("obj: %f\n", objValue);
                if (objValue < bestObj)
                    bestObj = objValue;
            }
        }
        delete [] roundRp;
    }
    printf("Number of Feasible Corners: %d\n", numFeasibleCorners);
    printf("Number of Feasibles Found: %d\n", numFeasibles);
    if (numFeasibles > 0)
        printf("Best Objective: %f\n", bestObj);
    printf("time: %.2f\n", CoinCpuTime() - start);

    if (numFeasibles == 0) {
        // cleanup
        delete [] varClassInt;
        for (int i = 0; i < numRows; i++)
            delete matrix[i];
        delete [] matrix;
        delete [] newObj;
        delete [] index;
        for (int i = 0; i < numberSolutions; i++)
            delete cornerPoints[i];
        delete [] cornerPoints;
        delete [] rp;
        return 0;
    }

    // We found something better
    solutionValue = bestObj;
    for (int k = 0; k < numCols; k++) {
        betterSolution[k] =  feasibles[numFeasibles-1][k];
    }
    delete [] varClassInt;
    for (int i = 0; i < numRows; i++)
        delete matrix[i];
    delete [] matrix;
    delete [] newObj;
    delete [] index;
    for (int i = 0; i < numberSolutions; i++)
        delete cornerPoints[i];
    delete [] cornerPoints;
    delete [] rp;
    std::cout << "Leaving the Randomized Rounding Heuristic" << std::endl;
    return 1;

}
コード例 #6
0
ファイル: enemigoServer.cpp プロジェクト: vnportnoy/Taller
void Enemigo::atacar(string& NickAtacado,PlayerManager& pm,ServerSocket& socks){
	BitStream bs;
	int danio = intRand(0,30);
	//resto danio si ataca a un golem o a un enemigo
	bool encontro = false;
	bool murio = false;
	for(auto it = pm.getEnemies().begin();it !=pm.getEnemies().end();it++) {
		Enemigo* unEnemigo = it->second;
		if(unEnemigo->getNick() == NickAtacado){
			unEnemigo->hacerDanio(danio);
			encontro = true;
			if(!it->second->estaVivo()){
				murio = true;
				pm.getEnemies().erase(it);
				break;
			}
		}
	}
	//para golem
	if(!encontro){
		for(auto it = pm.getGolems().begin();it !=pm.getGolems().end();it++) {
			Golem* unGolem = it->second;
			if(unGolem->getNick() == NickAtacado){
				unGolem->hacerDanio(danio);
			
				if(!it->second->estaVivo()){
					//aviso a los demas que murio enemigo
					murio = true;
					pm.getGolems().erase(it);
					break;
				}
			}
		}
	}
	//aviso del ataque
	for(auto it = socks.get_clients().begin();it !=socks.get_clients().end();it++) {
		//ataco con la danio
		bs.clear();
		bs << PROTO::ATACAR << this->getNick() << NickAtacado;
		it->second.send(bs.str());
		//mando danio
		bs.clear();
		bs << PROTO::DAMAGE << this->getNick() << NickAtacado << danio;
		it->second.send(bs.str());
		std::cout << "Update " << it->second.nick << " que " << this->getNick() << "->" << NickAtacado << endl;
		//aviso si murio
		if(murio){
			//Veo si termino la mision
			if (mision.getTipo() == Misiones::MISION_ENEMIGO) {
				if (mision.enemigoMision() == NickAtacado) {
					bs.clear();
					bs << PROTO::WINNER << pm.getEnemy(NickAtacado)->ultimoAtacante();
					it->second.send(bs.str());
				}
			} else {
				bs.clear();
				bs << PROTO::ENEMY_DEAD << NickAtacado;
				it->second.send(bs.str());
			}
		}
	}
	return;
}
コード例 #7
0
int main(int argc, char *argv[]) {

	struct sigaction sig;

    int			StationSeq[SENSOR_MAX_NUM];

    int 		sfd, maxWait, i, j, rand;
	int			anzSensors;
    char		buf[BUF_SIZE];
    SensorData  sensor;
    float		deltaT;

    float       tempPreset[8]  = {20, 45, 30, 20, 15, 10, 15, 20};
    float       startup[8]     = {0, 0, 0, 0, 0, 0, 0, 0};
    int         sequenceNr[8]  = {0, 0, 0, 0, 0, 0, 0, 0};

    //*** check for hostname ... a kind of hack
	
    if (argc < 4)  {
        printf("Need number of devices, hostname or IP address and port number\n");
        exit(-1);
    }

	if ((anzSensors = numOfSensors(atoi(argv[1]))) < 0) {
		printf("\n*** invalid number of sensor devices ***\n\n");
		exit(0);
	}
	
	// set up signal handlers
	sigemptyset(&sig.sa_mask);
	sig.sa_handler = SignalHandler;
	sig.sa_flags = 0;
	sigaction(SIGTERM, &sig, NULL);
	sigaction(SIGKILL, &sig, NULL);
	sigaction(SIGINT,  &sig, NULL);

    sleep(2);
	printf("Sensor device starting up\n");

    globalK = 0;
    while (globalK < MAX_ITERATIONS) {
 
	    RandomSequence(StationSeq, anzSensors);

	    for (i = 0; i <  anzSensors; i++) { 	// for all devices
            deltaT = intRand(-2, 2);
            sensor.deviceID   = StationSeq[i];
            sensor.sequenceNr = sequenceNr[sensor.deviceID];
            sensor.valIS      = deltaT + startup[sensor.deviceID];
            sensor.valREF     = tempPreset[sensor.deviceID];
			sensor.status     = 0;

            sequenceNr[sensor.deviceID]++;
            sfd = connToServer(argv[2], atoi(argv[3]));
		    write(sfd, (char *)&sensor,sizeof(SensorData));
		    close(sfd);           
		    maxWait		= 4000000;
		    maxWait		= maxWait / anzSensors;
		    rand		= intRand(maxWait/3, maxWait);
		    usleep(rand);
        }
        for (j = 0; j < anzSensors; j++) {
            if (startup[j] < tempPreset[j])
                startup[j] += 2;
            else
                startup[j] = tempPreset[j];
        }
	    globalK++;
    }
    exit(0);

} // end main