Skip to content

Instantly share code, notes, and snippets.

@dereckmezquita
Created November 6, 2021 21:49
Show Gist options
  • Save dereckmezquita/a5b94f6cd7c10a9c7ba314b5a074af48 to your computer and use it in GitHub Desktop.
Save dereckmezquita/a5b94f6cd7c10a9c7ba314b5a074af48 to your computer and use it in GitHub Desktop.
Code for randomly selecting random numbers between an integer and tallying up results. Reference for generating random numbers. R used for visualisation.
#include <Rcpp.h>
#include <iostream>
#include <random>
#include <chrono>
using namespace Rcpp;
std::mt19937 rng(std::chrono::steady_clock::now().time_since_epoch().count());
// [[Rcpp::export]]
NumericVector randomChoose(int iter, int sample) {
NumericVector collected(sample, 0.0);
for(int i = 1; i <= iter; i++) {
collected[std::uniform_int_distribution<int>(0, sample)(rng)]++;
}
return collected;
}
// [[Rcpp::export]]
List iterRandomChoose(int runs, int by) {
List results(runs / by);
for(int i = 0; i < runs; i += by) {
std::cout << i << std::endl;
// std::cout << i / by << std::endl;
results[i / by] = randomChoose(i, 10);
}
return results;
}
@dereckmezquita
Copy link
Author

dereckmezquita commented Nov 6, 2021

Code used for visualisation:

library("ggplot2")
# https://youtu.be/zs7CvPP7OVM

Rcpp::sourceCpp("./randomChoose.cpp")

runs <- 250000L

messageParallel <- function(...) {
	system(sprintf('echo "%s"', paste0(..., collapse = "")))
}

res <- iterRandomChoose(runs, 1000)

future::plan(strategy = "multisession", workers = future::availableCores() - 1)

invisible(future.apply::future_mapply(function(df, i) {
	df <- data.frame(
		index = as.character(1:length(df)),
		total = df
	)
	df$index <- factor(df$index, levels = df$index)
	
	p <- ggplot2::ggplot(df, ggplot2::aes(x = index, y = total)) +
		ggplot2::geom_bar(stat = "identity") +
		ggplot2::scale_y_continuous(n.breaks = 30, limits = c(0, 25000)) +
		ggplot2::labs(title = "Frequency of integer based on random sampling", subtitle = "C++ 11: mt19937 rng used from <random>", caption = stringr::str_interp('Iterations: ${i}'))
	
	png(stringr::str_interp('./plots/${i}.png'))
	print(p)
	dev.off()
	
}, res, seq_along(res), SIMPLIFY = FALSE))

Brew install imagemagik:

convert -delay 20 -loop 0 `ls | sort -n` random-number-selection.gif

random-number-selection

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment