<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: algorithm code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Fri, 16 May 2008 16:49:40 GMT</pubDate>
    <description>DZone Snippets: algorithm code</description>
    <item>
      <title>Bit field class</title>
      <link>http://snippets.dzone.com/posts/show/5495</link>
      <description>// A bit field is an important data structure in computer science, major uses include memory allocators and Bloom filters.&lt;br /&gt;// The code is in the form of a header file and an implementation file.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;&lt;bitfield.h&gt;&lt;br /&gt;// This class is a code snippet, it can be freely used and distributed.&lt;br /&gt;// Author: irfan[dot]hamid[at]gmail[dot]com&lt;br /&gt;//&lt;br /&gt;// Bit fields are a widely used mechanism in computing applications.&lt;br /&gt;// Typical applications include memory allocators and Bloom filters. This class&lt;br /&gt;// provides a generic bit field implementation for an arbitrary number of bits.&lt;br /&gt;//&lt;br /&gt;// Implementation notes:&lt;br /&gt;// The use of C++ allows the clean separation of the data structure from the&lt;br /&gt;// interface. The bit field is implemented as a vector of unsigned int that is&lt;br /&gt;// allocated at object creation.&lt;br /&gt;//&lt;br /&gt;// field: The vector that represents the bit field itself&lt;br /&gt;// bit_count: The total number of bits in the bit field&lt;br /&gt;&lt;br /&gt;#ifndef __BITFIELD_H__&lt;br /&gt;#define __BITFIELD_H__&lt;br /&gt;#include &lt;math.h&gt;&lt;br /&gt;#define SZ_UINT sizeof(unsigned int)&lt;br /&gt;&lt;br /&gt;class Bitfield&lt;br /&gt;{&lt;br /&gt;protected:&lt;br /&gt;	unsigned int *field;&lt;br /&gt;	unsigned int bit_count;&lt;br /&gt;&lt;br /&gt;public:&lt;br /&gt;	Bitfield (int bc);&lt;br /&gt;	~Bitfield ();&lt;br /&gt;&lt;br /&gt;	int set (int bit);&lt;br /&gt;	int get (int bit);&lt;br /&gt;	int reset (int bit);&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;#endif&lt;br /&gt;&lt;/bitfield.h&gt;&lt;br /&gt;&lt;br /&gt;&lt;bitfield.cpp&gt;&lt;br /&gt;#include &lt;stdlib.h&gt;&lt;br /&gt;#include "bitfield.h"&lt;br /&gt;&lt;br /&gt;// The constructor takes an int param which gives the number of bits in this&lt;br /&gt;// bit field.&lt;br /&gt;Bitfield::Bitfield (int bc)&lt;br /&gt;{&lt;br /&gt;	bit_count = bc;&lt;br /&gt;&lt;br /&gt;	// E.g, ceil(257/32*8) = 65, 64 ints fully used, last one partially used&lt;br /&gt;	field = (unsigned int*) malloc(((int) ceil(bc/SZ_UINT*8)));&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;Bitfield::~Bitfield ()&lt;br /&gt;{&lt;br /&gt;	if (field)&lt;br /&gt;		free(field);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// This function sets the corresponding bit in the field equal to 1.&lt;br /&gt;//&lt;br /&gt;// Returns: 0 on success, -1 on error.&lt;br /&gt;int Bitfield::set (int bit)&lt;br /&gt;{&lt;br /&gt;	// Sanity check&lt;br /&gt;	if (bit &gt;= bit_count || !field)&lt;br /&gt;		return -1;&lt;br /&gt;&lt;br /&gt;	// The correct index into the vector will be given by bit/SZ_UNIT. The&lt;br /&gt;	// index into the correct vector element is given by bit%SZ_UNIT, to&lt;br /&gt;	// achieve this, simply left shift 0x01 the appropriate number of times.&lt;br /&gt;	field[bit/SZ_UINT] |= (0x00000001 &lt;&lt; (bit%(SZ_UINT*8)-1));&lt;br /&gt;	return 0;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// This function sets the corresponding bit in the field equal to 0.&lt;br /&gt;//&lt;br /&gt;// Returns: 0 on success, -1 on error.&lt;br /&gt;int Bitfield::reset (int bit)&lt;br /&gt;{&lt;br /&gt;	if (bit &gt;= bit_count || !field)&lt;br /&gt;		return -1;&lt;br /&gt;	field[bit/SZ_UINT] &amp;= ~(0x00000001 &lt;&lt; (bit%(SZ_UINT*8)-1));&lt;br /&gt;	return 0;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// This function returns the value of the corresponding bit.&lt;br /&gt;//&lt;br /&gt;// Returns: The value of the bit, if the field is initialized and bit index is&lt;br /&gt;// within bounds, -1 otherwise.&lt;br /&gt;int Bitfield::get (int bit)&lt;br /&gt;{&lt;br /&gt;	if (bit &gt;= bit_count || !field)&lt;br /&gt;		return -1;&lt;br /&gt;	return (field[bit/SZ_UINT] &amp; (0x00000001 &lt;&lt; (bit%(SZ_UINT*8)-1)) ? 1 : 0);&lt;br /&gt;}&lt;br /&gt;&lt;/bitfield.cpp&gt;&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 15 May 2008 11:48:59 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/5495</guid>
      <author>phaana (Irfan Hamid)</author>
    </item>
    <item>
      <title>Fast anagram determination</title>
      <link>http://snippets.dzone.com/posts/show/5494</link>
      <description>// This function will determine whether the two C strings provided are anagrams or not. Only alphabetical strings are considered.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;/******************************************************************************&lt;br /&gt; * This function is a code snippet. It can be freely used and distributed.&lt;br /&gt; * Author: irfan[dot]hamid[at]gmail[at]com&lt;br /&gt; *&lt;br /&gt; * This function takes two ASCII strings in C syntax (null-terminated&lt;br /&gt; * character arrays) and determines whether they are anagrams or not.&lt;br /&gt; *&lt;br /&gt; * Implementation notes:&lt;br /&gt; * The function contains a histogram that stores the frequency of each &lt;br /&gt; * character it encounters in the first string. For each character of the &lt;br /&gt; * second string, it decrements the corresponding entry in the histogram. If &lt;br /&gt; * before every decrement, the value of the histogram bucket reaches zero, &lt;br /&gt; * then the two strings are not anagrams, as there is some character that has&lt;br /&gt; * more occurrences in the second string than in the first string.&lt;br /&gt; *&lt;br /&gt; * If either of the two strings contains a non-alphabetic character, the&lt;br /&gt; * anagram property is considered to be violated.&lt;br /&gt; *&lt;br /&gt; * Remarks:&lt;br /&gt; * It is an efficient implementation because:&lt;br /&gt; *   o It is in-place, the original strings are not copied, no alloc or copy&lt;br /&gt; *   o Does not clobber the original strings&lt;br /&gt; *   o It is a linear time implementation&lt;br /&gt; *&lt;br /&gt; * Returns:&lt;br /&gt; * True if the strings are anagrams, false otherwise.&lt;br /&gt;******************************************************************************/&lt;br /&gt;&lt;br /&gt;bool is_anagram (char w1[], char w2[])&lt;br /&gt;{&lt;br /&gt;	unsigned int i, sz;&lt;br /&gt;&lt;br /&gt;	/* The histogram */&lt;br /&gt;	int freqtbl[26];&lt;br /&gt;&lt;br /&gt;	/* Sanity check */&lt;br /&gt;	if ((sz = strlen(w1)) != strlen(w2))&lt;br /&gt;		return false;&lt;br /&gt;&lt;br /&gt;	/* Initialize the histogram */&lt;br /&gt;	bzero(freqtbl, 26*sizeof(int));&lt;br /&gt;&lt;br /&gt;	/* Read the first string, incrementing the corresponding histogram entry */&lt;br /&gt;	for (i = 0; i &lt; sz; i++) {&lt;br /&gt;		if (w1[i] &gt;= 'A' &amp;&amp; w1[i] &lt;= 'Z')&lt;br /&gt;			freqtbl[w1[i]-'A']++;&lt;br /&gt;		else if (w1[i] &gt;= 'a' &amp;&amp; w1[i] &lt;= 'z')&lt;br /&gt;			freqtbl[w1[i]-'a']++;&lt;br /&gt;		else&lt;br /&gt;			return false;&lt;br /&gt;	}&lt;br /&gt;&lt;br /&gt;	/* Read the second string, decrementing the corresponding histogram entry */&lt;br /&gt;	for (i = 0; i &lt; sz; i++) {&lt;br /&gt;		if (w2[i] &gt;= 'A' &amp;&amp; w2[i] &lt;= 'Z') {&lt;br /&gt;			if (freqtbl[w2[i]-'A'] == 0)&lt;br /&gt;				return false;&lt;br /&gt;			freqtbl[w2[i]-'A']--;&lt;br /&gt;		} else if (w2[i] &gt;= 'a' &amp;&amp; w2[i] &lt;= 'z') {&lt;br /&gt;			if (freqtbl[w2[i]-'a'] == 0)&lt;br /&gt;				return false;&lt;br /&gt;			freqtbl[w2[i]-'a']--;&lt;br /&gt;		} else {&lt;br /&gt;			return false;&lt;br /&gt;		}&lt;br /&gt;	}&lt;br /&gt;&lt;br /&gt;	return true;&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Wed, 14 May 2008 23:40:31 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/5494</guid>
      <author>phaana (Irfan Hamid)</author>
    </item>
    <item>
      <title>Speeding up Dijkstra's Algorithm</title>
      <link>http://snippets.dzone.com/posts/show/4996</link>
      <description>Demonstrates a way of speeding up the O(n&lt;sup&gt;2&lt;/sup&gt;) version of Dijkstra's Algorithm by about 4x.&lt;br /&gt;&lt;br /&gt;Here, dist[][] is the adjacency matrix representing the graph and n is the number of nodes. d2[] is where the lengths of the shortest paths are saved.&lt;br /&gt;&lt;br /&gt;For a full explanation, see &lt;a href="http://compprog.wordpress.com/2008/01/17/speeding-up-dijkstras-algorithm-1/"&gt;this&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;void dijkstra2(int s) {&lt;br /&gt;	int queue[GRAPHSIZE];&lt;br /&gt;	char inQueue[GRAPHSIZE];&lt;br /&gt;	int begq = 0,&lt;br /&gt;	    endq = 0;&lt;br /&gt;	int i, mini;&lt;br /&gt;	int visited[GRAPHSIZE];&lt;br /&gt;&lt;br /&gt;	for (i = 1; i &lt;= n; ++i) {&lt;br /&gt;		d2[i] = INFINITY;&lt;br /&gt;		visited[i] = 0; /* the i-th element has not yet been visited */&lt;br /&gt;		inQueue[i] = 0;&lt;br /&gt;	}&lt;br /&gt;&lt;br /&gt;	d2[s] = 0;&lt;br /&gt;	queue[endq] = s;&lt;br /&gt;	endq = (endq + 1) % GRAPHSIZE;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;	while (begq != endq) {&lt;br /&gt;		mini = queue[begq];&lt;br /&gt;		begq = (begq + 1) % GRAPHSIZE;&lt;br /&gt;		inQueue[mini] = 0;&lt;br /&gt;&lt;br /&gt;		visited[mini] = 1;&lt;br /&gt;&lt;br /&gt;		for (i = 1; i &lt;= n; ++i)&lt;br /&gt;			if (dist[mini][i])&lt;br /&gt;				if (d2[mini] + dist[mini][i] &lt; d2[i]) { &lt;br /&gt;					d2[i] = d2[mini] + dist[mini][i];&lt;br /&gt;					if (!inQueue[i]) {&lt;br /&gt;						queue[endq] = i;&lt;br /&gt;						endq = (endq + 1) % GRAPHSIZE;&lt;br /&gt;						inQueue[i] = 1;&lt;br /&gt;					}&lt;br /&gt;				}&lt;br /&gt;	}&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 17 Jan 2008 15:57:42 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4996</guid>
      <author>scvalex (Alexandru Scvortov)</author>
    </item>
    <item>
      <title>Gaussian Elimination in C</title>
      <link>http://snippets.dzone.com/posts/show/4874</link>
      <description>This is a simple implementation of the &lt;a href="http://en.wikipedia.org/wiki/Gaussian_elimination"&gt;Gaussian Elimination&lt;/a&gt; algorithm for solving n linear equations with n unknowns.&lt;br /&gt;&lt;br /&gt;Further explanation is given &lt;a href="http://compprog.wordpress.com/2007/12/11/gaussian-elimination/"&gt;here&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;#include &lt;stdio.h&gt;&lt;br /&gt;&lt;br /&gt;int n;&lt;br /&gt;float a[10][11];&lt;br /&gt;&lt;br /&gt;void forwardSubstitution() {&lt;br /&gt;	int i, j, k, max;&lt;br /&gt;	float t;&lt;br /&gt;	for (i = 0; i &lt; n; ++i) {&lt;br /&gt;		max = i;&lt;br /&gt;		for (j = i + 1; j &lt; n; ++j)&lt;br /&gt;			if (a[j][i] &gt; a[max][i])&lt;br /&gt;				max = j;&lt;br /&gt;		&lt;br /&gt;		for (j = 0; j &lt; n + 1; ++j) {&lt;br /&gt;			t = a[max][j];&lt;br /&gt;			a[max][j] = a[i][j];&lt;br /&gt;			a[i][j] = t;&lt;br /&gt;		}&lt;br /&gt;		&lt;br /&gt;		for (j = n; j &gt;= i; --j)&lt;br /&gt;			for (k = i + 1; k &lt; n; ++k)&lt;br /&gt;				a[k][j] -= a[k][i]/a[i][i] * a[i][j];&lt;br /&gt;&lt;br /&gt;/*		for (k = 0; k &lt; n; ++k) {&lt;br /&gt;			for (j = 0; j &lt; n + 1; ++j)&lt;br /&gt;				printf("%.2f\t", a[k][j]);&lt;br /&gt;			printf("\n");&lt;br /&gt;		}*/&lt;br /&gt;	}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;void reverseElimination() {&lt;br /&gt;	int i, j;&lt;br /&gt;	for (i = n - 1; i &gt;= 0; --i) {&lt;br /&gt;		a[i][n] = a[i][n] / a[i][i];&lt;br /&gt;		a[i][i] = 1;&lt;br /&gt;		for (j = i - 1; j &gt;= 0; --j) {&lt;br /&gt;			a[j][n] -= a[j][i] * a[i][n];&lt;br /&gt;			a[j][i] = 0;&lt;br /&gt;		}&lt;br /&gt;	}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;void gauss() {&lt;br /&gt;	int i, j;&lt;br /&gt;&lt;br /&gt;	forwardSubstitution();&lt;br /&gt;	reverseElimination();&lt;br /&gt;	&lt;br /&gt;	for (i = 0; i &lt; n; ++i) {&lt;br /&gt;		for (j = 0; j &lt; n + 1; ++j)&lt;br /&gt;			printf("%.2f\t", a[i][j]);&lt;br /&gt;		printf("\n");&lt;br /&gt;	}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main(int argc, char *argv[]) {&lt;br /&gt;	int i, j;&lt;br /&gt;&lt;br /&gt;	FILE *fin = fopen("gauss.in", "r");&lt;br /&gt;	fscanf(fin, "%d", &amp;n);&lt;br /&gt;	for (i = 0; i &lt; n; ++i)&lt;br /&gt;		for (j = 0; j &lt; n + 1; ++j)&lt;br /&gt;			fscanf(fin, "%f", &amp;a[i][j]);&lt;br /&gt;	fclose(fin);&lt;br /&gt;	&lt;br /&gt;	gauss();&lt;br /&gt;	&lt;br /&gt;	return 0;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Tue, 11 Dec 2007 13:46:27 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4874</guid>
      <author>scvalex (Alexandru Scvortov)</author>
    </item>
    <item>
      <title>Dijkstra's Algorithm</title>
      <link>http://snippets.dzone.com/posts/show/4832</link>
      <description>This is a simple O(n^2) implementation of &lt;a href="http://en.wikipedia.org/wiki/Dijkstra's_algorithm"&gt;Dijkstra's algorithm&lt;/a&gt; for finding the shortest paths from a single source to all nodes in a graph.&lt;br /&gt;&lt;br /&gt;Further explanation is given &lt;a href="http://compprog.wordpress.com/2007/12/01/one-source-shortest-path-dijkstras-algorithm/"&gt;here&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;#include &lt;stdio.h&gt;&lt;br /&gt;&lt;br /&gt;#define GRAPHSIZE 2048&lt;br /&gt;#define INFINITY GRAPHSIZE*GRAPHSIZE&lt;br /&gt;#define MAX(a, b) ((a &gt; b) ? (a) : (b))&lt;br /&gt;&lt;br /&gt;int e; /* The number of nonzero edges in the graph */&lt;br /&gt;int n; /* The number of nodes in the graph */&lt;br /&gt;long dist[GRAPHSIZE][GRAPHSIZE]; /* dist[i][j] is the distance between node i and j; or 0 if there is no direct connection */&lt;br /&gt;long d[GRAPHSIZE]; /* d[i] is the length of the shortest path between the source (s) and node i */&lt;br /&gt;&lt;br /&gt;void printD() {&lt;br /&gt;	int i;&lt;br /&gt;	for (i = 1; i &lt;= n; ++i)&lt;br /&gt;		printf("%10d", i);&lt;br /&gt;	printf("\n");&lt;br /&gt;	for (i = 1; i &lt;= n; ++i) {&lt;br /&gt;		printf("%10ld", d[i]);&lt;br /&gt;	}&lt;br /&gt;	printf("\n");&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;void dijkstra(int s) {&lt;br /&gt;	int i, k, mini;&lt;br /&gt;	int visited[GRAPHSIZE];&lt;br /&gt;&lt;br /&gt;	for (i = 1; i &lt;= n; ++i) {&lt;br /&gt;		d[i] = INFINITY;&lt;br /&gt;		visited[i] = 0; /* the i-th element has not yet been visited */&lt;br /&gt;	}&lt;br /&gt;&lt;br /&gt;	d[s] = 0;&lt;br /&gt;&lt;br /&gt;	for (k = 1; k &lt;= n; ++k) {&lt;br /&gt;		mini = -1;&lt;br /&gt;		for (i = 1; i &lt;= n; ++i)&lt;br /&gt;			if (!visited[i] &amp;&amp; ((mini == -1) || (d[i] &lt; d[mini])))&lt;br /&gt;				mini = i;&lt;br /&gt;&lt;br /&gt;		visited[mini] = 1;&lt;br /&gt;&lt;br /&gt;		for (i = 1; i &lt;= n; ++i)&lt;br /&gt;			if (dist[mini][i])&lt;br /&gt;				if (d[mini] + dist[mini][i] &lt; d[i]) &lt;br /&gt;					d[i] = d[mini] + dist[mini][i];&lt;br /&gt;	}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main(int argc, char *argv[]) {&lt;br /&gt;	int i, j;&lt;br /&gt;	int u, v, w;&lt;br /&gt;&lt;br /&gt;	FILE *fin = fopen("dist.txt", "r");&lt;br /&gt;	fscanf(fin, "%d", &amp;e);&lt;br /&gt;	for (i = 0; i &lt; e; ++i)&lt;br /&gt;		for (j = 0; j &lt; e; ++j)&lt;br /&gt;			dist[i][j] = 0;&lt;br /&gt;	n = -1;&lt;br /&gt;	for (i = 0; i &lt; e; ++i) {&lt;br /&gt;		fscanf(fin, "%d%d%d", &amp;u, &amp;v, &amp;w);&lt;br /&gt;		dist[u][v] = w;&lt;br /&gt;		n = MAX(u, MAX(v, n));&lt;br /&gt;	}&lt;br /&gt;	fclose(fin);&lt;br /&gt;&lt;br /&gt;	dijkstra(1);&lt;br /&gt;&lt;br /&gt;	printD();&lt;br /&gt;&lt;br /&gt;	return 0;&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Sat, 01 Dec 2007 19:41:53 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4832</guid>
      <author>scvalex (Alexandru Scvortov)</author>
    </item>
    <item>
      <title>Bellman-Ford Algorithm</title>
      <link>http://snippets.dzone.com/posts/show/4828</link>
      <description>This is a simple implementation of the &lt;a href="http://en.wikipedia.org/wiki/Bellman-ford"&gt;Bellman-Ford&lt;/a&gt; algorithm for finding the shortest path from a single source in a graph.&lt;br /&gt;&lt;br /&gt;A detailed explanation is given &lt;a href="http://compprog.wordpress.com/2007/11/29/one-source-shortest-path-the-bellman-ford-algorithm/"&gt;here&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;#include &lt;stdio.h&gt;&lt;br /&gt;&lt;br /&gt;typedef struct {&lt;br /&gt;	int u, v, w;&lt;br /&gt;} Edge;&lt;br /&gt;&lt;br /&gt;int n; /* the number of nodes */&lt;br /&gt;int e; /* the number of edges */&lt;br /&gt;Edge edges[1024]; /* large enough for n &lt;= 2^5=32 */&lt;br /&gt;int d[32]; /* d[i] is the minimum distance from node s to node i */&lt;br /&gt;&lt;br /&gt;#define INFINITY 10000&lt;br /&gt;&lt;br /&gt;void printDist() {&lt;br /&gt;	int i;&lt;br /&gt;&lt;br /&gt;	printf("Distances:\n");&lt;br /&gt;&lt;br /&gt;	for (i = 0; i &lt; n; ++i)&lt;br /&gt;		printf("to %d\t", i + 1);&lt;br /&gt;	printf("\n");&lt;br /&gt;&lt;br /&gt;	for (i = 0; i &lt; n; ++i)&lt;br /&gt;		printf("%d\t", d[i]);&lt;br /&gt;&lt;br /&gt;	printf("\n\n");&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;void bellman_ford(int s) {&lt;br /&gt;	int i, j;&lt;br /&gt;&lt;br /&gt;	for (i = 0; i &lt; n; ++i)&lt;br /&gt;		d[i] = INFINITY;&lt;br /&gt;&lt;br /&gt;	d[s] = 0;&lt;br /&gt;&lt;br /&gt;	for (i = 0; i &lt; n - 1; ++i)&lt;br /&gt;		for (j = 0; j &lt; e; ++j)&lt;br /&gt;			if (d[edges[j].u] + edges[j].w &lt; d[edges[j].v])&lt;br /&gt;				d[edges[j].v] = d[edges[j].u] + edges[j].w;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main(int argc, char *argv[]) {&lt;br /&gt;	int i, j;&lt;br /&gt;	int w;&lt;br /&gt;&lt;br /&gt;	FILE *fin = fopen("dist.txt", "r");&lt;br /&gt;	fscanf(fin, "%d", &amp;n);&lt;br /&gt;	e = 0;&lt;br /&gt;&lt;br /&gt;	for (i = 0; i &lt; n; ++i)&lt;br /&gt;		for (j = 0; j &lt; n; ++j) {&lt;br /&gt;			fscanf(fin, "%d", &amp;w);&lt;br /&gt;			if (w != 0) {&lt;br /&gt;				edges[e].u = i;&lt;br /&gt;				edges[e].v = j;&lt;br /&gt;				edges[e].w = w;&lt;br /&gt;				++e;&lt;br /&gt;			}&lt;br /&gt;		}&lt;br /&gt;	fclose(fin);&lt;br /&gt;&lt;br /&gt;	/* printDist(); */&lt;br /&gt;&lt;br /&gt;	bellman_ford(0);&lt;br /&gt;&lt;br /&gt;	printDist();&lt;br /&gt;&lt;br /&gt;	return 0;&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 29 Nov 2007 14:55:34 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4828</guid>
      <author>scvalex (Alexandru Scvortov)</author>
    </item>
    <item>
      <title>The 0-1 Knapsack Problem in C</title>
      <link>http://snippets.dzone.com/posts/show/4802</link>
      <description>This is a dynamic-programming algorithm implementation for solving the &lt;a href="http://en.wikipedia.org/wiki/Knapsack_problem"&gt;the 0-1 Knapsack Problem&lt;/a&gt; in C.&lt;br /&gt;&lt;br /&gt;Further explanation is given &lt;a href="http://compprog.wordpress.com/2007/11/20/the-0-1-knapsack-problem/"&gt;here&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;#include &lt;stdio.h&gt;&lt;br /&gt;&lt;br /&gt;#define MAXWEIGHT 100&lt;br /&gt;&lt;br /&gt;int n = 3; /* The number of objects */&lt;br /&gt;int c[10] = {8, 6, 4}; /* c[i] is the *COST* of the ith object; i.e. what&lt;br /&gt;				YOU PAY to take the object */&lt;br /&gt;int v[10] = {16, 10, 7}; /* v[i] is the *VALUE* of the ith object; i.e.&lt;br /&gt;				what YOU GET for taking the object */&lt;br /&gt;int W = 10; /* The maximum weight you can take */ &lt;br /&gt;&lt;br /&gt;void fill_sack() {&lt;br /&gt;	int a[MAXWEIGHT]; /* a[i] holds the maximum value that can be obtained&lt;br /&gt;				using at most i weight */&lt;br /&gt;	int last_added[MAXWEIGHT]; /* I use this to calculate which object were&lt;br /&gt;					added */&lt;br /&gt;	int i, j;&lt;br /&gt;	int aux;&lt;br /&gt;&lt;br /&gt;	for (i = 0; i &lt;= W; ++i) {&lt;br /&gt;		a[i] = 0;&lt;br /&gt;		last_added[i] = -1;&lt;br /&gt;	}&lt;br /&gt;&lt;br /&gt;	a[0] = 0;&lt;br /&gt;	for (i = 1; i &lt;= W; ++i)&lt;br /&gt;		for (j = 0; j &lt; n; ++j)&lt;br /&gt;			if ((c[j] &lt;= i) &amp;&amp; (a[i] &lt; a[i - c[j]] + v[j])) {&lt;br /&gt;				a[i] = a[i - c[j]] + v[j];&lt;br /&gt;				last_added[i] = j;&lt;br /&gt;			}&lt;br /&gt;&lt;br /&gt;	for (i = 0; i &lt;= W; ++i)&lt;br /&gt;		if (last_added[i] != -1)&lt;br /&gt;			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]]);&lt;br /&gt;		else&lt;br /&gt;			printf("Weight %d; Benefit: 0; Can't reach this exact weight.\n", i);&lt;br /&gt;&lt;br /&gt;	printf("---\n");&lt;br /&gt;&lt;br /&gt;	aux = W;&lt;br /&gt;	while ((aux &gt; 0) &amp;&amp; (last_added[aux] != -1)) {&lt;br /&gt;		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]]);&lt;br /&gt;		aux -= c[last_added[aux]];&lt;br /&gt;	}&lt;br /&gt;&lt;br /&gt;	printf("Total value added: %d$\n", a[W]);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main(int argc, char *argv[]) {&lt;br /&gt;	fill_sack();&lt;br /&gt;&lt;br /&gt;	return 0;&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Tue, 20 Nov 2007 17:17:50 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4802</guid>
      <author>scvalex (Alexandru Scvortov)</author>
    </item>
    <item>
      <title>The Fractional Knapsack Problem in C</title>
      <link>http://snippets.dzone.com/posts/show/4800</link>
      <description>This is the classic Greedy algorithm implementation for solving the &lt;a href="http://en.wikipedia.org/wiki/Knapsack_problem"&gt;Fractional Knapsack Problem&lt;/a&gt; in C.&lt;br /&gt;&lt;br /&gt;Further explanations &lt;a href="http://compprog.wordpress.com/2007/11/20/the-fractional-knapsack-problem/"&gt;here&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;#include &lt;stdio.h&gt;&lt;br /&gt;&lt;br /&gt;int n = 5; /* The number of objects */&lt;br /&gt;int c[10] = {12, 1, 2, 1, 4}; /* c[i] is the *COST* of the ith object; i.e. what&lt;br /&gt;				YOU PAY to take the object */&lt;br /&gt;int v[10] = {4, 2, 2, 1, 10}; /* v[i] is the *VALUE* of the ith object; i.e.&lt;br /&gt;				what YOU GET for taking the object */&lt;br /&gt;int W = 15; /* The maximum weight you can take */&lt;br /&gt;&lt;br /&gt;void simple_fill() {&lt;br /&gt;	int cur_w;&lt;br /&gt;	float tot_v;&lt;br /&gt;	int i, maxi;&lt;br /&gt;	int used[10];&lt;br /&gt;&lt;br /&gt;	for (i = 0; i &lt; n; ++i)&lt;br /&gt;		used[i] = 0; /* I have not used the ith object yet */&lt;br /&gt;&lt;br /&gt;	cur_w = W;&lt;br /&gt;	while (cur_w &gt; 0) { /* while there's still room*/&lt;br /&gt;		/* Find the best object */&lt;br /&gt;		maxi = -1;&lt;br /&gt;		for (i = 0; i &lt; n; ++i)&lt;br /&gt;			if ((used[i] == 0) &amp;&amp;&lt;br /&gt;				((maxi == -1) || ((float)v[i]/c[i] &gt; (float)v[maxi]/c[maxi])))&lt;br /&gt;				maxi = i;&lt;br /&gt;&lt;br /&gt;		used[maxi] = 1; /* mark the maxi-th object as used */&lt;br /&gt;		cur_w -= c[maxi]; /* with the object in the bag, I can carry less */&lt;br /&gt;		tot_v += v[maxi];&lt;br /&gt;		if (cur_w &gt;= 0)&lt;br /&gt;			printf("Added object %d (%d$, %dKg) completly in the bag. Space left: %d.\n", maxi + 1, v[maxi], c[maxi], cur_w);&lt;br /&gt;		else {&lt;br /&gt;			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);&lt;br /&gt;			tot_v -= v[maxi];&lt;br /&gt;			tot_v += (1 + (float)cur_w/c[maxi]) * v[maxi];&lt;br /&gt;		}&lt;br /&gt;	}&lt;br /&gt;&lt;br /&gt;	printf("Filled the bag with objects worth %.2f$.\n", tot_v);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main(int argc, char *argv[]) {&lt;br /&gt;	simple_fill();&lt;br /&gt;&lt;br /&gt;	return 0;&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Tue, 20 Nov 2007 13:39:13 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4800</guid>
      <author>scvalex (Alexandru Scvortov)</author>
    </item>
    <item>
      <title>All Sources Shortest Path: The Floyd-Warshall Algorithm</title>
      <link>http://snippets.dzone.com/posts/show/4759</link>
      <description>This is a straightforward implementation of the &lt;a href="http://en.wikipedia.org/wiki/Floyd-Warshall_algorithm"&gt;Floyd-Warshall algorithm&lt;/a&gt; for finding the shortest path between all nodes of a graph.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;A more detailed explanation is given &lt;a href="http://compprog.wordpress.com/2007/11/15/all-sources-shortest-path-the-floyd-warshall-algorithm/"&gt;here&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;#include &lt;stdio.h&gt;&lt;br /&gt;&lt;br /&gt;int n; /* Then number of nodes */&lt;br /&gt;int dist[16][16]; /* dist[i][j] is the length of the edge between i and j if&lt;br /&gt;			it exists, or 0 if it does not */&lt;br /&gt;&lt;br /&gt;void printDist() {&lt;br /&gt;	int i, j;&lt;br /&gt;	printf("    ");&lt;br /&gt;	for (i = 0; i &lt; n; ++i)&lt;br /&gt;		printf("%4c", 'A' + i);&lt;br /&gt;	printf("\n");&lt;br /&gt;	for (i = 0; i &lt; n; ++i) {&lt;br /&gt;		printf("%4c", 'A' + i);&lt;br /&gt;		for (j = 0; j &lt; n; ++j)&lt;br /&gt;			printf("%4d", dist[i][j]);&lt;br /&gt;		printf("\n");&lt;br /&gt;	}&lt;br /&gt;	printf("\n");&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;/*&lt;br /&gt;	floyd_warshall()&lt;br /&gt;&lt;br /&gt;	after calling this function dist[i][j] will the the minimum distance&lt;br /&gt;	between i and j if it exists (i.e. if there's a path between i and j)&lt;br /&gt;	or 0, otherwise&lt;br /&gt;*/&lt;br /&gt;void floyd_warshall() {&lt;br /&gt;	int i, j, k;&lt;br /&gt;	for (k = 0; k &lt; n; ++k) {&lt;br /&gt;		printDist();&lt;br /&gt;		for (i = 0; i &lt; n; ++i)&lt;br /&gt;			for (j = 0; j &lt; n; ++j)&lt;br /&gt;				/* If i and j are different nodes and if &lt;br /&gt;					the paths between i and k and between&lt;br /&gt;					k and j exist, do */&lt;br /&gt;				if ((dist[i][k] * dist[k][j] != 0) &amp;&amp; (i != j))&lt;br /&gt;					/* See if you can't get a shorter path&lt;br /&gt;						between i and j by interspacing&lt;br /&gt;						k somewhere along the current&lt;br /&gt;						path */&lt;br /&gt;					if ((dist[i][k] + dist[k][j] &lt; dist[i][j]) ||&lt;br /&gt;						(dist[i][j] == 0))&lt;br /&gt;						dist[i][j] = dist[i][k] + dist[k][j];&lt;br /&gt;	}&lt;br /&gt;	printDist();&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main(int argc, char *argv[]) {&lt;br /&gt;	FILE *fin = fopen("dist.txt", "r");&lt;br /&gt;	fscanf(fin, "%d", &amp;n);&lt;br /&gt;	int i, j;&lt;br /&gt;	for (i = 0; i &lt; n; ++i)&lt;br /&gt;		for (j = 0; j &lt; n; ++j)&lt;br /&gt;			fscanf(fin, "%d", &amp;dist[i][j]);&lt;br /&gt;	fclose(fin);&lt;br /&gt;&lt;br /&gt;	floyd_warshall();&lt;br /&gt;&lt;br /&gt;	return 0;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 15 Nov 2007 16:19:25 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4759</guid>
      <author>scvalex (Alexandru Scvortov)</author>
    </item>
    <item>
      <title>Prim's Algorithm for Finding Minimum Spanning Trees in C</title>
      <link>http://snippets.dzone.com/posts/show/4743</link>
      <description>The is a straight-forward implementation of Prim's Algorithm for finding the minimum spanning tree of a graph.&lt;br /&gt;&lt;br /&gt;A detailed explanation is given &lt;a href="http://compprog.wordpress.com/2007/11/09/minimal-spanning-trees-prims-algorithm/"&gt;here&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;#include &lt;stdio.h&gt;&lt;br /&gt;&lt;br /&gt;/*&lt;br /&gt;	The input file (weight.txt) look something like this&lt;br /&gt;		4&lt;br /&gt;		0 0 0 21&lt;br /&gt;		0 0 8 17&lt;br /&gt;		0 8 0 16&lt;br /&gt;		21 17 16 0&lt;br /&gt;&lt;br /&gt;	The first line contains n, the number of nodes.&lt;br /&gt;	Next is an nxn matrix containg the distances between the nodes&lt;br /&gt;	NOTE: The distance between a node and itself should be 0&lt;br /&gt;*/&lt;br /&gt;&lt;br /&gt;int n; /* The number of nodes in the graph */&lt;br /&gt;&lt;br /&gt;int weight[100][100]; /* weight[i][j] is the distance between node i and node j;&lt;br /&gt;			if there is no path between i and j, weight[i][j] should&lt;br /&gt;			be 0 */&lt;br /&gt;&lt;br /&gt;char inTree[100]; /* inTree[i] is 1 if the node i is already in the minimum&lt;br /&gt;			spanning tree; 0 otherwise*/&lt;br /&gt;&lt;br /&gt;int d[100]; /* d[i] is the distance between node i and the minimum spanning&lt;br /&gt;		tree; this is initially infinity (100000); if i is already in&lt;br /&gt;		the tree, then d[i] is undefined;&lt;br /&gt;		this is just a temporary variable. It's not necessary but speeds&lt;br /&gt;		up execution considerably (by a factor of n) */&lt;br /&gt;&lt;br /&gt;int whoTo[100]; /* whoTo[i] holds the index of the node i would have to be&lt;br /&gt;			linked to in order to get a distance of d[i] */&lt;br /&gt;&lt;br /&gt;/* updateDistances(int target)&lt;br /&gt;	should be called immediately after target is added to the tree;&lt;br /&gt;	updates d so that the values are correct (goes through target's&lt;br /&gt;	neighbours making sure that the distances between them and the tree&lt;br /&gt;	are indeed minimum)&lt;br /&gt;*/&lt;br /&gt;void updateDistances(int target) {&lt;br /&gt;	int i;&lt;br /&gt;	for (i = 0; i &lt; n; ++i)&lt;br /&gt;		if ((weight[target][i] != 0) &amp;&amp; (d[i] &gt; weight[target][i])) {&lt;br /&gt;			d[i] = weight[target][i];&lt;br /&gt;			whoTo[i] = target;&lt;br /&gt;		}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main(int argc, char *argv[]) {&lt;br /&gt;	FILE *f = fopen("dist.txt", "r");&lt;br /&gt;	fscanf(f, "%d", &amp;n);&lt;br /&gt;	int i, j;&lt;br /&gt;	for (i = 0; i &lt; n; ++i)&lt;br /&gt;		for (j = 0; j &lt; n; ++j)&lt;br /&gt;			fscanf(f, "%d", &amp;weight[i][j]);&lt;br /&gt;	fclose(f);&lt;br /&gt;&lt;br /&gt;	/* Initialise d with infinity */&lt;br /&gt;	for (i = 0; i &lt; n; ++i)&lt;br /&gt;		d[i] = 100000;&lt;br /&gt;&lt;br /&gt;	/* Mark all nodes as NOT beeing in the minimum spanning tree */&lt;br /&gt;	for (i = 0; i &lt; n; ++i)&lt;br /&gt;		inTree[i] = 0;&lt;br /&gt;&lt;br /&gt;	/* Add the first node to the tree */&lt;br /&gt;	printf("Adding node %c\n", 0 + 'A');&lt;br /&gt;	inTree[0] = 1;&lt;br /&gt;	updateDistances(0);&lt;br /&gt;&lt;br /&gt;	int total = 0;&lt;br /&gt;	int treeSize;&lt;br /&gt;	for (treeSize = 1; treeSize &lt; n; ++treeSize) {&lt;br /&gt;		/* Find the node with the smallest distance to the tree */&lt;br /&gt;		int min = -1;&lt;br /&gt;		for (i = 0; i &lt; n; ++i)&lt;br /&gt;			if (!inTree[i])&lt;br /&gt;				if ((min == -1) || (d[min] &gt; d[i]))&lt;br /&gt;					min = i;&lt;br /&gt;&lt;br /&gt;		/* And add it */&lt;br /&gt;		printf("Adding edge %c-%c\n", whoTo[min] + 'A', min + 'A');&lt;br /&gt;		inTree[min] = 1;&lt;br /&gt;		total += d[min];&lt;br /&gt;&lt;br /&gt;		updateDistances(min);&lt;br /&gt;	}&lt;br /&gt;&lt;br /&gt;	printf("Total distance: %d\n", total);&lt;br /&gt;&lt;br /&gt;	return 0;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Fri, 09 Nov 2007 12:31:11 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4743</guid>
      <author>scvalex (Alexandru Scvortov)</author>
    </item>
  </channel>
</rss>
