Last active
February 8, 2022 22:05
-
-
Save jmbarbone/a5ef07bda7cdce82e9a391dc05719251 to your computer and use it in GitHub Desktop.
4/5 felines
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
numbers <- function(big = 2L, small = 6L - big) { | |
stopifnot(big + small == 6L) | |
c(sample(50:100, big), sample(0:49, small)) | |
} | |
problem <- function(x = numbers(), parenthesis = TRUE, ns = length(x)) { | |
stopifnot(all(ns > 1), all(ns <= length(x))) | |
x <- as.integer(x) | |
n <- if (length(ns) == 1) ns else sample(ns, 1) | |
ops <- sample(c("+", "-", "/", "*"), n - 1L, TRUE) | |
numbers <- sample(x, n) | |
numbers <- format(numbers) | |
if (parenthesis) { | |
pinds <- sort(sample(seq_len(n), n, TRUE)) | |
odds <- seq.int(1L, n, 2L) | |
evens <- seq.int(2L, n, 2L) | |
for (i in pinds[odds]) { | |
numbers[i] <- paste0("(", numbers[i]) | |
} | |
for (i in pinds[evens]) { | |
numbers[i] <- paste0(numbers[i], ")") | |
} | |
if (length(evens) != length(odds)) { | |
numbers[n] <- paste0(numbers[n], ")") | |
} | |
} | |
form <- paste(numbers, c(ops, ""), collapse = " ") | |
res <- eval(parse(text = form)) | |
attr(res, "answer") <- form | |
attr(res, "vals") <- x | |
if (!valid_solution(res)) { | |
res <- problem(x, parenthesis = parenthesis, ns = ns) | |
} | |
class(res) <- "problem" | |
res | |
} | |
solution <- function(x = numbers(), answer, ns = length(x)) { | |
stopifnot(valid_solution(answer)) | |
answer <- as.integer(answer) | |
repeat { | |
res <- problem(x, ns = ns) | |
if (res == answer) break | |
form <- paste(attr(res, "answer")) | |
form <- format(form, width = 35) | |
ans <- format(as.integer(res), width = 3) | |
cat(form, " = ", ans, "\n", sep = "") | |
Sys.sleep(.25) | |
} | |
attr(res, "answer") | |
} | |
valid_solution <- function(x) { | |
isTRUE(x %% 1 == 0 & x >= 0 & x <= 999) | |
} | |
print.problem <- function(x, ...) { | |
print(as.integer(x)) | |
invisible(x) | |
} | |
x <- c(25, 50, 3, 10, 2, 1) | |
x <- c(25, 50, 3, 2, 1) | |
system.time(message(solution(x, 834, ns = 5), " = 834")) | |
x <- c(100, 25, 75, 50, 4, 3) | |
system.time(message(solution(x, 797), " = 797")) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment