본문 바로가기
C++/예제

난수와 std::map을 사용한 랜덤 이벤트 시간 생성 예제

by 계양구놈팽이 2023. 7. 17.

아래 코드는 std::map<int64_t, std::string>을 사용하여 200개의 랜덤한 시간 간격을 가지는 "dummy" 문자열을 저장 합니다.

#include <iostream>
#include <map>
#include <random>
#include <chrono>
#include <iomanip>

typedef int64_t Time;
typedef std::map<Time, std::string> TimeMap;
const int num_entries = 200;

Time random_time(Time start, Time end) {
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<Time> dist(start, end / num_entries); // 2
    return dist(gen);
}

void populate_map(Time start, Time end, TimeMap& time_map) {

    Time current_time = start;
    for(int i = 0; i < num_entries; ++i) {
        Time interval = random_time(1, end - start); // 랜덤한 간격 생성
        current_time += interval; //시간 키의 중복을 방지하기 위해 이전 시간 값에 랜덤 시간을 더해 사용
        time_map[current_time] = "dummy";
    }
}

int main() {
    Time start = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
    Time end = start + 1000 * 60 * 60 * 24; // 1일
    TimeMap time_map;
    populate_map(start, end, time_map);
    for(const auto& pair : time_map) {
        // Convert milliseconds
        std::time_t time_t_timestamp = pair.first / 1000;

        std::tm *tm_timestamp = std::gmtime(&time_t_timestamp);

        std::cout << std::put_time(tm_timestamp, "%Y-%m-%d %H:%M:%S") << ": " << pair.second << std::endl;
    }
    return 0;
}