Last active
January 2, 2018 22:52
-
-
Save ibartomeus/928e095499c34c7629ad4d60fcab8e21 to your computer and use it in GitHub Desktop.
Calculate how many possible sets there are in a set game
This file contains hidden or 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
#Calculate how many sets there are in a set game. | |
#each card has 4 characteristics with 3 factors each | |
color <- c("red", "green", "purple") | |
shape <- c("round", "diamond", "curly") | |
texture <- c("fill", "empty", "striped") | |
number <- c("one", "two", "three") | |
create_board <- function(n = 12){ | |
data.frame(color = sample(color, n, TRUE), | |
shape = sample(shape, n, TRUE), | |
texture = sample(texture, n, TRUE), | |
number = sample(number, n, TRUE)) | |
} | |
set <- function(a = c(1,2,3), d){ #a = position in the board; d = board | |
ifelse(all((d[a,1] == d[a[1],1]) | all(c(d[a[2:3],1] != d[a[1],1], d[a[2],1] != d[a[3],1]))) & | |
(all(d[a,2] == d[a[1],2]) | all(c(d[a[2:3],2] != d[a[1],2], d[a[2],2] != d[a[3],2]))) & | |
(all(d[a,3] == d[a[1],3]) | all(c(d[a[2:3],3] != d[a[1],3], d[a[2],3] != d[a[3],3]))) & | |
(all(d[a,4] == d[a[1],4]) | all(c(d[a[2:3],4] != d[a[1],4], d[a[2],4] != d[a[3],4]))), | |
TRUE, FALSE) | |
} | |
any_set <- function(d, n = 12){ #n can be derived from d, and simplify one param. | |
x <- c() | |
cb <- combn(x = n, m = 3, simplify = TRUE) #220 combinations for n = 12 | |
for(i in 1:ncol(cb)){ | |
x[i] <- set(cb[,i], d) | |
} | |
cb[,which(x)] | |
} | |
#example with a random game | |
d <- create_board() | |
any_set(d) | |
#one practical example | |
d <- data.frame(color = c("v", "m", "r", "v", "v", "m", "r", "m", "m", "m", "m", "v"), | |
shape = c("c", "r", "c", "r", "r", "r", "o", "o", "c", "r", "r", "r"), | |
texture = c("h", "h", "h", "s", "r", "h", "h", "r", "r", "s", "r", "r"), | |
number = c("1", "3", "2", "1", "3", "2", "2", "1", "1", "2", "3", "1")) | |
any_set(d) | |
#how many non-sets are in 100 games? | |
x <- c() | |
for(i in 1:100){ | |
x[i] <- ifelse(sum(any_set(create_board())) > 0, 0, 1) | |
} #slow, which means code can be optimized. | |
sum(x) #5 to 9 games with no sets on average. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment