赤玉5個、黒玉3個、白玉2個を(4個, 3個, 3個)に分ける方法(もらう人を区別しない)」を全て列挙せよ
library(gtools) # permutations を使用
# 各色の玉の個数
balls <- c(赤 = 4, 黒 = 3, 白 = 2, 青 = 1)
# 各箱のサイズ
box_sizes <- c(4, 3, 3)
# 指定したサイズで玉を選ぶ関数
generate_combinations <- function(balls, size) {
colors <- names(balls)
all_combinations <- permutations(n = length(colors), r = size, v = colors, repeats.allowed = TRUE)
# 各組み合わせが元の玉の数を超えないようにフィルタリング
valid_combinations <- all_combinations[apply(all_combinations, 1, function(combo) {
all(table(combo) <= balls[names(table(combo))])
}), ]
return(unique(t(apply(valid_combinations, 1, sort)))) # 各組み合わせをソートして重複を削除
}
# すべての分割を求める
unique_distributions <- list()
first_box_choices <- generate_combinations(balls, box_sizes[1])
for (first_box in 1:nrow(first_box_choices)) {
remaining1 <- balls
first_selection <- first_box_choices[first_box, ]
for (color in first_selection) {
remaining1[color] <- remaining1[color] - 1
}
second_box_choices <- generate_combinations(remaining1, box_sizes[2])
for (second_box in 1:nrow(second_box_choices)) {
remaining2 <- remaining1
second_selection <- second_box_choices[second_box, ]
for (color in second_selection) {
remaining2[color] <- remaining2[color] - 1
}
# 第3箱は残りの玉で確定
third_box <- rep(names(remaining2), times = remaining2)
# 各箱内をソートし、3つの箱の並びも統一
sorted_distribution <- list(sort(first_selection), sort(second_selection), sort(third_box))
sorted_distribution <- sorted_distribution[order(sapply(sorted_distribution, paste, collapse = ""))] # 箱順も統一
# **文字列化してリストを扱いやすくする**
unique_distributions <- append(unique_distributions, list(paste(sapply(sorted_distribution, paste, collapse = ","), collapse = " | ")))
}
}
# 重複を削除
unique_distributions <- unique(unique_distributions)
# 総数を確認(正しく63になるはず)
length(unique_distributions)
# 結果を表示
print(unique_distributions)
高校数学の質問スレ(医者・東大卒専用) Part438
■ このスレッドは過去ログ倉庫に格納されています
756132人目の素数さん
2025/03/24(月) 08:15:20.18ID:Wji9obyD■ このスレッドは過去ログ倉庫に格納されています
ニュース
- 【竹中平蔵】「金銭解雇ルールを作れ」 「全然仕事できないのにクビにできない」正社員に持論 ★2 [煮卵★]
- ソースネクスト、顧客のパスワードは暗号化して保存していたが、暗号化解除プログラムもサイバー攻撃される 顧客情報2252万件流出 [お断り★]
- イーロン・マスク氏、テスラの新型「ロードスター」、空中旋回を披露 動画あり [お断り★]
- 【野球】ドジャースまさかの4連敗で終戦…大谷翔平8月以来の1発も空砲 ブルワーズにナ・リーグ優勝決定Sで屈する ★3 [阿末�ュノヶ峰★]
- 【野球】バット直撃で頭部負傷から半年 川上拓斗審判員の意識回復 「球場に戻って審判がしたい」と懸命にリハビリ中… [数の子★]
- 中国大使、フィリピンと戦えば「楽勝」だが武力は選ばず 「中国のような隣国を持てて幸運に思うべき」 [お断り★]
- 🇯🇵解体業の20代日本人男2人、神社の屋根の銅板をはぎ取り盗む 逮捕 [377482965]
- おい❗華金だから、飲みいくのらよ❗(・o・🍬)🏰
- 【悲報】池袋駅の『生徒会にも穴はある』の広告、「気持ち悪い」と炎上wwwwwwwwwwwwwwwwwww [839150984]
- 高市さん、外食支援のために商品券の配布を検討へ [709039863]
- かーちゃんが食堂でパート初めてから夜ご飯美味しくなった
- 高市早苗「サナはリフレ派ではありません。これだけははっきりと真実を伝えたかった」 [731544683]