Created
January 22, 2016 14:57
-
-
Save DexGroves/be930e95fbe4ed8a8b16 to your computer and use it in GitHub Desktop.
Stop ruining my Fridays fivethirtyeight.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library("igraph") | |
library("stringi") | |
library("magrittr") | |
generate_bridge_df <- function(nrow, ncol) { | |
this_layer <- generate_layer(ncol) | |
first_connections <- data.frame(from = "Northside", | |
to = get_layer_vertices(this_layer)) | |
all_bridges <- rbind(first_connections, this_layer) | |
for (row in seq(nrow - 1)) { | |
current_vertices <- get_layer_vertices(this_layer) | |
this_layer <- generate_layer(ncol) | |
these_connections <- data.frame(from = current_vertices, | |
to = get_layer_vertices(this_layer)) | |
all_bridges <- rbind(all_bridges, these_connections, this_layer) | |
} | |
last_connections <- data.frame(from = get_layer_vertices(this_layer), | |
to = "Southside") | |
graph.data.frame(rbind(all_bridges, last_connections), directed = FALSE) | |
} | |
generate_layer <- function(ncol) { | |
island_names <- stri_rand_strings(ncol, 10) | |
data.frame(from = island_names[1:(ncol - 1)], | |
to = island_names[2:ncol], | |
stringsAsFactors = FALSE) | |
} | |
get_layer_vertices <- function(layer) { | |
unique(c(layer$to, layer$from)) | |
} | |
random_storm <- function(island_graph) { | |
bridges <- E(island_graph) | |
destroyed_bridges <- bridges[runif(length(bridges)) > 0.5] | |
delete_edges(island_graph, destroyed_bridges) | |
} | |
can_get_south <- function(island_graph) { | |
vertex.connectivity(island_graph, "Northside", "Southside") > 0 | |
} | |
unharmed_bridges <- generate_bridge_df(2, 3) | |
plot(unharmed_bridges) | |
unharmed_bridges %>% random_storm %>% plot | |
unharmed_bridges %>% random_storm %>% can_get_south |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment