Largest proper divisor of n

a(1) = 1; for n > 1, a(n) = '''largest''' proper divisor of n, where '''n < 101 '''.

Solution:
#include <stdio.h>

unsigned int lpd(unsigned int n) {
    if (n<=1) return 1;
    int i;
    for (i=n-1; i>0; i--)
        if (n%i == 0) return i;
}

int main() {
    int i;
    for (i=1; i<=100; i++) {
        printf("%3d", lpd(i));
        if (i % 10 == 0) printf("\n");
    }
    return 0;
}


Last Friday of each month

Write a program or a script that returns the date of the last Fridays of each month of a given year.

The year may be given through any simple input method in your language (command line, std in, etc).

Example of an expected output:
./last_fridays 2012
2012-01-27
2012-02-24
2012-03-30
2012-04-27
2012-05-25
2012-06-29
2012-07-27
2012-08-31
2012-09-28
2012-10-26
2012-11-30
2012-12-28

;Related tasks
* [[Five weekends]]
* [[Day of the week]]
* [[Find the last Sunday of each month]]

Solution:
#include <stdio.h>
#include <stdlib.h>

int main(int c, char *v[])
{
	int days[] = {31,29,31,30,31,30,31,31,30,31,30,31};
	int m, y, w;

	if (c < 2 || (y = atoi(v[1])) <= 1700) return 1;
 	days[1] -= (y % 4) || (!(y % 100) && (y % 400));
	w = y * 365 + (y - 1) / 4 - (y - 1) / 100 + (y - 1) / 400 + 6;

	for(m = 0; m < 12; m++) {
		w = (w + days[m]) % 7;
		printf("%d-%02d-%d\n", y, m + 1,
			days[m] + (w < 5 ? -2 : 5) - w);
	}

	return 0;
}


Last letter-first letter

A certain children's game involves starting with a word in a particular category.   Each participant in turn says a word, but that word must begin with the final letter of the previous word.   Once a word has been given, it cannot be repeated.   If an opponent cannot give a word in the category, they fall out of the game.

For example, with   "animals"   as the category,

Child 1: dog
Child 2: goldfish
Child 1: hippopotamus
Child 2: snake
...

;Task:
Take the following selection of 70 English Pokemon names   (extracted from   Wikipedia's list of Pokemon)   and generate the/a sequence with the highest possible number of Pokemon names where the subsequent name starts with the final letter of the preceding name.

No Pokemon name is to be repeated.

audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon
cresselia croagunk darmanitan deino emboar emolga exeggcute gabite
girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan
kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine
nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2
porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking
sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko
tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask

Extra brownie points for dealing with the full list of   646   names.

Solution:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define forall(i, n) for (int i = 0; i < n; i++)
typedef struct edge { char s, e, *str; struct edge *lnk; } edge;
typedef struct { edge* e[26]; int nin, nout, in[26], out[26];} node;
typedef struct { edge *e, *tail; int len, has[26]; } chain;

node nodes[26];
edge *names, **tmp;
int n_names;

/* add edge to graph */
void store_edge(edge *g)
{
	if (!g) return;
	int i = g->e, j = g->s;
	node *n = nodes + j;

	g->lnk = n->e[i];

	n->e[i] = g, n->out[i]++, n->nout++;
	n = nodes + i, n->in[j]++, n->nin++;
}

/* unlink an edge between nodes i and j, and return the edge */
edge* remove_edge(int i, int j)
{
	node *n = nodes + i;
	edge *g = n->e[j];
	if (g) {
		n->e[j] = g->lnk;
		g->lnk = 0;
		n->out[j]--, n->nout--;

		n = nodes + j;
		n->in[i]--;
		n->nin--;
	}
	return g;
}

void read_names()
{
	FILE *fp = fopen("poke646", "rt");
	int i, len;
	char *buf;
	edge *p;

	if (!fp) abort();

	fseek(fp, 0, SEEK_END);
	len = ftell(fp);
	buf = malloc(len + 1);
	fseek(fp, 0, SEEK_SET);
	fread(buf, 1, len, fp);
	fclose(fp);

	buf[len] = 0;
	for (n_names = i = 0; i < len; i++)
		if (isspace(buf[i]))
			buf[i] = 0, n_names++;

	if (buf[len-1]) n_names++;

	memset(nodes, 0, sizeof(node) * 26);
	tmp = calloc(n_names, sizeof(edge*));

	p = names = malloc(sizeof(edge) * n_names);
	for (i = 0; i < n_names; i++, p++) {
		if (i)	p->str = names[i-1].str + len + 1;
		else	p->str = buf;

		len = strlen(p->str);
		p->s = p->str[0] - 'a';
		p->e = p->str[len-1] - 'a';
		if (p->s < 0 || p->s >= 26 || p->e < 0 || p->e >= 26) {
			printf("bad name %s: first/last char must be letter\n",
				p->str);
			abort();
		}
	}
	printf("read %d names\n", n_names);
}

void show_chain(chain *c)
{
	printf("%d:", c->len);
	for (edge * e = c->e; e || !putchar('\n'); e = e->lnk)
		printf(" %s", e->str);
}

/* Which next node has most enter or exit edges. */
int widest(int n, int out)
{
	if (nodes[n].out[n]) return n;

	int mm = -1, mi = -1;
	forall(i, 26) {
		if (out) {
			if (nodes[n].out[i] && nodes[i].nout > mm)
				mi = i, mm = nodes[i].nout;
		} else {
			if (nodes[i].out[n] && nodes[i].nin > mm)
				mi = i, mm = nodes[i].nin;
		}
	}

	return mi;
}

void insert(chain *c, edge *e)
{
	e->lnk = c->e;
	if (!c->tail) c->tail = e;
	c->e = e;
	c->len++;
}

void append(chain *c, edge *e)
{
	if (c->tail) c->tail->lnk = e;
	else c->e = e;
	c->tail = e;
	c->len++;
}

edge * shift(chain *c)
{
	edge *e = c->e;
	if (e) {
		c->e = e->lnk;
		if (!--c->len) c->tail = 0;
	}
	return e;
}

chain* make_chain(int s)
{
	chain *c = calloc(1, sizeof(chain));

	/* extend backwards */
	for (int i, j = s; (i = widest(j, 0)) >= 0; j = i)
		insert(c, remove_edge(i, j));

	/* extend forwards */
	for (int i, j = s; (i = widest(j, 1)) >= 0; j = i)
		append(c, remove_edge(j, i));

	for (int step = 0;; step++) {
		edge *e = c->e;

		for (int i = 0; i < step; i++)
			if (!(e = e->lnk)) break;
		if (!e) return c;

		int n = 0;
		for (int i, j = e->s; (i = widest(j, 0)) >= 0; j = i) {
			if (!(e = remove_edge(i, j))) break;
			tmp[n++] = e;
		}

		if (n > step) {
			forall(i, step) store_edge(shift(c));
			forall(i, n) insert(c, tmp[i]);
			step = -1;
		} else while (--n >= 0)
			store_edge(tmp[n]);
	}
	return c;
}

int main(void)
{
	int best = 0;
	read_names();

	forall(i, 26) {
		/* rebuild the graph */
		memset(nodes, 0, sizeof(nodes));
		forall(j, n_names) store_edge(names + j);

		/* make a chain from node i */
		chain *c = make_chain(i);
		if (c->len > best) {
			show_chain(c);
			best = c->len;
		}
		free(c);
	}

	printf("longest found: %d\n", best);
	return 0;
}


Law of cosines - triples

The Law of cosines states that for an angle g, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula:
           A2 + B2 - 2ABcos(g) = C2

;Specific angles:
For an angle of of   '''90o'''   this becomes the more familiar "Pythagoras equation":
           A2 + B2  =  C2

For an angle of   '''60o'''   this becomes the less familiar  equation:
           A2 + B2 - AB  =  C2

And finally for an angle of   '''120o'''   this becomes the equation:
           A2 + B2 + AB  =  C2

;Task:
*   Find all integer solutions (in order) to the three specific cases, distinguishing between each angle being considered.
*   Restrain all sides to the integers   '''1..13'''   inclusive.
*   Show how many results there are for each of the three angles mentioned above.
*   Display results on this page.

Note: Triangles with the same length sides but different order are to be treated as the same.

;Optional Extra credit:
* How many 60deg integer triples are there for sides in the range 1..10_000 ''where the sides are not all of the same length''.

;Related Task
* [[Pythagorean triples]]

;See also:
* Visualising Pythagoras: ultimate proofs and crazy contortions Mathlogger Video

Solution:
/*
 * RossetaCode: Law of cosines - triples
 *
 * An quick and dirty brute force solutions with O(N^3) cost.
 * Anyway it is possible set MAX_SIDE_LENGTH equal to 10000
 * and use fast computer to obtain the "extra credit" badge.
 *
 * Obviously, there are better algorithms.
 */

#include <stdio.h>
#include <math.h>

#define MAX_SIDE_LENGTH 13
//#define DISPLAY_TRIANGLES 1

int main(void)
{
    static char description[3][80] = {
        "gamma =  90 degrees,  a*a + b*b       == c*c",
        "gamma =  60 degrees,  a*a + b*b - a*b == c*c",
        "gamma = 120 degrees,  a*a + b*b + a*b == c*c"
    };
    static int coeff[3] = { 0, 1, -1 };

    for (int k = 0; k < 3; k++)
    {
        int counter = 0;
        for (int a = 1; a <= MAX_SIDE_LENGTH; a++)
            for (int b = 1; b <= a; b++)
                for (int c = 1; c <= MAX_SIDE_LENGTH; c++)
                    if (a * a + b * b - coeff[k] * a * b == c * c)
                    {
                        counter++;
#ifdef DISPLAY_TRIANGLES
                        printf("  %d  %d  %d\n", a, b, c);
#endif
                    }
        printf("%s,  number of triangles = %d\n", description[k], counter);
    }

    return 0;
}


Least common multiple

Compute the   least common multiple   (LCM)   of two integers.

Given   ''m''   and   ''n'',   the least common multiple is the smallest positive integer that has both   ''m''   and   ''n''   as factors.

;Example:
The least common multiple of   '''12'''   and   '''18'''   is   '''36''',       because:
:*   '''12'''   is a factor     ('''12''' x '''3''' = '''36'''),     and
:*   '''18'''   is a factor     ('''18''' x '''2''' = '''36'''),     and
:*   there is no positive integer less than   '''36'''   that has both factors.

As a special case,   if either   ''m''   or   ''n''   is zero,   then the least common multiple is zero.

One way to calculate the least common multiple is to iterate all the multiples of   ''m'',   until you find one that is also a multiple of   ''n''.

If you already have   ''gcd''   for [[greatest common divisor]],   then this formula calculates   ''lcm''.

:::: \operatorname{lcm}(m, n) = \frac{|m \times n|}{\operatorname{gcd}(m, n)}

One can also find   ''lcm''   by merging the [[prime decomposition]]s of both   ''m''   and   ''n''.

;Related task
:*   greatest common divisor.

;See also:
*   MathWorld entry:   Least Common Multiple.
*   Wikipedia entry:   Least common multiple.

Solution:
#include <stdio.h>

int gcd(int m, int n)
{
        int tmp;
        while(m) { tmp = m; m = n % m; n = tmp; }
        return n;
}

int lcm(int m, int n)
{
        return m / gcd(m, n) * n;
}

int main()
{
        printf("lcm(35, 21) = %d\n", lcm(21,35));
        return 0;
}


Levenshtein distance

{{Wikipedia}}

In information theory and computer science, the '''Levenshtein distance''' is a edit distance). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character.

;Example:
The Levenshtein distance between "'''kitten'''" and "'''sitting'''" is 3, since the following three edits change one into the other, and there isn't a way to do it with fewer than three edits:
::#   '''k'''itten    '''s'''itten       (substitution of 'k' with 's')
::#   sitt'''e'''n    sitt'''i'''n       (substitution of 'e' with 'i')
::#   sittin          sittin'''g'''      (insert 'g' at the end).

''The Levenshtein distance between   "'''rosettacode'''",   "'''raisethysword'''"   is   '''8'''.

''The distance between two strings is same as that when both strings are reversed.''

;Task:
Implements a Levenshtein distance function, or uses a library function, to show the Levenshtein distance between   "kitten"   and   "sitting".

;Related task:
*   [[Longest common subsequence]]

Solution:
#include <stdio.h>
#include <string.h>

/* s, t: two strings; ls, lt: their respective length */
int levenshtein(const char *s, int ls, const char *t, int lt)
{
        int a, b, c;

        /* if either string is empty, difference is inserting all chars
         * from the other
         */
        if (!ls) return lt;
        if (!lt) return ls;

        /* if last letters are the same, the difference is whatever is
         * required to edit the rest of the strings
         */
        if (s[ls - 1] == t[lt - 1])
                return levenshtein(s, ls - 1, t, lt - 1);

        /* else try:
         *      changing last letter of s to that of t; or
         *      remove last letter of s; or
         *      remove last letter of t,
         * any of which is 1 edit plus editing the rest of the strings
         */
        a = levenshtein(s, ls - 1, t, lt - 1);
        b = levenshtein(s, ls,     t, lt - 1);
        c = levenshtein(s, ls - 1, t, lt    );

        if (a > b) a = b;
        if (a > c) a = c;

        return a + 1;
}

int main()
{
        const char *s1 = "rosettacode";
        const char *s2 = "raisethysword";
        printf("distance between `%s' and `%s': %d\n", s1, s2,
                levenshtein(s1, strlen(s1), s2, strlen(s2)));

        return 0;
}


Levenshtein distance/Alignment

The [[Levenshtein distance]] algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order.

An alignment is a notation used to describe the operations used to turn a string into an other.  At some point in the strings, the minus character ('-') is placed in order to signify that a character must be added at this very place.  For instance, an alignment between the words 'place' and 'palace' is:

P-LACE
PALACE

;Task:
Write a function that shows the alignment of two strings for the corresponding levenshtein distance.

As an example, use the words "rosettacode" and "raisethysword".

You can either implement an algorithm, or use a dedicated library (thus showing us how it is named in your language).

Solution:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct edit_s edit_t, *edit;
struct edit_s {
	char c1, c2;
	int n;
	edit next;
};

void leven(char *a, char *b)
{
	int i, j, la = strlen(a), lb = strlen(b);
	edit *tbl = malloc(sizeof(edit) * (1 + la));
	tbl[0] = calloc((1 + la) * (1 + lb), sizeof(edit_t));
	for (i = 1; i <= la; i++)
		tbl[i] = tbl[i-1] + (1+lb);

	for (i = la; i >= 0; i--) {
		char *aa = a + i;
		for (j = lb; j >= 0; j--) {
			char *bb = b + j;
			if (!*aa && !*bb) continue;

			edit e = &tbl[i][j];
			edit repl = &tbl[i+1][j+1];
			edit dela = &tbl[i+1][j];
			edit delb = &tbl[i][j+1];

			e->c1 = *aa;
			e->c2 = *bb;
			if (!*aa) {
				e->next = delb;
				e->n = e->next->n + 1;
				continue;
			}
			if (!*bb) {
				e->next = dela;
				e->n = e->next->n + 1;
				continue;
			}

			e->next = repl;
			if (*aa == *bb) {
				e->n = e->next->n;
				continue;
			}

			if (e->next->n > delb->n) {
				e->next = delb;
				e->c1 = 0;
			}
			if (e->next->n > dela->n) {
				e->next = dela;
				e->c1 = *aa;
				e->c2 = 0;
			}
			e->n = e->next->n + 1;
		}
	}

	edit p = tbl[0];
	printf("%s -> %s: %d edits\n", a, b, p->n);

	while (p->next) {
		if (p->c1 == p->c2)
			printf("%c", p->c1);
		else {
			putchar('(');
			if (p->c1) putchar(p->c1);
			putchar(',');
			if (p->c2) putchar(p->c2);
			putchar(')');
		}

		p = p->next;
	}
	putchar('\n');

	free(tbl[0]);
	free(tbl);
}

int main(void)
{
	leven("raisethysword", "rosettacode");
	return 0;
}


List rooted trees

You came back from grocery shopping.    After putting away all the goods, you are left with a pile of plastic bags, which you want to save for later use, so you take one bag and stuff all the others into it, and throw it under the sink.   In doing so, you realize that there are various ways of nesting the bags, with all bags viewed as identical.

If we use a matching pair of parentheses to represent a bag, the ways are:

For 1 bag, there's one way:
  ()	<- a bag

for 2 bags, there's one way:
  (())	<- one bag in another

for 3 bags, there are two:
  ((())) <- 3 bags nested Russian doll style
  (()()) <- 2 bags side by side, inside the third

for 4 bags, four:
  (()()())
  ((())())
  ((()()))
  (((())))

Note that because all bags are identical, the two 4-bag strings ((())()) and (()(())) represent the same configuration.

It's easy to see that each configuration for ''n'' bags represents a ''n''-node rooted tree, where a bag is a tree node, and a bag with its content forms a subtree.  The outermost bag is the tree root.  Number of configurations for given ''n'' is given by OEIS A81.

;Task:
Write a program that, when given ''n'', enumerates all ways of nesting ''n'' bags.   You can use the parentheses notation above, or any tree representation that's unambiguous and preferably intuitive.

This task asks for enumeration of trees only; for counting solutions without enumeration, that OEIS page lists various formulas, but that's not encouraged by this task, especially if implementing it would significantly increase code size.

As an example output, run 5 bags.   There should be 9 ways.

Solution:
#include <stdio.h>
#include <stdlib.h>

typedef unsigned int uint;
typedef unsigned long long tree;
#define B(x) (1ULL<<(x))

tree *list = 0;
uint cap = 0, len = 0;
uint offset[32] = {0, 1, 0};

void append(tree t)
{
	if (len == cap) {
		cap = cap ? cap*2 : 2;
		list = realloc(list, cap*sizeof(tree));
	}
	list[len++] = 1 | t<<1;
}

void show(tree t, uint len)
{
	for (; len--; t >>= 1)
		putchar(t&1 ? '(' : ')');
}

void listtrees(uint n)
{
	uint i;
	for (i = offset[n]; i < offset[n+1]; i++) {
		show(list[i], n*2);
		putchar('\n');
	}
}

/* assemble tree from subtrees
	n:   length of tree we want to make
	t:   assembled parts so far
	sl:  length of subtree we are looking at
	pos: offset of subtree we are looking at
	rem: remaining length to be put together
*/
void assemble(uint n, tree t, uint sl, uint pos, uint rem)
{
	if (!rem) {
		append(t);
		return;
	}

	if (sl > rem) // need smaller subtrees
		pos = offset[sl = rem];
	else if (pos >= offset[sl + 1]) {
		// used up sl-trees, try smaller ones
		if (!--sl) return;
		pos = offset[sl];
	}

	assemble(n, t<<(2*sl) | list[pos], sl, pos, rem - sl);
	assemble(n, t, sl, pos + 1, rem);
}

void mktrees(uint n)
{
	if (offset[n + 1]) return;
	if (n) mktrees(n - 1);

	assemble(n, 0, n-1, offset[n-1], n-1);
	offset[n+1] = len;
}

int main(int c, char**v)
{
	int n;
	if (c < 2 || (n = atoi(v[1])) <= 0 || n > 25) n = 5;

	// init 1-tree
	append(0);

	mktrees((uint)n);
	fprintf(stderr, "Number of %d-trees: %u\n", n, offset[n+1] - offset[n]);
	listtrees((uint)n);

	return 0;
}


Long year

Most years have 52 weeks, some have 53, according to ISO8601.

;Task:
Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.

Solution:
#include <stdio.h>
#include <math.h>

// https://webspace.science.uu.nl/~gent0113/calendar/isocalendar.htm

int p(int year) {
	return (int)((double)year + floor(year/4) - floor(year/100) + floor(year/400)) % 7;
}

int is_long_year(int year) {
	return p(year) == 4 || p(year - 1) == 3;
}

void print_long_years(int from, int to) {
	for (int year = from; year <= to; ++year) {
		if (is_long_year(year)) {
			printf("%d ", year);
		}
	}
}

int main() {

	printf("Long (53 week) years between 1800 and 2100\n\n");
	print_long_years(1800, 2100);
	printf("\n");
	return 0;
}


Longest common subsequence

'''Introduction'''

Define a ''subsequence'' to be any output string obtained by deleting zero or more symbols from an input string.

The '''Longest Common Subsequence''' ('''LCS''') is a subsequence of maximum length common to two or more strings.

Let ''A''  ''A''[0]... ''A''[m - 1] and ''B''  ''B''[0]... ''B''[n - 1], m < n be strings drawn from an alphabet S of size s, containing every distinct symbol in A + B.

An ordered pair (i, j) will be referred to as a match if ''A''[i] = ''B''[j], where 0 <= i < m and 0 <= j < n.

The set of matches '''M''' defines a relation over matches: '''M'''[i, j] = (i, j)  '''M'''.

Define a ''non-strict'' product-order (<=) over ordered pairs, such that (i1, j1) <= (i2, j2) = i1 <= i2 and j1 <= j2.  We define (>=) similarly.

We say ordered pairs p1 and p2 are ''comparable'' if either p1 <= p2 or p1 >= p2 holds.  If i1 < i2 and j2 < j1 (or i2 < i1 and j1 < j2) then neither p1 <= p2 nor p1 >= p2 are possible, and we say p1 and p2 are ''incomparable''.

Define the ''strict'' product-order (<) over ordered pairs, such that (i1, j1) < (i2, j2) = i1 < i2 and j1 < j2.  We define (>) similarly.

A chain '''C''' is a subset of '''M''' consisting of at least one element m; and where either m1 < m2 or m1 > m2 for every pair of distinct elements m1 and m2.  An antichain '''D''' is any subset of '''M''' in which every pair of distinct elements m1 and m2 are incomparable.

A chain can be visualized as a strictly increasing curve that passes through matches (i, j) in the m*n coordinate space of '''M'''[i, j].

Every Common Sequence of length ''q'' corresponds to a chain of cardinality ''q'', over the set of matches '''M'''.  Thus, finding an LCS can be restated as the problem of finding a chain of maximum cardinality ''p''.

According to [Dilworth 1950], this cardinality ''p'' equals the minimum number of disjoint antichains into which '''M''' can be decomposed.  Note that such a decomposition into the minimal number p of disjoint antichains may not be unique.

'''Background'''

Where the number of symbols appearing in matches is small relative to the length of the input strings, reuse of the symbols increases; and the number of matches will tend towards O(''m*n'') quadratic growth.  This occurs, for example, in the Bioinformatics application of nucleotide and protein sequencing.

The divide-and-conquer approach of [Hirschberg 1975] limits the space required to O(''n'').  However, this approach requires O(''m*n'') time even in the best case.

This quadratic time dependency may become prohibitive, given very long input strings.  Thus, heuristics are often favored over optimal Dynamic Programming solutions.

In the application of comparing file revisions, records from the input files form a large symbol space; and the number of symbols approaches the length of the LCS.  In this case the number of matches reduces to linear, O(''n'') growth.

A binary search optimization due to [Hunt and Szymanski 1977] can be applied to the basic Dynamic Programming approach, resulting in an expected performance of O(''n log m'').  Performance can degrade to O(''m*n log m'') time in the worst case, as the number of matches grows to O(''m*n'').

'''Note'''

[Rick 2000] describes a linear-space algorithm with a time bound of O(''n*s + p*min(m, n - p)'').

'''Legend'''

 A, B are input strings of lengths m, n respectively
 p is the length of the LCS
 M is the set of matches (i, j) such that A[i] = B[j]
 r is the magnitude of M
 s is the magnitude of the alphabet S of distinct symbols in A + B

'''References'''

[Dilworth 1950] "A decomposition theorem for partially ordered sets"
by Robert P. Dilworth, published January 1950,
Annals of Mathematics [Volume 51, Number 1, ''pp.'' 161-166]

[Goeman and Clausen 2002] "A New Practical Linear Space Algorithm for the Longest Common
Subsequence Problem" by Heiko Goeman and Michael Clausen,
published 2002, Kybernetika [Volume 38, Issue 1, ''pp.'' 45-66]

[Hirschberg 1975] "A linear space algorithm for computing maximal common subsequences"
by Daniel S. Hirschberg, published June 1975
Communications of the ACM [Volume 18, Number 6, ''pp.'' 341-343]

[Hunt and McIlroy 1976] "An Algorithm for Differential File Comparison"
by James W. Hunt and M. Douglas McIlroy, June 1976
Computing Science Technical Report, Bell Laboratories 41

