Narcissist

Quoting from the Esolangs wiki page:

A '''narcissist''' (or '''Narcissus program''') is the decision-problem version of a [[quine]].

A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" or "accept" if that string matches its own source code, or a "0" or "reject" if it does not.

For concreteness, in this task we shall assume that symbol = character.

The narcissist should be able to cope with any finite input, whatever its length.

Any form of output is allowed, as long as the program always halts, and "accept", "reject" and "not yet finished" are distinguishable.

Solution: extern void*stdin;main(){ char*p = "extern void*stdin;main(){ char*p = %c%s%c,a[300],b[300];sprintf(a,p,34,p,34);fgets(b,300,stdin);putchar(48+!strcmp(a,b)); }",a[300],b[300];sprintf(a,p,34,p,34);fgets(b,300,stdin);putchar(48+!strcmp(a,b)); }


Narcissistic decimal number

A   Narcissistic decimal number   is a non-negative integer,   n,   that is equal to the sum of the   m-th   powers of each of the digits in the decimal representation of   n,   where   m   is the number of digits in the decimal representation of   n.

Narcissistic (decimal) numbers are sometimes called   '''Armstrong'''   numbers, named after Michael F. Armstrong.
They are also known as   '''Plus Perfect'''   numbers.

;An example:
::::*   if   n   is   '''153'''
::::*   then   m,   (the number of decimal digits)   is   '''3'''
::::*   we have    13 + 53 + 33   =   1 + 125 + 27   =   '''153'''
::::*   and so   '''153'''   is a narcissistic decimal number

;Task:
Generate and show here the first   '''25'''   narcissistic decimal numbers.

Note:   0^1 = 0,   the first in the series.

;See also:
*   the  OEIS entry:     Armstrong (or Plus Perfect, or narcissistic) numbers.
*   MathWorld entry:   Narcissistic Number.
*   Wikipedia entry:     Narcissistic number.

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

#define MAX_LEN 81

mpz_t power[10];
mpz_t dsum[MAX_LEN + 1];
int cnt[10], len;

void check_perm(void)
{
	char s[MAX_LEN + 1];
	int i, c, out[10] = { 0 };

	mpz_get_str(s, 10, dsum[0]);
	for (i = 0; s[i]; i++) {
		c = s[i]-'0';
		if (++out[c] > cnt[c]) return;
	}

	if (i == len)
		gmp_printf(" %Zd", dsum[0]);
}

void narc_(int pos, int d)
{
	if (!pos) {
		check_perm();
		return;
	}

	do {
		mpz_add(dsum[pos-1], dsum[pos], power[d]);
		++cnt[d];
		narc_(pos - 1, d);
		--cnt[d];
	} while (d--);
}

void narc(int n)
{
	int i;
	len = n;
	for (i = 0; i < 10; i++)
		mpz_ui_pow_ui(power[i], i, n);

	mpz_init_set_ui(dsum[n], 0);

	printf("length %d:", n);
	narc_(n, 9);
	putchar('\n');
}

int main(void)
{
	int i;

	for (i = 0; i <= 10; i++)
		mpz_init(power[i]);
	for (i = 1; i <= MAX_LEN; i++) narc(i);

	return 0;
}


Nautical bell

Task

Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day.

The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise.

It is permissible for the program to daemonize, or to slave off a scheduler, and it is permissible to use alternative notification methods (such as producing a written notice "Two Bells Gone"), if these are more usual for the system type.

;Related task:
* [[Sleep]]

Solution:
#include<unistd.h>
#include<stdio.h>
#include<time.h>

#define SHORTLAG 1000
#define LONGLAG  2000

int main(){
	int i,times,hour,min,sec,min1,min2;

	time_t t;
	struct tm* currentTime;

	while(1){
		time(&t);
		currentTime = localtime(&t);

		hour = currentTime->tm_hour;
		min = currentTime->tm_min;
		sec = currentTime->tm_sec;

		hour = 12;
		min = 0;
		sec = 0;

		if((min==0 || min==30) && sec==0)
			times = ((hour*60 + min)%240)%8;
		if(times==0){
			times = 8;
		}

		if(min==0){
			min1 = 0;
			min2 = 0;
		}

		else{
			min1 = 3;
			min2 = 0;
		}

		if((min==0 || min==30) && sec==0){
			printf("\nIt is now %d:%d%d %s. Sounding the bell %d times.",hour,min1,min2,(hour>11)?"PM":"AM",times);

			for(i=1;i<=times;i++){
				printf("\a");

				(i%2==0)?sleep(LONGLAG):sleep(SHORTLAG);
			}
		}
	}
	return 0;
}


Nested function

In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function.

;Task:
Write a program consisting of two nested functions that prints the following text.

 1. first
 2. second
 3. third

The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function.

The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter.

;References:
:* Nested function

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

typedef struct{
	char str[30];
}item;

item* makeList(char* separator){
	int counter = 0,i;
	item* list = (item*)malloc(3*sizeof(item));

	item makeItem(){
		item holder;

		char names[5][10] = {"first","second","third","fourth","fifth"};

		sprintf(holder.str,"%d%s%s",++counter,separator,names[counter]);

		return holder;
	}

	for(i=0;i<3;i++)
		list[i] = makeItem();

	return list;
}

int main()
{
	int i;
	item* list = makeList(". ");

	for(i=0;i<3;i++)
		printf("\n%s",list[i].str);

	return 0;
}


Next highest int from digits

Given a zero or positive integer, the task is to generate the next largest
integer using only the given digits*1.

*   Numbers will not be padded to the left with zeroes.
*   Use all given digits, with their given multiplicity. (If a digit appears twice in the input number, it should appear twice in the result).
*   If there is no next highest integer return zero.

:*1   Alternatively phrased as:   "Find the smallest integer larger than the (positive or zero) integer   '''N'''
:: which can be obtained by reordering the (base ten) digits of   '''N'''".

;Algorithm 1:
#   Generate all the permutations of the digits and sort into numeric order.
#   Find the number in the list.
#   Return the next highest number from the list.

The above could prove slow and memory hungry for numbers with large numbers of
digits, but should be easy to reason about its correctness.

;Algorithm 2:
#   Scan right-to-left through the digits of the number until you find a digit with a larger digit somewhere to the right of it.
#   Exchange that digit with the digit on the right that is ''both'' more than it, and closest to it.
#   Order the digits to the right of this position, after the swap; lowest-to-highest, left-to-right. (I.e. so they form the lowest numerical representation)

'''E.g.:'''

    n = 12453

    12_4_53

    12_5_43

    12_5_34

    return: 12534

This second algorithm is faster and more memory efficient, but implementations
may be harder to test.

One method of testing, (as used in developing the task),   is to compare results from both
algorithms for random numbers generated from a range that the first algorithm can handle.

;Task requirements:
Calculate the next highest int from the digits of the following numbers:
:*   0
:*   9
:*   12
:*   21
:*   12453
:*   738440
:*   45072010
:*   95322020

;Optional stretch goal:
:*   9589776899767587796600

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

void swap(char* str, int i, int j) {
    char c = str[i];
    str[i] = str[j];
    str[j] = c;
}

void reverse(char* str, int i, int j) {
    for (; i < j; ++i, --j)
        swap(str, i, j);
}

bool next_permutation(char* str) {
    int len = strlen(str);
    if (len < 2)
        return false;
    for (int i = len - 1; i > 0; ) {
        int j = i, k;
        if (str[--i] < str[j]) {
            k = len;
            while (str[i] >= str[--k]) {}
            swap(str, i, k);
            reverse(str, j, len - 1);
            return true;
        }
    }
    return false;
}

uint32_t next_highest_int(uint32_t n) {
    char str[16];
    snprintf(str, sizeof(str), "%u", n);
    if (!next_permutation(str))
        return 0;
    return strtoul(str, 0, 10);
}

int main() {
    uint32_t numbers[] = {0, 9, 12, 21, 12453, 738440, 45072010, 95322020};
    const int count = sizeof(numbers)/sizeof(int);
    for (int i = 0; i < count; ++i)
        printf("%d -> %d\n", numbers[i], next_highest_int(numbers[i]));
    // Last one is too large to convert to an integer
    const char big[] = "9589776899767587796600";
    char next[sizeof(big)];
    memcpy(next, big, sizeof(big));
    next_permutation(next);
    printf("%s -> %s\n", big, next);
    return 0;
}


Nim game

Nim is a simple game where the second player-if they know the trick-will always win.

The game has only 3 rules:
::*   start with   '''12'''   tokens
::*   each player takes    '''1,  2,  or  3'''   tokens in turn
::*  the player who takes the last token wins.

To win every time,   the second player simply takes 4 minus the number the first player took.   So if the first player takes 1,   the second takes 3; if the first player takes 2,   the second should take 2; and if the first player takes 3,   the second player will take 1.

;Task:
Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.

Solution:
#include  <stdio.h>

int playerTurn(int numTokens, int take);
int computerTurn(int numTokens);

int main(void)
{
	printf("Nim Game\n\n");

	int Tokens = 12;

	while(Tokens > 0)
	{
		printf("How many tokens would you like to take?: ");

		int uin;
		scanf("%i", &uin);

		int nextTokens = playerTurn(Tokens, uin);

		if (nextTokens == Tokens)
		{
			continue;
		}

		Tokens = nextTokens;

		Tokens = computerTurn(Tokens);
	}
	printf("Computer wins.");

	return 0;
}

int playerTurn(int numTokens, int take)
{
	if (take < 1 || take > 3)
	{
		printf("\nTake must be between 1 and 3.\n\n");
		return numTokens;
	}
	int remainingTokens = numTokens - take;

	printf("\nPlayer takes %i tokens.\n", take);
	printf("%i tokens remaining.\n\n", remainingTokens);

	return remainingTokens;
}

int computerTurn(int numTokens)
{
	int take = numTokens % 4;
	int remainingTokens = numTokens - take;

	printf("Computer takes %u tokens.\n", take);
	printf("%i tokens remaining.\n\n", remainingTokens);

	return remainingTokens;
}


Nonoblock

Nonogram puzzle.

;Given:
* The number of cells in a row.
* The size of each, (space separated), connected block of cells to fit in the row, in left-to right order.

;Task:
* show all possible positions.
* show the number of positions of the blocks for the following cases within the row.
* show all output on this page.
* use a "neat" diagram of the block positions.

;Enumerate the following configurations:
#   '''5'''   cells   and   '''[2, 1]'''   blocks
#   '''5'''   cells   and   '''[]'''   blocks   (no blocks)
#   '''10'''   cells   and   '''[8]'''   blocks
#   '''15'''   cells   and   '''[2, 3, 2, 3]'''   blocks
#   '''5'''   cells   and   '''[2, 3]'''   blocks   (should give some indication of this not being possible)

;Example:
Given a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as:

    |_|_|_|_|_| # 5 cells and [2, 1] blocks

And would expand to the following 3 possible rows of block positions:

    |A|A|_|B|_|
    |A|A|_|_|B|
    |_|A|A|_|B|

Note how the sets of blocks are always separated by a space.

Note also that it is not necessary for each block to have a separate letter.
Output approximating

This:
                        |#|#|_|#|_|
                        |#|#|_|_|#|
                        |_|#|#|_|#|

This would also work:
                        ##.#.
                        ##..#
                       .##.#

;An algorithm:
* Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember).
* The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks.
* for each position of the LH block recursively compute the position of the rest of the blocks in the ''remaining'' space to the right of the current placement of the LH block.

(This is the algorithm used in the [[Nonoblock#Python]] solution).

;Reference:
* The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its [[Nonoblock#Python]] solution.

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

void nb(int cells, int total_block_size, int* blocks, int block_count,
        char* output, int offset, int* count) {
    if (block_count == 0) {
        printf("%2d  %s\n", ++*count, output);
        return;
    }
    int block_size = blocks[0];
    int max_pos = cells - (total_block_size + block_count - 1);
    total_block_size -= block_size;
    cells -= block_size + 1;
    ++blocks;
    --block_count;
    for (int i = 0; i <= max_pos; ++i, --cells) {
        memset(output + offset, '.', max_pos + block_size);
        memset(output + offset + i, '#', block_size);
        nb(cells, total_block_size, blocks, block_count, output,
           offset + block_size + i + 1, count);
    }
}

void nonoblock(int cells, int* blocks, int block_count) {
    printf("%d cells and blocks [", cells);
    for (int i = 0; i < block_count; ++i)
        printf(i == 0 ? "%d" : ", %d", blocks[i]);
    printf("]:\n");
    int total_block_size = 0;
    for (int i = 0; i < block_count; ++i)
        total_block_size += blocks[i];
    if (cells < total_block_size + block_count - 1) {
        printf("no solution\n");
        return;
    }
    char output[cells + 1];
    memset(output, '.', cells);
    output[cells] = '\0';
    int count = 0;
    nb(cells, total_block_size, blocks, block_count, output, 0, &count);
}

int main() {
    int blocks1[] = {2, 1};
    nonoblock(5, blocks1, 2);
    printf("\n");

    nonoblock(5, NULL, 0);
    printf("\n");

    int blocks2[] = {8};
    nonoblock(10, blocks2, 1);
    printf("\n");

    int blocks3[] = {2, 3, 2, 3};
    nonoblock(15, blocks3, 4);
    printf("\n");

    int blocks4[] = {2, 3};
    nonoblock(5, blocks4, 2);

    return 0;
}


Numbers with equal rises and falls

When a number is written in base 10,   adjacent digits may "rise" or "fall" as the number is read   (usually from left to right).

;Definition:
Given the decimal digits of the number are written as a series   d:
:*   A   ''rise''         is an index   i   such that    d(i)  <  d(i+1)
:*   A   ''fall''    is an index   i   such that    d(i)  >  d(i+1)

;Examples:
:*   The number          '''726,169'''   has   '''3'''   rises and   '''2'''   falls,   so it isn't in the sequence.
:*   The number     '''83,548'''    has   '''2'''   rises and   '''2'''   falls,   so it   is   in the sequence.

;Task:
:*   Print the first   '''200'''    numbers in the sequence
:*   Show that the   '''10 millionth'''   (10,000,000th)   number in the sequence is   '''41,909,002'''

;See also:
*   OEIS Sequence  A296712   describes numbers whose digit sequence in base 10 have equal "rises" and "falls".

;Related tasks:
*   Esthetic numbers

Solution:
#include <stdio.h>

/* Check whether a number has an equal amount of rises
 * and falls
 */
int riseEqFall(int num) {
    int rdigit = num % 10;
    int netHeight = 0;
    while (num /= 10) {
        netHeight += ((num % 10) > rdigit) - ((num % 10) < rdigit);
        rdigit = num % 10;
    }
    return netHeight == 0;
}

/* Get the next member of the sequence, in order,
 * starting at 1
 */
int nextNum() {
    static int num = 0;
    do {num++;} while (!riseEqFall(num));
    return num;
}

int main(void) {
    int total, num;

    /* Generate first 200 numbers */
    printf("The first 200 numbers are: \n");
    for (total = 0; total < 200; total++)
        printf("%d ", nextNum());

    /* Generate 10,000,000th number */
    printf("\n\nThe 10,000,000th number is: ");
    for (; total < 10000000; total++) num = nextNum();
    printf("%d\n", num);

    return 0;
}


Numeric error propagation

If   '''f''',   '''a''',   and   '''b'''   are values with uncertainties   sf,   sa,   and   sb,   and   '''c'''   is a constant;
then if   '''f'''   is derived from   '''a''',   '''b''',   and   '''c'''   in the following ways,
then   sf   can be calculated as follows:

:;Addition/Subtraction
:* If   f = a +- c,   or   f = c +- a   then   '''sf = sa'''
:* If   f = a +- b   then   '''sf2 = sa2 + sb2'''

:;Multiplication/Division
:* If   f = ca   or   f = ac       then   '''sf = |csa|'''
:* If   f = ab   or   f = a / b              then   '''sf2 = f2( (sa / a)2 + (sb / b)2)'''

:;Exponentiation
:* If   f = ac   then   '''sf = |fc(sa / a)|'''

Caution:
::This implementation of error propagation does not address issues of dependent and independent values.   It is assumed that   '''a'''   and   '''b'''   are independent and so the formula for multiplication should not be applied to   '''a*a'''   for example.   See   the talk page   for some of the implications of this issue.

;Task details:
# Add an uncertain number type to your language that can support addition, subtraction, multiplication, division, and exponentiation between numbers with an associated error term together with 'normal' floating point numbers without an associated error term. Implement enough functionality to perform the following calculations.
# Given coordinates and their errors:x1 = 100 +- 1.1y1 =  50 +- 1.2x2 = 200 +- 2.2y2 = 100 +- 2.3 if point p1 is located at (x1, y1) and p2 is at (x2, y2); calculate the distance between the two points using the classic Pythagorean formula:   d =    (x1 - x2)2   +   (y1 - y2)2
# Print and display both    '''d'''    and its error.

;References:
* A Guide to Error Propagation B. Keeney, 2005.
* Propagation of uncertainty Wikipedia.

;Related task:
*   [[Quaternion type]]

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

typedef struct{
    double value;
    double delta;
}imprecise;

#define SQR(x) ((x) * (x))
imprecise imprecise_add(imprecise a, imprecise b)
{
    imprecise ret;
    ret.value = a.value + b.value;
    ret.delta = sqrt(SQR(a.delta) + SQR(b.delta));
    return ret;
}

imprecise imprecise_mul(imprecise a, imprecise b)
{
    imprecise ret;
    ret.value = a.value * b.value;
    ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta));
    return ret;
}

imprecise imprecise_div(imprecise a, imprecise b)
{
    imprecise ret;
    ret.value = a.value / b.value;
    ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta)) / SQR(b.value);
    return ret;
}

imprecise imprecise_pow(imprecise a, double c)
{
    imprecise ret;
    ret.value = pow(a.value, c);
    ret.delta = fabs(ret.value * c * a.delta / a.value);
    return ret;
}

char* printImprecise(imprecise val)
{
	char principal[30],error[30],*string,sign[2];
	sign[0] = 241;    /* ASCII code for ±, technical notation for denoting errors */
	sign[1] = 00;

	sprintf(principal,"%f",val.value);
	sprintf(error,"%f",val.delta);

	string = (char*)malloc((strlen(principal)+1+strlen(error)+1)*sizeof(char));

	strcpy(string,principal);
	strcat(string,sign);
	strcat(string,error);

	return string;
}

int main(void) {
    imprecise x1 = {100, 1.1};
    imprecise y1 = {50, 1.2};
    imprecise x2 = {-200, 2.2};
    imprecise y2 = {-100, 2.3};
    imprecise d;

    d = imprecise_pow(imprecise_add(imprecise_pow(imprecise_add(x1, x2), 2),imprecise_pow(imprecise_add(y1, y2), 2)), 0.5);
    printf("Distance, d, between the following points :");
    printf("\n( x1, y1) = ( %s, %s)",printImprecise(x1),printImprecise(y1));
    printf("\n( x2, y2) = ( %s, %s)",printImprecise(x2),printImprecise(y2));
    printf("\nis d = %s", printImprecise(d));
    return 0;
}


Odd word problem

Write a program that solves the odd word problem with the restrictions given below.

;Description:
You are promised an input stream consisting of English letters and punctuations.

It is guaranteed that:
* the words (sequence of consecutive letters) are delimited by one and only one punctuation,
* the stream will begin with a word,
* the words will be at least one letter long,   and
* a full stop (a period, [.]) appears after, and only after, the last word.

;Example:
A stream with six words:
:: what,is,the;meaning,of:life.

The task is to reverse the letters in every other word while leaving punctuations intact, producing:
:: what,si,the;gninaem,of:efil.
while observing the following restrictions:
# Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;
# You '''are not''' to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
# You '''are''' allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.

;Test cases:
Work on both the   "life"   example given above, and also the text:
:: we,are;not,in,kansas;any,more.

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

static int
owp(int odd)
{
        int ch, ret;
        ch = getc(stdin);
        if (!odd) {
                putc(ch, stdout);
                if (ch == EOF || ch == '.')
                        return EOF;
                if (ispunct(ch))
                        return 0;
                owp(odd);
                return 0;
        } else {
                if (ispunct(ch))
                        return ch;
                ret = owp(odd);
                putc(ch, stdout);
                return ret;
        }
}

int
main(int argc, char **argv)
{
        int ch = 1;
        while ((ch = owp(!ch)) != EOF) {
                if (ch)
                        putc(ch, stdout);
                if (ch == '.')
                        break;
        }
        return 0;
}


Old Russian measure of length

Write a program to perform a conversion of the old Russian measures of length to the metric system   (and vice versa).

It is an example of a linear transformation of several variables.

The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
''vershoks'', ''arshins'', ''sazhens'', ''versts'', ''meters'', ''centimeters'' and ''kilometers''.

;Also see:
:*   Old Russian measure of length

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

#define UNITS_LENGTH 13

int main(int argC,char* argV[])
{
	int i,reference;
	char *units[UNITS_LENGTH] = {"kilometer","meter","centimeter","tochka","liniya","diuym","vershok","piad","fut","arshin","sazhen","versta","milia"};
    double factor, values[UNITS_LENGTH] = {1000.0,1.0,0.01,0.000254,0.00254,0.0254,0.04445,0.1778,0.3048,0.7112,2.1336,1066.8,7467.6};

	if(argC!=3)
		printf("Usage : %s followed by length as <value> <unit>");
	else{
		for(i=0;argV[2][i]!=00;i++)
			argV[2][i] = tolower(argV[2][i]);

		for(i=0;i<UNITS_LENGTH;i++){
			if(strstr(argV[2],units[i])!=NULL){
				reference = i;
				factor = atof(argV[1])*values[i];
				break;
			}
		}

		printf("%s %s is equal in length to : \n",argV[1],argV[2]);

		for(i=0;i<UNITS_LENGTH;i++){
			if(i!=reference)
				printf("\n%lf %s",factor/values[i],units[i]);
		}
	}

	return 0;
}


Old lady swallowed a fly

Present a program which emits the lyrics to the song   ''I Knew an Old Lady Who Swallowed a Fly'',   taking advantage of the repetitive structure of the song's lyrics.

This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.

Solution:
#include <stdio.h>
static char const *animals[] = {
    "fly",
    "spider",
    "bird",
    "cat",
    "dog",
    "goat",
    "cow",
    "horse"
};
static char const *verses[]  = {
    "I don't know why she swallowed that fly.\nPerhaps she'll die\n",
    "That wiggled and jiggled and tickled inside her",
    "How absurd, to swallow a bird",
    "Imagine that. She swallowed a cat",
    "What a hog to swallow a dog",
    "She just opened her throat and swallowed that goat",
    "I don't know how she swallowed that cow",
    "She's dead of course"
};

#define LEN(ARR) (sizeof ARR / sizeof *ARR)

int main(void)
{
    for (size_t i = 0; i < LEN(animals); i++) {
        printf("There was an old lady who swallowed a %s\n%s\n", animals[i], verses[i]);
        for (size_t j = i; j > 0 && i < LEN(animals) - 1; j--) {
            printf("She swallowed the %s to catch the %s\n", animals[j], animals[j-1]);
            if (j == 1) {
                printf("%s\n", verses[0]);
            }
        }
    }
}


One of n lines in a file

A method of choosing a line randomly from a file:
::* Without reading the file more than once
::* When substantial parts of the file cannot be held in memory
::* Without knowing how many lines are in the file
Is to:
::* keep the first line of the file as a possible choice, then
::* Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
::* Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
::* ...
::* Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N

::* Return the computed possible choice when no further lines exist in the file.

;Task:
# Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file. The number returned can vary, randomly, in each run.
# Use one_of_n in a ''simulation'' to find what would be the chosen line of a 10-line file simulated 1,000,000 times.
# Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.

Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.

Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling

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

inline int irand(int n)
{
	int r, randmax = RAND_MAX/n * n;
	while ((r = rand()) >= randmax);
	return r / (randmax / n);
}

inline int one_of_n(int n)
{
	int i, r = 0;
	for (i = 1; i < n; i++) if (!irand(i + 1)) r = i;
	return r;
}

int main(void)
{
	int i, r[10] = {0};

	for (i = 0; i < 1000000; i++, r[one_of_n(10)]++);
	for (i = 0; i < 10; i++)
		printf("%d%c", r[i], i == 9 ? '\n':' ');

	return 0;
}


Operator precedence

Operators in C and C++}}

;Task:
Provide a list of   [[wp:order of operations|precedence   and   associativity   of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it.

Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction.

State whether arguments are passed by value or by reference.

Solution: Same as [http://rosettacode.org/wiki/Operator_precedence#C.2B.2B|See C++].


Padovan sequence

The Fibonacci sequence in several ways.
Some are given in the table below, and the referenced video shows some of the geometric
similarities.

::{| class="wikitable"
! Comment !! Padovan !! Fibonacci
|-
|  ||  ||
|-
| Named after. || Richard Padovan || Leonardo of Pisa: Fibonacci
|-
|  ||  ||
|-
| Recurrence initial values. || P(0)=P(1)=P(2)=1 || F(0)=0, F(1)=1
|-
| Recurrence relation. || P(n)=P(n-2)+P(n-3) || F(n)=F(n-1)+F(n-2)
|-
|  ||  ||
|-
| First 10 terms. || 1,1,1,2,2,3,4,5,7,9 || 0,1,1,2,3,5,8,13,21,34
|-
|  ||  ||
|-
| Ratio of successive terms... || Plastic ratio, p || Golden ratio, g
|-
|  || 1.324717957244746025960908854... || 1.6180339887498948482...
|-
| Exact formula of ratios p and q. || ((9+69**.5)/18)**(1/3) + ((9-69**.5)/18)**(1/3) || (1+5**0.5)/2
|-
| Ratio is real root of polynomial. || p: x**3-x-1 || g: x**2-x-1
|-
|  ||  ||
|-
| Spirally tiling the plane using. || Equilateral triangles || Squares
|-
|  ||  ||
|-
| Constants for ... || s= 1.0453567932525329623 || a=5**0.5
|-
| ... Computing by truncation. || P(n)=floor(p**(n-1) / s + .5) || F(n)=floor(g**n / a + .5)
|-
|  ||  ||
|-
| L-System Variables. || A,B,C || A,B
|-
| L-System Start/Axiom. || A || A
|-
| L-System Rules. || A->B,B->C,C->AB || A->B,B->AB
|}

;Task:
* Write a function/method/subroutine to compute successive members of the Padovan series using the recurrence relation.
* Write a function/method/subroutine to compute successive members of the Padovan series using the floor function.
* Show the first twenty terms of the sequence.
* Confirm that the recurrence and floor based functions give the same results for 64 terms,
* Write a function/method/... using the L-system to generate successive strings.
* Show the first 10 strings produced from the L-system
* Confirm that the length of the first 32 strings produced is the Padovan sequence.

Show output here, on this page.

;Ref:
* The Plastic Ratio - Numberphile video.

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

/* Generate (and memoize) the Padovan sequence using
 * the recurrence relationship */
int pRec(int n) {
    static int *memo = NULL;
    static size_t curSize = 0;

    /* grow memoization array when necessary and fill with zeroes */
    if (curSize <= (size_t) n) {
        size_t lastSize = curSize;
        while (curSize <= (size_t) n) curSize += 1024 * sizeof(int);
        memo = realloc(memo, curSize * sizeof(int));
        memset(memo + lastSize, 0, (curSize - lastSize) * sizeof(int));
    }

    /* if we don't have the value for N yet, calculate it */
    if (memo[n] == 0) {
        if (n<=2) memo[n] = 1;
        else memo[n] = pRec(n-2) + pRec(n-3);
    }

    return memo[n];
}

/* Calculate the Nth value of the Padovan sequence
 * using the floor function */
int pFloor(int n) {
    long double p = 1.324717957244746025960908854;
    long double s = 1.0453567932525329623;
    return powl(p, n-1)/s + 0.5;
}

/* Given the previous value for the L-system, generate the
 * next value */
void nextLSystem(const char *prev, char *buf) {
    while (*prev) {
        switch (*prev++) {
            case 'A': *buf++ = 'B'; break;
            case 'B': *buf++ = 'C'; break;
            case 'C': *buf++ = 'A'; *buf++ = 'B'; break;
        }
    }
    *buf = '\0';
}

int main() {
    // 8192 is enough up to P_33.
    #define BUFSZ 8192
    char buf1[BUFSZ], buf2[BUFSZ];
    int i;

    /* Print P_0..P_19 */
    printf("P_0 .. P_19: ");
    for (i=0; i<20; i++) printf("%d ", pRec(i));
    printf("\n");

    /* Check that functions match up to P_63 */
    printf("The floor- and recurrence-based functions ");
    for (i=0; i<64; i++) {
        if (pRec(i) != pFloor(i)) {
            printf("do not match at %d: %d != %d.\n",
                i, pRec(i), pFloor(i));
            break;
        }
    }
    if (i == 64) {
        printf("match from P_0 to P_63.\n");
    }

    /* Show first 10 L-system strings */
    printf("\nThe first 10 L-system strings are:\n");
    for (strcpy(buf1, "A"), i=0; i<10; i++) {
        printf("%s\n", buf1);
        strcpy(buf2, buf1);
        nextLSystem(buf2, buf1);
    }

    /* Check lengths of strings against pFloor up to P_31 */
    printf("\nThe floor- and L-system-based functions ");
    for (strcpy(buf1, "A"), i=0; i<32; i++) {
        if ((int)strlen(buf1) != pFloor(i)) {
            printf("do not match at %d: %d != %d\n",
                i, (int)strlen(buf1), pFloor(i));
            break;
        }
        strcpy(buf2, buf1);
        nextLSystem(buf2, buf1);
    }
    if (i == 32) {
        printf("match from P_0 to P_31.\n");
    }

    return 0;
}


Palindrome dates

Today   ('''2020-02-02''',   at the time of this writing)   happens to be a palindrome,   without the hyphens,   not only for those countries which express their dates in the   '''yyyy-mm-dd'''   format but,   unusually,   also for countries which use the   '''dd-mm-yyyy'''   format.

;Task
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the   '''yyyy-mm-dd'''   format.

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

bool is_palindrome(const char* str) {
    size_t n = strlen(str);
    for (size_t i = 0; i + 1 < n; ++i, --n) {
        if (str[i] != str[n - 1])
            return false;
    }
    return true;
}

int main() {
    time_t timestamp = time(0);
    const int seconds_per_day = 24*60*60;
    int count = 15;
    char str[32];
    printf("Next %d palindrome dates:\n", count);
    for (; count > 0; timestamp += seconds_per_day) {
        struct tm* ptr = gmtime(&timestamp);
        strftime(str, sizeof(str), "%Y%m%d", ptr);
        if (is_palindrome(str)) {
            strftime(str, sizeof(str), "%F", ptr);
            printf("%s\n", str);
            --count;
        }
    }
    return 0;
}


Pangram checker

A pangram is a sentence that contains all the letters of the English alphabet at least once.

For example:   ''The quick brown fox jumps over the lazy dog''.

;Task:
Write a function or method to check a sentence to see if it is a   pangram   (or not)   and show its use.

;Related tasks:
:*   determine if a string has all the same characters
:*   determine if a string has all unique characters

Solution:
#include <stdio.h>

int is_pangram(const char *s)
{
	const char *alpha = ""
		"abcdefghjiklmnopqrstuvwxyz"
		"ABCDEFGHIJKLMNOPQRSTUVWXYZ";

	char ch, wasused[26] = {0};
	int total = 0;

	while ((ch = *s++) != '\0') {
		const char *p;
		int idx;

		if ((p = strchr(alpha, ch)) == NULL)
			continue;

		idx = (p - alpha) % 26;

		total += !wasused[idx];
		wasused[idx] = 1;
		if (total == 26)
			return 1;
	}
	return 0;
}

int main(void)
{
	int i;
	const char *tests[] = {
		"The quick brown fox jumps over the lazy dog.",
		"The qu1ck brown fox jumps over the lazy d0g."
	};

	for (i = 0; i < 2; i++)
		printf("\"%s\" is %sa pangram\n",
			tests[i], is_pangram(tests[i])?"":"not ");
	return 0;
}


Paraffins

This organic chemistry task is essentially to implement a tree enumeration algorithm.

;Task:
Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes).

Paraffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bond.   All bonds for each atom must be used, so it is easiest to think of an alkane as linked carbon atoms forming the "backbone" structure, with adding hydrogen atoms linking the remaining unused bonds.

In a paraffin, one is allowed neither double bonds (two bonds between the same pair of atoms), nor cycles of linked carbons.   So all paraffins with   '''n'''   carbon atoms share the empirical formula     CnH2n+2

But for all   '''n''' >= 4   there are several distinct molecules ("isomers") with the same formula but different structures.

The number of isomers rises rather rapidly when   '''n'''   increases.

In counting isomers it should be borne in mind that the four bond positions on a given carbon atom can be freely interchanged and bonds rotated (including 3-D "out of the paper" rotations when it's being observed on a flat diagram),   so rotations or re-orientations of parts of the molecule (without breaking bonds) do not give different isomers.   So what seem at first to be different molecules may in fact turn out to be different orientations of the same molecule.

;Example:
With   '''n''' = 3   there is only one way of linking the carbons despite the different orientations the molecule can be drawn;   and with   '''n''' = 4   there are two configurations:
:::*   a   straight   chain:     (CH3)(CH2)(CH2)(CH3)
:::*   a        branched chain:       (CH3)(CH(CH3))(CH3)

Due to bond rotations, it doesn't matter which direction the branch points in.

The phenomenon of "stereo-isomerism" (a molecule being different from its mirror image due to the actual 3-D arrangement of bonds) is ignored for the purpose of this task.

The input is the number   '''n'''   of carbon atoms of a molecule (for instance '''17''').

The output is how many different different paraffins there are with   '''n'''   carbon atoms  (for instance   24,894   if   '''n''' = 17).

The sequence of those results is visible in the OEIS entry:
:::   A00602: number of n-node unrooted quartic trees; number of n-carbon alkanes C(n)H(2n+2) ignoring stereoisomers.

The sequence is (the index starts from zero, and represents the number of carbon atoms):

 1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159, 355, 802, 1858, 4347, 10359,
 24894, 60523, 148284, 366319, 910726, 2278658, 5731580, 14490245,
 36797588, 93839412, 240215803, 617105614, 1590507121, 4111846763,
 10660307791, 27711253769, ...

;Extra credit:
Show the paraffins in some way.

A flat 1D representation, with arrays or lists is enough, for instance:

*Main> all_paraffins 1
                        [CCP H H H H]
*Main> all_paraffins 2
                        [BCP (C H H H) (C H H H)]
*Main> all_paraffins 3
                        [CCP H H (C H H H) (C H H H)]
*Main> all_paraffins 4
                        [BCP (C H H (C H H H)) (C H H (C H H H)),
                         CCP H (C H H H) (C H H H) (C H H H)]
*Main> all_paraffins 5
                        [CCP H H (C H H (C H H H)) (C H H (C H H H)),
                         CCP H (C H H H) (C H H H) (C H H (C H H H)),
                         CCP (C H H H) (C H H H) (C H H H) (C H H H)]
*Main> all_paraffins 6
                        [BCP (C H H (C H H (C H H H))) (C H H (C H H (C H H H))),
                         BCP (C H H (C H H (C H H H))) (C H (C H H H) (C H H H)),
                         BCP (C H (C H H H) (C H H H)) (C H (C H H H) (C H H H)),
                         CCP H (C H H H) (C H H (C H H H)) (C H H (C H H H)),
                         CCP (C H H H) (C H H H) (C H H H) (C H H (C H H H))]
Showing a basic 2D ASCII-art representation of the paraffins is better; for instance (molecule names aren't necessary):
       methane          ethane               propane               isobutane

          H              H   H              H   H   H              H   H   H
          |              |   |              |   |   |              |   |   |
      H - C - H      H - C - C - H      H - C - C - C - H      H - C - C - C - H
          |              |   |              |   |   |              |   |   |
          H              H   H              H   H   H              H   |   H
                                                                       |
                                                                   H - C - H
                                                                       |
                                                                       H

;Links:
*   A paper that explains the problem and its solution in a functional language:
http://www.cs.wright.edu/~tkprasad/courses/cs776/paraffins-turner.pdf

*   A Haskell implementation:
https://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs

*   A Scheme implementation:
http://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm

*   A Fortress implementation:         (this site has been closed)
http://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005

Solution:
#include <stdio.h>

#define MAX_N 33	/* max number of tree nodes */
#define BRANCH 4	/* max number of edges a single node can have */

/* The basic idea: a paraffin molecule can be thought as a simple tree
   with each node being a carbon atom.  Counting molecules is thus the
   problem of counting free (unrooted) trees of given number of nodes.

   An unrooted tree needs to be uniquely represented, so we need a way
   to cannonicalize equivalent free trees.  For that, we need to first
   define the cannonical form of rooted trees.  Since rooted trees can
   be constructed by a root node and up to BRANCH rooted subtrees that
   are arranged in some definite order, we can define it thusly:
     * Given the root of a tree, the weight of each of its branches is
       the number of nodes contained in that branch;
     * A cannonical rooted tree would have its direct subtrees ordered
       in descending order by weight;
     * In case multiple subtrees are the same weight, they are ordered
       by some unstated, but definite, order (this code doesn't really
       care what the ordering is; it only counts the number of choices
       in such a case, not enumerating individual trees.)

   A rooted tree of N nodes can then be constructed by adding smaller,
   cannonical rooted trees to a root node, such that:
     * Each subtree has fewer than BRANCH branches (since it must have
       an empty slot for an edge to connect to the new root);
     * Weight of those subtrees added later are no higher than earlier
       ones;
     * Their weight total N-1.
   A rooted tree so constructed would be itself cannonical.

   For an unrooted tree, we can define the radius of any of its nodes:
   it's the maximum weight of any of the subtrees if this node is used
   as the root.  A node is the center of a tree if it has the smallest
   radius among all the nodes.  A tree can have either one or two such
   centers; if two, they must be adjacent (cf. Knuth, tAoCP 2.3.4.4).

   An important fact is that, a node in a tree is its sole center, IFF
   its radius times 2 is no greater than the sum of the weights of all
   branches (ibid).  While we are making rooted trees, we can add such
   trees encountered to the count of cannonical unrooted trees.

   A bi-centered unrooted tree with N nodes can be made by joining two
   trees, each with N/2 nodes and fewer than BRANCH subtrees, at root.
   The pair must be ordered in aforementioned implicit way so that the
   product is cannonical. */

typedef unsigned long long xint;
#define FMT "llu"

xint rooted[MAX_N] = {1, 1, 0};
xint unrooted[MAX_N] = {1, 1, 0};

/* choose k out of m possible values; chosen values may repeat, but the
   ordering of them does not matter.  It's binomial(m + k - 1, k) */
xint choose(xint m, xint k)
{
	xint i, r;

	if (k == 1) return m;
	for (r = m, i = 1; i < k; i++)
		r = r * (m + i) / (i + 1);
	return r;
}

/* constructing rooted trees of BR branches at root, with at most
   N radius, and SUM nodes in the partial tree already built. It's
   recursive, and CNT and L carry down the number of combinations
   and the tree radius already encountered. */
void tree(xint br, xint n, xint cnt, xint sum, xint l)
{
	xint b, c, m, s;

	for (b = br + 1; b <= BRANCH; b++) {
		s = sum + (b - br) * n;
		if (s >= MAX_N) return;

		/* First B of BR branches are all of weight n; the
		   rest are at most of weight N-1 */
		c = choose(rooted[n], b - br) * cnt;

		/* This partial tree is singly centered as is */
		if (l * 2 < s) unrooted[s] += c;

		/* Trees saturate at root can't be used as building
		   blocks for larger trees, so forget them */
		if (b == BRANCH) return;
		rooted[s] += c;

		/* Build the rest of the branches */
		for (m = n; --m; ) tree(b, m, c, s, l);
	}
}

void bicenter(int s)
{
	if (s & 1) return;

	/* Pick two of the half-size building blocks, allowing
	   repetition. */
	unrooted[s] += rooted[s/2] * (rooted[s/2] + 1) / 2;
}

int main()
{
	xint n;
	for (n = 1; n < MAX_N; n++) {
		tree(0, n, 1, 1, n);
		bicenter(n);
		printf("%"FMT": %"FMT"\n", n, unrooted[n]);
	}

	return 0;
}


Parsing/RPN calculator algorithm

Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed ''as a table''.

* Assume an input of a correct, space separated, string of tokens of an RPN expression
* Test with the RPN expression generated from the   [[Parsing/Shunting-yard algorithm]]   task:
         3 4 2 * 1 5 - 2 3 ^ ^ / +
* Print or display the output here

;Notes:
*    '''^'''    means exponentiation in the expression above.
*    '''/'''    means division.

;See also:
*   [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression.
*   Several solutions to [[24 game/Solve]] make use of RPN evaluators (although tracing how they work is not a part of that task).
*   [[Parsing/RPN to infix conversion]].
*   [[Arithmetic evaluation]].

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

void die(const char *msg)
{
	fprintf(stderr, "%s", msg);
	abort();
}

#define MAX_D 256
double stack[MAX_D];
int depth;

void push(double v)
{
	if (depth >= MAX_D) die("stack overflow\n");
	stack[depth++] = v;
}

double pop()
{
	if (!depth) die("stack underflow\n");
	return stack[--depth];
}

double rpn(char *s)
{
	double a, b;
	int i;
	char *e, *w = " \t\n\r\f";

	for (s = strtok(s, w); s; s = strtok(0, w)) {
		a = strtod(s, &e);
		if (e > s)		printf(" :"), push(a);
#define binop(x) printf("%c:", *s), b = pop(), a = pop(), push(x)
		else if (*s == '+')	binop(a + b);
		else if (*s == '-')	binop(a - b);
		else if (*s == '*')	binop(a * b);
		else if (*s == '/')	binop(a / b);
		else if (*s == '^')	binop(pow(a, b));
#undef binop
		else {
			fprintf(stderr, "'%c': ", *s);
			die("unknown oeprator\n");
		}
		for (i = depth; i-- || 0 * putchar('\n'); )
			printf(" %g", stack[i]);
	}

	if (depth != 1) die("stack leftover\n");

	return pop();
}

int main(void)
{
	char s[] = " 3 4 2 * 1 5 - 2 3 ^ ^ / + ";
	printf("%g\n", rpn(s));
	return 0;
}


Parsing/RPN to infix conversion

Create a program that takes an infix notation.

* Assume an input of a correct, space separated, string of tokens
* Generate a space separated output string representing the same expression in infix notation
* Show how the major datastructure of your algorithm changes with each new token parsed.
* Test with the following input RPN strings then print and display the output here.
:::::{| class="wikitable"
! RPN input !! sample output
|- || align="center"
| 3 4 2 * 1 5 - 2 3 ^ ^ / +|| 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
|- || align="center"
| 1 2 + 3 4 + ^ 5 6 + ^|| ( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )
|}

* Operator precedence and operator associativity is given in this table:
::::::::{| class="wikitable"

! operator !! associativity !! operation
|- || align="center"
|                    ^   ||  4  ||  right  ||  exponentiation
|- || align="center"
|                    *   ||  3  ||   left  ||  multiplication
|- || align="center"
|                    /   ||  3  ||   left  ||     division
|- || align="center"
|                    +   ||  2  ||   left  ||     addition
|- || align="center"
|                    -   ||  2  ||   left  ||   subtraction
|}

;See also:
*   [[Parsing/Shunting-yard algorithm]]   for a method of generating an RPN from an infix expression.
*   [[Parsing/RPN calculator algorithm]]   for a method of calculating a final value from this output RPN expression.
*   Postfix to infix   from the RubyQuiz site.

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

char** components;
int counter = 0;

typedef struct elem{
	char data[10];
	struct elem* left;
	struct elem* right;
}node;

typedef node* tree;

int precedenceCheck(char oper1,char oper2){
	return (oper1==oper2)? 0:(oper1=='^')? 1:(oper2=='^')? 2:(oper1=='/')? 1:(oper2=='/')? 2:(oper1=='*')? 1:(oper2=='*')? 2:(oper1=='+')? 1:(oper2=='+')? 2:(oper1=='-')? 1:2;
}

int isOperator(char c){
	return (c=='+'||c=='-'||c=='*'||c=='/'||c=='^');
}

void inorder(tree t){
	if(t!=NULL){
		if(t->left!=NULL && isOperator(t->left->data[0])==1 && (precedenceCheck(t->data[0],t->left->data[0])==1 || (precedenceCheck(t->data[0],t->left->data[0])==0 && t->data[0]=='^'))){
			printf("(");
			inorder(t->left);
			printf(")");
		}
		else
			inorder(t->left);

		printf(" %s ",t->data);

		if(t->right!=NULL && isOperator(t->right->data[0])==1 && (precedenceCheck(t->data[0],t->right->data[0])==1 || (precedenceCheck(t->data[0],t->right->data[0])==0 && t->data[0]!='^'))){
			printf("(");
			inorder(t->right);
			printf(")");
		}
		else
			inorder(t->right);
	}
}

char* getNextString(){
	if(counter<0){
		printf("\nInvalid RPN !");
		exit(0);
	}
	return components[counter--];
}

tree buildTree(char* obj,char* trace){
	tree t = (tree)malloc(sizeof(node));

	strcpy(t->data,obj);

	t->right = (isOperator(obj[0])==1)?buildTree(getNextString(),trace):NULL;
	t->left = (isOperator(obj[0])==1)?buildTree(getNextString(),trace):NULL;

	if(trace!=NULL){
			printf("\n");
			inorder(t);
	}

	return t;
}

int checkRPN(){
	int i, operSum = 0, numberSum = 0;

	if(isOperator(components[counter][0])==0)
		return 0;

	for(i=0;i<=counter;i++)
		(isOperator(components[i][0])==1)?operSum++:numberSum++;

	return (numberSum - operSum == 1);
}

void buildStack(char* str){
	int i;
	char* token;

	for(i=0;str[i]!=00;i++)
		if(str[i]==' ')
			counter++;

	components = (char**)malloc((counter + 1)*sizeof(char*));

	token = strtok(str," ");

	i = 0;

	while(token!=NULL){
		components[i] = (char*)malloc(strlen(token)*sizeof(char));
		strcpy(components[i],token);
		token = strtok(NULL," ");
		i++;
	}
}

int main(int argC,char* argV[]){
	int i;
	tree t;

	if(argC==1)
		printf("Usage : %s <RPN expression enclosed by quotes> <optional parameter to trace the build process>",argV[0]);
	else{
		buildStack(argV[1]);

		if(checkRPN()==0){
			printf("\nInvalid RPN !");
			return 0;
		}

		t = buildTree(getNextString(),argV[2]);

		printf("\nFinal infix expression : ");
		inorder(t);
	}

	return 0;
}


Parsing/Shunting-yard algorithm

Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.

* Assume an input of a correct, space separated, string of tokens representing an infix expression
* Generate a space separated output string representing the RPN
* Test with the input string:
::::  3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
* print and display the output here.
* Operator precedence is given in this table:
:{| class="wikitable"

! operator !! associativity !! operation
|- || align="center"
|                     ^   ||  4  ||  right  ||  exponentiation
|- || align="center"
|                     *   ||  3  ||  left   ||  multiplication
|- || align="center"
|                     /   ||  3  ||  left   ||  division
|- || align="center"
|                     +   ||  2  ||  left   ||  addition
|- || align="center"
|                     -   ||  2  ||  left   ||  subtraction
|}

;Extra credit
Add extra text explaining the actions and an optional comment for the action on receipt of each token.

;Note
The handling of functions and arguments is not required.

;See also:
* [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression.
* [[Parsing/RPN to infix conversion]].

Solution:
#include <sys/types.h>
#include <regex.h>
#include <stdio.h>

typedef struct {
	const char *s;
	int len, prec, assoc;
} str_tok_t;

typedef struct {
	const char * str;
	int assoc, prec;
	regex_t re;
} pat_t;

enum assoc { A_NONE, A_L, A_R };
pat_t pat_eos = {"", A_NONE, 0};

pat_t pat_ops[] = {
	{"^\\)",	A_NONE, -1},
	{"^\\*\\*",	A_R, 3},
	{"^\\^",	A_R, 3},
	{"^\\*",	A_L, 2},
	{"^/",		A_L, 2},
	{"^\\+",	A_L, 1},
	{"^-",		A_L, 1},
	{0}
};

pat_t pat_arg[] = {
	{"^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?"},
	{"^[a-zA-Z_][a-zA-Z_0-9]*"},
	{"^\\(", A_L, -1},
	{0}
};

str_tok_t stack[256]; /* assume these are big enough */
str_tok_t queue[256];
int l_queue, l_stack;
#define qpush(x) queue[l_queue++] = x
#define spush(x) stack[l_stack++] = x
#define spop()   stack[--l_stack]

void display(const char *s)
{
	int i;
	printf("\033[1;1H\033[JText | %s", s);
	printf("\nStack| ");
	for (i = 0; i < l_stack; i++)
		printf("%.*s ", stack[i].len, stack[i].s); // uses C99 format strings
	printf("\nQueue| ");
	for (i = 0; i < l_queue; i++)
		printf("%.*s ", queue[i].len, queue[i].s);
	puts("\n\n<press enter>");
	getchar();
}

int prec_booster;

#define fail(s1, s2) {fprintf(stderr, "[Error %s] %s\n", s1, s2); return 0;}

int init(void)
{
	int i;
	pat_t *p;

	for (i = 0, p = pat_ops; p[i].str; i++)
		if (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))
			fail("comp", p[i].str);

	for (i = 0, p = pat_arg; p[i].str; i++)
		if (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))
			fail("comp", p[i].str);

	return 1;
}

pat_t* match(const char *s, pat_t *p, str_tok_t * t, const char **e)
{
	int i;
	regmatch_t m;

	while (*s == ' ') s++;
	*e = s;

	if (!*s) return &pat_eos;

	for (i = 0; p[i].str; i++) {
		if (regexec(&(p[i].re), s, 1, &m, REG_NOTEOL))
			continue;
		t->s = s;
		*e = s + (t->len = m.rm_eo - m.rm_so);
		return p + i;
	}
	return 0;
}

int parse(const char *s) {
	pat_t *p;
	str_tok_t *t, tok;

	prec_booster = l_queue = l_stack = 0;
	display(s);
	while (*s) {
		p = match(s, pat_arg, &tok, &s);
		if (!p || p == &pat_eos) fail("parse arg", s);

		/* Odd logic here. Don't actually stack the parens: don't need to. */
		if (p->prec == -1) {
			prec_booster += 100;
			continue;
		}
		qpush(tok);
		display(s);

re_op:		p = match(s, pat_ops, &tok, &s);
		if (!p) fail("parse op", s);

		tok.assoc = p->assoc;
		tok.prec = p->prec;

		if (p->prec > 0)
			tok.prec = p->prec + prec_booster;
		else if (p->prec == -1) {
			if (prec_booster < 100)
				fail("unmatched )", s);
			tok.prec = prec_booster;
		}

		while (l_stack) {
			t = stack + l_stack - 1;
			if (!(t->prec == tok.prec && t->assoc == A_L)
					&& t->prec <= tok.prec)
				break;
			qpush(spop());
			display(s);
		}

		if (p->prec == -1) {
			prec_booster -= 100;
			goto re_op;
		}

		if (!p->prec) {
			display(s);
			if (prec_booster)
				fail("unmatched (", s);
			return 1;
		}

		spush(tok);
		display(s);
	}

	if (p->prec > 0)
		fail("unexpected eol", s);

	return 1;
}

int main()
{
	int i;
	const char *tests[] = {
		"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3",	/* RC mandated: OK */
		"123",					/* OK */
		"3+4 * 2 / ( 1 - 5 ) ^ 2 ^ 3.14",	/* OK */
		"(((((((1+2+3**(4 + 5))))))",		/* bad parens */
		"a^(b + c/d * .1e5)!",			/* unknown op */
		"(1**2)**3",				/* OK */
		"2 + 2 *",				/* unexpected eol */
		0
	};

	if (!init()) return 1;
	for (i = 0; tests[i]; i++) {
		printf("Testing string `%s'   <enter>\n", tests[i]);
		getchar();

		printf("string `%s': %s\n\n", tests[i],
			parse(tests[i]) ? "Ok" : "Error");
	}

	return 0;
}


Pascal's triangle/Puzzle

This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers.

           [ 151]
          [  ][  ]
        [40][  ][  ]
      [  ][  ][  ][  ]
    [ X][11][ Y][ 4][ Z]

Each brick of the pyramid is the sum of the two bricks situated below it.
Of the three missing numbers at the base of the pyramid,
the middle one is the sum of the other two (that is, Y = X + Z).

;Task:
Write a program to find a solution to this puzzle.

Solution:
/* Pascal's pyramid solver
 *
 *               [top]
 *            [   ] [   ]
 *         [mid] [   ] [   ]
 *      [   ] [   ] [   ] [   ]
 *   [ x ] [ a ] [ y ] [ b ] [ z ]
 *             x + z = y
 *
 * This solution makes use of a little bit of mathematical observation,
 * such as the fact that top = 4(a+b) + 7(x+z) and mid = 2x + 2a + z.
 */

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

void pascal(int a, int b, int mid, int top, int* x, int* y, int* z)
{
    double ytemp = (top - 4 * (a + b)) / 7.;
    if(fmod(ytemp, 1.) >= 0.0001)
    {
        x = 0;
        return;
    }
    *y = ytemp;
    *x = mid - 2 * a - *y;
    *z = *y - *x;
}
int main()
{
    int a = 11, b = 4, mid = 40, top = 151;
    int x, y, z;
    pascal(a, b, mid, top, &x, &y, &z);
    if(x != 0)
        printf("x: %d, y: %d, z: %d\n", x, y, z);
    else printf("No solution\n");

    return 0;
}


Pascal matrix generation

A pascal matrix is a two-dimensional square matrix holding numbers from   binomial coefficients   and which can be shown as    nCr.

Shown below are truncated   5-by-5   matrices   M[i, j]   for   i,j   in range   0..4.

A Pascal upper-triangular matrix that is populated with   jCi:

[[1, 1, 1, 1, 1],
 [0, 1, 2, 3, 4],
 [0, 0, 1, 3, 6],
 [0, 0, 0, 1, 4],
 [0, 0, 0, 0, 1]]

A Pascal lower-triangular matrix that is populated with   iCj   (the transpose of the upper-triangular matrix):

[[1, 0, 0, 0, 0],
 [1, 1, 0, 0, 0],
 [1, 2, 1, 0, 0],
 [1, 3, 3, 1, 0],
 [1, 4, 6, 4, 1]]

A Pascal symmetric matrix that is populated with   i+jCi:

[[1, 1, 1, 1, 1],
 [1, 2, 3, 4, 5],
 [1, 3, 6, 10, 15],
 [1, 4, 10, 20, 35],
 [1, 5, 15, 35, 70]]

;Task:
Write functions capable of generating each of the three forms of   n-by-n   matrices.

Use those functions to display upper, lower, and symmetric Pascal   5-by-5   matrices on this page.

The output should distinguish between different matrices and the rows of each matrix   (no showing a list of 25 numbers assuming the reader should split it into rows).

;Note:
The   [[Cholesky decomposition]]   of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.

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

void pascal_low(int **mat, int n) {
    int i, j;

    for (i = 0; i < n; ++i)
        for (j = 0; j < n; ++j)
            if (i < j)
                mat[i][j] = 0;
            else if (i == j || j == 0)
                mat[i][j] = 1;
            else
                mat[i][j] = mat[i - 1][j - 1] + mat[i - 1][j];
}

void pascal_upp(int **mat, int n) {
    int i, j;

    for (i = 0; i < n; ++i)
        for (j = 0; j < n; ++j)
            if (i > j)
                mat[i][j] = 0;
            else if (i == j || i == 0)
                mat[i][j] = 1;
            else
                mat[i][j] = mat[i - 1][j - 1] + mat[i][j - 1];
}

void pascal_sym(int **mat, int n) {
    int i, j;

    for (i = 0; i < n; ++i)
        for (j = 0; j < n; ++j)
            if (i == 0 || j == 0)
                mat[i][j] = 1;
            else
                mat[i][j] = mat[i - 1][j] + mat[i][j - 1];
}

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

    /* Input size of the matrix */
    n = 5;

    /* Matrix allocation */
    mat = calloc(n, sizeof(int *));
    for (i = 0; i < n; ++i)
        mat[i] = calloc(n, sizeof(int));

    /* Matrix computation */
    printf("=== Pascal upper matrix ===\n");
    pascal_upp(mat, n);
    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++)
            printf("%4d%c", mat[i][j], j < n - 1 ? ' ' : '\n');

    printf("=== Pascal lower matrix ===\n");
    pascal_low(mat, n);
    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++)
            printf("%4d%c", mat[i][j], j < n - 1 ? ' ' : '\n');

    printf("=== Pascal symmetric matrix ===\n");
    pascal_sym(mat, n);
    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++)
            printf("%4d%c", mat[i][j], j < n - 1 ? ' ' : '\n');

    return 0;
}


Password generator

Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
          lower-case letters:  a --> z
          upper-case letters:  A --> Z
                      digits:  0 --> 9
  other printable characters:  !"#$%&'()*+,-./:;<=>?@[]^_{|}~
  (the above character list excludes white-space, backslash and grave)

The generated password(s) must include   ''at least one''   (of each of the four groups):
    lower-case letter,
    upper-case letter,
    digit  (numeral),   and
    one  "other"  character.

The user must be able to specify the password length and the number of passwords to generate.

The passwords should be displayed or written to a file, one per line.

The randomness should be from a system source or library.

The program should implement a help option or button which should describe the program and options when invoked.

You may also allow the user to specify a seed value, and give the option of excluding visually similar characters.

For example:            Il1     O0     5S     2Z            where the characters are:
::::*   capital eye, lowercase ell, the digit one
::::*   capital oh, the digit zero
::::*   the digit five, capital ess
::::*   the digit two, capital zee

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

#define DEFAULT_LENGTH 4
#define DEFAULT_COUNT 1

char* symbols[] = {"ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", "0123456789", "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~"};
int length = DEFAULT_LENGTH;
int count = DEFAULT_COUNT;
unsigned seed;
char exSymbols = 0;

void GetPassword () {
    //create an array of values that determine the number of characters from each category
    int lengths[4] = {1, 1, 1, 1};
    int count = 4;
    while (count < length) {
        lengths[rand()%4]++;
        count++;
    }

    //loop through the array of lengths and set the characters in password
    char password[length + 1];
    for (int i = 0; i < length; ) {
        //pick which string to read from
        int str = rand()%4;
        if (!lengths[str])continue;   //if the number of characters for that string have been reached, continue to the next interation

        char c;
        switch (str) {
            case 2:
                c = symbols[str][rand()%10];
                while (exSymbols && (c == 'I' || c == 'l' || c == '1' || c == 'O' || c == '0' || c == '5' || c == 'S' || c == '2' || c == 'Z'))
                    c = symbols[str][rand()%10];
                password[i] = c;
            break;

            case 3:
                c = symbols[str][rand()%30];
                while (exSymbols && (c == 'I' || c == 'l' || c == '1' || c == 'O' || c == '0' || c == '5' || c == 'S' || c == '2' || c == 'Z'))
                    c = symbols[str][rand()%30];
                password[i] = c;
            break;

            default:
                c = symbols[str][rand()%26];
                while (exSymbols && (c == 'I' || c == 'l' || c == '1' || c == 'O' || c == '0' || c == '5' || c == 'S' || c == '2' || c == 'Z'))
                    c = symbols[str][rand()%26];
                password[i] = c;
            break;
        }

        i++;
        lengths[str]--;
    }

    password [length] = '\0';
    printf ("%s\n", password);
}

int main (int argc, char* argv[]) {
    seed = (unsigned)time(NULL);

    //handle user input from the command line
    for (int i = 1; i < argc; i++) {
        switch (argv[i][1]) {
            case 'l':
                if (sscanf (argv[i+1], "%d", &length) != 1) {
                    puts ("Unrecognized input. Syntax: -l [integer]");
                    return -1;
                }

                if (length < 4) {
                    puts ("Password length must be at least 4 characters.");
                    return -1;
                }
                i++;
            break;

            case 'c':
                if (sscanf (argv[i+1], "%d", &count) != 1) {
                    puts ("Unrecognized input. Syntax: -c [integer]");
                    return -1;
                }

                if (count <= 0) {
                    puts ("Count must be at least 1.");
                    return -1;
                }
                i++;
            break;

            case 's':
                if (sscanf (argv[i+1], "%d", &seed) != 1) {
                    puts ("Unrecognized input. Syntax: -s [integer]");
                    return -1;
                }
                i++;
            break;

            case 'e':
                exSymbols = 1;
            break;

            default:
                help:
                printf ("Help:\nThis program generates a random password.\n"
                "Commands:"
                   "Set password length: -l [integer]\n"
                   "Set password count: -c [integer]\n"
                   "Set seed: -s [integer]\n"
                   "Exclude similiar characters: -e\n"
                   "Display help: -h");
                return 0;
            break;
        }
    }

    srand (seed);

    for (int i = 0; i < count; i++)
        GetPassword();

    return 0;
}


Pathological floating point problems

Most programmers are familiar with the inexactness of floating point calculations in a binary processor.

The classic example being:

0.1 + 0.2 =  0.30000000000000004

In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding.

There are pathological problems however, where seemingly simple, straight-forward calculations are extremely sensitive to even tiny amounts of imprecision.

This task's purpose is to show how your language deals with such classes of problems.

'''A sequence that seems to converge to a wrong limit.'''

Consider the sequence:
::::::   v1 =  2
::::::   v2 = -4
::::::   vn = 111   -   1130   /   vn-1   +   3000  /   (vn-1 * vn-2)

As   '''n'''   grows larger, the series should converge to   '''6'''   but small amounts of error will cause it to approach   '''100'''.

;Task 1:
Display the values of the sequence where   n =   3, 4, 5, 6, 7, 8, 20, 30, 50 & 100   to at least '''16''' decimal places.

    n = 3     18.5
    n = 4      9.378378
    n = 5      7.801153
    n = 6      7.154414
    n = 7      6.806785
    n = 8      6.5926328
    n = 20     6.0435521101892689
    n = 30     6.006786093031205758530554
    n = 50     6.0001758466271871889456140207471954695237
    n = 100    6.000000019319477929104086803403585715024350675436952458072592750856521767230266

;Task 2:
'''The Chaotic Bank Society'''   is offering a new investment account to their customers.

You first deposit   $e - 1   where   e   is   2.7182818...   the base of natural logarithms.

After each year, your account balance will be multiplied by the number of years that have passed, and $1 in service charges will be removed.

So ...
::* after 1 year, your balance will be multiplied by 1 and $1 will be removed for service charges.
::* after 2 years your balance will be doubled and $1 removed.
::* after 3 years your balance will be tripled and $1 removed.
::*  ...
::* after 10 years, multiplied by 10 and $1 removed,  and so on.

What will your balance be after   25   years?
    Starting balance: $e-1
    Balance = (Balance * year) - 1 for 25 years
    Balance after 25 years: $0.0399387296732302

;Task 3, extra credit:
'''Siegfried Rump's example.'''   Consider the following function, designed by Siegfried Rump in 1988.
::::::   f(a,b) = 333.75b6 + a2( 11a2b2 - b6 - 121b4 - 2 ) + 5.5b8 + a/(2b)
::::::  compute    f(a,b)    where    a=77617.0    and    b=33096.0
::::::   f(77617.0, 33096.0)   =   -0.827396059946821

Demonstrate how to solve at least one of the first two problems, or both, and the third if you're feeling particularly jaunty.

;See also;
*   Floating-Point Arithmetic   Section 1.3.2 Difficult problems.

Solution:
Such exercises are very good examples that just because you have a nice library doesn't mean you won't get the wrong results. I was over-ambitious and the result is I have been wrangling with the Chaotic Bank task for a long time now, I will come back to it later but for now here are the first two cases, the "trivial" one of 0.1 + 0.2 and the Pathological series :
===First two tasks===


Pentagram

A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees.

;Task:
Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and background. For the fill it should be assumed that all points inside the triangles and the pentagon are inside the pentagram.

;See also
* Angle sum of a pentagram

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

#define pi M_PI

int main(){

	char colourNames[][14] = { "BLACK", "BLUE", "GREEN", "CYAN", "RED", "MAGENTA", "BROWN", "LIGHTGRAY", "DARKGRAY",
              "LIGHTBLUE", "LIGHTGREEN", "LIGHTCYAN", "LIGHTRED", "LIGHTMAGENTA", "YELLOW", "WHITE" };

	int stroke=0,fill=0,back=0,i;

	double centerX = 300,centerY = 300,coreSide,armLength,pentaLength;

	printf("Enter core pentagon side length : ");
	scanf("%lf",&coreSide);

	printf("Enter pentagram arm length : ");
	scanf("%lf",&armLength);

	printf("Available colours are :\n");

	for(i=0;i<16;i++){
		printf("%d. %s\t",i+1,colourNames[i]);
		if((i+1) % 3 == 0){
			printf("\n");
		}
	}

	while(stroke==fill && fill==back){
		printf("\nEnter three diffrenet options for stroke, fill and background : ");
		scanf("%d%d%d",&stroke,&fill,&back);
	}

	pentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);

	initwindow(2*centerX,2*centerY,"Pentagram");

	setcolor(stroke-1);

	setfillstyle(SOLID_FILL,back-1);

	bar(0,0,2*centerX,2*centerY);

	floodfill(centerX,centerY,back-1);

	setfillstyle(SOLID_FILL,fill-1);

	for(i=0;i<5;i++){
		line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));
		line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));
		line(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));

		floodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);
	}

	floodfill(centerX,centerY,stroke-1);

	getch();

	closegraph();
}


Perfect shuffle

A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on:

::: 7 8 9 J Q K-7  8  9  J  Q  K-7 J 8 Q 9 K

When you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles:

::::: {| style="border-spacing:0.5em 0;border-collapse:separate;margin:0 1em;text-align:right"
|-
| ''original:'' ||
1
2
3
4
5
6
7
8
|-
| ''after 1st shuffle:'' ||
1
5
2
6
3
7
4
8
|-
| ''after 2nd shuffle:'' ||
1
3
5
7
2
4
6
8
|-
| ''after 3rd shuffle:'' ||
1
2
3
4
5
6
7
8
|}

'''''The Task'''''

# Write a function that can perform a perfect shuffle on an even-sized list of values.
# Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below.
#* You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck.
#* Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases.
'''''Test Cases'''''

::::: {| class="wikitable"
|-
! input ''(deck size)'' !! output ''(number of shuffles required)''
|-
| 8 || 3
|-
| 24 || 11
|-
| 52 || 8
|-
| 100 || 30
|-
| 1020 || 1018
|-
| 1024 || 10
|-
| 10000 || 300
|}

Solution:
/* ===> INCLUDES <============================================================*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

/* ===> CONSTANTS <===========================================================*/
#define N_DECKS 7
const int kDecks[N_DECKS] = { 8, 24, 52, 100, 1020, 1024, 10000 };

/* ===> FUNCTION PROTOTYPES <=================================================*/
int CreateDeck( int **deck, int nCards );
void InitDeck( int *deck, int nCards );
int DuplicateDeck( int **dest, const int *orig, int nCards );
int InitedDeck( int *deck, int nCards );
int ShuffleDeck( int *deck, int nCards );
void FreeDeck( int **deck );

/* ===> FUNCTION DEFINITIONS <================================================*/

int main() {
    int i, nCards, nShuffles;
    int *deck = NULL;

    for( i=0; i<N_DECKS; ++i ) {
        nCards = kDecks[i];

        if( !CreateDeck(&deck,nCards) ) {
            fprintf( stderr, "Error: malloc() failed!\n" );
            return 1;
        }

        InitDeck( deck, nCards );
        nShuffles = 0;

        do {
            ShuffleDeck( deck, nCards );
            ++nShuffles;
        } while( !InitedDeck(deck,nCards) );

        printf( "Cards count: %d, shuffles required: %d.\n", nCards, nShuffles );

        FreeDeck( &deck );
    }

    return 0;
}

int CreateDeck( int **deck, int nCards ) {
    int *tmp = NULL;

    if( deck != NULL )
        tmp = malloc( nCards*sizeof(*tmp) );

    return tmp!=NULL ? (*deck=tmp)!=NULL : 0; /* (?success) (:failure) */
}

void InitDeck( int *deck, int nCards ) {
    if( deck != NULL ) {
        int i;

        for( i=0; i<nCards; ++i )
            deck[i] = i;
    }
}

int DuplicateDeck( int **dest, const int *orig, int nCards ) {
    if( orig != NULL && CreateDeck(dest,nCards) ) {
        memcpy( *dest, orig, nCards*sizeof(*orig) );
        return 1; /* success */
    }
    else {
        return 0; /* failure */
    }
}

int InitedDeck( int *deck, int nCards ) {
    int i;

    for( i=0; i<nCards; ++i )
        if( deck[i] != i )
            return 0; /* not inited */

    return 1; /* inited */
}

int ShuffleDeck( int *deck, int nCards ) {
    int *copy = NULL;

    if( DuplicateDeck(&copy,deck,nCards) ) {
        int i, j;

        for( i=j=0; i<nCards/2; ++i, j+=2 ) {
            deck[j] = copy[i];
            deck[j+1] = copy[i+nCards/2];
        }

        FreeDeck( &copy );
        return 1; /* success */
    }
    else {
        return 0; /* failure */
    }
}

void FreeDeck( int **deck ) {
    if( *deck != NULL ) {
        free( *deck );
        *deck = NULL;
    }
}


Perfect totient numbers

Generate and show here, the first twenty Perfect totient numbers.

;Related task:
::*   [[Totient function]]

;Also see:
::*   the OEIS      entry for   perfect totient numbers.
::*   mrob            list of the first 54

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

long totient(long n){
	long tot = n,i;

	for(i=2;i*i<=n;i+=2){
		if(n%i==0){
			while(n%i==0)
				n/=i;
			tot-=tot/i;
		}

		if(i==2)
			i=1;
	}

	if(n>1)
		tot-=tot/n;

	return tot;
}

