Knapsack code - not working for some cases - c

My code is as the following:
#include<stdio.h>
int max(int a,int b)
{
return a>b?a:b;
}
int Knapsack(int items,int weight[],int value[],int maxWeight)
{
int dp[items+1][maxWeight+1];
/* dp[i][w] represents maximum value that can be attained if the maximum weight is w and
items are chosen from 1...i */
/* dp[0][w] = 0 for all w because we have chosen 0 items */
int iter,w;
for(iter=0;iter<=maxWeight;iter++)
{
dp[0][iter]=0;
}
/* dp[i][0] = 0 for all w because maximum weight we can take is 0 */
for(iter=0;iter<=items;iter++)
{
dp[iter][0]=0;
}
for(iter=1;iter<=items;iter++)
{
for(w=0;w<=maxWeight;w=w+1)
{
dp[iter][w] = dp[iter-1][w]; /* If I do not take this item */
if(w-weight[iter] >=0)
{
/* suppose if I take this item */
dp[iter][w] = max( (dp[iter][w]) , (dp[iter-1][w-weight[iter]])+value[iter]);
}
}
}
return dp[items][maxWeight];
}
int main()
{
int items=9;
int weight[/*items+1*/10]={60, 10, 20, 20, 20, 20, 10, 10, 10};
int value[/*items+1*/10]={73, 81, 86, 72, 90, 77, 85, 70, 87};
int iter;
int i;
int maxWeight=180;
for (i=0;i<10;i++){
value[i] = value[i]*weight[i];
}
printf("Max value attained can be %d\n",Knapsack(items,weight,value,maxWeight));
}
My knapsack code is working when
items=12;
int weight[/*items+1*/13]={60, 20, 20, 20, 10, 20, 10, 10, 10, 20, 20, 10};
int value[/*items+1*/13]={48, 77, 46, 82, 85, 43, 49, 73, 65, 48, 47, 51};
where it returned the correct output 7820.
But it doesn't returned the correct output when
items=9;
int weight[/*items+1*/10]={60, 10, 20, 20, 20, 20, 10, 10, 10};
int value[/*items+1*/10]={73, 81, 86, 72, 90, 77, 85, 70, 87};
where it returned the output 9730, the correct output should be 14110.
From observation, the program somehow skipped the 1st value (weight=60, value =73).
I have checked the code several times, but I just cant find what's wrong.
Can someone explain to me why? Thank you!

In your code, you are trying to access out of bounds index for weight and value array. When iter reaches value 9, weight[iter] and value[iter] becomes out of bounds index. I guess, in C you simply get some garbage value for out of index access, but in Java, that will throw an exception. Change the code in your inner for loop to:
dp[iter][w] = dp[iter-1][w]; /* If I do not take this item */
if(w-weight[iter - 1] >=0)
{
/* suppose if I take this item */
dp[iter][w] = maximum( (dp[iter][w]) , (dp[iter-1][w-weight[iter - 1]])+value[iter - 1]);
}
and it will work fine.

int weight[/*items+1*/10]={60, 10, 20, 20, 20, 20, 10, 10, 10};
int value[/*items+1*/10]={73, 81, 86, 72, 90, 77, 85, 70, 87};
Your arrays are of length 10, but you are filling only 9 entries. Hence the last entry gets filled to 0. How to initialize all members of an array to the same value?
int weight[/*items+1*/10]={60, 10, 20, 20, 20, 20, 10, 10, 10, 0};
int value[/*items+1*/10]={73, 81, 86, 72, 90, 77, 85, 70, 87, 0};
But you are trying to access the indices (1 to 9) in your algorithm.
Instead try filling all entries:
int weight[/*items+1*/10]={0, 60, 10, 20, 20, 20, 20, 10, 10, 10};
int value[/*items+1*/10]={0, 73, 81, 86, 72, 90, 77, 85, 70, 87};
EDIT:
The first case gives correct output since in that case the first entry is not included in the optimal solution.

Related

