如何解决创建一个基本的 R 骰子滚动函数来求和骰子值
我正在尝试编写一个函数,根据骰子上显示的数字,将最多 4 个(公平的 6 面)骰子卷组合起来,以尽可能多地创建特定值(名为“target.mountain”)。
然后返回这些值以及未在所述组合中使用的任何值。如果未用于形成“target.mountain”的其他数字的总和可以在范围 (5-10) 内,则执行此操作。
举个例子,我投了 4、3、2、5,我的 target.mountain 值为 9
我愿意
4 + 5 -> 9 和 2 + 3 = 5 我的函数将返回 9,5
另一个例子可能是
滚动 = (2,3,6,4) --> (6 + 3),(4 + 2) --> 9,6
一旦找到这些值,就列出来,看起来像
[1] 9,5(示例 1)
[1] 9,6(例 2)
我该怎么做?
如果您曾经玩过棋盘游戏“Mountain Goats”,那么这可能会说明我需要骰子如何工作,因为我无法弄清楚!
解决方法
让我们把问题变得更难一些,比如 5 个骰子。
library(tidyverse)
rolls <- sample(1:6,replace = TRUE,size = 5)
target.mountain <- 7
#Make all possible combinations of the dice:
map_dfr(seq_along(rolls),~ combn(seq_along(rolls),.x,simplify = FALSE) %>%
map(~tibble(dice = list(.),sum = sum(rolls[.]),rolls = list(rolls[.]),length = length(.)))) %>%
#filter to only those combinations which equal the target
filter(sum == target.mountain) %>%
#Now make all possible combinations of the sets that equal the target
{map2(.x = list(.),.y = nrow(.) %>% map(.x = seq(.),.f = combn,x=.,simplify = FALSE) %>% unlist(recursive = FALSE),~.x[unlist(.y),])} %>%
#Subset to non-overlapping sets
subset(map_lgl(.,~length(reduce(.x$dice,union))==length(unlist(.x$dice)))) -> part1
map(part1,as.data.frame)
#[[1]]
# dice sum rolls length
#1 1,3 7 3,4 2
#
#[[2]]
# dice sum rolls length
#1 4,5 7 6,1 2
#
#[[3]]
# dice sum rolls length
#1 2,3,5 7 2,4,1 3
#
#[[4]]
# dice sum rolls length
#1 1,4 2
#2 4,1 2
从这里你可以应用任何你想要的规则:
part1 %>%
#subset to the largest number of sets
subset(map_dbl(.,nrow) == max(map_dbl(.,nrow))) %>%
#subset to the fewest number of total dice
subset(map_dbl(.,~sum(.x$length)) == min(map_dbl(.,~sum(.x$length)))) %>%
#if there are still ties,pick the first
`[[`(1) -> part2
as.data.frame(part2)
# dice sum rolls length
#1 1,1 2
,
问题的可能解决方案
target.mountain = 9
dice <- c(4,2,5)
library(tidyverse)
fn <- function(target.mountain,dice){
fltr <- map(seq_along(dice),~combn(dice,sum) == target.mountain)
out <- map(seq_along(dice),.x))
sum_target <- map2(out,fltr,~.x[,.y]) %>%
purrr::discard(.x = .,function(x) length(x) == 0) %>%
keep(.x = .,.p = function(x) length(x) == min(lengths(.))) %>%
flatten_dbl()
no_sum_target <- dice[!(dice %in% sum_target)]
result <- toString(c(sum(sum_target),no_sum_target))
return(result)
}
fn(target.mountain = target.mountain,dice = dice)
#> [1] "9,2"
由 reprex package (v1.0.0) 于 2021 年 3 月 29 日创建
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。