long* perfectTotients(long n){
	long *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot;

	for(m=1;count<n;m++){
		 tot = m;
		 sum = 0;
        while(tot != 1){
            tot = totient(tot);
            sum += tot;
        }
        if(sum == m)
			ptList[count++] = m;
        }

		return ptList;
}

long main(long argC, char* argV[])
{
	long *ptList,i,n;

	if(argC!=2)
		printf("Usage : %s <number of perfect Totient numbers required>",argV[0]);
	else{
		n = atoi(argV[1]);

		ptList = perfectTotients(n);

		printf("The first %d perfect Totient numbers are : \n[",n);

		for(i=0;i<n;i++)
			printf(" %d,",ptList[i]);
		printf("\b]");
	}

	return 0;
}


Periodic table

Display the row and column in the periodic table of the given atomic number.

;The periodic table:
Let us consider the following periodic table representation.

     __________________________________________________________________________
    |   1   2   3   4   5   6   7   8   9   10  11  12  13  14  15  16  17  18 |
    |                                                                          |
    |1  H                                                                   He |
    |                                                                          |
    |2  Li  Be                                          B   C   N   O   F   Ne |
    |                                                                          |
    |3  Na  Mg                                          Al  Si  P   S   Cl  Ar |
    |                                                                          |
    |4  K   Ca  Sc  Ti  V   Cr  Mn  Fe  Co  Ni  Cu  Zn  Ga  Ge  As  Se  Br  Kr |
    |                                                                          |
    |5  Rb  Sr  Y   Zr  Nb  Mo  Tc  Ru  Rh  Pd  Ag  Cd  In  Sn  Sb  Te  I   Xe |
    |                                                                          |
    |6  Cs  Ba  *   Hf  Ta  W   Re  Os  Ir  Pt  Au  Hg  Tl  Pb  Bi  Po  At  Rn |
    |                                                                          |
    |7  Fr  Ra  deg   Rf  Db  Sg  Bh  Hs  Mt  Ds  Rg  Cn  Nh  Fl  Mc  Lv  Ts  Og |
    |__________________________________________________________________________|
    |                                                                          |
    |                                                                          |
    |8  Lantanoidi* La  Ce  Pr  Nd  Pm  Sm  Eu  Gd  Tb  Dy  Ho  Er  Tm  Yb  Lu |
    |                                                                          |
    |9   Aktinoidideg Ak  Th  Pa  U   Np  Pu  Am  Cm  Bk  Cf  Es  Fm  Md  No  Lr |
    |__________________________________________________________________________|

;Example test cases;

*   1 -> 1 1
*   2 -> 1 18
*   29 -> 4 11
*   42 -> 5 6
*   57 -> 8 4
*   58 -> 8 5
*   72 -> 6 4
*   89 -> 9 4

;Details;

The representation of the periodic table may be represented in various way. The one presented in this challenge does have the following property : Lantanides and Aktinoides are all in a dedicated row, hence there is no element that is placed at 6, 3 nor 7, 3.

You may take a look at the atomic number repartitions here.

The atomic number is at least 1, at most 118.

;See also:
*   the periodic table
*   This task was an idea from CompSciFact
*   The periodic table in ascii that was used as template

Solution:
#include <gadget/gadget.h>

LIB_GADGET_START

/* prototypes */
GD_VIDEO put_chemical_cell( GD_VIDEO table, MT_CELL * E, DS_ARRAY E_data );
MT_CELL* load_chem_elements( MT_CELL * E, DS_ARRAY * E_data );
int select_box_chemical_elem( RDS(MT_CELL, Elements) );
void put_information(RDS( MT_CELL, elem), int i);

Main

   GD_VIDEO table;
   /* las dimensiones del terminal son muy importantes
      para desplegar la tabla */
   Resize_terminal(42,135);
   Init_video( &table );

   Gpm_Connect conn;

   if ( ! Init_mouse(&conn)){
        Msg_red("No se puede conectar al servidor del ratón\n");
        Stop(1);
   }
   Enable_raw_mode();
   Hide_cursor;

   /* I declare a multitype array "Elements", and load the file that will populate this array. */
   New multitype Elements;
   Elements = load_chem_elements( pSDS(Elements) );
   Throw( load_fail );

  /* I create a "Button" object with which the execution will end. */
   New objects Btn_exit;
   Btn_exit = New_object_mouse( SMD(&Btn_exit), BUTTOM, "  Terminar  ", 6,44, 15, 0);

  /* Fill the space on the screen with the table of chemical elements. */
   table = put_chemical_cell( table, SDS(Elements) );

  /* I print the screen and place the mouse object. */
   Refresh(table);
   Put object Btn_exit;

  /* I wait for a mouse event. */
   int c;
   Waiting_some_clic(c)
   {
       if( select_box_chemical_elem(SDS(Elements)) ){
           Waiting_some_clic(c) break;
       }
       if (Object_mouse( Btn_exit)) break;

       Refresh(table);
       Put object Btn_exit;
   }

   Free object Btn_exit;
   Free multitype Elements;

   Exception( load_fail ){
      Msg_red("No es un archivo matriciable");
   }

   Free video table;
   Disable_raw_mode();
   Close_mouse();
   Show_cursor;

   At SIZE_TERM_ROWS,0;
   Prnl;
End

void put_information(RDS(MT_CELL, elem), int i)
{
    At 2,19;
    Box_solid(11,64,67,17);
    Color(15,17);
    At 4,22; Print "Elemento (%s) = %s", (char*)$s-elem[i,5],(char*)$s-elem[i,6];
    if (Cell_type(elem,i,7) == double_TYPE ){
        At 5,22; Print "Peso atómico  = %f", $d-elem[i,7];
    }else{
        At 5,22; Print "Peso atómico  = (%ld)", $l-elem[i,7];
    }
    At 6,22; Print "Posición      = (%ld, %ld)",$l-elem[i,0]+ ($l-elem[i,0]>=8 ? 0:1),$l-elem[i,1]+1;
    At 8,22; Print "1ª energía de";
    if (Cell_type(elem,i,12) == double_TYPE ){
        At 9,22; Print "ionización (kJ/mol) = %.*f",2,$d-elem[i,12];
    }else{
        At 9,22; Print "ionización (kJ/mol) = ---";
    }
    if (Cell_type(elem,i,13) == double_TYPE ){
        At 10,22; Print "Electronegatividad  = %.*f",2,$d-elem[i,13];
    }else{
        At 10,22; Print "Electronegatividad  = ---";
    }
    At 4,56; Print "Conf. electrónica:";
    At 5,56; Print "       %s", (char*)$s-elem[i,14];
    At 7,56; Print "Estados de oxidación:";
    if ( Cell_type(elem,i,15) == string_TYPE ){
        At 8,56; Print "       %s", (char*)$s-elem[i,15];
    }else{
       /* Strangely, when the file loader detects a "+n", it treats it as a string,
          but when it detects a "-n", it treats it as a "long".
          I must review that. */
        At 8,56; Print "       %ld", $l-elem[i,15];
    }
    At 10,56; Print "Número Atómico: %ld",$l-elem[i,4];
    Reset_color;
}

int select_box_chemical_elem( RDS(MT_CELL, elem) )
{
   int i;
   Iterator up i [0:1:Rows(elem)]{
       if ( Is_range_box( $l-elem[i,8], $l-elem[i,9], $l-elem[i,10], $l-elem[i,11]) ){
           Gotoxy( $l-elem[i,8], $l-elem[i,9] );
           Color_fore( 15 ); Color_back( 0 );
           Box( 4,5, DOUB_ALL );

           Gotoxy( $l-elem[i,8]+1, $l-elem[i,9]+2); Print "%ld",$l-elem[i,4];
           Gotoxy( $l-elem[i,8]+2, $l-elem[i,9]+2); Print "%s",(char*)$s-elem[i,5];
           Flush_out;
           Reset_color;
           put_information(SDS(elem),i);
           return 1;
       }
   }
   return 0;
}

GD_VIDEO put_chemical_cell(GD_VIDEO table, MT_CELL * elem, DS_ARRAY elem_data)
{
   int i;

   /* put each cell */
   Iterator up i [0:1:Rows(elem)]{
       long rx = 2+($l-elem[i,0]*4);
       long cx = 3+($l-elem[i,1]*7);
       long offr = rx+3;
       long offc = cx+6;

       Gotoxy(table, rx, cx);

       Color_fore(table, $l-elem[i,2]);
       Color_back(table,$l-elem[i,3]);

       Box(table, 4,5, SING_ALL );

       char Atnum[50], Elem[50];
       sprintf(Atnum,"\x1b[3m%ld\x1b[23m",$l-elem[i,4]);
       sprintf(Elem, "\x1b[1m%s\x1b[22m",(char*)$s-elem[i,5]);

       Outvid(table,rx+1, cx+2, Atnum);
       Outvid(table,rx+2, cx+2, Elem);

       Reset_text(table);
       /* Update positions of each cell to be detected by the mouse. */
       $l-elem[i,8] = rx;
       $l-elem[i,9] = cx;
       $l-elem[i,10] = offr;
       $l-elem[i,11] = offc;

   }
   /* put rows and cols */
   Iterator up i [ 1: 1: 19 ]{
       Gotoxy(table, 31, 5+(i-1)*7);
       char num[5]; sprintf( num, "%d",i );
       Outvid(table, num );
   }
   Iterator up i [ 1: 1: 8 ]{
       Gotoxy(table, 3+(i-1)*4, 130);
       char num[5]; sprintf( num, "%d",i );
       Outvid(table, num );
   }
   Outvid( table, 35,116, "8");
   Outvid( table, 39,116, "9");

   /* others */
   Color_fore(table, 15);
   Color_back(table, 0);
   Outvid(table,35,2,"Lantánidos ->");
   Outvid(table,39,2,"Actínidos  ->");
   Reset_text(table);
   return table;
}

MT_CELL* load_chem_elements( MT_CELL * E, DS_ARRAY * E_data )
{
   F_STAT dataFile = Stat_file("chem_table.txt");
   if( dataFile.is_matrix ){
       /*
          Set the ranges to read from the file.
          You can choose the portion of the file that you want to upload.
       */
       Range ptr E [0:1:dataFile.total_lines-1, 0:1:dataFile.max_tokens_per_line-1];
       E = Load_matrix_mt( SDS(E), "chem_table.txt", dataFile, DET_LONG);
   }else{
       Is_ok=0;
   }
   return E;
}


Perlin noise

