Beispiel #1
0
Particle* Particle::CreateChild(float dExpansionRadius, float dYawRange) {
	float newX = this->x + Randomize(-dExpansionRadius, dExpansionRadius);
	float newY = this->y + Randomize(-dExpansionRadius, dExpansionRadius);
	float newYaw = this->yaw + Randomize(-dYawRange, dYawRange);
	Particle* p = new Particle(newX, newY, newYaw, 1);
	p->SetMap(this->map);
	p->SetMaxDistance(this->maxDistance);
	p->SetLaserProxy(this->laserProxy);

	return p;
}
Beispiel #2
0
int main()
{
   Queue<int> line;                                  // Line-up waiting to get in

   int patrons = InitialPatrons;                     // Number people in the Inn

   int time, i, arrivals, departures, entry_time;

   Randomize();                                      // Seed the random numbers

   for (time=0; time<300; time++)                    // Each minute from 8 - 1.
   {
      arrivals = RandomNum(num_arrive[time/60]);     // arriving this minute

      for (i=0; i<arrivals; i++) line.Enqueue(time); // End of the line

      departures = RandomNum(num_depart[time/60]);   // leaving this minute

      patrons -= departures;                         // bye-bye

      while (patrons < Capacity && !line.Empty())
      {
         entry_time = line.Front();                  // move from line into Inn
         line.Dequeue();
         patrons++;
      }
      cout << setw(4) << time << ":  " << arrivals << "  " << departures
           << setw(5) << patrons << endl;
   }

   cout << setw(4) << time << ":  " << arrivals << "  " << departures
        << setw(5) << patrons << endl;

   return (0);
}
int Week4P3(void)
{
	int r = Randomize(0, 50);
	int i;
	
	for (i = 100; r > 0; i--)
	{
		printf("%d",r);
		if (r % 2 == 0) 
		{
			r = r / 2;
			printf("-> ");
		}
		else if (r % 2 != 0 && r != 1)
		{
			r = 3 * r + 1;
			printf("-> ");
		}
		else if (r == 1)
		{
			printf("\n");
			system("pause");
			exit(0);
		}
	}
	return 0;
}
Beispiel #4
0
void Generate_Initial_Velocities( reax_system *system, real T )
{
  int i;
  real m, scale, norm;
  
  
  if( T <= 0.1 ) {
    for( i = 0; i < system->n; i++ )
      rvec_MakeZero( system->my_atoms[i].v );
  }
  else {
    Randomize();
    
    for( i = 0; i < system->n; i++ ) {
      rvec_Random( system->my_atoms[i].v );
      
      norm = rvec_Norm_Sqr( system->my_atoms[i].v );
      m = system->reax_param.sbp[ system->my_atoms[i].type ].mass;
      scale = sqrt( m * norm / (3.0 * K_B * T) );
      
      rvec_Scale( system->my_atoms[i].v, 1./scale, system->my_atoms[i].v );
      
      // fprintf( stderr, "v = %f %f %f\n", 
      // system->my_atoms[i].v[0], 
      // system->my_atoms[i].v[1], 
      // system->my_atoms[i].v[2] );      
      
      // fprintf( stderr, "scale = %f\n", scale );
      // fprintf( stderr, "v = %f %f %f\n", 
      // system->my_atoms[i].v[0], 
      // system->my_atoms[i].v[1], 
      // system->my_atoms[i].v[2] );
    }
  }
}
Beispiel #5
0
//---------------------------------------------------------------------------
void __fastcall TMainForm::AddPhoto(AnsiString existingFileName)
{
	AnsiString photoFile = "";
    AnsiString hash = "";
	if (existingFileName.IsEmpty()) {
		Randomize();
		hash = GetMD5Hash(AnsiString(Random(99999999999999999999999999999999)));
		photoFile = GetAppPath()+"Photo\\"+hash+".jpg";
	} else {
		hash = existingFileName;
	}
    photoFile = GetAppPath()+"Photo\\"+hash+".jpg";

	if (OpenPictureDialog->Execute()) {
		if (!OpenPictureDialog->FileName.IsEmpty()) {
			if (FileExists(OpenPictureDialog->FileName)) {
				int ID = DBGrid->Fields[14]->AsInteger;
				AnsiString query = "UPDATE tblMembers SET mPhoto = '" + hash + "' WHERE ID = " + AnsiString(ID);
				CMData->ADOQuery->SQL->Clear();
				CMData->ADOQuery->SQL->Add(query);
				CMData->ADOQuery->ExecSQL();
				query = AnsiString("select mSur, mName, mPat, mBD, mCD, mNat, mAdd, mTel, mFam, mPro, ") +
					AnsiString ("mLife, mSug, mEtc, mPhoto, ID from tblMembers order by mSur, mName, mPat");
				CMData->ADOQuery->SQL->Clear();
				CMData->ADOQuery->SQL->Add(query);
				CMData->ADOQuery->Open();
				CopyFile(OpenPictureDialog->FileName.c_str(), photoFile.c_str(), false);
			} else {
				MessageDlg("Файл '" + OpenPictureDialog->FileName + "' не найден!", mtError, TMsgDlgButtons() << mbOK, 0);
			}
		}
	}
}
bool pawsCharBirth::OnButtonPressed(int /*mouseButton*/, int /*keyModifier*/, pawsWidget* widget)
{
        /// Check to see if it is one of the sibling buttons
    if ( strncmp( widget->GetName(), "sibling", 7 ) == 0 )
    {
        if (lastSiblingsChoice != -1)
            createManager->RemoveChoice( lastSiblingsChoice );
        createManager->AddChoice( widget->GetID() );
        lastSiblingsChoice = widget->GetID();                           
        pawsMultiLineTextBox* siblingsDesc = (pawsMultiLineTextBox*) FindWidget("sibling_desc");
        siblingsDesc->SetText( createManager->GetDescription(widget->GetID()) );
        return true;        
    } 

    if ( strcmp(widget->GetName(),"randomize") == 0 )
    {
        Randomize();
        return true;
    }

    int id = widget->GetID();
    switch ( id )
    {   
    case BACK_BUTTON:
        {
            Hide();
            PawsManager::GetSingleton().FindWidget( "CharCreateMain" )->Show();
            return true;
        }
    case NEXT_BUTTON:
        {
            if (months->GetSelectedRowNum() == -1)
            {
                psSystemMessage error(0,MSG_ERROR,PawsManager::GetSingleton().Translate("Please choose your birth month"));
                error.FireEvent();
                return true;
            }

            if (days->GetSelectedRowNum() == -1)
            {
                psSystemMessage error(0,MSG_ERROR,PawsManager::GetSingleton().Translate("Please choose your birthday"));
                error.FireEvent();
                return true;
            }

            if (lastSiblingsChoice == -1)
            {
                psSystemMessage error(0,MSG_ERROR,PawsManager::GetSingleton().Translate("Please choose your sibling count"));
                error.FireEvent();
                return true;
            }

            createManager->GetParentData();
            Hide();
            PawsManager::GetSingleton().FindWidget( "Parents" )->Show();
            return true;
        }
    }
    return false;
}
Beispiel #7
0
void G_InitNew(skill_t skill,Word map)
{
	Randomize();		/* Reset the random number generator */

	gamemap = map;
	gameskill = skill;

/* Force players to be initialized upon first level load */

	players.playerstate = PST_REBORN;
	players.mo = 0;	/* For net consistancy checks */
	
	DemoRecording = FALSE;		/* No demo in progress */
	DemoPlayback = FALSE;

	if (skill == sk_nightmare ) {		/* Hack for really BAD monsters */
		states[S_SARG_ATK1].Time = 2*4;	/* Speed up the demons */
		states[S_SARG_ATK2].Time = 2*4;
		states[S_SARG_ATK3].Time = 2*4;
		mobjinfo[MT_SERGEANT].Speed = 15;
		mobjinfo[MT_SHADOWS].Speed = 15;
		mobjinfo[MT_BRUISERSHOT].Speed = 40;	/* Baron of hell */
		mobjinfo[MT_HEADSHOT].Speed = 40;		/* Cacodemon */
		mobjinfo[MT_TROOPSHOT].Speed = 40;
	} else {
		states[S_SARG_ATK1].Time = 4*4;		/* Set everyone back to normal */
		states[S_SARG_ATK2].Time = 4*4;
		states[S_SARG_ATK3].Time = 4*4;
		mobjinfo[MT_SERGEANT].Speed = 8;
		mobjinfo[MT_SHADOWS].Speed = 8;
		mobjinfo[MT_BRUISERSHOT].Speed = 30;
		mobjinfo[MT_HEADSHOT].Speed = 20;
		mobjinfo[MT_TROOPSHOT].Speed = 20;
	}
}
Beispiel #8
0
/*
 * Function: main
 * -----------------
 * Serves as entry point of program. Takes in all user inputs to determine specific boggle configuration.
 * Then, it gives the user a chance to find words in the boggleBoard. Then, the computer takes over
 * to find any remaining words. Finally, gives user option to play another round.
 *
 *@return 0 if program completed successfully.
 */
