You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何生成数值向量中2、3、4个元素组合的所有求和结果列表(R语言骰子向量示例)

Solution for Generating All Combination Sums from Dice Roll Vector

Hey there! Let's walk through how to generate the list you need—including every element from your dice vector plus all possible sums of 2, 3, or 4 elements combined.

First, let's recap your setup: you've got a target value target.mountain <- 10 and generate your dice vector with Roll_dice <- sample(1:6, 4, replace=TRUE). For example, let's use your sample vector c(6,5,3,2) to demonstrate.

Step-by-Step Code

Here's a clean, straightforward way to get all the required sums in R:

# Your existing setup
target.mountain <- 10
Roll_dice <- sample(1:6, 4, replace = TRUE)
# Example vector (uncomment to test with your sample)
# Roll_dice <- c(6,5,3,2)

# Initialize a list to store sums for each combination size
all_combo_sums <- list()

# Loop through combination sizes 1 to 4
for (k in 1:4) {
  # Generate all unique combinations of k elements from Roll_dice
  combinations <- combn(Roll_dice, k)
  # Calculate the sum for each combination
  sum_per_combo <- colSums(combinations)
  # Add these sums to our list
  all_combo_sums[[k]] <- sum_per_combo
}

# Convert the list to a single vector (unsorted)
unsorted_result <- unlist(all_combo_sums)

# Optional: Sort the result to match your example's structure
sorted_result <- sort(unsorted_result)

# Print the sorted result
print(sorted_result)

Example Output

Using your sample Roll_dice <- c(6,5,3,2), the sorted_result will look like this:

[1]  2  3  5  5  6  7  8  8  9 10 11 11 13 14 16

How It Works

  • combn(Roll_dice, k) generates every possible subset of k elements from your dice vector. For k=1, this is just each individual element.
  • colSums(combinations) calculates the sum for each subset (since combn returns subsets as columns).
  • We collect all these sums in a list, then unlist to get a flat vector. Sorting it gives the organized output you showed in your example.

If you don't need the sorted version, just use unsorted_result instead—it will include all values in the order of combination sizes (individual elements first, then 2-element sums, etc.).

内容的提问来源于stack exchange,提问作者KnowsNothingAboutCode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 12:29:06