How to get used elements from space complexity optimized 0-1 knapsack - c

I have implemented 0-1 knapsack. "DP" is the 1D table that holds maximum profits. "capacity" is the maximum capacity, "n" is the number of elements. At the end it holds the last row of 2D classic approach in "DP". But i can't figure out how to get which elements are used with just looking at the 1D array.
DP = (int*)calloc(capacity + 1, sizeof(int));
used = (int*)calloc(n, sizeof(int));
for (i = 0; i < n; i++) {
for (j = capacity; j > 0; j--) {
if (weight[i] <= j && DP[j] < DP[j - weight[i]] + profit[i]) {
DP[j] = DP[j - weight[i]] + profit[i];
used[i] = 1;
}
}
}
// for example
// int profit[] = { 7, 16, 13, 8, 1, 11, 14, 11, 12, 7, 6, 10, 1, 1, 11, 12}
// int weight[] = { 6, 2, 7, 2, 1, 2, 5, 4, 12, 16, 1, 4, 10, 12, 12, 2}
// results DP = {0, 6, 16, 22, 28, 34, 39, 45, 47}
// total profit of used elements: 72 <- it should be 47
// total weight of used elements: 20 <- it should be lesser than 8(the capacity)

Related

How to divide an integer into an array of roughly equal and evenly distributed parts that sum to the original integer?

Given an integer n, what is an algorithm that can divide it into an array of d parts, which has the properties that its members sum to the original integer n, are roughly equal in size, and are reasonably evenly distributed throughout the array? e.g. dividing 13 into 10 parts looks something like:
[1, 1, 2, 1, 1, 2, 1, 1, 2, 1]
More specifically, it shouldn't look like:
[1, 1, 1, 1, 1, 1, 1, 2, 2, 2] (uneven distribution)
[1, 1, 1, 1, 1, 1, 1, 1, 1, 4] (not roughly equal in size)
The parity of the array's members is not important.
One way is to use a dynamic ratio (a/b) in relation to the ratio of the large values to small values (c/r) in order to decide the distribution of the remainder after division:
function split(n, d)
{
if(d === 0)
return [];
// Integer division spelled in JavaScript
const q = Math.floor(n / d);
const r = n % d;
const c = d - r;
let out = Array(d);
let a = 1;
let b = 1;
for(let i = 0; i < d; i++)
{
// Make the ratio a/b tend towards c/r
if((a * r) < (b * c))
{
a++;
out[i] = q;
}
else
{
b++;
out[i] = q + 1;
}
}
// Check the array sums to n
console.log(out, n === out.reduce((a, b) => a + b, 0));
return out;
}
split(11, 10);
split(173, 9);
split(13, 10);
split(1773, 19);
This produces the output:
[1, 1, 1, 1, 1, 1, 1, 1, 2, 1], true
[19, 19, 19, 20, 19, 19, 19, 20, 19], true
[1, 1, 2, 1, 1, 2, 1, 1, 2, 1], true
[93, 93, 94, 93, 93, 94, 93, 93, 94, 93, 93, 94, 93, 93, 94, 93, 93, 94, 93], true

fwrite() puts unknown zero

I have one strange problem while using fwrite() in C.After editing of file with integers, i get zero ("0") before my last element which added by fwrite().My exercise is to divide integers in file on groups which are consisted of 10 elements or less.
For example, i have :
{2, 3, 9, 4, 6, 7, 5, 87, 65,12, 45, 2, 3, 4, 5, 6, 7, 8, 9}
after editing i need :
{2, 3, 9, 4, 6, 7, 5, 87, 65, 12, 87, 45, 2, 3, 4, 5, 6, 7, 8, 9, 45 };
With code below I get:
{2, 3, 9, 4, 6, 7, 5, 87, 65, 12, 87, 45, 2, 3, 4, 5, 6, 7, 8, 9, 0, 45 };
In the process of step-by-step debugging fwrite() works only two times, it wites 87 after first ten elements, and 45 after remained.Zero wasn`t writed by fwrite().Is that so?From where it comes finally?
My code:
while (!feof(fp)) {
fread(&elems[k], sizeof(int), 1, fp);
fwrite(&elems[k], sizeof(int), 1, hp);
++k;
if (k == 10 || feof(fp)){
for (i = 0; i < 10; ++i){
if (elems[i] > max_number){
max_number = elems[i];
}
}
fwrite(&max_number, sizeof(int), 1, hp);
for (i = 0; i < 10; ++i){
elems[i] = 0;
}
max_number = INT_MIN;
k = 0;
}
}
Thank for answers!
Using feof will result in reading an extra item.
Must check for errors from fwrite and fread calls.
One possible error is the EOF error.
If fread returns 0 items read the value will be left at whatever it was before. Probably 0. Which is probably where your extra 0 comes from.

realloc() is screwing up my data... what's going on?

I'm writing a variable list implementation. In my insertion step, I check if the array's size is maxed out, and if so I double the maximum capacity and call realloc() to allocate me some new memory. Going from size 2 to 4, 4 to 8, and 8 to 16 works fine, but going from size 16 to 32 gives me some random zeroes in my array. Can anyone tell me what's going on here? I know I could avoid using realloc() by mallocing some new space, using memcpy and then freeing the old pointer... and perhaps there's no performance hit from doing that. But my intuition tells me that there is, and in any case I thought that's what realloc was there for. Can anyone tell me what's going on? The key function in this code is the append function.
#include <stdio.h>
#include <stdlib.h>
#include "problem5.h"
#define FAILURE -1
#define SUCCESS 0
ArrayList ArrayList_Init(int n, int (*append) (ArrayList, int), void (*print) (ArrayList), void (*insert) (ArrayList, int, int), void (*destroy) (ArrayList), int (*valueOf) (ArrayList, int))
{
ArrayList newArrayList = (ArrayList) malloc(sizeof(ArrayList_));
newArrayList->max_size = n;
newArrayList->current_size = 0;
newArrayList->data = malloc(n*sizeof(int));
newArrayList->append = append;
newArrayList->destroy = destroy;
newArrayList->print = print;
newArrayList->insert = insert;
newArrayList->valueOf = valueOf;
return newArrayList;
}// init a new list with capacity n
int append_(ArrayList list, int val)
{
//if the array is at maximum capacity
//double the capacity
//update max_size
//insert the value in the first open spot in the array (aka index current_size)
//increment current_size
if (list->current_size == list->max_size) {
list->max_size *= 2;
if (( list->data = realloc(list->data, list->max_size) ) == NULL)
return FAILURE;
}
list->data[list->current_size] = val;
list->current_size++;
return SUCCESS;
}
void print_(ArrayList list)
{
int i;
printf("List of size %d, max size %d. Contents:\n", list->current_size, list->max_size);
for (i=0; i<list->current_size; i++)
printf("%d, ", list->data[i]);
printf("\n");
}
void insert_(ArrayList list, int val, int index) {
}// insert val into index
void destroy_(ArrayList list)
{
//free list memory
}
int valueOf_(ArrayList list, int index)
{
//return value of specified element
return 0;
}
int main()
{
ArrayList list;
int stat, count = 0;
list = ArrayList_Init(2, append_, print_, insert_, destroy_, valueOf_); // init a new list with capacity 8
do {
printf("Appending %d\n", count);
stat = list->append(list, count) ; // add val to end of the list
list->print(list);
} while (stat == SUCCESS && ++count < 20);
return 0;
}
And here's the output of this:
Appending 0
List of size 1, max size 2. Contents:
0,
Appending 1
List of size 2, max size 2. Contents:
0, 1,
Appending 2
List of size 3, max size 4. Contents:
0, 1, 2,
Appending 3
List of size 4, max size 4. Contents:
0, 1, 2, 3,
Appending 4
List of size 5, max size 8. Contents:
0, 1, 2, 3, 4,
Appending 5
List of size 6, max size 8. Contents:
0, 1, 2, 3, 4, 5,
Appending 6
List of size 7, max size 8. Contents:
0, 1, 2, 3, 4, 5, 6,
Appending 7
List of size 8, max size 8. Contents:
0, 1, 2, 3, 4, 5, 6, 7,
Appending 8
List of size 9, max size 16. Contents:
0, 1, 2, 3, 4, 5, 6, 7, 8,
Appending 9
List of size 10, max size 16. Contents:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
Appending 10
List of size 11, max size 16. Contents:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
Appending 11
List of size 12, max size 16. Contents:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
Appending 12
List of size 13, max size 16. Contents:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
Appending 13
List of size 14, max size 16. Contents:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
Appending 14
List of size 15, max size 16. Contents:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
Appending 15
List of size 16, max size 16. Contents:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
Appending 16
List of size 17, max size 32. Contents:
0, 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16,
Appending 17
List of size 18, max size 32. Contents:
0, 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17,
Appending 18
List of size 19, max size 32. Contents:
0, 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 18,
Appending 19
List of size 20, max size 32. Contents:
0, 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 18, 19,
It is very bad to write so:
list->data = realloc(list->data, list->max_size)
You should use new variable and if memory was reallocated you write so:
List->data = temp;
It will protect you from memory leak.
And you forgot *sizeof(int)

How can I use Opencv SparseMatrix

I want to make a sparse matrix in OpenCV.
How can I do the basic operation for this matrix like:
Putting or accessing data from matrix elements.
Cheers
Using the C++ interface might be more appropriate. Notice that the example code in the documentation [1] lacks the modulo operation und thus fails.
const int dims = 2;
int size[] = {3, 20}; // rows and columns if in two dimensions
SparseMat sparse_mat(dims, size, CV_32F);
for(int i = 0; i < 1000; i++) {
// create a random index in dims dimensions
int idx[dims];
for(int k = 0; k < dims; k++)
idx[k] = rand() % size[k];
sparse_mat.ref<float>(idx) += 1.f;
}
cout << "bottom right element # (2,19) = " << sparse_mat.ref<float>(2,19) << "\n";
Mat dense;
sparse_mat.convertTo(dense, CV_32F);
cout << dense;
Gives the following output
bottom right element # (2,19) = 19
[9, 23, 13, 26, 18, 13, 18, 15, 13, 17, 13, 18, 19, 6, 20, 20, 12, 15, 15, 15;
17, 17, 14, 16, 12, 14, 17, 15, 15, 18, 24, 18, 13, 22, 18, 11, 18, 22, 17, 15;
19, 16, 14, 10, 18, 19, 10, 17, 18, 15, 24, 22, 18, 18, 18, 23, 21, 16, 14, 19]
[1] The OpenCV Reference Manual. Version 2.4.3. 2012, p. 46.
Sets and Sparse Matrices, page 23:
Sparse matrix in OpenCV uses CvSet for storing elements.
CvSparseMat* get_color_map( const IplImage* img )
{
int dims[] = { 256, 256, 256 };
CvSparseMat* cmap = cvCreateSparseMat(3, dims, CV_32SC1);
for( int i = 0; i < img->height; i++ ) for( int j = 0; j < img->width; j++ )
{
uchar* ptr=&CV_IMAGE_ELEM(img,uchar,i,j*3);
int idx[] = {ptr[0],ptr[1],ptr[2]};
((int*)cvPtrND(cmap,idx))[0]++;
}
// print the map
CvSparseMatIterator it;
for(CvSparseNode *node = cvInitSparseMatIterator( mat, &iterator );
node != 0; node = cvGetNextSparseNode( &iterator ))
{
int* idx = CV_NODE_IDX(cmap,node);
int count=*(int*)CV_NODE_VAL(cmap,idx);
printf( ā€œ(b=%d,g=%d,r=%d): %d\nā€, idx[0], idx[1], idx[2], count );
}
return cmap;
}

Finding the sum of the digits

I have a 5-digit integer, say
int num = 23456;
How to find the sum of its digits?
Use the modulo operation to get the value of the least significant digit:
int num = 23456;
int total = 0;
while (num != 0) {
total += num % 10;
num /= 10;
}
If the input could be a negative number then it would be a good idea to check for that and invert the sign.
#include <stdio.h>
int main()
{
int i = 23456;
int sum = 0;
while(i)
{
sum += i % 10;
i /= 10;
}
printf("%i", sum);
return 0;
}
int sum=0;while(num){sum+=num%10;num/=10;}
Gives a negative answer if num is negative, in C99 anyway.
Is this homework?
How about this:
for(sum=0 ,num=23456;num; sum+=num %10, num/=10);
If you want a way to do it without control statements, and incredibly efficient to boot, O(1) instead of the O(n), n = digit count method:
int getSum (unsigned int val) {
static int lookup[] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, // 0- 9
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // 10- 19
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, // 20- 29
:
9, 10, 11, 12, 13, 14, 15, 16, 17, 18, // 90- 99
:
14, 15, 16, 17, 18, 19, 20, 21, 22, 23, // 23450-23459
::
};
return lookup[23456];
}
:-)
Slightly related: if you want the repeated digit sum, a nice optimization would be:
if (num%3==0) return (num%9==0) ? 9 : 3;
Followed by the rest of the code.
Actually, I answered with another (somewhat humorous) answer which used a absolutely huge array for a table lookup but, thinking back on it, it's not that bad an idea, provided you limit the table size.
The following functions trade off space for time. As with all optimisations, you should profile them yourself in the target environment.
First the (elegant) recursive version:
unsigned int getSum (unsigned int val) {
static const unsigned char lookup[] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, // 0- 9
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // 10- 19
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, // 20- 29
:
18, 19, 20, 21, 22, 23, 24, 25, 26, 27 // 990-999
};
return (val == 0) ? 0 : getSum (val / 1000) + lookup[val%1000];
}
It basically separates the number into three-digit groupings with fixed lookups for each possibility. This can easily handle a 64-bit unsigned value with a recursion depth of seven stack frames.
For those who don't even trust that small amount of recursion (and you should, since normal programs go that deep and more even without recursion), you could try the iterative solution:
unsigned int getSum (unsigned int val) {
static const unsigned char lookup[] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, // 0- 9
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // 10- 19
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, // 20- 29
:
18, 19, 20, 21, 22, 23, 24, 25, 26, 27 // 990-999
};
unsigned int tot = 0;
while (val != 0) {
tot += lookup[val%1000];
val /= 1000;
}
return tot;
}
These are probably three times faster than the one-digit-at-a-time solution, at the cost of a thousand bytes of data. If you're not adverse to using 10K or 100K, you could increase the speed to four or five times but you may want to write a program to generate the static array statement above :-)
As with all optimisation options, measure, don't guess!
I prefer the more elegant recursive solution myself but I'm also one of those types who prefer cryptic crosswords. Read into that what you will.
#include <stdio.h>
2 #include <stdlib.h>
3
4 #define BUFSIZE 20
5
6 int main(void)
7 {
8 int number = 23456;
9 char myBuf[BUFSIZE];
10 int result;
11 int i = 0;
12
13 sprintf(myBuf,"%i\0",number);
14
15 for( i = 0; i < BUFSIZE && myBuf[i] != '\0';i++)
16 {
17 result += (myBuf[i]-48);
18 }
19
20 printf("The result is %d",result);
21 return 0;
22 }
23
Another idea here using the sprintf and the ascii number representation
#include<stdio.h>
main()
{
int sum=0,n;
scanf("%d",&n);
while(n){
sum+=n%10;
n/=10;
}
printf("result=%d",sum);
}
sum is the sum of digits of number n

Resources