c - 0-1 knapsack brute force -


I can not seem to find the problem with the following code written with a pseudo-code: p [] with the advantages, array w [] weight, weight - maximum weight , number (number of items) receives and wal (coming back) . Please help! Thank you. I think this issue can be with dynamic array or loop

 
> int bruteforce (int p [], int w [], int size, int weight, int val {int k , I, j, tempWyight, tempValue; Int * A = (int *) coloc (size, size); (I = 0; i & lt; pow (2, size); i ++) j = size for; TempWight = 0; TempValue = 0; While (A [J]! = 0 & J & gt; 0) {A [J] = 0; J = j - 1; } A [J] = 1; For (k = 0; k & lt; size; k ++) if (a [k] = 1) tempWeight = tempWight + w [k]; TempValue = tempValue + p [k]; If ((tempValue & gt; Wall) & amp; (tempWeight & lt; = weight)) val = tempValue; Return valve; }

Uh! There are several things going on here:

  • Please indent your code properly. Then you will see that you are losing crisp braces in two places: for block only extends until return val . If is related to the statement, there may be two functions of tempWight and tempValue inside a block.

  • condition a [k] = 1 is not what you want. This is an assignment (unfortunately) also acts as a condition that is always right. Change it to (a [k] == 1) . Some people habit of keeping the first constant in this way: If (1 == A [k]) which will give a compiler error, if you have = for > == .

  • If you allocate memory for A , you should also open before returning from the function.

  • Your calculation a [i] is wrong here You have braces, which means that j only if A [J] if not zero then it will be updated. You should apply a binary extra with the move here.

  • The pow function is useful for floating-point numbers. Here, you are working with integer 1 < & Lt; It may be better to use the pow (2, i) instead of . You can also use a [i] to take the final digit in the form of termination criteria; see below.

  • This is a slight stylistic point, but when you have braces around the main loop, you will see that most of your local variables are needed only inside the loop. You should tighten your scope by declaring these variables inside the code block. (This is not important here, but can be added to readability in larger programs.)

So, puts it all in your code:

  int brute force (int p [], int w [], int size, int weight, int val) {int * a = (int *) coloc (size, size); Int i; For (i = 0 ;; i ++) {int j = size; Int tempWight = 0; Int tempValue = 0; Int k; K = 1; (J = 0; J & lt; size; j ++) for {a [j] + = k; K = A [J] / 2; A [J] = A [J]% 2; } If (k) breaks; For (k = 0; k & lt; size; k ++) {if (a [k] == 1) {tempWeight = tempWight + w [k]; TempValue = tempValue + p [k]; }} If (tempValue & gt; val & amp; tempWeight & lt; = weight) {val = tempValue; }} Free (A); Return valve; }  

Comments

Popular posts from this blog

import - Python ImportError: No module named wmi -

Editing Python Class in Shell and SQLAlchemy -

lua - HowTo create a fuel bar -