Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Mathematics knundrum
Message
Information générale
Forum:
Visual FoxPro
Catégorie:
Codage, syntaxe et commandes
Divers
Thread ID:
00780672
Message ID:
00782594
Vues:
19
Hi,

Haven't read the whole of this thread and someone may have suggested this approach but, FWIW, this may help:
** Sample Data**************
PUBLIC ARRAY laA(7)
laA(1) = 616.35
laA(2) = 22.5
laA(3) = 115.34
laA(4) = 756.57
laA(5) = 44.67
laA(6) = 202.3
laA(7) = 100.01
PUBLIC lnNoElems
lnNoElems = ALEN(laA)

LOCAL lnTarget
lnTarget = 1345.36
***************************

LOCAL lcItemSelected,lnTotalTaken

lcItemsSelected = ""

lnTotalTaken = Recurse(lnTarget,1, @lcItemsSelected)

? lnTotalTaken,lcItemsSelected

FUNCTION Recurse(tnAmtRemaining, tnCurrentElement, tcItemsSelected)

LOCAL lni,lnBestAmt
lnBestAmt = 0

LOCAL lnTest
LOCAL lcItemsSelectedThisLevel

FOR lni = tnCurrentElement TO lnNoElems
  IF laA(lni) =< tnAmtRemaining
     lcItemsSelectedThisLevel = ""
     lnTest =  laA(lni) + Recurse(tnAmtRemaining-laA(lni),lni+1, @lcItemsSelectedThisLevel)
     IF lnTest > lnBestAmt
       lnBestAmt = lnTest
       tcItemsSelected = ALLTRIM(STR(lni))+"," +lcItemsSelectedThisLevel
     ENDIF
  ENDIF
ENDFOR
RETURN lnBestAmt
This was cobbled together about a year ago as a test (with my usual extensive use of useful comments) - I think I based it on some C code for the knapsack algorithm. It was only done as a 'proof of concept' thing and returns a comma deliminated string of the selected elements - probably better to stick these into another array instead.

HTH,
Regards,
Viv
Précédent
Répondre
Fil
Voir

Click here to load this message in the networking platform