int main()
{
	Randomize(); //initializes random constructor
	SetWindowSize(8, 5);
	InitGraphics();
	Welcome();
	GiveInstructions();
	Lexicon wordList("lexicon.dat"); //generates list of all possible words
	while (true) {
		Lexicon usedWords; //generates a list that stores all words found by the player and computer
		InitGraphics();
		SoundFeature();
		int boardDimension = BoggleBoardSize();
		DrawBoard(boardDimension, boardDimension);
		Grid<char> boggleBoard(boardDimension, boardDimension);
		if (!UserBoardConfiguration()) {
			InitializeRandomBoard(boggleBoard); //if user chooses not to specify board configuration, a random one is generated
		} else {
			string diceConfig = GetDiceConfiguration(boardDimension);
			SetDiceConfiguration(boggleBoard, diceConfig);
		}
		DrawBoggleBoard(boggleBoard);
		Grid<bool> usedDice(boggleBoard.numRows(), boggleBoard.numCols());
		CreateMarker(usedDice);
		InputGuesses(boggleBoard, wordList, usedWords, usedDice); //player's turn
		FindRemainingWords(boggleBoard, wordList, usedWords, usedDice); //computer's turn
		PlayNamedSound("thats pathetic.wav"); //assumes the player will always lose to the computer
		if (!GameContinue()) break;
	}
	return 0;
}
Beispiel #9
0
cCaveTunnel::cCaveTunnel(
	int a_BlockStartX, int a_BlockStartY, int a_BlockStartZ, int a_StartRadius,
	int a_BlockEndX,   int a_BlockEndY,   int a_BlockEndZ,   int a_EndRadius,
	cNoise & a_Noise
)
{
	m_Points.push_back(cCaveDefPoint(a_BlockStartX, a_BlockStartY, a_BlockStartZ, a_StartRadius));
	m_Points.push_back(cCaveDefPoint(a_BlockEndX,   a_BlockEndY,   a_BlockEndZ,   a_EndRadius));

	if ((a_BlockStartY <= 0) && (a_BlockEndY <= 0))
	{
		// Don't bother detailing this cave, it's under the world anyway
		m_MinBlockX = m_MaxBlockX = 0;
		m_MinBlockY = m_MaxBlockY = -1;
		m_MinBlockZ = m_MaxBlockZ = 0;
		return;
	}

	Randomize(a_Noise);
	Smooth();

	// We know that the linear finishing won't affect the bounding box, so let's calculate it now, as we have less data:
	CalcBoundingBox();

	FinishLinear();
}
Beispiel #10
0
string BuildMarkovString(int k, Map< Map<int> > &p, string &max_p_pattern) {
    string new_text = max_p_pattern;
    string current_view = max_p_pattern;
    Randomize();
    int r_index;
    string key;
    for (int i = 0; i < nCHARS; i++) {
		int total = p[current_view]["TOTAL"];
        r_index = RandomInteger(1, p[current_view]["TOTAL"]);
        Map<int>::Iterator itr = p[current_view].iterator();
        
        while (itr.hasNext()) {
            key = itr.next();
            if ( key == "TOTAL" )
                key = itr.next();
            if (r_index <= p[current_view][key]) {
                new_text += key;
                current_view += key;
                current_view.replace(0, 1, "");
                break;
            }
            else {
                r_index -= p[current_view][key];
            }
        }   
    }
    return new_text;
}
Beispiel #11
0
int main() {
    Randomize();

    int voters;
    while(true) {
        cout << "Enter number of voters: ";
        voters = GetInteger();
        if (voters > 0) break;
        cout << "Please enter a positive number." << endl;
    }
    
    double spread;
    while(true) {
        cout << "Enter percentage spread between candidates: ";
        spread = GetReal();
        if (spread >= 0 && spread <= 1) break;
        cout << "Spread must be between 0 and 1.0" << endl;
    }

    double error;
    while(true) {
        cout << "Enter voting error percentage: ";
        error = GetReal();
        if (error >= 0 && error <= 1) break;
        cout << "Error percentage must be between 0 and 1.0 " << endl;
    }

    cout << endl << "Chance of an invalid election result after " 
            << NUM_TRIALS << " trials = " 
            << CalculateError(voters, spread, error) << "%" << endl;
    return 0;
}
Beispiel #12
0
int main(int argc, char** argv)
{
  int numtrials = 1000000; // Lets try a million times to break this.
  int a, b; // The values to be swapped
  int origa, origb; // Copies to make sure the swap worked.
  Randomize();


  for (int i=0; i<numtrials; i++) {
    // First, load a and be with random bit patterns.
    a = Random(2);
    b = Random(2);
    for (int j=0; j<31; j++) {
      a = a << 1; a += Random(2);
      b = b << 1; b += Random(2);
    }

    // Now, save them to check later
    origa = a; origb = b;

    // Now, do the swap
    a = a + b;
    b = a - b;
    a = a - b;

    // Now check that it is OK
    if ((a != origb) || (b != origa))
      cout << "ERROR: a was " << origa << ", b was " << origb << endl;
  }

  return 0;
}
Beispiel #13
0
//---------------------------------------------------------------------------
void CoreInitialize()
{
  Randomize();
  CryptographyInitialize();

  // configuration needs to be created and loaded before putty is initialized,
  // so that random seed path is known
  Configuration = CreateConfiguration();

  try
  {
    Configuration->Load();
  }
  catch (Exception & E)
  {
    ShowExtendedException(&E);
  }

  PuttyInitialize();
  #ifndef NO_FILEZILLA
  TFileZillaIntf::Initialize();
  #endif

  StoredSessions = new TStoredSessionList();

  try
  {
    StoredSessions->Load();
  }
  catch (Exception & E)
  {
    ShowExtendedException(&E);
  }
}
Beispiel #14
0
//---------------------------------------------------------------------------
WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
    try
    {
         Randomize();
         Application->Initialize();
         Application->HelpFile = "";
		 Application->CreateForm(__classid(TFMain_11011981), &FMain_11011981);
         Application->CreateForm(__classid(TFExplorer_11011981), &FExplorer_11011981);
         Application->CreateForm(__classid(TFTypeInfo_11011981), &FTypeInfo_11011981);
         Application->CreateForm(__classid(TFStringInfo_11011981), &FStringInfo_11011981);
         Application->CreateForm(__classid(TFInputDlg_11011981), &FInputDlg_11011981);
         Application->CreateForm(__classid(TFindDlg_11011981), &FindDlg_11011981);
         Application->CreateForm(__classid(TFEditFunctionDlg_11011981), &FEditFunctionDlg_11011981);
         Application->CreateForm(__classid(TFEditFieldsDlg_11011981), &FEditFieldsDlg_11011981);
         Application->CreateForm(__classid(TFAboutDlg_11011981), &FAboutDlg_11011981);
         Application->CreateForm(__classid(TFKBViewer_11011981), &FKBViewer_11011981);
         Application->CreateForm(__classid(TFLegend_11011981), &FLegend_11011981);
         Application->CreateForm(__classid(TFHex2DoubleDlg_11011981), &FHex2DoubleDlg_11011981);
         Application->CreateForm(__classid(TFPlugins), &FPlugins);
         Application->CreateForm(__classid(TFActiveProcesses), &FActiveProcesses);
         Application->Run();
    }
    catch (Exception &exception)
    {
         Application->ShowException(&exception);
    }
    return 0;
}
void __fastcall TForm2::FormCreate(TObject *Sender) {
	for (int i = 8; i < 256; i++) {
		cmbSifre->Items->Add(i);
	}
	cmbSifre->ItemIndex = 2;
	Randomize();
}
Beispiel #16
0
size_t DSSMReader<ElemType>::RecordsToRead(size_t mbStartSample, bool tail)
{
    assert(mbStartSample >= m_epochStartSample);
    // determine how far ahead we need to read
    bool randomize = Randomize();
    // need to read to the end of the next minibatch
    size_t epochSample = mbStartSample;
    epochSample %= m_epochSize;

    // determine number left to read for this epoch
    size_t numberToEpoch = m_epochSize - epochSample;
    // we will take either a minibatch or the number left in the epoch
    size_t numberToRead = min(numberToEpoch, m_mbSize);
    if (numberToRead == 0 && !tail)
        numberToRead = m_mbSize;

    if (randomize)
    {
        size_t randomizeSweep = RandomizeSweep(mbStartSample);
        // if first read or read takes us to another randomization range
        // we need to read at least randomization range records
        if (randomizeSweep != m_randomordering.CurrentSeed()) // the range has changed since last time
        {
            numberToRead = RoundUp(epochSample, m_randomizeRange) - epochSample;
            if (numberToRead == 0 && !tail)
                numberToRead = m_randomizeRange;
        }
    }
    return numberToRead;
}
Beispiel #17
0
void DSSMReader<ElemType>::StartMinibatchLoop(size_t mbSize, size_t epoch, size_t requestedEpochSamples)
{
    size_t mbStartSample = m_epoch * m_epochSize;
    if (m_totalSamples == 0)
    {
        m_totalSamples = dssm_queryInput.numRows;
    }

    size_t fileRecord = m_totalSamples ? mbStartSample % m_totalSamples : 0;
    fprintf(stderr, "starting epoch %lld at record count %lld, and file position %lld\n", m_epoch, mbStartSample, fileRecord);

    // reset the next read sample
    m_readNextSample = 0;
    m_epochStartSample = m_mbStartSample = mbStartSample;
    m_mbSize = mbSize;
    m_epochSize = requestedEpochSamples;
    dssm_queryInput.SetupEpoch(mbSize);
    dssm_docInput.SetupEpoch(mbSize);
    if (m_epochSize > (size_t) dssm_queryInput.numRows)
    {
        m_epochSize = (size_t) dssm_queryInput.numRows;
    }
    if (Randomize())
    {
        random_shuffle(&read_order[0], &read_order[m_epochSize]);
    }
    m_epoch = epoch;
    m_mbStartSample = epoch * m_epochSize;
}
Beispiel #18
0
void SparseBinaryInput<ElemType>::Shuffle()
{
    if (Randomize())
    {
        shuffle(&(m_readOrder[0]), &(m_readOrder[m_readOrderLength - 1]), m_randomEngine);
    }
}
/*
* Main Random Writer function. Asks the user for the input text file and
* Markov order number. Generates a maximum of MAX_CHARS characters.
*/
void RandWriter() {
    Randomize();
    ifstream in;
    while(true) {
        cout << "Please enter filename containing source text: ";
        string fileName = GetLine();
        in.open(fileName.c_str());
        if (!in.fail()) break;
        in.clear();
        cout << "File open error." << endl;
    }
    while(true) {
        cout << "What order of analysis? (a number from 1 to 10): ";
        orderK = GetInteger();
        if (orderK >= 1 && orderK <= 10) break;
        cout << "Invalid number" << endl;
    }
    ParseInputText(in);
    in.close();
    string seed = GetInitialSeed();
    GenerateRandomText(seed);
    // clear containers for reuse
    seedMap.clear();
    seedsWithDupes.clear();
}
Beispiel #20
0
//---------------------------------------------------------------------------
void StartQuiz(int NumberOfQuestions)
{
	Randomize();
	CreateQuiz();
	QuizForm->NewQuiz(NumberOfQuestions);
	QuizForm->Show();
}
Beispiel #21
0
/* Private (static) Functions Section
 *-------------------------------------------------------------------
 */
