t <- 5842
S <- c(267, 493, 869, 961, 1000, 1153, 1246, 1598, 1766, 1922)
# S is not decreasingly sorted, so ...
o <- order(S, decreasing = TRUE)
So <- S[o] # So is decreasingly sorted
sol <- subsetsum(So, t) # $inds: 2 4 6 7 8 w.r.t. So
is <- o[sol$inds] # is: 9 7 5 4 3 w.r.t. S
sum(S[is]) # 5842
if (FALSE) {
amount <- 4748652
products <-
c(30500,30500,30500,30500,42000,42000,42000,42000,
42000,42000,42000,42000,42000,42000,71040,90900,
76950,35100,71190,53730,456000,70740,70740,533600,
83800,59500,27465,28000,28000,28000,28000,28000,
26140,49600,77000,123289,27000,27000,27000,27000,
27000,27000,80000,33000,33000,55000,77382,48048,
51186,40000,35000,21716,63051,15025,15025,15025,
15025,800000,1110000,59700,25908,829350,1198000,1031655)
# prepare set
prods <- products[products <= amount] # no elements > amount
prods <- sort(prods, decreasing=TRUE) # decreasing order
# now find one solution
system.time(is <- subsetsum(prods, amount))
# user system elapsed
# 0.030 0.000 0.029
prods[is]
# [1] 70740 70740 71190 76950 77382 80000 83800
# [8] 90900 456000 533600 829350 1110000 1198000
sum(prods[is]) == amount
# [1] TRUE
# Timings:
# unsorted decr.sorted
# "greedy" 22.930 0.030 (therefore the default settings)
# "dynamic" 2.515 0.860 (overhead for smaller sets)
# sss_test 8.450 0.040 (no indices returned)
}
Run the code above in your browser using DataLab