My C function to reverse an array fills the first and last index with random numbers after consecutive runs. Why is this?

I've created a function to reverse an array in C. The first run of the function will reverse the array perfectly. Runs following that will fill the first and/or last index of the array with seemingly random info. I'm assuming this may have to do with the array accidentally receiving information from surrounding memory addresses after several runs.
My function is written as follows:
void reverse_array(int array[], int* result, int size) {
int index = 0;
int reverse_index;
for (reverse_index = size - 1; reverse_index > 0; reverse_index--) {
result[index] = array[reverse_index];
index++;
}
}
Running the following code with "nums" being an array filled with integers 0 to 99, the expected output is returned:
int main(void) {
int size = 100;
int nums[size];
int i;
for (i = 0; i < size; i++) {
nums[i] = i;
}
int reversed[size];
reverse_array(nums, reversed, size);
print_array(reversed);
return 0;
}
The problem arises when I try and run the function several times consecutively. In the following code, I attempt to flip an array several times:
int main(void) {
int size = 100;
int nums[size];
int i;
for (i = 0; i < size; i++) {
nums[i] = i;
}
int reversed[size];
reverse_array(nums, reversed, size);
int reversed2[size];
reverse_array(reversed, reversed2, size);
int reversed3[size];
reverse_array(reversed2, reversed3, size);
int reversed4[size];
reverse_array(reversed3, reversed4, size);
int reversed5[size];
reverse_array(reversed4, reversed5, size);
print_array(reversed5, size);
return 0;
}
Printing out the second flip, or "reversed2," returns the following:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 32760,
The output is almost exactly as to be expected, except for the final index. This happens with all following flips, though with different values. Printing the 5th flip, or "reversed5," yields the following:
0, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80,
79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60,
59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40,
39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20,
19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 32760,
I'm very new to C, and can only guess what is causing this. As stated above, I think it may have to do with the array accidentally picking up information from surrounding memory addresses, but that's only a guess. Thanks for reading, any help is greatly appreciated.
Edit: Thank you all very much. I could not ask for more straight forward and helpful responses. I feel kind of dumb now, but that's part of the learning process.
for (reverse_index = size - 1; reverse_index > 0; reverse_index--)
Your problem is with this line of code,this > should be changed to >=.

How does the addbit bit manipulation function work in this permutation code sample

I have code to perform a permutation on a block of data (64 bit) and the code works but I don't understand how the addbit function works. This is the function that performs the permutation on a to and from bit position.
I understand that because if a bit gets over-written in the destination data block then if that previous bit needs to be permuted then it will be lost and that is why there is a source and destination data block.
But I dont understand the logic in addbit.
Why is FIRSTBIT used?
The code works, but I would like to understand why.
#include <stdint.h>
#include <stdio.h>
// FIRSTBIT is first bit in 64 bit data?
#define FIRSTBIT 0x8000000000000000 // 1000000000...
// eg move bit 64 in input data to bit position 1
// then move bit 63 in input data to bit position 2 etc
const int TestPermutation[64] = {
64, 63, 62, 61, 60, 59, 58, 57,
56, 55, 54, 53, 52, 51, 50, 49,
48, 47, 46, 45, 44, 43, 42, 41,
40, 39, 38, 37, 36, 35, 34, 33,
32, 31, 30, 29, 28, 27, 26, 25,
24, 23, 22, 21, 20, 19, 18, 17,
16, 15, 14, 13, 12, 11, 10, 9,
8, 7, 6, 5, 4, 3, 2, 1
};
// move data bit from 'from' at position_from to position_to in block
// How does this work?
void addbit(uint64_t *block, uint64_t from, int position_from, int position_to)
{
if (((from << (position_from)) & FIRSTBIT) != 0)
*block += (FIRSTBIT >> position_to);
}
// perform permutation based on TestPermutation array
void permute(uint64_t* data) {
uint64_t data_temp = 0;
for (int ii = 0; ii < 64; ii++)
{
addbit(&data_temp, *data, TestPermutation[ii] - 1, ii);
}
*data = data_temp;
}
void print_binary(uint64_t number) {
for (int i = sizeof(uint64_t) * 8 - 1; i >= 0; --i) {
printf("%c", ((number >> i) & 1) ? '1' : '0');
}
printf("\n");
}
int main() {
uint64_t data = 0xF0F0F0F0F0F0F0F0; // test block
print_binary(data); // 1111000011110000111100001111000011110000111100001111000011110000
permute(&data);
print_binary(data); // 0000111100001111000011110000111100001111000011110000111100001111
}

