I think the following should be good as well. Since we know that X
must contain 10 smaller elements compared to those in Y
there doesn't seem to be the need to reject.
a <- 15
b <- 10
set.seed(42)
tmp1 <- runif(b, min=0, max=20)
tmp2 <- runif(b, min=0, max=20)
if (sum(tmp1) > sum(tmp2)) {
Y <- tmp1
X <- tmp2
} else {
Y <- tmp2
X <- tmp1
}
X <- c(X, runif(a - b, min=0, max=20))
if (sum(X) >= sum(Y)) {
yind <- sample.int(b, 1)
Y[yind] <- sum(X) - sum(Y[-yind])
} else {
xind <- sample.int(a, 1)
X[xind] <- sum(Y) - sum(X[-xind])
}
sum(X) == sum(Y)
# [1] TRUE
Explanation of the algorithm.
- generate two vectors of the smaller length
- Assing the one that has the larger sum to
Y
since it is shorter.
- Generate the remainder of
X
- If
sum(X) > sum(Y)
, select an element of Y
randomly and make sum(X) = sum(Y)
, if not pick an element of X
for this.