void testrnd()
{
    puts("Testing Rnd() function");

    puts("\ntesting with negativee number (-10)");
    testrndloop(3, -10);

    Randomize(0x50000L);
    Rnd(1);
    puts("\ntesting with 0 as seed");
    testrndloop(3, 0);

    Randomize(0x50000L);
    puts("\ntesting with positive number (1)");
    testrndloop(8, 1);

}
Beispiel #22
0
void ResetDemo()
{
	Randomize(0);
	pBuffer = KeyLog;
	demo_frames = *pBuffer;
	demo_data = *(pBuffer+1);
	demo_prev_data = 0;
}
int main ()
{
    Randomize();
    RunIntSort();
    RunSetIntSort();
    RunStringSort();
	return 0;
}
Beispiel #24
0
void testrand()
{
    unsigned long uval;
    puts("Testing Randomize() function");
    uval = 0x50000L;
    printf("testing with value of %lu (0x%lX)\n", uval, uval);
    Randomize(uval);
    testrndloop(4, 1);
}
Beispiel #25
0
/*
 * Function: RunPerformanceTrial
 * -----------------------------
 * Runs a time trial using pqueues of specified size.  The first 2 time trials report
 * the amount of time necessary to enqueue/dequeue and use pqueue to sort.
 * The last trial reports on memory usage.
 */