I did not understand what is happening with int array in my code

#include <stdio.h>
int main()
{
int marks[40] = {83, 86, 97, 83, 93, 83, 86, 52, 49, 41, 42, 47, 90, 59, 63, 86, 40, 46, 92, 56, 51, 48, 67, 49, 42, 90, 42, 83, 47, 95, 69, 82, 82, 58, 69, 67, 53, 56, 71, 62};
int i,j,count[101],tm;
for(i=0;i<101;i++)
{
count[i]=0;
}
for(i=0;i<40;i++)
{
tm=marks[i];
count[tm]=count[tm]+1;
}
for(i=0;i<=100;i++)
{
if(count[i]!=0)
{
printf("Marks: %d count: %d\n",i,count[i]);
}
}
return 0;
}
This is my code. I did not understand in this here.
first i=0, marks[i], marks[0] means marks[0]=83
so
tm=marks[0]=83
and then
count[tm]=count[tm]+1;
And I did not understand in this line.
I added some comments to your code such that you can easier understand what is happening.
#include <stdio.h>
int main(void) // use void if your function has no parameters
{
int marks[] = {83, 86, 97, 83, 93, 83, 86, 52, 49, 41, 42, 47, 90, 59, 63, 86, 40, 46, 92, 56, 51, 48, 67, 49, 42, 90, 42, 83, 47, 95, 69, 82, 82, 58, 69, 67, 53, 56, 71, 62}; // you can leave out the array size if you instantiate it afterwards
int i, tm; // j is never used, so leave it out
int count[101]; // count[i] tells you in the end how often the mark i occured in the marks array
for(i=0; i < 101; i++) // initialize the count array with zeros
{
count[i]=0;
}
for(i=0;i<40;i++) // loop over the marks array and increment thhe count array at the current mark position by one
{
tm=marks[i];
count[tm]=count[tm]+1; // increment the count of mark i by one
}
// marks[i] tells you how often i appears in the marks array -> marks is a frequency table
for(i=0;i<=100;i++) // print out how often a mark appeared, but only if it appeared at least once
{
if(count[i]!=0)
{
printf("Marks: %d count: %d\n",i,count[i]);
}
}
return (0);
}
Those two lines
tm=marks[i];
count[tm]=count[tm]+1;
do the following:
get the value stored in marks[i]
store the value pulled in 1. into tm
get the value of count[tm]
add 1 to what had been pulled in 3.
store the result of the addition done in 4. into count[tm], overwriting the value that had been pulled in 3..
By adding 1 in step 4, you are counting the number of occurrences of a specific mark.

Split string to 140 char chunks

