Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 21-30 of 103 total

Toggling between alternative implementations using comments

If you have two implementations and are unsure which one's the keeper - this may just be what you need.
Imagine you are just working on some performance critical function/method and have to run some tests. Commenting out and changing stuff can be quite tedious if it involves lot's of code changes. With this snippet, you only have to delete (or add) one character to toggle between your options.
Here's how it's done.

   1  
   2  ...
   3  //*
   4  option1();
   5  /*/
   6  option2();
   7  //*/
   8  ...
   9  // option1() is used...


Delete the first
   1  /
and the second option is used.

   1  
   2  ...
   3  /*
   4  option1();
   5  /*/
   6  option2();
   7  //*/
   8  ...
   9  // option2() is used...


If you re-add it, option 1 becomes active again.
So how is this done?
If you start with "//*" the line is a line comment ("*" is commented out).
"/*" starts a block comment instead. "/*/" is either an opening block comment or a closing block comment.
"//*/" is the end of a block comment when inside one - or it's a line comment commenting out "*/".

The 0-1 Knapsack Problem in C

This is a dynamic-programming algorithm implementation for solving the the 0-1 Knapsack Problem in C.

Further explanation is given here.

   1  
   2  #include <stdio.h>
   3  
   4  #define MAXWEIGHT 100
   5  
   6  int n = 3; /* The number of objects */
   7  int c[10] = {8, 6, 4}; /* c[i] is the *COST* of the ith object; i.e. what
   8  				YOU PAY to take the object */
   9  int v[10] = {16, 10, 7}; /* v[i] is the *VALUE* of the ith object; i.e.
  10  				what YOU GET for taking the object */
  11  int W = 10; /* The maximum weight you can take */ 
  12  
  13  void fill_sack() {
  14  	int a[MAXWEIGHT]; /* a[i] holds the maximum value that can be obtained
  15  				using at most i weight */
  16  	int last_added[MAXWEIGHT]; /* I use this to calculate which object were
  17  					added */
  18  	int i, j;
  19  	int aux;
  20  
  21  	for (i = 0; i <= W; ++i) {
  22  		a[i] = 0;
  23  		last_added[i] = -1;
  24  	}
  25  
  26  	a[0] = 0;
  27  	for (i = 1; i <= W; ++i)
  28  		for (j = 0; j < n; ++j)
  29  			if ((c[j] <= i) && (a[i] < a[i - c[j]] + v[j])) {
  30  				a[i] = a[i - c[j]] + v[j];
  31  				last_added[i] = j;
  32  			}
  33  
  34  	for (i = 0; i <= W; ++i)
  35  		if (last_added[i] != -1)
  36  			printf("Weight %d; Benefit: %d; To reach this weight I added object %d (%d$ %dKg) to weight %d.\n", i, a[i], last_added[i] + 1, v[last_added[i]], c[last_added[i]], i - c[last_added[i]]);
  37  		else
  38  			printf("Weight %d; Benefit: 0; Can't reach this exact weight.\n", i);
  39  
  40  	printf("---\n");
  41  
  42  	aux = W;
  43  	while ((aux > 0) && (last_added[aux] != -1)) {
  44  		printf("Added object %d (%d$ %dKg). Space left: %d\n", last_added[aux] + 1, v[last_added[aux]], c[last_added[aux]], aux - c[last_added[aux]]);
  45  		aux -= c[last_added[aux]];
  46  	}
  47  
  48  	printf("Total value added: %d$\n", a[W]);
  49  }
  50  
  51  int main(int argc, char *argv[]) {
  52  	fill_sack();
  53  
  54  	return 0;
  55  }

The Fractional Knapsack Problem in C

This is the classic Greedy algorithm implementation for solving the Fractional Knapsack Problem in C.

Further explanations here

   1  
   2  #include <stdio.h>
   3  
   4  int n = 5; /* The number of objects */
   5  int c[10] = {12, 1, 2, 1, 4}; /* c[i] is the *COST* of the ith object; i.e. what
   6  				YOU PAY to take the object */
   7  int v[10] = {4, 2, 2, 1, 10}; /* v[i] is the *VALUE* of the ith object; i.e.
   8  				what YOU GET for taking the object */
   9  int W = 15; /* The maximum weight you can take */
  10  
  11  void simple_fill() {
  12  	int cur_w;
  13  	float tot_v;
  14  	int i, maxi;
  15  	int used[10];
  16  
  17  	for (i = 0; i < n; ++i)
  18  		used[i] = 0; /* I have not used the ith object yet */
  19  
  20  	cur_w = W;
  21  	while (cur_w > 0) { /* while there's still room*/
  22  		/* Find the best object */
  23  		maxi = -1;
  24  		for (i = 0; i < n; ++i)
  25  			if ((used[i] == 0) &&
  26  				((maxi == -1) || ((float)v[i]/c[i] > (float)v[maxi]/c[maxi])))
  27  				maxi = i;
  28  
  29  		used[maxi] = 1; /* mark the maxi-th object as used */
  30  		cur_w -= c[maxi]; /* with the object in the bag, I can carry less */
  31  		tot_v += v[maxi];
  32  		if (cur_w >= 0)
  33  			printf("Added object %d (%d$, %dKg) completly in the bag. Space left: %d.\n", maxi + 1, v[maxi], c[maxi], cur_w);
  34  		else {
  35  			printf("Added %d%% (%d$, %dKg) of object %d in the bag.\n", (int)((1 + (float)cur_w/c[maxi]) * 100), v[maxi], c[maxi], maxi + 1);
  36  			tot_v -= v[maxi];
  37  			tot_v += (1 + (float)cur_w/c[maxi]) * v[maxi];
  38  		}
  39  	}
  40  
  41  	printf("Filled the bag with objects worth %.2f$.\n", tot_v);
  42  }
  43  
  44  int main(int argc, char *argv[]) {
  45  	simple_fill();
  46  
  47  	return 0;
  48  }

All Sources Shortest Path: The Floyd-Warshall Algorithm

This is a straightforward implementation of the Floyd-Warshall algorithm for finding the shortest path between all nodes of a graph.


A more detailed explanation is given here.

   1  
   2  #include <stdio.h>
   3  
   4  int n; /* Then number of nodes */
   5  int dist[16][16]; /* dist[i][j] is the length of the edge between i and j if
   6  			it exists, or 0 if it does not */
   7  
   8  void printDist() {
   9  	int i, j;
  10  	printf("    ");
  11  	for (i = 0; i < n; ++i)
  12  		printf("%4c", 'A' + i);
  13  	printf("\n");
  14  	for (i = 0; i < n; ++i) {
  15  		printf("%4c", 'A' + i);
  16  		for (j = 0; j < n; ++j)
  17  			printf("%4d", dist[i][j]);
  18  		printf("\n");
  19  	}
  20  	printf("\n");
  21  }
  22  
  23  /*
  24  	floyd_warshall()
  25  
  26  	after calling this function dist[i][j] will the the minimum distance
  27  	between i and j if it exists (i.e. if there's a path between i and j)
  28  	or 0, otherwise
  29  */
  30  void floyd_warshall() {
  31  	int i, j, k;
  32  	for (k = 0; k < n; ++k) {
  33  		printDist();
  34  		for (i = 0; i < n; ++i)
  35  			for (j = 0; j < n; ++j)
  36  				/* If i and j are different nodes and if 
  37  					the paths between i and k and between
  38  					k and j exist, do */
  39  				if ((dist[i][k] * dist[k][j] != 0) && (i != j))
  40  					/* See if you can't get a shorter path
  41  						between i and j by interspacing
  42  						k somewhere along the current
  43  						path */
  44  					if ((dist[i][k] + dist[k][j] < dist[i][j]) ||
  45  						(dist[i][j] == 0))
  46  						dist[i][j] = dist[i][k] + dist[k][j];
  47  	}
  48  	printDist();
  49  }
  50  
  51  int main(int argc, char *argv[]) {
  52  	FILE *fin = fopen("dist.txt", "r");
  53  	fscanf(fin, "%d", &n);
  54  	int i, j;
  55  	for (i = 0; i < n; ++i)
  56  		for (j = 0; j < n; ++j)
  57  			fscanf(fin, "%d", &dist[i][j]);
  58  	fclose(fin);
  59  
  60  	floyd_warshall();
  61  
  62  	return 0;
  63  }
  64  

Prim's Algorithm for Finding Minimum Spanning Trees in C

The is a straight-forward implementation of Prim's Algorithm for finding the minimum spanning tree of a graph.

A detailed explanation is given here.

   1  
   2  #include <stdio.h>
   3  
   4  /*
   5  	The input file (weight.txt) look something like this
   6  		4
   7  		0 0 0 21
   8  		0 0 8 17
   9  		0 8 0 16
  10  		21 17 16 0
  11  
  12  	The first line contains n, the number of nodes.
  13  	Next is an nxn matrix containg the distances between the nodes
  14  	NOTE: The distance between a node and itself should be 0
  15  */
  16  
  17  int n; /* The number of nodes in the graph */
  18  
  19  int weight[100][100]; /* weight[i][j] is the distance between node i and node j;
  20  			if there is no path between i and j, weight[i][j] should
  21  			be 0 */
  22  
  23  char inTree[100]; /* inTree[i] is 1 if the node i is already in the minimum
  24  			spanning tree; 0 otherwise*/
  25  
  26  int d[100]; /* d[i] is the distance between node i and the minimum spanning
  27  		tree; this is initially infinity (100000); if i is already in
  28  		the tree, then d[i] is undefined;
  29  		this is just a temporary variable. It's not necessary but speeds
  30  		up execution considerably (by a factor of n) */
  31  
  32  int whoTo[100]; /* whoTo[i] holds the index of the node i would have to be
  33  			linked to in order to get a distance of d[i] */
  34  
  35  /* updateDistances(int target)
  36  	should be called immediately after target is added to the tree;
  37  	updates d so that the values are correct (goes through target's
  38  	neighbours making sure that the distances between them and the tree
  39  	are indeed minimum)
  40  */
  41  void updateDistances(int target) {
  42  	int i;
  43  	for (i = 0; i < n; ++i)
  44  		if ((weight[target][i] != 0) && (d[i] > weight[target][i])) {
  45  			d[i] = weight[target][i];
  46  			whoTo[i] = target;
  47  		}
  48  }
  49  
  50  int main(int argc, char *argv[]) {
  51  	FILE *f = fopen("dist.txt", "r");
  52  	fscanf(f, "%d", &n);
  53  	int i, j;
  54  	for (i = 0; i < n; ++i)
  55  		for (j = 0; j < n; ++j)
  56  			fscanf(f, "%d", &weight[i][j]);
  57  	fclose(f);
  58  
  59  	/* Initialise d with infinity */
  60  	for (i = 0; i < n; ++i)
  61  		d[i] = 100000;
  62  
  63  	/* Mark all nodes as NOT beeing in the minimum spanning tree */
  64  	for (i = 0; i < n; ++i)
  65  		inTree[i] = 0;
  66  
  67  	/* Add the first node to the tree */
  68  	printf("Adding node %c\n", 0 + 'A');
  69  	inTree[0] = 1;
  70  	updateDistances(0);
  71  
  72  	int total = 0;
  73  	int treeSize;
  74  	for (treeSize = 1; treeSize < n; ++treeSize) {
  75  		/* Find the node with the smallest distance to the tree */
  76  		int min = -1;
  77  		for (i = 0; i < n; ++i)
  78  			if (!inTree[i])
  79  				if ((min == -1) || (d[min] > d[i]))
  80  					min = i;
  81  
  82  		/* And add it */
  83  		printf("Adding edge %c-%c\n", whoTo[min] + 'A', min + 'A');
  84  		inTree[min] = 1;
  85  		total += d[min];
  86  
  87  		updateDistances(min);
  88  	}
  89  
  90  	printf("Total distance: %d\n", total);
  91  
  92  	return 0;
  93  }
  94  

Print a binary number in C

These are two functions that print the binary representation of an integer. The first simply prints it out, while the second only prints out the relevant digits (i.e. cuts the first x 0 digits) in groups of four.

Explanation here.

   1  
   2  #include <stdio.h>
   3  
   4  /* Print n as a binary number */
   5  void printbitssimple(int n) {
   6  	unsigned int i;
   7  	i = 1<<(sizeof(n) * 8 - 1);
   8  
   9  	while (i > 0) {
  10  		if (n & i)
  11  			printf("1");
  12  		else
  13  			printf("0");
  14  		i >>= 1;
  15  	}
  16  }
  17  
  18  /* Print n as a binary number */
  19  void printbits(int n) {
  20  	unsigned int i, step;
  21  
  22  	if (0 == n) { /* For simplicity's sake, I treat 0 as a special case*/
  23  		printf("0000");
  24  		return;
  25  	}
  26  
  27  	i = 1<<(sizeof(n) * 8 - 1);
  28  
  29  	step = -1; /* Only print the relevant digits */
  30  	step >>= 4; /* In groups of 4 */
  31  	while (step >= n) {
  32  		i >>= 4;
  33  		step >>= 4;
  34  	}
  35  
  36  	/* At this point, i is the smallest power of two larger or equal to n */
  37  	while (i > 0) {
  38  		if (n & i)
  39  			printf("1");
  40  		else
  41  			printf("0");
  42  		i >>= 1;
  43  	}
  44  }
  45  
  46  int main(int argc, char *argv[]) {
  47  	int i;
  48  	for (i = 0; i < 16; ++i) {
  49  		printf("%d = ", i);
  50  		printbitssimple(i);
  51  		printf("\n");
  52  	}
  53  
  54  	return 0;
  55  }
  56  

