-1

我正在尝试编写一个函数,该函数结合最多 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”棋盘游戏,那么这可能会对我需要骰子如何工作有所了解,因为我无法弄清楚!

4

2 回答 2

1

让我们把问题变得更难一些,比如 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, 3   7  3, 4      2
#2 4, 5   7  6, 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, 3   7  3, 4      2
#2 4, 5   7  6, 1      2
于 2021-03-29T17:19:55.920 回答
0

问题的可能解决方案

target.mountain = 9
dice <- c(4,3,2,5)

library(tidyverse)

fn <- function(target.mountain, dice){
  fltr <- map(seq_along(dice), ~combn(dice, .x, sum) == target.mountain)
  out <- map(seq_along(dice), ~combn(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, 3, 2"

reprex 包于 2021-03-29 创建(v1.0.0)

于 2021-03-29T17:08:59.557 回答