This is my function:
char** split_string(char* message){
int i = 0;
int j = 0;
int numberOfMsgs = 0;
int charsInLastMsg = (int)(strlen(message)%140);
if((int)strlen(message) > 140*4){
return NULL;
}
if((int)(strlen(message)%140)){
numberOfMsgs = (int)(strlen(message)/140) + 1;
}
else{
numberOfMsgs = (int)(strlen(message)/140);
}
printf("message length = %d, we will have %d messages, and last msg will have %d characters\n", (int)strlen(message), numberOfMsgs, charsInLastMsg);
char **m = malloc(numberOfMsgs * sizeof(char*));
for (j =0 ; j <= numberOfMsgs; j++){
m[j] = malloc(141 * sizeof(char));
}
for(i=0;i<numberOfMsgs;i++){
if(i == numberOfMsgs - 1){
memcpy(m[i], message + (140*i), charsInLastMsg);
m[i][charsInLastMsg] = '\0';
}
else{
memcpy(m[i], message + (140*i), 140);
m[i][140] = '\0';
}
printf("m%d = %s\n", i, m[i]);
}
return m;
}
Which I'm calling like this:
char* message = "1, 2, 3, 4, 5, 6, 7, 8, 9 and 10, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100.";
int i=0;
char** m = split_string(message);
while(*m){
printf("string%d = %s\n", i, m[i]); //Problem at this line.
m++;
}
But, when I run it, I'm getting a segmentation fault at the line indicated above. If I don't print, the program runs fine, so I think the function split_string() is alright.
What am I doing wrong? I'm a newbie, plz help.
/************************************EXPECTED O/P**********************************/
I want the string to be split into 140 char strings as below:
string0 = 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36
string1 = , 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71
string2 = , 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100.
There are several issues in your code. You have already fixed some.
Your client code
while (*m) {
printf("string%d = %s\n", i, *m);
i++;
m++;
}
(where I have taken the liberty to replace m[i] with i always 0 with *m) suggests that the char-pointer array m is NULL-terminated, i.e. that a NULL pointer indicates the end of the string list. (Much like a '\0' character indicates the end of a string.)
But your function split_string doesn't put a NULL pointer at the end: Your client code will read beyond valid memory.
char **m = malloc(numberOfMsgs * sizeof(char*));
Here, you should allocate (numberOfMsgs + 1) strings, one extra for the NULL.
for (j =0 ; j <= numberOfMsgs; j++){
m[j] = malloc(141 * sizeof(char));
}
Here, you should only allocate numberOfMsgs strings. The NULL string doesn't have to be allocated, just be set to NULL:
m[numberOfMsgs] = NULL;
Finally, you should free the allocated memory. In your case, you can't do that, because you have incremented (and thus changed) the base pointer m. The OS can't free the memory, because the new m isn't registered by the memory allocator.
So, for example:
char **m = split_string(message, 140);
int i = 0;
while (m[i]) {
printf("%d: '%s'\n", i, m[i]);
free(m[i]);
i++;
}
free(m);
That is the problem working with arrays, the information about its size should be stored somewhere, you can never know looking at a char ** how many members it has.
That is why null-terminated strings (c strings) exist, the NULL char marks its end, so you have to iterate through the whole string until you find NULL to know it's length.
Anyway, I´d suggest you modify your split_string() function to:
char** split_string(char* message, size_t * n_msgs) {
//...
*n_msgs = numberOfMsgs;
///
}
And then:
size_t msgs = 0;
char** m = split_string(message, &msgs);
//...
Your while loop is an infinite loop. You are testing the expression *m which never changes, so you will keep increasing i and eventually m[i] will refer to memory that has not been allocated.
You should change for (j =0 ; j <= numberOfMsgs; j++){
m[j] = malloc(141 * sizeof(char));
to
for (j =0 ; j < numberOfMsgs; j++){
m[j] = malloc(141 * sizeof(char));

multiplication of two numbers

Few days back I had an interview with Qualcomm. I was kinnda stucked to one question, the question thou looked very simple but neither me nor the interviewer were satisfied with my answers, if anyone can provide any good solution to this problem.
The question is:
Multiply 2 numbers without using any loops and additions and of course no multiplication and division.
To which I replied: recursion
He said anything else at very low level.
To which the genuine thought that came to my mind was bit shifting, but bit shifting will only multiply the number by power of 2 and for other numbers we finally have to do a addition.
For example: 10 * 7 can be done as: (binary of 7 ~~ 111)
10<< 2 + 10<<1 + 10
40 + 20 + 10 = 70
But again addition was not allowed.
Any thoughts on this issue guys.
Here is a solution just using lookup, addition and shifting. The lookup does not require multiplication as it is an array of pointers to another array - hence addition required to find the right array. Then using the second value you can repeat pointer arithmetic and get the lookup result.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
/* Note:As this is an array of pointers to an array of values, addition is
only required for the lookup.
i.e.
First part: lookup + a value -> A pointer to an array
Second part - Add a value to the pointer to above pointer to get the value
*/
unsigned char lookup[16][16] = {
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 },
{ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30 },
{ 0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45 },
{ 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60 },
{ 0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75 },
{ 0, 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90 },
{ 0, 7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, 84, 91, 98, 105 },
{ 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96, 104, 112, 120 },
{ 0, 9, 18, 27, 36, 45, 54, 63, 72, 81, 90, 99, 108, 117, 126, 135 },
{ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150 },
{ 0, 11, 22, 33, 44, 55, 66, 77, 88, 99, 110, 121, 132, 143, 154, 165 },
{ 0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 168, 180 },
{ 0, 13, 26, 39, 52, 65, 78, 91, 104, 117, 130, 143, 156, 169, 182, 195 },
{ 0, 14, 28, 42, 56, 70, 84, 98, 112, 126, 140, 154, 168, 182, 196, 210 },
{ 0, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180, 195, 210, 225 }
};
unsigned short answer, mult;
unsigned char x, y, a, b;
x = (unsigned char)atoi(argv[1]);
y = (unsigned char)atoi(argv[2]);
printf("Multiple %d by %d\n", x, y);
answer = 0;
/* First nibble of x, First nibble of y */
a = x & 0xf;
b = y & 0xf;
mult = lookup[a][b];
answer += mult;
printf("Looking up %d, %d get %d - Answer so far %d\n", a, b, mult, answer);
/* First nibble of x, Second nibble of y */
a = x & 0xf;
b = (y & 0xf0) >> 4;
mult = lookup[a][b];
answer += mult << 4;
printf("Looking up %d, %d get %d - Answer so far %d\n", a, b, mult, answer);
/* Second nibble of x, First nibble of y */
a = (x & 0xf0) >> 4;
b = y & 0xf;
mult = lookup[a][b];
answer += mult << 4;
printf("Looking up %d, %d get %d - Answer so far %d\n", a, b, mult, answer);
/* Second nibble of x, Second nibble of y */
a = (x & 0xf0) >> 4;
b = (y & 0xf0) >> 4;
mult = lookup[a][b];
answer += mult << 8;
printf("Looking up %d, %d get %d - Answer so far %d\n", a, b, mult, answer);
return 0;
}
Perhaps you could recursively add, using bitwise operations as a replacement for the addition operator. See: Adding Two Numbers With Bitwise and Shift Operators
You can separate your problems by first implementing the addition and then the multiplication based on the addition.
For the addition, implement what they do on processors at the gate level using the C bitwise operators:
http://en.wikipedia.org/wiki/Full_adder
Then for the multiplication, with the addition you implemented, use goto statements and labels so no loop statement (the for, while and do iteration statements) will be used.
What about russian peasant multiplication without using addition? Is there an easy way (a few lines, no loops) to simulate addition using only AND, OR, XOR and NOT?
You can implement addition by bits operators. But still, if you want to avoid loops, you should write a lot of code. (I used to implement multiplication without arithmetic operators, but I use loop, shifting the index until it became zero. If it can help you, tell me, and I will search the file)
You could use logarithms and subtraction instead.
log(a*b) = log(a) + log(b)
a+b = -(-a-b)
exp(log(a)) = a
round(exp(-(-log(a)-log(b))))
How about multiplication tables?
Question: Multiply 2 numbers without using any loops and additions and of course no multiplication and division.
Multiplication is defined in terms of addition. It is impossible not to find addition in an implementation of multiplication.
Arbitrary precision numbers cannot be multiplied without loop/recursion.
Multiplication of two numbers of fixed bit-lengths can be implemented via a table lookup. The problem is the size of the table. Generating the table requires addition.
The answer is: It cannot be done.

Resources