The   '''computer graphics,   most notably to procedurally generate textures or heightmaps.

The Perlin noise is basically a   pseudo-random   mapping of   \R^d   into   \R   with an integer   d   which can be arbitrarily large but which is usually   2,   3,   or   4.

Either by using a dedicated library or by implementing the algorithm, show that the Perlin noise   (as defined in 2002 in the Java implementation below)   of the point in 3D-space with coordinates     3.14,   42,   7     is     0.13691995878400012.

''Note: this result assumes 64 bit IEEE-754 floating point calculations. If your language uses a different floating point representation, make a note of it and calculate the value accurate to 15 decimal places, or your languages accuracy threshold if it is less. Trailing zeros need not be displayed.''

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

int p[512];

double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }
double lerp(double t, double a, double b) { return a + t * (b - a); }
double grad(int hash, double x, double y, double z) {
      int h = hash & 15;
      double u = h<8 ? x : y,
             v = h<4 ? y : h==12||h==14 ? x : z;
      return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);
   }

double noise(double x, double y, double z) {
      int X = (int)floor(x) & 255,
          Y = (int)floor(y) & 255,
          Z = (int)floor(z) & 255;
      x -= floor(x);
      y -= floor(y);
      z -= floor(z);
      double u = fade(x),
             v = fade(y),
             w = fade(z);
      int A = p[X  ]+Y, AA = p[A]+Z, AB = p[A+1]+Z,
          B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z;

      return lerp(w, lerp(v, lerp(u, grad(p[AA  ], x  , y  , z   ),
                                     grad(p[BA  ], x-1, y  , z   )),
                             lerp(u, grad(p[AB  ], x  , y-1, z   ),
                                     grad(p[BB  ], x-1, y-1, z   ))),
                     lerp(v, lerp(u, grad(p[AA+1], x  , y  , z-1 ),
                                     grad(p[BA+1], x-1, y  , z-1 )),
                             lerp(u, grad(p[AB+1], x  , y-1, z-1 ),
                                     grad(p[BB+1], x-1, y-1, z-1 ))));
   }

void loadPermutation(char* fileName){
	FILE* fp = fopen(fileName,"r");
	int permutation[256],i;

	for(i=0;i<256;i++)
		fscanf(fp,"%d",&permutation[i]);

	fclose(fp);

	for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i];
}

int main(int argC,char* argV[])
{
	if(argC!=5)
		printf("Usage : %s <permutation data file> <x,y,z co-ordinates separated by space>");
	else{
		loadPermutation(argV[1]);
		printf("Perlin Noise for (%s,%s,%s) is %.17lf",argV[2],argV[3],argV[4],noise(strtod(argV[2],NULL),strtod(argV[3],NULL),strtod(argV[4],NULL)));
	}

	return 0;
}


Permutations/Derangements

A derangement is a permutation of the order of distinct items in which ''no item appears in its original place''.

For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1).

The number of derangements of ''n'' distinct items is known as the subfactorial of ''n'', sometimes written as !''n''.
There are various ways to calculate !''n''.

;Task:
# Create a named function/method/subroutine/... to generate derangements of the integers ''0..n-1'', (or ''1..n'' if you prefer).
# Generate ''and show'' all the derangements of 4 integers using the above routine.
# Create a function that calculates the subfactorial of ''n'', !''n''.
# Print and show a table of the ''counted'' number of derangements of ''n'' vs. the calculated !''n'' for n from 0..9 inclusive.

;Optional stretch goal:
*   Calculate    !''20''

;Related tasks:
*   [[Anagrams/Deranged anagrams]]
*   [[Best shuffle]]
*   [[Left_factorials]]

Solution:
#include <stdio.h>
typedef unsigned long long LONG;

LONG deranged(int depth, int len, int *d, int show)
{
        int i;
        char tmp;
        LONG count = 0;

        if (depth == len) {
                if (show) {
                        for (i = 0; i < len; i++) putchar(d[i] + 'a');
                        putchar('\n');
                }
                return 1;
        }
        for (i = len - 1; i >= depth; i--) {
                if (i == d[depth]) continue;

                tmp = d[i]; d[i] = d[depth]; d[depth] = tmp;
                count += deranged(depth + 1, len, d, show);
                tmp = d[i]; d[i] = d[depth]; d[depth] = tmp;
        }
        return count;
}

LONG gen_n(int n, int show)
{
        LONG i;
        int a[1024]; /* 1024 ought to be big enough for anybody */

        for (i = 0; i < n; i++) a[i] = i;
        return deranged(0, n, a, show);
}

LONG sub_fact(int n)
{
        return n < 2 ? 1 - n : (sub_fact(n - 1) + sub_fact(n - 2)) * (n - 1);
}

int main()
{
        int i;

        printf("Deranged Four:\n");
        gen_n(4, 1);

        printf("\nCompare list vs calc:\n");
        for (i = 0; i < 10; i++)
                printf("%d:\t%llu\t%llu\n", i, gen_n(i, 0), sub_fact(i));

        printf("\nfurther calc:\n");
        for (i = 10; i <= 20; i++)
                printf("%d: %llu\n", i, sub_fact(i));

        return 0;
}


Permutations/Rank of a permutation

A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items.
For our purposes the ranking will assign integers 0 .. (n! - 1) to an ordering of all the permutations of the integers 0 .. (n - 1).

For example, the permutations of the digits zero to 3 arranged lexicographically have the following rank:

  PERMUTATION      RANK
  (0, 1, 2, 3) ->  0
  (0, 1, 3, 2) ->  1
  (0, 2, 1, 3) ->  2
  (0, 2, 3, 1) ->  3
  (0, 3, 1, 2) ->  4
  (0, 3, 2, 1) ->  5
  (1, 0, 2, 3) ->  6
  (1, 0, 3, 2) ->  7
  (1, 2, 0, 3) ->  8
  (1, 2, 3, 0) ->  9
  (1, 3, 0, 2) -> 10
  (1, 3, 2, 0) -> 11
  (2, 0, 1, 3) -> 12
  (2, 0, 3, 1) -> 13
  (2, 1, 0, 3) -> 14
  (2, 1, 3, 0) -> 15
  (2, 3, 0, 1) -> 16
  (2, 3, 1, 0) -> 17
  (3, 0, 1, 2) -> 18
  (3, 0, 2, 1) -> 19
  (3, 1, 0, 2) -> 20
  (3, 1, 2, 0) -> 21
  (3, 2, 0, 1) -> 22
  (3, 2, 1, 0) -> 23

Algorithms exist that can generate a rank from a permutation for some particular ordering of permutations, and that can generate the same rank from the given individual permutation (i.e. given a rank of 17 produce (2, 3, 1, 0) in the example above).

One use of such algorithms could be in generating a small, random, sample of permutations of n items without duplicates when the total number of permutations is large. Remember that the total number of permutations of n items is given by n! which grows large very quickly: A 32 bit integer can only hold 12!, a 64 bit integer only 20!. It becomes difficult to take the straight-forward approach of generating all permutations then taking a random sample of them.

A question on the Stack Overflow site asked how to generate one million random and indivudual permutations of 144 items.

;Task:
# Create a function to generate a permutation from a rank.
# Create the inverse function that given the permutation generates its rank.
# Show that for n=3 the two functions are indeed inverses of each other.
# Compute and show here 4 random, individual, samples of permutations of 12 objects.

;Stretch goal:
* State how reasonable it would be to use your program to address the limits of the Stack Overflow question.

;References:
# Ranking and Unranking Permutations in Linear Time by Myrvold & Ruskey. (Also available via Google here).
# Ranks on the DevData site.
# Another answer on Stack Overflow to a different question that explains its algorithm in detail.

;Related tasks:
#[[Factorial_base_numbers_indexing_permutations_of_a_collection]]

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

#define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0)

void _mr_unrank1(int rank, int n, int *vec) {
    int t, q, r;
    if (n < 1) return;

    q = rank / n;
    r = rank % n;
    SWAP(vec[r], vec[n-1]);
    _mr_unrank1(q, n-1, vec);
}

int _mr_rank1(int n, int *vec, int *inv) {
    int s, t;
    if (n < 2) return 0;

    s = vec[n-1];
    SWAP(vec[n-1], vec[inv[n-1]]);
    SWAP(inv[s], inv[n-1]);
    return s + n * _mr_rank1(n-1, vec, inv);
}

/* Fill the integer array <vec> (of size <n>) with the
 * permutation at rank <rank>.
 */
void get_permutation(int rank, int n, int *vec) {
    int i;
    for (i = 0; i < n; ++i) vec[i] = i;
    _mr_unrank1(rank, n, vec);
}

/* Return the rank of the current permutation of array <vec>
 * (of size <n>).
 */
int get_rank(int n, int *vec) {
    int i, r, *v, *inv;

    v = malloc(n * sizeof(int));
    inv = malloc(n * sizeof(int));

    for (i = 0; i < n; ++i) {
        v[i] = vec[i];
        inv[vec[i]] = i;
    }
    r = _mr_rank1(n, v, inv);
    free(inv);
    free(v);
    return r;
}

int main(int argc, char *argv[]) {
    int i, r, tv[4];

    for (r = 0; r < 24; ++r) {
        printf("%3d: ", r);
        get_permutation(r, 4, tv);

        for (i = 0; i < 4; ++i) {
            if (0 == i) printf("[ ");
            else printf(", ");
            printf("%d", tv[i]);
        }
        printf(" ] = %d\n", get_rank(4, tv));
    }
}


Permutations by swapping

Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items.

Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd.

Show the permutations and signs of three items, in order of generation ''here''.

Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind.

Note: The Steinhaus-Johnson-Trotter algorithm generates successive permutations where ''adjacent'' items are swapped, but from this discussion adjacency is not a requirement.

;References:
* Steinhaus-Johnson-Trotter algorithm
* Johnson-Trotter Algorithm Listing All Permutations
* Heap's algorithm
* Tintinnalogia

;Related tasks:
*   [[Matrix arithmetic]
*   [[Gray code]]

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

int flag = 1;

void heapPermute(int n, int arr[],int arrLen){
	int temp;
	int i;

	if(n==1){
		printf("\n[");

		for(i=0;i<arrLen;i++)
			printf("%d,",arr[i]);
		printf("\b] Sign : %d",flag);

		flag*=-1;
	}
	else{
		for(i=0;i<n-1;i++){
			heapPermute(n-1,arr,arrLen);

			if(n%2==0){
				temp = arr[i];
				arr[i] = arr[n-1];
				arr[n-1] = temp;
			}
			else{
				temp = arr[0];
				arr[0] = arr[n-1];
				arr[n-1] = temp;
			}
		}
		heapPermute(n-1,arr,arrLen);
	}
}

int main(int argC,char* argV[0])
{
	int *arr, i=0, count = 1;
	char* token;

	if(argC==1)
		printf("Usage : %s <comma separated list of integers>",argV[0]);
	else{
		while(argV[1][i]!=00){
			if(argV[1][i++]==',')
				count++;
		}

		arr = (int*)malloc(count*sizeof(int));

		i = 0;

		token = strtok(argV[1],",");

		while(token!=NULL){
			arr[i++] = atoi(token);
			token = strtok(NULL,",");
		}

		heapPermute(i,arr,count);
	}

	return 0;
}


Phrase reversals

Given a string of space separated words containing the following phrase:
  rosetta code phrase reversal

:# Reverse the characters of the string.
:# Reverse the characters of each individual word in the string, maintaining original word order within the string.
:# Reverse the order of each word of the string, maintaining the order of characters in each word.

Show your output here.

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

/* The functions used are destructive, so after each call the string needs
 * to be copied over again. One could easily allocate new strings as
 * required, but this way allows the caller to manage memory themselves */

char* reverse_section(char *s, size_t length)
{
    if (length == 0) return s;

    size_t i; char temp;
    for (i = 0; i < length / 2 + 1; ++i)
        temp = s[i], s[i] = s[length - i], s[length - i] = temp;
    return s;
}

char* reverse_words_in_order(char *s, char delim)
{
    if (!strlen(s)) return s;

    size_t i, j;
    for (i = 0; i < strlen(s) - 1; ++i) {
        for (j = 0; s[i + j] != 0 && s[i + j] != delim; ++j)
            ;
        reverse_section(s + i, j - 1);
        s += j;
    }
    return s;
}

char* reverse_string(char *s)
{
    return strlen(s) ? reverse_section(s, strlen(s) - 1) : s;
}

char* reverse_order_of_words(char *s, char delim)
{
    reverse_string(s);
    reverse_words_in_order(s, delim);
    return s;
}

int main(void)
{
    char str[]    = "rosetta code phrase reversal";
    size_t lenstr = sizeof(str) / sizeof(str[0]);
    char scopy[lenstr];
    char delim = ' ';

    /* Original String */
    printf("Original:       \"%s\"\n", str);

    /* Reversed string */
    strncpy(scopy, str, lenstr);
    reverse_string(scopy);
    printf("Reversed:       \"%s\"\n", scopy);

    /* Reversed words in string */
    strncpy(scopy, str, lenstr);
    reverse_words_in_order(scopy, delim);
    printf("Reversed words: \"%s\"\n", scopy);

    /* Reversed order of words in string */
    strncpy(scopy, str, lenstr);
    reverse_order_of_words(scopy, delim);
    printf("Reversed order: \"%s\"\n", scopy);

    return 0;
}