void RunPerformanceTrial(int size)
{
	Randomize();
	PQueue pq;
	cout << endl << "---- Performance for " << size << "-element pqueue (" << pq.implementationName() << ")" << " -----" << endl << endl;
	RunEnqueueDequeueTrial(size);
	RunSortTrial(size);
    RunMemoryTrial(size);
    cout << endl << "------------------- End of trial ---------------------" << endl << endl;
}
int main(int argc, char *argv[])
#endif
{
	Randomize();
	initSDL();
	initGL();
	loop();
	doneSDL();
	return 0;
}
//MOVE BUBBLEAF
void Bubbleaf::ApplyMovement(const int ticks, const std::vector<double>& sine) noexcept
{
    SetXSpeed(GetXSpeed() * 0.98);

    int phase = floor( (1.25*ticks) + Randomize() );
    SetYSpeed( 0.11 * sine[phase%512] );

    SetX( GetX()+GetXSpeed() );
    SetY( GetY()+GetYSpeed() );
}
Beispiel #28
0
void MainScreen::fire_timer() {
    Randomize(1);
    ReplayList replays;
    size_t demo = rand() % (replays.size() + 1);
    if (demo == replays.size()) {
        stack()->push(new ScrollTextScreen(5600, kTitleTextScrollWidth, 15.0));
    } else {
        stack()->push(new ReplayGame(replays.at(demo)));
    }
}
Beispiel #29
0
//---------------------------------------------------------------------------
void __fastcall TfrmMain::FormCreate(TObject *Sender)
{
    /* xp problem, with sizable forms;
      This form is sizable so you can test what happens if you
      size the window and a balloon is showing
    */
    ClientHeight = 505;
    ClientWidth = 665;

    Randomize();
}
Beispiel #30
0
int main(void)
{
   int secret;			/*  Declare variables */ 
   
   Randomize();

   while(1){
     secret = RandomInteger(1,100);
     playHiLo(secret);
   }
   return 0;
}