krizzo
krizzo

Reputation: 1883

Progressively slow down loop?

I've been trying to figure out a way that I can cpp progressively slow down loop for a dice program I want to write. Getting a random number and displaying/comparing it is not difficult. My issue is trying to figure out how I could display random numbers as if the dice was rolling where it progressively gets slower and slower until I want to display the rand number that was generated.

I've thought about doing a for-loop inside another for-loop and using the first loops number to subtract from the second. I don't know if there is a better way or not. All seraching comes up with seraches on how a program is going slower because they weren't allocating memory.

for (int i = 5; i > 0; i--)
{
    for (int j = 1000; j > 0; j -= i)
    {
        cout << randNumGen();
    }
}

Upvotes: 1

Views: 3342

Answers (1)

111111
111111

Reputation: 16148

#include <thread>
#include <chrono>

:::
for (int i = 5; i > 0; i--)
{
    for (int j = 1000; j > 0; j -= i)
    {
        cout << randNumGen();
        std::this_thread::sleep_for(
             std::chrono::milliseconds(j));

    }
}

http://en.cppreference.com/w/cpp/thread/sleep_for

http://en.cppreference.com/w/cpp/chrono

it is probably also worth your while look at C++11 random it is more C++ way of generating random number in a cross platform way.

std::uniform_int_distribution<int> distribution(1, 6); //dice values
std::mt19937 engine; // Mersenne twister MT19937
int random = distribution(engine);

http://en.cppreference.com/w/cpp/numeric/random

#include <thread>
#include <chrono>
#include <random>
#include <iostream>

:::

std::random_device rd;
std::uniform_int_distribution<int> dist(1, 6); //dice values
std::mt19937 mt(rd()); // Mersenne twister MT19937

for (int i = 5; i > 0; i--) //i don't really get what your loops mean
{
    for (int j = 1000; j > 0; j -= i)
    {
        cout << dist(mt);
        std::this_thread::sleep_for(
             std::chrono::milliseconds(j));

    }
}

You will need to compile with c++11 support for gcc and clang this is -std=c++0x

Upvotes: 3

Related Questions