library(RcppAlgos)

persons <- c("A","B","C","D")
vegs <- c("ナス","ピーマン","キュウリ","タマネギ")

all_bits <- permuteGeneral(v = c(0L, 1L), m = 16, repetition = TRUE)

is_valid <- function(bits16) {
M <- matrix(bits16, nrow = 4, ncol = 4, byrow = TRUE,
dimnames = list(persons, vegs))

c1 <- (sum(M[, "タマネギ"] == 1L) == 3L) && (M["A", "タマネギ"] == 1L)

both0 <- (M["A", ] == 0L) & (M["B", ] == 0L)
c2 <- (sum(both0) == 1L) && (both0["ピーマン"] == FALSE)

c3 <- (sum(M["C", ] == 1L) == 2L) && (M["C", "キュウリ"] == 1L)

not_egg <- which(M[, "ナス"] == 0L)
c4 <- (length(not_egg) == 2L) && all(M[not_egg, "キュウリ"] == 0L)

c5 <- (sum(M["D", ] == 1L) > sum(M["B", ] == 1L))

isTRUE(c1 && c2 && c3 && c4 && c5)
}

ok_idx <- which(apply(all_bits, 1, is_valid))
cat("解の個数:", length(ok_idx), "\n")

solutions <- all_bits[ok_idx, , drop = FALSE]

for (i in seq_len(nrow(solutions))) {
cat("\n--- 解", i, "---\n")
M <- matrix(solutions[i, ], nrow = 4, ncol = 4, byrow = TRUE,
dimnames = list(persons, vegs))
print(M)

bought_list <- lapply(persons, function(p) vegs[which(M[p, ] == 1L)])
names(bought_list) <- persons
print(bought_list)
}