[Hunt and Szymanski 1977] "A Fast Algorithm for Computing Longest Common Subsequences"
by James W. Hunt and Thomas G. Szymanski, published May 1977
Communications of the ACM [Volume 20, Number 5, ''pp.'' 350-353]

[Rick 2000] "Simple and fast linear space computation of longest common subsequences"
by Claus Rick, received 17 March 2000, Information Processing Letters,
Elsevier Science [Volume 75, ''pp.'' 275-281]

'''Examples'''

The sequences "1234" and "1224533324" have an LCS of "1234":
 '''1234'''
 '''12'''245'''3'''332'''4'''

For a string example, consider the sequences "thisisatest" and "testing123testing". An LCS would be "tsitest":
 '''t'''hi'''si'''sa'''test'''
 '''t'''e'''s'''t'''i'''ng123'''test'''ing

In this puzzle, your code only needs to deal with strings. Write a function which returns an LCS of two strings (case-sensitive). You don't need to show multiple LCS's.

For more information on this problem please see Wikipedia.

Solution:
#include <stdio.h>
#include <stdlib.h>

#define MAX(a, b) (a > b ? a : b)

int lcs (char *a, int n, char *b, int m, char **s) {
    int i, j, k, t;
    int *z = calloc((n + 1) * (m + 1), sizeof (int));
    int **c = calloc((n + 1), sizeof (int *));
    for (i = 0; i <= n; i++) {
        c[i] = &z[i * (m + 1)];
    }
    for (i = 1; i <= n; i++) {
        for (j = 1; j <= m; j++) {
            if (a[i - 1] == b[j - 1]) {
                c[i][j] = c[i - 1][j - 1] + 1;
            }
            else {
                c[i][j] = MAX(c[i - 1][j], c[i][j - 1]);
            }
        }
    }
    t = c[n][m];
    *s = malloc(t);
    for (i = n, j = m, k = t - 1; k >= 0;) {
        if (a[i - 1] == b[j - 1])
            (*s)[k] = a[i - 1], i--, j--, k--;
        else if (c[i][j - 1] > c[i - 1][j])
            j--;
        else
            i--;
    }
    free(c);
    free(z);
    return t;
}


Longest increasing subsequence

Calculate and show here a longest increasing subsequence of the list:
:\{3, 2, 6, 4, 5, 1\}
And of the list:
:\{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15\}

Note that a list may have more than one subsequence that is of the maximum length.

;Ref:
# Dynamic Programming #1: Longest Increasing Subsequence on YouTube
# An efficient solution can be based on Patience sorting.

Solution:
#include <stdio.h>
#include <stdlib.h>

struct node {
	int val, len;
	struct node *next;
};

void lis(int *v, int len)
{
	int i;
	struct node *p, *n = calloc(len, sizeof *n);
	for (i = 0; i < len; i++)
		n[i].val = v[i];

	for (i = len; i--; ) {
		// find longest chain that can follow n[i]
		for (p = n + i; p++ < n + len; ) {
			if (p->val > n[i].val && p->len >= n[i].len) {
				n[i].next = p;
				n[i].len = p->len + 1;
			}
		}
	}

	// find longest chain
	for (i = 0, p = n; i < len; i++)
		if (n[i].len > p->len) p = n + i;

	do printf(" %d", p->val); while ((p = p->next));
	putchar('\n');

	free(n);
}

int main(void)
{
	int x[] = { 3, 2, 6, 4, 5, 1 };
	int y[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };

	lis(x, sizeof(x) / sizeof(int));
	lis(y, sizeof(y) / sizeof(int));
	return 0;
}


MAC vendor lookup

Every connected device around the world comes with a unique Media Access Control address, or a   MAC address.

A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address.

;Task:
Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address.

A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result.

Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls.

'''{"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}'''

Solution:
#include <curl/curl.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

/* Length of http://api.macvendors.com/ */
#define FIXED_LENGTH 16

struct MemoryStruct {
  char *memory;
  size_t size;
};

static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
  size_t realsize = size * nmemb;
  struct MemoryStruct *mem = (struct MemoryStruct *)userp;

  mem->memory = realloc(mem->memory, mem->size + realsize + 1);

  memcpy(&(mem->memory[mem->size]), contents, realsize);
  mem->size += realsize;
  mem->memory[mem->size] = 0;

  return realsize;
}

void checkResponse(char* str){
	char ref[] = "Vendor not found";
	int len = strlen(str),flag = 1,i;

	if(len<16)
		fputs(str,stdout);
	else{
		for(i=0;i<len && i<16;i++)
			flag = flag && (ref[i]==str[i]);

		flag==1?fputs("N/A",stdout):fputs(str,stdout);
	}
}

int main(int argC,char* argV[])
{
		if(argC!=2)
			printf("Usage : %s <MAC address>",argV[0]);
		else{
			CURL *curl;
			int len = strlen(argV[1]);
			char* str = (char*)malloc((FIXED_LENGTH + len)*sizeof(char));
			struct MemoryStruct chunk;
			CURLcode res;

			chunk.memory = malloc(1);
			chunk.size = 0;

        if ((curl = curl_easy_init()) != NULL) {
				sprintf(str,"http://api.macvendors.com/%s",argV[1]);

                                curl_easy_setopt(curl, CURLOPT_URL, str);
				curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
				curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);

				free(str);

				res = curl_easy_perform(curl);

                if (res == CURLE_OK) {
				checkResponse(chunk.memory);
                                return EXIT_SUCCESS;
                }

                curl_easy_cleanup(curl);
			}
		}

        return EXIT_FAILURE;
}


MD4

Find the MD4 message digest of a string of [[octet]]s.
Use the ASCII encoded string "Rosetta Code" (without quotes).
You may either call an MD4 library, or implement MD4 in your language.

'''MD4''' is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols.

RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.

Solution:
/*
 *
 *      Author: George Mossessian
 *
 *      The MD4 hash algorithm, as described in https://tools.ietf.org/html/rfc1320
 */

#include <stdlib.h>
#include <string.h>
#include <stdint.h>

char *MD4(char *str, int len); //this is the prototype you want to call. Everything else is internal.

typedef struct string{
        char *c;
        int len;
        char sign;
}string;

static uint32_t *MD4Digest(uint32_t *w, int len);
static void setMD4Registers(uint32_t AA, uint32_t BB, uint32_t CC, uint32_t DD);
static uint32_t changeEndianness(uint32_t x);
static void resetMD4Registers(void);
static string stringCat(string first, string second);
static string uint32ToString(uint32_t l);
static uint32_t stringToUint32(string s);

static const char *BASE16 = "0123456789abcdef=";

#define F(X,Y,Z) (((X)&(Y))|((~(X))&(Z)))
#define G(X,Y,Z) (((X)&(Y))|((X)&(Z))|((Y)&(Z)))
#define H(X,Y,Z) ((X)^(Y)^(Z))

#define LEFTROTATE(A,N) ((A)<<(N))|((A)>>(32-(N)))

#define MD4ROUND1(a,b,c,d,x,s) a += F(b,c,d) + x; a = LEFTROTATE(a, s);
#define MD4ROUND2(a,b,c,d,x,s) a += G(b,c,d) + x + (uint32_t)0x5A827999; a = LEFTROTATE(a, s);
#define MD4ROUND3(a,b,c,d,x,s) a += H(b,c,d) + x + (uint32_t)0x6ED9EBA1; a = LEFTROTATE(a, s);

static uint32_t A = 0x67452301;
static uint32_t B = 0xefcdab89;
static uint32_t C = 0x98badcfe;
static uint32_t D = 0x10325476;

string newString(char * c, int t){
	string r;
	int i;
	if(c!=NULL){
		r.len = (t<=0)?strlen(c):t;
		r.c=(char *)malloc(sizeof(char)*(r.len+1));
		for(i=0; i<r.len; i++) r.c[i]=c[i];
		r.c[r.len]='\0';
		return r;
	}
	r.len=t;
	r.c=(char *)malloc(sizeof(char)*(r.len+1));
	memset(r.c,(char)0,sizeof(char)*(t+1));
	r.sign = 1;
	return r;
}

string stringCat(string first, string second){
	string str=newString(NULL, first.len+second.len);
	int i;

	for(i=0; i<first.len; i++){
		str.c[i]=first.c[i];
	}
	for(i=first.len; i<str.len; i++){
		str.c[i]=second.c[i-first.len];
	}
	return str;
}

string base16Encode(string in){
	string out=newString(NULL, in.len*2);
	int i,j;

	j=0;
	for(i=0; i<in.len; i++){
		out.c[j++]=BASE16[((in.c[i] & 0xF0)>>4)];
		out.c[j++]=BASE16[(in.c[i] & 0x0F)];
	}
	out.c[j]='\0';
	return out;
}

string uint32ToString(uint32_t l){
	string s = newString(NULL,4);
	int i;
	for(i=0; i<4; i++){
		s.c[i] = (l >> (8*(3-i))) & 0xFF;
	}
	return s;
}

uint32_t stringToUint32(string s){
	uint32_t l;
	int i;
	l=0;
	for(i=0; i<4; i++){
		l = l|(((uint32_t)((unsigned char)s.c[i]))<<(8*(3-i)));
	}
	return l;
}

char *MD4(char *str, int len){
	string m=newString(str, len);
	string digest;
	uint32_t *w;
	uint32_t *hash;
	uint64_t mlen=m.len;
	unsigned char oneBit = 0x80;
	int i, wlen;

	m=stringCat(m, newString((char *)&oneBit,1));

	//append 0 ≤ k < 512 bits '0', such that the resulting message length in bits
	//	is congruent to −64 ≡ 448 (mod 512)4
	i=((56-m.len)%64);
	if(i<0) i+=64;
	m=stringCat(m,newString(NULL, i));

	w = malloc(sizeof(uint32_t)*(m.len/4+2));

	//append length, in bits (hence <<3), least significant word first
	for(i=0; i<m.len/4; i++){
		w[i]=stringToUint32(newString(&(m.c[4*i]), 4));
	}
	w[i++] = (mlen<<3) & 0xFFFFFFFF;
	w[i++] = (mlen>>29) & 0xFFFFFFFF;

	wlen=i;

	//change endianness, but not for the appended message length, for some reason?
	for(i=0; i<wlen-2; i++){
		w[i]=changeEndianness(w[i]);
	}

	hash = MD4Digest(w,wlen);

	digest=newString(NULL,0);
	for(i=0; i<4; i++){
		hash[i]=changeEndianness(hash[i]);
		digest=stringCat(digest,uint32ToString(hash[i]));
	}

	return base16Encode(digest).c;
}

uint32_t *MD4Digest(uint32_t *w, int len){
	//assumes message.len is a multiple of 64 bytes.
	int i,j;
	uint32_t X[16];
	uint32_t *digest = malloc(sizeof(uint32_t)*4);
	uint32_t AA, BB, CC, DD;

	for(i=0; i<len/16; i++){
		for(j=0; j<16; j++){
			X[j]=w[i*16+j];
		}

		AA=A;
		BB=B;
		CC=C;
		DD=D;

		MD4ROUND1(A,B,C,D,X[0],3);
		MD4ROUND1(D,A,B,C,X[1],7);
		MD4ROUND1(C,D,A,B,X[2],11);
		MD4ROUND1(B,C,D,A,X[3],19);
		MD4ROUND1(A,B,C,D,X[4],3);
		MD4ROUND1(D,A,B,C,X[5],7);
		MD4ROUND1(C,D,A,B,X[6],11);
		MD4ROUND1(B,C,D,A,X[7],19);
		MD4ROUND1(A,B,C,D,X[8],3);
		MD4ROUND1(D,A,B,C,X[9],7);
		MD4ROUND1(C,D,A,B,X[10],11);
		MD4ROUND1(B,C,D,A,X[11],19);
		MD4ROUND1(A,B,C,D,X[12],3);
		MD4ROUND1(D,A,B,C,X[13],7);
		MD4ROUND1(C,D,A,B,X[14],11);
		MD4ROUND1(B,C,D,A,X[15],19);

		MD4ROUND2(A,B,C,D,X[0],3);
		MD4ROUND2(D,A,B,C,X[4],5);
		MD4ROUND2(C,D,A,B,X[8],9);
		MD4ROUND2(B,C,D,A,X[12],13);
		MD4ROUND2(A,B,C,D,X[1],3);
		MD4ROUND2(D,A,B,C,X[5],5);
		MD4ROUND2(C,D,A,B,X[9],9);
		MD4ROUND2(B,C,D,A,X[13],13);
		MD4ROUND2(A,B,C,D,X[2],3);
		MD4ROUND2(D,A,B,C,X[6],5);
		MD4ROUND2(C,D,A,B,X[10],9);
		MD4ROUND2(B,C,D,A,X[14],13);
		MD4ROUND2(A,B,C,D,X[3],3);
		MD4ROUND2(D,A,B,C,X[7],5);
		MD4ROUND2(C,D,A,B,X[11],9);
		MD4ROUND2(B,C,D,A,X[15],13);

		MD4ROUND3(A,B,C,D,X[0],3);
		MD4ROUND3(D,A,B,C,X[8],9);
		MD4ROUND3(C,D,A,B,X[4],11);
		MD4ROUND3(B,C,D,A,X[12],15);
		MD4ROUND3(A,B,C,D,X[2],3);
		MD4ROUND3(D,A,B,C,X[10],9);
		MD4ROUND3(C,D,A,B,X[6],11);
		MD4ROUND3(B,C,D,A,X[14],15);
		MD4ROUND3(A,B,C,D,X[1],3);
		MD4ROUND3(D,A,B,C,X[9],9);
		MD4ROUND3(C,D,A,B,X[5],11);
		MD4ROUND3(B,C,D,A,X[13],15);
		MD4ROUND3(A,B,C,D,X[3],3);
		MD4ROUND3(D,A,B,C,X[11],9);
		MD4ROUND3(C,D,A,B,X[7],11);
		MD4ROUND3(B,C,D,A,X[15],15);

		A+=AA;
		B+=BB;
		C+=CC;
		D+=DD;
	}

	digest[0]=A;
	digest[1]=B;
	digest[2]=C;
	digest[3]=D;
	resetMD4Registers();
	return digest;
}

uint32_t changeEndianness(uint32_t x){
	return ((x & 0xFF) << 24) | ((x & 0xFF00) << 8) | ((x & 0xFF0000) >> 8) | ((x & 0xFF000000) >> 24);
}

void setMD4Registers(uint32_t AA, uint32_t BB, uint32_t CC, uint32_t DD){
	A=AA;
	B=BB;
	C=CC;
	D=DD;
}

void resetMD4Registers(void){
	setMD4Registers(0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476);
}


Machine code

The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language.

For example, the following assembly language program is given for x86 (32 bit) architectures:

mov EAX, [ESP+4]
add EAX, [ESP+8]
ret

This would translate into the following opcode bytes:
139 68 36 4 3 68 36 8 195

Or in hexadecimal:
8B 44 24 04 03 44 24 08 C3

;Task:
If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language:

* Poke the necessary opcodes into a memory location.
* Provide a means to pass two values to the machine code.
* Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19.
* Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)

Solution:
#include <stdio.h>
#include <sys/mman.h>
#include <string.h>

int test (int a, int b)
{
  /*
       mov EAX, [ESP+4]
       add EAX, [ESP+8]
       ret
  */
  char code[] = {0x8B, 0x44, 0x24, 0x4, 0x3, 0x44, 0x24, 0x8, 0xC3};
  void *buf;
  int c;
  /* copy code to executable buffer */
  buf = mmap (0,sizeof(code),PROT_READ|PROT_WRITE|PROT_EXEC,
             MAP_PRIVATE|MAP_ANON,-1,0);

  memcpy (buf, code, sizeof(code));
  /* run code */
  c = ((int (*) (int, int))buf)(a, b);
  /* free buffer */
  munmap (buf, sizeof(code));
  return c;
}

int main ()
{
  printf("%d\n", test(7,12));
  return 0;
}


Mad Libs

{{wikipedia}}

Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results.

;Task;
Write a program to create a Mad Libs like story.

The program should read an arbitrary multiline story from input.

The story will be terminated with a blank line.

Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements.

Stop when there are none left and print the final story.

The input should be an arbitrary story in the form:

 went for a walk in the park.
found a .  decided to take it home.

Given this example, it should then ask for a name, a he or she and a noun ( gets replaced both times with the same value).

Solution:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define err(...) fprintf(stderr, ## __VA_ARGS__), exit(1)

/* We create a dynamic string with a few functions which make modifying
 * the string and growing a bit easier */
typedef struct {
    char *data;
    size_t alloc;
    size_t length;
} dstr;

inline int dstr_space(dstr *s, size_t grow_amount)
{
    return s->length + grow_amount < s->alloc;
}

int dstr_grow(dstr *s)
{
    s->alloc *= 2;
    char *attempt = realloc(s->data, s->alloc);

    if (!attempt) return 0;
    else s->data = attempt;

    return 1;
}

dstr* dstr_init(const size_t to_allocate)
{
    dstr *s = malloc(sizeof(dstr));
    if (!s) goto failure;

    s->length = 0;
    s->alloc  = to_allocate;
    s->data   = malloc(s->alloc);

    if (!s->data) goto failure;

    return s;

failure:
    if (s->data) free(s->data);
    if (s) free(s);
    return NULL;
}

void dstr_delete(dstr *s)
{
    if (s->data) free(s->data);
    if (s) free(s);
}

dstr* readinput(FILE *fd)
{
    static const size_t buffer_size = 4096;
    char buffer[buffer_size];

    dstr *s = dstr_init(buffer_size);
    if (!s) goto failure;

    while (fgets(buffer, buffer_size, fd)) {
        while (!dstr_space(s, buffer_size))
            if (!dstr_grow(s)) goto failure;

        strncpy(s->data + s->length, buffer, buffer_size);
        s->length += strlen(buffer);
    }

    return s;

failure:
    dstr_delete(s);
    return NULL;
}

void dstr_replace_all(dstr *story, const char *replace, const char *insert)
{
    const size_t replace_l = strlen(replace);
    const size_t insert_l  = strlen(insert);
    char *start = story->data;

    while ((start = strstr(start, replace))) {
        if (!dstr_space(story, insert_l - replace_l))
            if (!dstr_grow(story)) err("Failed to allocate memory");

        if (insert_l != replace_l) {
            memmove(start + insert_l, start + replace_l, story->length -
                    (start + replace_l - story->data));

            /* Remember to null terminate the data so we can utilize it
             * as we normally would */
            story->length += insert_l - replace_l;
            story->data[story->length] = 0;
        }

        memmove(start, insert, insert_l);
    }
}

void madlibs(dstr *story)
{
    static const size_t buffer_size = 128;
    char insert[buffer_size];
    char replace[buffer_size];

    char *start,
         *end = story->data;

    while (start = strchr(end, '<')) {
        if (!(end = strchr(start, '>'))) err("Malformed brackets in input");

        /* One extra for current char and another for nul byte */
        strncpy(replace, start, end - start + 1);
        replace[end - start + 1] = '\0';

        printf("Enter value for field %s: ", replace);

        fgets(insert, buffer_size, stdin);
        const size_t il = strlen(insert) - 1;
        if (insert[il] == '\n')
            insert[il] = '\0';

        dstr_replace_all(story, replace, insert);
    }
    printf("\n");
}

int main(int argc, char *argv[])
{
    if (argc < 2) return 0;

    FILE *fd = fopen(argv[1], "r");
    if (!fd) err("Could not open file: '%s\n", argv[1]);

    dstr *story = readinput(fd); fclose(fd);
    if (!story) err("Failed to allocate memory");

    madlibs(story);
    printf("%s\n", story->data);
    dstr_delete(story);
    return 0;
}


Magic squares of doubly even order

Solution:
#include<stdlib.h>
#include<ctype.h>
#include<stdio.h>

int** doublyEvenMagicSquare(int n) {
	if (n < 4 || n % 4 != 0)
		return NULL;

	int bits = 38505;
	int size = n * n;
	int mult = n / 4,i,r,c,bitPos;

	int** result = (int**)malloc(n*sizeof(int*));

	for(i=0;i<n;i++)
		result[i] = (int*)malloc(n*sizeof(int));

	for (r = 0, i = 0; r < n; r++) {
		for (c = 0; c < n; c++, i++) {
			bitPos = c / mult + (r / mult) * 4;
			result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;
		}
	}
	return result;
}

int numDigits(int n){
	int count = 1;

	while(n>=10){
		n /= 10;
		count++;
	}

	return count;
}

void printMagicSquare(int** square,int rows){
	int i,j,baseWidth = numDigits(rows*rows) + 3;

	printf("Doubly Magic Square of Order : %d and Magic Constant : %d\n\n",rows,(rows * rows + 1) * rows / 2);

	for(i=0;i<rows;i++){
		for(j=0;j<rows;j++){
			printf("%*s%d",baseWidth - numDigits(square[i][j]),"",square[i][j]);
		}
		printf("\n");
	}
}

int main(int argC,char* argV[])
{
	int n;

	if(argC!=2||isdigit(argV[1][0])==0)
		printf("Usage : %s <integer specifying rows in magic square>",argV[0]);
	else{
		n = atoi(argV[1]);
		printMagicSquare(doublyEvenMagicSquare(n),n);
	}
	return 0;
}


Magic squares of odd order

A magic square is an   '''NxN'''   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   ''and''   both long (main) diagonals are equal to the same sum (which is called the   ''magic number''   or   ''magic constant'').

The numbers are usually (but not always) the first   '''N'''2   positive integers.

A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a ''semimagic square''.

{| class="wikitable" style="float:right;border: 4px solid blue; background:lightgreen; color:black; margin-left:auto;margin-right:auto;text-align:center;width:15em;height:15em;table-layout:fixed;font-size:150%"
|-
| '''8''' || '''1''' || '''6'''
|-
| '''3''' || '''5''' || '''7'''
|-
| '''4''' || '''9''' || '''2'''
|}

;Task
For any odd   '''N''',   generate a magic square with the integers   ''' 1''' --> '''N''',   and show the results here.

Optionally, show the ''magic number''.

You should demonstrate the generator by showing at least a magic square for   '''N''' = '''5'''.

; Related tasks
* [[Magic squares of singly even order]]
* [[Magic squares of doubly even order]]

; See also:
* MathWorld(tm) entry: Magic_square
* Odd Magic Squares (1728.org)

Solution:
#include <stdio.h>
#include <stdlib.h>

int f(int n, int x, int y)
{
	return (x + y*2 + 1)%n;
}

int main(int argc, char **argv)
{
	int i, j, n;

	//Edit: Add argument checking
	if(argc!=2) return 1;

	//Edit: Input must be odd and not less than 3.
	n = atoi(argv[1]);
	if (n < 3 || (n%2) == 0) return 2;

	for (i = 0; i < n; i++) {
		for (j = 0; j < n; j++)
			printf("% 4d", f(n, n - j - 1, i)*n + f(n, j, i) + 1);
		putchar('\n');
	}
	printf("\n Magic Constant: %d.\n", (n*n+1)/2*n);

	return 0;
}


Magic squares of singly even order

A magic square is an '''NxN''' square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant'').

A  magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6, 10, 14). This means that the subsquares have an odd size, which plays a role in the construction.

;Task
Create a magic square of 6 x 6.

; Related tasks
* [[Magic squares of odd order]]
* [[Magic squares of doubly even order]]

; See also
* Singly Even Magic Squares (1728.org)

Solution:
#include<stdlib.h>
   #include<ctype.h>
   #include<stdio.h>

   int** oddMagicSquare(int n) {
        if (n < 3 || n % 2 == 0)
            return NULL;

        int value = 0;
        int squareSize = n * n;
        int c = n / 2, r = 0,i;

        int** result = (int**)malloc(n*sizeof(int*));

		for(i=0;i<n;i++)
			result[i] = (int*)malloc(n*sizeof(int));

        while (++value <= squareSize) {
            result[r][c] = value;
            if (r == 0) {
                if (c == n - 1) {
                    r++;
                } else {
                    r = n - 1;
                    c++;
                }
            } else if (c == n - 1) {
                r--;
                c = 0;
            } else if (result[r - 1][c + 1] == 0) {
                r--;
                c++;
            } else {
                r++;
            }
        }
        return result;
    }

    int** singlyEvenMagicSquare(int n) {
        if (n < 6 || (n - 2) % 4 != 0)
            return NULL;

        int size = n * n;
        int halfN = n / 2;
        int subGridSize = size / 4, i;

        int** subGrid = oddMagicSquare(halfN);
        int gridFactors[] = {0, 2, 3, 1};
        int** result = (int**)malloc(n*sizeof(int*));

		for(i=0;i<n;i++)
			result[i] = (int*)malloc(n*sizeof(int));

        for (int r = 0; r < n; r++) {
            for (int c = 0; c < n; c++) {
                int grid = (r / halfN) * 2 + (c / halfN);
                result[r][c] = subGrid[r % halfN][c % halfN];
                result[r][c] += gridFactors[grid] * subGridSize;
            }
        }

        int nColsLeft = halfN / 2;
        int nColsRight = nColsLeft - 1;

        for (int r = 0; r < halfN; r++)
            for (int c = 0; c < n; c++) {
                if (c < nColsLeft || c >= n - nColsRight
                        || (c == nColsLeft && r == nColsLeft)) {

                    if (c == 0 && r == nColsLeft)
                        continue;

                    int tmp = result[r][c];
                    result[r][c] = result[r + halfN][c];
                    result[r + halfN][c] = tmp;
                }
            }

        return result;
    }

	int numDigits(int n){
		int count = 1;

		while(n>=10){
			n /= 10;
			count++;
		}

		return count;
	}

	void printMagicSquare(int** square,int rows){
		int i,j;

		for(i=0;i<rows;i++){
			for(j=0;j<rows;j++){
				printf("%*s%d",rows - numDigits(square[i][j]),"",square[i][j]);
			}
			printf("\n");
		}
		printf("\nMagic constant: %d ", (rows * rows + 1) * rows / 2);
	}

	int main(int argC,char* argV[])
	{
		int n;

		if(argC!=2||isdigit(argV[1][0])==0)
			printf("Usage : %s <integer specifying rows in magic square>",argV[0]);
		else{
			n = atoi(argV[1]);
			printMagicSquare(singlyEvenMagicSquare(n),n);
		}
		return 0;
	}


Map range

Given two ranges:
:::*   [a_1,a_2]   and
:::*   [b_1,b_2];
:::*   then a value   s   in range   [a_1,a_2]
:::*   is linearly mapped to a value   t   in range   [b_1,b_2]
   where:

:::*   t = b_1 + {(s - a_1)(b_2 - b_1) \over (a_2 - a_1)}

;Task:
Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range.

Use this function to map values from the range    [0, 10]    to the range    [-1, 0].

;Extra credit:
Show additional idiomatic ways of performing the mapping, using tools available to the language.

Solution:
#include <stdio.h>

#define mapRange(a1,a2,b1,b2,s) (b1 + (s-a1)*(b2-b1)/(a2-a1))

int main()
{
	int i;
	puts("Mapping [0,10] to [-1,0] at intervals of 1:");

	for(i=0;i<=10;i++)
	{
		printf("f(%d) = %g\n",i,mapRange(0,10,-1,0,i));
	}

	return 0;
}


Matrix digital rain

Implement the Matrix Digital Rain visual effect from the movie "The Matrix" as described in Wikipedia.

Provided is a reference implementation in Common Lisp to be run in a terminal.

Solution:
/**
 * Loosely emulates the "digital rain" effect from The Matrix.
 *
 * @author Dan Ruscoe <dan@ruscoe.org>
 */
#include <unistd.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <ncurses.h>

/* Time between row updates in microseconds.
   Controls the speed of the digital rain effect.
*/
#define ROW_DELAY 40000

/**
 * Gets a random integer within a given range.
 *
 * @param int min The low-end of the range.
 * @param int max The high-end of the range.
 *
 * @return int The random integer.
 */
int get_rand_in_range(int min, int max)
{
  return (rand() % ((max + 1) - min) + min);
}

int main(void)
{
  /* Basic seed for random numbers. */
  srand(time(NULL));

  /* Characters to randomly appear in the rain sequence. */
  char chars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

  int total_chars = sizeof(chars);

  /* Set up ncurses screen and colors. */
  initscr();
  noecho();
  curs_set(FALSE);

  start_color();
  init_pair(1, COLOR_GREEN, COLOR_BLACK);
  attron(COLOR_PAIR(1));

  int max_x = 0, max_y = 0;

  getmaxyx(stdscr, max_y, max_x);

  /* Create arrays of columns based on screen width. */

  /* Array containing the current row of each column. */
  int columns_row[max_x];

  /* Array containing the active status of each column.
     A column draws characters on a row when active.
  */
  int columns_active[max_x];

  int i;

  /* Set top row as current row for all columns. */
  for (i = 0; i < max_x; i++)
  {
    columns_row[i] = -1;
    columns_active[i] = 0;
  }

  while (1)
  {
    for (i = 0; i < max_x; i++)
    {
      if (columns_row[i] == -1)
      {
        /* If a column is at the top row, pick a
           random starting row and active status.
        */
        columns_row[i] = get_rand_in_range(0, max_y);
        columns_active[i] = get_rand_in_range(0, 1);
      }
    }

    /* Loop through columns and draw characters on rows. */
    for (i = 0; i < max_x; i++)
    {
      if (columns_active[i] == 1)
      {
        /* Draw a random character at this column's current row. */
        int char_index = get_rand_in_range(0, total_chars);
        mvprintw(columns_row[i], i, "%c", chars[char_index]);
      }
      else
      {
        /* Draw an empty character if the column is inactive. */
        mvprintw(columns_row[i], i, " ");
      }

      columns_row[i]++;

      /* When a column reaches the bottom row, reset to top. */
      if (columns_row[i] >= max_y)
      {
        columns_row[i] = -1;
      }

      /* Randomly alternate the column's active status. */
      if (get_rand_in_range(0, 1000) == 0)
      {
        columns_active[i] = (columns_active[i] == 0) ? 1 : 0;
      }
    }

    usleep(ROW_DELAY);
    refresh();
  }

  endwin();
  return 0;
}


Maximum triangle path sum

Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:

                          55
                        94 48
                       95 30 96
                     77 71 26 67

One of such walks is 55 - 94 - 30 - 26.
You can compute the total of the numbers you have seen in such walk,
in this case it's 205.

Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321.

;Task:
Find the maximum total in the triangle below:

                          55
                        94 48
                       95 30 96
                     77 71 26 67
                    97 13 76 38 45
                  07 36 79 16 37 68
                 48 07 09 18 70 26 06
               18 72 79 46 59 79 29 90
              20 76 87 11 32 07 07 49 18
            27 83 58 35 71 11 25 57 29 85
           14 64 36 96 27 11 58 56 92 18 55
         02 90 03 60 48 49 41 46 33 36 47 23
        92 50 48 02 36 59 42 79 72 20 82 77 42
      56 78 38 80 39 75 02 71 66 66 01 03 55 72
     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36
   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52
  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15
27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93

Such numbers can be included in the solution code, or read from a "triangle.txt" file.

This task is derived from the Euler Problem #18.

Solution:
#include <stdio.h>
#include <math.h>

#define max(x,y)  ((x) > (y) ? (x) : (y))

int tri[] = {
        55,
	94, 48,
	95, 30, 96,
	77, 71, 26, 67,
	97, 13, 76, 38, 45,
	7, 36, 79, 16, 37, 68,
	48, 7, 9, 18, 70, 26, 6,
	18, 72, 79, 46, 59, 79, 29, 90,
	20, 76, 87, 11, 32, 7, 7, 49, 18,
	27, 83, 58, 35, 71, 11, 25, 57, 29, 85,
	14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,
	2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,
	92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,
	56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,
	44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,
	85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,
	6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,
	27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93
};

int main(void)
{
    const int len  = sizeof(tri) / sizeof(tri[0]);
    const int base = (sqrt(8*len + 1) - 1) / 2;
    int step       = base - 1;
    int stepc      = 0;

    int i;
    for (i = len - base - 1; i >= 0; --i) {
        tri[i] += max(tri[i + step], tri[i + step + 1]);
        if (++stepc == step) {
            step--;
            stepc = 0;
        }
    }

    printf("%d\n", tri[0]);
    return 0;
}


McNuggets problem

From Wikipedia:
 The McNuggets version of the coin problem was introduced by Henri Picciotto,
 who included it in his algebra textbook co-authored with Anita Wah. Picciotto
 thought of the application in the 1980s while dining with his son at
 McDonald's, working the problem out on a napkin. A McNugget number is
 the total number of McDonald's Chicken McNuggets in any number of boxes.
 In the United Kingdom, the original boxes (prior to the introduction of
 the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets.

;Task:
Calculate (from 0 up to a limit of 100) the largest non-McNuggets
number (a number ''n'' which cannot be expressed with ''6x + 9y + 20z = n''
where ''x'', ''y'' and ''z'' are natural numbers).

Solution:
#include <stdio.h>

int
main() {
    int max = 0, i = 0, sixes, nines, twenties;

loopstart: while (i < 100) {
        for (sixes = 0; sixes*6 < i; sixes++) {
            if (sixes*6 == i) {
                i++;
                goto loopstart;
            }

            for (nines = 0; nines*9 < i; nines++) {
                if (sixes*6 + nines*9 == i) {
                    i++;
                    goto loopstart;
                }

                for (twenties = 0; twenties*20 < i; twenties++) {
                    if (sixes*6 + nines*9 + twenties*20 == i) {
                        i++;
                        goto loopstart;
                    }
                }
            }
        }
        max = i;
        i++;
    }

    printf("Maximum non-McNuggets number is %d\n", max);

    return 0;
}


Memory layout of a data structure

It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity.
 Pin Settings for Plug
 (Reverse order for socket.)
 __________________________________________
 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
 _________________
 1  2  3  4  5
 6  7  8  9
 25 pin                        9 pin
 1 - PG   Protective ground
 2 - TD   Transmitted data     3
 3 - RD   Received data        2
 4 - RTS  Request to send      7
 5 - CTS  Clear to send        8
 6 - DSR  Data set ready       6
 7 - SG   Signal ground        5
 8 - CD   Carrier detect       1
 9 - + voltage (testing)
 10 - - voltage (testing)
 11 -
 12 - SCD  Secondary CD
 13 - SCS  Secondary CTS
 14 - STD  Secondary TD
 15 - TC   Transmit clock
 16 - SRD  Secondary RD
 17 - RC   Receiver clock
 18 -
 19 - SRS  Secondary RTS
 20 - DTR  Data terminal ready      4
 21 - SQD  Signal quality detector
 22 - RI   Ring indicator           9
 23 - DRS  Data rate select
 24 - XTC  External clock
 25 -

Solution:
struct RS232_data
{
  unsigned carrier_detect        : 1;
  unsigned received_data         : 1;
  unsigned transmitted_data      : 1;
  unsigned data_terminal_ready   : 1;
  unsigned signal_ground         : 1;
  unsigned data_set_ready        : 1;
  unsigned request_to_send       : 1;
  unsigned clear_to_send         : 1;
  unsigned ring_indicator        : 1;
};


Metaprogramming

{{omit from|BBC BASIC}}
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation.

For the purposes of this task, "support for metaprogramming" means any way the user can effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.

Solution:
#include <gadget/gadget.h>

LIB_GADGET_START

void Muestra_archivo_original();

Main
   Assert (Exist_file("load_matrix.txt"), file_not_found);

   /* recupero informacion del archivo para su apertura segura */
   F_STAT dataFile = Stat_file("load_matrix.txt");
   Assert (dataFile.is_matrix, file_not_matrixable)  // tiene forma de matriz???

   New multitype test;

   /* The data range to be read is established.
      It is possible to read only part of the file using these ranges. */
   Range for test [0:1:dataFile.total_lines-1, 0:1:dataFile.max_tokens_per_line-1];

   /* cargamos el array detectando números enteros como long */
   test = Load_matrix_mt( pSDS(test), "load_matrix.txt", dataFile, DET_LONG);

   /* modifica algunas cosas del archivo */
   Let( $s-test[0,1], "Columna 1");
   $l-test[2,1] = 1000;
   $l-test[2,2] = 2000;

   /* inserto filas */
   /* preparo la fila a insertar */
   New multitype nueva_fila;
   sAppend_mt(nueva_fila,"fila 3.1");  /* sAppend_mt() and Append_mt() are macros */
   Append_mt(nueva_fila,float,0.0);
   Append_mt(nueva_fila,int,0);
   Append_mt(nueva_fila,double,0.0);
   Append_mt(nueva_fila,long, 0L);

   /* insertamos la misma fila en el array, 3 veces */
   test = Insert_row_mt(pSDS(test),pSDS(nueva_fila), 4);
   test = Insert_row_mt(pSDS(test),pSDS(nueva_fila), 4);
   test = Insert_row_mt(pSDS(test),pSDS(nueva_fila), 4);
   Free multitype nueva_fila;

   Print "\nGuardando archivo en \"save_matrix.txt\"...\n";
   DEC_PREC = 20; /* establece precision decimal */

   All range for test;
   Save_matrix_mt(SDS(test), "save_matrix.txt" );

   Free multitype test;

   Print "\nArchivo original:\n";
   Muestra_archivo_original();

   Exception( file_not_found ){
      Msg_red("File not found\n");
   }
   Exception( file_not_matrixable ){
      Msg_red("File is not matrixable\n");
   }

End

void Muestra_archivo_original(){
    String csys;
    csys = `cat load_matrix.txt`;
    Print "\n%s\n", csys;
    Free secure csys;
}


Metronome

The task is to implement a   metronome.

The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable.

For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an external player may be used.

However, the playing of the sounds should not interfere with the timing of the metronome.

The visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities.

If the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.

Solution:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>

struct timeval start, last;

inline int64_t tv_to_u(struct timeval s)
{
	return s.tv_sec * 1000000 + s.tv_usec;
}

inline struct timeval u_to_tv(int64_t x)
{
	struct timeval s;
	s.tv_sec = x / 1000000;
	s.tv_usec = x % 1000000;
	return s;
}

void draw(int dir, int64_t period, int64_t cur, int64_t next)
{
	int len = 40 * (next - cur) / period;
	int s, i;

	if (len > 20) len = 40 - len;
	s = 20 + (dir ? len : -len);

	printf("\033[H");
	for (i = 0; i <= 40; i++) putchar(i == 20 ? '|': i == s ? '#' : '-');
}

void beat(int delay)
{
	struct timeval tv = start;
	int dir = 0;
	int64_t d = 0, corr = 0, slp, cur, next = tv_to_u(start) + delay;
	int64_t draw_interval = 20000;
	printf("\033[H\033[J");
	while (1) {
		gettimeofday(&tv, 0);
		slp = next - tv_to_u(tv) - corr;
		usleep(slp);
		gettimeofday(&tv, 0);

		putchar(7); /* bell */
		fflush(stdout);

		printf("\033[5;1Hdrift: %d compensate: %d (usec)   ",
			(int)d, (int)corr);
		dir = !dir;

		cur = tv_to_u(tv);
		d = cur - next;
		corr = (corr + d) / 2;
		next += delay;

		while (cur + d + draw_interval < next) {
			usleep(draw_interval);
			gettimeofday(&tv, 0);
			cur = tv_to_u(tv);
			draw(dir, delay, cur, next);
			fflush(stdout);
		}
	}
}

int main(int c, char**v)
{
	int bpm;

	if (c < 2 || (bpm = atoi(v[1])) <= 0) bpm = 60;
	if (bpm > 600) {
		fprintf(stderr, "frequency %d too high\n", bpm);
		exit(1);
	}

	gettimeofday(&start, 0);
	last = start;
	beat(60 * 1000000 / bpm);

	return 0;
}


Middle three digits

Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.

Note: The order of the middle digits should be preserved.

Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:

123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0

Show your output on this page.

Solution:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void midThree(char arg[])
{
    char output[4];
    int midPoint;
    arg[0]=='-'?midPoint = ((strlen(arg) + 1) / 2):midPoint = ((strlen(arg) + 1) / 2) - 1;

    if(strlen(arg) < 3)
        {
            printf("Error, %d is too short.\n",atoi(arg));
            return ;
        }
        else if(strlen(arg)  == 4 || strlen(arg) == 3)
        {
            printf("Error, %d has %d digits, no 3 middle digits.\n",atoi(arg),arg[0]=='-'?strlen(arg)-1:strlen(arg));
            return ;
        }
    else{
    for(int i=0; i<3; i++)
    {
        output[i] = arg[(midPoint-1) + i];
    }
    output[3] = '\0';
    printf("The middle three digits of %s are %s.\n",arg,output);
}}

int main(int argc, char * argv[])
{
    char input[50];
    int x[] = {123, 12345, 1234567, 987654321, 10001, -10001,
		-123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0,
		1234567890},i;

    if(argc < 2)
    {
        printf("Usage: %s <integer>\n",argv[0]);
        printf("Examples with preloaded data shown below :\n");

        for(i=0;i<18;i++)
        {
	        midThree(itoa(x[i],argv[0],10));
	     }
        return 1;
    }
    else
    {
        sprintf(input,"%d",atoi(argv[1]));
            midThree(argv[1]);
            return 0;

    }
}


Mind boggling card trick

Matt Parker of the "Stand Up Maths channel" has a   YouTube video   of a card trick that creates a semblance of order from chaos.

The task is to simulate the trick in a way that mimics the steps shown in the video.

; 1. Cards.
# Create a common deck of cards of 52 cards    (which are half red, half black).
# Give the pack a good shuffle.
; 2. Deal from the shuffled deck, you'll be creating three piles.
#   Assemble the cards face down.
##   Turn up the   ''top card''   and hold it in your hand.
###    if the card is         black,        then add the   ''next''   card (unseen) to the       "black"      pile.
###    If the card is     red,    then add the   ''next''   card (unseen) to the   "red"  pile.
##   Add the   ''top card''   that you're holding to the '''discard''' pile.   (You might optionally show these discarded cards to get an idea of the randomness).
# Repeat the above for the rest of the shuffled deck.
; 3. Choose a random number   (call it '''X''')   that will be used to swap cards from the "red" and "black" piles.
# Randomly choose   '''X'''   cards from the   "red"  pile (unseen), let's call this the   "red"  bunch.
# Randomly choose   '''X'''   cards from the       "black"      pile (unseen), let's call this the      "black"       bunch.
# Put the     "red"    bunch into the         "black"      pile.
# Put the        "black"        bunch into the      "red"  pile.
# (The above two steps complete the swap of   '''X'''   cards of the "red" and "black" piles.  (Without knowing what those cards are --- they could be red or black, nobody knows).
; 4. Order from randomness?
# Verify (or not) the mathematician's assertion that:
      '''The number of black cards in the "black" pile equals the number of red cards in the "red" pile.'''

(Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.)

Show output on this page.

Solution:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#define SIM_N           5  /* Run 5 simulations */
#define PRINT_DISCARDED 1  /* Whether or not to print the discard pile */

#define min(x,y) ((x<y)?(x):(y))

typedef uint8_t card_t;

/* Return a random number from an uniform distribution (0..n-1) */
unsigned int rand_n(unsigned int n) {
    unsigned int out, mask = 1;
    /* Find how many bits to mask off */
    while (mask < n) mask = mask<<1 | 1;
    /* Generate random number */
    do {
        out = rand() & mask;
    } while (out >= n);
    return out;
}

/* Return a random card (0..51) from an uniform distribution */
card_t rand_card() {
    return rand_n(52);
}

/* Print a card */
void print_card(card_t card) {
    static char *suits = "HCDS"; /* hearts, clubs, diamonds and spades */
    static char *cards[] = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
    printf(" %s%c", cards[card>>2], suits[card&3]);
}

/* Shuffle a pack */
void shuffle(card_t *pack) {
    int card;
    card_t temp, randpos;
    for (card=0; card<52; card++) {
        randpos = rand_card();
        temp = pack[card];
        pack[card] = pack[randpos];
        pack[randpos] = temp;
    }
}

/* Do the card trick, return whether cards match */
int trick() {
    card_t pack[52];
    card_t blacks[52/4], reds[52/4];
    card_t top, x, card;
    int blackn=0, redn=0, blacksw=0, redsw=0, result;

    /* Create and shuffle a pack */
    for (card=0; card<52; card++) pack[card] = card;
    shuffle(pack);

    /* Deal cards */
#if PRINT_DISCARDED
    printf("Discarded:"); /* Print the discard pile */
#endif
    for (card=0; card<52; card += 2) {
        top = pack[card]; /* Take card */
        if (top & 1) { /* Add next card to black or red pile */
            blacks[blackn++] = pack[card+1];
        } else {
            reds[redn++] = pack[card+1];
        }
#if PRINT_DISCARDED
        print_card(top); /* Show which card is discarded */
#endif
    }
#if PRINT_DISCARDED
    printf("\n");
#endif

    /* Swap an amount of cards */
    x = rand_n(min(blackn, redn));
    for (card=0; card<x; card++) {
        /* Pick a random card from the black and red pile to swap */
        blacksw = rand_n(blackn);
        redsw = rand_n(redn);
        /* Swap them */
        top = blacks[blacksw];
        blacks[blacksw] = reds[redsw];
        reds[redsw] = top;
    }

    /* Verify the assertion */
    result = 0;
    for (card=0; card<blackn; card++)
        result += (blacks[card] & 1) == 1;
    for (card=0; card<redn; card++)
        result -= (reds[card] & 1) == 0;
    result = !result;

    printf("The number of black cards in the 'black' pile"
           " %s the number of red cards in the 'red' pile.\n",
           result? "equals" : "does not equal");
    return result;
}

int main() {
    unsigned int seed, i, successes = 0;
    FILE *r;

    /* Seed the RNG with bytes from from /dev/urandom */
    if ((r = fopen("/dev/urandom", "r")) == NULL) {
        fprintf(stderr, "cannot open /dev/urandom\n");
        return 255;
    }
    if (fread(&seed, sizeof(unsigned int), 1, r) != 1) {
        fprintf(stderr, "failed to read from /dev/urandom\n");
        return 255;
    }
    fclose(r);
    srand(seed);

    /* Do simulations. */
    for (i=1; i<=SIM_N; i++) {
        printf("Simulation %d\n", i);
        successes += trick();
        printf("\n");
    }

    printf("Result: %d successes out of %d simulations\n",
        successes, SIM_N);

    return 0;
}


Minimum multiple of m where digital sum equals m

Generate the sequence '''a(n)''' when each element is the minimum integer multiple '''m''' such that the digit sum of '''n''' times '''m''' is equal to '''n'''.

;Task

* Find the first 40 elements of the sequence.

;Stretch

* Find the next 30 elements of the sequence.

;See also

;* OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n

Solution:
#include <stdio.h>

unsigned digit_sum(unsigned n) {
    unsigned sum = 0;
    do { sum += n % 10; }
    while(n /= 10);
    return sum;
}

unsigned a131382(unsigned n) {
    unsigned m;
    for (m = 1; n != digit_sum(m*n); m++);
    return m;
}

int main() {
    unsigned n;
    for (n = 1; n <= 70; n++) {
        printf("%9u", a131382(n));
        if (n % 10 == 0) printf("\n");
    }
    return 0;
}


Minimum positive multiple in base 10 using only 0 and 1

Every positive integer has infinitely many base-10 multiples that only use the digits '''0''' and '''1'''. The goal of this task is to find and display the '''minimum''' multiple that has this property.

This is simple to do, but can be challenging to do efficiently.

To avoid repeating long, unwieldy phrases, the operation "minimum positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1" will hereafter be referred to as "'''B10'''".

;Task:

Write a routine to find the B10 of a given integer.

E.G.

       '''n'''                  '''B10'''      '''n'''  x '''multiplier'''
       1                    1    ( 1  x 1         )
       2                   10    ( 2  x 5         )
       7                 1001    ( 7  x 143       )
       9            111111111    ( 9  x 12345679  )
      10                   10    ( 10 x 1         )

and so on.

Use the routine to find and display here, on this page, the '''B10''' value for:

    1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999

Optionally find '''B10''' for:

    1998, 2079, 2251, 2277

Stretch goal; find '''B10''' for:

    2439, 2997, 4878

There are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you ''do'' use magic numbers, explain briefly why and what they do for your implementation.

;See also:

:* OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's.
:* How to find Minimum Positive Multiple in base 10 using only 0 and 1

Solution:
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

__int128 imax(__int128 a, __int128 b) {
    if (a > b) {
        return a;
    }
    return b;
}

__int128 ipow(__int128 b, __int128 n) {
    __int128 res;
    if (n == 0) {
        return 1;
    }
    if (n == 1) {
        return b;
    }
    res = b;
    while (n > 1) {
        res *= b;
        n--;
    }
    return res;
}

__int128 imod(__int128 m, __int128 n) {
    __int128 result = m % n;
    if (result < 0) {
        result += n;
    }
    return result;
}

bool valid(__int128 n) {
    if (n < 0) {
        return false;
    }
    while (n > 0) {
        int r = n % 10;
        if (r > 1) {
            return false;
        }
        n /= 10;
    }
    return true;
}

__int128 mpm(const __int128 n) {
    __int128 *L;
    __int128 m, k, r, j;

    if (n == 1) {
        return 1;
    }

    L = calloc(n * n, sizeof(__int128));
    L[0] = 1;
    L[1] = 1;
    m = 0;
    while (true) {
        m++;
        if (L[(m - 1) * n + imod(-ipow(10, m), n)] == 1) {
            break;
        }
        L[m * n + 0] = 1;
        for (k = 1; k < n; k++) {
            L[m * n + k] = imax(L[(m - 1) * n + k], L[(m - 1) * n + imod(k - ipow(10, m), n)]);
        }
    }

    r = ipow(10, m);
    k = imod(-r, n);

    for (j = m - 1; j >= 1; j--) {
        if (L[(j - 1) * n + k] == 0) {
            r = r + ipow(10, j);
            k = imod(k - ipow(10, j), n);
        }
    }

    if (k == 1) {
        r++;
    }
    return r / n;
}

void print128(__int128 n) {
    char buffer[64]; // more then is needed, but is nice and round;
    int pos = (sizeof(buffer) / sizeof(char)) - 1;
    bool negative = false;

    if (n < 0) {
        negative = true;
        n = -n;
    }

    buffer[pos] = 0;
    while (n > 0) {
        int rem = n % 10;
        buffer[--pos] = rem + '0';
        n /= 10;
    }
    if (negative) {
        buffer[--pos] = '-';
    }
    printf(&buffer[pos]);
}

void test(__int128 n) {
    __int128 mult = mpm(n);
    if (mult > 0) {
        print128(n);
        printf(" * ");
        print128(mult);
        printf(" = ");
        print128(n * mult);
        printf("\n");
    } else {
        print128(n);
        printf("(no solution)\n");
    }
}

int main() {
    int i;

    // 1-10 (inclusive)
    for (i = 1; i <= 10; i++) {
        test(i);
    }
    // 95-105 (inclusive)
    for (i = 95; i <= 105; i++) {
        test(i);
    }
    test(297);
    test(576);
    test(594); // needs a larger number type (64 bits signed)
    test(891);
    test(909);
    test(999); // needs a larger number type (87 bits signed)

    // optional
    test(1998);
    test(2079);
    test(2251);
    test(2277);

    // stretch
    test(2439);
    test(2997);
    test(4878);

    return 0;
}


Modular exponentiation

Find the last   '''40'''   decimal digits of   a^b,   where

::*   a = 2988348162058574136915891421498819466320163312926952423791023078876139
::*   b = 2351399303373464486466122544523690094744975233415544072992656881240319

A computer is too slow to find the entire value of   a^b.

Instead, the program must use a fast algorithm for modular exponentiation:   a^b \mod m.

The algorithm must work for any integers   a, b, m,     where   b \ge 0   and   m > 0.

Solution: Given numbers are too big for even 64 bit integers, so might as well take the lazy route and use GMP:


Modular inverse

From Wikipedia:

In modulo    ''m''    is an integer    ''x''    such that

::a\,x \equiv 1 \pmod{m}.

Or in other words, such that:

::\exists k \in\Z,\qquad a\, x = 1 + k\,m

It can be shown that such an inverse exists   if and only if    ''a''    and    ''m''    are coprime,   but we will ignore this for this task.

;Task:
Either by implementing the algorithm, by using a dedicated library or by using a built-in function in
your language,   compute the modular inverse of   42 modulo 2017.

Solution:
#include <stdio.h>

int mul_inv(int a, int b)
{
	int b0 = b, t, q;
	int x0 = 0, x1 = 1;
	if (b == 1) return 1;
	while (a > 1) {
		q = a / b;
		t = b, b = a % b, a = t;
		t = x0, x0 = x1 - q * x0, x1 = t;
	}
	if (x1 < 0) x1 += b0;
	return x1;
}

int main(void) {
	printf("%d\n", mul_inv(42, 2017));
	return 0;
}


Monads/List monad

A Monad is a combination of a data-type with two helper functions written for that type.

The data-type can be of any kind which can contain values of some other type - common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as '''eta''' and '''mu''', but usually given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type.

The bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure.

A sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product.

The natural implementation of bind for the List monad is a composition of '''concat''' and '''map''', which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping.

Demonstrate in your programming language the following:

#Construct a List Monad by writing the 'bind' function and the 'pure' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented)
#Make two functions, each which take a number and return a monadic number, e.g. Int -> List Int and Int -> List String
#Compose the two functions with bind

Solution:
#include <stdio.h>
#include <stdlib.h>

#define MONAD void*
#define INTBIND(f, g, x) (f((int*)g(x)))
#define RETURN(type,x) &((type)*)(x)

MONAD boundInt(int *x) {
    return (MONAD)(x);
}

MONAD boundInt2str(int *x) {
    char buf[100];
    char*str= malloc(1+sprintf(buf, "%d", *x));
    sprintf(str, "%d", *x);
    return (MONAD)(str);
}

void task(int y) {
    char *z= INTBIND(boundInt2str, boundInt, &y);
    printf("%s\n", z);
    free(z);
}

int main() {
    task(13);
}


Monads/Maybe monad

Demonstrate in your programming language the following:

#Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented)
#Make two functions, each which take a number and return a monadic number, e.g. Int -> Maybe Int and Int -> Maybe String
#Compose the two functions with bind

A Monad is a single type which encapsulates several other types, eliminating boilerplate code. In practice it acts like a dynamically typed computational sequence, though in many cases the type issues can be resolved at compile time.

A Maybe Monad is a monad which specifically encapsulates the type of an undefined value.

Solution:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

typedef enum type
{
  INT,
  STRING
} Type;

typedef struct maybe
{
  int i;
  char *s;
  Type t;
  _Bool is_something;
} Maybe;

void print_Maybe(Maybe *m)
{
  if (m->t == INT)
    printf("Just %d : INT\n", m->i);

  else if (m->t == STRING)
    printf("Just \"%s\" : STRING\n", m->s);

  else
    printf("Nothing\n");

}

Maybe *return_maybe(void *data, Type t)
{
  Maybe *m = malloc(sizeof(Maybe));
  if (t == INT)
  {
    m->i = *(int *) data;
    m->s = NULL;
    m->t = INT;
    m->is_something = true;
  }

  else if (t == STRING)
  {
    m->i = 0;
    m->s = data;
    m->t = STRING;
    m->is_something = true;
  }

  else
  {
    m->i = 0;
    m->s = NULL;
    m->t = 0;
    m->is_something = false;
  }

  return m;
}

Maybe *bind_maybe(Maybe *m, Maybe *(*f)(void *))
{
  Maybe *n = malloc(sizeof(Maybe));

  if (f(&(m->i))->is_something)
  {
    n->i = f(&(m->i))->i;
    n->s = f(&(m->i))->s;
    n->t = f(&(m->i))->t;
    n->is_something = true;
  }

  else
  {
    n->i = 0;
    n->s = NULL;
    n->t = 0;
    n->is_something = false;
  }
  return n;
}

Maybe *f_1(void *v) // Int -> Maybe Int
{
  Maybe *m = malloc(sizeof(Maybe));
  m->i = (*(int *) v) * (*(int *) v);
  m->s = NULL;
  m->t = INT;
  m->is_something = true;
  return m;
}

Maybe *f_2(void *v) // :: Int -> Maybe String
{
  Maybe *m = malloc(sizeof(Maybe));
  m->i = 0;
  m->s = malloc(*(int *) v * sizeof(char) + 1);
  for (int i = 0; i < *(int *) v; i++)
  {
    m->s[i] = 'x';
  }
  m->s[*(int *) v + 1] = '\0';
  m->t = STRING;
  m->is_something = true;
  return m;
}

int main()
{
  int i = 7;
  char *s = "lorem ipsum dolor sit amet";

  Maybe *m_1 = return_maybe(&i, INT);
  Maybe *m_2 = return_maybe(s, STRING);

  print_Maybe(m_1); // print value of m_1: Just 49
  print_Maybe(m_2); // print value of m_2 : Just "lorem ipsum dolor sit amet"

  print_Maybe(bind_maybe(m_1, f_1)); // m_1 `bind` f_1 :: Maybe Int
  print_Maybe(bind_maybe(m_1, f_2)); // m_1 `bind` f_2 :: Maybe String

  print_Maybe(bind_maybe(bind_maybe(m_1, f_1), f_2)); // (m_1 `bind` f_1) `bind` f_2 :: Maybe String -- it prints 49 'x' characters in a row
}


Move-to-front algorithm

Given a symbol table of a ''zero-indexed'' array of all possible input symbols
this algorithm reversibly transforms a sequence
of input symbols into an array of output numbers (indices).

The transform in many cases acts to give frequently repeated input symbols
lower indices which is  useful in some compression algorithms.

;Encoding algorithm:

    for each symbol of the input sequence:
        output the index of the symbol in the symbol table
        move that symbol to the front of the symbol table

;Decoding algorithm:

    # Using the same starting symbol table
    for each index of the input sequence:
        output the symbol at that index of the symbol table
        move that symbol to the front of the symbol table

;Example:
Encoding the string of character symbols 'broood' using a symbol table of the lowercase characters   '''a'''-to-'''z'''

:::::{| class="wikitable" border="1"
|-
! Input
! Output
! SymbolTable
|-
| '''b'''roood
| 1
| 'abcdefghijklmnopqrstuvwxyz'
|-
| b'''r'''oood
| 1 17
| 'bacdefghijklmnopqrstuvwxyz'
|-
| br'''o'''ood
| 1 17 15
| 'rbacdefghijklmnopqstuvwxyz'
|-
| bro'''o'''od
| 1 17 15 0
| 'orbacdefghijklmnpqstuvwxyz'
|-
| broo'''o'''d
| 1 17 15 0 0
| 'orbacdefghijklmnpqstuvwxyz'
|-
| brooo'''d'''
| 1 17 15 0 0 5
| 'orbacdefghijklmnpqstuvwxyz'
|}

Decoding the indices back to the original symbol order:
:::::{| class="wikitable" border="1"
|-
! Input
! Output
! SymbolTable
|-
|  '''1''' 17 15 0 0 5
| b
| 'abcdefghijklmnopqrstuvwxyz'
|-
| 1 '''17''' 15 0 0 5
| br
| 'bacdefghijklmnopqrstuvwxyz'
|-
| 1 17 '''15''' 0 0 5
| bro
| 'rbacdefghijklmnopqstuvwxyz'
|-
| 1 17 15 '''0''' 0 5
| broo
| 'orbacdefghijklmnpqstuvwxyz'
|-
| 1 17 15 0 '''0''' 5
| brooo
| 'orbacdefghijklmnpqstuvwxyz'
|-
| 1 17 15 0 0 '''5'''
| broood
| 'orbacdefghijklmnpqstuvwxyz'
|}

;Task:
:*   Encode and decode the following three strings of characters using the symbol table of the lowercase characters   '''a'''-to-'''z'''   as above.
:*   Show the strings and their encoding here.
:*   Add a check to ensure that the decoded string is the same as the original.

The strings are:

    broood
 bananaaa
 hiphophiphop
(Note the misspellings in the above strings.)

Solution:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define MAX_SIZE 100

int move_to_front(char *str,char c)
{
    char *q,*p;
    int shift=0;
    p=(char *)malloc(strlen(str)+1);
    strcpy(p,str);
    q=strchr(p,c); //returns pointer to location of char c in string str
    shift=q-p;      // no of characters from 0 to position of c in str
    strncpy(str+1,p,shift);
    str[0]=c;
    free(p);
  //  printf("\n%s\n",str);
    return shift;
}

void decode(int* pass,int size,char *sym)
{
    int i,index;
    char c;
    char table[]="abcdefghijklmnopqrstuvwxyz";
    for(i=0;i<size;i++)
    {
        c=table[pass[i]];
        index=move_to_front(table,c);
        if(pass[i]!=index) printf("there is an error");
        sym[i]=c;
    }
    sym[size]='\0';
}

void encode(char *sym,int size,int *pass)
{
    int i=0;
    char c;
    char table[]="abcdefghijklmnopqrstuvwxyz";
    for(i=0;i<size;i++)
    {
        c=sym[i];
        pass[i]=move_to_front(table,c);
    }
}

int check(char *sym,int size,int *pass)
{
    int *pass2=malloc(sizeof(int)*size);
    char *sym2=malloc(sizeof(char)*size);
    int i,val=1;

    encode(sym,size,pass2);
    i=0;
    while(i<size && pass[i]==pass2[i])i++;
    if(i!=size)val=0;

    decode(pass,size,sym2);
    if(strcmp(sym,sym2)!=0)val=0;

    free(sym2);
    free(pass2);

    return val;
}

int main()
{
    char sym[3][MAX_SIZE]={"broood","bananaaa","hiphophiphop"};
    int pass[MAX_SIZE]={0};
    int i,len,j;
    for(i=0;i<3;i++)
    {
        len=strlen(sym[i]);
        encode(sym[i],len,pass);
        printf("%s : [",sym[i]);
        for(j=0;j<len;j++)
            printf("%d ",pass[j]);
        printf("]\n");
        if(check(sym[i],len,pass))
            printf("Correct :)\n");
        else
            printf("Incorrect :(\n");
    }
    return 0;
}


Multi-dimensional array

For the purposes of this task, the actual memory layout or access method of this data structure is not mandated.

It is enough to:
# State the number and extent of each index to the array.
# Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value.
# Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position.

;Task:
* State if the language supports multi-dimensional arrays in its syntax and usual implementation.
* State whether the language uses row-major or column major order for multi-dimensional array storage, or any other relevant kind of storage.
* Show how to create a four dimensional array in your language and set, access, set to another value; and access the new value of an integer-indexed item of the array. The idiomatic method for the language is preferred.
:* The array should allow a range of five, four, three and two (or two three four five if convenient), in each of the indices, in order. (For example, ''if'' indexing starts at zero for the first index then a range of 0..4 inclusive would suffice).
* State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated.
* If the language has exceptional native multi-dimensional array support such as optional bounds checking, reshaping, or being able to state both the lower and upper bounds of index ranges, then this is the task to mention them.

Show all output here, (but you may judiciously use ellipses to shorten repetitive output text).

Solution:
#include<stdlib.h>
#include<stdio.h>

/*The stdlib header file is required for the malloc and free functions*/

int main()
{
	/*Declaring a four fold integer pointer, also called
	a pointer to a pointer to a pointer to an integer pointer*/

	int**** hyperCube, i,j,k;

	/*We will need i,j,k for the memory allocation*/

	/*First the five lines*/

	hyperCube = (int****)malloc(5*sizeof(int***));

	/*Now the four planes*/

	for(i=0;i<5;i++){
		hyperCube[i] = (int***)malloc(4*sizeof(int**));

		/*Now the 3 cubes*/

		for(j=0;j<4;j++){
			hyperCube[i][j] = (int**)malloc(3*sizeof(int*));

			/*Now the 2 hypercubes (?)*/

			for(k=0;k<3;k++){
				hyperCube[i][j][k] = (int*)malloc(2*sizeof(int));
			}
		}
	}

	/*All that looping and function calls may seem futile now,
	but imagine real applications when the dimensions of the dataset are
	not known beforehand*/

	/*Yes, I just copied the rest from the first program*/

	hyperCube[4][3][2][1] = 1;

	/*IMPORTANT : C ( and hence C++ and Java and everyone of the family ) arrays are zero based.
	The above element is thus actually the last element of the hypercube.*/

	/*Now we print out that element*/

	printf("\n%d",hyperCube[4][3][2][1]);

	/*But that's not the only way to get at that element*/
	printf("\n%d",*(*(*(*(hyperCube + 4) + 3) + 2) + 1));

	/*Yes, I know, it's beautiful*/
	*(*(*(*(hyperCube+3)+2)+1)) = 3;

	printf("\n%d",hyperCube[3][2][1][0]);

	/*Always nice to clean up after you, yes memory is cheap, but C is 45+ years old,
	and anyways, imagine you are dealing with terabytes of data, or more...*/

	free(hyperCube);

	return 0;
}


Multifactorial

The factorial of a number, written as n!, is defined as n! = n(n-1)(n-2)...(2)(1).

Multifactorials generalize factorials as follows:
: n! = n(n-1)(n-2)...(2)(1)
: n!! = n(n-2)(n-4)...
: n!! ! = n(n-3)(n-6)...
: n!! !! = n(n-4)(n-8)...
: n!! !! ! = n(n-5)(n-10)...

In all cases, the terms in the products are positive integers.

If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold:
# Write a function that given n and the degree, calculates the multifactorial.
# Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial.

'''Note:''' The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.

Solution:
/* Include statements and constant definitions */
#include <stdio.h>
#define HIGHEST_DEGREE 5
#define LARGEST_NUMBER 10

/* Recursive implementation of multifactorial function */
int multifact(int n, int deg){
   return n <= deg ? n : n * multifact(n - deg, deg);
}

/* Iterative implementation of multifactorial function */
int multifact_i(int n, int deg){
   int result = n;
   while (n >= deg + 1){
      result *= (n - deg);
      n -= deg;
   }
   return result;
}

/* Test function to print out multifactorials */
int main(void){
   int i, j;
   for (i = 1; i <= HIGHEST_DEGREE; i++){
      printf("\nDegree %d: ", i);
      for (j = 1; j <= LARGEST_NUMBER; j++){
         printf("%d ", multifact(j, i));
      }
   }
}


Multiple distinct objects

Create a [[sequence]] (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime.

By ''distinct'' we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.

By ''initialized'' we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type.

This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the ''same'' mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.

This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).

See also: [[Closures/Value capture]]

Solution:
foo *foos = malloc(n * sizeof(*foos));
for (int i = 0; i < n; i++)
  init_foo(&foos[i]);


Multisplit

It is often necessary to split a string into pieces
based on several different (potentially multi-character) separator strings,
while still retaining the information about which separators were present in the input.

This is particularly useful when doing small parsing tasks.
The task is to write code to demonstrate this.

The function (or procedure or method, as appropriate) should
take an input string and an ordered collection of separators.

The order of the separators is significant:
The delimiter order represents priority in matching, with the first defined delimiter having the highest priority.
In cases where there would be an ambiguity as to
which separator to use at a particular point
(e.g., because one separator is a prefix of another)
the separator with the highest priority should be used.
Delimiters can be reused and the output from the function should be an ordered sequence of substrings.

Test your code using the input string "a!===b=!=c" and the separators "==", "!=" and "=".

For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c".
Note that the quotation marks are shown for clarity and do not form part of the output.

'''Extra Credit:''' provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.

Solution:
#include <stdio.h>
#include <string.h>

void parse_sep(const char *str, const char *const *pat, int len)
{
	int i, slen;
	while (*str != '\0') {
		for (i = 0; i < len || !putchar(*(str++)); i++) {
			slen = strlen(pat[i]);
			if (strncmp(str, pat[i], slen)) continue;
			printf("{%.*s}", slen, str);
			str += slen;
			break;
		}
	}
}

int main()
{
	const char *seps[] = { "==", "!=", "=" };
	parse_sep("a!===b=!=c", seps, 3);

	return 0;
}


Munchausen numbers

A Munchausen number is a natural number ''n'' the sum of whose digits (in base 10), each raised to the power of itself, equals ''n''.

('''Munchausen''' is also spelled: '''Munchhausen'''.)

For instance:    3435 = 33 + 44 + 33 + 55

;Task
Find all Munchausen numbers between   '''1'''   and   '''5000'''.

;Also see:
:* The OEIS entry:  A046253
:* The Wikipedia entry:  Perfect digit-to-digit invariant, redirected from ''Munchausen Number''

Solution:
#include <stdio.h>
#include <math.h>

int main() {
    for (int i = 1; i < 5000; i++) {
        // loop through each digit in i
        // e.g. for 1000 we get 0, 0, 0, 1.
        int sum = 0;
        for (int number = i; number > 0; number /= 10) {
            int digit = number % 10;
            // find the sum of the digits
            // raised to themselves
            sum += pow(digit, digit);
        }
        if (sum == i) {
            // the sum is equal to the number
            // itself; thus it is a
            // munchausen number
            printf("%i\n", i);
        }
    }
    return 0;
}


Musical scale

Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz.

These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfege.

For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed.

For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file),  or the task can be omitted.

Solution:
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<dos.h>

typedef struct{
	char str[3];
	int key;
	}note;

note sequence[] = {{"Do",0},{"Re",2},{"Mi",4},{"Fa",5},{"So",7},{"La",9},{"Ti",11},{"Do",12}};

int main(void)
{
	int i=0;

	while(!kbhit())
	{
		printf("\t%s",sequence[i].str);
		sound(261.63*pow(2,sequence[i].key/12.0));
		delay(sequence[i].key%12==0?500:1000);
		i = (i+1)%8;
		i==0?printf("\n"):printf("");
	}
	nosound();
	return 0;
}


N-queens problem

right

Solve the eight queens puzzle.

You can extend the problem to solve the puzzle with a board of size   '''N'''x'''N'''.

For the number of solutions for small values of   '''N''',   see   OEIS: A000170.

;Related tasks:
* [[A* search algorithm]]
* [[Solve a Hidato puzzle]]
* [[Solve a Holy Knight's tour]]
* [[Knight's tour]]
* [[Peaceful chess queen armies]]
* [[Solve a Hopido puzzle]]
* [[Solve a Numbrix puzzle]]
* [[Solve the no connection puzzle]]

Solution:
#include <stdio.h>
#include <stdlib.h>

typedef unsigned int uint;
uint count = 0;

#define ulen sizeof(uint) * 8

/* could have defined as int solve(...), but void may have less
   chance to confuse poor optimizer */
void solve(int n)
{
	int cnt = 0;
	const uint full = -(int)(1 << (ulen - n));
	register uint bits, pos, *m, d, e;

	uint b0, b1, l[32], r[32], c[32], mm[33] = {0};
	n -= 3;
	/* require second queen to be left of the first queen, so
	   we ever only test half of the possible solutions. This
	   is why we can't handle n=1 here */
	for (b0 = 1U << (ulen - n - 3); b0; b0 <<= 1) {
		for (b1 = b0 << 2; b1; b1 <<= 1) {
			d = n;
			/* c: columns occupied by previous queens.
			   l: columns attacked by left diagonals
			   r: by right diagnoals */
			c[n] = b0 | b1;
			l[n] = (b0 << 2) | (b1 << 1);
			r[n] = (b0 >> 2) | (b1 >> 1);

			/* availabe columns on current row. m is stack */
			bits = *(m = mm + 1) = full & ~(l[n] | r[n] | c[n]);

			while (bits) {
				/* d: depth, aka row. counting backwards
				   because !d is often faster than d != n */
				while (d) {
					/* pos is right most nonzero bit */
					pos = -(int)bits & bits;

					/* mark bit used. only put current bits
					   on stack if not zero, so backtracking
					   will skip exhausted rows (because reading
					   stack variable is sloooow compared to
					   registers) */
					if ((bits &= ~pos))
						*m++ = bits | d;

					/* faster than l[d+1] = l[d]... */
					e = d--;
					l[d] = (l[e] | pos) << 1;
					r[d] = (r[e] | pos) >> 1;
					c[d] =  c[e] | pos;

					bits = full & ~(l[d] | r[d] | c[d]);

					if (!bits) break;
					if (!d) { cnt++; break; }
				}
				/* Bottom of stack m is a zero'd field acting
				   as sentinel.  When saving to stack, left
				   27 bits are the available columns, while
				   right 5 bits is the depth. Hence solution
				   is limited to size 27 board -- not that it
				   matters in foreseeable future. */
				d = (bits = *--m) & 31U;
				bits &= ~31U;
			}
		}
	}
	count = cnt * 2;
}

int main(int c, char **v)
{
	int nn;
	if (c <= 1 || (nn = atoi(v[1])) <= 0) nn = 8;

	if (nn > 27) {
		fprintf(stderr, "Value too large, abort\n");
		exit(1);
	}

	/* Can't solve size 1 board; might as well skip 2 and 3 */
	if (nn < 4) count = nn == 1;
	else	    solve(nn);

	printf("\nSolutions: %d\n", count);
	return 0;
}