Generate combinations

Code generates all the combinations of n elements choosing k elements.

See this for definition.

See this for explanation.

   1  
   2  #include <stdio.h>
   3  
   4  /* Prints out a combination like {1, 2} */
   5  void printc(int comb[], int k) {
   6  	printf("{");
   7  	int i;
   8  	for (i = 0; i < k; ++i)
   9  		printf("%d, ", comb[i] + 1);
  10  	printf("\b\b}\n");
  11  }
  12  
  13  /*
  14  	next_comb(int comb[], int k, int n)
  15  		Generates the next combination of n elements as k after comb
  16  
  17  	comb => the previous combination ( use (0, 1, 2, ..., k) for first)
  18  	k => the size of the subsets to generate
  19  	n => the size of the original set
  20  
  21  	Returns: 1 if a valid combination was found
  22  		0, otherwise
  23  */
  24  int next_comb(int comb[], int k, int n) {
  25  	int i = k - 1;
  26  	++comb[i];
  27  	while ((i >= 0) && (comb[i] >= n - k + 1 + i)) {
  28  		--i;
  29  		++comb[i];
  30  	}
  31  
  32  	if (comb[0] > n - k) /* Combination (n-k, n-k+1, ..., n) reached */
  33  		return 0; /* No more combinations can be generated */
  34  
  35  	/* comb now looks like (..., x, n, n, n, ..., n).
  36  	Turn it into (..., x, x + 1, x + 2, ...) */
  37  	for (i = i + 1; i < k; ++i)
  38  		comb[i] = comb[i - 1] + 1;
  39  
  40  	return 1;
  41  }
  42  
  43  int main(int argc, char *argv[]) {
  44  	int n = 5; /* The size of the set; for {1, 2, 3, 4} it's 4 */
  45  	int k = 3; /* The size of the subsets; for {1, 2}, {1, 3}, ... it's 2 */
  46  	int comb[16]; /* comb[i] is the index of the i-th element in the
  47  			combination */
  48  
  49  	/* Setup comb for the initial combination */
  50  	int i;
  51  	for (i = 0; i < k; ++i)
  52  		comb[i] = i;
  53  
  54  	/* Print the first combination */
  55  	printc(comb, k);
  56  
  57  	/* Generate and print all the other combinations */
  58  	while (next_comb(comb, k, n))
  59  		printc(comb, k);
  60  
  61  	return 0;
  62  }
  63  

Generate permutations

Generates all the permutations of {1, 2, ..., n}.

See this for further explanations.

   1  
   2  #include <stdio.h>
   3  
   4  void printv(int v[], int n) {
   5  	int i;
   6  
   7  	for (i = 0; i < n; i++)
   8  		printf("%d ", v[i]);
   9  	printf("\n");
  10  }
  11  
  12  /*!
  13  	This just swaps the values of a and b
  14  
  15  	i.e if a = 1 and b = 2, after
  16  
  17  		SWAP(a, b);
  18  
  19  	a = 2 and b = 1
  20  */
  21  #define SWAP(a, b) a = a + b - (b = a)
  22  
  23  /*!
  24  	Generates the next permutation of the vector v of length n.
  25  
  26  	@return 1, if there are no more permutations to be generated
  27  
  28  	@return 0, otherwise
  29  */
  30  int next(int v[], int n) {
  31  	/* P2 */
  32  	/* Find the largest i */
  33  	int i = n - 2;
  34  	while ((i >= 0) && (v[i] > v[i + 1]))
  35  		--i;
  36  
  37  	/* If i is smaller than 0, then there are no more permutations. */
  38  	if (i < 0)
  39  		return 1;
  40  
  41  	/* Find the largest element after vi but not larger than vi */
  42  	int k = n - 1;
  43  	while (v[i] > v[k])
  44  		--k;
  45  	SWAP(v[i], v[k]);
  46  
  47  	/* Swap the last n - i elements. */
  48  	int j;
  49  	k = 0;
  50  	for (j = i + 1; j < (n + i) / 2 + 1; ++j, ++k)
  51  		SWAP(v[j], v[n - k - 1]);
  52  
  53  	return 0;
  54  }
  55  
  56  int main(int argc, char *argv[]) {
  57  	int v[128];
  58  	int n = 3;
  59  
  60  	/* The initial permutation is 1 2 3 ...*/
  61  	/* P1 */
  62  	int i;
  63  	for (i = 0; i < n; ++i)
  64  		v[i] = i + 1;
  65  	printv(v, n);
  66  
  67  	int done = 1;
  68  	do {
  69  		if (!(done = next(v, n)))
  70  			printv(v, n); /* P3 */
  71  	} while (!done);
  72  
  73  	return 0;
  74  }

Generate all subsets of a set

This code generates all the subsets of {1, 2, ..., n} and prints them.

This also contains a very fast binary counter implementation.

See this for further explanations.

   1  
   2  #include <stdio.h>
   3  
   4  /* Applies the mask to a set like {1, 2, ..., n} and prints it */
   5  void printv(int mask[], int n) {
   6  	int i;
   7  	printf("{ ");
   8  	for (i = 0; i < n; ++i)
   9  		if (mask[i])
  10  			printf("%d ", i + 1); /*i+1 is part of the subset*/
  11  	printf("\b }\n");
  12  }
  13  
  14  /* Generates the next mask*/
  15  int next(int mask[], int n) {
  16  	int i;
  17  	for (i = 0; (i < n) && mask[i]; ++i)
  18  		mask[i] = 0;
  19  
  20  	if (i < n) {
  21  		mask[i] = 1;
  22  		return 1;
  23  	}
  24  	return 0;
  25  }
  26  
  27  int main(int argc, char *argv[]) {
  28  	int n = 3;
  29  
  30  	int mask[16]; /* Guess what this is */
  31  	int i;
  32  	for (i = 0; i < n; ++i)
  33  		mask[i] = 0;
  34  
  35  	/* Print the first set */
  36  	printv(mask, n);
  37  
  38  	/* Print all the others */
  39  	while (next(mask, n))
  40  		printv(mask, n);
  41  
  42  	return 0;
  43  }

Fast selection

Selectv returns the position of the nth smallest number in the list.

Selectv modifies the list.

   1  
   2  #include <stdio.h>
   3  
   4  typedef struct {
   5  	int len;
   6  	int e[102];
   7  } List;
   8  
   9  void printv(char *msg, List l) {
  10  	printf("%s", msg);
  11  	int i;
  12  	for (i = 0; i < l.len; ++i)
  13  		printf("%d ", l.e[i]);
  14  	printf("\n");
  15  }
  16  
  17  int pivot(List *l, int p, int r) {
  18  	int x = l->e[r];
  19  	int i = p - 1;
  20  	int j = r + 1;
  21  	
  22  	while (1) {
  23  		do {
  24  			++i;
  25  		} while (l->e[i] < x);
  26  		do {
  27  			--j;
  28  		} while (l->e[j] > x);
  29  	
  30  		//printf("%d %d\n", i, j);
  31  		
  32  		if (i < j) {
  33  			int aux = l->e[i];
  34  			l->e[i] = l->e[j];
  35  			l->e[j] = aux;
  36  		} else
  37  			return i - 1;
  38  	}
  39  }
  40  
  41  
  42  int selectv(List *l, int nrp, int p, int r) {
  43  	//printf("p, r: %d, %d\n", p, r);
  44  	//printf("nrp: %d\n", nrp);
  45  	//printv("l: ", *l);
  46  	
  47  	if (p == r)
  48  		return l->e[p];
  49  	
  50  	if (p < r) {
  51  		int q = pivot(l, p, r);
  52  		
  53  		//getchar();
  54  		
  55  		if (q - p + 1< nrp)
  56  			return selectv(l, nrp - (q - p) - 1, q + 1, r);
  57  		return selectv(l, nrp, p, q);
  58  	}
  59  	return -1;
  60  }
  61  
  62  int main(int argc, char *argv[]) {
  63  	List l;
  64  	l.len = 100;
  65  	int i;
  66  	for (i = 0; i < l.len; ++i)
  67  		l.e[i] = l.len - i;
  68  	
  69  	int nth = 56;
  70  	printf("%d: %d\n", nth, selectv(&l, nth, 0, l.len - 1));
  71  	
  72  	//printv("L: ", l);
  73  	
  74  	return 0;
  75  }
  76  
« Newer Snippets
Older Snippets »
Showing 21-30 of 103 total