{"title": "100 doors", "language": "C", "task": "There are 100 doors in a row that are all initially closed. \n\nYou make 100 passes by the doors. \n\nThe first time through, visit every door and ''toggle'' the door (if the door is closed, open it; if it is open, close it). \n\nThe second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it. \n\nThe third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.\n\n\n;Task:\nAnswer the question: what state are the doors in after the last pass? Which are open, which are closed?\n\n\n'''Alternate:''' \nAs noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.\n\nOpening only those doors is an optimization that may also be expressed; \nhowever, as should be obvious, this defeats the intent of comparing implementations across programming languages.\n\n", "solution": "#include \n\n#define NUM_DOORS 100\n\nint main(int argc, char *argv[])\n{\n int is_open[NUM_DOORS] = { 0 } ;\n int * doorptr, * doorlimit = is_open + NUM_DOORS ;\n int pass ;\n\n /* do the N passes, go backwards because the order is not important */\n for ( pass= NUM_DOORS ; ( pass ) ; -- pass ) {\n for ( doorptr= is_open + ( pass-1 ); ( doorptr < doorlimit ) ; doorptr += pass ) {\n ( * doorptr ) ^= 1 ;\n }\n }\n\n /* output results */\n for ( doorptr= is_open ; ( doorptr != doorlimit ) ; ++ doorptr ) {\n printf(\"door #%lld is %s\\n\", ( doorptr - is_open ) + 1, ( * doorptr ) ? \"open\" : \"closed\" ) ;\n }\n}"} {"title": "100 prisoners", "language": "C", "task": "The Problem:\n* 100 prisoners are individually numbered 1 to 100\n* A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside.\n* Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start.\n* Prisoners start outside the room\n:* They can decide some strategy before any enter the room.\n:* Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer.\n:* A prisoner can open no more than 50 drawers.\n:* A prisoner tries to find his own number.\n:* A prisoner finding his own number is then held apart from the others.\n* If '''all''' 100 prisoners find their own numbers then they will all be pardoned. If ''any'' don't then ''all'' sentences stand. \n\n\n;The task:\n# Simulate several thousand instances of the game where the prisoners randomly open drawers\n# Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of:\n:* First opening the drawer whose outside number is his prisoner number.\n:* If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum).\n\n\nShow and compare the computed probabilities of success for the two strategies, here, on this page.\n\n\n;References:\n# The unbelievable solution to the 100 prisoner puzzle standupmaths (Video).\n# [[wp:100 prisoners problem]]\n# 100 Prisoners Escape Puzzle DataGenetics.\n# Random permutation statistics#One hundred prisoners on Wikipedia.\n\n", "solution": "#include\n#include\n#include\n#include\n\n#define LIBERTY false\n#define DEATH true\n\ntypedef struct{\n\tint cardNum;\n\tbool hasBeenOpened;\n}drawer;\n\ndrawer *drawerSet;\n\nvoid initialize(int prisoners){\n\tint i,j,card;\n\tbool unique;\n\n\tdrawerSet = ((drawer*)malloc(prisoners * sizeof(drawer))) -1;\n\n\tcard = rand()%prisoners + 1;\n\tdrawerSet[1] = (drawer){.cardNum = card, .hasBeenOpened = false};\n\n\tfor(i=1 + 1;i \",argv[0]);\n\n\tprisoners = atoi(argv[1]);\n\tchances = atoi(argv[2]);\n\ttrials = strtoull(argv[3],&end,10);\n\n\tsrand(time(NULL));\n\n\tprintf(\"Running random trials...\");\n\tfor(i=0;i\n#include \n#include \n\nenum Move { MOVE_UP = 0, MOVE_DOWN = 1, MOVE_LEFT = 2, MOVE_RIGHT = 3 };\n\n/* *****************************************************************************\n * Model\n */\n\n#define NROWS 4\n#define NCOLLUMNS 4\nint holeRow; \nint holeCollumn; \nint cells[NROWS][NCOLLUMNS];\nconst int nShuffles = 100;\n\nint Game_update(enum Move move){\n const int dx[] = { 0, 0, -1, +1 };\n const int dy[] = { -1, +1, 0, 0 };\n int i = holeRow + dy[move];\n int j = holeCollumn + dx[move]; \n if ( i >= 0 && i < NROWS && j >= 0 && j < NCOLLUMNS ){\n cells[holeRow][holeCollumn] = cells[i][j];\n cells[i][j] = 0; holeRow = i; holeCollumn = j;\n return 1;\n }\n return 0;\n}\n\nvoid Game_setup(void){\n int i,j,k;\n for ( i = 0; i < NROWS; i++ )\n for ( j = 0; j < NCOLLUMNS; j++ )\n cells[i][j] = i * NCOLLUMNS + j + 1;\n cells[NROWS-1][NCOLLUMNS-1] = 0;\n holeRow = NROWS - 1;\n holeCollumn = NCOLLUMNS - 1;\n k = 0;\n while ( k < nShuffles )\n k += Game_update((enum Move)(rand() % 4));\n}\n\nint Game_isFinished(void){\n int i,j; int k = 1;\n for ( i = 0; i < NROWS; i++ )\n for ( j = 0; j < NCOLLUMNS; j++ ) \n if ( (k < NROWS*NCOLLUMNS) && (cells[i][j] != k++ ) )\n return 0;\n return 1; \n}\n\n\n/* *****************************************************************************\n * View \n */\n\nvoid View_showBoard(){\n int i,j;\n putchar('\\n');\n for ( i = 0; i < NROWS; i++ )\n for ( j = 0; j < NCOLLUMNS; j++ ){\n if ( cells[i][j] )\n printf(j != NCOLLUMNS-1 ? \" %2d \" : \" %2d \\n\", cells[i][j]);\n else\n printf(j != NCOLLUMNS-1 ? \" %2s \" : \" %2s \\n\", \"\");\n }\n putchar('\\n');\n}\n\nvoid View_displayMessage(char* text){\n printf(\"\\n%s\\n\", text);\n}\n\n\n/* *****************************************************************************\n * Controller\n */\n\nenum Move Controller_getMove(void){\n int c;\n for(;;){\n printf(\"%s\", \"enter u/d/l/r : \");\n c = getchar();\n while( getchar() != '\\n' )\n ;\n switch ( c ){\n case 27: exit(EXIT_SUCCESS);\n case 'd' : return MOVE_UP; \n case 'u' : return MOVE_DOWN;\n case 'r' : return MOVE_LEFT;\n case 'l' : return MOVE_RIGHT;\n }\n }\n}\n\nvoid Controller_pause(void){\n getchar();\n}\n\nint main(void){\n\n srand((unsigned)time(NULL));\n\n do Game_setup(); while ( Game_isFinished() );\n\n View_showBoard();\n while( !Game_isFinished() ){ \n Game_update( Controller_getMove() ); \n View_showBoard(); \n }\n\n View_displayMessage(\"You win\");\n Controller_pause();\n\n return EXIT_SUCCESS;\n}\n\n"} {"title": "21 game", "language": "C", "task": "'''21''' is a two player game, the game is played by choosing \na number ('''1''', '''2''', or '''3''') to be added to the ''running total''.\n\nThe game is won by the player whose chosen number causes the ''running total''\nto reach ''exactly'' '''21'''.\n\nThe ''running total'' starts at zero. \nOne player will be the computer.\n \nPlayers alternate supplying a number to be added to the ''running total''. \n\n\n;Task:\nWrite a computer program that will:\n::* do the prompting (or provide a button menu), \n::* check for errors and display appropriate error messages, \n::* do the additions (add a chosen number to the ''running total''), \n::* display the ''running total'', \n::* provide a mechanism for the player to quit/exit/halt/stop/close the program,\n::* issue a notification when there is a winner, and\n::* determine who goes first (maybe a random or user choice, or can be specified when the game begins). \n\n", "solution": "/**\n * Game 21 - an example in C language for Rosseta Code.\n *\n * A simple game program whose rules are described below\n * - see DESCRIPTION string.\n *\n * This program should be compatible with C89 and up.\n */\n\n\n/*\n * Turn off MS Visual Studio panic warnings which disable to use old gold\n * library functions like printf, scanf etc. This definition should be harmless\n * for non-MS compilers.\n */\n#define _CRT_SECURE_NO_WARNINGS\n\n#include \n#include \n#include \n\n/*\n * Define bool, true and false as needed. The stdbool.h is a standard header\n * in C99, therefore for older compilers we need DIY booleans. BTW, there is\n * no __STDC__VERSION__ predefined macro in MS Visual C, therefore we need\n * check also _MSC_VER.\n */\n#if __STDC_VERSION__ >= 199901L || _MSC_VER >= 1800\n#include \n#else\n#define bool int\n#define true 1\n#define false 0\n#endif\n\n#define GOAL 21\n#define NUMBER_OF_PLAYERS 2\n#define MIN_MOVE 1\n#define MAX_MOVE 3\n#define BUFFER_SIZE 256\n\n#define _(STRING) STRING\n\n\n/*\n * Spaces are meaningful: on some systems they can be visible.\n */\nstatic char DESCRIPTION[] = \n \"21 Game \\n\"\n \" \\n\"\n \"21 is a two player game, the game is played by choosing a number \\n\"\n \"(1, 2, or 3) to be added to the running total. The game is won by\\n\"\n \"the player whose chosen number causes the running total to reach \\n\"\n \"exactly 21. The running total starts at zero. \\n\\n\";\n\nstatic int total;\n\n\nvoid update(char* player, int move)\n{\n printf(\"%8s: %d = %d + %d\\n\\n\", player, total + move, total, move);\n total += move;\n if (total == GOAL)\n printf(_(\"The winner is %s.\\n\\n\"), player);\n}\n\n\nint ai()\n{\n/*\n * There is a winning strategy for the first player. The second player can win\n * then and only then the frist player does not use the winning strategy.\n * \n * The winning strategy may be defined as best move for the given running total.\n * The running total is a number from 0 to GOAL. Therefore, for given GOAL, best\n * moves may be precomputed (and stored in a lookup table). Actually (when legal\n * moves are 1 or 2 or 3) the table may be truncated to four first elements.\n */\n#if GOAL < 32 && MIN_MOVE == 1 && MAX_MOVE == 3\n static const int precomputed[] = { 1, 1, 3, 2, 1, 1, 3, 2, 1, 1, 3, 2, 1, 1,\n 3, 2, 1, 1, 3, 2, 1, 1, 3, 2, 1, 1, 3, 2, 1, 1, 3 };\n update(_(\"ai\"), precomputed[total]);\n#elif MIN_MOVE == 1 && MAX_MOVE == 3\n static const int precomputed[] = { 1, 1, 3, 2};\n update(_(\"ai\"), precomputed[total % (MAX_MOVE + 1)]);\n#else\n int i;\n int move = 1;\n for (i = MIN_MOVE; i <= MAX_MOVE; i++)\n if ((total + i - 1) % (MAX_MOVE + 1) == 0)\n move = i;\n for (i = MIN_MOVE; i <= MAX_MOVE; i++)\n if (total + i == GOAL)\n move = i;\n update(_(\"ai\"), move);\n#endif\n}\n\n\nvoid human(void)\n{\n char buffer[BUFFER_SIZE];\n int move;\n \n while ( printf(_(\"enter your move to play (or enter 0 to exit game): \")),\n fgets(buffer, BUFFER_SIZE, stdin), \n sscanf(buffer, \"%d\", &move) != 1 ||\n (move && (move < MIN_MOVE || move > MAX_MOVE || total+move > GOAL)))\n puts(_(\"\\nYour answer is not a valid choice.\\n\"));\n putchar('\\n');\n if (!move) exit(EXIT_SUCCESS);\n update(_(\"human\"), move);\n}\n\n\nint main(int argc, char* argv[])\n{\n srand(time(NULL));\n puts(_(DESCRIPTION));\n while (true)\n {\n puts(_(\"\\n---- NEW GAME ----\\n\"));\n puts(_(\"\\nThe running total is currently zero.\\n\"));\n total = 0;\n\n if (rand() % NUMBER_OF_PLAYERS)\n {\n puts(_(\"The first move is AI move.\\n\"));\n ai();\n }\n else\n puts(_(\"The first move is human move.\\n\"));\n\n while (total < GOAL)\n {\n human();\n ai();\n }\n }\n}"} {"title": "24 game", "language": "C", "task": "The 24 Game tests one's mental arithmetic. \n\n\n;Task\nWrite a program that displays four digits, each from 1 --> 9 (inclusive) with repetitions allowed.\n\nThe program should prompt for the player to enter an arithmetic expression using ''just'' those, and ''all'' of those four digits, used exactly ''once'' each. The program should ''check'' then evaluate the expression. \n\nThe goal is for the player to enter an expression that (numerically) evaluates to '''24'''.\n* Only the following operators/functions are allowed: multiplication, division, addition, subtraction\n* Division should use floating point or rational arithmetic, etc, to preserve remainders.\n* Brackets are allowed, if using an infix expression evaluator.\n* Forming multiple digit numbers from the supplied digits is ''disallowed''. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).\n* The order of the digits when given does not have to be preserved.\n\n\n;Notes\n* The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.\n* The task is not for the program to generate the expression, or test whether an expression is even possible.\n\n\n;Related tasks\n* [[24 game/Solve]]\n\n\n;Reference\n* The 24 Game on h2g2.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n \njmp_buf ctx;\nconst char *msg;\n \nenum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV };\n \ntypedef struct expr_t *expr, expr_t;\nstruct expr_t {\n\tint op, val, used;\n\texpr left, right;\n};\n \n#define N_DIGITS 4\nexpr_t digits[N_DIGITS];\n \nvoid gen_digits()\n{\n\tint i;\n\tfor (i = 0; i < N_DIGITS; i++)\n\t\tdigits[i].val = 1 + rand() % 9;\n}\n \n#define MAX_INPUT 64\nchar str[MAX_INPUT];\nint pos;\n \n#define POOL_SIZE 8\nexpr_t pool[POOL_SIZE];\nint pool_ptr;\n \nvoid reset()\n{\n\tint i;\n\tmsg = 0;\n\tpool_ptr = pos = 0;\n\tfor (i = 0; i < POOL_SIZE; i++) {\n\t\tpool[i].op = OP_NONE;\n\t\tpool[i].left = pool[i].right = 0;\n\t}\n\tfor (i = 0; i < N_DIGITS; i++)\n\t\tdigits[i].used = 0;\n}\n \n/* longish jumpish back to input cycle */\nvoid bail(const char *s)\n{\n\tmsg = s;\n\tlongjmp(ctx, 1);\n}\n \nexpr new_expr()\n{\n\tif (pool_ptr < POOL_SIZE)\n\t\treturn pool + pool_ptr++;\n\treturn 0;\n}\n \n/* check next input char */\nint next_tok()\n{\n\twhile (isspace(str[pos])) pos++;\n\treturn str[pos];\n}\n \n/* move input pointer forward */\nint take()\n{\n\tif (str[pos] != '\\0') return ++pos;\n\treturn 0;\n}\n \n/* BNF(ish)\nexpr = term { (\"+\")|(\"-\") term }\nterm = fact { (\"*\")|(\"/\") expr }\nfact =\tnumber\n\t| '(' expr ')'\n*/\n \nexpr get_fact();\nexpr get_term();\nexpr get_expr();\n \nexpr get_expr()\n{\n\tint c;\n\texpr l, r, ret;\n\tif (!(ret = get_term())) bail(\"Expected term\");\n\twhile ((c = next_tok()) == '+' || c == '-') {\n\t\tif (!take()) bail(\"Unexpected end of input\");\n\t\tif (!(r = get_term())) bail(\"Expected term\");\n \n\t\tl = ret;\n\t\tret = new_expr();\n\t\tret->op = (c == '+') ? OP_ADD : OP_SUB;\n\t\tret->left = l;\n\t\tret->right = r;\n\t}\n\treturn ret;\n}\n \nexpr get_term()\n{\n\tint c;\n\texpr l, r, ret;\n\tret = get_fact();\n\twhile((c = next_tok()) == '*' || c == '/') {\n\t\tif (!take()) bail(\"Unexpected end of input\");\n \n\t\tr = get_fact();\n\t\tl = ret;\n\t\tret = new_expr();\n\t\tret->op = (c == '*') ? OP_MUL : OP_DIV;\n\t\tret->left = l;\n\t\tret->right = r;\n\t}\n\treturn ret;\n}\n \nexpr get_digit()\n{\n\tint i, c = next_tok();\n\texpr ret;\n\tif (c >= '0' && c <= '9') {\n\t\ttake();\n\t\tret = new_expr();\n\t\tret->op = OP_NUM;\n\t\tret->val = c - '0';\n\t\tfor (i = 0; i < N_DIGITS; i++)\n\t\t\tif (digits[i].val == ret->val && !digits[i].used) {\n\t\t\t\tdigits[i].used = 1;\n\t\t\t\treturn ret;\n\t\t\t}\n\t\tbail(\"Invalid digit\");\n\t}\n\treturn 0;\n}\n \nexpr get_fact()\n{\n\tint c;\n\texpr l = get_digit();\n\tif (l) return l;\n\tif ((c = next_tok()) == '(') {\n\t\ttake();\n\t\tl = get_expr();\n\t\tif (next_tok() != ')') bail(\"Unbalanced parens\");\n\t\ttake();\n\t\treturn l;\n\t}\n\treturn 0;\n}\n \nexpr parse()\n{\n\tint i;\n\texpr ret = get_expr();\n\tif (next_tok() != '\\0')\n\t\tbail(\"Trailing garbage\");\n\tfor (i = 0; i < N_DIGITS; i++)\n\t\tif (!digits[i].used)\n\t\t\tbail(\"Not all digits are used\");\n\treturn ret;\n}\n \ntypedef struct frac_t frac_t, *frac;\nstruct frac_t { int denom, num; };\n \nint gcd(int m, int n)\n{\n\tint t;\n\twhile (m) {\n\t\tt = m; m = n % m; n = t;\n\t}\n\treturn n;\n}\n \n/* evaluate expression tree. result in fraction form */\nvoid eval_tree(expr e, frac res)\n{\n\tfrac_t l, r;\n\tint t;\n\tif (e->op == OP_NUM) {\n\t\tres->num = e->val;\n\t\tres->denom = 1;\n\t\treturn;\n\t}\n \n\teval_tree(e->left, &l);\n\teval_tree(e->right, &r);\n \n\tswitch(e->op) {\n\tcase OP_ADD:\n\t\tres->num = l.num * r.denom + l.denom * r.num;\n\t\tres->denom = l.denom * r.denom;\n\t\tbreak;\n\tcase OP_SUB:\n\t\tres->num = l.num * r.denom - l.denom * r.num;\n\t\tres->denom = l.denom * r.denom;\n\t\tbreak;\n\tcase OP_MUL:\n\t\tres->num = l.num * r.num;\n\t\tres->denom = l.denom * r.denom;\n\t\tbreak;\n\tcase OP_DIV:\n\t\tres->num = l.num * r.denom;\n\t\tres->denom = l.denom * r.num;\n\t\tbreak;\n\t}\n\tif ((t = gcd(res->denom, res->num))) {\n\t\tres->denom /= t;\n\t\tres->num /= t;\n\t}\n}\n \nvoid get_input()\n{\n\tint i;\nreinput:\n\treset();\n\tprintf(\"\\nAvailable digits are:\");\n\tfor (i = 0; i < N_DIGITS; i++) \n\t\tprintf(\" %d\", digits[i].val);\n\tprintf(\". Type an expression and I'll check it for you, or make new numbers.\\n\"\n\t\t\"Your choice? [Expr/n/q] \");\n \n\twhile (1) {\n\t\tfor (i = 0; i < MAX_INPUT; i++) str[i] = '\\n';\n\t\tfgets(str, MAX_INPUT, stdin);\n\t\tif (*str == '\\0') goto reinput;\n\t\tif (str[MAX_INPUT - 1] != '\\n')\n\t\t\tbail(\"string too long\");\n \n\t\tfor (i = 0; i < MAX_INPUT; i++)\n\t\t\tif (str[i] == '\\n') str[i] = '\\0';\n\t\tif (str[0] == 'q') {\n\t\t\tprintf(\"Bye\\n\");\n\t\t\texit(0);\n\t\t}\n\t\tif (str[0] == 'n') {\n\t\t\tgen_digits();\n\t\t\tgoto reinput;\n\t\t}\n\t\treturn;\n\t}\n}\n \nint main()\n{\n\tfrac_t f;\n\tsrand(time(0));\n \n\tgen_digits();\n\twhile(1) {\n\t\tget_input();\n\t\tsetjmp(ctx); /* if parse error, jump back here with err msg set */\n\t\tif (msg) {\n\t\t\t/* after error jump; announce, reset, redo */\n\t\t\tprintf(\"%s at '%.*s'\\n\", msg, pos, str);\n\t\t\tcontinue;\n\t\t}\n \n\t\teval_tree(parse(), &f);\n \n\t\tif (f.denom == 0) bail(\"Divide by zero\");\n\t\tif (f.denom == 1 && f.num == 24)\n\t\t\tprintf(\"You got 24. Very good.\\n\");\n\t\telse {\n\t\t\tif (f.denom == 1)\n\t\t\t\tprintf(\"Eval to: %d, \", f.num);\n\t\t\telse\n\t\t\t\tprintf(\"Eval to: %d/%d, \", f.num, f.denom);\n\t\t\tprintf(\"no good. Try again.\\n\");\n\t\t}\n\t}\n\treturn 0;\n}"} {"title": "24 game/Solve", "language": "C", "task": "Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the [[24 game]].\n\nShow examples of solutions generated by the program.\n\n\n;Related task:\n* [[Arithmetic Evaluator]]\n\n", "solution": "#include \n\ntypedef struct {int val, op, left, right;} Node;\n\nNode nodes[10000];\nint iNodes;\n\nint b;\nfloat eval(Node x){\n if (x.op != -1){\n float l = eval(nodes[x.left]), r = eval(nodes[x.right]);\n switch(x.op){\n case 0: return l+r;\n case 1: return l-r;\n case 2: return r-l;\n case 3: return l*r;\n case 4: return r?l/r:(b=1,0);\n case 5: return l?r/l:(b=1,0);\n }\n }\n else return x.val*1.;\n}\n\nvoid show(Node x){\n if (x.op != -1){\n printf(\"(\");\n switch(x.op){\n case 0: show(nodes[x.left]); printf(\" + \"); show(nodes[x.right]); break;\n case 1: show(nodes[x.left]); printf(\" - \"); show(nodes[x.right]); break;\n case 2: show(nodes[x.right]); printf(\" - \"); show(nodes[x.left]); break;\n case 3: show(nodes[x.left]); printf(\" * \"); show(nodes[x.right]); break;\n case 4: show(nodes[x.left]); printf(\" / \"); show(nodes[x.right]); break;\n case 5: show(nodes[x.right]); printf(\" / \"); show(nodes[x.left]); break;\n }\n printf(\")\");\n }\n else printf(\"%d\", x.val);\n}\n\nint float_fix(float x){ return x < 0.00001 && x > -0.00001; }\n\nvoid solutions(int a[], int n, float t, int s){\n if (s == n){\n b = 0;\n float e = eval(nodes[0]); \n \n if (!b && float_fix(e-t)){\n show(nodes[0]);\n printf(\"\\n\");\n }\n }\n else{\n nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1};\n \n for (int op = 0; op < 6; op++){ \n int k = iNodes-1;\n for (int i = 0; i < k; i++){\n nodes[iNodes++] = nodes[i];\n nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2};\n solutions(a, n, t, s+1);\n nodes[i] = nodes[--iNodes];\n }\n }\n \n iNodes--;\n }\n};\n\nint main(){\n // define problem\n\n int a[4] = {8, 3, 8, 3};\n float t = 24;\n\n // print all solutions\n\n nodes[0] = (typeof(Node)){a[0],-1,-1,-1};\n iNodes = 1;\n\n solutions(a, sizeof(a)/sizeof(int), t, 1);\n\n return 0;\n}"} {"title": "4-rings or 4-squares puzzle", "language": "C", "task": "Replace '''a, b, c, d, e, f,''' and\n '''g ''' with the decimal\ndigits LOW ---> HIGH\nsuch that the sum of the letters inside of each of the four large squares add up to\nthe same sum.\n\n\n +--------------+ +--------------+\n | | | |\n | a | | e |\n | | | |\n | +---+------+---+ +---+---------+\n | | | | | | | |\n | | b | | d | | f | |\n | | | | | | | |\n | | | | | | | |\n +----------+---+ +---+------+---+ |\n | c | | g |\n | | | |\n | | | |\n +--------------+ +-------------+\n\n\nShow all output here.\n\n\n:* Show all solutions for each letter being unique with\n LOW=1 HIGH=7\n:* Show all solutions for each letter being unique with\n LOW=3 HIGH=9\n:* Show only the ''number'' of solutions when each letter can be non-unique\n LOW=0 HIGH=9\n\n\n;Related task:\n* [[Solve the no connection puzzle]]\n\n", "solution": "#include \n\n#define TRUE 1\n#define FALSE 0\n\nint a,b,c,d,e,f,g;\nint lo,hi,unique,show;\nint solutions;\n\nvoid\nbf()\n{\n for (f = lo;f <= hi; f++)\n if ((!unique) ||\n ((f != a) && (f != c) && (f != d) && (f != g) && (f != e)))\n {\n b = e + f - c;\n if ((b >= lo) && (b <= hi) &&\n ((!unique) || ((b != a) && (b != c) &&\n (b != d) && (b != g) && (b != e) && (b != f))))\n {\n solutions++;\n if (show)\n printf(\"%d %d %d %d %d %d %d\\n\",a,b,c,d,e,f,g);\n }\n }\n}\n\n\nvoid\nge()\n{\n for (e = lo;e <= hi; e++)\n if ((!unique) || ((e != a) && (e != c) && (e != d)))\n {\n g = d + e;\n if ((g >= lo) && (g <= hi) &&\n ((!unique) || ((g != a) && (g != c) &&\n (g != d) && (g != e))))\n bf();\n }\n}\n\nvoid\nacd()\n{\n for (c = lo;c <= hi; c++)\n for (d = lo;d <= hi; d++)\n if ((!unique) || (c != d))\n {\n a = c + d;\n if ((a >= lo) && (a <= hi) &&\n ((!unique) || ((c != 0) && (d != 0))))\n ge();\n }\n}\n\n\nvoid\nfoursquares(int plo,int phi, int punique,int pshow)\n{\n lo = plo;\n hi = phi;\n unique = punique;\n show = pshow;\n solutions = 0;\n\n printf(\"\\n\");\n\n acd();\n\n if (unique)\n printf(\"\\n%d unique solutions in %d to %d\\n\",solutions,lo,hi);\n else\n printf(\"\\n%d non-unique solutions in %d to %d\\n\",solutions,lo,hi);\n}\n\nmain()\n{\n foursquares(1,7,TRUE,TRUE);\n foursquares(3,9,TRUE,TRUE);\n foursquares(0,9,FALSE,FALSE);\n}\n"} {"title": "A+B", "language": "C", "task": "'''A+B''' --- a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.\n\n\n;Task:\nGiven two integers, '''A''' and '''B'''. \n\nTheir sum needs to be calculated.\n\n\n;Input data:\nTwo integers are written in the input stream, separated by space(s):\n: (-1000 \\le A,B \\le +1000)\n\n\n;Output data:\nThe required output is one integer: the sum of '''A''' and '''B'''.\n\n\n;Example:\n::{|class=\"standard\"\n ! input \n ! output \n |-\n | 2 2 \n | 4 \n |-\n | 3 2 \n | 5 \n |}\n\n", "solution": "// Input file: input.txt\n// Output file: output.txt\n#include \nint main()\n{\n freopen(\"input.txt\", \"rt\", stdin);\n freopen(\"output.txt\", \"wt\", stdout);\n int a, b;\n scanf(\"%d%d\", &a, &b);\n printf(\"%d\\n\", a + b);\n return 0;\n}"} {"title": "ABC problem", "language": "C", "task": "You are given a collection of ABC blocks (maybe like the ones you had when you were a kid). \n\nThere are twenty blocks with two letters on each block. \n\nA complete alphabet is guaranteed amongst all sides of the blocks. \n\nThe sample collection of blocks: \n (B O)\n (X K)\n (D Q)\n (C P)\n (N A)\n (G T)\n (R E)\n (T G)\n (Q D)\n (F S)\n (J W)\n (H U)\n (V I)\n (A N)\n (O B)\n (E R)\n (F S)\n (L Y)\n (P C)\n (Z M)\n\n\n;Task:\nWrite a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks. \n\n\nThe rules are simple:\n::# Once a letter on a block is used that block cannot be used again\n::# The function should be case-insensitive\n::# Show the output on this page for the following 7 words in the following example\n\n\n;Example:\n >>> can_make_word(\"A\")\n True\n >>> can_make_word(\"BARK\")\n True\n >>> can_make_word(\"BOOK\")\n False\n >>> can_make_word(\"TREAT\")\n True\n >>> can_make_word(\"COMMON\")\n False\n >>> can_make_word(\"SQUAD\")\n True\n >>> can_make_word(\"CONFUSE\")\n True\n\n", "solution": "#include \n#include \n\nint can_make_words(char **b, char *word)\n{\n\tint i, ret = 0, c = toupper(*word);\n\n#define SWAP(a, b) if (a != b) { char * tmp = a; a = b; b = tmp; }\n\n\tif (!c) return 1;\n\tif (!b[0]) return 0;\n\n\tfor (i = 0; b[i] && !ret; i++) {\n\t\tif (b[i][0] != c && b[i][1] != c) continue;\n\t\tSWAP(b[i], b[0]);\n\t\tret = can_make_words(b + 1, word + 1);\n\t\tSWAP(b[i], b[0]);\n\t}\n\n\treturn ret;\n}\n\nint main(void)\n{\n\tchar* blocks[] = {\n\t\t\"BO\", \"XK\", \"DQ\", \"CP\", \"NA\", \n\t\t\"GT\", \"RE\", \"TG\", \"QD\", \"FS\", \n\t\t\"JW\", \"HU\", \"VI\", \"AN\", \"OB\", \n\t\t\"ER\", \"FS\", \"LY\", \"PC\", \"ZM\",\n\t\t0 };\n\n\tchar *words[] = {\n\t\t\"\", \"A\", \"BARK\", \"BOOK\", \"TREAT\", \"COMMON\", \"SQUAD\", \"Confuse\", 0\n\t};\n\n\tchar **w;\n\tfor (w = words; *w; w++)\n\t\tprintf(\"%s\\t%d\\n\", *w, can_make_words(blocks, *w));\n\n\treturn 0;\n}"} {"title": "ASCII art diagram converter", "language": "C", "task": "Given the RFC 1035 message diagram from Section 4.1.1 (Header section format) as a string:\nhttp://www.ietf.org/rfc/rfc1035.txt\n\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ID |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n |QR| Opcode |AA|TC|RD|RA| Z | RCODE |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | QDCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ANCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | NSCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ARCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n\nWhere (every column of the table is 1 bit):\n\n ID is 16 bits\n QR = Query (0) or Response (1)\n Opcode = Four bits defining kind of query:\n 0: a standard query (QUERY)\n 1: an inverse query (IQUERY)\n 2: a server status request (STATUS)\n 3-15: reserved for future use\n AA = Authoritative Answer bit\n TC = Truncation bit\n RD = Recursion Desired bit\n RA = Recursion Available bit\n Z = Reserved\n RCODE = Response code\n QC = Question Count\n ANC = Answer Count\n AUC = Authority Count\n ADC = Additional Count\n\nWrite a function, member function, class or template that accepts a similar multi-line string as input to define a data structure or something else able to decode or store a header with that specified bit structure.\n\nIf your language has macros, introspection, code generation, or powerful enough templates, then accept such string at compile-time to define the header data structure statically.\n\nSuch \"Header\" function or template should accept a table with 8, 16, 32 or 64 columns, and any number of rows. For simplicity the only allowed symbols to define the table are + - | (plus, minus, pipe), and whitespace. Lines of the input string composed just of whitespace should be ignored. Leading and trailing whitespace in the input string should be ignored, as well as before and after each table row. The box for each bit of the diagram takes four chars \"+--+\". The code should perform a little of validation of the input string, but for brevity a full validation is not required.\n\nBonus: perform a thoroughly validation of the input string.\n\n", "solution": "#include \n#include \n#include \nenum { MAX_ROWS=14, MAX_NAMES=20, NAME_SZ=80 };\n\nchar *Lines[MAX_ROWS] = {\n \" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n \" | ID |\",\n \" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n \" |QR| Opcode |AA|TC|RD|RA| Z | RCODE |\",\n \" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n \" | QDCOUNT |\",\n \" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n \" | ANCOUNT |\",\n \" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n \" | NSCOUNT |\",\n \" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n \" | ARCOUNT |\",\n \" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\"\n};\ntypedef struct {\n unsigned bit3s;\n unsigned mask;\n unsigned data;\n char A[NAME_SZ+2];\n}NAME_T;\nNAME_T names[MAX_NAMES];\nunsigned idx_name;\nenum{ID,BITS,QDCOUNT,ANCOUNT,NSCOUNT,ARCOUNT,MAX_HDR};\nunsigned header[MAX_HDR]; // for test\nunsigned idx_hdr;\n\nint bit_hdr(char *pLine);\nint bit_names(char *pLine);\nvoid dump_names(void);\nvoid make_test_hdr(void);\n\nint main(void){\n char *p1; int rv;\n printf(\"Extract meta-data from bit-encoded text form\\n\");\n make_test_hdr();\n idx_name = 0;\n for( int i=0; i0) continue;\n if( rv = bit_names(Lines[i]),rv>0) continue;\n //printf(\"%s, %d\\n\",p1, numbits );\n }\n dump_names();\n}\n\nint bit_hdr(char *pLine){ // count the '+--'\n char *p1 = strchr(pLine,'+');\n if( p1==NULL ) return 0;\n int numbits=0;\n for( int i=0; i ' ') tmp[k++] = p1[j];\n }\n tmp[k]= 0; sz++;\n NAME_T *pn = &names[idx_name++];\n strcpy(&pn->A[0], &tmp[0]);\n pn->bit3s = sz/3;\n if( pn->bit3s < 16 ){\n\t for( int i=0; ibit3s; i++){\n\t pn->mask |= 1 << maskbitcount--;\n\t }\n\t pn->data = header[idx_hdr] & pn->mask;\n\t unsigned m2 = pn->mask;\n\t while( (m2 & 1)==0 ){\n\t m2>>=1; \n\t pn->data >>= 1;\n\t }\n\t if( pn->mask == 0xf ) idx_hdr++;\n\n }\n else{\n\t pn->data = header[idx_hdr++];\n }\n }\n return sz;\n}\n\nvoid dump_names(void){ // print extracted names and bits\n NAME_T *pn;\n printf(\"-name-bits-mask-data-\\n\");\n for( int i=0; ibit3s < 1 ) break;\n printf(\"%10s %2d X%04x = %u\\n\",pn->A, pn->bit3s, pn->mask, pn->data);\n }\n puts(\"bye..\");\n}\n\nvoid make_test_hdr(void){\n header[ID] = 1024;\n header[QDCOUNT] = 12;\n header[ANCOUNT] = 34;\n header[NSCOUNT] = 56;\n header[ARCOUNT] = 78;\n // QR OP AA TC RD RA Z RCODE\n // 1 0110 1 0 1 0 000 1010\n // 1011 0101 0000 1010\n // B 5 0 A\n header[BITS] = 0xB50A;\n}\n"} {"title": "Abbreviations, easy", "language": "C", "task": "This task is an easier (to code) variant of the Rosetta Code task: [[Abbreviations, simple]].\n\n\nFor this task, the following ''command table'' will be used:\n Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\n COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\n MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\n READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\n RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up\n\n\n\n\nNotes concerning the above ''command table'':\n::* it can be thought of as one long literal string (with blanks at end-of-lines)\n::* it may have superfluous blanks\n::* it may be in any case (lower/upper/mixed)\n::* the order of the words in the ''command table'' must be preserved as shown\n::* the user input(s) may be in any case (upper/lower/mixed)\n::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)\n::* A valid abbreviation is a word that has:\n:::* at least the minimum length of the number of capital letters of the word in the ''command table''\n:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''\n:::* a length not longer than the word in the ''command table''\n::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTer'''\n::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTer'''\n::::* The number of capital letters in '''ALTer''' indicates that any abbreviation for '''ALTer''' must be at least three letters\n::::* Any word longer than five characters can't be an abbreviation for '''ALTer'''\n::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''Overlay'''\n::* if there isn't any lowercase letters in the word in the ''command table'', then there isn't an abbreviation permitted\n\n\n\n;Task:\n::* The command table needn't be verified/validated.\n::* Write a function to validate if the user \"words\" (given as input) are valid (in the ''command table'').\n::* If the word is valid, then return the full uppercase version of that \"word\".\n::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).\n::* A blank input (or a null input) should return a null string.\n::* Show all output here.\n\n\n;An example test case to be used for this task:\nFor a user string of:\n riG rePEAT copies put mo rest types fup. 6 poweRin\nthe computer program should return the string:\n RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nconst char* command_table =\n \"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy \"\n \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n \"Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO \"\n \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT \"\n \"READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT \"\n \"RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n char* cmd;\n size_t length;\n size_t min_len;\n struct command_tag* next;\n} command_t;\n\n// str is assumed to be all uppercase\nbool command_match(const command_t* command, const char* str) {\n size_t olen = strlen(str);\n return olen >= command->min_len && olen <= command->length\n && strncmp(str, command->cmd, olen) == 0;\n}\n\n// convert string to uppercase\nchar* uppercase(char* str, size_t n) {\n for (size_t i = 0; i < n; ++i)\n str[i] = toupper((unsigned char)str[i]);\n return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n size_t len = 0;\n while (len < n && isupper((unsigned char)str[len]))\n ++len;\n return len;\n}\n\nvoid fatal(const char* message) {\n fprintf(stderr, \"%s\\n\", message);\n exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n void* ptr = malloc(n);\n if (ptr == NULL)\n fatal(\"Out of memory\");\n return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n void* ptr = realloc(p, n);\n if (ptr == NULL)\n fatal(\"Out of memory\");\n return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n size_t size = 0;\n size_t capacity = 16;\n char** words = xmalloc(capacity * sizeof(char*));\n size_t len = strlen(str);\n for (size_t begin = 0; begin < len; ) {\n size_t i = begin;\n for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n begin = i;\n for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n size_t word_len = i - begin;\n if (word_len == 0)\n break;\n char* word = xmalloc(word_len + 1);\n memcpy(word, str + begin, word_len);\n word[word_len] = 0;\n begin += word_len;\n if (capacity == size) {\n capacity *= 2;\n words = xrealloc(words, capacity * sizeof(char*));\n }\n words[size++] = word;\n }\n *count = size;\n return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n command_t* cmd = NULL;\n size_t count = 0;\n char** words = split_into_words(table, &count);\n for (size_t i = 0; i < count; ++i) {\n char* word = words[i];\n command_t* new_cmd = xmalloc(sizeof(command_t));\n size_t word_len = strlen(word);\n new_cmd->length = word_len;\n new_cmd->min_len = get_min_length(word, word_len);\n new_cmd->cmd = uppercase(word, word_len);\n new_cmd->next = cmd;\n cmd = new_cmd;\n }\n free(words);\n return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n while (cmd != NULL) {\n command_t* next = cmd->next;\n free(cmd->cmd);\n free(cmd);\n cmd = next;\n }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n if (command_match(cmd, word))\n return cmd;\n }\n return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n printf(\" input: %s\\n\", input);\n printf(\"output:\");\n size_t count = 0;\n char** words = split_into_words(input, &count);\n for (size_t i = 0; i < count; ++i) {\n char* word = words[i];\n uppercase(word, strlen(word));\n const command_t* cmd_ptr = find_command(commands, word);\n printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n free(word);\n }\n free(words);\n printf(\"\\n\");\n}\n\nint main() {\n command_t* commands = make_command_list(command_table);\n const char* input = \"riG rePEAT copies put mo rest types fup. 6 poweRin\";\n test(commands, input);\n free_command_list(commands);\n return 0;\n}"} {"title": "Abbreviations, simple", "language": "C", "task": "The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an \neasy way to add flexibility when specifying or using commands, sub-commands, options, etc.\n\n\n\nFor this task, the following ''command table'' will be used:\n add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3\n compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate\n 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2\n forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load\n locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2\n msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3\n refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left\n 2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1\n\n\n\n\nNotes concerning the above ''command table'':\n::* it can be thought of as one long literal string (with blanks at end-of-lines)\n::* it may have superfluous blanks\n::* it may be in any case (lower/upper/mixed)\n::* the order of the words in the ''command table'' must be preserved as shown\n::* the user input(s) may be in any case (upper/lower/mixed)\n::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)\n::* a command is followed by an optional number, which indicates the minimum abbreviation\n::* A valid abbreviation is a word that has:\n:::* at least the minimum length of the word's minimum number in the ''command table''\n:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''\n:::* a length not longer than the word in the ''command table''\n::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTER 3'''\n::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTER 3'''\n::::* The '''3''' indicates that any abbreviation for '''ALTER''' must be at least three characters\n::::* Any word longer than five characters can't be an abbreviation for '''ALTER'''\n::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''overlay 1'''\n::* if there isn't a number after the command, then there isn't an abbreviation permitted\n\n\n\n;Task:\n::* The command table needn't be verified/validated.\n::* Write a function to validate if the user \"words\" (given as input) are valid (in the ''command table'').\n::* If the word is valid, then return the full uppercase version of that \"word\".\n::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).\n::* A blank input (or a null input) should return a null string.\n::* Show all output here.\n\n\n;An example test case to be used for this task:\nFor a user string of:\n riG rePEAT copies put mo rest types fup. 6 poweRin\nthe computer program should return the string:\n RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nconst char* command_table =\n \"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 \"\n \"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate \"\n \"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n \"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load \"\n \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 \"\n \"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 \"\n \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n \"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1\";\n\ntypedef struct command_tag {\n char* cmd;\n size_t length;\n size_t min_len;\n struct command_tag* next;\n} command_t;\n\n// str is assumed to be all uppercase\nbool command_match(const command_t* command, const char* str) {\n size_t olen = strlen(str);\n return olen >= command->min_len && olen <= command->length\n && strncmp(str, command->cmd, olen) == 0;\n}\n\n// convert string to uppercase\nchar* uppercase(char* str, size_t n) {\n for (size_t i = 0; i < n; ++i)\n str[i] = toupper((unsigned char)str[i]);\n return str;\n}\n\nvoid fatal(const char* message) {\n fprintf(stderr, \"%s\\n\", message);\n exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n void* ptr = malloc(n);\n if (ptr == NULL)\n fatal(\"Out of memory\");\n return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n void* ptr = realloc(p, n);\n if (ptr == NULL)\n fatal(\"Out of memory\");\n return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n size_t size = 0;\n size_t capacity = 16;\n char** words = xmalloc(capacity * sizeof(char*));\n size_t len = strlen(str);\n for (size_t begin = 0; begin < len; ) {\n size_t i = begin;\n for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n begin = i;\n for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n size_t word_len = i - begin;\n if (word_len == 0)\n break;\n char* word = xmalloc(word_len + 1);\n memcpy(word, str + begin, word_len);\n word[word_len] = 0;\n begin += word_len;\n if (capacity == size) {\n capacity *= 2;\n words = xrealloc(words, capacity * sizeof(char*));\n }\n words[size++] = word;\n }\n *count = size;\n return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n command_t* cmd = NULL;\n size_t count = 0;\n char** words = split_into_words(table, &count);\n for (size_t i = 0; i < count; ++i) {\n char* word = words[i];\n command_t* new_cmd = xmalloc(sizeof(command_t));\n size_t word_len = strlen(word);\n new_cmd->length = word_len;\n new_cmd->min_len = word_len;\n new_cmd->cmd = uppercase(word, word_len);\n if (i + 1 < count) {\n char* eptr = 0;\n unsigned long min_len = strtoul(words[i + 1], &eptr, 10);\n if (min_len > 0 && *eptr == 0) {\n free(words[i + 1]);\n new_cmd->min_len = min_len;\n ++i;\n }\n }\n new_cmd->next = cmd;\n cmd = new_cmd;\n }\n free(words);\n return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n while (cmd != NULL) {\n command_t* next = cmd->next;\n free(cmd->cmd);\n free(cmd);\n cmd = next;\n }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n if (command_match(cmd, word))\n return cmd;\n }\n return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n printf(\" input: %s\\n\", input);\n printf(\"output:\");\n size_t count = 0;\n char** words = split_into_words(input, &count);\n for (size_t i = 0; i < count; ++i) {\n char* word = words[i];\n uppercase(word, strlen(word));\n const command_t* cmd_ptr = find_command(commands, word);\n printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n free(word);\n }\n free(words);\n printf(\"\\n\");\n}\n\nint main() {\n command_t* commands = make_command_list(command_table);\n const char* input = \"riG rePEAT copies put mo rest types fup. 6 poweRin\";\n test(commands, input);\n free_command_list(commands);\n return 0;\n}"} {"title": "Abelian sandpile model", "language": "C", "task": "{{wikipedia|Abelian sandpile model}}\nImplement the '''Abelian sandpile model''' also known as '''Bak-Tang-Wiesenfeld model'''. Its history, mathematical definition and properties can be found under its wikipedia article.\n\nThe task requires the creation of a 2D grid of arbitrary size on which \"piles of sand\" can be placed. Any \"pile\" that has 4 or more sand particles on it ''collapses'', resulting in '''four particles being subtracted from the pile''' and '''distributed among its neighbors.'''\n\nIt is recommended to display the output in some kind of image format, as terminal emulators are usually too small to display images larger than a few dozen characters tall. As an example of how to accomplish this, see the Bitmap/Write a PPM file task.\nExamples up to 2^30, wow!\njavascript running on web\n'''Examples:'''\n\n\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 1 0 0\n0 0 4 0 0 -> 0 1 0 1 0\n0 0 0 0 0 0 0 1 0 0\n0 0 0 0 0 0 0 0 0 0\n\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 1 0 0\n0 0 6 0 0 -> 0 1 2 1 0\n0 0 0 0 0 0 0 1 0 0\n0 0 0 0 0 0 0 0 0 0\n\n0 0 0 0 0 0 0 1 0 0\n0 0 0 0 0 0 2 1 2 0\n0 0 16 0 0 -> 1 1 0 1 1\n0 0 0 0 0 0 2 1 2 0\n0 0 0 0 0 0 0 1 0 0\n\n", "solution": "#include\n#include\n#include\n\nint main(int argc, char** argv)\n{\n\tint i,j,sandPileEdge, centerPileHeight, processAgain = 1,top,down,left,right;\t\n\tint** sandPile;\n\tchar* fileName;\n\tstatic unsigned char colour[3];\n\n\tif(argc!=3){\n\t\tprintf(\"Usage: %s
\",argv[0]);\n\t\treturn 0;\n\t}\n\n\tsandPileEdge = atoi(argv[1]);\n\tcenterPileHeight = atoi(argv[2]);\n\n\tif(sandPileEdge<=0 || centerPileHeight<=0){\n\t\tprintf(\"Sand pile and center pile dimensions must be positive integers.\");\n\t\treturn 0;\n\t}\n\n\tsandPile = (int**)malloc(sandPileEdge * sizeof(int*));\n\n\tfor(i=0;i=4){\t\t\t\t\n\t\t\t\t\tif(i-1>=0){\n\t\t\t\t\t\ttop = 1;\n\t\t\t\t\t\tsandPile[i-1][j]+=1;\n\t\t\t\t\t\tif(sandPile[i-1][j]>=4)\n\t\t\t\t\t\t\tprocessAgain = 1;\n\t\t\t\t\t}\n\t\t\t\t\tif(i+1=4)\n\t\t\t\t\t\t\tprocessAgain = 1;\n\t\t\t\t\t}\n\t\t\t\t\tif(j-1>=0){\n\t\t\t\t\t\tleft = 1;\n\t\t\t\t\t\tsandPile[i][j-1]+=1;\n\t\t\t\t\t\tif(sandPile[i][j-1]>=4)\n\t\t\t\t\t\t\tprocessAgain = 1;\n\t\t\t\t\t}\n\t\t\t\t\tif(j+1=4)\n\t\t\t\t\t\t\tprocessAgain = 1;\n\t\t\t\t\t}\n\t\t\t\tsandPile[i][j] -= (top + down + left + right);\n\t\t\t\tif(sandPile[i][j]>=4)\n\t\t\t\t\tprocessAgain = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprintf(\"Final sand pile : \\n\\n\");\n\n\tfor(i=0;i 2n''',\nor, equivalently, the ''sum of proper divisors'' (or aliquot sum) '''s(n) > n'''.\n\n\n;E.G.:\n'''12''' is abundant, it has the proper divisors '''1,2,3,4 & 6''' which sum to '''16''' ( > '''12''' or '''n'''); \n or alternately, has the sigma sum of '''1,2,3,4,6 & 12''' which sum to '''28''' ( > '''24''' or '''2n''').\n\n\nAbundant numbers are common, though '''even''' abundant numbers seem to be much more common than '''odd''' abundant numbers. \n\nTo make things more interesting, this task is specifically about finding ''odd abundant numbers''.\n\n\n;Task\n*Find and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum.\n*Find and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum.\n*Find and display here: the first abundant odd number greater than one billion (109) and either its proper divisor sum or sigma sum.\n\n\n;References:\n:* OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n)\n:* American Journal of Mathematics, Vol. 35, No. 4 (Oct., 1913), pp. 413-422 - Finiteness of the Odd Perfect and Primitive Abundant Numbers with n Distinct Prime Factors (LE Dickson)\n\n", "solution": "#include \n#include \n\n// The following function is for odd numbers ONLY\n// Please use \"for (unsigned i = 2, j; i*i <= n; i ++)\" for even and odd numbers\nunsigned sum_proper_divisors(const unsigned n) {\n unsigned sum = 1;\n for (unsigned i = 3, j; i < sqrt(n)+1; i += 2) if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);\n return sum;\n}\n\nint main(int argc, char const *argv[]) {\n unsigned n, c;\n for (n = 1, c = 0; c < 25; n += 2) if (n < sum_proper_divisors(n)) printf(\"%u: %u\\n\", ++c, n);\n\n for ( ; c < 1000; n += 2) if (n < sum_proper_divisors(n)) c ++;\n printf(\"\\nThe one thousandth abundant odd number is: %u\\n\", n);\n\n for (n = 1000000001 ;; n += 2) if (n < sum_proper_divisors(n)) break;\n printf(\"The first abundant odd number above one billion is: %u\\n\", n);\n \n return 0;\n}"} {"title": "Accumulator factory", "language": "C", "task": "{{requires|Mutable State}}\n\nA problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).\n\n\n;Rules:\nThe detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text'').\n:Before you submit an example, make sure the function\n\n:# Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).Although these exact function and parameter names need not be used\n:# Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) ''(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)''\n:# Generates functions that return the sum of every number ever passed to them, not just the most recent. ''(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)''\n:# Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. ''(Follow your language's conventions here.)''\n:# Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. ''(No global variables or other such things.)''\n: E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'':\n:: x = foo(1); \nx(5); \nfoo(3);\nprint x(2.3);\n: It should print 8.3. ''(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)''\n\n\n;Task:\nCreate a function that implements the described rules. \n\n\nIt need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.\n\nWhere it is not possible to hold exactly to the constraints above, describe the deviations.\n\n", "solution": "#include \n//~ Take a number n and return a function that takes a number i\n#define ACCUMULATOR(name,n) __typeof__(n) name (__typeof__(n) i) { \\\n static __typeof__(n) _n=n; LOGIC; }\n//~ have it return n incremented by the accumulation of i\n#define LOGIC return _n+=i\nACCUMULATOR(x,1.0)\nACCUMULATOR(y,3)\nACCUMULATOR(z,'a')\n#undef LOGIC\nint main (void) {\n printf (\"%f\\n\", x(5)); /* 6.000000 */\n printf (\"%f\\n\", x(2.3)); /* 8.300000 */\n printf (\"%i\\n\", y(5.0)); /* 8 */\n printf (\"%i\\n\", y(3.3)); /* 11 */\n printf (\"%c\\n\", z(5)); /* f */\n return 0;\n}"} {"title": "Aliquot sequence classifications", "language": "C", "task": "An aliquot sequence of a positive integer K is defined recursively as the first member\nbeing K and subsequent members being the sum of the [[Proper divisors]] of the previous term.\n\n:* If the terms eventually reach 0 then the series for K is said to '''terminate'''.\n\n:There are several classifications for non termination:\n:* If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called '''perfect'''.\n:* If the third term ''would'' be repeating K then the sequence repeats with period 2 and K is called '''amicable'''.\n:* If the Nth term ''would'' be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called '''sociable'''.\n:Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...\n:* Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called '''aspiring'''.\n:* K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called '''cyclic'''.\n\n:And finally:\n:* Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called '''non-terminating'''. For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating '''16''' terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328. \n\n\n;Task:\n# Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.\n# Use it to display the classification and sequences of the numbers one to ten inclusive.\n# Use it to show the classification and sequences of the following integers, in order:\n:: 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.\n\nShow all output on this page.\n\n\n;Related tasks:\n* [[Abundant, deficient and perfect number classifications]]. (Classifications from only the first two members of the whole sequence).\n* [[Proper divisors]]\n* [[Amicable pairs]]\n\n", "solution": "#include\n#include\n#include\n\nunsigned long long raiseTo(unsigned long long base, unsigned long long power){\n unsigned long long result = 1,i;\n for (i=0; i 1)\n\t\t\tprod *= ((raiseTo(i,count + 1) - 1)/(i-1));\n\t}\n\t\n\tif(n>2)\n\t\tprod *= (n+1);\n\n\treturn prod - temp;\n}\n\nvoid printSeries(unsigned long long* arr,int size,char* type){\n\tint i;\n\t\n\tprintf(\"\\nInteger : %llu, Type : %s, Series : \",arr[0],type);\n\t\n\tfor(i=0;i\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],'.')!=NULL)\n\t\t\tprocessFile(argV[1]);\n\t\telse\n\t\t\taliquotClassifier(strtoull(argV[1],(char**)NULL,10));\n\t}\n\treturn 0;\n}\n"} {"title": "Amb", "language": "C", "task": "Define and give an example of the Amb operator.\n\nThe Amb operator (short for \"ambiguous\") expresses nondeterminism. This doesn't refer to randomness (as in \"nondeterministic universe\") but is closely related to the term as it is used in automata theory (\"non-deterministic finite automaton\").\n\nThe Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.\n\nProblems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent. \n\nEssentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other \"parallel universes\" somehow go away. Amb called with no arguments fails.\n\nFor simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.\n\nA pseudo-code program which satisfies this constraint might look like:\n\nlet x = Amb(1, 2, 3)\nlet y = Amb(7, 6, 4, 5)\nAmb(x * y = 8)\nprint x, y\n\nThe output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.\n\nAlternatively, failure could be represented using strictly Amb():\n\nunless x * y = 8 do Amb()\n\nOr else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:\n\nlet x = Ambsel(1, 2, 3)\nlet y = Ambsel(4, 5, 6)\nAmbassert(x * y = 8)\nprint x, y\n\nwhere Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.\n\nThe task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:\n\n#\"the\" \"that\" \"a\"\n#\"frog\" \"elephant\" \"thing\"\n#\"walked\" \"treaded\" \"grows\"\n#\"slowly\" \"quickly\"\n\nThe constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.\n\nThe only successful sentence is \"that thing grows slowly\"; other combinations do not satisfy the constraint and thus fail.\n\nThe goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.\n\n", "solution": "typedef const char * amb_t;\n\namb_t amb(size_t argc, ...)\n{\n amb_t *choices;\n va_list ap;\n int i;\n \n if(argc) {\n choices = malloc(argc*sizeof(amb_t));\n va_start(ap, argc);\n i = 0;\n do { choices[i] = va_arg(ap, amb_t); } while(++i < argc);\n va_end(ap);\n \n i = 0;\n do { TRY(choices[i]); } while(++i < argc);\n free(choices);\n }\n \n FAIL;\n}\n\nint joins(const char *left, const char *right) { return left[strlen(left)-1] == right[0]; }\n\nint _main() {\n const char *w1,*w2,*w3,*w4;\n \n w1 = amb(3, \"the\", \"that\", \"a\");\n w2 = amb(3, \"frog\", \"elephant\", \"thing\");\n w3 = amb(3, \"walked\", \"treaded\", \"grows\");\n w4 = amb(2, \"slowly\", \"quickly\");\n \n if(!joins(w1, w2)) amb(0);\n if(!joins(w2, w3)) amb(0);\n if(!joins(w3, w4)) amb(0);\n \n printf(\"%s %s %s %s\\n\", w1, w2, w3, w4);\n \n return EXIT_SUCCESS;\n}"} {"title": "Anagrams/Deranged anagrams", "language": "C", "task": "Two or more words are said to be anagrams if they have the same characters, but in a different order. \n\nBy analogy with derangements we define a ''deranged anagram'' as two words with the same characters, but in which the same character does ''not'' appear in the same position in both words.\n\n;Task\n\nUse the word list at unixdict to find and display the longest deranged anagram. \n\n\n;Related\n* [[Permutations/Derangements]]\n* Best shuffle\n\n{{Related tasks/Word plays}}\n\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n// Letter lookup by frequency. This is to reduce word insertion time.\nconst char *freq = \"zqxjkvbpygfwmucldrhsnioate\";\nint char_to_idx[128];\n\n// Trie structure of sorts\nstruct word {\n\tconst char *w;\n\tstruct word *next;\n};\n\nunion node {\n\tunion node *down[10];\n\tstruct word *list[10];\n};\n\nint deranged(const char *s1, const char *s2)\n{\n\tint i;\n\tfor (i = 0; s1[i]; i++)\n\t\tif (s1[i] == s2[i]) return 0;\n\treturn 1;\n}\n\nint count_letters(const char *s, unsigned char *c)\n{\n\tint i, len;\n\tmemset(c, 0, 26);\n\tfor (len = i = 0; s[i]; i++) {\n\t\tif (s[i] < 'a' || s[i] > 'z')\n\t\t\treturn 0;\n\t\tlen++, c[char_to_idx[(unsigned char)s[i]]]++;\n\t}\n\treturn len;\n}\n\nconst char * insert(union node *root, const char *s, unsigned char *cnt)\n{\n\tint i;\n\tunion node *n;\n\tstruct word *v, *w = 0;\n\n\tfor (i = 0; i < 25; i++, root = n) {\n\t\tif (!(n = root->down[cnt[i]]))\n\t\t\troot->down[cnt[i]] = n = calloc(1, sizeof(union node));\n\t}\n\n\tw = malloc(sizeof(struct word));\n\tw->w = s;\n\tw->next = root->list[cnt[25]];\n\troot->list[cnt[25]] = w;\n\n\tfor (v = w->next; v; v = v->next) {\n\t\tif (deranged(w->w, v->w))\n\t\t\treturn v->w;\n\t}\n\treturn 0;\n}\n\nint main(int c, char **v)\n{\n\tint i, j = 0;\n\tchar *words;\n\tstruct stat st;\n\n\tint fd = open(c < 2 ? \"unixdict.txt\" : v[1], O_RDONLY);\n\tif (fstat(fd, &st) < 0) return 1;\n\n\twords = malloc(st.st_size);\n\tread(fd, words, st.st_size);\n\tclose(fd);\n\n\tunion node root = {{0}};\n\tunsigned char cnt[26];\n\tint best_len = 0;\n\tconst char *b1, *b2;\n\n\tfor (i = 0; freq[i]; i++)\n\t\tchar_to_idx[(unsigned char)freq[i]] = i;\n\n\t/* count words, change newline to null */\n\tfor (i = j = 0; i < st.st_size; i++) {\n\t\tif (words[i] != '\\n') continue;\n\t\twords[i] = '\\0';\n\n\t\tif (i - j > best_len) {\n\t\t\tcount_letters(words + j, cnt);\n\t\t\tconst char *match = insert(&root, words + j, cnt);\n\n\t\t\tif (match) {\n\t\t\t\tbest_len = i - j;\n\t\t\t\tb1 = words + j;\n\t\t\t\tb2 = match;\n\t\t\t}\n\t\t}\n\n\t\tj = ++i;\n\t}\n\n\tif (best_len) printf(\"longest derangement: %s %s\\n\", b1, b2);\n\n\treturn 0;\n}"} {"title": "Angle difference between two bearings", "language": "C", "task": "Finding the angle between two bearings is often confusing.[https://stackoverflow.com/questions/16180595/find-the-angle-between-two-bearings]\n\n\n;Task:\nFind the angle which is the result of the subtraction '''b2 - b1''', where '''b1''' and '''b2''' are the bearings. \n\nInput bearings are expressed in the range '''-180''' to '''+180''' degrees. \nThe result is also expressed in the range '''-180''' to '''+180''' degrees. \n\n\nCompute the angle for the following pairs:\n* 20 degrees ('''b1''') and 45 degrees ('''b2''')\n* -45 and 45\n* -85 and 90\n* -95 and 90\n* -45 and 125\n* -45 and 145\n* 29.4803 and -88.6381\n* -78.3251 and -159.036\n\n\n;Optional extra: \nAllow the input bearings to be any (finite) value. \n\n\n;Test cases:\n* -70099.74233810938 and 29840.67437876723\n* -165313.6666297357 and 33693.9894517456\n* 1174.8380510598456 and -154146.66490124757\n* 60175.77306795546 and 42213.07192354373\n\n", "solution": "#include\n#include\n#include\n\nvoid processFile(char* name){\n\t\n\tint i,records;\n\tdouble diff,b1,b2;\n\tFILE* fp = fopen(name,\"r\");\n\t\n\tfscanf(fp,\"%d\\n\",&records);\n\t\n\tfor(i=0;i=180)?diff-360:diff));\t\n\t}\n\t\n\tfclose(fp);\n}\n\nint main(int argC,char* argV[])\n{\n\tdouble diff;\n\t\n\tif(argC < 2)\n\t\tprintf(\"Usage : %s \",argV[0]);\n\telse if(argC == 2)\n\t\tprocessFile(argV[1]);\n\telse{\n\t\tdiff = fmod(atof(argV[2])-atof(argV[1]),360.0);\n\t\tprintf(\"Difference between b2(%s) and b1(%s) is %lf\",argV[2],argV[1],(diff<-180)?diff+360:((diff>=180)?diff-360:diff));\n\t}\n\n\treturn 0;\n}\n"} {"title": "Apply a digital filter (direct form II transposed)", "language": "C", "task": "Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the \"direct form II transposed\" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [https://ccrma.stanford.edu/~jos/fp/Transposed_Direct_Forms.html]\n\n;Task:\n\nFilter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667]\n\nThe signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]\n\n;See also:\n[Wikipedia on Butterworth filters]\n\n\n", "solution": "#include\n#include\n#include\n\n#define MAX_LEN 1000\n\ntypedef struct{\n\tfloat* values;\n\tint size;\n}vector;\n\nvector extractVector(char* str){\n\tvector coeff;\n\tint i=0,count = 1;\n\tchar* token;\n\t\n\twhile(str[i]!=00){\n\t\tif(str[i++]==' ')\n\t\t\tcount++;\n\t}\n\t\n\tcoeff.values = (float*)malloc(count*sizeof(float));\n\tcoeff.size = count;\n\t\n\ttoken = strtok(str,\" \");\n\t\n\ti = 0;\n\t\n\twhile(token!=NULL){\n\t\tcoeff.values[i++] = atof(token);\n\t\ttoken = strtok(NULL,\" \");\n\t}\n\t\n\treturn coeff;\n}\n\nvector processSignalFile(char* fileName){\n\tint i,j;\n\tfloat sum;\n\tchar str[MAX_LEN];\n\tvector coeff1,coeff2,signal,filteredSignal;\n\t\n\tFILE* fp = fopen(fileName,\"r\");\n\t\n\tfgets(str,MAX_LEN,fp);\n\tcoeff1 = extractVector(str);\n\t\n\tfgets(str,MAX_LEN,fp);\n\tcoeff2 = extractVector(str);\n\t\n\tfgets(str,MAX_LEN,fp);\n\tsignal = extractVector(str);\n\n fclose(fp);\n\t\n\tfilteredSignal.values = (float*)calloc(signal.size,sizeof(float));\n\tfilteredSignal.size = signal.size;\n\t\n\tfor(i=0;i=0)\n\t\t\t\tsum += coeff2.values[j]*signal.values[i-j];\n\t\t}\n\t\t\n\t\tfor(j=0;j=0)\n\t\t\t\tsum -= coeff1.values[j]*filteredSignal.values[i-j];\n\t\t}\n\t\t\n\t\tsum /= coeff1.values[0];\n\t\tfilteredSignal.values[i] = sum;\n\t}\n\t\n\treturn filteredSignal;\n}\n\nvoid printVector(vector v, char* outputFile){\n\tint i;\n\t\n\tif(outputFile==NULL){\n\t\tprintf(\"[\");\n\t\tfor(i=0;i3)\n\t\tprintf(\"Usage : %s \",argV[0]);\n\telse{\n\t\tif(argC!=2){\n\t\t\tstr = (char*)malloc((strlen(argV[2]) + strlen(str) + 1)*sizeof(char));\n\t\t\tstrcpy(str,\"written to \");\n\t\t}\n\t\tprintf(\"Filtered signal %s\",(argC==2)?\"is:\\n\":strcat(str,argV[2]));\n\t\tprintVector(processSignalFile(argV[1]),argV[2]);\n\t}\n\treturn 0;\n}\n"} {"title": "Archimedean spiral", "language": "C", "task": "The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. \n\n\nAn Archimedean spiral can be described by the equation:\n\n:\\, r=a+b\\theta\n\nwith real numbers ''a'' and ''b''.\n\n\n;Task\nDraw an Archimedean spiral.\n\n", "solution": "#include\n#include\n#include\n\n#define pi M_PI\n\nint main(){\n\tdouble a,b,cycles,incr,i;\n\t\n\tint steps,x=500,y=500;\n\t\n\tprintf(\"Enter the parameters a and b : \");\n\tscanf(\"%lf%lf\",&a,&b);\n\t\n\tprintf(\"Enter cycles : \");\n\tscanf(\"%lf\",&cycles);\n\t\n\tprintf(\"Enter divisional steps : \");\n\tscanf(\"%d\",&steps);\n\t\n\tincr = 1.0/steps;\n\t\n\tinitwindow(1000,1000,\"Archimedean Spiral\");\n\t\n\tfor(i=0;i<=cycles*pi;i+=incr){\n\t\tputpixel(x + (a + b*i)*cos(i),x + (a + b*i)*sin(i),15);\n\t}\n\t\n\tgetch();\n\t\n\tclosegraph();\t\n}\n"} {"title": "Arena storage pool", "language": "C", "task": "Dynamically allocated objects take their memory from a [[heap]]. \n\nThe memory for an object is provided by an '''allocator''' which maintains the storage pool used for the [[heap]].\n\nOften a call to allocator is denoted as\nP := new T\nwhere '''T''' is the type of an allocated object, and '''P''' is a [[reference]] to the object.\n\nThe storage pool chosen by the allocator can be determined by either:\n* the object type '''T'''\n* the type of pointer '''P'''\n\n\nIn the former case objects can be allocated only in one storage pool. \n\nIn the latter case objects of the type can be allocated in any storage pool or on the [[stack]].\n\n\n;Task:\nThe task is to show how allocators and user-defined storage pools are supported by the language. \n\nIn particular:\n# define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.\n# allocate some objects (e.g., integers) in the pool.\n\n\nExplain what controls the storage pool choice in the language.\n\n", "solution": "#include \n#include \n#include \n\n// VERY rudimentary C memory management independent of C library's malloc.\n\n// Linked list (yes, this is inefficient)\nstruct __ALLOCC_ENTRY__\n{\n void * allocatedAddr;\n size_t size;\n struct __ALLOCC_ENTRY__ * next;\n};\ntypedef struct __ALLOCC_ENTRY__ __ALLOCC_ENTRY__;\n\n// Keeps track of allocated memory and metadata\n__ALLOCC_ENTRY__ * __ALLOCC_ROOT__ = NULL;\n__ALLOCC_ENTRY__ * __ALLOCC_TAIL__ = NULL;\n\n// Add new metadata to the table\nvoid _add_mem_entry(void * location, size_t size)\n{\n \n __ALLOCC_ENTRY__ * newEntry = (__ALLOCC_ENTRY__ *) mmap(NULL, sizeof(__ALLOCC_ENTRY__), PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);\n \n if (__ALLOCC_TAIL__ != NULL)\n {\n __ALLOCC_TAIL__ -> next = newEntry;\n __ALLOCC_TAIL__ = __ALLOCC_TAIL__ -> next;\n }\n else\n {\n // Create new table\n __ALLOCC_ROOT__ = newEntry;\n __ALLOCC_TAIL__ = newEntry;\n }\n \n __ALLOCC_ENTRY__ * tail = __ALLOCC_TAIL__;\n tail -> allocatedAddr = location;\n tail -> size = size;\n tail -> next = NULL;\n __ALLOCC_TAIL__ = tail;\n}\n\n// Remove metadata from the table given pointer\nsize_t _remove_mem_entry(void * location)\n{\n __ALLOCC_ENTRY__ * curNode = __ALLOCC_ROOT__;\n \n // Nothing to do\n if (curNode == NULL)\n {\n return 0;\n }\n \n // First entry matches\n if (curNode -> allocatedAddr == location)\n {\n __ALLOCC_ROOT__ = curNode -> next;\n size_t chunkSize = curNode -> size;\n \n // No nodes left\n if (__ALLOCC_ROOT__ == NULL)\n {\n __ALLOCC_TAIL__ = NULL;\n }\n munmap(curNode, sizeof(__ALLOCC_ENTRY__));\n \n return chunkSize;\n }\n \n // If next node is null, remove it\n while (curNode -> next != NULL)\n {\n __ALLOCC_ENTRY__ * nextNode = curNode -> next;\n \n if (nextNode -> allocatedAddr == location)\n {\n size_t chunkSize = nextNode -> size;\n \n if(curNode -> next == __ALLOCC_TAIL__)\n {\n __ALLOCC_TAIL__ = curNode;\n }\n curNode -> next = nextNode -> next;\n munmap(nextNode, sizeof(__ALLOCC_ENTRY__));\n \n return chunkSize;\n }\n \n curNode = nextNode;\n }\n \n // Nothing was found\n return 0;\n}\n\n// Allocate a block of memory with size\n// When customMalloc an already mapped location, causes undefined behavior\nvoid * customMalloc(size_t size)\n{\n // Now we can use 0 as our error state\n if (size == 0)\n {\n return NULL;\n }\n \n void * mapped = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);\n \n // Store metadata\n _add_mem_entry(mapped, size);\n \n return mapped;\n}\n\n// Free a block of memory that has been customMalloc'ed\nvoid customFree(void * addr)\n{\n size_t size = _remove_mem_entry(addr);\n \n munmap(addr, size);\n}\n\nint main(int argc, char const *argv[])\n{\n int *p1 = customMalloc(4*sizeof(int)); // allocates enough for an array of 4 int\n int *p2 = customMalloc(sizeof(int[4])); // same, naming the type directly\n int *p3 = customMalloc(4*sizeof *p3); // same, without repeating the type name\n \n if(p1) {\n for(int n=0; n<4; ++n) // populate the array\n p1[n] = n*n;\n for(int n=0; n<4; ++n) // print it back out\n printf(\"p1[%d] == %d\\n\", n, p1[n]);\n }\n \n customFree(p1);\n customFree(p2);\n customFree(p3);\n \n return 0;\n}"} {"title": "Arithmetic-geometric mean", "language": "C", "task": "{{wikipedia|Arithmetic-geometric mean}}\n\n\n;Task:\nWrite a function to compute the arithmetic-geometric mean of two numbers.\n\n\nThe arithmetic-geometric mean of two numbers can be (usefully) denoted as \\mathrm{agm}(a,g), and is equal to the limit of the sequence:\n: a_0 = a; \\qquad g_0 = g\n: a_{n+1} = \\tfrac{1}{2}(a_n + g_n); \\quad g_{n+1} = \\sqrt{a_n g_n}.\nSince the limit of a_n-g_n tends (rapidly) to zero with iterations, this is an efficient method.\n\nDemonstrate the function by calculating:\n:\\mathrm{agm}(1,1/\\sqrt{2})\n \n\n;Also see:\n* mathworld.wolfram.com/Arithmetic-Geometric Mean\n\n", "solution": "/*Arithmetic Geometric Mean of 1 and 1/sqrt(2)\n\n Nigel_Galloway\n February 7th., 2012.\n*/\n\n#include \"gmp.h\"\n\nvoid agm (const mpf_t in1, const mpf_t in2, mpf_t out1, mpf_t out2) {\n\tmpf_add (out1, in1, in2);\n\tmpf_div_ui (out1, out1, 2);\n\tmpf_mul (out2, in1, in2);\n\tmpf_sqrt (out2, out2);\n}\n\nint main (void) {\n\tmpf_set_default_prec (65568);\n\tmpf_t x0, y0, resA, resB;\n\n\tmpf_init_set_ui (y0, 1);\n\tmpf_init_set_d (x0, 0.5);\n\tmpf_sqrt (x0, x0);\n\tmpf_init (resA);\n\tmpf_init (resB);\n\n\tfor(int i=0; i<7; i++){\n\t\tagm(x0, y0, resA, resB);\n\t\tagm(resA, resB, x0, y0);\n\t}\n\tgmp_printf (\"%.20000Ff\\n\", x0);\n\tgmp_printf (\"%.20000Ff\\n\\n\", y0);\n\n\treturn 0;\n}"} {"title": "Arithmetic-geometric mean/Calculate Pi", "language": "C", "task": "Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate \\pi.\n\nWith the same notations used in [[Arithmetic-geometric mean]], we can summarize the paper by writing:\n\n\\pi =\n\\frac{4\\; \\mathrm{agm}(1, 1/\\sqrt{2})^2}\n{1 - \\sum\\limits_{n=1}^{\\infty} 2^{n+1}(a_n^2-g_n^2)}\n\n\nThis allows you to make the approximation, for any large '''N''':\n\n\\pi \\approx\n\\frac{4\\; a_N^2}\n{1 - \\sum\\limits_{k=1}^N 2^{k+1}(a_k^2-g_k^2)}\n\n\nThe purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of \\pi.\n\n", "solution": "See [[Talk:Arithmetic-geometric mean]]\n\n"} {"title": "Arithmetic numbers", "language": "C", "task": "Definition\nA positive integer '''n''' is an arithmetic number if the average of its positive divisors is also an integer.\n\nClearly all odd primes '''p''' must be arithmetic numbers because their only divisors are '''1''' and '''p''' whose sum is even and hence their average must be an integer. However, the prime number '''2''' is not an arithmetic number because the average of its divisors is 1.5.\n\n;Example\n30 is an arithmetic number because its 7 divisors are: [1, 2, 3, 5, 6, 10, 15, 30], their sum is 72 and average 9 which is an integer. \n\n;Task\nCalculate and show here:\n\n1. The first 100 arithmetic numbers.\n\n2. The '''x'''th arithmetic number where '''x''' = 1,000 and '''x''' = 10,000.\n\n3. How many of the first '''x''' arithmetic numbers are composite.\n\nNote that, technically, the arithmetic number '''1''' is neither prime nor composite.\n\n;Stretch\nCarry out the same exercise in 2. and 3. above for '''x''' = 100,000 and '''x''' = 1,000,000.\n\n;References\n\n* Wikipedia: Arithmetic number\n* OEIS:A003601 - Numbers n such that the average of the divisors of n is an integer\n\n", "solution": "#include \n\nvoid divisor_count_and_sum(unsigned int n, unsigned int* pcount,\n unsigned int* psum) {\n unsigned int divisor_count = 1;\n unsigned int divisor_sum = 1;\n unsigned int power = 2;\n for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n ++divisor_count;\n divisor_sum += power;\n }\n for (unsigned int p = 3; p * p <= n; p += 2) {\n unsigned int count = 1, sum = 1;\n for (power = p; n % p == 0; power *= p, n /= p) {\n ++count;\n sum += power;\n }\n divisor_count *= count;\n divisor_sum *= sum;\n }\n if (n > 1) {\n divisor_count *= 2;\n divisor_sum *= n + 1;\n }\n *pcount = divisor_count;\n *psum = divisor_sum;\n}\n\nint main() {\n unsigned int arithmetic_count = 0;\n unsigned int composite_count = 0;\n\n for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) {\n unsigned int divisor_count;\n unsigned int divisor_sum;\n divisor_count_and_sum(n, &divisor_count, &divisor_sum);\n if (divisor_sum % divisor_count != 0)\n continue;\n ++arithmetic_count;\n if (divisor_count > 2)\n ++composite_count;\n if (arithmetic_count <= 100) {\n printf(\"%3u \", n);\n if (arithmetic_count % 10 == 0)\n printf(\"\\n\");\n }\n if (arithmetic_count == 1000 || arithmetic_count == 10000 ||\n arithmetic_count == 100000 || arithmetic_count == 1000000) {\n printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n,\n composite_count);\n }\n }\n return 0;\n}"} {"title": "Array length", "language": "C", "task": "Determine the amount of elements in an array.\n\n\nAs an example use an array holding the strings 'apple' and 'orange'.\n\n\n\n", "solution": "#define _CRT_SECURE_NO_WARNINGS // turn off panic warnings\n#define _CRT_NONSTDC_NO_WARNINGS // enable old-gold POSIX names in MSVS\n\n#include \n#include \n#include \n#include \n#include \n\n\nstruct StringArray\n{\n size_t sizeOfArray;\n size_t numberOfElements;\n char** elements;\n};\ntypedef struct StringArray* StringArray;\n\nStringArray StringArray_new(size_t size)\n{\n StringArray this = calloc(1, sizeof(struct StringArray));\n if (this)\n {\n this->elements = calloc(size, sizeof(int));\n if (this->elements)\n this->sizeOfArray = size;\n else\n {\n free(this);\n this = NULL;\n }\n }\n return this;\n}\n\nvoid StringArray_delete(StringArray* ptr_to_this)\n{\n assert(ptr_to_this != NULL);\n StringArray this = (*ptr_to_this);\n if (this)\n {\n for (size_t i = 0; i < this->sizeOfArray; i++)\n free(this->elements[i]);\n free(this->elements);\n free(this);\n this = NULL;\n }\n}\n\nvoid StringArray_add(StringArray this, ...)\n{\n char* s;\n va_list args;\n va_start(args, this);\n while (this->numberOfElements < this->sizeOfArray && (s = va_arg(args, char*)))\n this->elements[this->numberOfElements++] = strdup(s);\n va_end(args);\n}\n\n\nint main(int argc, char* argv[])\n{\n StringArray a = StringArray_new(10);\n StringArray_add(a, \"apple\", \"orange\", NULL);\n\n printf(\n \"There are %d elements in an array with a capacity of %d elements:\\n\\n\",\n a->numberOfElements, a->sizeOfArray);\n\n for (size_t i = 0; i < a->numberOfElements; i++)\n printf(\" the element %d is the string \\\"%s\\\"\\n\", i, a->elements[i]);\n\n StringArray_delete(&a);\n\n return EXIT_SUCCESS;\n}"} {"title": "Average loop length", "language": "C", "task": "Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence.\n\n\n;Task:\nWrite a program or a script that estimates, for each N, the average length until the first such repetition.\n\nAlso calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one.\n\n\nThis problem comes from the end of Donald Knuth's Christmas tree lecture 2011.\n\nExample of expected output:\n\n N average analytical (error)\n=== ========= ============ =========\n 1 1.0000 1.0000 ( 0.00%)\n 2 1.4992 1.5000 ( 0.05%)\n 3 1.8784 1.8889 ( 0.56%)\n 4 2.2316 2.2188 ( 0.58%)\n 5 2.4982 2.5104 ( 0.49%)\n 6 2.7897 2.7747 ( 0.54%)\n 7 3.0153 3.0181 ( 0.09%)\n 8 3.2429 3.2450 ( 0.07%)\n 9 3.4536 3.4583 ( 0.14%)\n 10 3.6649 3.6602 ( 0.13%)\n 11 3.8091 3.8524 ( 1.12%)\n 12 3.9986 4.0361 ( 0.93%)\n 13 4.2074 4.2123 ( 0.12%)\n 14 4.3711 4.3820 ( 0.25%)\n 15 4.5275 4.5458 ( 0.40%)\n 16 4.6755 4.7043 ( 0.61%)\n 17 4.8877 4.8579 ( 0.61%)\n 18 4.9951 5.0071 ( 0.24%)\n 19 5.1312 5.1522 ( 0.41%)\n 20 5.2699 5.2936 ( 0.45%)\n\n", "solution": "#include \n#include \n#include \n#include \n\n#define MAX_N 20\n#define TIMES 1000000\n\ndouble factorial(int n) {\n\tdouble f = 1;\n\tint i;\n\tfor (i = 1; i <= n; i++) f *= i;\n\treturn f;\n}\n\ndouble expected(int n) {\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 1; i <= n; i++)\n\t\tsum += factorial(n) / pow(n, i) / factorial(n - i);\n\treturn sum;\n}\n\nint randint(int n) {\n\tint r, rmax = RAND_MAX / n * n;\n\twhile ((r = rand()) >= rmax);\n\treturn r / (RAND_MAX / n);\n}\n\nint test(int n, int times) {\n\tint i, count = 0;\n\tfor (i = 0; i < times; i++) {\n\t\tint x = 1, bits = 0;\n\t\twhile (!(bits & x)) {\n\t\t\tcount++;\n\t\t\tbits |= x;\n\t\t\tx = 1 << randint(n);\n\t\t}\n\t}\n\treturn count;\n}\n\nint main(void) {\n\tsrand(time(0));\n\tputs(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n\tint n;\n\tfor (n = 1; n <= MAX_N; n++) {\n\t\tint cnt = test(n, TIMES);\n\t\tdouble avg = (double)cnt / TIMES;\n\t\tdouble theory = expected(n);\n\t\tdouble diff = (avg / theory - 1) * 100;\n\t\tprintf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, avg, theory, diff);\n\t}\n\treturn 0;\n}"} {"title": "Averages/Mean angle", "language": "C", "task": "{{Related tasks/Statistical measures}}\n\n\n", "solution": "#include\n#include\n\ndouble\nmeanAngle (double *angles, int size)\n{\n double y_part = 0, x_part = 0;\n int i;\n\n for (i = 0; i < size; i++)\n {\n x_part += cos (angles[i] * M_PI / 180);\n y_part += sin (angles[i] * M_PI / 180);\n }\n\n return atan2 (y_part / size, x_part / size) * 180 / M_PI;\n}\n\nint\nmain ()\n{\n double angleSet1[] = { 350, 10 };\n double angleSet2[] = { 90, 180, 270, 360};\n double angleSet3[] = { 10, 20, 30};\n\n printf (\"\\nMean Angle for 1st set : %lf degrees\", meanAngle (angleSet1, 2));\n printf (\"\\nMean Angle for 2nd set : %lf degrees\", meanAngle (angleSet2, 4));\n printf (\"\\nMean Angle for 3rd set : %lf degrees\\n\", meanAngle (angleSet3, 3));\n return 0;\n}"} {"title": "Averages/Pythagorean means", "language": "C", "task": "{{Related tasks/Statistical measures}}\n\n\n", "solution": "#include \n#include // atoi()\n#include // pow()\n\nint main(int argc, char* argv[])\n{\n int i, count=0;\n double f, sum=0.0, prod=1.0, resum=0.0;\n\n for (i=1; i\n#include \n\ndouble rms(double *v, int n)\n{\n int i;\n double sum = 0.0;\n for(i = 0; i < n; i++)\n sum += v[i] * v[i];\n return sqrt(sum / n);\n}\n\nint main(void)\n{\n double v[] = {1., 2., 3., 4., 5., 6., 7., 8., 9., 10.};\n printf(\"%f\\n\", rms(v, sizeof(v)/sizeof(double)));\n return 0;\n}"} {"title": "Babbage problem", "language": "C", "task": "Charles Babbage\nCharles Babbage's analytical engine.\n\nCharles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:\n{{quote\n | What is the smallest positive integer whose square ends in the digits 269,696?\n | Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.\n}}\nHe thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.\n\n\n;Task\n\nThe task is to find out if Babbage had the right answer -- and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand. \nAs Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.\n\nFor these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].\n\n\n;Motivation\n\nThe aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.\n\n", "solution": "// This code is the implementation of Babbage Problem\n\n#include \n#include \n#include \n \nint main() {\n\tint current = 0, \t//the current number \n\t square;\t\t//the square of the current number\n\n\t//the strategy of take the rest of division by 1e06 is\n\t//to take the a number how 6 last digits are 269696\n\twhile (((square=current*current) % 1000000 != 269696) && (square+INT_MAX)\n\t printf(\"Condition not satisfied before INT_MAX reached.\");\n\telse\t\t \n\t printf (\"The smallest number whose square ends in 269696 is %d\\n\", current);\n\t \n //the end\n\treturn 0 ;\n}\n"} {"title": "Balanced brackets", "language": "C", "task": "'''Task''': \n* Generate a string with '''N''' opening brackets '''[''' and with '''N''' closing brackets ''']''', in some arbitrary order. \n* Determine whether the generated string is ''balanced''; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.\n\n\n\n;Examples:\n (empty) OK\n [] OK \n [][] OK \n [[][]] OK \n ][ NOT OK\n ][][ NOT OK\n []][[] NOT OK\n\n", "solution": "#include\n#include\n#include\n\nint isBal(const char*s,int l){\n signed c=0;\n while(l--)\n\tif(s[l]==']') ++c;\n\telse if(s[l]=='[') if(--c<0) break;\n return !c;\n}\n\nvoid shuffle(char*s,int h){\n int x,t,i=h;\n while(i--){\n\tt=s[x=rand()%h];\n\ts[x]=s[i];\n\ts[i]=t;\n }\n}\n\nvoid genSeq(char*s,int n){\n if(n){\n\tmemset(s,'[',n);\n\tmemset(s+n,']',n);\n\tshuffle(s,n*2);\n }\n s[n*2]=0;\n}\n\nvoid doSeq(int n){\n char s[64];\n const char *o=\"False\";\n genSeq(s,n);\n if(isBal(s,n*2)) o=\"True\";\n printf(\"'%s': %s\\n\",s,o);\n}\n\nint main(){\n int n=0;\n while(n<9) doSeq(n++);\n return 0;\n}"} {"title": "Barnsley fern", "language": "C", "task": "A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).\n\n\n;Task:\nCreate this fractal fern, using the following transformations:\n* f1 (chosen 1% of the time)\n xn + 1 = 0\n yn + 1 = 0.16 yn\n\n* f2 (chosen 85% of the time)\n xn + 1 = 0.85 xn + 0.04 yn\n yn + 1 = -0.04 xn + 0.85 yn + 1.6\n\n* f3 (chosen 7% of the time)\n xn + 1 = 0.2 xn - 0.26 yn\n yn + 1 = 0.23 xn + 0.22 yn + 1.6\n\n* f4 (chosen 7% of the time)\n xn + 1 = -0.15 xn + 0.28 yn\n yn + 1 = 0.26 xn + 0.24 yn + 0.44.\n\nStarting position: x = 0, y = 0\n\n", "solution": "#include\n#include\n#include\n#include\n\nvoid barnsleyFern(int windowWidth, unsigned long iter){\n\t\n\tdouble x0=0,y0=0,x1,y1;\n\tint diceThrow;\n\ttime_t t;\n\tsrand((unsigned)time(&t));\n\t\n\twhile(iter>0){\n\t\tdiceThrow = rand()%100;\n\t\t\n\t\tif(diceThrow==0){\n\t\t\tx1 = 0;\n\t\t\ty1 = 0.16*y0;\n\t\t}\n\t\t\n\t\telse if(diceThrow>=1 && diceThrow<=7){\n\t\t\tx1 = -0.15*x0 + 0.28*y0;\n\t\t\ty1 = 0.26*x0 + 0.24*y0 + 0.44;\n\t\t}\n\t\t\n\t\telse if(diceThrow>=8 && diceThrow<=15){\n\t\t\tx1 = 0.2*x0 - 0.26*y0;\n\t\t\ty1 = 0.23*x0 + 0.22*y0 + 1.6;\n\t\t}\n\t\t\n\t\telse{\n\t\t\tx1 = 0.85*x0 + 0.04*y0;\n\t\t\ty1 = -0.04*x0 + 0.85*y0 + 1.6;\n\t\t}\n\t\t\n\t\tputpixel(30*x1 + windowWidth/2.0,30*y1,GREEN);\n\t\t\n\t\tx0 = x1;\n\t\ty0 = y1;\n\t\t\n\t\titer--;\n\t}\n\n}\n\nint main()\n{\n\tunsigned long num;\n\t\n\tprintf(\"Enter number of iterations : \");\n\tscanf(\"%ld\",&num);\n\t\n\tinitwindow(500,500,\"Barnsley Fern\");\n\t\n\tbarnsleyFern(500,num);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n}\n"} {"title": "Benford's law", "language": "C", "task": "{{Wikipedia|Benford's_law}}\n\n\n'''Benford's law''', also called the '''first-digit law''', refers to the frequency distribution of digits in many (but not all) real-life sources of data. \n\nIn this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. \n\nBenford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.\n\nThis result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.\n\nA set of numbers is said to satisfy Benford's law if the leading digit d (d \\in \\{1, \\ldots, 9\\}) occurs with probability\n\n:::: P(d) = \\log_{10}(d+1)-\\log_{10}(d) = \\log_{10}\\left(1+\\frac{1}{d}\\right)\n\nFor this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).\n\nUse the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. \n\nYou can generate them or load them from a file; whichever is easiest. \n\nDisplay your actual vs expected distribution.\n\n\n''For extra credit:'' Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.\n\n\n;See also:\n* numberphile.com.\n* A starting page on Wolfram Mathworld is {{Wolfram|Benfords|Law}}.\n\n", "solution": "#include \n#include \n#include \n\nfloat *benford_distribution(void)\n{\n static float prob[9];\n for (int i = 1; i < 10; i++)\n prob[i - 1] = log10f(1 + 1.0 / i);\n\n return prob;\n}\n\nfloat *get_actual_distribution(char *fn)\n{\n FILE *input = fopen(fn, \"r\");\n if (!input)\n {\n perror(\"Can't open file\");\n exit(EXIT_FAILURE);\n }\n\n int tally[9] = { 0 };\n char c;\n int total = 0;\n while ((c = getc(input)) != EOF)\n {\n /* get the first nonzero digit on the current line */\n while (c < '1' || c > '9')\n c = getc(input);\n\n tally[c - '1']++;\n total++;\n\n /* discard rest of line */\n while ((c = getc(input)) != '\\n' && c != EOF)\n ;\n }\n fclose(input);\n \n static float freq[9];\n for (int i = 0; i < 9; i++)\n freq[i] = tally[i] / (float) total;\n\n return freq;\n}\n\nint main(int argc, char **argv)\n{\n if (argc != 2)\n {\n printf(\"Usage: benford \\n\");\n return EXIT_FAILURE;\n }\n\n float *actual = get_actual_distribution(argv[1]);\n float *expected = benford_distribution(); \n\n puts(\"digit\\tactual\\texpected\");\n for (int i = 0; i < 9; i++)\n printf(\"%d\\t%.3f\\t%.3f\\n\", i + 1, actual[i], expected[i]);\n\n return EXIT_SUCCESS;\n}"} {"title": "Best shuffle", "language": "C", "task": "Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. \n\nA shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative.\n\nDisplay the result as follows: \n\n original string, shuffled string, (score) \n\nThe score gives the number of positions whose character value did ''not'' change. \n\n\n;Example:\n tree, eetr, (0)\n\n\n;Test cases:\n abracadabra\n seesaw\n elk\n grrrrrr\n up\n a\n\n\n;Related tasks\n* [[Anagrams/Deranged anagrams]]\n* [[Permutations/Derangements]]\n\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\n#define DEBUG\n\nvoid best_shuffle(const char* txt, char* result) {\n const size_t len = strlen(txt);\n if (len == 0)\n return;\n\n#ifdef DEBUG\n // txt and result must have the same length\n assert(len == strlen(result));\n#endif\n\n // how many of each character?\n size_t counts[UCHAR_MAX];\n memset(counts, '\\0', UCHAR_MAX * sizeof(int));\n size_t fmax = 0;\n for (size_t i = 0; i < len; i++) {\n counts[(unsigned char)txt[i]]++;\n const size_t fnew = counts[(unsigned char)txt[i]];\n if (fmax < fnew)\n fmax = fnew;\n }\n assert(fmax > 0 && fmax <= len);\n\n // all character positions, grouped by character\n size_t *ndx1 = malloc(len * sizeof(size_t));\n if (ndx1 == NULL)\n exit(EXIT_FAILURE);\n for (size_t ch = 0, i = 0; ch < UCHAR_MAX; ch++)\n if (counts[ch])\n for (size_t j = 0; j < len; j++)\n if (ch == (unsigned char)txt[j]) {\n ndx1[i] = j;\n i++;\n }\n\n // regroup them for cycles\n size_t *ndx2 = malloc(len * sizeof(size_t));\n if (ndx2 == NULL)\n exit(EXIT_FAILURE);\n for (size_t i = 0, n = 0, m = 0; i < len; i++) {\n ndx2[i] = ndx1[n];\n n += fmax;\n if (n >= len) {\n m++;\n n = m;\n }\n }\n\n // how long can our cyclic groups be?\n const size_t grp = 1 + (len - 1) / fmax;\n assert(grp > 0 && grp <= len);\n\n // how many of them are full length?\n const size_t lng = 1 + (len - 1) % fmax;\n assert(lng > 0 && lng <= len);\n\n // rotate each group\n for (size_t i = 0, j = 0; i < fmax; i++) {\n const size_t first = ndx2[j];\n const size_t glen = grp - (i < lng ? 0 : 1);\n for (size_t k = 1; k < glen; k++)\n ndx1[j + k - 1] = ndx2[j + k];\n ndx1[j + glen - 1] = first;\n j += glen;\n }\n\n // result is original permuted according to our cyclic groups\n result[len] = '\\0';\n for (size_t i = 0; i < len; i++)\n result[ndx2[i]] = txt[ndx1[i]];\n\n free(ndx1);\n free(ndx2);\n}\n\nvoid display(const char* txt1, const char* txt2) {\n const size_t len = strlen(txt1);\n assert(len == strlen(txt2));\n int score = 0;\n for (size_t i = 0; i < len; i++)\n if (txt1[i] == txt2[i])\n score++;\n (void)printf(\"%s, %s, (%u)\\n\", txt1, txt2, score);\n}\n\nint main() {\n const char* data[] = {\"abracadabra\", \"seesaw\", \"elk\", \"grrrrrr\",\n \"up\", \"a\", \"aabbbbaa\", \"\", \"xxxxx\"};\n const size_t data_len = sizeof(data) / sizeof(data[0]);\n for (size_t i = 0; i < data_len; i++) {\n const size_t shuf_len = strlen(data[i]) + 1;\n char shuf[shuf_len];\n\n#ifdef DEBUG\n memset(shuf, 0xFF, sizeof shuf);\n shuf[shuf_len - 1] = '\\0';\n#endif\n\n best_shuffle(data[i], shuf);\n display(data[i], shuf);\n }\n\n return EXIT_SUCCESS;\n}"} {"title": "Bin given limits", "language": "C", "task": "You are given a list of n ascending, unique numbers which are to form limits\nfor n+1 bins which count how many of a large set of input numbers fall in the\nrange of each bin.\n\n(Assuming zero-based indexing)\n\n bin[0] counts how many inputs are < limit[0]\n bin[1] counts how many inputs are >= limit[0] and < limit[1]\n ..''\n bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1]\n bin[n] counts how many inputs are >= limit[n-1]\n\n;Task:\nThe task is to create a function that given the ascending limits and a stream/\nlist of numbers, will return the bins; together with another function that\ngiven the same list of limits and the binning will ''print the limit of each bin\ntogether with the count of items that fell in the range''.\n\nAssume the numbers to bin are too large to practically sort.\n\n;Task examples:\nPart 1: Bin using the following limits the given input data\n\n limits = [23, 37, 43, 53, 67, 83]\n data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n\nPart 2: Bin using the following limits the given input data\n\n limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,\n 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,\n 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]\n\nShow output here, on this page.\n", "solution": "#include \n#include \n\nsize_t upper_bound(const int* array, size_t n, int value) {\n size_t start = 0;\n while (n > 0) {\n size_t step = n / 2;\n size_t index = start + step;\n if (value >= array[index]) {\n start = index + 1;\n n -= step + 1;\n } else {\n n = step;\n }\n }\n return start;\n}\n\nint* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {\n int* result = calloc(nlimits + 1, sizeof(int));\n if (result == NULL)\n return NULL;\n for (size_t i = 0; i < ndata; ++i)\n ++result[upper_bound(limits, nlimits, data[i])];\n return result;\n}\n\nvoid print_bins(const int* limits, size_t n, const int* bins) {\n if (n == 0)\n return;\n printf(\" < %3d: %2d\\n\", limits[0], bins[0]);\n for (size_t i = 1; i < n; ++i)\n printf(\">= %3d and < %3d: %2d\\n\", limits[i - 1], limits[i], bins[i]);\n printf(\">= %3d : %2d\\n\", limits[n - 1], bins[n]);\n}\n\nint main() {\n const int limits1[] = {23, 37, 43, 53, 67, 83};\n const int data1[] = {95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57,\n 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,\n 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98,\n 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n printf(\"Example 1:\\n\");\n size_t n = sizeof(limits1) / sizeof(int);\n int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));\n if (b == NULL) {\n fprintf(stderr, \"Out of memory\\n\");\n return EXIT_FAILURE;\n }\n print_bins(limits1, n, b);\n free(b);\n\n const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};\n const int data2[] = {\n 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,\n 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,\n 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,\n 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,\n 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,\n 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,\n 101, 684, 727, 749};\n\n printf(\"\\nExample 2:\\n\");\n n = sizeof(limits2) / sizeof(int);\n b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));\n if (b == NULL) {\n fprintf(stderr, \"Out of memory\\n\");\n return EXIT_FAILURE;\n }\n print_bins(limits2, n, b);\n free(b);\n\n return EXIT_SUCCESS;\n}"} {"title": "Bioinformatics/Sequence mutation", "language": "C", "task": "Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:\n# Choosing a random base position in the sequence.\n# Mutate the sequence by doing one of either:\n## '''S'''wap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base)\n## '''D'''elete the chosen base at the position.\n## '''I'''nsert another base randomly chosen from A,C, G, or T into the sequence at that position.\n# Randomly generate a test DNA sequence of at least 200 bases\n# \"Pretty print\" the sequence and a count of its size, and the count of each base in the sequence\n# Mutate the sequence ten times.\n# \"Pretty print\" the sequence after all mutations, and a count of its size, and the count of each base in the sequence.\n\n;Extra credit:\n* Give more information on the individual mutations applied.\n* Allow mutations to be weighted and/or chosen.\n", "solution": "#include\n#include\n#include\n\ntypedef struct genome{\n char base;\n struct genome *next;\n}genome;\n\ntypedef struct{\n char mutation;\n int position;\n}genomeChange;\n\ntypedef struct{\n int adenineCount,thymineCount,cytosineCount,guanineCount;\n}baseCounts;\n\ngenome *strand;\nbaseCounts baseData;\nint genomeLength = 100, lineLength = 50;\n\nint numDigits(int num){\n int len = 1;\n\n while(num>10){\n num /= 10;\n len++;\n }\n return len;\n}\n\nvoid generateStrand(){\n\n int baseChoice = rand()%4, i;\n genome *strandIterator, *newStrand;\n\n baseData.adenineCount = 0;\n baseData.thymineCount = 0;\n baseData.cytosineCount = 0;\n baseData.guanineCount = 0;\n \n strand = (genome*)malloc(sizeof(genome));\n strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n strand->next = NULL;\n\n strandIterator = strand;\n\n for(i=1;ibase = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n newStrand->next = NULL;\n\n strandIterator->next = newStrand;\n strandIterator = newStrand;\n }\n}\n\ngenomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){\n int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight);\n \n genomeChange mutationCommand;\n\n mutationCommand.mutation = mutationChoice=swapWeight && mutationChoicebase);\n strandIterator = strandIterator->next;\n }\n len += lineLength;\n }\n\n while(strandIterator!=NULL){\n printf(\"%c\",strandIterator->base);\n strandIterator = strandIterator->next;\n }\n\n printf(\"\\n\\nBase Counts\\n-----------\");\n\n printf(\"\\n%*c%3s%*d\",width,'A',\":\",width,baseData.adenineCount);\n printf(\"\\n%*c%3s%*d\",width,'T',\":\",width,baseData.thymineCount);\n printf(\"\\n%*c%3s%*d\",width,'C',\":\",width,baseData.cytosineCount);\n printf(\"\\n%*c%3s%*d\",width,'G',\":\",width,baseData.guanineCount);\n\t\n\tprintf(\"\\n\\nTotal:%*d\",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount);\n\n printf(\"\\n\");\n}\n\nvoid mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){\n int i,j,width,baseChoice;\n genomeChange newMutation;\n genome *strandIterator, *strandFollower, *newStrand;\n\n for(i=0;inext;\n }\n \n if(newMutation.mutation=='S'){\n if(strandIterator->base=='A'){\n strandIterator->base='T';\n printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n }\n else if(strandIterator->base=='A'){\n strandIterator->base='T';\n printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n }\n else if(strandIterator->base=='C'){\n strandIterator->base='G';\n printf(\"\\nSwapping C at position : %*d with G\",width,newMutation.position);\n }\n else{\n strandIterator->base='C';\n printf(\"\\nSwapping G at position : %*d with C\",width,newMutation.position);\n }\n }\n\n else if(newMutation.mutation=='I'){\n baseChoice = rand()%4;\n\n newStrand = (genome*)malloc(sizeof(genome));\n newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n printf(\"\\nInserting %c at position : %*d\",newStrand->base,width,newMutation.position);\n baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n newStrand->next = strandIterator;\n strandFollower->next = newStrand;\n genomeLength++;\n }\n\n else{\n strandFollower->next = strandIterator->next;\n strandIterator->next = NULL;\n printf(\"\\nDeleting %c at position : %*d\",strandIterator->base,width,newMutation.position);\n free(strandIterator);\n genomeLength--;\n }\n }\n}\n\nint main(int argc,char* argv[])\n{\n int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10;\n\n if(argc==1||argc>6){\n printf(\"Usage : %s \\n\",argv[0]);\n return 0;\n }\n\n switch(argc){\n case 2: genomeLength = atoi(argv[1]);\n break;\n case 3: genomeLength = atoi(argv[1]);\n numMutations = atoi(argv[2]);\n break;\n case 4: genomeLength = atoi(argv[1]);\n numMutations = atoi(argv[2]);\n swapWeight = atoi(argv[3]);\n break; \n case 5: genomeLength = atoi(argv[1]);\n numMutations = atoi(argv[2]);\n swapWeight = atoi(argv[3]);\n insertWeight = atoi(argv[4]);\n break; \n case 6: genomeLength = atoi(argv[1]);\n numMutations = atoi(argv[2]);\n swapWeight = atoi(argv[3]);\n insertWeight = atoi(argv[4]);\n deleteWeight = atoi(argv[5]);\n break; \n };\n\n srand(time(NULL));\n generateStrand();\n\t\n\tprintf(\"\\nOriginal:\");\n printGenome();\n mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight);\n \n\tprintf(\"\\n\\nMutated:\");\n\tprintGenome();\n\n return 0;\n}\n"} {"title": "Bioinformatics/base count", "language": "C", "task": "Given this string representing ordered DNA bases:\n\nCGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\nCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\nAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\nGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\nCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\nTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\nTTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\nCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\nTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\nGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\n\n\n\n;Task:\n:* \"Pretty print\" the sequence followed by a summary of the counts of each of the bases: ('''A''', '''C''', '''G''', and '''T''') in the sequence \n:* print the total count of each base in the string.\n\n\n\n", "solution": "#include\n#include\n#include\n\ntypedef struct genome{\n char* strand;\n int length;\n struct genome* next;\n}genome;\n\ngenome* genomeData;\nint totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0;\n\nint numDigits(int num){\n int len = 1;\n\n while(num>10){\n num = num/10;\n len++;\n }\n\n return len;\n}\n\nvoid buildGenome(char str[100]){\n int len = strlen(str),i;\n genome *genomeIterator, *newGenome; \n\n totalLength += len;\n\n for(i=0;istrand = (char*)malloc(len*sizeof(char));\n strcpy(genomeData->strand,str);\n genomeData->length = len;\n\n genomeData->next = NULL;\n }\n\n else{\n genomeIterator = genomeData;\n\n while(genomeIterator->next!=NULL)\n genomeIterator = genomeIterator->next;\n\n newGenome = (genome*)malloc(sizeof(genome));\n\n newGenome->strand = (char*)malloc(len*sizeof(char));\n strcpy(newGenome->strand,str);\n newGenome->length = len;\n\n newGenome->next = NULL;\n genomeIterator->next = newGenome;\n }\n}\n\nvoid printGenome(){\n genome* genomeIterator = genomeData;\n\n int width = numDigits(totalLength), len = 0;\n\n printf(\"Sequence:\\n\");\n\n while(genomeIterator!=NULL){\n printf(\"\\n%*d%3s%3s\",width+1,len,\":\",genomeIterator->strand);\n len += genomeIterator->length;\n\n genomeIterator = genomeIterator->next;\n }\n\n printf(\"\\n\\nBase Count\\n----------\\n\\n\");\n\n printf(\"%3c%3s%*d\\n\",'A',\":\",width+1,Adenine);\n printf(\"%3c%3s%*d\\n\",'T',\":\",width+1,Thymine);\n printf(\"%3c%3s%*d\\n\",'C',\":\",width+1,Cytosine);\n printf(\"%3c%3s%*d\\n\",'G',\":\",width+1,Guanine);\n printf(\"\\n%3s%*d\\n\",\"Total:\",width+1,Adenine + Thymine + Cytosine + Guanine);\n\n free(genomeData);\n}\n\nint main(int argc,char** argv)\n{\n char str[100];\n int counter = 0, len;\n \n if(argc!=2){\n printf(\"Usage : %s \\n\",argv[0]);\n return 0;\n }\n\n FILE *fp = fopen(argv[1],\"r\");\n\n while(fscanf(fp,\"%s\",str)!=EOF)\n buildGenome(str);\n fclose(fp);\n\n printGenome();\n\n return 0;\n}\n"} {"title": "Bitcoin/address validation", "language": "C", "task": "Write a program that takes a bitcoin address as argument, \nand checks whether or not this address is valid.\n\nA bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters:\n:::* 0 zero\n:::* O uppercase oh\n:::* I uppercase eye\n:::* l lowercase ell\n\n\nWith this encoding, a bitcoin address encodes 25 bytes:\n* the first byte is the version number, which will be zero for this task ;\n* the next twenty bytes are a [[RIPEMD-160]] digest, but you don't have to know that for this task: you can consider them a pure arbitrary data ;\n* the last four bytes are a checksum check. They are the first four bytes of a double [[SHA-256]] digest of the previous 21 bytes.\n\n\nTo check the bitcoin address, you must read the first twenty-one bytes, compute the checksum, and check that it corresponds to the last four bytes.\n\nThe program can either return a boolean value or throw an exception when not valid.\n\nYou can use a digest library for [[SHA-256]].\n\n\n;Example of a bitcoin address:\n\n 1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i\n\n\nIt doesn't belong to anyone and is part of the test suite of the bitcoin software. \nYou can change a few characters in this string and check that it'll fail the test.\n\n", "solution": "#include \n#include \n#include \n\nconst char *coin_err;\n#define bail(s) { coin_err = s; return 0; }\n\nint unbase58(const char *s, unsigned char *out) {\n\tstatic const char *tmpl = \"123456789\"\n\t\t\"ABCDEFGHJKLMNPQRSTUVWXYZ\"\n\t\t\"abcdefghijkmnopqrstuvwxyz\";\n\tint i, j, c;\n\tconst char *p;\n\n\tmemset(out, 0, 25);\n\tfor (i = 0; s[i]; i++) {\n\t\tif (!(p = strchr(tmpl, s[i])))\n\t\t\tbail(\"bad char\");\n\n\t\tc = p - tmpl;\n\t\tfor (j = 25; j--; ) {\n\t\t\tc += 58 * out[j];\n\t\t\tout[j] = c % 256;\n\t\t\tc /= 256;\n\t\t}\n\n\t\tif (c) bail(\"address too long\");\n\t}\n\n\treturn 1;\n}\n\nint valid(const char *s) {\n\tunsigned char dec[32], d1[SHA256_DIGEST_LENGTH], d2[SHA256_DIGEST_LENGTH];\n\n\tcoin_err = \"\";\n\tif (!unbase58(s, dec)) return 0;\n\n\tSHA256(SHA256(dec, 21, d1), SHA256_DIGEST_LENGTH, d2);\n\n\tif (memcmp(dec + 21, d2, 4))\n\t\tbail(\"bad digest\");\n\n\treturn 1;\n}\n\nint main (void) {\n\tconst char *s[] = {\n\t\t\"1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9\",\n\t\t\"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i\",\n\t\t\"1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nJ9\",\n\t\t\"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62I\",\n\t\t0 };\n\tint i;\n\tfor (i = 0; s[i]; i++) {\n\t\tint status = valid(s[i]);\n\t\tprintf(\"%s: %s\\n\", s[i], status ? \"Ok\" : coin_err);\n\t}\n\n\treturn 0;\n}"} {"title": "Bitcoin/public point to address", "language": "C", "task": "elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion.\n\nThe encoding steps are:\n* take the X and Y coordinates of the given public point, and concatenate them in order to have a 64 byte-longed string ;\n* add one byte prefix equal to 4 (it is a convention for this way of encoding a public point) ;\n* compute the [[SHA-256]] of this string ;\n* compute the [[RIPEMD-160]] of this SHA-256 digest ;\n* compute the checksum of the concatenation of the version number digit (a single zero byte) and this RIPEMD-160 digest, as described in [[bitcoin/address validation]] ;\n* Base-58 encode (see below) the concatenation of the version number (zero in this case), the ripemd digest and the checksum\n\nThe base-58 encoding is based on an alphabet of alphanumeric characters (numbers, upper case and lower case, in that order) but without the four characters 0, O, l and I.\n\nHere is an example public point:\nX = 0x50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352\nY = 0x2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6\n\nThe corresponding address should be:\n16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM\n\nNb. The leading '1' is not significant as 1 is zero in base-58. It is however often added to the bitcoin address for various reasons. There can actually be several of them. You can ignore this and output an address without the leading 1.\n\n''Extra credit:'' add a verification procedure about the public point, making sure it belongs to the secp256k1 elliptic curve\n", "solution": "#include \n#include \n#include \n#include \n#include \n\n#define COIN_VER 0\nconst char *coin_err;\n\ntypedef unsigned char byte;\n\nint is_hex(const char *s) {\n\tint i;\n\tfor (i = 0; i < 64; i++)\n\t\tif (!isxdigit(s[i])) return 0;\n\treturn 1;\n}\n\nvoid str_to_byte(const char *src, byte *dst, int n) {\n\twhile (n--) sscanf(src + n * 2, \"%2hhx\", dst + n);\n}\n\nchar* base58(byte *s, char *out) {\n\tstatic const char *tmpl = \"123456789\"\n\t\t\"ABCDEFGHJKLMNPQRSTUVWXYZ\"\n\t\t\"abcdefghijkmnopqrstuvwxyz\";\n\tstatic char buf[40];\n\n\tint c, i, n;\n\tif (!out) out = buf;\n\n\tout[n = 34] = 0;\n\twhile (n--) {\n\t\tfor (c = i = 0; i < 25; i++) {\n\t\t\tc = c * 256 + s[i];\n\t\t\ts[i] = c / 58;\n\t\t\tc %= 58;\n\t\t}\n\t\tout[n] = tmpl[c];\n\t}\n\n\tfor (n = 0; out[n] == '1'; n++);\n\tmemmove(out, out + n, 34 - n);\n\n\treturn out;\n}\n\nchar *coin_encode(const char *x, const char *y, char *out) {\n\tbyte s[65];\n\tbyte rmd[5 + RIPEMD160_DIGEST_LENGTH];\n\n\tif (!is_hex(x) || !(is_hex(y))) {\n\t\tcoin_err = \"bad public point string\";\n\t\treturn 0;\n\t}\n\n\ts[0] = 4;\n\tstr_to_byte(x, s + 1, 32);\n\tstr_to_byte(y, s + 33, 32);\n\n\trmd[0] = COIN_VER;\n\tRIPEMD160(SHA256(s, 65, 0), SHA256_DIGEST_LENGTH, rmd + 1);\n\n\tmemcpy(rmd + 21, SHA256(SHA256(rmd, 21, 0), SHA256_DIGEST_LENGTH, 0), 4);\n\n\treturn base58(rmd, out);\n}\n\nint main(void) {\n\tputs(coin_encode(\n\t\t\"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352\",\n\t\t\"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6\",\n\t\t0));\n\treturn 0;\n}"} {"title": "Bitwise IO", "language": "C", "task": "The aim of this task is to write functions (or create a class if yourlanguage is Object Oriented and you prefer) for reading and writing sequences of\nbits, most significant bit first. While the output of a asciiprint \"STRING\" is the ASCII byte sequence\n\"S\", \"T\", \"R\", \"I\", \"N\", \"G\", the output of a \"print\" of the bits sequence\n0101011101010 (13 bits) must be 0101011101010; real I/O is performed always\n''quantized'' by byte (avoiding endianness issues and relying on underlying\nbuffering for performance), therefore you must obtain as output the bytes\n0101 0111 0101 0'''000''' (bold bits are padding bits), i.e. in hexadecimal 57 50.\n\nAs test, you can implement a '''rough''' (e.g. don't care about error handling or\nother issues) compression/decompression program for ASCII sequences\nof bytes, i.e. bytes for which the most significant bit is always unused, so that you can write\nseven bits instead of eight (each 8 bytes of input, we write 7 bytes of output).\n\nThese bit oriented I/O functions can be used to implement compressors and\ndecompressors; e.g. Dynamic and Static Huffman encodings use variable length\nbits sequences, while LZW (see [[LZW compression]]) use fixed or variable ''words''\nnine (or more) bits long.\n\n* Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed.\n* Errors handling is not mandatory\n\n", "solution": "#include \n#include \n#include \n#include \n\ntypedef uint8_t byte;\ntypedef struct {\n FILE *fp;\n uint32_t accu;\n int bits;\n} bit_io_t, *bit_filter;\n\nbit_filter b_attach(FILE *f)\n{\n bit_filter b = malloc(sizeof(bit_io_t));\n b->bits = b->accu = 0;\n b->fp = f;\n return b;\n}\n\nvoid b_write(byte *buf, size_t n_bits, size_t shift, bit_filter bf)\n{\n uint32_t accu = bf->accu;\n int bits = bf->bits;\n\n buf += shift / 8;\n shift %= 8;\n\n while (n_bits || bits >= 8) {\n while (bits >= 8) {\n bits -= 8;\n fputc(accu >> bits, bf->fp);\n accu &= (1 << bits) - 1;\n }\n while (bits < 8 && n_bits) {\n accu = (accu << 1) | (((128 >> shift) & *buf) >> (7 - shift));\n --n_bits;\n bits++;\n if (++shift == 8) {\n shift = 0;\n buf++;\n }\n }\n }\n bf->accu = accu;\n bf->bits = bits;\n}\n\nsize_t b_read(byte *buf, size_t n_bits, size_t shift, bit_filter bf)\n{\n uint32_t accu = bf->accu;\n int bits = bf->bits;\n int mask, i = 0;\n\n buf += shift / 8;\n shift %= 8;\n\n while (n_bits) {\n while (bits && n_bits) {\n mask = 128 >> shift;\n if (accu & (1 << (bits - 1))) *buf |= mask;\n else *buf &= ~mask;\n\n n_bits--;\n bits--;\n\n if (++shift >= 8) {\n shift = 0;\n buf++;\n }\n }\n if (!n_bits) break;\n accu = (accu << 8) | fgetc(bf->fp);\n bits += 8;\n }\n bf->accu = accu;\n bf->bits = bits;\n\n return i;\n}\n\nvoid b_detach(bit_filter bf)\n{\n if (bf->bits) {\n bf->accu <<= 8 - bf->bits;\n fputc(bf->accu, bf->fp);\n }\n free(bf);\n}\n\nint main()\n{\n unsigned char s[] = \"abcdefghijk\";\n unsigned char s2[11] = {0};\n int i;\n\n FILE *f = fopen(\"test.bin\", \"wb\");\n bit_filter b = b_attach(f);\n /* for each byte in s, write 7 bits skipping 1 */\n for (i = 0; i < 10; i++) b_write(s + i, 7, 1, b);\n b_detach(b);\n fclose(f);\n\n /* read 7 bits and expand to each byte of s2 skipping 1 bit */\n f = fopen(\"test.bin\", \"rb\");\n b = b_attach(f);\n for (i = 0; i < 10; i++) b_read(s2 + i, 7, 1, b);\n b_detach(b);\n fclose(f);\n\n printf(\"%10s\\n\", s2); /* should be the same first 10 bytes as in s */\n\n return 0;\n}"} {"title": "Box the compass", "language": "C", "task": "Avast me hearties!\nThere be many a land lubber that knows naught of the pirate ways and gives direction by degree!\nThey know not how to box the compass! \n\n\n;Task description:\n# Create a function that takes a heading in degrees and returns the correct 32-point compass heading.\n# Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:\n:[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).\n\n\n;Notes;\n* The headings and indices can be calculated from this pseudocode:\nfor i in 0..32 inclusive:\n heading = i * 11.25\n case i %3:\n if 1: heading += 5.62; break\n if 2: heading -= 5.62; break\n end\n index = ( i mod 32) + 1\n* The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..\n\n", "solution": "#include \n\nint main()\n{\n int i, j;\n double degrees[] = { 0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5,\n 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88,\n 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12,\n 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5,\n 354.37, 354.38 };\n const char * names = \"North \"\n \"North by east \"\n \"North-northeast \"\n \"Northeast by north \"\n \"Northeast \"\n \"Northeast by east \"\n \"East-northeast \"\n \"East by north \"\n \"East \"\n \"East by south \"\n \"East-southeast \"\n \"Southeast by east \"\n \"Southeast \"\n \"Southeast by south \"\n \"South-southeast \"\n \"South by east \"\n \"South \"\n \"South by west \"\n \"South-southwest \"\n \"Southwest by south \"\n \"Southwest \"\n \"Southwest by west \"\n \"West-southwest \"\n \"West by south \"\n \"West \"\n \"West by north \"\n \"West-northwest \"\n \"Northwest by west \"\n \"Northwest \"\n \"Northwest by north \"\n \"North-northwest \"\n \"North by west \"\n \"North \";\n\n for (i = 0; i < 33; i++) {\n j = .5 + degrees[i] * 32 / 360;\n\n printf(\"%2d %.22s %6.2f\\n\", (j % 32) + 1, names + (j % 32) * 22,\n degrees[i]);\n }\n\n return 0;\n}"} {"title": "CSV data manipulation", "language": "C", "task": "CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. \n\nThe CSV format is flexible but somewhat ill-defined. \n\nFor present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.\n\n\n;Task:\nRead a CSV file, change some values and save the changes back to a file.\n\nFor this task we will use the following CSV file:\n\n C1,C2,C3,C4,C5\n 1,5,9,13,17\n 2,6,10,14,18\n 3,7,11,15,19\n 4,8,12,16,20\n\nSuggestions\n\n Show how to add a column, headed 'SUM', of the sums of the rows.\n If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.\n\n\n", "solution": "#define TITLE \"CSV data manipulation\"\n#define URL \"http://rosettacode.org/wiki/CSV_data_manipulation\"\n\n#define _GNU_SOURCE\n#define bool int\n#include \n#include /* malloc...*/\n#include /* strtok...*/\n#include \n#include \n\n\n/**\n * How to read a CSV file ?\n */\n\n\ntypedef struct {\n\tchar * delim;\n\tunsigned int rows;\n\tunsigned int cols;\n\tchar ** table;\n} CSV;\n\n\n/** \n * Utility function to trim whitespaces from left & right of a string\n */\nint trim(char ** str) {\n\tint trimmed;\n\tint n;\n\tint len;\n\t\n\tlen = strlen(*str);\n\tn = len - 1;\n\t/* from right */\n\twhile((n>=0) && isspace((*str)[n])) {\n\t\t(*str)[n] = '\\0'; \n\t\ttrimmed += 1;\n\t\tn--;\n\t}\n\n\t/* from left */\n\tn = 0;\n\twhile((n < len) && (isspace((*str)[0]))) {\n\t\t(*str)[0] = '\\0'; \n\t\t*str = (*str)+1;\n\t\ttrimmed += 1;\n\t\tn++;\n\t}\n\treturn trimmed;\n}\n\n\n/** \n * De-allocate csv structure \n */\nint csv_destroy(CSV * csv) {\n\tif (csv == NULL) { return 0; }\n\tif (csv->table != NULL) { free(csv->table); }\n\tif (csv->delim != NULL) { free(csv->delim); }\n\tfree(csv);\n\treturn 0;\n}\n\n\n/**\n * Allocate memory for a CSV structure \n */\nCSV * csv_create(unsigned int cols, unsigned int rows) {\n\tCSV * csv;\n\t\n\tcsv = malloc(sizeof(CSV));\n\tcsv->rows = rows;\n\tcsv->cols = cols;\n\tcsv->delim = strdup(\",\");\n\n\tcsv->table = malloc(sizeof(char *) * cols * rows);\n\tif (csv->table == NULL) { goto error; }\n\n\tmemset(csv->table, 0, sizeof(char *) * cols * rows);\n\n\treturn csv;\n\nerror:\n\tcsv_destroy(csv);\n\treturn NULL;\n}\n\n\n/**\n * Get value in CSV table at COL, ROW\n */\nchar * csv_get(CSV * csv, unsigned int col, unsigned int row) {\n\tunsigned int idx;\n\tidx = col + (row * csv->cols);\n\treturn csv->table[idx];\n}\n\n\n/**\n * Set value in CSV table at COL, ROW\n */\nint csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) {\n\tunsigned int idx;\n\tidx = col + (row * csv->cols);\n\tcsv->table[idx] = value;\n\treturn 0;\n}\n\nvoid csv_display(CSV * csv) {\n\tint row, col;\n\tchar * content;\n\tif ((csv->rows == 0) || (csv->cols==0)) {\n\t\tprintf(\"[Empty table]\\n\");\n\t\treturn ;\n\t}\n\n\tprintf(\"\\n[Table cols=%d rows=%d]\\n\", csv->cols, csv->rows);\n\tfor (row=0; rowrows; row++) {\n\t\tprintf(\"[|\");\n\t\tfor (col=0; colcols; col++) {\n\t\t\tcontent = csv_get(csv, col, row);\n printf(\"%s\\t|\", content);\n\t\t}\n printf(\"]\\n\");\n\t}\n\tprintf(\"\\n\");\n}\n\n/**\n * Resize CSV table\n */\nint csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) {\n\tunsigned int cur_col, \n\t\t\t\t cur_row, \n\t\t\t\t max_cols,\n\t\t\t\t max_rows;\n\tCSV * new_csv;\n\tchar * content;\n\tbool in_old, in_new;\n\n\t/* Build a new (fake) csv */\n\tnew_csv = csv_create(new_cols, new_rows);\n\tif (new_csv == NULL) { goto error; }\n\n\tnew_csv->rows = new_rows;\n\tnew_csv->cols = new_cols;\n\n\n\tmax_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols;\n\tmax_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows;\n\n\tfor (cur_col=0; cur_colcols) && (cur_row < old_csv->rows);\n\t\t\tin_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows);\n\n\t\t\tif (in_old && in_new) {\n\t\t\t\t/* re-link data */\n\t\t\t\tcontent = csv_get(old_csv, cur_col, cur_row);\n\t\t\t\tcsv_set(new_csv, cur_col, cur_row, content);\n\t\t\t} else if (in_old) {\n\t\t\t\t/* destroy data */\n\t\t\t\tcontent = csv_get(old_csv, cur_col, cur_row);\n\t\t\t\tfree(content);\n\t\t\t} else { /* skip */ }\n\t\t}\n\t}\n\t/* on rows */\t\t\n\tfree(old_csv->table);\n\told_csv->rows = new_rows;\n\told_csv->cols = new_cols;\n\told_csv->table = new_csv->table;\n\tnew_csv->table = NULL;\n\tcsv_destroy(new_csv);\n\n\treturn 0;\n\nerror:\n\tprintf(\"Unable to resize CSV table: error %d - %s\\n\", errno, strerror(errno));\n\treturn -1;\n}\n\n\n/**\n * Open CSV file and load its content into provided CSV structure\n **/\nint csv_open(CSV * csv, char * filename) {\n\tFILE * fp;\n\tunsigned int m_rows;\n\tunsigned int m_cols, cols;\n\tchar line[2048];\n\tchar * lineptr;\n\tchar * token;\n\n\n\tfp = fopen(filename, \"r\");\n\tif (fp == NULL) { goto error; }\n\n\tm_rows = 0;\n\tm_cols = 0;\n\twhile(fgets(line, sizeof(line), fp) != NULL) {\n \t\tm_rows += 1;\n \t\tcols = 0;\n \t\tlineptr = line;\n \t\twhile ((token = strtok(lineptr, csv->delim)) != NULL) {\n \t\t\tlineptr = NULL;\n \t\t\ttrim(&token);\n cols += 1;\n \tif (cols > m_cols) { m_cols = cols; }\n csv_resize(csv, m_cols, m_rows);\n csv_set(csv, cols-1, m_rows-1, strdup(token));\n }\n\t}\n\n\tfclose(fp);\n\tcsv->rows = m_rows;\n\tcsv->cols = m_cols;\n\treturn 0;\n\nerror:\n\tfclose(fp);\n\tprintf(\"Unable to open %s for reading.\", filename);\n\treturn -1;\n}\n\n\n/**\n * Open CSV file and save CSV structure content into it\n **/\nint csv_save(CSV * csv, char * filename) {\n\tFILE * fp;\n\tint row, col;\n\tchar * content;\n\n\tfp = fopen(filename, \"w\");\n\tfor (row=0; rowrows; row++) {\n\t\tfor (col=0; colcols; col++) {\n\t\t\tcontent = csv_get(csv, col, row);\n fprintf(fp, \"%s%s\", content, \n \t\t((col == csv->cols-1) ? \"\" : csv->delim) );\n\t\t}\n fprintf(fp, \"\\n\");\n\t}\n\n\tfclose(fp);\n\treturn 0;\n}\n\n\n/** \n * Test\n */\nint main(int argc, char ** argv) {\n\tCSV * csv;\n\n\tprintf(\"%s\\n%s\\n\\n\",TITLE, URL);\n\n\tcsv = csv_create(0, 0);\n\tcsv_open(csv, \"fixtures/csv-data-manipulation.csv\");\n\tcsv_display(csv);\n\n\tcsv_set(csv, 0, 0, \"Column0\");\n\tcsv_set(csv, 1, 1, \"100\");\n\tcsv_set(csv, 2, 2, \"200\");\n\tcsv_set(csv, 3, 3, \"300\");\n\tcsv_set(csv, 4, 4, \"400\");\n\tcsv_display(csv);\n\n\tcsv_save(csv, \"tmp/csv-data-manipulation.result.csv\");\n\tcsv_destroy(csv);\n\n\treturn 0;\n}\n"} {"title": "CSV to HTML translation", "language": "C", "task": "Consider a simplified CSV format where all rows are separated by a newline \nand all columns are separated by commas. \n\nNo commas are allowed as field data, but the data may contain \nother characters and character sequences that would \nnormally be ''escaped'' when converted to HTML\n\n\n;Task:\nCreate a function that takes a string representation of the CSV data\nand returns a text string of an HTML table representing the CSV data. \n\nUse the following data as the CSV text to convert, and show your output.\n: Character,Speech\n: The multitude,The messiah! Show us the messiah!\n: Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!\n: The multitude,Who are you?\n: Brians mother,I'm his mother; that's who!\n: The multitude,Behold his mother! Behold his mother!\n\n\n;Extra credit:\n''Optionally'' allow special formatting for the first row of the table as if it is the tables header row \n(via preferably; CSS if you must).\n\n", "solution": "#include \n\nconst char *input = \n\t\"Character,Speech\\n\"\n\t\"The multitude,The messiah! Show us the messiah!\\n\"\n\t\"Brians mother,Now you listen here! He's not the messiah; \"\n\t\t\"he's a very naughty boy! Now go away!\\n\"\n\t\"The multitude,Who are you?\\n\"\n\t\"Brians mother,I'm his mother; that's who!\\n\"\n\t\"The multitude,Behold his mother! Behold his mother!\";\n\nint main()\n{\n\tconst char *s;\n\tprintf(\"\\n\\n\\n
\");\n\tfor (s = input; *s; s++) {\n\t\tswitch(*s) {\n\t\tcase '\\n': printf(\"
\"); break;\n\t\tcase ',': printf(\"\"); break;\n\t\tcase '<': printf(\"<\"); break;\n\t\tcase '>': printf(\">\"); break;\n\t\tcase '&': printf(\"&\"); break;\n\t\tdefault: putchar(*s);\n\t\t}\n\t}\n\tputs(\"
\");\n\n\treturn 0;\n}"} {"title": "Calculating the value of e", "language": "C", "task": "Calculate the value of ''e''.\n\n\n(''e'' is also known as ''Euler's number'' and ''Napier's constant''.)\n\n\nSee details: Calculating the value of e\n\n", "solution": "#include \n#include \n\nint main(void)\n{\n double e;\n\n puts(\"The double precision in C give about 15 significant digits.\\n\"\n \"Values below are presented with 16 digits after the decimal point.\\n\");\n\n // The most direct way to compute Euler constant.\n //\n e = exp(1);\n printf(\"Euler constant e = %.16lf\\n\", e);\n\n // The fast and independed method: e = lim (1 + 1/n)**n\n //\n e = 1.0 + 0x1p-26;\n for (int i = 0; i < 26; i++)\n e *= e;\n printf(\"Euler constant e = %.16lf\\n\", e);\n\n // Taylor expansion e = 1 + 1/1 + 1/2 + 1/2/3 + 1/2/3/4 + 1/2/3/4/5 + ...\n // Actually Kahan summation may improve the accuracy, but is not necessary.\n //\n const int N = 1000;\n double a[1000];\n a[0] = 1.0;\n for (int i = 1; i < N; i++)\n {\n a[i] = a[i-1] / i;\n }\n e = 1.;\n for (int i = N - 1; i > 0; i--)\n e += a[i];\n printf(\"Euler constant e = %.16lf\\n\", e);\n\n return 0;\n}"} {"title": "Call a function", "language": "C", "task": "Demonstrate the different syntax and semantics provided for calling a function. \n\n\nThis may include:\n:* Calling a function that requires no arguments\n:* Calling a function with a fixed number of arguments\n:* Calling a function with optional arguments\n:* Calling a function with a variable number of arguments\n:* Calling a function with named arguments\n:* Using a function in statement context\n:* Using a function in first-class context within an expression\n:* Obtaining the return value of a function\n:* Distinguishing built-in functions and user-defined functions\n:* Distinguishing subroutines and functions\n;* Stating whether arguments are passed by value or by reference\n;* Is partial application possible and how\n\n\nThis task is ''not'' about defining functions.\n\n", "solution": "/* function with no argument */\nf();\n\n/* fix number of arguments */\ng(1, 2, 3);\n\n/* Optional arguments: err...\n Feel free to make sense of the following. I can't. */\nint op_arg();\nint main()\n{\n\top_arg(1);\n\top_arg(1, 2);\n\top_arg(1, 2, 3);\n\treturn 0;\n}\nint op_arg(int a, int b)\n{\n\tprintf(\"%d %d %d\\n\", a, b, (&b)[1]);\n\treturn a;\n} /* end of sensible code */\n\n/* Variadic function: how the args list is handled solely depends on the function */\nvoid h(int a, ...)\n{\n\tva_list ap;\n\tva_start(ap);\n\t...\n}\n/* call it as: (if you feed it something it doesn't expect, don't count on it working) */\nh(1, 2, 3, 4, \"abcd\", (void*)0);\n\n/* named arguments: this is only possible through some pre-processor abuse\n*/\nstruct v_args {\n int arg1;\n int arg2;\n char _sentinel;\n};\n\nvoid _v(struct v_args args)\n{\n printf(\"%d, %d\\n\", args.arg1, args.arg2);\n}\n\n#define v(...) _v((struct v_args){__VA_ARGS__})\n\nv(.arg2 = 5, .arg1 = 17); // prints \"17,5\"\n/* NOTE the above implementation gives us optional typesafe optional arguments as well (unspecified arguments are initialized to zero)*/\nv(.arg2=1); // prints \"0,1\"\nv(); // prints \"0,0\"\n\n/* as a first-class object (i.e. function pointer) */\nprintf(\"%p\", f); /* that's the f() above */\n\n/* return value */\ndouble a = asin(1);\n\n/* built-in functions: no such thing. Compiler may interally give special treatment\n to bread-and-butter functions such as memcpy(), but that's not a C built-in per se */\n\n/* subroutines: no such thing. You can goto places, but I doubt that counts. */\n\n/* Scalar values are passed by value by default. However, arrays are passed by reference. */\n/* Pointers *sort of* work like references, though. */"} {"title": "Canonicalize CIDR", "language": "C", "task": "Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form. \n\nThat is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.\n\n\n;Example:\nGiven '''87.70.141.1/22''', your code should output '''87.70.140.0/22'''\n\n\n;Explanation:\nAn Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 digit is given in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the network portion of the address, while the rightmost (least-significant) bits determine the host portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion.\n\nIn general, CIDR blocks stand in for the entire set of IP addresses sharing the same network component, so it's common to see access control lists that specify individual IP addresses using /32 to indicate that only the one address is included. Software accepting this notation as input often expects it to be entered in canonical form, in which the host bits are all zeroes. But network admins sometimes skip this step and just enter the address of a specific host on the subnet with the network size, resulting in a non-canonical entry.\n\nThe example address, 87.70.141.1/22, represents binary 0101011101000110100011 / 0100000001, with the / indicating the network/host division. To canonicalize, clear all the bits to the right of the / and convert back to dotted decimal: 0101011101000110100011 / 0000000000 - 87.70.140.0.\n\n\n;More examples for testing\n\n 36.18.154.103/12 - 36.16.0.0/12\n 62.62.197.11/29 - 62.62.197.8/29\n 67.137.119.181/4 - 64.0.0.0/4\n 161.214.74.21/24 - 161.214.74.0/24\n 184.232.176.184/18 - 184.232.128.0/18\n\n\n", "solution": "#include \n#include \n#include \n\ntypedef struct cidr_tag {\n uint32_t address;\n unsigned int mask_length;\n} cidr_t;\n\n// Convert a string in CIDR format to an IPv4 address and netmask,\n// if possible. Also performs CIDR canonicalization.\nbool cidr_parse(const char* str, cidr_t* cidr) {\n int a, b, c, d, m;\n if (sscanf(str, \"%d.%d.%d.%d/%d\", &a, &b, &c, &d, &m) != 5)\n return false;\n if (m < 1 || m > 32\n || a < 0 || a > UINT8_MAX\n || b < 0 || b > UINT8_MAX\n || c < 0 || c > UINT8_MAX\n || d < 0 || d > UINT8_MAX)\n return false;\n uint32_t mask = ~((1 << (32 - m)) - 1);\n uint32_t address = (a << 24) + (b << 16) + (c << 8) + d;\n address &= mask;\n cidr->address = address;\n cidr->mask_length = m;\n return true;\n}\n\n// Write a string in CIDR notation into the supplied buffer.\nvoid cidr_format(const cidr_t* cidr, char* str, size_t size) {\n uint32_t address = cidr->address;\n unsigned int d = address & UINT8_MAX;\n address >>= 8;\n unsigned int c = address & UINT8_MAX;\n address >>= 8;\n unsigned int b = address & UINT8_MAX;\n address >>= 8;\n unsigned int a = address & UINT8_MAX;\n snprintf(str, size, \"%u.%u.%u.%u/%u\", a, b, c, d,\n cidr->mask_length);\n}\n\nint main(int argc, char** argv) {\n const char* tests[] = {\n \"87.70.141.1/22\",\n \"36.18.154.103/12\",\n \"62.62.197.11/29\",\n \"67.137.119.181/4\",\n \"161.214.74.21/24\",\n \"184.232.176.184/18\"\n };\n for (int i = 0; i < sizeof(tests)/sizeof(tests[0]); ++i) {\n cidr_t cidr;\n if (cidr_parse(tests[i], &cidr)) {\n char out[32];\n cidr_format(&cidr, out, sizeof(out));\n printf(\"%-18s -> %s\\n\", tests[i], out);\n } else {\n fprintf(stderr, \"%s: invalid CIDR\\n\", tests[i]);\n }\n }\n return 0;\n}"} {"title": "Cartesian product of two or more lists", "language": "C", "task": "Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.\n\nDemonstrate that your function/method correctly returns:\n::{1, 2} x {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}\n\nand, in contrast:\n::{3, 4} x {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}\n\nAlso demonstrate, using your function/method, that the product of an empty list with any other list is empty.\n:: {1, 2} x {} = {}\n:: {} x {1, 2} = {}\n\nFor extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.\n\nUse your n-ary Cartesian product function to show the following products:\n:: {1776, 1789} x {7, 12} x {4, 14, 23} x {0, 1}\n:: {1, 2, 3} x {30} x {500, 100}\n:: {1, 2, 3} x {} x {500, 100}\n\n\n", "solution": "#include\n#include\n#include\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s \",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n"} {"title": "Catalan numbers/Pascal's triangle", "language": "C", "task": "Print out the first '''15''' Catalan numbers by extracting them from Pascal's triangle.\n\n\n;See:\n* Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.\n\n* Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.\n* Sequence A000108 on OEIS has a lot of information on Catalan Numbers.\n\n;Related Tasks:\n[[Pascal's triangle]]\n\n", "solution": "//This code implements the print of 15 first Catalan's Numbers\n//Formula used:\n// __n__\n// | | (n + k) / k n>0\n// k=2 \n\n#include \n#include \n\n//the number of Catalan's Numbers to be printed\nconst int N = 15;\n\nint main()\n{\n //loop variables (in registers)\n register int k, n;\n\n //necessarily ull for reach big values\n unsigned long long int num, den;\n\n //the nmmber\n int catalan;\n\n //the first is not calculated for the formula\n printf(\"1 \");\n\n //iterating from 2 to 15\n for (n=2; n<=N; ++n) {\n //initializaing for products\n num = den = 1;\n //applying the formula\n for (k=2; k<=n; ++k) {\n num *= (n+k);\n den *= k;\n catalan = num /den;\n }\n \n //output\n printf(\"%d \", catalan);\n }\n\n //the end\n printf(\"\\n\");\n return 0;\n}\n"} {"title": "Catamorphism", "language": "C", "task": "''Reduce'' is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. \n\n\n;Task:\nShow how ''reduce'' (or ''foldl'' or ''foldr'' etc), work (or would be implemented) in your language.\n\n\n;See also:\n* Wikipedia article: Fold\n* Wikipedia article: Catamorphism\n\n", "solution": "#include \n\ntypedef int (*intFn)(int, int);\n\nint reduce(intFn fn, int size, int *elms)\n{\n int i, val = *elms;\n for (i = 1; i < size; ++i)\n val = fn(val, elms[i]);\n return val;\n}\n\nint add(int a, int b) { return a + b; }\nint sub(int a, int b) { return a - b; }\nint mul(int a, int b) { return a * b; }\n\nint main(void)\n{\n int nums[] = {1, 2, 3, 4, 5};\n printf(\"%d\\n\", reduce(add, 5, nums));\n printf(\"%d\\n\", reduce(sub, 5, nums));\n printf(\"%d\\n\", reduce(mul, 5, nums));\n return 0;\n}"} {"title": "Chaos game", "language": "C", "task": "The Chaos Game is a method of generating the attractor of an iterated function system (IFS). \n\nOne of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.\n\n\n;Task\nPlay the Chaos Game using the corners of an equilateral triangle as the reference points. Add a starting point at random (preferably inside the triangle). Then add the next point halfway between the starting point and one of the reference points. This reference point is chosen at random.\n\nAfter a sufficient number of iterations, the image of a Sierpinski Triangle should emerge.\n\n\n;See also\n* The Game of Chaos\n\n", "solution": "#include\n#include\n#include\n#include\n#include\n\n#define pi M_PI\n\nint main(){\n\t\n\ttime_t t;\n\tdouble side, vertices[3][3],seedX,seedY,windowSide;\n\tint i,iter,choice;\n\t\n\tprintf(\"Enter triangle side length : \");\n\tscanf(\"%lf\",&side);\n\t\n\tprintf(\"Enter number of iterations : \");\n\tscanf(\"%d\",&iter);\n\t\n\twindowSide = 10 + 2*side;\n\n\tinitwindow(windowSide,windowSide,\"Sierpinski Chaos\");\n\t\n\tfor(i=0;i<3;i++){\n\t\tvertices[i][0] = windowSide/2 + side*cos(i*2*pi/3);\n\t\tvertices[i][1] = windowSide/2 + side*sin(i*2*pi/3);\n\t\tputpixel(vertices[i][0],vertices[i][1],15);\n\t}\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tseedX = rand()%(int)(vertices[0][0]/2 + (vertices[1][0] + vertices[2][0])/4);\n\tseedY = rand()%(int)(vertices[0][1]/2 + (vertices[1][1] + vertices[2][1])/4);\n\t\n\tputpixel(seedX,seedY,15);\n\t\n\tfor(i=0;i\t//for isatty()\n#include \t//for fileno()\n\nint main(void)\n{\n\tputs(isatty(fileno(stdin))\n\t\t? \"stdin is tty\"\n\t\t: \"stdin is not tty\");\n\treturn 0;\n}"} {"title": "Check output device is a terminal", "language": "C", "task": "Demonstrate how to check whether the output device is a terminal or not.\n\n\n;Related task:\n* [[Check input device is a terminal]]\n\n", "solution": "#include // for isatty()\n#include // for fileno()\n\nint main()\n{\n puts(isatty(fileno(stdout))\n ? \"stdout is tty\"\n : \"stdout is not tty\");\n return 0;\n}"} {"title": "Chinese remainder theorem", "language": "C", "task": "Suppose n_1, n_2, \\ldots, n_k are positive [[integer]]s that are pairwise co-prime. \n\nThen, for any given sequence of integers a_1, a_2, \\dots, a_k, there exists an integer x solving the following system of simultaneous congruences:\n\n::: \\begin{align}\n x &\\equiv a_1 \\pmod{n_1} \\\\\n x &\\equiv a_2 \\pmod{n_2} \\\\\n &{}\\ \\ \\vdots \\\\\n x &\\equiv a_k \\pmod{n_k}\n\\end{align}\n\nFurthermore, all solutions x of this system are congruent modulo the product, N=n_1n_2\\ldots n_k.\n\n\n;Task:\nWrite a program to solve a system of linear congruences by applying the Chinese Remainder Theorem. \n\nIf the system of equations cannot be solved, your program must somehow indicate this. \n\n(It may throw an exception or return a special false value.) \n\nSince there are infinitely many solutions, the program should return the unique solution s where 0 \\leq s \\leq n_1n_2\\ldots n_k.\n\n\n''Show the functionality of this program'' by printing the result such that the n's are [3,5,7] and the a's are [2,3,2].\n\n\n'''Algorithm''': The following algorithm only applies if the n_i's are pairwise co-prime. \n\nSuppose, as above, that a solution is required for the system of congruences:\n\n::: x \\equiv a_i \\pmod{n_i} \\quad\\mathrm{for}\\; i = 1, \\ldots, k\n\nAgain, to begin, the product N = n_1n_2 \\ldots n_k is defined. \n\nThen a solution x can be found as follows:\n\nFor each i, the integers n_i and N/n_i are co-prime. \n\nUsing the Extended Euclidean algorithm, we can find integers r_i and s_i such that r_i n_i + s_i N/n_i = 1. \n\nThen, one solution to the system of simultaneous congruences is:\n\n::: x = \\sum_{i=1}^k a_i s_i N/n_i\n\nand the minimal solution,\n\n::: x \\pmod{N}.\n\n", "solution": "#include \n\n// returns x where (a * x) % b == 1\nint mul_inv(int a, int b)\n{\n\tint b0 = b, t, q;\n\tint x0 = 0, x1 = 1;\n\tif (b == 1) return 1;\n\twhile (a > 1) {\n\t\tq = a / b;\n\t\tt = b, b = a % b, a = t;\n\t\tt = x0, x0 = x1 - q * x0, x1 = t;\n\t}\n\tif (x1 < 0) x1 += b0;\n\treturn x1;\n}\n\nint chinese_remainder(int *n, int *a, int len)\n{\n\tint p, i, prod = 1, sum = 0;\n\n\tfor (i = 0; i < len; i++) prod *= n[i];\n\n\tfor (i = 0; i < len; i++) {\n\t\tp = prod / n[i];\n\t\tsum += a[i] * mul_inv(p, n[i]) * p;\n\t}\n\n\treturn sum % prod;\n}\n\nint main(void)\n{\n\tint n[] = { 3, 5, 7 };\n\tint a[] = { 2, 3, 2 };\n\n\tprintf(\"%d\\n\", chinese_remainder(n, a, sizeof(n)/sizeof(n[0])));\n\treturn 0;\n}"} {"title": "Circles of given radius through two points", "language": "C", "task": "2 circles with a given radius through 2 points in 2D space.\n\nGiven two points on a plane and a radius, usually two circles of given radius can be drawn through the points. \n;Exceptions:\n# r==0.0 should be treated as never describing circles (except in the case where the points are coincident).\n# If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.\n# If the points form a diameter then return two identical circles ''or'' return a single circle, according to which is the most natural mechanism for the implementation language.\n# If the points are too far apart then no circles can be drawn.\n\n\n;Task detail:\n* Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, ''or some indication of special cases where two, possibly equal, circles cannot be returned''.\n* Show here the output for the following inputs:\n\n p1 p2 r\n0.1234, 0.9876 0.8765, 0.2345 2.0\n0.0000, 2.0000 0.0000, 0.0000 1.0\n0.1234, 0.9876 0.1234, 0.9876 2.0\n0.1234, 0.9876 0.8765, 0.2345 0.5\n0.1234, 0.9876 0.1234, 0.9876 0.0\n\n\n\n;Related task:\n* [[Total circles area]].\n\n\n;See also:\n* Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel\n\n", "solution": "#include\n#include\n\ntypedef struct{\n\tdouble x,y;\n\t}point;\n\t\ndouble distance(point p1,point p2)\n{\n\treturn sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));\n}\n\t\nvoid findCircles(point p1,point p2,double radius)\n{\n\tdouble separation = distance(p1,p2),mirrorDistance;\n\t\n\tif(separation == 0.0)\n\t{\n\t\tradius == 0.0 ? printf(\"\\nNo circles can be drawn through (%.4f,%.4f)\",p1.x,p1.y):\n\t\t\t\t\t\t\t printf(\"\\nInfinitely many circles can be drawn through (%.4f,%.4f)\",p1.x,p1.y);\n\t}\n\t\n\telse if(separation == 2*radius)\n\t{\n\t\tprintf(\"\\nGiven points are opposite ends of a diameter of the circle with center (%.4f,%.4f) and radius %.4f\",(p1.x+p2.x)/2,(p1.y+p2.y)/2,radius); \n\t}\n\t\n\telse if(separation > 2*radius)\n\t{\n\t\tprintf(\"\\nGiven points are farther away from each other than a diameter of a circle with radius %.4f\",radius);\n\t} \n\t\n\telse\n\t{\n\t\tmirrorDistance =sqrt(pow(radius,2) - pow(separation/2,2));\n\t\t\n\t\tprintf(\"\\nTwo circles are possible.\");\n\t\tprintf(\"\\nCircle C1 with center (%.4f,%.4f), radius %.4f and Circle C2 with center (%.4f,%.4f), radius %.4f\",(p1.x+p2.x)/2 + mirrorDistance*(p1.y-p2.y)/separation,(p1.y+p2.y)/2 + mirrorDistance*(p2.x-p1.x)/separation,radius,(p1.x+p2.x)/2 - mirrorDistance*(p1.y-p2.y)/separation,(p1.y+p2.y)/2 - mirrorDistance*(p2.x-p1.x)/separation,radius);\n\t}\n}\n\nint main()\n{\n int i;\n\n point cases[] = \t\n {\t{0.1234, 0.9876}, {0.8765, 0.2345}, \n\t{0.0000, 2.0000}, {0.0000, 0.0000}, \n\t{0.1234, 0.9876}, {0.1234, 0.9876}, \n\t{0.1234, 0.9876}, {0.8765, 0.2345}, \n\t{0.1234, 0.9876}, {0.1234, 0.9876}\n };\n\n double radii[] = {2.0,1.0,2.0,0.5,0.0};\n\n for(i=0;i<5;i++)\n {\t\n\tprintf(\"\\nCase %d)\",i+1);\n\tfindCircles(cases[2*i],cases[2*i+1],radii[i]);\n }\n\n return 0;\n}\n"} {"title": "Closures/Value capture", "language": "C", "task": "Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index '' i '' (you may choose to start '' i '' from either '''0''' or '''1'''), when run, should return the square of the index, that is, '' i '' 2. \n\nDisplay the result of running any but the last function, to demonstrate that the function indeed remembers its value.\n\n\n;Goal:\nDemonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. \n\nIn imperative languages, one would generally use a loop with a mutable counter variable. \n\nFor each function to maintain the correct number, it has to capture the ''value'' of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.\n\nSee also: [[Multiple distinct objects]]\n", "solution": "#include \n#include \n#include \n#include \n\ntypedef int (*f_int)();\n \n#define TAG 0xdeadbeef\nint _tmpl() { \n\tvolatile int x = TAG;\n\treturn x * x;\n}\n\n#define PROT (PROT_EXEC | PROT_WRITE)\n#define FLAGS (MAP_PRIVATE | MAP_ANONYMOUS) \nf_int dupf(int v)\n{\n\tsize_t len = (void*)dupf - (void*)_tmpl;\n\tf_int ret = mmap(NULL, len, PROT, FLAGS, 0, 0);\n\tchar *p;\n\tif(ret == MAP_FAILED) {\n\t\tperror(\"mmap\");\n\t\texit(-1);\n\t}\n\tmemcpy(ret, _tmpl, len);\n\tfor (p = (char*)ret; p < (char*)ret + len - sizeof(int); p++)\n\t\tif (*(int *)p == TAG) *(int *)p = v;\n\treturn ret;\n}\n \nint main()\n{\n\tf_int funcs[10];\n\tint i;\n\tfor (i = 0; i < 10; i++) funcs[i] = dupf(i);\n \n\tfor (i = 0; i < 9; i++)\n\t\tprintf(\"func[%d]: %d\\n\", i, funcs[i]());\n \n\treturn 0;\n}"} {"title": "Colorful numbers", "language": "C", "task": "A '''colorful number''' is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique.\n\n\n;E.G.\n\n24753 is a colorful number. 2, 4, 7, 5, 3, (2x4)8, (4x7)28, (7x5)35, (5x3)15, (2x4x7)56, (4x7x5)140, (7x5x3)105, (2x4x7x5)280, (4x7x5x3)420, (2x4x7x5x3)840\n\nEvery product is unique.\n\n\n2346 is '''not''' a colorful number. 2, 3, 4, '''6''', (2x3)'''6''', (3x4)12, (4x6)24, (2x3x4)48, (3x4x6)72, (2x3x4x6)144\n\nThe product '''6''' is repeated.\n\n\nSingle digit numbers '''are''' considered to be colorful. A colorful number larger than 9 cannot contain a repeated digit, the digit 0 or the digit 1. As a consequence, there is a firm upper limit for colorful numbers; no colorful number can have more than 8 digits.\n\n\n;Task\n\n* Write a routine (subroutine, function, procedure, whatever it may be called in your language) to test if a number is a colorful number or not.\n* Use that routine to find all of the colorful numbers less than 100.\n* Use that routine to find the largest possible colorful number.\n\n\n;Stretch\n\n* Find and display the count of colorful numbers in each order of magnitude.\n* Find and show the total count of '''all''' colorful numbers.\n\n\n''Colorful numbers have no real number theory application. They are more a recreational math puzzle than a useful tool.''\n\n", "solution": "#include \n#include \n#include \n#include \n\nbool colorful(int n) {\n // A colorful number cannot be greater than 98765432.\n if (n < 0 || n > 98765432)\n return false;\n int digit_count[10] = {};\n int digits[8] = {};\n int num_digits = 0;\n for (int m = n; m > 0; m /= 10) {\n int d = m % 10;\n if (n > 9 && (d == 0 || d == 1))\n return false;\n if (++digit_count[d] > 1)\n return false;\n digits[num_digits++] = d;\n }\n // Maximum number of products is (8 x 9) / 2.\n int products[36] = {};\n for (int i = 0, product_count = 0; i < num_digits; ++i) {\n for (int j = i, p = 1; j < num_digits; ++j) {\n p *= digits[j];\n for (int k = 0; k < product_count; ++k) {\n if (products[k] == p)\n return false;\n }\n products[product_count++] = p;\n }\n }\n return true;\n}\n\nstatic int count[8];\nstatic bool used[10];\nstatic int largest = 0;\n\nvoid count_colorful(int taken, int n, int digits) {\n if (taken == 0) {\n for (int d = 0; d < 10; ++d) {\n used[d] = true;\n count_colorful(d < 2 ? 9 : 1, d, 1);\n used[d] = false;\n }\n } else {\n if (colorful(n)) {\n ++count[digits - 1];\n if (n > largest)\n largest = n;\n }\n if (taken < 9) {\n for (int d = 2; d < 10; ++d) {\n if (!used[d]) {\n used[d] = true;\n count_colorful(taken + 1, n * 10 + d, digits + 1);\n used[d] = false;\n }\n }\n }\n }\n}\n\nint main() {\n setlocale(LC_ALL, \"\");\n\n clock_t start = clock();\n\n printf(\"Colorful numbers less than 100:\\n\");\n for (int n = 0, count = 0; n < 100; ++n) {\n if (colorful(n))\n printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n }\n\n count_colorful(0, 0, 0);\n printf(\"\\n\\nLargest colorful number: %'d\\n\", largest);\n\n printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n int total = 0;\n for (int d = 0; d < 8; ++d) {\n printf(\"%d %'d\\n\", d + 1, count[d]);\n total += count[d];\n }\n printf(\"\\nTotal: %'d\\n\", total);\n\n clock_t end = clock();\n printf(\"\\nElapsed time: %f seconds\\n\",\n (end - start + 0.0) / CLOCKS_PER_SEC);\n return 0;\n}"} {"title": "Colour bars/Display", "language": "C", "task": "Display a series of vertical color bars across the width of the display. \n\nThe color bars should either use:\n:::* the system palette, or \n:::* the sequence of colors: \n::::::* black\n::::::* red\n::::::* green\n::::::* blue\n::::::* magenta\n::::::* cyan\n::::::* yellow\n::::::* white\n\n", "solution": "#include\n\n#define COLOURS 8\n\nint main()\n{\n\tint colour=0,i,j,MAXROW,MAXCOL;\n\tstruct text_info tInfo;\n\tgettextinfo(&tInfo);\n\tMAXROW = tInfo.screenheight;\n\tMAXCOL = tInfo.screenwidth;\n\ttextbackground(BLACK); //8 colour constants are defined\n\tclrscr();\n\t\n\tfor(colour=0;colour\n#include \n#include \n\nchar *quib(const char **strs, size_t size)\n{\n\n size_t len = 3 + ((size > 1) ? (2 * size + 1) : 0);\n size_t i;\n\n for (i = 0; i < size; i++)\n len += strlen(strs[i]);\n\n char *s = malloc(len * sizeof(*s));\n if (!s)\n {\n perror(\"Can't allocate memory!\\n\");\n exit(EXIT_FAILURE);\n }\n\n strcpy(s, \"{\");\n switch (size) {\n case 0: break;\n case 1: strcat(s, strs[0]);\n break;\n default: for (i = 0; i < size - 1; i++)\n {\n strcat(s, strs[i]);\n if (i < size - 2)\n strcat(s, \", \");\n else\n strcat(s, \" and \");\n }\n strcat(s, strs[i]);\n break;\n } \n strcat(s, \"}\");\n return s;\n}\n\nint main(void)\n{\n const char *test[] = {\"ABC\", \"DEF\", \"G\", \"H\"};\n char *s;\n\n for (size_t i = 0; i < 5; i++)\n {\n s = quib(test, i);\n printf(\"%s\\n\", s);\n free(s);\n }\n return EXIT_SUCCESS;\n}"} {"title": "Command-line arguments", "language": "C", "task": "{{selection|Short Circuit|Console Program Basics}} Retrieve the list of command-line arguments given to the program. For programs that only print the arguments when run directly, see [[Scripted main]].\nSee also [[Program name]].\n\nFor parsing command line arguments intelligently, see [[Parsing command-line arguments]].\n\nExample command line:\n\n myprogram -c \"alpha beta\" -h \"gamma\"\n\n", "solution": "#include \n#include \n\nint main(int argc, char* argv[])\n{\n int i;\n (void) printf(\"This program is named %s.\\n\", argv[0]);\n for (i = 1; i < argc; ++i)\n (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n return EXIT_SUCCESS;\n}"} {"title": "Compare a list of strings", "language": "C", "task": "Given a list of arbitrarily many strings, show how to:\n\n* test if they are all lexically '''equal'''\n* test if every string is lexically '''less than''' the one after it ''(i.e. whether the list is in strict ascending order)''\n\n\nEach of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar. \n\nIf the input list has less than two elements, the tests should always return true.\n\nThere is ''no'' need to provide a complete program and output.\n \nAssume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible.\n\nTry to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers.\n\nIf you need further guidance/clarification, see [[#Perl]] and [[#Python]] for solutions that use implicit short-circuiting loops, and [[#Raku]] for a solution that gets away with simply using a built-in language feature. \n\n", "solution": "#include \n#include \n\nstatic bool\nstrings_are_equal(const char **strings, size_t nstrings)\n{\n for (size_t i = 1; i < nstrings; i++)\n if (strcmp(strings[0], strings[i]) != 0)\n return false;\n return true;\n}\n\nstatic bool\nstrings_are_in_ascending_order(const char **strings, size_t nstrings)\n{\n for (size_t i = 1; i < nstrings; i++)\n if (strcmp(strings[i - 1], strings[i]) >= 0)\n return false;\n return true;\n}"} {"title": "Compile-time calculation", "language": "C", "task": "Some programming languages allow calculation of values at compile time. \n\n\n;Task:\nCalculate 10! (ten factorial) at compile time. \n\nPrint the result when the program is run.\n\nDiscuss what limitations apply to compile-time calculations in your language.\n\n", "solution": "#include \n#include \n\n#define ORDER_PP_DEF_8fac ORDER_PP_FN( \\\n8fn(8X, 8seq_fold(8times, 1, 8seq_iota(1, 8inc(8X)))) )\n\nint main(void) {\n\tprintf(\"10! = %d\\n\", ORDER_PP( 8to_lit( 8fac(10) ) ) );\n\treturn 0;\n}"} {"title": "Compiler/AST interpreter", "language": "C", "task": "The C and Python versions can be considered reference implementations.\n\n;Related Tasks\n\n* Lexical Analyzer task\n* Syntax Analyzer task\n* Code Generator task\n* Virtual Machine Interpreter task\n\n\n__TOC__\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\n#define da_dim(name, type) type *name = NULL; \\\n int _qy_ ## name ## _p = 0; \\\n int _qy_ ## name ## _max = 0\n#define da_rewind(name) _qy_ ## name ## _p = 0\n#define da_redim(name) do {if (_qy_ ## name ## _p >= _qy_ ## name ## _max) \\\n name = realloc(name, (_qy_ ## name ## _max += 32) * sizeof(name[0]));} while (0)\n#define da_append(name, x) do {da_redim(name); name[_qy_ ## name ## _p++] = x;} while (0)\n#define da_len(name) _qy_ ## name ## _p\n#define da_add(name) do {da_redim(name); _qy_ ## name ## _p++;} while (0)\n\ntypedef enum {\n nd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While,\n nd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq,\n nd_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or\n} NodeType;\n\ntypedef struct Tree Tree;\nstruct Tree {\n NodeType node_type;\n Tree *left;\n Tree *right;\n int value;\n};\n\n// dependency: Ordered by NodeType, must remain in same order as NodeType enum\n\nstruct {\n char *enum_text;\n NodeType node_type;\n} atr[] = {\n {\"Identifier\" , nd_Ident, }, {\"String\" , nd_String, },\n {\"Integer\" , nd_Integer,}, {\"Sequence\" , nd_Sequence,},\n {\"If\" , nd_If, }, {\"Prtc\" , nd_Prtc, },\n {\"Prts\" , nd_Prts, }, {\"Prti\" , nd_Prti, },\n {\"While\" , nd_While, }, {\"Assign\" , nd_Assign, },\n {\"Negate\" , nd_Negate, }, {\"Not\" , nd_Not, },\n {\"Multiply\" , nd_Mul, }, {\"Divide\" , nd_Div, },\n {\"Mod\" , nd_Mod, }, {\"Add\" , nd_Add, },\n {\"Subtract\" , nd_Sub, }, {\"Less\" , nd_Lss, },\n {\"LessEqual\" , nd_Leq, }, {\"Greater\" , nd_Gtr, },\n {\"GreaterEqual\", nd_Geq, }, {\"Equal\" , nd_Eql, },\n {\"NotEqual\" , nd_Neq, }, {\"And\" , nd_And, },\n {\"Or\" , nd_Or, },\n};\n\nFILE *source_fp;\nda_dim(string_pool, const char *);\nda_dim(global_names, const char *);\nda_dim(global_values, int);\n\nvoid error(const char *fmt, ... ) {\n va_list ap;\n char buf[1000];\n\n va_start(ap, fmt);\n vsprintf(buf, fmt, ap);\n printf(\"error: %s\\n\", buf);\n exit(1);\n}\n\nTree *make_node(NodeType node_type, Tree *left, Tree *right) {\n Tree *t = calloc(sizeof(Tree), 1);\n t->node_type = node_type;\n t->left = left;\n t->right = right;\n return t;\n}\n\nTree *make_leaf(NodeType node_type, int value) {\n Tree *t = calloc(sizeof(Tree), 1);\n t->node_type = node_type;\n t->value = value;\n return t;\n}\n\nint interp(Tree *x) { /* interpret the parse tree */\n if (!x) return 0;\n switch(x->node_type) {\n case nd_Integer: return x->value;\n case nd_Ident: return global_values[x->value];\n case nd_String: return x->value;\n\n case nd_Assign: return global_values[x->left->value] = interp(x->right);\n case nd_Add: return interp(x->left) + interp(x->right);\n case nd_Sub: return interp(x->left) - interp(x->right);\n case nd_Mul: return interp(x->left) * interp(x->right);\n case nd_Div: return interp(x->left) / interp(x->right);\n case nd_Mod: return interp(x->left) % interp(x->right);\n case nd_Lss: return interp(x->left) < interp(x->right);\n case nd_Gtr: return interp(x->left) > interp(x->right);\n case nd_Leq: return interp(x->left) <= interp(x->right);\n case nd_Eql: return interp(x->left) == interp(x->right);\n case nd_Neq: return interp(x->left) != interp(x->right);\n case nd_And: return interp(x->left) && interp(x->right);\n case nd_Or: return interp(x->left) || interp(x->right); \n case nd_Negate: return -interp(x->left);\n case nd_Not: return !interp(x->left);\n\n case nd_If: if (interp(x->left))\n interp(x->right->left);\n else\n interp(x->right->right);\n return 0;\n\n case nd_While: while (interp(x->left))\n interp(x->right);\n return 0;\n\n case nd_Prtc: printf(\"%c\", interp(x->left));\n return 0;\n case nd_Prti: printf(\"%d\", interp(x->left));\n return 0;\n case nd_Prts: printf(\"%s\", string_pool[interp(x->left)]);\n return 0;\n\n case nd_Sequence: interp(x->left);\n interp(x->right);\n return 0;\n\n default: error(\"interp: unknown tree type %d\\n\", x->node_type);\n }\n return 0;\n}\n\nvoid init_in(const char fn[]) {\n if (fn[0] == '\\0')\n source_fp = stdin;\n else {\n source_fp = fopen(fn, \"r\");\n if (source_fp == NULL)\n error(\"Can't open %s\\n\", fn);\n }\n}\n\nNodeType get_enum_value(const char name[]) {\n for (size_t i = 0; i < sizeof(atr) / sizeof(atr[0]); i++) {\n if (strcmp(atr[i].enum_text, name) == 0) {\n return atr[i].node_type;\n }\n }\n error(\"Unknown token %s\\n\", name);\n return -1;\n}\n\nchar *read_line(int *len) {\n static char *text = NULL;\n static int textmax = 0;\n\n for (*len = 0; ; (*len)++) {\n int ch = fgetc(source_fp);\n if (ch == EOF || ch == '\\n') {\n if (*len == 0)\n return NULL;\n break;\n }\n if (*len + 1 >= textmax) {\n textmax = (textmax == 0 ? 128 : textmax * 2);\n text = realloc(text, textmax);\n }\n text[*len] = ch;\n }\n text[*len] = '\\0';\n return text;\n}\n\nchar *rtrim(char *text, int *len) { // remove trailing spaces\n for (; *len > 0 && isspace(text[*len - 1]); --(*len))\n ;\n\n text[*len] = '\\0';\n return text;\n}\n\nint fetch_string_offset(char *st) {\n int len = strlen(st);\n st[len - 1] = '\\0';\n ++st;\n char *p, *q;\n p = q = st;\n\n while ((*p++ = *q++) != '\\0') {\n if (q[-1] == '\\\\') {\n if (q[0] == 'n') {\n p[-1] = '\\n';\n ++q;\n } else if (q[0] == '\\\\') {\n ++q;\n }\n }\n }\n\n for (int i = 0; i < da_len(string_pool); ++i) {\n if (strcmp(st, string_pool[i]) == 0) {\n return i;\n }\n }\n da_add(string_pool);\n int n = da_len(string_pool) - 1;\n string_pool[n] = strdup(st);\n return da_len(string_pool) - 1;\n}\n\nint fetch_var_offset(const char *name) {\n for (int i = 0; i < da_len(global_names); ++i) {\n if (strcmp(name, global_names[i]) == 0)\n return i;\n }\n da_add(global_names);\n int n = da_len(global_names) - 1;\n global_names[n] = strdup(name);\n da_append(global_values, 0);\n return n;\n}\n\nTree *load_ast() {\n int len;\n char *yytext = read_line(&len);\n yytext = rtrim(yytext, &len);\n\n // get first token\n char *tok = strtok(yytext, \" \");\n\n if (tok[0] == ';') {\n return NULL;\n }\n NodeType node_type = get_enum_value(tok);\n\n // if there is extra data, get it\n char *p = tok + strlen(tok);\n if (p != &yytext[len]) {\n int n;\n for (++p; isspace(*p); ++p)\n ;\n switch (node_type) {\n case nd_Ident: n = fetch_var_offset(p); break;\n case nd_Integer: n = strtol(p, NULL, 0); break;\n case nd_String: n = fetch_string_offset(p); break;\n default: error(\"Unknown node type: %s\\n\", p);\n }\n return make_leaf(node_type, n);\n }\n\n Tree *left = load_ast();\n Tree *right = load_ast();\n return make_node(node_type, left, right);\n}\n\nint main(int argc, char *argv[]) {\n init_in(argc > 1 ? argv[1] : \"\");\n\n Tree *x = load_ast();\n interp(x);\n\n return 0;\n}"} {"title": "Compiler/code generator", "language": "C", "task": "The C and Python versions can be considered reference implementations.\n\n;Related Tasks\n\n* Lexical Analyzer task\n* Syntax Analyzer task\n* Virtual Machine Interpreter task\n* AST Interpreter task\n\n\n__TOC__\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n\ntypedef unsigned char uchar;\n\ntypedef enum {\n nd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While,\n nd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq,\n nd_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or\n} NodeType;\n\ntypedef enum { FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND,\n OR, NEG, NOT, JMP, JZ, PRTC, PRTS, PRTI, HALT\n} Code_t;\n\ntypedef uchar code;\n\ntypedef struct Tree {\n NodeType node_type;\n struct Tree *left;\n struct Tree *right;\n char *value;\n} Tree;\n\n#define da_dim(name, type) type *name = NULL; \\\n int _qy_ ## name ## _p = 0; \\\n int _qy_ ## name ## _max = 0\n\n#define da_redim(name) do {if (_qy_ ## name ## _p >= _qy_ ## name ## _max) \\\n name = realloc(name, (_qy_ ## name ## _max += 32) * sizeof(name[0]));} while (0)\n\n#define da_rewind(name) _qy_ ## name ## _p = 0\n\n#define da_append(name, x) do {da_redim(name); name[_qy_ ## name ## _p++] = x;} while (0)\n#define da_len(name) _qy_ ## name ## _p\n#define da_add(name) do {da_redim(name); _qy_ ## name ## _p++;} while (0)\n\nFILE *source_fp, *dest_fp;\nstatic int here;\nda_dim(object, code);\nda_dim(globals, const char *);\nda_dim(string_pool, const char *);\n\n// dependency: Ordered by NodeType, must remain in same order as NodeType enum\nstruct {\n char *enum_text;\n NodeType node_type;\n Code_t opcode;\n} atr[] = {\n {\"Identifier\" , nd_Ident, -1 },\n {\"String\" , nd_String, -1 },\n {\"Integer\" , nd_Integer, -1 },\n {\"Sequence\" , nd_Sequence, -1 },\n {\"If\" , nd_If, -1 },\n {\"Prtc\" , nd_Prtc, -1 },\n {\"Prts\" , nd_Prts, -1 },\n {\"Prti\" , nd_Prti, -1 },\n {\"While\" , nd_While, -1 },\n {\"Assign\" , nd_Assign, -1 },\n {\"Negate\" , nd_Negate, NEG},\n {\"Not\" , nd_Not, NOT},\n {\"Multiply\" , nd_Mul, MUL},\n {\"Divide\" , nd_Div, DIV},\n {\"Mod\" , nd_Mod, MOD},\n {\"Add\" , nd_Add, ADD},\n {\"Subtract\" , nd_Sub, SUB},\n {\"Less\" , nd_Lss, LT },\n {\"LessEqual\" , nd_Leq, LE },\n {\"Greater\" , nd_Gtr, GT },\n {\"GreaterEqual\", nd_Geq, GE },\n {\"Equal\" , nd_Eql, EQ },\n {\"NotEqual\" , nd_Neq, NE },\n {\"And\" , nd_And, AND},\n {\"Or\" , nd_Or, OR },\n};\n\nvoid error(const char *fmt, ... ) {\n va_list ap;\n char buf[1000];\n\n va_start(ap, fmt);\n vsprintf(buf, fmt, ap);\n va_end(ap);\n printf(\"error: %s\\n\", buf);\n exit(1);\n}\n\nCode_t type_to_op(NodeType type) {\n return atr[type].opcode;\n}\n\nTree *make_node(NodeType node_type, Tree *left, Tree *right) {\n Tree *t = calloc(sizeof(Tree), 1);\n t->node_type = node_type;\n t->left = left;\n t->right = right;\n return t;\n}\n\nTree *make_leaf(NodeType node_type, char *value) {\n Tree *t = calloc(sizeof(Tree), 1);\n t->node_type = node_type;\n t->value = strdup(value);\n return t;\n}\n\n/*** Code generator ***/\n\nvoid emit_byte(int c) {\n da_append(object, (uchar)c);\n ++here;\n}\n\nvoid emit_int(int32_t n) {\n union {\n int32_t n;\n unsigned char c[sizeof(int32_t)];\n } x;\n\n x.n = n;\n\n for (size_t i = 0; i < sizeof(x.n); ++i) {\n emit_byte(x.c[i]);\n }\n}\n\nint hole() {\n int t = here;\n emit_int(0);\n return t;\n}\n\nvoid fix(int src, int dst) {\n *(int32_t *)(object + src) = dst-src;\n}\n\nint fetch_var_offset(const char *id) {\n for (int i = 0; i < da_len(globals); ++i) {\n if (strcmp(id, globals[i]) == 0)\n return i;\n }\n da_add(globals);\n int n = da_len(globals) - 1;\n globals[n] = strdup(id);\n return n;\n}\n\nint fetch_string_offset(const char *st) {\n for (int i = 0; i < da_len(string_pool); ++i) {\n if (strcmp(st, string_pool[i]) == 0)\n return i;\n }\n da_add(string_pool);\n int n = da_len(string_pool) - 1;\n string_pool[n] = strdup(st);\n return n;\n}\n\nvoid code_gen(Tree *x) {\n int p1, p2, n;\n\n if (x == NULL) return;\n switch (x->node_type) {\n case nd_Ident:\n emit_byte(FETCH);\n n = fetch_var_offset(x->value);\n emit_int(n);\n break;\n case nd_Integer:\n emit_byte(PUSH);\n emit_int(atoi(x->value));\n break;\n case nd_String:\n emit_byte(PUSH);\n n = fetch_string_offset(x->value);\n emit_int(n);\n break;\n case nd_Assign:\n n = fetch_var_offset(x->left->value);\n code_gen(x->right);\n emit_byte(STORE);\n emit_int(n);\n break;\n case nd_If:\n code_gen(x->left); // if expr\n emit_byte(JZ); // if false, jump\n p1 = hole(); // make room for jump dest\n code_gen(x->right->left); // if true statements\n if (x->right->right != NULL) {\n emit_byte(JMP);\n p2 = hole();\n }\n fix(p1, here);\n if (x->right->right != NULL) {\n code_gen(x->right->right);\n fix(p2, here);\n }\n break;\n case nd_While:\n p1 = here;\n code_gen(x->left); // while expr\n emit_byte(JZ); // if false, jump\n p2 = hole(); // make room for jump dest\n code_gen(x->right); // statements\n emit_byte(JMP); // back to the top\n fix(hole(), p1); // plug the top\n fix(p2, here); // plug the 'if false, jump'\n break;\n case nd_Sequence:\n code_gen(x->left);\n code_gen(x->right);\n break;\n case nd_Prtc:\n code_gen(x->left);\n emit_byte(PRTC);\n break;\n case nd_Prti:\n code_gen(x->left);\n emit_byte(PRTI);\n break;\n case nd_Prts:\n code_gen(x->left);\n emit_byte(PRTS);\n break;\n case nd_Lss: case nd_Gtr: case nd_Leq: case nd_Geq: case nd_Eql: case nd_Neq:\n case nd_And: case nd_Or: case nd_Sub: case nd_Add: case nd_Div: case nd_Mul:\n case nd_Mod:\n code_gen(x->left);\n code_gen(x->right);\n emit_byte(type_to_op(x->node_type));\n break;\n case nd_Negate: case nd_Not:\n code_gen(x->left);\n emit_byte(type_to_op(x->node_type));\n break;\n default:\n error(\"error in code generator - found %d, expecting operator\\n\", x->node_type);\n }\n}\n\nvoid code_finish() {\n emit_byte(HALT);\n}\n\nvoid list_code() {\n fprintf(dest_fp, \"Datasize: %d Strings: %d\\n\", da_len(globals), da_len(string_pool));\n for (int i = 0; i < da_len(string_pool); ++i)\n fprintf(dest_fp, \"%s\\n\", string_pool[i]);\n\n code *pc = object;\n\n again: fprintf(dest_fp, \"%5d \", (int)(pc - object));\n switch (*pc++) {\n case FETCH: fprintf(dest_fp, \"fetch [%d]\\n\", *(int32_t *)pc);\n pc += sizeof(int32_t); goto again;\n case STORE: fprintf(dest_fp, \"store [%d]\\n\", *(int32_t *)pc);\n pc += sizeof(int32_t); goto again;\n case PUSH : fprintf(dest_fp, \"push %d\\n\", *(int32_t *)pc);\n pc += sizeof(int32_t); goto again;\n case ADD : fprintf(dest_fp, \"add\\n\"); goto again;\n case SUB : fprintf(dest_fp, \"sub\\n\"); goto again;\n case MUL : fprintf(dest_fp, \"mul\\n\"); goto again;\n case DIV : fprintf(dest_fp, \"div\\n\"); goto again;\n case MOD : fprintf(dest_fp, \"mod\\n\"); goto again;\n case LT : fprintf(dest_fp, \"lt\\n\"); goto again;\n case GT : fprintf(dest_fp, \"gt\\n\"); goto again;\n case LE : fprintf(dest_fp, \"le\\n\"); goto again;\n case GE : fprintf(dest_fp, \"ge\\n\"); goto again;\n case EQ : fprintf(dest_fp, \"eq\\n\"); goto again;\n case NE : fprintf(dest_fp, \"ne\\n\"); goto again;\n case AND : fprintf(dest_fp, \"and\\n\"); goto again;\n case OR : fprintf(dest_fp, \"or\\n\"); goto again;\n case NOT : fprintf(dest_fp, \"not\\n\"); goto again;\n case NEG : fprintf(dest_fp, \"neg\\n\"); goto again;\n case JMP : fprintf(dest_fp, \"jmp (%d) %d\\n\",\n *(int32_t *)pc, (int32_t)(pc + *(int32_t *)pc - object));\n pc += sizeof(int32_t); goto again;\n case JZ : fprintf(dest_fp, \"jz (%d) %d\\n\",\n *(int32_t *)pc, (int32_t)(pc + *(int32_t *)pc - object));\n pc += sizeof(int32_t); goto again;\n case PRTC : fprintf(dest_fp, \"prtc\\n\"); goto again;\n case PRTI : fprintf(dest_fp, \"prti\\n\"); goto again;\n case PRTS : fprintf(dest_fp, \"prts\\n\"); goto again;\n case HALT : fprintf(dest_fp, \"halt\\n\"); break;\n default:error(\"listcode:Unknown opcode %d\\n\", *(pc - 1));\n }\n}\n\nvoid init_io(FILE **fp, FILE *std, const char mode[], const char fn[]) {\n if (fn[0] == '\\0')\n *fp = std;\n else if ((*fp = fopen(fn, mode)) == NULL)\n error(0, 0, \"Can't open %s\\n\", fn);\n}\n\nNodeType get_enum_value(const char name[]) {\n for (size_t i = 0; i < sizeof(atr) / sizeof(atr[0]); i++) {\n if (strcmp(atr[i].enum_text, name) == 0) {\n return atr[i].node_type;\n }\n }\n error(\"Unknown token %s\\n\", name);\n return -1;\n}\n\nchar *read_line(int *len) {\n static char *text = NULL;\n static int textmax = 0;\n\n for (*len = 0; ; (*len)++) {\n int ch = fgetc(source_fp);\n if (ch == EOF || ch == '\\n') {\n if (*len == 0)\n return NULL;\n break;\n }\n if (*len + 1 >= textmax) {\n textmax = (textmax == 0 ? 128 : textmax * 2);\n text = realloc(text, textmax);\n }\n text[*len] = ch;\n }\n text[*len] = '\\0';\n return text;\n}\n\nchar *rtrim(char *text, int *len) { // remove trailing spaces\n for (; *len > 0 && isspace(text[*len - 1]); --(*len))\n ;\n\n text[*len] = '\\0';\n return text;\n}\n\nTree *load_ast() {\n int len;\n char *yytext = read_line(&len);\n yytext = rtrim(yytext, &len);\n\n // get first token\n char *tok = strtok(yytext, \" \");\n\n if (tok[0] == ';') {\n return NULL;\n }\n NodeType node_type = get_enum_value(tok);\n\n // if there is extra data, get it\n char *p = tok + strlen(tok);\n if (p != &yytext[len]) {\n for (++p; isspace(*p); ++p)\n ;\n return make_leaf(node_type, p);\n }\n\n Tree *left = load_ast();\n Tree *right = load_ast();\n return make_node(node_type, left, right);\n}\n\nint main(int argc, char *argv[]) {\n init_io(&source_fp, stdin, \"r\", argc > 1 ? argv[1] : \"\");\n init_io(&dest_fp, stdout, \"wb\", argc > 2 ? argv[2] : \"\");\n\n code_gen(load_ast());\n code_finish();\n list_code();\n\n return 0;\n}"} {"title": "Compiler/lexical analyzer", "language": "C", "task": "The C and Python versions can be considered reference implementations.\n\n\n;Related Tasks\n* Syntax Analyzer task\n* Code Generator task\n* Virtual Machine Interpreter task\n* AST Interpreter task\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define NELEMS(arr) (sizeof(arr) / sizeof(arr[0]))\n\n#define da_dim(name, type) type *name = NULL; \\\n int _qy_ ## name ## _p = 0; \\\n int _qy_ ## name ## _max = 0\n#define da_rewind(name) _qy_ ## name ## _p = 0\n#define da_redim(name) do {if (_qy_ ## name ## _p >= _qy_ ## name ## _max) \\\n name = realloc(name, (_qy_ ## name ## _max += 32) * sizeof(name[0]));} while (0)\n#define da_append(name, x) do {da_redim(name); name[_qy_ ## name ## _p++] = x;} while (0)\n#define da_len(name) _qy_ ## name ## _p\n\ntypedef enum {\n tk_EOI, tk_Mul, tk_Div, tk_Mod, tk_Add, tk_Sub, tk_Negate, tk_Not, tk_Lss, tk_Leq,\n tk_Gtr, tk_Geq, tk_Eq, tk_Neq, tk_Assign, tk_And, tk_Or, tk_If, tk_Else, tk_While,\n tk_Print, tk_Putc, tk_Lparen, tk_Rparen, tk_Lbrace, tk_Rbrace, tk_Semi, tk_Comma,\n tk_Ident, tk_Integer, tk_String\n} TokenType;\n\ntypedef struct {\n TokenType tok;\n int err_ln, err_col;\n union {\n int n; /* value for constants */\n char *text; /* text for idents */\n };\n} tok_s;\n\nstatic FILE *source_fp, *dest_fp;\nstatic int line = 1, col = 0, the_ch = ' ';\nda_dim(text, char);\n\ntok_s gettok(void);\n\nstatic void error(int err_line, int err_col, const char *fmt, ... ) {\n char buf[1000];\n va_list ap;\n\n va_start(ap, fmt);\n vsprintf(buf, fmt, ap);\n va_end(ap);\n printf(\"(%d,%d) error: %s\\n\", err_line, err_col, buf);\n exit(1);\n}\n\nstatic int next_ch(void) { /* get next char from input */\n the_ch = getc(source_fp);\n ++col;\n if (the_ch == '\\n') {\n ++line;\n col = 0;\n }\n return the_ch;\n}\n\nstatic tok_s char_lit(int n, int err_line, int err_col) { /* 'x' */\n if (the_ch == '\\'')\n error(err_line, err_col, \"gettok: empty character constant\");\n if (the_ch == '\\\\') {\n next_ch();\n if (the_ch == 'n')\n n = 10;\n else if (the_ch == '\\\\')\n n = '\\\\';\n else error(err_line, err_col, \"gettok: unknown escape sequence \\\\%c\", the_ch);\n }\n if (next_ch() != '\\'')\n error(err_line, err_col, \"multi-character constant\");\n next_ch();\n return (tok_s){tk_Integer, err_line, err_col, {n}};\n}\n\nstatic tok_s div_or_cmt(int err_line, int err_col) { /* process divide or comments */\n if (the_ch != '*')\n return (tok_s){tk_Div, err_line, err_col, {0}};\n\n /* comment found */\n next_ch();\n for (;;) {\n if (the_ch == '*') {\n if (next_ch() == '/') {\n next_ch();\n return gettok();\n }\n } else if (the_ch == EOF)\n error(err_line, err_col, \"EOF in comment\");\n else\n next_ch();\n }\n}\n\nstatic tok_s string_lit(int start, int err_line, int err_col) { /* \"st\" */\n da_rewind(text);\n\n while (next_ch() != start) {\n if (the_ch == '\\n') error(err_line, err_col, \"EOL in string\");\n if (the_ch == EOF) error(err_line, err_col, \"EOF in string\");\n da_append(text, (char)the_ch);\n }\n da_append(text, '\\0');\n\n next_ch();\n return (tok_s){tk_String, err_line, err_col, {.text=text}};\n}\n\nstatic int kwd_cmp(const void *p1, const void *p2) {\n return strcmp(*(char **)p1, *(char **)p2);\n}\n\nstatic TokenType get_ident_type(const char *ident) {\n static struct {\n const char *s;\n TokenType sym;\n } kwds[] = {\n {\"else\", tk_Else},\n {\"if\", tk_If},\n {\"print\", tk_Print},\n {\"putc\", tk_Putc},\n {\"while\", tk_While},\n }, *kwp;\n\n return (kwp = bsearch(&ident, kwds, NELEMS(kwds), sizeof(kwds[0]), kwd_cmp)) == NULL ? tk_Ident : kwp->sym;\n}\n\nstatic tok_s ident_or_int(int err_line, int err_col) {\n int n, is_number = true;\n\n da_rewind(text);\n while (isalnum(the_ch) || the_ch == '_') {\n da_append(text, (char)the_ch);\n if (!isdigit(the_ch))\n is_number = false;\n next_ch();\n }\n if (da_len(text) == 0)\n error(err_line, err_col, \"gettok: unrecognized character (%d) '%c'\\n\", the_ch, the_ch);\n da_append(text, '\\0');\n if (isdigit(text[0])) {\n if (!is_number)\n error(err_line, err_col, \"invalid number: %s\\n\", text);\n n = strtol(text, NULL, 0);\n if (n == LONG_MAX && errno == ERANGE)\n error(err_line, err_col, \"Number exceeds maximum value\");\n return (tok_s){tk_Integer, err_line, err_col, {n}};\n }\n return (tok_s){get_ident_type(text), err_line, err_col, {.text=text}};\n}\n\nstatic tok_s follow(int expect, TokenType ifyes, TokenType ifno, int err_line, int err_col) { /* look ahead for '>=', etc. */\n if (the_ch == expect) {\n next_ch();\n return (tok_s){ifyes, err_line, err_col, {0}};\n }\n if (ifno == tk_EOI)\n error(err_line, err_col, \"follow: unrecognized character '%c' (%d)\\n\", the_ch, the_ch);\n return (tok_s){ifno, err_line, err_col, {0}};\n}\n\ntok_s gettok(void) { /* return the token type */\n /* skip white space */\n while (isspace(the_ch))\n next_ch();\n int err_line = line;\n int err_col = col;\n switch (the_ch) {\n case '{': next_ch(); return (tok_s){tk_Lbrace, err_line, err_col, {0}};\n case '}': next_ch(); return (tok_s){tk_Rbrace, err_line, err_col, {0}};\n case '(': next_ch(); return (tok_s){tk_Lparen, err_line, err_col, {0}};\n case ')': next_ch(); return (tok_s){tk_Rparen, err_line, err_col, {0}};\n case '+': next_ch(); return (tok_s){tk_Add, err_line, err_col, {0}};\n case '-': next_ch(); return (tok_s){tk_Sub, err_line, err_col, {0}};\n case '*': next_ch(); return (tok_s){tk_Mul, err_line, err_col, {0}};\n case '%': next_ch(); return (tok_s){tk_Mod, err_line, err_col, {0}};\n case ';': next_ch(); return (tok_s){tk_Semi, err_line, err_col, {0}};\n case ',': next_ch(); return (tok_s){tk_Comma,err_line, err_col, {0}};\n case '/': next_ch(); return div_or_cmt(err_line, err_col);\n case '\\'': next_ch(); return char_lit(the_ch, err_line, err_col);\n case '<': next_ch(); return follow('=', tk_Leq, tk_Lss, err_line, err_col);\n case '>': next_ch(); return follow('=', tk_Geq, tk_Gtr, err_line, err_col);\n case '=': next_ch(); return follow('=', tk_Eq, tk_Assign, err_line, err_col);\n case '!': next_ch(); return follow('=', tk_Neq, tk_Not, err_line, err_col);\n case '&': next_ch(); return follow('&', tk_And, tk_EOI, err_line, err_col);\n case '|': next_ch(); return follow('|', tk_Or, tk_EOI, err_line, err_col);\n case '\"' : return string_lit(the_ch, err_line, err_col);\n default: return ident_or_int(err_line, err_col);\n case EOF: return (tok_s){tk_EOI, err_line, err_col, {0}};\n }\n}\n\nvoid run(void) { /* tokenize the given input */\n tok_s tok;\n do {\n tok = gettok();\n fprintf(dest_fp, \"%5d %5d %.15s\",\n tok.err_ln, tok.err_col,\n &\"End_of_input Op_multiply Op_divide Op_mod Op_add \"\n \"Op_subtract Op_negate Op_not Op_less Op_lessequal \"\n \"Op_greater Op_greaterequal Op_equal Op_notequal Op_assign \"\n \"Op_and Op_or Keyword_if Keyword_else Keyword_while \"\n \"Keyword_print Keyword_putc LeftParen RightParen LeftBrace \"\n \"RightBrace Semicolon Comma Identifier Integer \"\n \"String \"\n [tok.tok * 16]);\n if (tok.tok == tk_Integer) fprintf(dest_fp, \" %4d\", tok.n);\n else if (tok.tok == tk_Ident) fprintf(dest_fp, \" %s\", tok.text);\n else if (tok.tok == tk_String) fprintf(dest_fp, \" \\\"%s\\\"\", tok.text);\n fprintf(dest_fp, \"\\n\");\n } while (tok.tok != tk_EOI);\n if (dest_fp != stdout)\n fclose(dest_fp);\n}\n\nvoid init_io(FILE **fp, FILE *std, const char mode[], const char fn[]) {\n if (fn[0] == '\\0')\n *fp = std;\n else if ((*fp = fopen(fn, mode)) == NULL)\n error(0, 0, \"Can't open %s\\n\", fn);\n}\n\nint main(int argc, char *argv[]) {\n init_io(&source_fp, stdin, \"r\", argc > 1 ? argv[1] : \"\");\n init_io(&dest_fp, stdout, \"wb\", argc > 2 ? argv[2] : \"\");\n run();\n return 0;\n}"} {"title": "Compiler/syntax analyzer", "language": "C", "task": "The C and Python versions can be considered reference implementations.\n\n;Related Tasks\n\n* Lexical Analyzer task\n* Code Generator task\n* Virtual Machine Interpreter task\n* AST Interpreter task\n\n\n__TOC__\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n\n#define NELEMS(arr) (sizeof(arr) / sizeof(arr[0]))\n\ntypedef enum {\n tk_EOI, tk_Mul, tk_Div, tk_Mod, tk_Add, tk_Sub, tk_Negate, tk_Not, tk_Lss, tk_Leq, tk_Gtr,\n tk_Geq, tk_Eql, tk_Neq, tk_Assign, tk_And, tk_Or, tk_If, tk_Else, tk_While, tk_Print,\n tk_Putc, tk_Lparen, tk_Rparen, tk_Lbrace, tk_Rbrace, tk_Semi, tk_Comma, tk_Ident,\n tk_Integer, tk_String\n} TokenType;\n\ntypedef enum {\n nd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While,\n nd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq,\n nd_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or\n} NodeType;\n\ntypedef struct {\n TokenType tok;\n int err_ln;\n int err_col;\n char *text; /* ident or string literal or integer value */\n} tok_s;\n\ntypedef struct Tree {\n NodeType node_type;\n struct Tree *left;\n struct Tree *right;\n char *value;\n} Tree;\n\n// dependency: Ordered by tok, must remain in same order as TokenType enum\nstruct {\n char *text, *enum_text;\n TokenType tok;\n bool right_associative, is_binary, is_unary;\n int precedence;\n NodeType node_type;\n} atr[] = {\n {\"EOI\", \"End_of_input\" , tk_EOI, false, false, false, -1, -1 },\n {\"*\", \"Op_multiply\" , tk_Mul, false, true, false, 13, nd_Mul },\n {\"/\", \"Op_divide\" , tk_Div, false, true, false, 13, nd_Div },\n {\"%\", \"Op_mod\" , tk_Mod, false, true, false, 13, nd_Mod },\n {\"+\", \"Op_add\" , tk_Add, false, true, false, 12, nd_Add },\n {\"-\", \"Op_subtract\" , tk_Sub, false, true, false, 12, nd_Sub },\n {\"-\", \"Op_negate\" , tk_Negate, false, false, true, 14, nd_Negate },\n {\"!\", \"Op_not\" , tk_Not, false, false, true, 14, nd_Not },\n {\"<\", \"Op_less\" , tk_Lss, false, true, false, 10, nd_Lss },\n {\"<=\", \"Op_lessequal\" , tk_Leq, false, true, false, 10, nd_Leq },\n {\">\", \"Op_greater\" , tk_Gtr, false, true, false, 10, nd_Gtr },\n {\">=\", \"Op_greaterequal\", tk_Geq, false, true, false, 10, nd_Geq },\n {\"==\", \"Op_equal\" , tk_Eql, false, true, false, 9, nd_Eql },\n {\"!=\", \"Op_notequal\" , tk_Neq, false, true, false, 9, nd_Neq },\n {\"=\", \"Op_assign\" , tk_Assign, false, false, false, -1, nd_Assign },\n {\"&&\", \"Op_and\" , tk_And, false, true, false, 5, nd_And },\n {\"||\", \"Op_or\" , tk_Or, false, true, false, 4, nd_Or },\n {\"if\", \"Keyword_if\" , tk_If, false, false, false, -1, nd_If },\n {\"else\", \"Keyword_else\" , tk_Else, false, false, false, -1, -1 },\n {\"while\", \"Keyword_while\" , tk_While, false, false, false, -1, nd_While },\n {\"print\", \"Keyword_print\" , tk_Print, false, false, false, -1, -1 },\n {\"putc\", \"Keyword_putc\" , tk_Putc, false, false, false, -1, -1 },\n {\"(\", \"LeftParen\" , tk_Lparen, false, false, false, -1, -1 },\n {\")\", \"RightParen\" , tk_Rparen, false, false, false, -1, -1 },\n {\"{\", \"LeftBrace\" , tk_Lbrace, false, false, false, -1, -1 },\n {\"}\", \"RightBrace\" , tk_Rbrace, false, false, false, -1, -1 },\n {\";\", \"Semicolon\" , tk_Semi, false, false, false, -1, -1 },\n {\",\", \"Comma\" , tk_Comma, false, false, false, -1, -1 },\n {\"Ident\", \"Identifier\" , tk_Ident, false, false, false, -1, nd_Ident },\n {\"Integer literal\", \"Integer\" , tk_Integer, false, false, false, -1, nd_Integer},\n {\"String literal\", \"String\" , tk_String, false, false, false, -1, nd_String },\n};\n\nchar *Display_nodes[] = {\"Identifier\", \"String\", \"Integer\", \"Sequence\", \"If\", \"Prtc\",\n \"Prts\", \"Prti\", \"While\", \"Assign\", \"Negate\", \"Not\", \"Multiply\", \"Divide\", \"Mod\",\n \"Add\", \"Subtract\", \"Less\", \"LessEqual\", \"Greater\", \"GreaterEqual\", \"Equal\",\n \"NotEqual\", \"And\", \"Or\"};\n\nstatic tok_s tok;\nstatic FILE *source_fp, *dest_fp;\n\nTree *paren_expr();\n\nvoid error(int err_line, int err_col, const char *fmt, ... ) {\n va_list ap;\n char buf[1000];\n\n va_start(ap, fmt);\n vsprintf(buf, fmt, ap);\n va_end(ap);\n printf(\"(%d, %d) error: %s\\n\", err_line, err_col, buf);\n exit(1);\n}\n\nchar *read_line(int *len) {\n static char *text = NULL;\n static int textmax = 0;\n\n for (*len = 0; ; (*len)++) {\n int ch = fgetc(source_fp);\n if (ch == EOF || ch == '\\n') {\n if (*len == 0)\n return NULL;\n break;\n }\n if (*len + 1 >= textmax) {\n textmax = (textmax == 0 ? 128 : textmax * 2);\n text = realloc(text, textmax);\n }\n text[*len] = ch;\n }\n text[*len] = '\\0';\n return text;\n}\n\nchar *rtrim(char *text, int *len) { // remove trailing spaces\n for (; *len > 0 && isspace(text[*len - 1]); --(*len))\n ;\n\n text[*len] = '\\0';\n return text;\n}\n\nTokenType get_enum(const char *name) { // return internal version of name\n for (size_t i = 0; i < NELEMS(atr); i++) {\n if (strcmp(atr[i].enum_text, name) == 0)\n return atr[i].tok;\n }\n error(0, 0, \"Unknown token %s\\n\", name);\n return 0;\n}\n\ntok_s gettok() {\n int len;\n tok_s tok;\n char *yytext = read_line(&len);\n yytext = rtrim(yytext, &len);\n\n // [ ]*{lineno}[ ]+{colno}[ ]+token[ ]+optional\n\n // get line and column\n tok.err_ln = atoi(strtok(yytext, \" \"));\n tok.err_col = atoi(strtok(NULL, \" \"));\n\n // get the token name\n char *name = strtok(NULL, \" \");\n tok.tok = get_enum(name);\n\n // if there is extra data, get it\n char *p = name + strlen(name);\n if (p != &yytext[len]) {\n for (++p; isspace(*p); ++p)\n ;\n tok.text = strdup(p);\n }\n return tok;\n}\n\nTree *make_node(NodeType node_type, Tree *left, Tree *right) {\n Tree *t = calloc(sizeof(Tree), 1);\n t->node_type = node_type;\n t->left = left;\n t->right = right;\n return t;\n}\n\nTree *make_leaf(NodeType node_type, char *value) {\n Tree *t = calloc(sizeof(Tree), 1);\n t->node_type = node_type;\n t->value = strdup(value);\n return t;\n}\n\nvoid expect(const char msg[], TokenType s) {\n if (tok.tok == s) {\n tok = gettok();\n return;\n }\n error(tok.err_ln, tok.err_col, \"%s: Expecting '%s', found '%s'\\n\", msg, atr[s].text, atr[tok.tok].text);\n}\n\nTree *expr(int p) {\n Tree *x = NULL, *node;\n TokenType op;\n\n switch (tok.tok) {\n case tk_Lparen:\n x = paren_expr();\n break;\n case tk_Sub: case tk_Add:\n op = tok.tok;\n tok = gettok();\n node = expr(atr[tk_Negate].precedence);\n x = (op == tk_Sub) ? make_node(nd_Negate, node, NULL) : node;\n break;\n case tk_Not:\n tok = gettok();\n x = make_node(nd_Not, expr(atr[tk_Not].precedence), NULL);\n break;\n case tk_Ident:\n x = make_leaf(nd_Ident, tok.text);\n tok = gettok();\n break;\n case tk_Integer:\n x = make_leaf(nd_Integer, tok.text);\n tok = gettok();\n break;\n default:\n error(tok.err_ln, tok.err_col, \"Expecting a primary, found: %s\\n\", atr[tok.tok].text);\n }\n\n while (atr[tok.tok].is_binary && atr[tok.tok].precedence >= p) {\n TokenType op = tok.tok;\n\n tok = gettok();\n\n int q = atr[op].precedence;\n if (!atr[op].right_associative)\n q++;\n\n node = expr(q);\n x = make_node(atr[op].node_type, x, node);\n }\n return x;\n}\n\nTree *paren_expr() {\n expect(\"paren_expr\", tk_Lparen);\n Tree *t = expr(0);\n expect(\"paren_expr\", tk_Rparen);\n return t;\n}\n\nTree *stmt() {\n Tree *t = NULL, *v, *e, *s, *s2;\n\n switch (tok.tok) {\n case tk_If:\n tok = gettok();\n e = paren_expr();\n s = stmt();\n s2 = NULL;\n if (tok.tok == tk_Else) {\n tok = gettok();\n s2 = stmt();\n }\n t = make_node(nd_If, e, make_node(nd_If, s, s2));\n break;\n case tk_Putc:\n tok = gettok();\n e = paren_expr();\n t = make_node(nd_Prtc, e, NULL);\n expect(\"Putc\", tk_Semi);\n break;\n case tk_Print: /* print '(' expr {',' expr} ')' */\n tok = gettok();\n for (expect(\"Print\", tk_Lparen); ; expect(\"Print\", tk_Comma)) {\n if (tok.tok == tk_String) {\n e = make_node(nd_Prts, make_leaf(nd_String, tok.text), NULL);\n tok = gettok();\n } else\n e = make_node(nd_Prti, expr(0), NULL);\n\n t = make_node(nd_Sequence, t, e);\n\n if (tok.tok != tk_Comma)\n break;\n }\n expect(\"Print\", tk_Rparen);\n expect(\"Print\", tk_Semi);\n break;\n case tk_Semi:\n tok = gettok();\n break;\n case tk_Ident:\n v = make_leaf(nd_Ident, tok.text);\n tok = gettok();\n expect(\"assign\", tk_Assign);\n e = expr(0);\n t = make_node(nd_Assign, v, e);\n expect(\"assign\", tk_Semi);\n break;\n case tk_While:\n tok = gettok();\n e = paren_expr();\n s = stmt();\n t = make_node(nd_While, e, s);\n break;\n case tk_Lbrace: /* {stmt} */\n for (expect(\"Lbrace\", tk_Lbrace); tok.tok != tk_Rbrace && tok.tok != tk_EOI;)\n t = make_node(nd_Sequence, t, stmt());\n expect(\"Lbrace\", tk_Rbrace);\n break;\n case tk_EOI:\n break;\n default: error(tok.err_ln, tok.err_col, \"expecting start of statement, found '%s'\\n\", atr[tok.tok].text);\n }\n return t;\n}\n\nTree *parse() {\n Tree *t = NULL;\n\n tok = gettok();\n do {\n t = make_node(nd_Sequence, t, stmt());\n } while (t != NULL && tok.tok != tk_EOI);\n return t;\n}\n\nvoid prt_ast(Tree *t) {\n if (t == NULL)\n printf(\";\\n\");\n else {\n printf(\"%-14s \", Display_nodes[t->node_type]);\n if (t->node_type == nd_Ident || t->node_type == nd_Integer || t->node_type == nd_String) {\n printf(\"%s\\n\", t->value);\n } else {\n printf(\"\\n\");\n prt_ast(t->left);\n prt_ast(t->right);\n }\n }\n}\n\nvoid init_io(FILE **fp, FILE *std, const char mode[], const char fn[]) {\n if (fn[0] == '\\0')\n *fp = std;\n else if ((*fp = fopen(fn, mode)) == NULL)\n error(0, 0, \"Can't open %s\\n\", fn);\n}\n\nint main(int argc, char *argv[]) {\n init_io(&source_fp, stdin, \"r\", argc > 1 ? argv[1] : \"\");\n init_io(&dest_fp, stdout, \"wb\", argc > 2 ? argv[2] : \"\");\n prt_ast(parse());\n}"} {"title": "Compiler/virtual machine interpreter", "language": "C", "task": "The C and Python versions can be considered reference implementations.\n\n;Related Tasks\n\n* Lexical Analyzer task\n* Syntax Analyzer task\n* Code Generator task\n* AST Interpreter task\n\n\n__TOC__\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n\n#define NELEMS(arr) (sizeof(arr) / sizeof(arr[0]))\n\n#define da_dim(name, type) type *name = NULL; \\\n int _qy_ ## name ## _p = 0; \\\n int _qy_ ## name ## _max = 0\n\n#define da_redim(name) do {if (_qy_ ## name ## _p >= _qy_ ## name ## _max) \\\n name = realloc(name, (_qy_ ## name ## _max += 32) * sizeof(name[0]));} while (0)\n\n#define da_rewind(name) _qy_ ## name ## _p = 0\n\n#define da_append(name, x) do {da_redim(name); name[_qy_ ## name ## _p++] = x;} while (0)\n\ntypedef unsigned char uchar;\ntypedef uchar code;\n\ntypedef enum { FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND,\n OR, NEG, NOT, JMP, JZ, PRTC, PRTS, PRTI, HALT\n} Code_t;\n\ntypedef struct Code_map {\n char *text;\n Code_t op;\n} Code_map;\n\nCode_map code_map[] = {\n {\"fetch\", FETCH},\n {\"store\", STORE},\n {\"push\", PUSH },\n {\"add\", ADD },\n {\"sub\", SUB },\n {\"mul\", MUL },\n {\"div\", DIV },\n {\"mod\", MOD },\n {\"lt\", LT },\n {\"gt\", GT },\n {\"le\", LE },\n {\"ge\", GE },\n {\"eq\", EQ },\n {\"ne\", NE },\n {\"and\", AND },\n {\"or\", OR },\n {\"neg\", NEG },\n {\"not\", NOT },\n {\"jmp\", JMP },\n {\"jz\", JZ },\n {\"prtc\", PRTC },\n {\"prts\", PRTS },\n {\"prti\", PRTI },\n {\"halt\", HALT },\n};\n\nFILE *source_fp;\nda_dim(object, code);\n\nvoid error(const char *fmt, ... ) {\n va_list ap;\n char buf[1000];\n\n va_start(ap, fmt);\n vsprintf(buf, fmt, ap);\n va_end(ap);\n printf(\"error: %s\\n\", buf);\n exit(1);\n}\n\n/*** Virtual Machine interpreter ***/\nvoid run_vm(const code obj[], int32_t data[], int g_size, char **string_pool) {\n int32_t *sp = &data[g_size + 1];\n const code *pc = obj;\n\n again:\n switch (*pc++) {\n case FETCH: *sp++ = data[*(int32_t *)pc]; pc += sizeof(int32_t); goto again;\n case STORE: data[*(int32_t *)pc] = *--sp; pc += sizeof(int32_t); goto again;\n case PUSH: *sp++ = *(int32_t *)pc; pc += sizeof(int32_t); goto again;\n case ADD: sp[-2] += sp[-1]; --sp; goto again;\n case SUB: sp[-2] -= sp[-1]; --sp; goto again;\n case MUL: sp[-2] *= sp[-1]; --sp; goto again;\n case DIV: sp[-2] /= sp[-1]; --sp; goto again;\n case MOD: sp[-2] %= sp[-1]; --sp; goto again;\n case LT: sp[-2] = sp[-2] < sp[-1]; --sp; goto again;\n case GT: sp[-2] = sp[-2] > sp[-1]; --sp; goto again;\n case LE: sp[-2] = sp[-2] <= sp[-1]; --sp; goto again;\n case GE: sp[-2] = sp[-2] >= sp[-1]; --sp; goto again;\n case EQ: sp[-2] = sp[-2] == sp[-1]; --sp; goto again;\n case NE: sp[-2] = sp[-2] != sp[-1]; --sp; goto again;\n case AND: sp[-2] = sp[-2] && sp[-1]; --sp; goto again;\n case OR: sp[-2] = sp[-2] || sp[-1]; --sp; goto again;\n case NEG: sp[-1] = -sp[-1]; goto again;\n case NOT: sp[-1] = !sp[-1]; goto again;\n case JMP: pc += *(int32_t *)pc; goto again;\n case JZ: pc += (*--sp == 0) ? *(int32_t *)pc : (int32_t)sizeof(int32_t); goto again;\n case PRTC: printf(\"%c\", sp[-1]); --sp; goto again;\n case PRTS: printf(\"%s\", string_pool[sp[-1]]); --sp; goto again;\n case PRTI: printf(\"%d\", sp[-1]); --sp; goto again;\n case HALT: break;\n default: error(\"Unknown opcode %d\\n\", *(pc - 1));\n }\n}\n\nchar *read_line(int *len) {\n static char *text = NULL;\n static int textmax = 0;\n\n for (*len = 0; ; (*len)++) {\n int ch = fgetc(source_fp);\n if (ch == EOF || ch == '\\n') {\n if (*len == 0)\n return NULL;\n break;\n }\n if (*len + 1 >= textmax) {\n textmax = (textmax == 0 ? 128 : textmax * 2);\n text = realloc(text, textmax);\n }\n text[*len] = ch;\n }\n text[*len] = '\\0';\n return text;\n}\n\nchar *rtrim(char *text, int *len) { // remove trailing spaces\n for (; *len > 0 && isspace(text[*len - 1]); --(*len))\n ;\n\n text[*len] = '\\0';\n return text;\n}\n\nchar *translate(char *st) {\n char *p, *q;\n if (st[0] == '\"') // skip leading \" if there\n ++st;\n p = q = st;\n\n while ((*p++ = *q++) != '\\0') {\n if (q[-1] == '\\\\') {\n if (q[0] == 'n') {\n p[-1] = '\\n';\n ++q;\n } else if (q[0] == '\\\\') {\n ++q;\n }\n }\n if (q[0] == '\"' && q[1] == '\\0') // skip trialing \" if there\n ++q;\n }\n\n return st;\n}\n\n/* convert an opcode string into its byte value */\nint findit(const char text[], int offset) {\n for (size_t i = 0; i < sizeof(code_map) / sizeof(code_map[0]); i++) {\n if (strcmp(code_map[i].text, text) == 0)\n return code_map[i].op;\n }\n error(\"Unknown instruction %s at %d\\n\", text, offset);\n return -1;\n}\n\nvoid emit_byte(int c) {\n da_append(object, (uchar)c);\n}\n\nvoid emit_int(int32_t n) {\n union {\n int32_t n;\n unsigned char c[sizeof(int32_t)];\n } x;\n\n x.n = n;\n\n for (size_t i = 0; i < sizeof(x.n); ++i) {\n emit_byte(x.c[i]);\n }\n}\n\n/*\nDatasize: 5 Strings: 3\n\" is prime\\n\"\n\"Total primes found: \"\n\"\\n\"\n 154 jmp (-73) 82\n 164 jz (32) 197\n 175 push 0\n 159 fetch [4]\n 149 store [3]\n */\n\n/* Load code into global array object, return the string pool and data size */\nchar **load_code(int *ds) {\n int line_len, n_strings;\n char **string_pool;\n char *text = read_line(&line_len);\n text = rtrim(text, &line_len);\n\n strtok(text, \" \"); // skip \"Datasize:\"\n *ds = atoi(strtok(NULL, \" \")); // get actual data_size\n strtok(NULL, \" \"); // skip \"Strings:\"\n n_strings = atoi(strtok(NULL, \" \")); // get number of strings\n\n string_pool = malloc(n_strings * sizeof(char *));\n for (int i = 0; i < n_strings; ++i) {\n text = read_line(&line_len);\n text = rtrim(text, &line_len);\n text = translate(text);\n string_pool[i] = strdup(text);\n }\n\n for (;;) {\n int len;\n\n text = read_line(&line_len);\n if (text == NULL)\n break;\n text = rtrim(text, &line_len);\n\n int offset = atoi(strtok(text, \" \")); // get the offset\n char *instr = strtok(NULL, \" \"); // get the instruction\n int opcode = findit(instr, offset);\n emit_byte(opcode);\n char *operand = strtok(NULL, \" \");\n\n switch (opcode) {\n case JMP: case JZ:\n operand++; // skip the '('\n len = strlen(operand);\n operand[len - 1] = '\\0'; // remove the ')'\n emit_int(atoi(operand));\n break;\n case PUSH:\n emit_int(atoi(operand));\n break;\n case FETCH: case STORE:\n operand++; // skip the '['\n len = strlen(operand);\n operand[len - 1] = '\\0'; // remove the ']'\n emit_int(atoi(operand));\n break;\n }\n }\n return string_pool;\n}\n\nvoid init_io(FILE **fp, FILE *std, const char mode[], const char fn[]) {\n if (fn[0] == '\\0')\n *fp = std;\n else if ((*fp = fopen(fn, mode)) == NULL)\n error(0, 0, \"Can't open %s\\n\", fn);\n}\n\nint main(int argc, char *argv[]) {\n init_io(&source_fp, stdin, \"r\", argc > 1 ? argv[1] : \"\");\n int data_size;\n char **string_pool = load_code(&data_size);\n int data[1000 + data_size];\n run_vm(object, data, data_size, string_pool);\n}"} {"title": "Conjugate transpose", "language": "C", "task": "Suppose that a conjugate transpose of M is a matrix M^H containing the [[complex conjugate]]s of the [[matrix transposition]] of M.\n\n::: (M^H)_{ji} = \\overline{M_{ij}}\n\n\nThis means that row j, column i of the conjugate transpose equals the \ncomplex conjugate of row i, column j of the original matrix.\n\n\nIn the next list, M must also be a square matrix.\n\n* A Hermitian matrix equals its own conjugate transpose: M^H = M.\n* A multiplication with its conjugate transpose: M^HM = MM^H.\n* A iff M^HM = I_n and iff MM^H = I_n, where I_n is the identity matrix.\n\n\n\n;Task:\nGiven some matrix of complex numbers, find its conjugate transpose. \n\nAlso determine if the matrix is a:\n::* Hermitian matrix,\n::* normal matrix, or \n::* unitary matrix.\n\n\n;See also:\n* MathWorld entry: conjugate transpose\n* MathWorld entry: Hermitian matrix\n* MathWorld entry: normal matrix\n* MathWorld entry: unitary matrix\n\n", "solution": "/* Uses C99 specified complex.h, complex datatype has to be defined and operation provided if used on non-C99 compilers */\n\n#include\n#include\n#include\n\ntypedef struct\n{\n int rows, cols;\n complex **z;\n} matrix;\n\nmatrix\ntranspose (matrix a)\n{\n int i, j;\n matrix b;\n\n b.rows = a.cols;\n b.cols = a.rows;\n\n b.z = malloc (b.rows * sizeof (complex *));\n\n for (i = 0; i < b.rows; i++)\n {\n b.z[i] = malloc (b.cols * sizeof (complex));\n for (j = 0; j < b.cols; j++)\n {\n b.z[i][j] = conj (a.z[j][i]);\n }\n }\n\n return b;\n}\n\nint\nisHermitian (matrix a)\n{\n int i, j;\n matrix b = transpose (a);\n\n if (b.rows == a.rows && b.cols == a.cols)\n {\n for (i = 0; i < b.rows; i++)\n {\n for (j = 0; j < b.cols; j++)\n {\n if (b.z[i][j] != a.z[i][j])\n return 0;\n }\n }\n }\n\n else\n return 0;\n\n return 1;\n}\n\nmatrix\nmultiply (matrix a, matrix b)\n{\n matrix c;\n int i, j;\n\n if (a.cols == b.rows)\n {\n c.rows = a.rows;\n c.cols = b.cols;\n\n c.z = malloc (c.rows * (sizeof (complex *)));\n\n for (i = 0; i < c.rows; i++)\n {\n c.z[i] = malloc (c.cols * sizeof (complex));\n c.z[i][j] = 0 + 0 * I;\n for (j = 0; j < b.cols; j++)\n {\n c.z[i][j] += a.z[i][j] * b.z[j][i];\n }\n }\n\n }\n\n return c;\n}\n\nint\nisNormal (matrix a)\n{\n int i, j;\n matrix a_ah, ah_a;\n\n if (a.rows != a.cols)\n return 0;\n\n a_ah = multiply (a, transpose (a));\n ah_a = multiply (transpose (a), a);\n\n for (i = 0; i < a.rows; i++)\n {\n for (j = 0; j < a.cols; j++)\n {\n if (a_ah.z[i][j] != ah_a.z[i][j])\n return 0;\n }\n }\n\n return 1;\n}\n\nint\nisUnitary (matrix a)\n{\n matrix b;\n int i, j;\n if (isNormal (a) == 1)\n {\n b = multiply (a, transpose(a));\n\n for (i = 0; i < b.rows; i++)\n {\n for (j = 0; j < b.cols; j++)\n {\n if ((i == j && b.z[i][j] != 1) || (i != j && b.z[i][j] != 0))\n return 0;\n }\n }\n return 1;\n }\n return 0;\n}\n\n\nint\nmain ()\n{\n complex z = 3 + 4 * I;\n matrix a, aT;\n int i, j;\n printf (\"Enter rows and columns :\");\n scanf (\"%d%d\", &a.rows, &a.cols);\n\n a.z = malloc (a.rows * sizeof (complex *));\n printf (\"Randomly Generated Complex Matrix A is : \");\n for (i = 0; i < a.rows; i++)\n {\n printf (\"\\n\");\n a.z[i] = malloc (a.cols * sizeof (complex));\n for (j = 0; j < a.cols; j++)\n {\n a.z[i][j] = rand () % 10 + rand () % 10 * I;\n printf (\"\\t%f + %fi\", creal (a.z[i][j]), cimag (a.z[i][j]));\n }\n }\n\n aT = transpose (a);\n\n printf (\"\\n\\nTranspose of Complex Matrix A is : \");\n for (i = 0; i < aT.rows; i++)\n {\n printf (\"\\n\");\n aT.z[i] = malloc (aT.cols * sizeof (complex));\n for (j = 0; j < aT.cols; j++)\n {\n aT.z[i][j] = rand () % 10 + rand () % 10 * I;\n printf (\"\\t%f + %fi\", creal (aT.z[i][j]), cimag (aT.z[i][j]));\n }\n }\n\n printf (\"\\n\\nComplex Matrix A %s hermitian\",\n isHermitian (a) == 1 ? \"is\" : \"is not\");\n printf (\"\\n\\nComplex Matrix A %s unitary\",\n isUnitary (a) == 1 ? \"is\" : \"is not\");\n printf (\"\\n\\nComplex Matrix A %s normal\",\n isNormal (a) == 1 ? \"is\" : \"is not\");\n\n\n\n return 0;\n}"} {"title": "Continued fraction/Arithmetic/Construct from rational number", "language": "C", "task": "To understand this task in context please see [[Continued fraction arithmetic]]\nThe purpose of this task is to write a function \\mathit{r2cf}(\\mathrm{int} N_1, \\mathrm{int} N_2), or \\mathit{r2cf}(\\mathrm{Fraction} N), which will output a continued fraction assuming:\n:N_1 is the numerator\n:N_2 is the denominator\n \nThe function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.\n\nTo achieve this it must determine: the integer part; and remainder part, of N_1 divided by N_2. It then sets N_1 to N_2 and N_2 to the determined remainder part. It then outputs the determined integer part. It does this until \\mathrm{abs}(N_2) is zero.\n\nDemonstrate the function by outputing the continued fraction for:\n: 1/2\n: 3\n: 23/8\n: 13/11\n: 22/7\n: -151/77\n\\sqrt 2 should approach [1; 2, 2, 2, 2, \\ldots] try ever closer rational approximations until boredom gets the better of you:\n: 14142,10000\n: 141421,100000\n: 1414214,1000000\n: 14142136,10000000\n\nTry :\n: 31,10\n: 314,100\n: 3142,1000\n: 31428,10000\n: 314285,100000\n: 3142857,1000000\n: 31428571,10000000\n: 314285714,100000000\n\nObserve how this rational number behaves differently to \\sqrt 2 and convince yourself that, in the same way as 3.7 may be represented as 3.70 when an extra decimal place is required, [3;7] may be represented as [3;7,\\infty] when an extra term is required.\n\n", "solution": "#include\n\ntypedef struct{\n\tint num,den;\n\t}fraction;\n\nfraction examples[] = {{1,2}, {3,1}, {23,8}, {13,11}, {22,7}, {-151,77}}; \nfraction sqrt2[] = {{14142,10000}, {141421,100000}, {1414214,1000000}, {14142136,10000000}};\nfraction pi[] = {{31,10}, {314,100}, {3142,1000}, {31428,10000}, {314285,100000}, {3142857,1000000}, {31428571,10000000}, {314285714,100000000}};\n\nint r2cf(int *numerator,int *denominator)\n{\n\tint quotient=0,temp;\n\t\n\tif(denominator != 0)\n\t{\n\t\tquotient = *numerator / *denominator;\n\t\t\n\t\ttemp = *numerator;\n\t\t\n\t\t*numerator = *denominator;\n\t\t\n\t\t*denominator = temp % *denominator;\n\t}\n\t\n\treturn quotient;\n}\n\nint main()\n{\n\tint i;\n\t\n\tprintf(\"Running the examples :\");\n\t\n\tfor(i=0;i\n#include \n#include \n#include \n\n/* f : number to convert.\n * num, denom: returned parts of the rational.\n * md: max denominator value. Note that machine floating point number\n * has a finite resolution (10e-16 ish for 64 bit double), so specifying\n * a \"best match with minimal error\" is often wrong, because one can\n * always just retrieve the significand and return that divided by \n * 2**52, which is in a sense accurate, but generally not very useful:\n * 1.0/7.0 would be \"2573485501354569/18014398509481984\", for example.\n */\nvoid rat_approx(double f, int64_t md, int64_t *num, int64_t *denom)\n{\n\t/* a: continued fraction coefficients. */\n\tint64_t a, h[3] = { 0, 1, 0 }, k[3] = { 1, 0, 0 };\n\tint64_t x, d, n = 1;\n\tint i, neg = 0;\n\n\tif (md <= 1) { *denom = 1; *num = (int64_t) f; return; }\n\n\tif (f < 0) { neg = 1; f = -f; }\n\n\twhile (f != floor(f)) { n <<= 1; f *= 2; }\n\td = f;\n\n\t/* continued fraction and check denominator each step */\n\tfor (i = 0; i < 64; i++) {\n\t\ta = n ? d / n : 0;\n\t\tif (i && !a) break;\n\n\t\tx = d; d = n; n = x % n;\n\n\t\tx = a;\n\t\tif (k[1] * a + k[0] >= md) {\n\t\t\tx = (md - k[0]) / k[1];\n\t\t\tif (x * 2 >= a || k[1] >= md)\n\t\t\t\ti = 65;\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n\n\t\th[2] = x * h[1] + h[0]; h[0] = h[1]; h[1] = h[2];\n\t\tk[2] = x * k[1] + k[0]; k[0] = k[1]; k[1] = k[2];\n\t}\n\t*denom = k[1];\n\t*num = neg ? -h[1] : h[1];\n}\n\nint main()\n{\n\tint i;\n\tint64_t d, n;\n\tdouble f;\n\n\tprintf(\"f = %16.14f\\n\", f = 1.0/7);\n\tfor (i = 1; i <= 20000000; i *= 16) {\n\t\tprintf(\"denom <= %d: \", i);\n\t\trat_approx(f, i, &n, &d);\n\t\tprintf(\"%lld/%lld\\n\", n, d);\n\t}\n\n\tprintf(\"\\nf = %16.14f\\n\", f = atan2(1,1) * 4);\n\tfor (i = 1; i <= 20000000; i *= 16) {\n\t\tprintf(\"denom <= %d: \", i);\n\t\trat_approx(f, i, &n, &d);\n\t\tprintf(\"%lld/%lld\\n\", n, d);\n\t}\n\n\treturn 0;\n}"} {"title": "Convert seconds to compound duration", "language": "C", "task": "Write a function or program which:\n* takes a positive integer representing a duration in seconds as input (e.g., 100), and\n* returns a string which shows the same duration decomposed into:\n:::* weeks,\n:::* days, \n:::* hours, \n:::* minutes, and \n:::* seconds.\n\nThis is detailed below (e.g., \"2 hr, 59 sec\").\n\n\nDemonstrate that it passes the following three test-cases:\n\n'''''Test Cases'''''\n\n:::::{| class=\"wikitable\"\n|-\n! input number\n! output string\n|-\n| 7259\n| 2 hr, 59 sec\n|-\n| 86400\n| 1 d\n|-\n| 6000000\n| 9 wk, 6 d, 10 hr, 40 min\n|}\n\n'''''Details'''''\n\nThe following five units should be used:\n:::::{| class=\"wikitable\"\n|-\n! unit\n! suffix used in output\n! conversion\n|-\n| week\n| wk\n| 1 week = 7 days\n|-\n| day\n| d\n| 1 day = 24 hours\n|-\n| hour\n| hr\n| 1 hour = 60 minutes\n|-\n| minute\n| min\n| 1 minute = 60 seconds\n|-\n| second\n| sec\n| \n|}\n\nHowever, '''only''' include quantities with non-zero values in the output (e.g., return \"1 d\" and not \"0 wk, 1 d, 0 hr, 0 min, 0 sec\").\n\nGive larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)\n\nMimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).\n\n\n", "solution": "#include /* requires c99 */\n#include /* requires c99 */\n#include \n#include \n\n#define N_EL 5\n\nuintmax_t sec_to_week(uintmax_t);\nuintmax_t sec_to_day(uintmax_t);\nuintmax_t sec_to_hour(uintmax_t);\nuintmax_t sec_to_min(uintmax_t);\n\nuintmax_t week_to_sec(uintmax_t);\nuintmax_t day_to_sec(uintmax_t);\nuintmax_t hour_to_sec(uintmax_t);\nuintmax_t min_to_sec(uintmax_t);\n\nchar *format_sec(uintmax_t);\n /* the primary function */\n\n\nint main(int argc, char *argv[])\n{\n uintmax_t input;\n char *a;\n \n if(argc<2) {\n printf(\"usage: %s #seconds\\n\", argv[0]);\n return 1;\n }\n input = strtoumax(argv[1],(void *)0, 10 /*base 10*/);\n if(input<1) {\n printf(\"Bad input: %s\\n\", argv[1]);\n printf(\"usage: %s #seconds\\n\", argv[0]);\n return 1;\n }\n printf(\"Number entered: %\" PRIuMAX \"\\n\", input);\n a = format_sec(input);\n printf(a);\n free(a);\n \n return 0;\n}\n\n/* note: must free memory \n * after using this function */\nchar *format_sec(uintmax_t input)\n{\n int i;\n bool first;\n uintmax_t weeks, days, hours, mins; \n /*seconds kept in input*/\n \n char *retval;\n FILE *stream;\n size_t size;\n uintmax_t *traverse[N_EL]={&weeks,&days,\n &hours,&mins,&input};\n char *labels[N_EL]={\"wk\",\"d\",\"hr\",\"min\",\"sec\"};\n\n weeks = sec_to_week(input);\n input = input - week_to_sec(weeks);\n\n days = sec_to_day(input);\n input = input - day_to_sec(days);\n\n hours = sec_to_hour(input);\n input = input - hour_to_sec(hours);\n\n mins = sec_to_min(input);\n input = input - min_to_sec(mins); \n /* input now has the remaining seconds */\n\n /* open stream */\n stream = open_memstream(&retval,&size);\n if(stream == 0) {\n fprintf(stderr,\"Unable to allocate memory\");\n return 0;\n }\n\n /* populate stream */\n first = true;\n for(i=0;i\n\nint main(){\n char c;\n while ( (c=getchar()) != EOF ){\n putchar(c);\n }\n return 0;\n}\n"} {"title": "Count the coins", "language": "C", "task": "There are four types of common coins in US currency: \n:::# quarters (25 cents)\n:::# dimes (10 cents)\n:::# nickels (5 cents), and \n:::# pennies (1 cent) \n\n\nThere are six ways to make change for 15 cents:\n:::# A dime and a nickel \n:::# A dime and 5 pennies\n:::# 3 nickels\n:::# 2 nickels and 5 pennies\n:::# A nickel and 10 pennies\n:::# 15 pennies\n\n\n;Task:\nHow many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).\n\n\n;Optional:\nLess common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000? \n\n(Note: the answer is larger than 232).\n\n\n;References:\n* an algorithm from the book ''Structure and Interpretation of Computer Programs''.\n* an article in the algorithmist.\n* Change-making problem on Wikipedia.\n\n", "solution": "#include \n#include \n#include \n\n// ad hoc 128 bit integer type; faster than using GMP because of low\n// overhead\ntypedef struct { uint64_t x[2]; } i128;\n\n// display in decimal\nvoid show(i128 v) {\n\tuint32_t x[4] = {v.x[0], v.x[0] >> 32, v.x[1], v.x[1] >> 32};\n\tint i, j = 0, len = 4;\n\tchar buf[100];\n\tdo {\n\t\tuint64_t c = 0;\n\t\tfor (i = len; i--; ) {\n\t\t\tc = (c << 32) + x[i];\n\t\t\tx[i] = c / 10, c %= 10;\n\t\t}\n\n\t\tbuf[j++] = c + '0';\n\t\tfor (len = 4; !x[len - 1]; len--);\n\t} while (len);\n\n\twhile (j--) putchar(buf[j]);\n\tputchar('\\n');\n}\n\ni128 count(int sum, int *coins)\n{\n\tint n, i, k;\n\tfor (n = 0; coins[n]; n++);\n\n\ti128 **v = malloc(sizeof(int*) * n);\n\tint *idx = malloc(sizeof(int) * n);\n\n\tfor (i = 0; i < n; i++) {\n\t\tidx[i] = coins[i];\n\t\t// each v[i] is a cyclic buffer\n\t\tv[i] = calloc(sizeof(i128), coins[i]);\n\t}\n\n\tv[0][coins[0] - 1] = (i128) {{1, 0}};\n\n\tfor (k = 0; k <= sum; k++) {\n\t\tfor (i = 0; i < n; i++)\n\t\t\tif (!idx[i]--) idx[i] = coins[i] - 1;\n\n\t\ti128 c = v[0][ idx[0] ];\n\n\t\tfor (i = 1; i < n; i++) {\n\t\t\ti128 *p = v[i] + idx[i];\n\n\t\t\t// 128 bit addition\n\t\t\tp->x[0] += c.x[0];\n\t\t\tp->x[1] += c.x[1];\n\t\t\tif (p->x[0] < c.x[0]) // carry\n\t\t\t\tp->x[1] ++;\n\t\t\tc = *p;\n\t\t}\n\t}\n\n\ti128 r = v[n - 1][idx[n-1]];\n\n\tfor (i = 0; i < n; i++) free(v[i]);\n\tfree(v);\n\tfree(idx);\n\n\treturn r;\n}\n\n// simple recursive method; slow\nint count2(int sum, int *coins)\n{\n\tif (!*coins || sum < 0) return 0;\n\tif (!sum) return 1;\n\treturn count2(sum - *coins, coins) + count2(sum, coins + 1);\n}\n\nint main(void)\n{\n\tint us_coins[] = { 100, 50, 25, 10, 5, 1, 0 };\n\tint eu_coins[] = { 200, 100, 50, 20, 10, 5, 2, 1, 0 };\n\n\tshow(count( 100, us_coins + 2));\n\tshow(count( 1000, us_coins));\n\n\tshow(count( 1000 * 100, us_coins));\n\tshow(count( 10000 * 100, us_coins));\n\tshow(count(100000 * 100, us_coins));\n\n\tputchar('\\n');\n\n\tshow(count( 1 * 100, eu_coins));\n\tshow(count( 1000 * 100, eu_coins));\n\tshow(count( 10000 * 100, eu_coins));\n\tshow(count(100000 * 100, eu_coins));\n\n\treturn 0;\n}"} {"title": "Create an HTML table", "language": "C", "task": "Create an HTML table. \n* The table body should have at least three rows of three columns.\n* Each of these three columns should be labelled \"X\", \"Y\", and \"Z\". \n* An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. \n* The rows of the \"X\", \"Y\", and \"Z\" columns should be filled with random or sequential integers having 4 digits or less. \n* The numbers should be aligned in the same fashion for all columns.\n\n", "solution": "#include \n#include \n\nint main()\n{\n\tint i;\n\tprintf(\"\"\n\t\t\"\");\n\tfor (i = 0; i < 4; i++) {\n\t\tprintf(\"\", i,\n\t\t\trand() % 10000, rand() % 10000, rand() % 10000);\n\t}\n\tprintf(\"
XYZ
%d%d%d%d
\");\n\n\treturn 0;\n}"} {"title": "Currency", "language": "C", "task": "Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents. \n\n\n;Note:\nThe '''IEEE 754''' binary floating point representations of numbers like '''2.86''' and '''.0765''' are not exact.\n\nFor this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate. \n \nUse the values:\n::* 4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)\n::* 2 milkshakes at $2.86 each, and \n::* a tax rate of 7.65%. \n\n\n(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naive task solutions using 64 bit floating point types.) \n\nCompute and output (show results on this page):\n::* the total price before tax\n::* the tax\n::* the total with tax \n\n\nThe tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax. \n\nThe output must show dollars and cents with a decimal point. \n \nThe three results displayed should be:\n::* 22000000000000005.72\n::* 1683000000000000.44 \n::* 23683000000000006.16 \n\n\nDollar signs and thousands separators are optional.\n\n", "solution": "mpf_set_d(burgerUnitPrice,5.50);\n\tmpf_set_d(milkshakePrice,2 * 2.86);\n\tmpf_set_d(burgerNum,4000000000000000);\n\tmpf_set_d(milkshakeNum,2);\n"} {"title": "Currying", "language": "C", "task": "{{Wikipedia|Currying}}\n\n\n;Task:\nCreate a simple demonstrative example of Currying in a specific language. \n\nAdd any historic details as to how the feature made its way into the language.\n\n\n\n", "solution": "#include\n#include\n\nlong int factorial(int n){\n\tif(n>1)\n\t\treturn n*factorial(n-1);\n\treturn 1;\n}\n\nlong int sumOfFactorials(int num,...){\n\tva_list vaList;\n\tlong int sum = 0;\n\t\n\tva_start(vaList,num);\n\t\n\twhile(num--)\n\t\tsum += factorial(va_arg(vaList,int));\n\t\n\tva_end(vaList);\n\t\n\treturn sum;\n}\n\nint main()\n{\n\tprintf(\"\\nSum of factorials of [1,5] : %ld\",sumOfFactorials(5,1,2,3,4,5));\n\tprintf(\"\\nSum of factorials of [3,5] : %ld\",sumOfFactorials(3,3,4,5));\n\tprintf(\"\\nSum of factorials of [1,3] : %ld\",sumOfFactorials(3,1,2,3));\n\t\n\treturn 0;\n}\n"} {"title": "Cut a rectangle", "language": "C", "task": "A given rectangle is made from ''m'' x ''n'' squares. If ''m'' and ''n'' are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180deg). All such paths for 2 x 2 and 4 x 3 rectangles are shown below.\n\n[[file:rect-cut.svg]]\n\nWrite a program that calculates the number of different ways to cut an ''m'' x ''n'' rectangle. Optionally, show each of the cuts.\n\nPossibly related task: [[Maze generation]] for depth-first search.\n\n", "solution": "#include \n#include \n\ntypedef unsigned char byte;\nint w = 0, h = 0, verbose = 0;\nunsigned long count = 0;\n\nbyte **hor, **ver, **vis;\nbyte **c = 0;\n\nenum { U = 1, D = 2, L = 4, R = 8 };\n\nbyte ** alloc2(int w, int h)\n{\n\tint i;\n\tbyte **x = calloc(1, sizeof(byte*) * h + h * w);\n\tx[0] = (byte *)&x[h];\n\tfor (i = 1; i < h; i++)\n\t\tx[i] = x[i - 1] + w;\n\treturn x;\n}\n\nvoid show()\n{\n\tint i, j, v, last_v;\n\tprintf(\"%ld\\n\", count);\n#if 0\n\tfor (i = 0; i <= h; i++) {\n\t\tfor (j = 0; j <= w; j++)\n\t\t\tprintf(\"%d \", hor[i][j]);\n\t\tputs(\"\");\n\t}\n\tputs(\"\");\n\n\tfor (i = 0; i <= h; i++) {\n\t\tfor (j = 0; j <= w; j++)\n\t\t\tprintf(\"%d \", ver[i][j]);\n\t\tputs(\"\");\n\t}\n\tputs(\"\");\n#endif\n\tfor (i = 0; i < h; i++) {\n\t\tif (!i) v = last_v = 0;\n\t\telse last_v = v = hor[i][0] ? !last_v : last_v;\n\n\t\tfor (j = 0; j < w; v = ver[i][++j] ? !v : v)\n\t\t\tprintf(v ? \"\\033[31m[]\" : \"\\033[33m{}\");\n\t\tputs(\"\\033[m\");\n\t}\n\tputchar('\\n');\n}\n\nvoid walk(int y, int x)\n{\n\tif (x < 0 || y < 0 || x > w || y > h) return;\n\n\tif (!x || !y || x == w || y == h) {\n\t\t++count;\n\t\tif (verbose) show();\n\t\treturn;\n\t}\n\n\tif (vis[y][x]) return;\n\tvis[y][x]++; vis[h - y][w - x]++;\n\n\tif (x && !hor[y][x - 1]) {\n\t\thor[y][x - 1] = hor[h - y][w - x] = 1;\n\t\twalk(y, x - 1);\n\t\thor[y][x - 1] = hor[h - y][w - x] = 0;\n\t}\n\tif (x < w && !hor[y][x]) {\n\t\thor[y][x] = hor[h - y][w - x - 1] = 1;\n\t\twalk(y, x + 1);\n\t\thor[y][x] = hor[h - y][w - x - 1] = 0;\n\t}\n\n\tif (y && !ver[y - 1][x]) {\n\t\tver[y - 1][x] = ver[h - y][w - x] = 1;\n\t\twalk(y - 1, x);\n\t\tver[y - 1][x] = ver[h - y][w - x] = 0;\n\t}\n\n\tif (y < h && !ver[y][x]) {\n\t\tver[y][x] = ver[h - y - 1][w - x] = 1;\n\t\twalk(y + 1, x);\n\t\tver[y][x] = ver[h - y - 1][w - x] = 0;\n\t}\n\n\tvis[y][x]--; vis[h - y][w - x]--;\n}\n\nvoid cut(void)\n{\n\tif (1 & (h * w)) return;\n\n\thor = alloc2(w + 1, h + 1);\n\tver = alloc2(w + 1, h + 1);\n\tvis = alloc2(w + 1, h + 1);\n\n\tif (h & 1) {\n\t\tver[h/2][w/2] = 1;\n\t\twalk(h / 2, w / 2);\n\t} else if (w & 1) {\n\t\thor[h/2][w/2] = 1;\n\t\twalk(h / 2, w / 2);\n\t} else {\n\t\tvis[h/2][w/2] = 1;\n\n\t\thor[h/2][w/2-1] = hor[h/2][w/2] = 1;\n\t\twalk(h / 2, w / 2 - 1);\n\t\thor[h/2][w/2-1] = hor[h/2][w/2] = 0;\n\n\t\tver[h/2 - 1][w/2] = ver[h/2][w/2] = 1;\n\t\twalk(h / 2 - 1, w/2);\n\t}\n}\n\nvoid cwalk(int y, int x, int d)\n{\n\tif (!y || y == h || !x || x == w) {\n\t\t++count;\n\t\treturn;\n\t}\n\tvis[y][x] = vis[h-y][w-x] = 1;\n\n\tif (x && !vis[y][x-1])\n\t\tcwalk(y, x - 1, d|1);\n\tif ((d&1) && x < w && !vis[y][x+1])\n\t\tcwalk(y, x + 1, d|1);\n\tif (y && !vis[y-1][x])\n\t\tcwalk(y - 1, x, d|2);\n\tif ((d&2) && y < h && !vis[y + 1][x])\n\t\tcwalk(y + 1, x, d|2);\n\n\tvis[y][x] = vis[h-y][w-x] = 0;\n}\n\nvoid count_only(void)\n{\n\tint t;\n\tlong res;\n\tif (h * w & 1) return;\n\tif (h & 1) t = h, h = w, w = t;\n\n\tvis = alloc2(w + 1, h + 1);\n\tvis[h/2][w/2] = 1;\n\n\tif (w & 1) vis[h/2][w/2 + 1] = 1;\n\tif (w > 1) {\n\t\tcwalk(h/2, w/2 - 1, 1);\n\t\tres = 2 * count - 1;\n\t\tcount = 0;\n\t\tif (w != h)\n\t\t\tcwalk(h/2+1, w/2, (w & 1) ? 3 : 2);\n\n\t\tres += 2 * count - !(w & 1);\n\t} else {\n\t\tres = 1;\n\t}\n\tif (w == h) res = 2 * res + 2;\n\tcount = res;\n}\n\nint main(int c, char **v)\n{\n\tint i;\n\n\tfor (i = 1; i < c; i++) {\n\t\tif (v[i][0] == '-' && v[i][1] == 'v' && !v[i][2]) {\n\t\t\tverbose = 1;\n\t\t} else if (!w) {\n\t\t\tw = atoi(v[i]);\n\t\t\tif (w <= 0) goto bail;\n\t\t} else if (!h) {\n\t\t\th = atoi(v[i]);\n\t\t\tif (h <= 0) goto bail;\n\t\t} else\n\t\t\tgoto bail;\n\t}\n\tif (!w) goto bail;\n\tif (!h) h = w;\n\n\tif (verbose) cut();\n\telse count_only();\n\n\tprintf(\"Total: %ld\\n\", count);\n\treturn 0;\n\nbail:\tfprintf(stderr, \"bad args\\n\");\n\treturn 1;\n}"} {"title": "Damm algorithm", "language": "C", "task": "The '''Damm''' algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. \n\n\nThe algorithm is named after H. Michael Damm.\n\n\n;Task:\nVerify the checksum, stored as last digit of an input.\n\n\n\n", "solution": "#include \n#include \n#include \n\nbool damm(unsigned char *input, size_t length) {\n static const unsigned char table[10][10] = {\n {0, 3, 1, 7, 5, 9, 8, 6, 4, 2},\n {7, 0, 9, 2, 1, 5, 4, 8, 6, 3},\n {4, 2, 0, 6, 8, 7, 1, 3, 5, 9},\n {1, 7, 5, 0, 9, 8, 3, 4, 2, 6},\n {6, 1, 2, 3, 0, 4, 5, 9, 7, 8},\n {3, 6, 7, 4, 2, 0, 9, 5, 8, 1},\n {5, 8, 6, 9, 7, 2, 0, 1, 3, 4},\n {8, 9, 4, 5, 3, 6, 2, 0, 1, 7},\n {9, 4, 3, 8, 6, 1, 7, 2, 0, 5},\n {2, 5, 8, 1, 4, 3, 6, 7, 9, 0},\n };\n \n unsigned char interim = 0;\n for (size_t i = 0; i < length; i++) {\n interim = table[interim][input[i]];\n }\n return interim == 0;\n}\n\nint main() {\n unsigned char input[4] = {5, 7, 2, 4};\n puts(damm(input, 4) ? \"Checksum correct\" : \"Checksum incorrect\");\n return 0;\n}"} {"title": "Deceptive numbers", "language": "C", "task": "Repunits are numbers that consist entirely of repetitions of the digit one (unity). The notation '''Rn''' symbolizes the repunit made up of '''n''' ones.\n\nEvery prime '''p''' larger than 5, evenly divides the repunit '''Rp-1'''.\n\n\n;E.G.\n\nThe repunit '''R6''' is evenly divisible by '''7'''.\n\n111111 / 7 = 15873\n\nThe repunit '''R42''' is evenly divisible by '''43'''.\n\n111111111111111111111111111111111111111111 / 43 = 2583979328165374677002583979328165374677\n\nAnd so on.\n\n\nThere are composite numbers that also have this same property. They are often referred to as ''deceptive non-primes'' or ''deceptive numbers''.\n\n\nThe repunit '''R90''' is evenly divisible by the composite number '''91''' (=7*13).\n\n111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 / 91 = 1221001221001221001221001221001221001221001221001221001221001221001221001221001221001221\n\n\n;Task \n\n* Find and show at least the first '''10 deceptive numbers'''; composite numbers '''n''' that evenly divide the repunit '''Rn-1'''\n\n\n;See also\n\n;* Numbers Aplenty - Deceptive numbers\n;* OEIS:A000864 - Deceptive nonprimes: composite numbers k that divide the repunit R_{k-1}\n\n", "solution": "#include \n\nunsigned modpow(unsigned b, unsigned e, unsigned m)\n{\n unsigned p;\n for (p = 1; e; e >>= 1) {\n if (e & 1)\n p = p * b % m;\n b = b * b % m;\n }\n return p;\n}\n\nint is_deceptive(unsigned n)\n{\n unsigned x;\n if (n & 1 && n % 3 && n % 5) {\n for (x = 7; x * x <= n; x += 6) {\n if (!(n % x && n % (x + 4)))\n return modpow(10, n - 1, n) == 1;\n }\n }\n return 0;\n}\n\nint main(void)\n{\n unsigned c, i = 49;\n for (c = 0; c != 50; ++i) {\n if (is_deceptive(i)) {\n printf(\" %u\", i);\n ++c;\n }\n }\n return 0;\n}"} {"title": "Deepcopy", "language": "C", "task": "Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. \n\nThis is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects.\n\nIf this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure.\n\n\nThe task should show:\n\n* Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles.\n\n* Any limitations of the method.\n\n* That the structure and its copy are different.\n\n* Suitable links to external documentation for common libraries.\n\n", "solution": "#include\n#include\n\ntypedef struct elem{\n\tint data;\n\tstruct elem* next;\n}cell;\n\ntypedef cell* list;\n\nvoid addToList(list *a,int num){\n\tlist temp, holder;\n\t\n\tif(*a==NULL){\n\t\t*a = (list)malloc(sizeof(cell));\n\t\t(*a)->data = num;\n\t\t(*a)->next = NULL;\n\t}\n\telse{\n\t\ttemp = *a;\n\t\t\n\t\twhile(temp->next!=NULL)\n\t\t\ttemp = temp->next;\n\t\t\n\t\tholder = (list)malloc(sizeof(cell));\n\t\tholder->data = num;\n\t\tholder->next = NULL;\n\t\t\n\t\ttemp->next = holder;\n\t}\n}\n\nlist copyList(list a){\n\tlist b, tempA, tempB, temp;\n\t\n\tif(a!=NULL){\n\t\tb = (list)malloc(sizeof(cell));\n\t\tb->data = a->data;\n\t\tb->next = NULL;\n\t\t\n\t\ttempA = a->next;\n\t\ttempB = b;\n\t\t\n\t\twhile(tempA!=NULL){\n\t\t\ttemp = (list)malloc(sizeof(cell));\n\t\t\ttemp->data = tempA->data;\n\t\t\ttemp->next = NULL;\n\t\t\n\t\t\ttempB->next = temp;\n\t\t\ttempB = temp;\n\t\t\n\t\t\ttempA = tempA->next;\n\t\t}\n\t}\n\t\n\treturn b;\n}\n\nvoid printList(list a){\n\tlist temp = a;\n\t\n\twhile(temp!=NULL){\n\t\tprintf(\"%d,\",temp->data);\n\t\ttemp = temp->next;\n\t}\n\tprintf(\"\\b\");\n}\n\nint main()\n{\n\tlist a,b;\n\tint i;\n\t\n\tfor(i=1;i<=5;i++)\n\t\taddToList(&a,i);\n\t\n\tprintf(\"List a is : \");\n\t\n\tprintList(a);\n\t\n\tb = copyList(a);\n\t\n\tfree(a);\n\t\n\tprintf(\"\\nList a destroyed, List b is : \");\n\t\n\tprintList(b);\n\t\n\treturn 0;\n}\n"} {"title": "Department numbers", "language": "C", "task": "There is a highly organized city that has decided to assign a number to each of their departments:\n::* police department\n::* sanitation department\n::* fire department \n\n\nEach department can have a number between '''1''' and '''7''' (inclusive).\n\nThe three department numbers are to be unique (different from each other) and must add up to '''12'''.\n\nThe Chief of the Police doesn't like odd numbers and wants to have an even number for his department.\n\n\n;Task:\nWrite a computer program which outputs all valid combinations.\n\n\nPossible output (for the 1st and 14th solutions):\n \n --police-- --sanitation-- --fire-- \n 2 3 7 \n 6 5 1\n\n", "solution": "#include\n\nint main()\n{\n\tint police,sanitation,fire;\n\t\n\tprintf(\"Police Sanitation Fire\\n\");\n\tprintf(\"----------------------------------\");\n\t\n\tfor(police=2;police<=6;police+=2){\n\t\tfor(sanitation=1;sanitation<=7;sanitation++){\n\t\t\tfor(fire=1;fire<=7;fire++){\n\t\t\t\tif(police!=sanitation && sanitation!=fire && fire!=police && police+fire+sanitation==12){\n\t\t\t\t\tprintf(\"\\n%d\\t\\t%d\\t\\t%d\",police,sanitation,fire);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n"} {"title": "Detect division by zero", "language": "C", "task": "Write a function to detect a ''divide by zero error'' without checking if the denominator is zero.\n\n", "solution": "#include \t/* INT_MIN */\n#include \t/* siglongjmp(), sigsetjmp() */\n#include \t/* perror(), printf() */\n#include \t/* exit() */\n#include \t/* sigaction(), sigemptyset() */\n\nstatic sigjmp_buf fpe_env;\n\n/*\n * This SIGFPE handler jumps to fpe_env.\n *\n * A SIGFPE handler must not return, because the program might retry\n * the division, which might cause an infinite loop. The only safe\n * options are to _exit() the program or to siglongjmp() out.\n */\nstatic void\nfpe_handler(int signal, siginfo_t *w, void *a)\n{\n\tsiglongjmp(fpe_env, w->si_code);\n\t/* NOTREACHED */\n}\n\n/*\n * Try to do x / y, but catch attempts to divide by zero.\n */\nvoid\ntry_division(int x, int y)\n{\n\tstruct sigaction act, old;\n\tint code;\n\t/*\n\t * The result must be volatile, else C compiler might delay\n\t * division until after sigaction() restores old handler.\n\t */\n\tvolatile int result;\n\n\t/*\n\t * Save fpe_env so that fpe_handler() can jump back here.\n\t * sigsetjmp() returns zero.\n\t */\n\tcode = sigsetjmp(fpe_env, 1);\n\tif (code == 0) {\n\t\t/* Install fpe_handler() to trap SIGFPE. */\n\t\tact.sa_sigaction = fpe_handler;\n\t\tsigemptyset(&act.sa_mask);\n\t\tact.sa_flags = SA_SIGINFO;\n\t\tif (sigaction(SIGFPE, &act, &old) < 0) {\n\t\t\tperror(\"sigaction\");\n\t\t\texit(1);\n\t\t}\n\n\t\t/* Do division. */\n\t\tresult = x / y;\n\n\t\t/*\n\t\t * Restore old hander, so that SIGFPE cannot jump out\n\t\t * of a call to printf(), which might cause trouble.\n\t\t */\n\t\tif (sigaction(SIGFPE, &old, NULL) < 0) {\n\t\t\tperror(\"sigaction\");\n\t\t\texit(1);\n\t\t}\n\n\t\tprintf(\"%d / %d is %d\\n\", x, y, result);\n\t} else {\n\t\t/*\n\t\t * We caught SIGFPE. Our fpe_handler() jumped to our\n\t\t * sigsetjmp() and passes a nonzero code.\n\t\t *\n\t\t * But first, restore old handler.\n\t\t */\n\t\tif (sigaction(SIGFPE, &old, NULL) < 0) {\n\t\t\tperror(\"sigaction\");\n\t\t\texit(1);\n\t\t}\n\n\t\t/* FPE_FLTDIV should never happen with integers. */\n\t\tswitch (code) {\n\t\tcase FPE_INTDIV: /* integer division by zero */\n\t\tcase FPE_FLTDIV: /* float division by zero */\n\t\t\tprintf(\"%d / %d: caught division by zero!\\n\", x, y);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tprintf(\"%d / %d: caught mysterious error!\\n\", x, y);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n/* Try some division. */\nint\nmain()\n{\n\ttry_division(-44, 0);\n\ttry_division(-44, 5);\n\ttry_division(0, 5);\n\ttry_division(0, 0);\n\ttry_division(INT_MIN, -1);\n\treturn 0;\n}"} {"title": "Determinant and permanent", "language": "C", "task": "permanent of the matrix.\n\nThe determinant is given by\n:: \\det(A) = \\sum_\\sigma\\sgn(\\sigma)\\prod_{i=1}^n M_{i,\\sigma_i}\nwhile the permanent is given by\n:: \\operatorname{perm}(A)=\\sum_\\sigma\\prod_{i=1}^n M_{i,\\sigma_i}\nIn both cases the sum is over the permutations \\sigma of the permutations of 1, 2, ..., ''n''. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)\n\nMore efficient algorithms for the determinant are known: [[LU decomposition]], see for example [[wp:LU decomposition#Computing the determinant]]. Efficient methods for calculating the permanent are not known.\n\n\n;Related task:\n* [[Permutations by swapping]]\n\n", "solution": "#include \n#include \n#include \n\nvoid showmat(const char *s, double **m, int n)\n{\n\tprintf(\"%s:\\n\", s);\n\tfor (int i = 0; i < n; i++) {\n\t\tfor (int j = 0; j < n; j++)\n\t\t\tprintf(\"%12.4f\", m[i][j]);\n\t\t\tputchar('\\n');\n\t}\n}\n\nint trianglize(double **m, int n)\n{\n\tint sign = 1;\n\tfor (int i = 0; i < n; i++) {\n\t\tint max = 0;\n\n\t\tfor (int row = i; row < n; row++)\n\t\t\tif (fabs(m[row][i]) > fabs(m[max][i]))\n\t\t\t\tmax = row;\n\n\t\tif (max) {\n\t\t\tsign = -sign;\n\t\t\tdouble *tmp = m[i];\n\t\t\tm[i] = m[max], m[max] = tmp;\n\t\t}\n\n\t\tif (!m[i][i]) return 0;\n\n\t\tfor (int row = i + 1; row < n; row++) {\n\t\t\tdouble r = m[row][i] / m[i][i];\n\t\t\tif (!r)\tcontinue;\n\n\t\t\tfor (int col = i; col < n; col ++)\n\t\t\t\tm[row][col] -= m[i][col] * r;\n\t\t}\n\t}\n\treturn sign;\n}\n\ndouble det(double *in, int n)\n{\n\tdouble *m[n];\n\tm[0] = in;\n\n\tfor (int i = 1; i < n; i++)\n\t\tm[i] = m[i - 1] + n;\n\n\tshowmat(\"Matrix\", m, n);\n\n\tint sign = trianglize(m, n);\n\tif (!sign)\n\t\treturn 0;\n\n\tshowmat(\"Upper triangle\", m, n);\n\n\tdouble p = 1;\n\tfor (int i = 0; i < n; i++)\n\t\tp *= m[i][i];\n\treturn p * sign;\n}\n\n#define N 18\nint main(void)\n{\n\tdouble x[N * N];\n\tsrand(0);\n\tfor (int i = 0; i < N * N; i++)\n\t\tx[i] = rand() % N;\n\n\tprintf(\"det: %19f\\n\", det(x, N));\n\treturn 0;\n}"} {"title": "Determine if a string has all the same characters", "language": "C", "task": "Given a character string (which may be empty, or have a length of zero characters):\n::* create a function/procedure/routine to:\n::::* determine if all the characters in the string are the same\n::::* indicate if or which character is different from the previous character\n::* display each string and its length (as the strings are being examined)\n::* a zero-length (empty) string shall be considered as all the same character(s)\n::* process the strings from left-to-right\n::* if all the same character, display a message saying such\n::* if not all the same character, then:\n::::* display a message saying such\n::::* display what character is different\n::::* only the 1st different character need be displayed\n::::* display where the different character is in the string\n::::* the above messages can be part of a single message\n::::* display the hexadecimal value of the different character\n\n\nUse (at least) these seven test values (strings):\n:::* a string of length 0 (an empty string)\n:::* a string of length 3 which contains three blanks\n:::* a string of length 1 which contains: '''2'''\n:::* a string of length 3 which contains: '''333'''\n:::* a string of length 3 which contains: '''.55'''\n:::* a string of length 6 which contains: '''tttTTT'''\n:::* a string of length 9 with a blank in the middle: '''4444 444k'''\n\n\n\nShow all output here on this page.\n\n\n", "solution": "/**\n * An example for RossetaCode - an example of string operation with wchar_t and\n * with old 8-bit characters. Anyway, it seem that C is not very UTF-8 friendly,\n * thus C# or C++ may be a better choice.\n */\n\n#include \n#include \n#include \n\n/*\n * The wide character version of the program is compiled if WIDE_CHAR is defined\n */\n#define WIDE_CHAR\n\n#ifdef WIDE_CHAR\n#define CHAR wchar_t\n#else\n#define CHAR char\n#endif\n\n/**\n * Find a character different from the preceding characters in the given string.\n * \n * @param s the given string, NULL terminated.\n * \n * @return the pointer to the occurence of the different character \n * or a pointer to NULL if all characters in the string\n * are exactly the same.\n * \n * @notice This function return a pointer to NULL also for empty strings.\n * Returning NULL-or-CHAR would not enable to compute the position\n * of the non-matching character.\n * \n * @warning This function compare characters (single-bytes, unicode etc.).\n * Therefore this is not designed to compare bytes. The NULL character\n * is always treated as the end-of-string marker, thus this function\n * cannot be used to scan strings with NULL character inside string,\n * for an example \"aaa\\0aaa\\0\\0\".\n */\nconst CHAR* find_different_char(const CHAR* s)\n{\n /* The code just below is almost the same regardles \n char or wchar_t is used. */\n\n const CHAR c = *s;\n while (*s && c == *s)\n {\n s++;\n }\n return s;\n}\n\n/**\n * Apply find_different_char function to a given string and output the raport.\n * \n * @param s the given NULL terminated string.\n */\nvoid report_different_char(const CHAR* s)\n{\n#ifdef WIDE_CHAR\n wprintf(L\"\\n\");\n wprintf(L\"string: \\\"%s\\\"\\n\", s);\n wprintf(L\"length: %d\\n\", wcslen(s));\n const CHAR* d = find_different_char(s);\n if (d)\n {\n /*\n * We have got the famous pointers arithmetics and we can compute\n * difference of pointers pointing to the same array.\n */\n wprintf(L\"character '%wc' (%#x) at %d\\n\", *d, *d, (int)(d - s));\n }\n else\n {\n wprintf(L\"all characters are the same\\n\");\n }\n wprintf(L\"\\n\");\n#else\n putchar('\\n');\n printf(\"string: \\\"%s\\\"\\n\", s);\n printf(\"length: %d\\n\", strlen(s));\n const CHAR* d = find_different_char(s);\n if (d)\n { \n /*\n * We have got the famous pointers arithmetics and we can compute\n * difference of pointers pointing to the same array.\n */\n printf(\"character '%c' (%#x) at %d\\n\", *d, *d, (int)(d - s));\n }\n else\n {\n printf(\"all characters are the same\\n\");\n }\n putchar('\\n');\n#endif\n}\n\n/* There is a wmain function as an entry point when argv[] points to wchar_t */\n\n#ifdef WIDE_CHAR\nint wmain(int argc, wchar_t* argv[])\n#else\nint main(int argc, char* argv[])\n#endif\n{\n if (argc < 2)\n {\n report_different_char(L\"\");\n report_different_char(L\" \");\n report_different_char(L\"2\");\n report_different_char(L\"333\");\n report_different_char(L\".55\");\n report_different_char(L\"tttTTT\");\n report_different_char(L\"4444 444k\");\n }\n else\n {\n report_different_char(argv[1]);\n }\n\n return EXIT_SUCCESS;\n}"} {"title": "Determine if a string has all unique characters", "language": "C", "task": "Given a character string (which may be empty, or have a length of zero characters):\n::* create a function/procedure/routine to:\n::::* determine if all the characters in the string are unique\n::::* indicate if or which character is duplicated and where\n::* display each string and its length (as the strings are being examined)\n::* a zero-length (empty) string shall be considered as unique\n::* process the strings from left-to-right\n::* if unique, display a message saying such\n::* if not unique, then:\n::::* display a message saying such\n::::* display what character is duplicated\n::::* only the 1st non-unique character need be displayed\n::::* display where \"both\" duplicated characters are in the string\n::::* the above messages can be part of a single message\n::::* display the hexadecimal value of the duplicated character\n\n\n\nUse (at least) these five test values (strings):\n:::* a string of length 0 (an empty string)\n:::* a string of length 1 which is a single period ('''.''')\n:::* a string of length 6 which contains: '''abcABC'''\n:::* a string of length 7 which contains a blank in the middle: '''XYZ ZYX'''\n:::* a string of length 36 which ''doesn't'' contain the letter \"oh\":\n:::::::: '''1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ'''\n\n\n\nShow all output here on this page.\n\n\n", "solution": "#include\n#include\n#include\n#include\n\ntypedef struct positionList{\n int position;\n struct positionList *next;\n}positionList;\n\ntypedef struct letterList{\n char letter;\n int repititions;\n positionList* positions;\n struct letterList *next;\n}letterList;\n\nletterList* letterSet;\nbool duplicatesFound = false;\n\nvoid checkAndUpdateLetterList(char c,int pos){\n bool letterOccurs = false;\n letterList *letterIterator,*newLetter;\n positionList *positionIterator,*newPosition;\n\n if(letterSet==NULL){\n letterSet = (letterList*)malloc(sizeof(letterList));\n letterSet->letter = c;\n letterSet->repititions = 0;\n\n letterSet->positions = (positionList*)malloc(sizeof(positionList));\n letterSet->positions->position = pos;\n letterSet->positions->next = NULL;\n\n letterSet->next = NULL;\n }\n\n else{\n letterIterator = letterSet;\n\n while(letterIterator!=NULL){\n if(letterIterator->letter==c){\n letterOccurs = true;\n duplicatesFound = true;\n\n letterIterator->repititions++;\n positionIterator = letterIterator->positions;\n\n while(positionIterator->next!=NULL)\n positionIterator = positionIterator->next;\n \n newPosition = (positionList*)malloc(sizeof(positionList));\n newPosition->position = pos;\n newPosition->next = NULL;\n\n positionIterator->next = newPosition;\n }\n if(letterOccurs==false && letterIterator->next==NULL)\n break;\n else\n letterIterator = letterIterator->next;\n }\n\n if(letterOccurs==false){\n newLetter = (letterList*)malloc(sizeof(letterList));\n newLetter->letter = c;\n\n newLetter->repititions = 0;\n\n newLetter->positions = (positionList*)malloc(sizeof(positionList));\n newLetter->positions->position = pos;\n newLetter->positions->next = NULL;\n\n newLetter->next = NULL;\n\n letterIterator->next = newLetter;\n } \n }\n}\n\nvoid printLetterList(){\n positionList* positionIterator;\n letterList* letterIterator = letterSet;\n\n while(letterIterator!=NULL){\n if(letterIterator->repititions>0){\n printf(\"\\n'%c' (0x%x) at positions :\",letterIterator->letter,letterIterator->letter);\n\n positionIterator = letterIterator->positions;\n\n while(positionIterator!=NULL){\n printf(\"%3d\",positionIterator->position + 1);\n positionIterator = positionIterator->next;\n }\n }\n\n letterIterator = letterIterator->next;\n }\n printf(\"\\n\");\n}\n\nint main(int argc,char** argv)\n{\n int i,len;\n \n if(argc>2){\n printf(\"Usage : %s \\n\",argv[0]);\n return 0;\n }\n\n if(argc==1||strlen(argv[1])==1){\n printf(\"\\\"%s\\\" - Length %d - Contains only unique characters.\\n\",argc==1?\"\":argv[1],argc==1?0:1);\n return 0;\n }\n\n len = strlen(argv[1]);\n\n for(i=0;i>>''' (to delineate blanks)\n;* <<<<<>>>>>\n\n\n\n\nUse (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except\nthe 1st string:\n\n string\n number\n ++\n 1 |+-----------------------------------------------------------------------+ <###### a null string (length zero)\n 2 |\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln |\n 3 |..1111111111111111111111111111111111111111111111111111111111111117777888|\n 4 |I never give 'em hell, I just tell the truth, and they think it's hell. |\n 5 | --- Harry S Truman | <###### has many repeated blanks\n +------------------------------------------------------------------------+\n\n\n", "solution": "#include\n#include\n#include\n\n#define COLLAPSE 0\n#define SQUEEZE 1\n\ntypedef struct charList{\n char c;\n struct charList *next;\n} charList;\n\n/*\nImplementing strcmpi, the case insensitive string comparator, as it is not part of the C Standard Library.\n\nComment this out if testing on a compiler where it is already defined.\n*/\n\nint strcmpi(char* str1,char* str2){\n int len1 = strlen(str1), len2 = strlen(str2), i;\n\n if(len1!=len2){\n return 1;\n }\n\n else{\n for(i=0;i='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i]))\n return 1;\n else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i]))\n return 1;\n else if(str1[i]!=str2[i])\n return 1;\n }\n }\n\n return 0;\n}\n\ncharList *strToCharList(char* str){\n int len = strlen(str),i;\n\n charList *list, *iterator, *nextChar;\n\n list = (charList*)malloc(sizeof(charList));\n list->c = str[0];\n list->next = NULL;\n\n iterator = list;\n\n for(i=1;ic = str[i];\n nextChar->next = NULL;\n\n iterator->next = nextChar;\n iterator = nextChar;\n }\n\n return list;\n}\n\nchar* charListToString(charList* list){\n charList* iterator = list;\n int count = 0,i;\n char* str;\n\n while(iterator!=NULL){\n count++;\n iterator = iterator->next;\n }\n\n str = (char*)malloc((count+1)*sizeof(char));\n iterator = list;\n\n for(i=0;ic;\n iterator = iterator->next;\n }\n\n free(list);\n str[i] = '\\0';\n\n return str;\n}\n\nchar* processString(char str[100],int operation, char squeezeChar){\n charList *strList = strToCharList(str),*iterator = strList, *scout;\n\n if(operation==SQUEEZE){\n while(iterator!=NULL){\n if(iterator->c==squeezeChar){\n scout = iterator->next;\n\n while(scout!=NULL && scout->c==squeezeChar){\n iterator->next = scout->next;\n scout->next = NULL;\n free(scout);\n scout = iterator->next;\n }\n }\n iterator = iterator->next;\n }\n }\n\n else{\n while(iterator!=NULL && iterator->next!=NULL){\n if(iterator->c == (iterator->next)->c){\n scout = iterator->next;\n squeezeChar = iterator->c;\n\n while(scout!=NULL && scout->c==squeezeChar){\n iterator->next = scout->next;\n scout->next = NULL;\n free(scout);\n scout = iterator->next;\n }\n }\n iterator = iterator->next;\n }\n }\n\n return charListToString(strList);\n}\n\nvoid printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){\n if(operation==SQUEEZE){\n printf(\"Specified Operation : SQUEEZE\\nTarget Character : %c\",squeezeChar);\n }\n\n else\n printf(\"Specified Operation : COLLAPSE\");\n\n printf(\"\\nOriginal %c%c%c%s%c%c%c\\nLength : %d\",174,174,174,originalString,175,175,175,(int)strlen(originalString));\n printf(\"\\nFinal %c%c%c%s%c%c%c\\nLength : %d\\n\",174,174,174,finalString,175,175,175,(int)strlen(finalString));\n}\n\nint main(int argc, char** argv){\n int operation;\n char squeezeChar;\n\n if(argc<3||argc>4){\n printf(\"Usage : %s \\n\",argv[0]);\n return 0;\n }\n\n if(strcmpi(argv[1],\"SQUEEZE\")==0 && argc!=4){\n scanf(\"Please enter characted to be squeezed : %c\",&squeezeChar);\n operation = SQUEEZE;\n }\n\n else if(argc==4){\n operation = SQUEEZE;\n squeezeChar = argv[3][0];\n }\n\n else if(strcmpi(argv[1],\"COLLAPSE\")==0){\n operation = COLLAPSE;\n }\n\n if(strlen(argv[2])<2){\n printResults(argv[2],argv[2],operation,squeezeChar);\n }\n\n else{\n printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar);\n }\n \n return 0;\n}\n"} {"title": "Determine if a string is squeezable", "language": "C", "task": "Determine if a character string is ''squeezable''.\n\nAnd if so, squeeze the string (by removing any number of\na ''specified'' ''immediately repeated'' character).\n\n\nThis task is very similar to the task '''Determine if a character string is collapsible''' except\nthat only a specified character is ''squeezed'' instead of any character that is ''immediately repeated''.\n\n\nIf a character string has a specified ''immediately repeated'' character(s), the repeated characters are to be\ndeleted (removed), but not the primary (1st) character(s).\n\n\nA specified ''immediately repeated'' character is any specified character that is immediately \nfollowed by an identical character (or characters). Another word choice could've been ''duplicated\ncharacter'', but that might have ruled out (to some readers) triplicated characters *** or more.\n\n\n{This Rosetta Code task was inspired by a newly introduced (as of around\nNovember 2019) '''PL/I''' BIF: '''squeeze'''.}\n\n\n;Examples:\nIn the following character string with a specified ''immediately repeated'' character of '''e''':\n\n\n The better the 4-wheel drive, the further you'll be from help when ya get stuck! \n\n\nOnly the 2nd '''e''' is an specified repeated character, indicated by an underscore\n(above), even though they (the characters) appear elsewhere in the character string.\n\n\n\nSo, after ''squeezing'' the string, the result would be:\n\n The better the 4-whel drive, the further you'll be from help when ya get stuck! \n\n\n\n\nAnother example:\nIn the following character string, using a specified immediately repeated character '''s''':\n\n headmistressship \n\n\nThe \"squeezed\" string would be:\n\n headmistreship \n\n\n\n;Task:\nWrite a subroutine/function/procedure/routine*** to locate a ''specified immediately repeated'' character\nand ''squeeze'' (delete) them from the character string. The\ncharacter string can be processed from either direction.\n\n\nShow all output here, on this page:\n:* the specified repeated character (to be searched for and possibly ''squeezed''):\n:* the original string and its length\n:* the resultant string and its length\n:* the above strings should be \"bracketed\" with '''<<<''' and '''>>>''' (to delineate blanks)\n;* <<<<<>>>>>\n\n\n\nUse (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except\nthe 1st string:\n\n immediately\n string repeated\n number character\n ( | a blank, a minus, a seven, a period)\n ++\n 1 |+-----------------------------------------------------------------------+ ' ' <###### a null string (length zero)\n 2 |\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln | '-'\n 3 |..1111111111111111111111111111111111111111111111111111111111111117777888| '7'\n 4 |I never give 'em hell, I just tell the truth, and they think it's hell. | '.'\n 5 | --- Harry S Truman | (below) <###### has many repeated blanks\n +------------------------------------------------------------------------+ |\n |\n |\n For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:\n * a blank\n * a minus\n * a lowercase '''r'''\n\n\nNote: there should be seven results shown, one each for the 1st four strings, and three results for\nthe 5th string.\n\n\n", "solution": "#include\n#include\n#include\n\n#define COLLAPSE 0\n#define SQUEEZE 1\n\ntypedef struct charList{\n char c;\n struct charList *next;\n} charList;\n\n/*\nImplementing strcmpi, the case insensitive string comparator, as it is not part of the C Standard Library.\n\nComment this out if testing on a compiler where it is already defined.\n*/\n\nint strcmpi(char str1[100],char str2[100]){\n int len1 = strlen(str1), len2 = strlen(str2), i;\n\n if(len1!=len2){\n return 1;\n }\n\n else{\n for(i=0;i='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i]))\n return 1;\n else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i]))\n return 1;\n else if(str1[i]!=str2[i])\n return 1;\n }\n }\n\n return 0;\n}\n\ncharList *strToCharList(char* str){\n int len = strlen(str),i;\n\n charList *list, *iterator, *nextChar;\n\n list = (charList*)malloc(sizeof(charList));\n list->c = str[0];\n list->next = NULL;\n\n iterator = list;\n\n for(i=1;ic = str[i];\n nextChar->next = NULL;\n\n iterator->next = nextChar;\n iterator = nextChar;\n }\n\n return list;\n}\n\nchar* charListToString(charList* list){\n charList* iterator = list;\n int count = 0,i;\n char* str;\n\n while(iterator!=NULL){\n count++;\n iterator = iterator->next;\n }\n\n str = (char*)malloc((count+1)*sizeof(char));\n iterator = list;\n\n for(i=0;ic;\n iterator = iterator->next;\n }\n\n free(list);\n str[i] = '\\0';\n\n return str;\n}\n\nchar* processString(char str[100],int operation, char squeezeChar){\n charList *strList = strToCharList(str),*iterator = strList, *scout;\n\n if(operation==SQUEEZE){\n while(iterator!=NULL){\n if(iterator->c==squeezeChar){\n scout = iterator->next;\n\n while(scout!=NULL && scout->c==squeezeChar){\n iterator->next = scout->next;\n scout->next = NULL;\n free(scout);\n scout = iterator->next;\n }\n }\n iterator = iterator->next;\n }\n }\n\n else{\n while(iterator!=NULL && iterator->next!=NULL){\n if(iterator->c == (iterator->next)->c){\n scout = iterator->next;\n squeezeChar = iterator->c;\n\n while(scout!=NULL && scout->c==squeezeChar){\n iterator->next = scout->next;\n scout->next = NULL;\n free(scout);\n scout = iterator->next;\n }\n }\n iterator = iterator->next;\n }\n }\n\n return charListToString(strList);\n}\n\nvoid printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){\n if(operation==SQUEEZE){\n printf(\"Specified Operation : SQUEEZE\\nTarget Character : %c\",squeezeChar);\n }\n\n else\n printf(\"Specified Operation : COLLAPSE\");\n\n printf(\"\\nOriginal %c%c%c%s%c%c%c\\nLength : %d\",174,174,174,originalString,175,175,175,(int)strlen(originalString));\n printf(\"\\nFinal %c%c%c%s%c%c%c\\nLength : %d\\n\",174,174,174,finalString,175,175,175,(int)strlen(finalString));\n}\n\nint main(int argc, char** argv){\n int operation;\n char squeezeChar;\n\n if(argc<3||argc>4){\n printf(\"Usage : %s \\n\",argv[0]);\n return 0;\n }\n\n if(strcmpi(argv[1],\"SQUEEZE\")==0 && argc!=4){\n scanf(\"Please enter characted to be squeezed : %c\",&squeezeChar);\n operation = SQUEEZE;\n }\n\n else if(argc==4){\n operation = SQUEEZE;\n squeezeChar = argv[3][0];\n }\n\n else if(strcmpi(argv[1],\"COLLAPSE\")==0){\n operation = COLLAPSE;\n }\n\n if(strlen(argv[2])<2){\n printResults(argv[2],argv[2],operation,squeezeChar);\n }\n\n else{\n printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar);\n }\n \n return 0;\n}\n"} {"title": "Dice game probabilities", "language": "C", "task": "Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.\n\nThey roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?\n\nLater the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?\n\nThis task was adapted from the Project Euler Problem n.205:\nhttps://projecteuler.net/problem=205\n\n", "solution": "#include \n#include \n\ntypedef uint32_t uint;\ntypedef uint64_t ulong;\n\nulong ipow(const uint x, const uint y) {\n ulong result = 1;\n for (uint i = 1; i <= y; i++)\n result *= x;\n return result;\n}\n\nuint min(const uint x, const uint y) {\n return (x < y) ? x : y;\n}\n\nvoid throw_die(const uint n_sides, const uint n_dice, const uint s, uint counts[]) {\n if (n_dice == 0) {\n counts[s]++;\n return;\n }\n\n for (uint i = 1; i < n_sides + 1; i++)\n throw_die(n_sides, n_dice - 1, s + i, counts);\n}\n\ndouble beating_probability(const uint n_sides1, const uint n_dice1,\n const uint n_sides2, const uint n_dice2) {\n const uint len1 = (n_sides1 + 1) * n_dice1;\n uint C1[len1];\n for (uint i = 0; i < len1; i++)\n C1[i] = 0;\n throw_die(n_sides1, n_dice1, 0, C1);\n\n const uint len2 = (n_sides2 + 1) * n_dice2;\n uint C2[len2];\n for (uint j = 0; j < len2; j++)\n C2[j] = 0;\n throw_die(n_sides2, n_dice2, 0, C2);\n\n const double p12 = (double)(ipow(n_sides1, n_dice1) * ipow(n_sides2, n_dice2));\n\n double tot = 0;\n for (uint i = 0; i < len1; i++)\n for (uint j = 0; j < min(i, len2); j++)\n tot += (double)C1[i] * C2[j] / p12;\n return tot;\n}\n\nint main() {\n printf(\"%1.16f\\n\", beating_probability(4, 9, 6, 6));\n printf(\"%1.16f\\n\", beating_probability(10, 5, 7, 6));\n return 0;\n}"} {"title": "Digital root", "language": "C", "task": "The digital root, X, of a number, n, is calculated:\n: find X as the sum of the digits of n\n: find a new X by summing the digits of X, repeating until X has only one digit.\n\nThe additive persistence is the number of summations required to obtain the single digit. \n\nThe task is to calculate the additive persistence and the digital root of a number, e.g.:\n:627615 has additive persistence 2 and digital root of 9;\n:39390 has additive persistence 2 and digital root of 6;\n:588225 has additive persistence 2 and digital root of 3;\n:393900588225 has additive persistence 2 and digital root of 9;\n\nThe digital root may be calculated in bases other than 10.\n\n\n;See:\n* [[Casting out nines]] for this wiki's use of this procedure.\n* [[Digital root/Multiplicative digital root]]\n* [[Sum digits of an integer]]\n* Digital root sequence on OEIS\n* Additive persistence sequence on OEIS\n* [[Iterated digits squaring]]\n\n", "solution": "#include \n\nint droot(long long int x, int base, int *pers)\n{\n\tint d = 0;\n\tif (pers)\n\t\tfor (*pers = 0; x >= base; x = d, (*pers)++)\n\t\t\tfor (d = 0; x; d += x % base, x /= base);\n\telse if (x && !(d = x % (base - 1)))\n\t\t\td = base - 1;\n\n\treturn d;\n}\n\nint main(void)\n{\n\tint i, d, pers;\n\tlong long x[] = {627615, 39390, 588225, 393900588225LL};\n\n\tfor (i = 0; i < 4; i++) {\n\t\td = droot(x[i], 10, &pers);\n\t\tprintf(\"%lld: pers %d, root %d\\n\", x[i], pers, d);\n\t}\n\n\treturn 0;\n}"} {"title": "Disarium numbers", "language": "C", "task": "A '''Disarium number''' is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.\n\n\n;E.G.\n\n'''135''' is a '''Disarium number''':\n\n 11 + 32 + 53 == 1 + 9 + 125 == 135\n\nThere are a finite number of '''Disarium numbers'''.\n\n\n;Task\n\n* Find and display the first 18 '''Disarium numbers'''.\n\n\n;Stretch\n\n* Find and display all 20 '''Disarium numbers'''.\n\n\n;See also\n\n;* Geeks for Geeks - Disarium numbers\n;* OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...)\n;* Related task: Narcissistic decimal number\n;* Related task: Own digits power sum ''Which seems to be the same task as Narcissistic decimal number...''\n\n", "solution": "#include \n#include \n#include \n\nint power (int base, int exponent) {\n int result = 1;\n for (int i = 1; i <= exponent; i++) {\n result *= base;\n }\n return result;\n}\n\nint is_disarium (int num) {\n int n = num;\n int sum = 0;\n int len = n <= 9 ? 1 : floor(log10(n)) + 1;\n while (n > 0) {\n sum += power(n % 10, len);\n n /= 10;\n len--;\n }\n\n return num == sum;\n}\n\nint main() {\n int count = 0;\n int i = 0;\n while (count < 19) {\n if (is_disarium(i)) {\n printf(\"%d \", i);\n count++;\n }\n i++;\n }\n printf(\"%s\\n\", \"\\n\");\n}\n"} {"title": "Display a linear combination", "language": "C", "task": "Display a finite linear combination in an infinite vector basis (e_1, e_2,\\ldots).\n\nWrite a function that, when given a finite list of scalars (\\alpha^1,\\alpha^2,\\ldots), creates a string representing the linear combination \\sum_i\\alpha^i e_i in an explicit format often used in mathematics, that is:\n\n:\\alpha^{i_1}e_{i_1}\\pm|\\alpha^{i_2}|e_{i_2}\\pm|\\alpha^{i_3}|e_{i_3}\\pm\\ldots\n\nwhere \\alpha^{i_k}\\neq 0\n\nThe output must comply to the following rules:\n* don't show null terms, unless the whole combination is null. \n::::::: '''e(1)''' is fine, '''e(1) + 0*e(3)''' or '''e(1) + 0''' is wrong.\n* don't show scalars when they are equal to one or minus one. \n::::::: '''e(3)''' is fine, '''1*e(3)''' is wrong.\n* don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction. \n::::::: '''e(4) - e(5)''' is fine, '''e(4) + -e(5)''' is wrong.\n\n\nShow here output for the following lists of scalars:\n\n 1) 1, 2, 3\n 2) 0, 1, 2, 3\n 3) 1, 0, 3, 4\n 4) 1, 2, 0\n 5) 0, 0, 0\n 6) 0\n 7) 1, 1, 1\n 8) -1, -1, -1\n 9) -1, -2, 0, -3\n10) -1\n\n\n", "solution": "#include\n#include\n#include /*Optional, but better if included as fabs, labs and abs functions are being used. */\n\nint main(int argC, char* argV[])\n{\n\t\n\tint i,zeroCount= 0,firstNonZero = -1;\n\tdouble* vector;\n\t\n\tif(argC == 1){\n\t\tprintf(\"Usage : %s \",argV[0]);\n\t}\n\t\n\telse{\n\t\t\n\t\tprintf(\"Vector for [\");\n\t\tfor(i=1;i \");\n\t\t\n\t\t\n\t\tvector = (double*)malloc((argC-1)*sizeof(double));\n\t\t\n\t\tfor(i=1;i<=argC;i++){\n\t\t\tvector[i-1] = atof(argV[i]);\n\t\t\tif(vector[i-1]==0.0)\n\t\t\t\tzeroCount++;\n\t\t\tif(vector[i-1]!=0.0 && firstNonZero==-1)\n\t\t\t\tfirstNonZero = i-1;\n\t\t}\n\n\t\tif(zeroCount == argC){\n\t\t\tprintf(\"0\");\n\t\t}\n\t\t\n\t\telse{\n\t\t\tfor(i=0;i0.0)\n\t\t\t\t\tprintf(\"- %lf e%d \",fabs(vector[i]),i+1);\n\t\t\t\telse if(i==firstNonZero && vector[i]<0 && fabs(vector[i])-abs(vector[i])==0.0)\n\t\t\t\t\tprintf(\"- %ld e%d \",labs(vector[i]),i+1);\n\t\t\t\telse if(i==firstNonZero && vector[i]>0 && fabs(vector[i])-abs(vector[i])>0.0)\n\t\t\t\t\tprintf(\"%lf e%d \",vector[i],i+1);\n\t\t\t\telse if(i==firstNonZero && vector[i]>0 && fabs(vector[i])-abs(vector[i])==0.0)\n\t\t\t\t\tprintf(\"%ld e%d \",vector[i],i+1);\n\t\t\t\telse if(fabs(vector[i])==1.0 && i!=0)\n\t\t\t\t\tprintf(\"%c e%d \",(vector[i]==-1)?'-':'+',i+1);\n\t\t\t\telse if(i!=0 && vector[i]!=0 && fabs(vector[i])-abs(vector[i])>0.0)\n\t\t\t\t\tprintf(\"%c %lf e%d \",(vector[i]<0)?'-':'+',fabs(vector[i]),i+1);\n\t\t\t\telse if(i!=0 && vector[i]!=0 && fabs(vector[i])-abs(vector[i])==0.0)\n\t\t\t\t\tprintf(\"%c %ld e%d \",(vector[i]<0)?'-':'+',labs(vector[i]),i+1);\t\t\t\t\n\t\t\t}\n\t\t}\n\t}\n\t\n\tfree(vector);\n\t\n\treturn 0;\n}\n"} {"title": "Diversity prediction theorem", "language": "C", "task": "The ''wisdom of the crowd'' is the collective opinion of a group of individuals rather than that of a single expert.\n\nWisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other. \n\nThus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.\n\n\nScott E. Page introduced the diversity prediction theorem: \n: ''The squared error of the collective prediction equals the average squared error minus the predictive diversity''. \n\n\nTherefore, when the diversity in a group is large, the error of the crowd is small.\n\n\n;Definitions:\n::* Average Individual Error: Average of the individual squared errors\n::* Collective Error: Squared error of the collective prediction\n::* Prediction Diversity: Average squared distance from the individual predictions to the collective prediction\n::* Diversity Prediction Theorem: ''Given a crowd of predictive models'', then\n:::::: Collective Error = Average Individual Error - Prediction Diversity\n\n;Task:\nFor a given true value and a number of number of estimates (from a crowd), show (here on this page):\n:::* the true value and the crowd estimates\n:::* the average error\n:::* the crowd error\n:::* the prediction diversity\n\n\nUse (at least) these two examples:\n:::* a true value of '''49''' with crowd estimates of: ''' 48 47 51'''\n:::* a true value of '''49''' with crowd estimates of: ''' 48 47 51 42'''\n\n\n\n;Also see:\n:* Wikipedia entry: Wisdom of the crowd\n:* University of Michigan: PDF paper (exists on a web archive, the ''Wayback Machine'').\n\n", "solution": "#include\n#include\n#include\n\nfloat mean(float* arr,int size){\n\tint i = 0;\n\tfloat sum = 0;\n\t\n\twhile(i != size)\n\t\tsum += arr[i++];\n\t\n\treturn sum/size;\n}\n\nfloat variance(float reference,float* arr, int size){\n\tint i=0;\n\tfloat* newArr = (float*)malloc(size*sizeof(float));\n\t\n\tfor(;i \");\n\telse{\n\t\tarr = extractData(argV[2],&len);\n\t\t\n\t\treference = atof(argV[1]);\n\t\t\n\t\tmeanVal = mean(arr,len);\n\n\t\tprintf(\"Average Error : %.9f\\n\",variance(reference,arr,len));\n\t\tprintf(\"Crowd Error : %.9f\\n\",(reference - meanVal)*(reference - meanVal));\n\t\tprintf(\"Diversity : %.9f\",variance(meanVal,arr,len));\n\t}\n\t\n\treturn 0;\n}\n"} {"title": "Doomsday rule", "language": "C", "task": " About the task\nJohn Conway (1937-2020), was a mathematician who also invented several mathematically\noriented computer pastimes, such as the famous Game of Life cellular automaton program.\nDr. Conway invented a simple algorithm for finding the day of the week, given any date.\nThe algorithm was based on calculating the distance of a given date from certain\n\"anchor days\" which follow a pattern for the day of the week upon which they fall.\n\n; Algorithm\nThe formula is calculated assuming that Sunday is 0, Monday 1, and so forth with Saturday 7, and\n\n doomsday = (Tuesday(or 2) + 5(y mod 4) + 4(y mod 100) + 6(y mod 400)) % 7\n\nwhich, for 2021, is 0 (Sunday).\n\nTo calculate the day of the week, we then count days from a close doomsday,\nwith these as charted here by month, then add the doomsday for the year,\nthen get the remainder after dividing by 7. This should give us the number\ncorresponding to the day of the week for that date.\n\n Month\t Doomsday Dates for Month\n --------------------------------------------\n January (common years) 3, 10, 17, 24, 31\n January (leap years) 4, 11, 18, 25\n February (common years) 7, 14, 21, 28\n February (leap years) 1, 8, 15, 22, 29\n March 7, 14, 21, 28\n April 4, 11, 18, 25\n May 2, 9, 16, 23, 30\n June 6, 13, 20, 27\n July 4, 11, 18, 25\n August 1, 8, 15, 22, 29\n September 5, 12, 19, 26\n October 3, 10, 17, 24, 31\n November 7, 14, 21, 28\n December 5, 12, 19, 26\n\n; Task\n\nGiven the following dates:\n\n* 1800-01-06 (January 6, 1800)\n* 1875-03-29 (March 29, 1875)\n* 1915-12-07 (December 7, 1915)\n* 1970-12-23 (December 23, 1970)\n* 2043-05-14 (May 14, 2043)\n* 2077-02-12 (February 12, 2077)\n* 2101-04-02 (April 2, 2101)\n\n\nUse Conway's Doomsday rule to calculate the day of the week for each date.\n\n\n; see also\n* Doomsday rule\n* Tomorrow is the Day After Doomsday (p.28)\n\n\n\n\n", "solution": "#include \n#include \n#include \n\ntypedef struct { \n uint16_t year;\n uint8_t month;\n uint8_t day;\n} Date;\n\nbool leap(uint16_t year) {\n return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst char *weekday(Date date) {\n static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n static const char *days[] = {\n \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n \"Thursday\", \"Friday\", \"Saturday\"\n };\n \n unsigned c = date.year/100, r = date.year%100;\n unsigned s = r/12, t = r%12;\n \n unsigned c_anchor = (5 * (c%4) + 2) % 7;\n unsigned doom = (s + t + (t/4) + c_anchor) % 7;\n unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n const char *past = \"was\", *future = \"will be\";\n const char *months[] = { \"\",\n \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n };\n \n const Date dates[] = {\n {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n {2077,2,12}, {2101,4,2}\n };\n \n int i;\n for (i=0; i < sizeof(dates)/sizeof(Date); i++) {\n printf(\"%s %d, %d %s on a %s.\\n\",\n months[dates[i].month], dates[i].day, dates[i].year,\n dates[i].year > 2021 ? future : past,\n weekday(dates[i]));\n }\n \n return 0;\n}"} {"title": "Dot product", "language": "C", "task": "Create a function/use an in-built function, to compute the '''dot product''', also known as the '''scalar product''' of two vectors. \n\nIf possible, make the vectors of arbitrary length.\n\n\nAs an example, compute the dot product of the vectors:\n:::: [1, 3, -5] and \n:::: [4, -2, -1] \n\nIf implementing the dot product of two vectors directly:\n:::* each vector must be the same length\n:::* multiply corresponding terms from each vector\n:::* sum the products (to produce the answer)\n\n\n;Related task:\n* [[Vector products]]\n\n", "solution": "#include \n#include \n\nint dot_product(int *, int *, size_t);\n\nint\nmain(void)\n{\n int a[3] = {1, 3, -5};\n int b[3] = {4, -2, -1};\n\n printf(\"%d\\n\", dot_product(a, b, sizeof(a) / sizeof(a[0])));\n\n return EXIT_SUCCESS;\n}\n\nint\ndot_product(int *a, int *b, size_t n)\n{\n int sum = 0;\n size_t i;\n\n for (i = 0; i < n; i++) {\n sum += a[i] * b[i];\n }\n\n return sum;\n}"} {"title": "Draw a clock", "language": "C", "task": "Draw a clock. \n\n\nMore specific:\n# Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting \"one thousand and one\", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be ''drawn''; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.\n# The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.\n# A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.\n# A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.\n\n\n;Key points\n* animate simple object\n* timed event \n* polling system resources \n* code clarity\n\n", "solution": "// clockrosetta.c - https://rosettacode.org/wiki/Draw_a_clock\n\n// # Makefile\n// CFLAGS = -O3 -Wall -Wfatal-errors -Wpedantic -Werror\n// LDLIBS = -lX11 -lXext -lm\n// all: clockrosetta\n\n#define SIZE 500\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstatic XdbeBackBuffer dbewindow = 0;\nstatic Display *display;\nstatic Window window;\nstatic int needseg = 1;\nstatic double d2r;\nstatic XSegment seg[61];\nstatic GC gc;\nstatic int mw = SIZE / 2;\nstatic int mh = SIZE / 2;\n\nstatic void\ndraw(void)\n {\n struct tm *ptm;\n int i;\n double angle;\n double delta;\n int radius = (mw < mh ? mw : mh) - 2;\n XPoint pt[3];\n double onetwenty = 3.1415926 * 2 / 3;\n XdbeSwapInfo swapi;\n time_t newtime;\n\n if(dbewindow == 0)\n {\n dbewindow = XdbeAllocateBackBufferName(display, window, XdbeBackground);\n XClearWindow(display, window);\n }\n\n time(&newtime);\n ptm = localtime(&newtime);\n\n if(needseg)\n {\n d2r = atan2(1.0, 0.0) / 90.0;\n for(i = 0; i < 60; i++)\n {\n angle = (double)i * 6.0 * d2r;\n delta = i % 5 ? 0.97 : 0.9;\n seg[i].x1 = mw + radius * delta * sin(angle);\n seg[i].y1 = mh - radius * delta * cos(angle);\n seg[i].x2 = mw + radius * sin(angle);\n seg[i].y2 = mh - radius * cos(angle);\n }\n needseg = 0;\n }\n\n angle = (double)(ptm->tm_sec) * 6.0 * d2r;\n seg[60].x1 = mw;\n seg[60].y1 = mh;\n seg[60].x2 = mw + radius * 0.9 * sin(angle);\n seg[60].y2 = mh - radius * 0.9 * cos(angle);\n XDrawSegments(display, dbewindow, gc, seg, 61);\n\n angle = (double)ptm->tm_min * 6.0 * d2r;\n pt[0].x = mw + radius * 3 / 4 * sin(angle);\n pt[0].y = mh - radius * 3 / 4 * cos(angle);\n pt[1].x = mw + 6 * sin(angle + onetwenty);\n pt[1].y = mh - 6 * cos(angle + onetwenty);\n pt[2].x = mw + 6 * sin(angle - onetwenty);\n pt[2].y = mh - 6 * cos(angle - onetwenty);\n XFillPolygon(display, dbewindow, gc, pt, 3, Nonconvex, CoordModeOrigin);\n\n angle = (double)(ptm->tm_hour * 60 + ptm->tm_min) / 2.0 * d2r;\n pt[0].x = mw + radius / 2 * sin(angle);\n pt[0].y = mh - radius / 2 * cos(angle);\n pt[1].x = mw + 6 * sin(angle + onetwenty);\n pt[1].y = mh - 6 * cos(angle + onetwenty);\n pt[2].x = mw + 6 * sin(angle - onetwenty);\n pt[2].y = mh - 6 * cos(angle - onetwenty);\n XFillPolygon(display, dbewindow, gc, pt, 3, Nonconvex, CoordModeOrigin);\n\n swapi.swap_window = window;\n swapi.swap_action = XdbeBackground;\n XdbeSwapBuffers(display, &swapi, 1);\n }\n\nint\nmain(int argc, char *argv[])\n {\n Atom wm_both_protocols[1];\n Atom wm_delete;\n Atom wm_protocols;\n Window root;\n XEvent event;\n XSetWindowAttributes attr;\n fd_set fd;\n int exposed = 0;\n int more = 1;\n struct timeval tv;\n\n display = XOpenDisplay(NULL);\n\n if(display == NULL)\n {\n fprintf(stderr,\"Error: The display cannot be opened\\n\");\n exit(1);\n }\n\n root = DefaultRootWindow(display);\n wm_delete = XInternAtom(display, \"WM_DELETE_WINDOW\", False);\n wm_protocols = XInternAtom(display, \"WM_PROTOCOLS\", False);\n\n attr.background_pixel = 0x000000;\n attr.event_mask = KeyPress | KeyRelease |\n ButtonPressMask | ButtonReleaseMask | ExposureMask;\n\n window = XCreateWindow(display, root,\n 0, 0, SIZE, SIZE, 0,\n CopyFromParent, InputOutput, CopyFromParent,\n CWBackPixel | CWEventMask,\n &attr\n );\n\n XStoreName(display, window, \"Clock for RosettaCode\");\n\n wm_both_protocols[0] = wm_delete;\n XSetWMProtocols(display, window, wm_both_protocols, 1);\n\n gc = XCreateGC(display, window, 0, NULL);\n XSetForeground(display, gc, 0xFFFF80);\n\n XMapWindow(display, window);\n\n while(more)\n {\n if(QLength(display) > 0)\n {\n XNextEvent(display, &event);\n }\n else\n {\n int maxfd = ConnectionNumber(display);\n\n XFlush(display);\n FD_ZERO(&fd);\n FD_SET(ConnectionNumber(display), &fd);\n\n event.type = LASTEvent;\n tv.tv_sec = 0;\n tv.tv_usec = 250000;\n if(select(maxfd + 1, &fd, NULL, NULL, &tv) > 0)\n {\n if(FD_ISSET(ConnectionNumber(display), &fd))\n {\n XNextEvent(display, &event);\n }\n }\n }\n\n switch(event.type)\n {\n case Expose:\n exposed = 1;\n draw();\n break;\n\n case ButtonRelease:\n case KeyRelease:\n more = 0;\n case ButtonPress: // ignore\n case KeyPress: // ignore\n break;\n\n case LASTEvent: // the timeout comes here\n if(exposed) draw();\n break;\n\n case ConfigureNotify:\n mw = event.xconfigure.width / 2;\n mh = event.xconfigure.height / 2;\n needseg = 1;\n break;\n\n\n case ClientMessage: // for close request from WM\n if(event.xclient.window == window &&\n event.xclient.message_type == wm_protocols &&\n event.xclient.format == 32 &&\n event.xclient.data.l[0] == wm_delete)\n {\n more = 0;\n }\n break;\n\n// default:\n// printf(\"unexpected event.type %d\\n\", event.type);;\n }\n }\n\n XCloseDisplay(display);\n exit(0);\n }\n\n// END"} {"title": "Draw a rotating cube", "language": "C", "task": "Task\nDraw a rotating cube. \n\nIt should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional.\n\n\n;Related tasks\n* Draw a cuboid\n* write language name in 3D ASCII\n\n", "solution": "#include\n\ndouble rot = 0;\nfloat matCol[] = {1,0,0,0};\n\nvoid display(){\n\tglClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);\n\tglPushMatrix();\n\tglRotatef(30,1,1,0);\n\tglRotatef(rot,0,1,1);\n\tglMaterialfv(GL_FRONT,GL_DIFFUSE,matCol);\n\tglutWireCube(1);\n\tglPopMatrix();\n\tglFlush();\n}\n\n\nvoid onIdle(){\n\trot += 0.1;\n\tglutPostRedisplay();\n}\n\nvoid reshape(int w,int h){\n\tfloat ar = (float) w / (float) h ;\n\t\n\tglViewport(0,0,(GLsizei)w,(GLsizei)h);\n\tglTranslatef(0,0,-10);\n\tglMatrixMode(GL_PROJECTION);\n\tgluPerspective(70,(GLfloat)w/(GLfloat)h,1,12);\n\tglLoadIdentity();\n\tglFrustum ( -1.0, 1.0, -1.0, 1.0, 10.0, 100.0 ) ;\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n}\n\nvoid init(){\n\tfloat pos[] = {1,1,1,0};\n\tfloat white[] = {1,1,1,0};\n\tfloat shini[] = {70};\n\t\n\tglClearColor(.5,.5,.5,0);\n\tglShadeModel(GL_SMOOTH);\n\tglLightfv(GL_LIGHT0,GL_AMBIENT,white);\n\tglLightfv(GL_LIGHT0,GL_DIFFUSE,white);\n\tglMaterialfv(GL_FRONT,GL_SHININESS,shini);\n\tglEnable(GL_LIGHTING);\n\tglEnable(GL_LIGHT0);\n\tglEnable(GL_DEPTH_TEST);\n}\n\nint main(int argC, char* argV[])\n{\n\tglutInit(&argC,argV);\n\tglutInitDisplayMode(GLUT_SINGLE|GLUT_RGB|GLUT_DEPTH);\n\tglutInitWindowSize(600,500);\n\tglutCreateWindow(\"Rossetta's Rotating Cube\");\n\tinit();\n\tglutDisplayFunc(display);\n\tglutReshapeFunc(reshape);\n\tglutIdleFunc(onIdle);\n\tglutMainLoop();\n\treturn 0;\n}\n"} {"title": "Draw a sphere", "language": "C", "task": "{{requires|Graphics}}\n\n\n;Task:\nDraw a sphere. \n\nThe sphere can be represented graphically, or in ASCII art, depending on the language capabilities. \n\nEither static or rotational projection is acceptable for this task.\n\n\n;Related tasks:\n* draw a cuboid\n* draw a rotating cube\n* write language name in 3D ASCII\n* draw a Deathstar\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nconst char *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { 30, 30, -50 };\nvoid normalize(double * v)\n{\n double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n v[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n return d < 0 ? -d : 0;\n}\n\nvoid draw_sphere(double R, double k, double ambient)\n{\n int i, j, intensity;\n double b;\n double vec[3], x, y;\n for (i = floor(-R); i <= ceil(R); i++) {\n x = i + .5;\n for (j = floor(-2 * R); j <= ceil(2 * R); j++) {\n y = j / 2. + .5;\n if (x * x + y * y <= R * R) {\n vec[0] = x;\n vec[1] = y;\n vec[2] = sqrt(R * R - x * x - y * y);\n normalize(vec);\n b = pow(dot(light, vec), k) + ambient;\n intensity = (1 - b) * (sizeof(shades) - 1);\n if (intensity < 0) intensity = 0;\n if (intensity >= sizeof(shades) - 1)\n intensity = sizeof(shades) - 2;\n putchar(shades[intensity]);\n } else\n putchar(' ');\n }\n putchar('\\n');\n }\n}\n\n\nint main()\n{\n normalize(light);\n draw_sphere(20, 4, .1);\n draw_sphere(10, 2, .4);\n\n return 0;\n}"} {"title": "Dutch national flag problem", "language": "C", "task": "The Dutch national flag is composed of three coloured bands in the order:\n::* red (top)\n::* then white, and\n::* lastly blue (at the bottom). \n\n\nThe problem posed by Edsger Dijkstra is:\n:Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag.\nWhen the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ...\n\n\n;Task\n# Generate a randomized order of balls ''ensuring that they are not in the order of the Dutch national flag''.\n# Sort the balls in a way idiomatic to your language.\n# Check the sorted balls ''are'' in the order of the Dutch national flag.\n\n\n;C.f.:\n* Dutch national flag problem\n* Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)\n\n", "solution": "#include //printf()\n#include //srand(), rand(), RAND_MAX, qsort()\n#include //true, false\n#include //time()\n\n#define NUMBALLS 5 //NUMBALLS>1\n\nint compar(const void *a, const void *b){\n\tchar c1=*(const char*)a, c2=*(const char*)b; //first cast void* to char*, then dereference\n\treturn c1-c2;\n}\n\n_Bool issorted(char *balls){\n\tint i,state;\n\tstate=0;\n\tfor(i=0;istate)state=balls[i];\n\t}\n\treturn true;\n}\n\nvoid printout(char *balls){\n\tint i;\n\tchar str[NUMBALLS+1];\n\tfor(i=0;i\n#include \n#include \n#include \n\nuint64_t egyptian_division(uint64_t dividend, uint64_t divisor, uint64_t *remainder) {\n\t// remainder is an out parameter, pass NULL if you do not need the remainder\n\t\n\tstatic uint64_t powers[64];\n\tstatic uint64_t doublings[64];\n\n\tint i;\n\t\n\tfor(i = 0; i < 64; i++) {\n\t\tpowers[i] = 1 << i;\n\t\tdoublings[i] = divisor << i;\n\t\tif(doublings[i] > dividend)\n\t\t\tbreak;\n\t}\n\t\n\tuint64_t answer = 0;\n\tuint64_t accumulator = 0;\n\n\tfor(i = i - 1; i >= 0; i--) {\n\t\t// If the current value of the accumulator added to the\n\t\t// doublings cell would be less than or equal to the\n\t\t// dividend then add it to the accumulator\n\t\tif(accumulator + doublings[i] <= dividend) {\n\t\t\taccumulator += doublings[i];\n\t\t\tanswer += powers[i];\n\t\t}\n\t}\n\t\n\tif(remainder)\n\t\t*remainder = dividend - accumulator;\n\treturn answer;\n}\n\nvoid go(uint64_t a, uint64_t b) {\n\tuint64_t x, y;\n\tx = egyptian_division(a, b, &y);\n\tprintf(\"%llu / %llu = %llu remainder %llu\\n\", a, b, x, y);\n\tassert(a == b * x + y);\n}\n\nint main(void) {\n\tgo(580, 32);\n}\n"} {"title": "Elementary cellular automaton", "language": "C", "task": "An '''cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits.\n\nThe rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101.\n\n\n;Task:\nCreate a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice.\n\nThe space state should ''wrap'': this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally.\n\nThis task is basically a generalization of [[one-dimensional cellular automata]].\n\n\n;See also\n* Cellular automata (natureofcode.com)\n\n", "solution": "#include \n#include \n\ntypedef unsigned long long ull;\n#define N (sizeof(ull) * CHAR_BIT)\n#define B(x) (1ULL << (x))\n\nvoid evolve(ull state, int rule)\n{\n\tint i;\n\tull st;\n\n\tprintf(\"Rule %d:\\n\", rule);\n\tdo {\n\t\tst = state;\n\t\tfor (i = N; i--; ) putchar(st & B(i) ? '#' : '.');\n\t\tputchar('\\n');\n\n\t\tfor (state = i = 0; i < N; i++)\n\t\t\tif (rule & B(7 & (st>>(i-1) | st<<(N+1-i))))\n\t\t\t\tstate |= B(i);\n\t} while (st != state);\n}\n\nint main(int argc, char **argv)\n{\n\tevolve(B(N/2), 90);\n\tevolve(B(N/4)|B(N - N/4), 30); // well, enjoy the fireworks\n\n\treturn 0;\n}"} {"title": "Elementary cellular automaton/Random number generator", "language": "C", "task": "Mathematica software for its default random number generator.\n\nSteven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state.\n\nThe purpose of this task is to demonstrate this. With the code written in the most significant.\n\nYou can pick which ever length you want for the initial array but it should be visible in the code so that your output can be reproduced with an other language.\n\nFor extra-credits, you will make this algorithm run as fast as possible in your language, for instance with an extensive use of bitwise logic.\n\n;Reference:\n* Cellular automata: Is Rule 30 random? (PDF).\n\n\n", "solution": "#include \n#include \n\ntypedef unsigned long long ull;\n#define N (sizeof(ull) * CHAR_BIT)\n#define B(x) (1ULL << (x))\n\nvoid evolve(ull state, int rule)\n{\n\tint i, p, q, b;\n\n\tfor (p = 0; p < 10; p++) {\n\t\tfor (b = 0, q = 8; q--; ) {\n\t\t\tull st = state;\n\t\t\tb |= (st&1) << q;\n\n\t\t\tfor (state = i = 0; i < N; i++)\n\t\t\t\tif (rule & B(7 & (st>>(i-1) | st<<(N+1-i))))\n\t\t\t\t\tstate |= B(i);\n\t\t}\n\t\tprintf(\" %d\", b);\n\t}\n\tputchar('\\n');\n\treturn;\n}\n\nint main(void)\n{\n\tevolve(1, 30);\n\treturn 0;\n}"} {"title": "Elliptic curve arithmetic", "language": "C", "task": "digital signatures. \n\nThe purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the elliptic curve DSA protocol. \n\nIn a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the '''x''' and '''y''' coordinates of any point on the curve:\n\n:::: y^2 = x^3 + a x + b\n\n'''a''' and '''b''' are arbitrary parameters that define the specific curve which is used. \n\nFor this particular task, we'll use the following parameters:\n\n:::: a=0, b=7 \n\nThe most interesting thing about elliptic curves is the fact that it is possible to define a group structure on it. \n\nTo do so we define an internal composition rule with an additive notation '''+''', such that for any three distinct points '''P''', '''Q''' and '''R''' on the curve, whenever these points are aligned, we have:\n\n:::: P + Q + R = 0 \n\nHere '''0''' (zero) is the ''infinity point'', for which the '''x''' and '''y''' values are not defined. It's basically the same kind of point which defines the horizon in projective geometry. \n\nWe'll also assume here that this infinity point is unique and defines the neutral element of the addition.\n\nThis was not the definition of the addition, but only its desired property. For a more accurate definition, we proceed as such:\n\nGiven any three aligned points '''P''', '''Q''' and '''R''', we define the sum '''S = P + Q''' as the point (possibly the infinity point) such that '''S''', '''R''' and the infinity point are aligned.\n\nConsidering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points '''S''' and '''R''' can be aligned with the infinity point if and only if '''S''' and '''R''' are symmetric of one another towards the x-axis (because in that case there is no other candidate than the infinity point to complete the alignment triplet).\n\n'''S''' is thus defined as the symmetric of '''R''' towards the '''x''' axis.\n\nThe task consists in defining the addition which, for any two points of the curve, returns the sum of these two points. You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points. \n\nYou will use the '''a''' and '''b''' parameters of secp256k1, i.e. respectively zero and seven.\n\n''Hint'': You might need to define a \"doubling\" function, that returns '''P+P''' for any given point '''P'''.\n\n''Extra credit'': define the full elliptic curve arithmetic (still not modular, though) by defining a \"multiply\" function that returns, \nfor any point '''P''' and integer '''n''', the point '''P + P + ... + P''' ('''n''' times).\n\n", "solution": "#include \n#include \n\n#define C 7\ntypedef struct { double x, y; } pt;\n\npt zero(void) { return (pt){ INFINITY, INFINITY }; }\n\n// should be INFINITY, but numeric precision is very much in the way\nint is_zero(pt p) { return p.x > 1e20 || p.x < -1e20; }\n\npt neg(pt p) { return (pt){ p.x, -p.y }; }\n\npt dbl(pt p) {\n\tif (is_zero(p)) return p;\n\n\tpt r;\n\tdouble L = (3 * p.x * p.x) / (2 * p.y);\n\tr.x = L * L - 2 * p.x;\n\tr.y = L * (p.x - r.x) - p.y;\n\treturn r;\n}\n\npt add(pt p, pt q) {\n\tif (p.x == q.x && p.y == q.y) return dbl(p);\n\tif (is_zero(p)) return q;\n\tif (is_zero(q)) return p;\n\n\tpt r;\n\tdouble L = (q.y - p.y) / (q.x - p.x);\n\tr.x = L * L - p.x - q.x;\n\tr.y = L * (p.x - r.x) - p.y;\n\treturn r;\n}\n\npt mul(pt p, int n) {\n\tint i;\n\tpt r = zero();\n\n\tfor (i = 1; i <= n; i <<= 1) {\n\t\tif (i & n) r = add(r, p);\n\t\tp = dbl(p);\n\t}\n\treturn r;\n}\n\nvoid show(const char *s, pt p) {\n\tprintf(\"%s\", s);\n\tprintf(is_zero(p) ? \"Zero\\n\" : \"(%.3f, %.3f)\\n\", p.x, p.y);\n}\n\npt from_y(double y) {\n\tpt r;\n\tr.x = pow(y * y - C, 1.0/3);\n\tr.y = y;\n\treturn r;\n}\n\nint main(void) {\n\tpt a, b, c, d;\n\n\ta = from_y(1);\n\tb = from_y(2);\n\n\tshow(\"a = \", a);\n\tshow(\"b = \", b);\n\tshow(\"c = a + b = \", c = add(a, b));\n\tshow(\"d = -c = \", d = neg(c));\n\tshow(\"c + d = \", add(c, d));\n\tshow(\"a + b + d = \", add(a, add(b, d)));\n\tshow(\"a * 12345 = \", mul(a, 12345));\n\n\treturn 0;\n}"} {"title": "Empty directory", "language": "C", "task": "Starting with a path to some directory, determine whether the directory is empty.\n\nAn empty directory contains no files nor subdirectories. \nWith [[Unix]] or [[Windows]] systems, every directory contains an entry for \".\" and almost every directory contains \"..\" (except for a root directory); an empty directory contains no other entries.\n\n", "solution": "#include \n#include \n#include \n\nint dir_empty(const char *path)\n{\n\tstruct dirent *ent;\n\tint ret = 1;\n\n\tDIR *d = opendir(path);\n\tif (!d) {\n\t\tfprintf(stderr, \"%s: \", path);\n\t\tperror(\"\");\n\t\treturn -1;\n\t}\n\n\twhile ((ent = readdir(d))) {\n\t\tif (!strcmp(ent->d_name, \".\") || !(strcmp(ent->d_name, \"..\")))\n\t\t\tcontinue;\n\t\tret = 0;\n\t\tbreak;\n\t}\n\n\tclosedir(d);\n\treturn ret;\n}\n\nint main(int c, char **v)\n{\n\tint ret = 0, i;\n\tif (c < 2) return -1;\n\n\tfor (i = 1; i < c; i++) {\n\t\tret = dir_empty(v[i]);\n\t\tif (ret >= 0)\n\t\t\tprintf(\"%s: %sempty\\n\", v[i], ret ? \"\" : \"not \");\n\t}\n\n\treturn 0;\n}"} {"title": "Empty string", "language": "C", "task": "Languages may have features for dealing specifically with empty strings \n(those containing no characters).\n\n\n;Task:\n::* Demonstrate how to assign an empty string to a variable.\n::* Demonstrate how to check that a string is empty.\n::* Demonstrate how to check that a string is not empty.\n\n\n\n", "solution": "#include \n\n/* ... */\n\n/* assign an empty string */\nconst char *str = \"\";\n\n/* to test a null string */\nif (str) { ... }\n\n/* to test if string is empty */\nif (str[0] == '\\0') { ... }\n\n/* or equivalently use strlen function \n strlen will seg fault on NULL pointer, so check first */\nif ( (str == NULL) || (strlen(str) == 0)) { ... }\n\n/* or compare to a known empty string, same thing. \"== 0\" means strings are equal */\nif (strcmp(str, \"\") == 0) { ... } \n"} {"title": "Entropy/Narcissist", "language": "C", "task": "Write a computer program that computes and shows its own [[entropy]].\n\n\n;Related Tasks: \n:* [[Fibonacci_word]]\n:* [[Entropy]]\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\n#define MAXLEN 961 //maximum string length\n\nint makehist(char *S,int *hist,int len){\n\tint wherechar[256];\n\tint i,histlen;\n\thistlen=0;\n\tfor(i=0;i<256;i++)wherechar[i]=-1;\n\tfor(i=0;i\n#include \n\nint list[] = {-7, 1, 5, 2, -4, 3, 0};\n\nint eq_idx(int *a, int len, int **ret)\n{\n\tint i, sum, s, cnt;\n\t/* alloc long enough: if we can afford the original list,\n\t * we should be able to afford to this. Beats a potential\n * million realloc() calls. Even if memory is a real concern,\n * there's no garantee the result is shorter than the input anyway */\n cnt = s = sum = 0;\n\t*ret = malloc(sizeof(int) * len);\n\n\tfor (i = 0; i < len; i++)\n sum += a[i];\n\n\tfor (i = 0; i < len; i++) {\n\t\tif (s * 2 + a[i] == sum) {\n\t\t\t(*ret)[cnt] = i;\n cnt++;\n }\n\t\ts += a[i];\n\t}\n\n /* uncouraged way to use realloc since it can leak memory, for example */\n\t*ret = realloc(*ret, cnt * sizeof(int));\n\n\treturn cnt;\n}\n\nint main()\n{\n\tint i, cnt, *idx;\n\tcnt = eq_idx(list, sizeof(list) / sizeof(int), &idx);\n\n\tprintf(\"Found:\");\n\tfor (i = 0; i < cnt; i++)\n printf(\" %d\", idx[i]);\n\tprintf(\"\\n\");\n\n\treturn 0;\n}"} {"title": "Euler's identity", "language": "C", "task": "{{Wikipedia|Euler's_identity}}\n\n\nIn mathematics, ''Euler's identity'' is the equality:\n\n ei\\pi + 1 = 0\n\nwhere\n\n e is Euler's number, the base of natural logarithms,\n ''i'' is the imaginary unit, which satisfies ''i''2 = -1, and\n \\pi is pi, the ratio of the circumference of a circle to its diameter.\n\nEuler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:\n\n The number 0.\n The number 1.\n The number \\pi (\\pi = 3.14159+),\n The number e (e = 2.71828+), which occurs widely in mathematical analysis.\n The number ''i'', the imaginary unit of the complex numbers.\n\n;Task\nShow in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation. \n\nMost languages are limited to IEEE 754 floating point calculations so will have some error in the calculation. \n\nIf that is the case, or there is some other limitation, show \nthat ei\\pi + 1 is ''approximately'' equal to zero and \nshow the amount of error in the calculation.\n\nIf your language is capable of symbolic calculations, show \nthat ei\\pi + 1 is ''exactly'' equal to zero for bonus kudos points.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nint main() {\n wchar_t pi = L'\\u03c0'; /* Small pi symbol */\n wchar_t ae = L'\\u2245'; /* Approximately equals symbol */\n double complex e = cexp(M_PI * I) + 1.0;\n setlocale(LC_CTYPE, \"\");\n printf(\"e ^ %lci + 1 = [%.16f, %.16f] %lc 0\\n\", pi, creal(e), cimag(e), ae);\n return 0;\n}"} {"title": "Euler's sum of powers conjecture", "language": "C", "task": "There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.\n\nThis conjecture is called Euler's sum of powers conjecture and can be stated as such:\n\n:At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk.\n\nIn 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.\n\nThe task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here.\n\nRelated tasks are:\n* [[Pythagorean quadruples]]. \n* [[Pythagorean triples]].\n\n\n\n", "solution": "// Alexander Maximov, July 2nd, 2015\n#include \n#include \ntypedef long long mylong;\n\nvoid compute(int N, char find_only_one_solution)\n{\tconst int M = 30; /* x^5 == x modulo M=2*3*5 */\n\tint a, b, c, d, e;\n\tmylong s, t, max, *p5 = (mylong*)malloc(sizeof(mylong)*(N+M));\n \n\tfor(s=0; s < N; ++s)\n\t\tp5[s] = s * s, p5[s] *= p5[s] * s;\n\tfor(max = p5[N - 1]; s < (N + M); p5[s++] = max + 1);\n \n\tfor(a = 1; a < N; ++a)\n\tfor(b = a + 1; b < N; ++b)\n\tfor(c = b + 1; c < N; ++c)\n\tfor(d = c + 1, e = d + ((t = p5[a] + p5[b] + p5[c]) % M); ((s = t + p5[d]) <= max); ++d, ++e)\n\t{\tfor(e -= M; p5[e + M] <= s; e += M); /* jump over M=30 values for e>d */\n\t\tif(p5[e] == s)\n\t\t{\tprintf(\"%d %d %d %d %d\\r\\n\", a, b, c, d, e);\n\t\t\tif(find_only_one_solution) goto onexit;\n\t\t}\n\t}\nonexit:\n\tfree(p5);\n}\n\nint main(void)\n{\n\tint tm = clock();\n\tcompute(250, 0);\n\tprintf(\"time=%d milliseconds\\r\\n\", (int)((clock() - tm) * 1000 / CLOCKS_PER_SEC));\n\treturn 0;\n}"} {"title": "Even or odd", "language": "C", "task": "Test whether an integer is even or odd.\n\nThere is more than one way to solve this task:\n\n* Use the even and odd predicates, if the language provides them.\n* Check the least significant digit. With binary integers, ''i iff ''i'' is even, or equals 1 iff ''i'' is odd.\n* Divide ''i'' by 2. The remainder equals 0 iff ''i'' is even. The remainder equals +1 or -1 iff ''i'' is odd.\n* Use modular congruences:\n** ''i'' 0 (mod 2) iff ''i'' is even.\n** ''i'' 1 (mod 2) iff ''i'' is odd.\n\n", "solution": "mpz_t x;\n...\nif (mpz_even_p(x)) { /* x is even */ }\nif (mpz_odd_p(x)) { /* x is odd */ }"} {"title": "Evolutionary algorithm", "language": "C", "task": "Starting with:\n* The target string: \"METHINKS IT IS LIKE A WEASEL\".\n* An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent).\n* A fitness function that computes the 'closeness' of its argument to the target string.\n* A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated.\n* While the parent is not yet the target:\n:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.\n:* Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others.\n:* repeat until the parent converges, (hopefully), to the target.\n\n\n;See also:\n* Wikipedia entry: Weasel algorithm.\n* Wikipedia entry: Evolutionary algorithm.\n\n\nNote: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions\n\nA cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically,\n* While the parent is not yet the target:\n:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.\n\nNote that some of the the solutions given retain characters in the mutated string that are ''correct'' in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of \"converges\"\n\n (:* repeat until the parent converges, (hopefully), to the target.\n\nStrictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by ''not'' being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent!\n\nAs illustration of this error, the code for 8th has the following remark.\n\n Create a new string based on the TOS, '''changing randomly any characters which\n don't already match the target''':\n\n''NOTE:'' this has been changed, the 8th version is completely random now\n\nClearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters!\n\nTo ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.\n\n", "solution": "#include \n#include \n#include \n\nconst char target[] = \"METHINKS IT IS LIKE A WEASEL\";\nconst char tbl[] = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ \";\n\n#define CHOICE (sizeof(tbl) - 1)\n#define MUTATE 15\n#define COPIES 30\n\n/* returns random integer from 0 to n - 1 */\nint irand(int n)\n{\n\tint r, rand_max = RAND_MAX - (RAND_MAX % n);\n\twhile((r = rand()) >= rand_max);\n\treturn r / (rand_max / n);\n}\n\n/* number of different chars between a and b */\nint unfitness(const char *a, const char *b)\n{\n\tint i, sum = 0;\n\tfor (i = 0; a[i]; i++)\n\t\tsum += (a[i] != b[i]);\n\treturn sum;\n}\n\n/* each char of b has 1/MUTATE chance of differing from a */\nvoid mutate(const char *a, char *b)\n{\n\tint i;\n\tfor (i = 0; a[i]; i++)\n\t\tb[i] = irand(MUTATE) ? a[i] : tbl[irand(CHOICE)];\n\n\tb[i] = '\\0';\n}\n\nint main()\n{\n\tint i, best_i, unfit, best, iters = 0;\n\tchar specimen[COPIES][sizeof(target) / sizeof(char)];\n\n\t/* init rand string */\n\tfor (i = 0; target[i]; i++)\n\t\tspecimen[0][i] = tbl[irand(CHOICE)];\n\tspecimen[0][i] = 0;\n\n\tdo {\n\t\tfor (i = 1; i < COPIES; i++)\n\t\t\tmutate(specimen[0], specimen[i]);\n\n\t\t/* find best fitting string */\n\t\tfor (best_i = i = 0; i < COPIES; i++) {\n\t\t\tunfit = unfitness(target, specimen[i]);\n\t\t\tif(unfit < best || !i) {\n\t\t\t\tbest = unfit;\n\t\t\t\tbest_i = i;\n\t\t\t}\n\t\t}\n\n\t\tif (best_i) strcpy(specimen[0], specimen[best_i]);\n\t\tprintf(\"iter %d, score %d: %s\\n\", iters++, best, specimen[0]);\n\t} while (best);\n\n\treturn 0;\n}"} {"title": "Executable library", "language": "C", "task": "The general idea behind an executable library is to create a library \nthat when used as a library does one thing; \nbut has the ability to be run directly via command line. \nThus the API comes with a CLI in the very same source code file.\n\n'''Task detail'''\n\n* Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the [[Hailstone sequence]] for that number.\n\n* The library, when executed directly should satisfy the remaining requirements of the [[Hailstone sequence]] task:\n:: 2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1\n:: 3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.\n\n* Create a second executable to calculate the following:\n** Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 <= n < 100,000.\n\n* Explain any extra setup/run steps needed to complete the task.\n\n'''Notes:''' \n* It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed ''not'' to be present in the runtime environment.\n* Interpreters are present in the runtime environment.\n\n", "solution": "#include \n#include \n\nlong hailstone(long n, long **seq)\n{\n long len = 0, buf_len = 4;\n if (seq)\n *seq = malloc(sizeof(long) * buf_len);\n\n while (1) {\n if (seq) {\n if (len >= buf_len) {\n buf_len *= 2;\n *seq = realloc(*seq, sizeof(long) * buf_len);\n }\n (*seq)[len] = n;\n }\n len ++;\n if (n == 1) break;\n if (n & 1) n = 3 * n + 1;\n else n >>= 1;\n }\n return len;\n}\n\nvoid free_sequence(long * s) { free(s); }\n\nconst char my_interp[] __attribute__((section(\".interp\"))) = \"/lib/ld-linux.so.2\";\n/* \"ld-linux.so.2\" should be whatever you use on your platform */\n\nint hail_main() /* entry point when running along, see compiler command line */\n{\n long i, *seq;\n\n long len = hailstone(27, &seq);\n printf(\"27 has %ld numbers in sequence:\\n\", len);\n for (i = 0; i < len; i++) {\n printf(\"%ld \", seq[i]);\n }\n printf(\"\\n\");\n free_sequence(seq);\n\n exit(0);\n}"} {"title": "Execute HQ9+", "language": "C", "task": "Implement a ''' [[HQ9+]] ''' interpreter or compiler.\n\n", "solution": "void runCode(const char *code)\n{\n int c_len = strlen(code);\n int i, bottles;\n unsigned accumulator=0;\n for(i=0;i 0 );\n break;\n\n case '+':\n //Am I the only one finding this one weird? :o\n accumulator++;\n break;\n }\n }\n};"} {"title": "Exponentiation order", "language": "C", "task": "This task will demonstrate the order of exponentiation ('''xy''') when there are multiple exponents.\n\n(Many programming languages, especially those with extended-precision integer arithmetic, usually support one of **, ^, | or some such for exponentiation.)\n\n\n;Task requirements\nShow the result of a language's evaluation of multiple exponentiation (either as an integer or floating point).\n\nIf your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.\n\n\nUsing whatever operator or syntax your language supports (if any), show the results in three lines (with identification):\n \n::::* 5**3**2 \n::::* (5**3)**2\n::::* 5**(3**2)\n\n\nIf there are other methods (or formats) of multiple exponentiations, show them as well. \n\n\n;See also:\n* MathWorld entry: exponentiation\n\n\n;Related tasks:\n* exponentiation operator\n* arbitrary-precision integers (included)\n* [[Exponentiation with infix operators in (or operating on) the base]]\n\n", "solution": "#include\n#include\n\nint main()\n{\n printf(\"(5 ^ 3) ^ 2 = %.0f\",pow(pow(5,3),2));\n printf(\"\\n5 ^ (3 ^ 2) = %.0f\",pow(5,pow(3,2)));\n\t\n return 0;\n}"} {"title": "Extend your language", "language": "C", "task": "{{Control Structures}}Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements.\n\nIf your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch:\n\nOccasionally, code must be written that depends on ''two'' conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are \"true\"). In a C-like language this could look like the following:\n\n if (condition1isTrue) {\n if (condition2isTrue)\n bothConditionsAreTrue();\n else\n firstConditionIsTrue();\n }\n else if (condition2isTrue)\n secondConditionIsTrue();\n else\n noConditionIsTrue();\n\nBesides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large.\n\nThis can be improved by introducing a new keyword '''if2'''. It is similar to '''if''', but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be:\n\n if2 (condition1isTrue) (condition2isTrue)\n bothConditionsAreTrue();\n else1\n firstConditionIsTrue();\n else2\n secondConditionIsTrue();\n else\n noConditionIsTrue();\n\nPick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.\n", "solution": "#include \n\n#define if2(a, b) switch(((a)) + ((b)) * 2) { case 3:\n#define else00\tbreak; case 0:\t/* both false */\n#define else10\tbreak; case 1:\t/* true, false */\n#define else01\tbreak; case 2:\t/* false, true */\n#define else2\tbreak; default: /* anything not metioned */\n#define fi2\t}\t\t/* stupid end bracket */\n\nint main()\n{\n\tint i, j;\n\tfor (i = 0; i < 3; i++) for (j = 0; j < 3; j++) {\n\t\tprintf(\"%d %d: \", i, j);\n\t\tif2 (i == 1, j == 1)\n\t\t\tprintf(\"both\\n\");\n\t\telse10\n\t\t\tprintf(\"left\\n\");\n\t\telse01\n\t\t\tprintf(\"right\\n\");\n\t\telse00 { /* <-- bracket is optional, flaw */, \n\t\t\tprintf(\"neither\\n\");\n\t\t\tif2 (i == 2, j == 2) \n\t\t\t\tprintf(\"\\tis 22\");\n\t\t\t\tprintf(\"\\n\"); /* flaw: this is part of if2! */\n\t\t\telse2\n\t\t\t\tprintf(\"\\tnot 22\\n\");\n\t\t\tfi2\t\t\t\t\n\t\t}\n\t\tfi2\n\t}\n\n\treturn 0;\n}"} {"title": "Extreme floating point values", "language": "C", "task": "The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.\n\nThe task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables. \n\nPrint the values of these variables if possible; and show some arithmetic with these values and variables. \n\nIf your language can directly enter these extreme floating point values then show it.\n\n\n;See also:\n* What Every Computer Scientist Should Know About Floating-Point Arithmetic\n\n\n;Related tasks:\n* [[Infinity]]\n* [[Detect division by zero]]\n* [[Literals/Floating point]]\n\n", "solution": "Note: Under the C standard, division by zero (of any type) is undefined behavior.\n\n: The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.\n\n: -- C99 standard, section 6.5.5 paragraph 5\n\nFloating-point division by zero in the following examples to obtain infinity or NaN are dependent on implementation-specific behavior.\n\n"} {"title": "FASTA format", "language": "C", "task": "In FASTA. \n\nA FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.\n\n\n;Task:\nWrite a program that reads a FASTA file such as:\n\n>Rosetta_Example_1\nTHERECANBENOSPACE\n>Rosetta_Example_2\nTHERECANBESEVERAL\nLINESBUTTHEYALLMUST\nBECONCATENATED\n\n", "solution": "#include \n#include \n#include \n\nvoid main()\n{\n\tFILE * fp;\n\tchar * line = NULL;\n\tsize_t len = 0;\n\tssize_t read;\n\n\tfp = fopen(\"fasta.txt\", \"r\");\n\tif (fp == NULL)\n\t\texit(EXIT_FAILURE);\n\n\tint state = 0;\n\twhile ((read = getline(&line, &len, fp)) != -1) {\n\t\t/* Delete trailing newline */\n\t\tif (line[read - 1] == '\\n')\n\t\t\tline[read - 1] = 0;\n\t\t/* Handle comment lines*/\n\t\tif (line[0] == '>') {\n\t\t\tif (state == 1)\n\t\t\t\tprintf(\"\\n\");\n\t\t\tprintf(\"%s: \", line+1);\n\t\t\tstate = 1;\n\t\t} else {\n\t\t\t/* Print everything else */\n\t\t\tprintf(\"%s\", line);\n\t\t}\n\t}\n\tprintf(\"\\n\");\n\n\tfclose(fp);\n\tif (line)\n\t\tfree(line);\n\texit(EXIT_SUCCESS);\n}"} {"title": "Fairshare between two and more", "language": "C", "task": "The [[Thue-Morse]] sequence is a sequence of ones and zeros that if two people\ntake turns in the given order, the first persons turn for every '0' in the\nsequence, the second for every '1'; then this is shown to give a fairer, more\nequitable sharing of resources. (Football penalty shoot-outs for example, might\nnot favour the team that goes first as much if the penalty takers take turns\naccording to the Thue-Morse sequence and took 2^n penalties)\n\nThe Thue-Morse sequence of ones-and-zeroes can be generated by:\n:''\"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence\"''\n\n\n;Sharing fairly between two or more:\nUse this method:\n:''When counting base '''b''', the digit sum modulo '''b''' is the Thue-Morse sequence of fairer sharing between '''b''' people.''\n\n\n;Task\nCounting from zero; using a function/method/routine to express an integer count in base '''b''',\nsum the digits modulo '''b''' to produce the next member of the Thue-Morse fairshare series for '''b''' people.\n\n\nShow the first 25 terms of the fairshare sequence:\n:* For two people:\n:* For three people\n:* For five people\n:* For eleven people\n\n\n;Related tasks: \n:* [[Non-decimal radices/Convert]]\n:* [[Thue-Morse]]\n\n\n;See also:\n:* A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences(r) (OEIS(r))\n\n", "solution": "#include \n#include \n\nint turn(int base, int n) {\n int sum = 0;\n while (n != 0) {\n int rem = n % base;\n n = n / base;\n sum += rem;\n }\n return sum % base;\n}\n\nvoid fairshare(int base, int count) {\n int i;\n\n printf(\"Base %2d:\", base);\n for (i = 0; i < count; i++) {\n int t = turn(base, i);\n printf(\" %2d\", t);\n }\n printf(\"\\n\");\n}\n\nvoid turnCount(int base, int count) {\n int *cnt = calloc(base, sizeof(int));\n int i, minTurn, maxTurn, portion;\n\n if (NULL == cnt) {\n printf(\"Failed to allocate space to determine the spread of turns.\\n\");\n return;\n }\n\n for (i = 0; i < count; i++) {\n int t = turn(base, i);\n cnt[t]++;\n }\n\n minTurn = INT_MAX;\n maxTurn = INT_MIN;\n portion = 0;\n for (i = 0; i < base; i++) {\n if (cnt[i] > 0) {\n portion++;\n }\n if (cnt[i] < minTurn) {\n minTurn = cnt[i];\n }\n if (cnt[i] > maxTurn) {\n maxTurn = cnt[i];\n }\n }\n\n printf(\" With %d people: \", base);\n if (0 == minTurn) {\n printf(\"Only %d have a turn\\n\", portion);\n } else if (minTurn == maxTurn) {\n printf(\"%d\\n\", minTurn);\n } else {\n printf(\"%d or %d\\n\", minTurn, maxTurn);\n }\n\n free(cnt);\n}\n\nint main() {\n fairshare(2, 25);\n fairshare(3, 25);\n fairshare(5, 25);\n fairshare(11, 25);\n\n printf(\"How many times does each get a turn in 50000 iterations?\\n\");\n turnCount(191, 50000);\n turnCount(1377, 50000);\n turnCount(49999, 50000);\n turnCount(50000, 50000);\n turnCount(50001, 50000);\n\n return 0;\n}"} {"title": "Farey sequence", "language": "C", "task": "The Farey sequence ''' ''F''n''' of order '''n''' is the sequence of completely reduced fractions between '''0''' and '''1''' which, when in lowest terms, have denominators less than or equal to '''n''', arranged in order of increasing size.\n\nThe ''Farey sequence'' is sometimes incorrectly called a ''Farey series''. \n\n\nEach Farey sequence:\n:::* starts with the value '''0''' (zero), denoted by the fraction \\frac{0}{1} \n:::* ends with the value '''1''' (unity), denoted by the fraction \\frac{1}{1}.\n\n\nThe Farey sequences of orders '''1''' to '''5''' are:\n\n:::: {\\bf\\it{F}}_1 = \\frac{0}{1}, \\frac{1}{1}\n:\n:::: {\\bf\\it{F}}_2 = \\frac{0}{1}, \\frac{1}{2}, \\frac{1}{1}\n:\n:::: {\\bf\\it{F}}_3 = \\frac{0}{1}, \\frac{1}{3}, \\frac{1}{2}, \\frac{2}{3}, \\frac{1}{1}\n:\n:::: {\\bf\\it{F}}_4 = \\frac{0}{1}, \\frac{1}{4}, \\frac{1}{3}, \\frac{1}{2}, \\frac{2}{3}, \\frac{3}{4}, \\frac{1}{1}\n:\n:::: {\\bf\\it{F}}_5 = \\frac{0}{1}, \\frac{1}{5}, \\frac{1}{4}, \\frac{1}{3}, \\frac{2}{5}, \\frac{1}{2}, \\frac{3}{5}, \\frac{2}{3}, \\frac{3}{4}, \\frac{4}{5}, \\frac{1}{1}\n\n;Task\n* Compute and show the Farey sequence for orders '''1''' through '''11''' (inclusive).\n* Compute and display the ''number'' of fractions in the Farey sequence for order '''100''' through '''1,000''' (inclusive) by hundreds.\n* Show the fractions as '''n/d''' (using the solidus [or slash] to separate the numerator from the denominator). \n\n\nThe length (the number of fractions) of a Farey sequence asymptotically approaches:\n\n::::::::::: 3 x n2 / \\pi2 \n\n;See also:\n* OEIS sequence A006842 numerators of Farey series of order 1, 2, *** \n* OEIS sequence A006843 denominators of Farey series of order 1, 2, *** \n* OEIS sequence A005728 number of fractions in Farey series of order n \n* MathWorld entry Farey sequence\n* Wikipedia entry Farey sequence\n\n", "solution": "#include \n#include \n#include \n\nvoid farey(int n)\n{\n\ttypedef struct { int d, n; } frac;\n\tfrac f1 = {0, 1}, f2 = {1, n}, t;\n\tint k;\n\n\tprintf(\"%d/%d %d/%d\", 0, 1, 1, n);\n\twhile (f2.n > 1) {\n\t\tk = (n + f1.n) / f2.n;\n\t\tt = f1, f1 = f2, f2 = (frac) { f2.d * k - t.d, f2.n * k - t.n };\n\t\tprintf(\" %d/%d\", f2.d, f2.n);\n\t}\n\n\tputchar('\\n');\n}\n\ntypedef unsigned long long ull;\null *cache;\nsize_t ccap;\n\null farey_len(int n)\n{\n\tif (n >= ccap) {\n\t\tsize_t old = ccap;\n\t\tif (!ccap) ccap = 16;\n\t\twhile (ccap <= n) ccap *= 2;\n\t\tcache = realloc(cache, sizeof(ull) * ccap);\n\t\tmemset(cache + old, 0, sizeof(ull) * (ccap - old));\n\t} else if (cache[n])\n\t\treturn cache[n];\n\n\tull len = (ull)n*(n + 3) / 2;\n\tint p, q = 0;\n\tfor (p = 2; p <= n; p = q) {\n\t\tq = n/(n/p) + 1;\n\t\tlen -= farey_len(n/p) * (q - p);\n\t}\n\n\tcache[n] = len;\n\treturn len;\n}\n\nint main(void)\n{\n\tint n;\n\tfor (n = 1; n <= 11; n++) {\n\t\tprintf(\"%d: \", n);\n\t\tfarey(n);\n\t}\n\n\tfor (n = 100; n <= 1000; n += 100)\n\t\tprintf(\"%d: %llu items\\n\", n, farey_len(n));\n\n\tn = 10000000;\n\tprintf(\"\\n%d: %llu items\\n\", n, farey_len(n));\n\treturn 0;\n}"} {"title": "Fast Fourier transform", "language": "C", "task": "Calculate the FFT (Fast Fourier Transform) of an input sequence.\n\nThe most general case allows for complex numbers at the input \nand results in a sequence of equal length, again of complex numbers. \nIf you need to restrict yourself to real numbers, the output should \nbe the magnitude (i.e.: sqrt(re2 + im2)) of the complex result. \n\nThe classic version is the recursive Cooley-Tukey FFT. Wikipedia has pseudo-code for that. \nFurther optimizations are possible but not required.\n\n", "solution": "#include \n#include \n#include \n \ndouble PI;\ntypedef double complex cplx;\n \nvoid _fft(cplx buf[], cplx out[], int n, int step)\n{\n\tif (step < n) {\n\t\t_fft(out, buf, n, step * 2);\n\t\t_fft(out + step, buf + step, n, step * 2);\n \n\t\tfor (int i = 0; i < n; i += 2 * step) {\n\t\t\tcplx t = cexp(-I * PI * i / n) * out[i + step];\n\t\t\tbuf[i / 2] = out[i] + t;\n\t\t\tbuf[(i + n)/2] = out[i] - t;\n\t\t}\n\t}\n}\n \nvoid fft(cplx buf[], int n)\n{\n\tcplx out[n];\n\tfor (int i = 0; i < n; i++) out[i] = buf[i];\n \n\t_fft(buf, out, n, 1);\n}\n \n \nvoid show(const char * s, cplx buf[]) {\n\tprintf(\"%s\", s);\n\tfor (int i = 0; i < 8; i++)\n\t\tif (!cimag(buf[i]))\n\t\t\tprintf(\"%g \", creal(buf[i]));\n\t\telse\n\t\t\tprintf(\"(%g, %g) \", creal(buf[i]), cimag(buf[i]));\n}\n\nint main()\n{\n\tPI = atan2(1, 1) * 4;\n\tcplx buf[] = {1, 1, 1, 1, 0, 0, 0, 0};\n \n\tshow(\"Data: \", buf);\n\tfft(buf, 8);\n\tshow(\"\\nFFT : \", buf);\n \n\treturn 0;\n}\n\n"} {"title": "Fibonacci n-step number sequences", "language": "C", "task": "These number series are an expansion of the ordinary [[Fibonacci sequence]] where:\n# For n = 2 we have the Fibonacci sequence; with initial values [1, 1] and F_k^2 = F_{k-1}^2 + F_{k-2}^2\n# For n = 3 we have the tribonacci sequence; with initial values [1, 1, 2] and F_k^3 = F_{k-1}^3 + F_{k-2}^3 + F_{k-3}^3\n# For n = 4 we have the tetranacci sequence; with initial values [1, 1, 2, 4] and F_k^4 = F_{k-1}^4 + F_{k-2}^4 + F_{k-3}^4 + F_{k-4}^4...\n# For general n>2 we have the Fibonacci n-step sequence - F_k^n; with initial values of the first n values of the (n-1)'th Fibonacci n-step sequence F_k^{n-1}; and k'th value of this n'th sequence being F_k^n = \\sum_{i=1}^{(n)} {F_{k-i}^{(n)}}\n\nFor small values of n, Greek numeric prefixes are sometimes used to individually name each series.\n\n:::: {| style=\"text-align: left;\" border=\"4\" cellpadding=\"2\" cellspacing=\"2\"\n|+ Fibonacci n-step sequences\n|- style=\"background-color: rgb(255, 204, 255);\"\n! n !! Series name !! Values\n|-\n| 2 || fibonacci || 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...\n|-\n| 3 || tribonacci || 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...\n|-\n| 4 || tetranacci || 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...\n|-\n| 5 || pentanacci || 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...\n|-\n| 6 || hexanacci || 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...\n|-\n| 7 || heptanacci || 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...\n|-\n| 8 || octonacci || 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...\n|-\n| 9 || nonanacci || 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...\n|-\n| 10 || decanacci || 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...\n|}\n\nAllied sequences can be generated where the initial values are changed:\n: '''The Lucas series''' sums the two preceding values like the fibonacci series for n=2 but uses [2, 1] as its initial values.\n\n\n\n;Task:\n# Write a function to generate Fibonacci n-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.\n# Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.\n\n\n;Related tasks:\n* [[Fibonacci sequence]]\n* Wolfram Mathworld\n* [[Hofstadter Q sequence]]\n* [[Leonardo numbers]]\n\n\n;Also see:\n* Lucas Numbers - Numberphile (Video)\n* Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)\n* Wikipedia, Lucas number\n* MathWorld, Fibonacci Number\n* Some identities for r-Fibonacci numbers\n* OEIS Fibonacci numbers\n* OEIS Lucas numbers\n\n", "solution": "/*\nThe function anynacci determines the n-arity of the sequence from the number of seed elements. 0 ended arrays are used since C does not have a way of determining the length of dynamic and function-passed integer arrays.*/\n\n#include\n#include\n\nint *\nanynacci (int *seedArray, int howMany)\n{\n int *result = malloc (howMany * sizeof (int));\n int i, j, initialCardinality;\n\n for (i = 0; seedArray[i] != 0; i++);\n initialCardinality = i;\n\n for (i = 0; i < initialCardinality; i++)\n result[i] = seedArray[i];\n\n for (i = initialCardinality; i < howMany; i++)\n {\n result[i] = 0;\n for (j = i - initialCardinality; j < i; j++)\n result[i] += result[j];\n }\n return result;\n}\n\nint\nmain ()\n{\n int fibo[] = { 1, 1, 0 }, tribo[] = { 1, 1, 2, 0 }, tetra[] = { 1, 1, 2, 4, 0 }, luca[] = { 2, 1, 0 };\n int *fibonacci = anynacci (fibo, 10), *tribonacci = anynacci (tribo, 10), *tetranacci = anynacci (tetra, 10), \n *lucas = anynacci(luca, 10);\n int i;\n\n printf (\"\\nFibonacci\\tTribonacci\\tTetranacci\\tLucas\\n\");\n\n for (i = 0; i < 10; i++)\n printf (\"\\n%d\\t\\t%d\\t\\t%d\\t\\t%d\", fibonacci[i], tribonacci[i],\n tetranacci[i], lucas[i]);\n\n return 0;\n}"} {"title": "Fibonacci word", "language": "C", "task": "The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here:\n\n Define F_Word1 as '''1'''\n Define F_Word2 as '''0'''\n Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: '''01'''\n Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2\n\n\n;Task:\nPerform the above steps for n = 37.\n\nYou may display the first few but not the larger values of n.\n{Doing so will get the task's author into trouble with them what be (again!).} \n\nInstead, create a table for F_Words '''1''' to '''37''' which shows:\n::* The number of characters in the word\n::* The word's [[Entropy]]\n\n\n;Related tasks: \n* Fibonacci word/fractal\n* [[Entropy]]\n* [[Entropy/Narcissist]]\n\n", "solution": "#include \n#include \n#include \n#include \n\nvoid print_headings()\n{\n\tprintf(\"%2s\", \"N\");\n\tprintf(\" %10s\", \"Length\");\n\tprintf(\" %-20s\", \"Entropy\");\n\tprintf(\" %-40s\", \"Word\");\n\tprintf(\"\\n\");\n}\n\ndouble calculate_entropy(int ones, int zeros)\n{\n\tdouble result = 0;\n\t\n\tint total = ones + zeros;\n\tresult -= (double) ones / total * log2((double) ones / total);\n\tresult -= (double) zeros / total * log2((double) zeros / total);\n\t\n\tif (result != result) { // NAN\n\t\tresult = 0;\n\t}\n\t\n\treturn result;\n}\n\nvoid print_entropy(char *word)\n{\n\tint ones = 0;\n\tint zeros = 0;\n\t\n\tint i;\n\tfor (i = 0; word[i]; i++) {\n\t\tchar c = word[i];\n\t\t\n\t\tswitch (c) {\n\t\t\tcase '0':\n\t\t\t\tzeros++;\n\t\t\t\tbreak;\n\t\t\tcase '1':\n\t\t\t\tones++;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tdouble entropy = calculate_entropy(ones, zeros);\n\tprintf(\" %-20.18f\", entropy);\n}\n\nvoid print_word(int n, char *word)\n{\n\tprintf(\"%2d\", n);\n\t\n\tprintf(\" %10ld\", strlen(word));\n\t\n\tprint_entropy(word);\n\t\n\tif (n < 10) {\n\t\tprintf(\" %-40s\", word);\n\t} else {\n\t\tprintf(\" %-40s\", \"...\");\n\t}\n\t\n\tprintf(\"\\n\");\n}\n\nint main(int argc, char *argv[])\n{\n\tprint_headings();\n\t\n\tchar *last_word = malloc(2);\n\tstrcpy(last_word, \"1\");\n\t\n\tchar *current_word = malloc(2);\n\tstrcpy(current_word, \"0\");\n\t\n\tprint_word(1, last_word);\n\tint i;\n\tfor (i = 2; i <= 37; i++) {\n\t\tprint_word(i, current_word);\n\t\t\n\t\tchar *next_word = malloc(strlen(current_word) + strlen(last_word) + 1);\n\t\tstrcpy(next_word, current_word);\n\t\tstrcat(next_word, last_word);\n\t\t\n\t\tfree(last_word);\n\t\tlast_word = current_word;\n\t\tcurrent_word = next_word;\n\t}\n\t\n\tfree(last_word);\n\tfree(current_word);\n\treturn 0;\n}"} {"title": "File extension is in extensions list", "language": "C", "task": "Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension ''(see e.g. FileNameExtensionFilter in Java)''.\n\nIt also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid.\n\nFor these reasons, this task exists in addition to the [[Extract file extension]] task.\n\n\n;Related tasks: \n* [[Extract file extension]]\n* [[String matching]]\n\n", "solution": "/*\n * File extension is in extensions list (dots allowed).\n *\n * This problem is trivial because the so-called extension is simply the end\n * part of the name.\n */\n\n#define _CRT_SECURE_NO_WARNINGS\n\n#include \n#include \n#include \n#include \n#include \n\n#ifdef _Bool\n#include \n#else\n#define bool int\n#define true 1\n#define false 0\n#endif\n\n/*\n * The implemented algorithm is not the most efficient one: for N extensions\n * of length M it has the cost O(N * M).\n */\nint checkFileExtension(char* fileName, char* fileExtensions)\n{\n char* fileExtension = fileExtensions;\n\n if ( *fileName )\n {\n while ( *fileExtension )\n {\n int fileNameLength = strlen(fileName);\n int extensionLength = strlen(fileExtension);\n if ( fileNameLength >= extensionLength )\n {\n char* a = fileName + fileNameLength - extensionLength;\n char* b = fileExtension;\n while ( *a && toupper(*a++) == toupper(*b++) )\n ;\n if ( !*a )\n return true;\n }\n fileExtension += extensionLength + 1;\n }\n }\n return false;\n}\n\nvoid printExtensions(char* extensions)\n{\n while( *extensions )\n {\n printf(\"%s\\n\", extensions);\n extensions += strlen(extensions) + 1;\n }\n}\n\nbool test(char* fileName, char* extension, bool expectedResult)\n{\n bool result = checkFileExtension(fileName,extension);\n bool returnValue = result == expectedResult;\n printf(\"%20s result: %-5s expected: %-5s test %s\\n\", \n fileName,\n result ? \"true\" : \"false\",\n expectedResult ? \"true\" : \"false\", \n returnValue ? \"passed\" : \"failed\" );\n return returnValue;\n}\n\nint main(void)\n{\n static char extensions[] = \".zip\\0.rar\\0.7z\\0.gz\\0.archive\\0.A##\\0.tar.bz2\\0\";\n\n setlocale(LC_ALL,\"\");\n\n printExtensions(extensions);\n printf(\"\\n\");\n\n if ( test(\"MyData.a##\", extensions,true )\n && test(\"MyData.tar.Gz\", extensions,true )\n && test(\"MyData.gzip\", extensions,false)\n && test(\"MyData.7z.backup\", extensions,false)\n && test(\"MyData...\", extensions,false)\n && test(\"MyData\", extensions,false)\n && test(\"MyData_v1.0.tar.bz2\",extensions,true )\n && test(\"MyData_v1.0.bz2\", extensions,false) \n && test(\"filename\", extensions,false)\n )\n printf(\"\\n%s\\n\", \"All tests passed.\");\n else\n printf(\"\\n%s\\n\", \"Last test failed.\");\n\n printf(\"\\n%s\\n\", \"press enter\");\n getchar();\n return 0;\n}"} {"title": "File size distribution", "language": "C", "task": "Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy.\n\n\nMy suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may not be that significant.\n\nDon't forget that empty files may exist, to serve as a marker.\n\n\nIs your file system predominantly devoted to a large number of smaller files, or a smaller number of huge files?\n\n", "solution": "#include\n#include\n#include\n\n#define MAXORDER 25\n\nint main(int argC, char* argV[])\n{\n\tchar str[MAXORDER],commandString[1000],*startPath;\n\tlong int* fileSizeLog = (long int*)calloc(sizeof(long int),MAXORDER),max;\n\tint i,j,len;\n\tdouble scale;\n\tFILE* fp;\n\n\tif(argC==1)\n\t\tprintf(\"Usage : %s \",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],' ')!=NULL){\n\t\tlen = strlen(argV[1]);\n\t\tstartPath = (char*)malloc((len+2)*sizeof(char));\n\t\tstartPath[0] = '\\\"';\n\t\tstartPath[len+1]='\\\"';\n\t\tstrncpy(startPath+1,argV[1],len);\n\t\tstartPath[len+2] = argV[1][len];\n\t\tsprintf(commandString,\"forfiles /p %s /s /c \\\"cmd /c echo @fsize\\\" 2>&1\",startPath);\n\t}\n\n\telse if(strlen(argV[1])==1 && argV[1][0]=='.')\n\t\tstrcpy(commandString,\"forfiles /s /c \\\"cmd /c echo @fsize\\\" 2>&1\");\n\n\telse\n\t\tsprintf(commandString,\"forfiles /p %s /s /c \\\"cmd /c echo @fsize\\\" 2>&1\",argV[1]);\n\n\tfp = popen(commandString,\"r\");\n\n\twhile(fgets(str,100,fp)!=NULL){\n\t\t\tif(str[0]=='0')\n\t\t\t\tfileSizeLog[0]++;\n\t\t\telse\n\t\t\t\tfileSizeLog[strlen(str)]++;\n\t}\n\n\tif(argC==2 || (argC==3 && (argV[2][0]=='t'||argV[2][0]=='T'))){\n\t\tfor(i=0;imax)?max=fileSizeLog[i]:max;\n\n\t\t\t\t(max < csbi.dwSize.X)?(scale=1):(scale=(1.0*(csbi.dwSize.X-50))/max);\n\n\t\t\t\tfor(i=0;i\n\nchar * base;\nvoid get_diff()\n{\n\tchar x;\n\tif (base - &x < 200)\n\t\tprintf(\"%p %d\\n\", &x, base - &x);\n}\n\nvoid recur()\n{\n\tget_diff();\n\trecur();\n}\n\nint main()\n{\n\tchar v = 32;\n\tprintf(\"pos of v: %p\\n\", base = &v);\n\trecur();\n\treturn 0;\n}"} {"title": "Find palindromic numbers in both binary and ternary bases", "language": "C", "task": "* Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in ''both'':\n:::* base 2\n:::* base 3\n* Display '''0''' (zero) as the first number found, even though some other definitions ignore it.\n* Optionally, show the decimal number found in its binary and ternary form.\n* Show all output here.\n\n\nIt's permissible to assume the first two numbers and simply list them.\n\n\n;See also\n* Sequence A60792, numbers that are palindromic in bases 2 and 3 on ''The On-Line Encyclopedia of Integer Sequences''.\n\n", "solution": "#include \ntypedef unsigned long long xint;\n\nint is_palin2(xint n)\n{\n\txint x = 0;\n\tif (!(n&1)) return !n;\n\twhile (x < n) x = x<<1 | (n&1), n >>= 1;\n\treturn n == x || n == x>>1;\n}\n\nxint reverse3(xint n)\n{\n\txint x = 0;\n\twhile (n) x = x*3 + (n%3), n /= 3;\n\treturn x;\n}\n\nvoid print(xint n, xint base)\n{\n\tputchar(' ');\n\t// printing digits backwards, but hey, it's a palindrome\n\tdo { putchar('0' + (n%base)), n /= base; } while(n);\n\tprintf(\"(%lld)\", base);\n}\n\nvoid show(xint n)\n{\n\tprintf(\"%llu\", n);\n\tprint(n, 2);\n\tprint(n, 3);\n\tputchar('\\n');\n}\n\nxint min(xint a, xint b) { return a < b ? a : b; }\nxint max(xint a, xint b) { return a > b ? a : b; }\n\nint main(void)\n{\n\txint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;\n\tint cnt;\n\n\tshow(0);\n\tcnt = 1;\n\n\tlo = 0;\n\thi = pow2 = pow3 = 1;\n\n\twhile (1) {\n\t\tfor (i = lo; i < hi; i++) {\n\t\t\tn = (i * 3 + 1) * pow3 + reverse3(i);\n\t\t\tif (!is_palin2(n)) continue;\n\t\t\tshow(n);\n\t\t\tif (++cnt >= 7) return 0;\n\t\t}\n\n\t\tif (i == pow3)\n\t\t\tpow3 *= 3;\n\t\telse\n\t\t\tpow2 *= 4;\n\n\t\twhile (1) {\n\t\t\twhile (pow2 <= pow3) pow2 *= 4;\n\n\t\t\tlo2 = (pow2 / pow3 - 1) / 3;\n\t\t\thi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;\n\t\t\tlo3 = pow3 / 3;\n\t\t\thi3 = pow3;\n\n\t\t\tif (lo2 >= hi3)\n\t\t\t\tpow3 *= 3;\n\t\t\telse if (lo3 >= hi2)\n\t\t\t\tpow2 *= 4;\n\t\t\telse {\n\t\t\t\tlo = max(lo2, lo3);\n\t\t\t\thi = min(hi2, hi3);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}"} {"title": "Find the intersection of a line with a plane", "language": "C", "task": "Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection.\n\n\n;Task:\nFind the point of intersection for the infinite ray with direction (0, -1, -1) passing through position (0, 0, 10) with the infinite plane with a normal vector of (0, 0, 1) and which passes through [0, 0, 5].\n\n", "solution": "#include\n\ntypedef struct{\n\tdouble x,y,z;\n}vector;\n\nvector addVectors(vector a,vector b){\n\treturn (vector){a.x+b.x,a.y+b.y,a.z+b.z};\n}\n\nvector subVectors(vector a,vector b){\n\treturn (vector){a.x-b.x,a.y-b.y,a.z-b.z};\n}\n\ndouble dotProduct(vector a,vector b){\n\treturn a.x*b.x + a.y*b.y + a.z*b.z;\n}\n\nvector scaleVector(double l,vector a){\n\treturn (vector){l*a.x,l*a.y,l*a.z};\n}\n\nvector intersectionPoint(vector lineVector, vector linePoint, vector planeNormal, vector planePoint){\n\tvector diff = subVectors(linePoint,planePoint);\n\t\n\treturn addVectors(addVectors(diff,planePoint),scaleVector(-dotProduct(diff,planeNormal)/dotProduct(lineVector,planeNormal),lineVector));\n}\n\nint main(int argC,char* argV[])\n{\n\tvector lV,lP,pN,pP,iP;\n\t\n\tif(argC!=5)\n\t\tprintf(\"Usage : %s \");\n\telse{\n\t\tsscanf(argV[1],\"(%lf,%lf,%lf)\",&lV.x,&lV.y,&lV.z);\n\t\tsscanf(argV[3],\"(%lf,%lf,%lf)\",&pN.x,&pN.y,&pN.z);\n\t\t\n\t\tif(dotProduct(lV,pN)==0)\n\t\t\tprintf(\"Line and Plane do not intersect, either parallel or line is on the plane\");\n\t\telse{\n\t\t\tsscanf(argV[2],\"(%lf,%lf,%lf)\",&lP.x,&lP.y,&lP.z);\n\t\t\tsscanf(argV[4],\"(%lf,%lf,%lf)\",&pP.x,&pP.y,&pP.z);\n\t\t\t\n\t\t\tiP = intersectionPoint(lV,lP,pN,pP);\n\t\t\t\n\t\t\tprintf(\"Intersection point is (%lf,%lf,%lf)\",iP.x,iP.y,iP.z);\n\t\t}\n\t}\n\t\t\n\treturn 0;\n}\n"} {"title": "Find the intersection of two lines", "language": "C", "task": "Finding the intersection of two lines that are in the same plane is an important topic in collision detection.[http://mathworld.wolfram.com/Line-LineIntersection.html]\n\n;Task:\nFind the point of intersection of two lines in 2D. \n\n\nThe 1st line passes though (4,0) and (6,10) . \nThe 2nd line passes though (0,3) and (10,7) .\n\n", "solution": "#include\n#include\n#include\n\ntypedef struct{\n\tdouble x,y;\n}point;\n\ndouble lineSlope(point a,point b){\n\t\n\tif(a.x-b.x == 0.0)\n\t\treturn NAN;\n\telse\n\t\treturn (a.y-b.y)/(a.x-b.x);\n}\n\npoint extractPoint(char* str){\n\tint i,j,start,end,length;\n\tchar* holder;\n\tpoint c;\n\t\n\tfor(i=0;str[i]!=00;i++){\n\t\tif(str[i]=='(')\n\t\t\tstart = i;\n\t\tif(str[i]==','||str[i]==')')\n\t\t{\n\t\t\tend = i;\n\t\t\t\n\t\t\tlength = end - start;\n\t\t\t\n\t\t\tholder = (char*)malloc(length*sizeof(char));\n\t\t\t\n\t\t\tfor(j=0;j\",argV[0]);\n\telse{\n\t\tc = intersectionPoint(extractPoint(argV[1]),extractPoint(argV[2]),extractPoint(argV[3]),extractPoint(argV[4]));\n\t\t\n\t\tif(isnan(c.x))\n\t\t\tprintf(\"The lines do not intersect, they are either parallel or co-incident.\");\n\t\telse\n\t\t\tprintf(\"Point of intersection : (%lf,%lf)\",c.x,c.y);\n\t}\n\t\n\treturn 0;\n}\n"} {"title": "Find the last Sunday of each month", "language": "C", "task": "Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).\n\nExample of an expected output:\n\n./last_sundays 2013\n2013-01-27\n2013-02-24\n2013-03-31\n2013-04-28\n2013-05-26\n2013-06-30\n2013-07-28\n2013-08-25\n2013-09-29\n2013-10-27\n2013-11-24\n2013-12-29\n\n;Related tasks\n* [[Day of the week]]\n* [[Five weekends]]\n* [[Last Friday of each month]]\n\n", "solution": "#include \n#include \n\nint main(int argc, char *argv[])\n{\n int days[] = {31,29,31,30,31,30,31,31,30,31,30,31};\n int m, y, w;\n\n if (argc < 2 || (y = atoi(argv[1])) <= 1752) return 1;\n days[1] -= (y % 4) || (!(y % 100) && (y % 400));\n w = y * 365 + 97 * (y - 1) / 400 + 4;\n\n for(m = 0; m < 12; m++) {\n w = (w + days[m]) % 7;\n printf(\"%d-%02d-%d\\n\", y, m + 1,days[m] - w);\n }\n\n return 0;\n}\n"} {"title": "Find the missing permutation", "language": "C", "task": "ABCD\n CABD\n ACDB\n DACB\n BCDA\n ACBD\n ADCB\n CDAB\n DABC\n BCAD\n CADB\n CDBA\n CBAD\n ABDC\n ADBC\n BDCA\n DCBA\n BACD\n BADC\n BDAC\n CBDA\n DBCA\n DCAB\n\n\nListed above are all-but-one of the permutations of the symbols '''A''', '''B''', '''C''', and '''D''', ''except'' for one permutation that's ''not'' listed. \n\n\n;Task:\nFind that missing permutation.\n\n\n;Methods:\n* Obvious method: \n enumerate all permutations of '''A''', '''B''', '''C''', and '''D''', \n and then look for the missing permutation. \n\n* alternate method:\n Hint: if all permutations were shown above, how many \n times would '''A''' appear in each position? \n What is the ''parity'' of this number?\n\n* another alternate method:\n Hint: if you add up the letter values of each column, \n does a missing letter '''A''', '''B''', '''C''', and '''D''' from each\n column cause the total value for each column to be unique?\n\n\n;Related task:\n* [[Permutations]])\n\n", "solution": "#include \n\n#define N 4\nconst char *perms[] = {\n\t\"ABCD\", \"CABD\", \"ACDB\", \"DACB\", \"BCDA\", \"ACBD\", \"ADCB\", \"CDAB\",\n\t\"DABC\", \"BCAD\", \"CADB\", \"CDBA\", \"CBAD\", \"ABDC\", \"ADBC\", \"BDCA\",\n\t\"DCBA\", \"BACD\", \"BADC\", \"BDAC\", \"CBDA\", \"DBCA\", \"DCAB\",\n};\n\nint main()\n{\n\tint i, j, n, cnt[N];\n\tchar miss[N];\n\n\tfor (n = i = 1; i < N; i++) n *= i; /* n = (N-1)!, # of occurrence */\n\n\tfor (i = 0; i < N; i++) {\n\t\tfor (j = 0; j < N; j++) cnt[j] = 0;\n\n\t\t/* count how many times each letter occur at position i */\n\t\tfor (j = 0; j < sizeof(perms)/sizeof(const char*); j++)\n\t\t\tcnt[perms[j][i] - 'A']++;\n\n\t\t/* letter not occurring (N-1)! times is the missing one */\n\t\tfor (j = 0; j < N && cnt[j] == n; j++);\n\n\t\tmiss[i] = j + 'A';\n\t}\n\tprintf(\"Missing: %.*s\\n\", N, miss);\n\n\treturn 0;\n\t\t\n}"} {"title": "First perfect square in base n with n unique digits", "language": "C", "task": "Find the first perfect square in a given base '''N''' that has at least '''N''' digits and\nexactly '''N''' ''significant unique'' digits when expressed in base '''N'''.\n\nE.G. In base '''10''', the first perfect square with at least '''10''' unique digits is '''1026753849''' ('''320432''').\n\nYou may use analytical methods to reduce the search space, but the code must do a search. Do not use magic numbers or just feed the code the answer to verify it is correct.\n\n;Task\n\n* Find and display here, on this page, the first perfect square in base '''N''', with '''N''' significant unique digits when expressed in base '''N''', for each of base '''2''' through '''12'''. Display each number in the base '''N''' for which it was calculated.\n\n* (optional) Do the same for bases '''13''' through '''16'''.\n\n* (stretch goal) Continue on for bases '''17''' - '''??''' (Big Integer math)\n\n\n;See also:\n\n;* OEIS A260182: smallest square that is pandigital in base n.\n\n;Related task\n\n;* [[Casting out nines]]\n\n", "solution": "#include \n#include \n\n#define BUFF_SIZE 32\n\nvoid toBaseN(char buffer[], long long num, int base) {\n char *ptr = buffer;\n char *tmp;\n\n // write it backwards\n while (num >= 1) {\n int rem = num % base;\n num /= base;\n\n *ptr++ = \"0123456789ABCDEF\"[rem];\n }\n *ptr-- = 0;\n\n // now reverse it to be written forwards\n for (tmp = buffer; tmp < ptr; tmp++, ptr--) {\n char c = *tmp;\n *tmp = *ptr;\n *ptr = c;\n }\n}\n\nint countUnique(char inBuf[]) {\n char buffer[BUFF_SIZE];\n int count = 0;\n int pos, nxt;\n\n strcpy_s(buffer, BUFF_SIZE, inBuf);\n\n for (pos = 0; buffer[pos] != 0; pos++) {\n if (buffer[pos] != 1) {\n count++;\n for (nxt = pos + 1; buffer[nxt] != 0; nxt++) {\n if (buffer[nxt] == buffer[pos]) {\n buffer[nxt] = 1;\n }\n }\n }\n }\n\n return count;\n}\n\nvoid find(int base) {\n char nBuf[BUFF_SIZE];\n char sqBuf[BUFF_SIZE];\n long long n, s;\n\n for (n = 2; /*blank*/; n++) {\n s = n * n;\n toBaseN(sqBuf, s, base);\n if (strlen(sqBuf) >= base && countUnique(sqBuf) == base) {\n toBaseN(nBuf, n, base);\n toBaseN(sqBuf, s, base);\n //printf(\"Base %d : Num %lld Square %lld\\n\", base, n, s);\n printf(\"Base %d : Num %8s Square %16s\\n\", base, nBuf, sqBuf);\n break;\n }\n }\n}\n\nint main() {\n int i;\n\n for (i = 2; i <= 15; i++) {\n find(i);\n }\n\n return 0;\n}"} {"title": "Flatten a list", "language": "C", "task": "Write a function to flatten the nesting in an arbitrary list of values. \n\nYour program should work on the equivalent of this list:\n [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]\nWhere the correct result would be the list:\n [1, 2, 3, 4, 5, 6, 7, 8]\n\n;Related task:\n* [[Tree traversal]]\n\n", "solution": "#include \n#include \n#include \n\ntypedef struct list_t list_t, *list;\nstruct list_t{\n\tint is_list, ival; /* ival is either the integer value or list length */\n\tlist *lst;\n};\n\nlist new_list()\n{\n\tlist x = malloc(sizeof(list_t));\n\tx->ival = 0;\n\tx->is_list = 1;\n\tx->lst = 0;\n\treturn x;\n}\n\nvoid append(list parent, list child)\n{\n\tparent->lst = realloc(parent->lst, sizeof(list) * (parent->ival + 1));\n\tparent->lst[parent->ival++] = child;\n}\n\nlist from_string(char *s, char **e, list parent)\n{\n\tlist ret = 0;\n\tif (!parent) parent = new_list();\n\n\twhile (*s != '\\0') {\n\t\tif (*s == ']') {\n\t\t\tif (e) *e = s + 1;\n\t\t\treturn parent;\n\t\t}\n\t\tif (*s == '[') {\n\t\t\tret = new_list();\n\t\t\tret->is_list = 1;\n\t\t\tret->ival = 0;\n\t\t\tappend(parent, ret);\n\t\t\tfrom_string(s + 1, &s, ret);\n\t\t\tcontinue;\n\t\t}\n\t\tif (*s >= '0' && *s <= '9') {\n\t\t\tret = new_list();\n\t\t\tret->is_list = 0;\n\t\t\tret->ival = strtol(s, &s, 10);\n\t\t\tappend(parent, ret);\n\t\t\tcontinue;\n\t\t}\n\t\ts++;\n\t}\n\n\tif (e) *e = s;\n\treturn parent;\n}\n\nvoid show_list(list l)\n{\n\tint i;\n\tif (!l) return;\n\tif (!l->is_list) {\n\t\tprintf(\"%d\", l->ival);\n\t\treturn;\n\t}\n\n\tprintf(\"[\");\n\tfor (i = 0; i < l->ival; i++) {\n\t\tshow_list(l->lst[i]);\n\t\tif (i < l->ival - 1) printf(\", \");\n\t}\n\tprintf(\"]\");\n}\n\nlist flatten(list from, list to)\n{\n\tint i;\n\tlist t;\n\n\tif (!to) to = new_list();\n\tif (!from->is_list) {\n\t\tt = new_list();\n\t\t*t = *from;\n\t\tappend(to, t);\n\t} else\n\t\tfor (i = 0; i < from->ival; i++)\n\t\t\tflatten(from->lst[i], to);\n\treturn to;\n}\n\nvoid delete_list(list l)\n{\n\tint i;\n\tif (!l) return;\n\tif (l->is_list && l->ival) {\n\t\tfor (i = 0; i < l->ival; i++)\n\t\t\tdelete_list(l->lst[i]);\n\t\tfree(l->lst);\n\t}\n\n\tfree(l);\n}\n\nint main()\n{\n\tlist l = from_string(\"[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []\", 0, 0);\n\n\tprintf(\"Nested: \");\n\tshow_list(l);\n\tprintf(\"\\n\");\n\n\tlist flat = flatten(l, 0);\n\tprintf(\"Flattened: \");\n\tshow_list(flat);\n\n\t/* delete_list(l); delete_list(flat); */\n\treturn 0;\n}"} {"title": "Flipping bits game", "language": "C", "task": "The game:\nGiven an '''NxN''' square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.\n\n\nThe game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered \ncolumns at once (as one move).\n\nIn an inversion. any '''1''' becomes '''0''', and any '''0''' becomes '''1''' for that whole row or column.\n\n\n;Task:\nCreate a program to score for the Flipping bits game.\n# The game should create an original random target configuration and a starting configuration.\n# Ensure that the starting position is ''never'' the target position.\n# The target position must be guaranteed as reachable from the starting position. (One possible way to do this is to generate the start position by legal flips from a random target position. The flips will always be reversible back to the target from the given start position).\n# The number of moves taken so far should be shown.\n\n\nShow an example of a short game here, on this page, for a '''3x3''' array of bits.\n\n", "solution": "#include \n#include \n\nint i, j;\n\nvoid fliprow(int **b, int sz, int n)\n{\n\tfor(i = 0; i < sz; i++)\n\t\tb[n+1][i] = !b[n+1][i];\n}\n\nvoid flipcol(int **b, int sz, int n)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i][n] = !b[i][n];\n}\n\nvoid initt(int **t, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tt[i][j] = rand()%2;\n}\n\nvoid initb(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tb[i][j] = t[i][j];\n\t\n\tfor(i = 1; i <= sz; i++)\n\t\tfliprow(b, sz, rand()%sz+1);\n\tfor(i = 0; i < sz; i++)\n\t\tflipcol(b, sz, rand()%sz);\n}\n\nvoid printb(int **b, int sz)\n{\n\tprintf(\" \");\n\tfor(i = 0; i < sz; i++)\n\t\tprintf(\" %d\", i);\n\tprintf(\"\\n\");\n\n\tfor(i = 1; i <= sz; i++)\n\t{\n\t\tprintf(\"%d\", i-1);\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tprintf(\" %d\", b[i][j]);\n\t\tprintf(\"\\n\");\n\t}\n\t\n\tprintf(\"\\n\");\n}\n\nint eq(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tif(b[i][j] != t[i][j])\n\t\t\t\treturn 0;\n\treturn 1;\n}\n\nvoid main()\n{\n\tint sz = 3;\n\tint eql = 0;\n\tint mov = 0;\n\tint **t = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tt[i] = malloc(sz*sizeof(int));\n\n\tint **b = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i] = malloc(sz*sizeof(int));\n\tchar roc;\n\tint n;\n\tinitt(t, sz);\n\tinitb(t, b, sz);\n\t\n\twhile(eq(t, b, sz))\n\t\tinitb(t, b, sz);\n\t\n\twhile(!eql)\n\t{\n\t\tprintf(\"Target: \\n\");\n\t\tprintb(t, sz);\n\t\tprintf(\"Board: \\n\");\n\t\tprintb(b, sz);\n\t\tprintf(\"What to flip: \");\n\t\tscanf(\" %c\", &roc);\n\t\tscanf(\" %d\", &n);\n\n\t\tswitch(roc)\n\t\t{\n\t\t\tcase 'r':\n\t\t\t\tfliprow(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tcase 'c':\n\t\t\t\tflipcol(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tperror(\"Please specify r or c and an number\");\n\t\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"Moves Taken: %d\\n\", ++mov);\n\n\t\tif(eq(t, b, sz))\n\t\t{\n\t\t\tprintf(\"You win!\\n\");\n\t\t\teql = 1;\n\t\t}\n\t}\n}\n"} {"title": "Floyd's triangle", "language": "C", "task": "Floyd's triangle lists the natural numbers in a right triangle aligned to the left where \n* the first row is '''1''' (unity)\n* successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.\n\n\nThe first few lines of a Floyd triangle looks like this:\n\n 1\n 2 3\n 4 5 6\n 7 8 9 10\n11 12 13 14 15\n\n\n\n;Task:\n:# Write a program to generate and display here the first n lines of a Floyd triangle. (Use n=5 and n=14 rows).\n:# Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.\n\n", "solution": "#include \n\nvoid t(int n)\n{\n\tint i, j, c, len;\n\n\ti = n * (n - 1) / 2;\n\tfor (len = c = 1; c < i; c *= 10, len++);\n\tc -= i; // c is the col where width changes\n\n#define SPEED_MATTERS 0\n#if SPEED_MATTERS\t// in case we really, really wanted to print huge triangles often\n\tchar tmp[32], s[4096], *p;\n\n\tsprintf(tmp, \"%*d\", len, 0);\n\n\tinline void inc_numstr(void) {\n\t\tint k = len;\n\n\tredo:\tif (!k--) return;\n\n\t\tif (tmp[k] == '9') {\n\t\t\ttmp[k] = '0';\n\t\t\tgoto redo;\n\t\t}\n\n\t\tif (++tmp[k] == '!')\n\t\t\ttmp[k] = '1';\n\t}\n\n\tfor (p = s, i = 1; i <= n; i++) {\n\t\tfor (j = 1; j <= i; j++) {\n\t\t\tinc_numstr();\n\t\t\t__builtin_memcpy(p, tmp + 1 - (j >= c), len - (j < c));\n\t\t\tp += len - (j < c);\n\n\t\t\t*(p++) = (i - j)? ' ' : '\\n';\n\n\t\t\tif (p - s + len >= 4096) {\n\t\t\t\tfwrite(s, 1, p - s, stdout);\n\t\t\t\tp = s;\n\t\t\t}\n\t\t}\n\t}\n\n\tfwrite(s, 1, p - s, stdout);\n#else // NO_IT_DOESN'T\n\tint num;\n\tfor (num = i = 1; i <= n; i++)\n\t\tfor (j = 1; j <= i; j++)\n\t\t\tprintf(\"%*d%c\",\tlen - (j < c), num++, i - j ? ' ':'\\n');\n#endif\n}\n\nint main(void)\n{\n\tt(5), t(14);\n\n\t// maybe not \n\t// t(10000);\n\treturn 0;\n}"} {"title": "Four bit adder", "language": "C", "task": "\"''Simulate''\" a four-bit adder.\n \nThis design can be realized using four 1-bit full adders. \nEach of these 1-bit full adders can be built with two gate. ; \n\nFinally a half adder can be made using an ''xor'' gate and an ''and'' gate. \n\nThe ''xor'' gate can be made using two ''not''s, two ''and''s and one ''or''.\n\n'''Not''', '''or''' and '''and''', the only allowed \"gates\" for the task, can be \"imitated\" by using the bitwise operators of your language. \n\nIf there is not a ''bit type'' in your language, to be sure that the ''not'' does not \"invert\" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra ''nand'' (''and'' then ''not'') with the constant '''1''' on one input.\n\nInstead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, ''connecting'' the other \"constructive blocks\", in turn made of \"simpler\" and \"smaller\" ones.\n\n{|\n|+Schematics of the \"constructive blocks\"\n!(Xor gate with ANDs, ORs and NOTs) \n! (A half adder) \n! (A full adder) \n! (A 4-bit adder) \n|-\n|Xor gate done with ands, ors and nots\n|A half adder\n|A full adder\n|A 4-bit adder\n|}\n\n\n\nSolutions should try to be as descriptive as possible, making it as easy as possible to identify \"connections\" between higher-order \"blocks\". \n\nIt is not mandatory to replicate the syntax of higher-order blocks in the atomic \"gate\" blocks, i.e. basic \"gate\" operations can be performed as usual bitwise operations, or they can be \"wrapped\" in a ''block'' in order to expose the same syntax of higher-order blocks, at implementers' choice.\n\nTo test the implementation, show the sum of two four-bit numbers (in binary).\n\n\n", "solution": "#include \n\ntypedef char pin_t;\n#define IN const pin_t *\n#define OUT pin_t *\n#define PIN(X) pin_t _##X; pin_t *X = & _##X;\n#define V(X) (*(X))\n\n/* a NOT that does not soil the rest of the host of the single bit */\n#define NOT(X) (~(X)&1)\n\n/* a shortcut to \"implement\" a XOR using only NOT, AND and OR gates, as\n task requirements constrain */\n#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))\n\nvoid halfadder(IN a, IN b, OUT s, OUT c)\n{\n V(s) = XOR(V(a), V(b));\n V(c) = V(a) & V(b);\n}\n\nvoid fulladder(IN a, IN b, IN ic, OUT s, OUT oc)\n{\n PIN(ps); PIN(pc); PIN(tc);\n\n halfadder(/*INPUT*/a, b, /*OUTPUT*/ps, pc);\n halfadder(/*INPUT*/ps, ic, /*OUTPUT*/s, tc);\n V(oc) = V(tc) | V(pc);\n}\n\nvoid fourbitsadder(IN a0, IN a1, IN a2, IN a3,\n\t\t IN b0, IN b1, IN b2, IN b3,\n\t\t OUT o0, OUT o1, OUT o2, OUT o3,\n\t\t OUT overflow)\n{\n PIN(zero); V(zero) = 0;\n PIN(tc0); PIN(tc1); PIN(tc2);\n\n fulladder(/*INPUT*/a0, b0, zero, /*OUTPUT*/o0, tc0);\n fulladder(/*INPUT*/a1, b1, tc0, /*OUTPUT*/o1, tc1);\n fulladder(/*INPUT*/a2, b2, tc1, /*OUTPUT*/o2, tc2);\n fulladder(/*INPUT*/a3, b3, tc2, /*OUTPUT*/o3, overflow);\n}\n\n\nint main()\n{\n PIN(a0); PIN(a1); PIN(a2); PIN(a3);\n PIN(b0); PIN(b1); PIN(b2); PIN(b3);\n PIN(s0); PIN(s1); PIN(s2); PIN(s3);\n PIN(overflow);\n\n V(a3) = 0; V(b3) = 1;\n V(a2) = 0; V(b2) = 1;\n V(a1) = 1; V(b1) = 1;\n V(a0) = 0; V(b0) = 0;\n\n fourbitsadder(a0, a1, a2, a3, /* INPUT */\n\t\tb0, b1, b2, b3,\n\t\ts0, s1, s2, s3, /* OUTPUT */\n\t\toverflow);\n\n printf(\"%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\\n\",\n\t V(a3), V(a2), V(a1), V(a0),\n\t V(b3), V(b2), V(b1), V(b0),\n\t V(s3), V(s2), V(s1), V(s0),\n\t V(overflow));\n \n return 0;\n}"} {"title": "Function prototype", "language": "C", "task": "Some languages provide the facility to declare functions and subroutines through the use of function prototyping. \n\n\n;Task:\nDemonstrate the methods available for declaring prototypes within the language. The provided solutions should include:\n\n* An explanation of any placement restrictions for prototype declarations\n* A prototype declaration for a function that does not require arguments\n* A prototype declaration for a function that requires two arguments\n* A prototype declaration for a function that utilizes varargs\n* A prototype declaration for a function that utilizes optional arguments\n* A prototype declaration for a function that utilizes named parameters\n* Example of prototype declarations for subroutines or procedures (if these differ from functions)\n* An explanation and example of any special forms of prototyping not covered by the above\n\n\nLanguages that do not provide function prototyping facilities should be omitted from this task.\n\n", "solution": "int noargs(void); /* Declare a function with no argument that returns an integer */\nint twoargs(int a,int b); /* Declare a function with two arguments that returns an integer */\nint twoargs(int ,int); /* Parameter names are optional in a prototype definition */\nint anyargs(); /* An empty parameter list can be used to declare a function that accepts varargs */\nint atleastoneargs(int, ...); /* One mandatory integer argument followed by varargs */"} {"title": "Fusc sequence", "language": "C", "task": "Definitions:\nThe '''fusc''' integer sequence is defined as:\n::* fusc(0) = 0\n::* fusc(1) = 1\n::* for '''n'''>1, the '''n'''th term is defined as:\n::::* if '''n''' is even; fusc(n) = fusc(n/2)\n::::* if '''n''' is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)\n\n\nNote that MathWorld's definition starts with unity, not zero. This task will be using the OEIS' version (above).\n\n\n\n;An observation:\n:::::* fusc(A) = fusc(B)\n\nwhere '''A''' is some non-negative integer expressed in binary, and\nwhere '''B''' is the binary value of '''A''' reversed.\n\n\n\nFusc numbers are also known as:\n::* fusc function (named by Dijkstra, 1982)\n::* Stern's Diatomic series (although it starts with unity, not zero)\n::* Stern-Brocot sequence (although it starts with unity, not zero)\n\n\n\n;Task:\n::* show the first '''61''' fusc numbers (starting at zero) in a horizontal format.\n::* show the fusc number (and its index) whose length is greater than any previous fusc number length.\n::::* (the length is the number of decimal digits when the fusc number is expressed in base ten.)\n::* show all numbers with commas (if appropriate).\n::* show all output here.\n\n\n;Related task:\n::* RosettaCode Stern-Brocot sequence\n\n\n\n;Also see:\n::* the MathWorld entry: Stern's Diatomic Series.\n::* the OEIS entry: A2487.\n\n", "solution": "#include\n#include\n\nint fusc(int n){\n if(n==0||n==1)\n return n;\n else if(n%2==0)\n return fusc(n/2);\n else\n return fusc((n-1)/2) + fusc((n+1)/2);\n}\n\nint numLen(int n){\n int sum = 1;\n\n while(n>9){\n n = n/10;\n sum++;\n }\n\n return sum;\n}\n\nvoid printLargeFuscs(int limit){\n int i,f,len,maxLen = 1;\n\n printf(\"\\n\\nPrinting all largest Fusc numbers upto %d \\nIndex-------Value\",limit);\n\n for(i=0;i<=limit;i++){\n f = fusc(i);\n len = numLen(f);\n\n if(len>maxLen){\n maxLen = len;\n printf(\"\\n%5d%12d\",i,f);\n }\n }\n}\n\n\nint main()\n{\n int i;\n\n printf(\"Index-------Value\");\n for(i=0;i<61;i++)\n printf(\"\\n%5d%12d\",i,fusc(i));\n printLargeFuscs(INT_MAX);\n return 0;\n}\n"} {"title": "Gapful numbers", "language": "C", "task": "Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the\nfirst and last digit are known as '''gapful numbers'''.\n\n\n''Evenly divisible'' means divisible with no remainder.\n\n\nAll one- and two-digit numbers have this property and are trivially excluded. Only\nnumbers >= '''100''' will be considered for this Rosetta Code task.\n\n\n;Example:\n'''187''' is a '''gapful''' number because it is evenly divisible by the\nnumber '''17''' which is formed by the first and last decimal digits\nof '''187'''. \n\n\nAbout 7.46% of positive integers are ''gapful''. \n\n\n;Task:\n:* Generate and show all sets of numbers (below) on one line (horizontally) with a title, here on this page\n:* Show the first '''30''' gapful numbers\n:* Show the first '''15''' gapful numbers >= '''1,000,000'''\n:* Show the first '''10''' gapful numbers >= '''1,000,000,000'''\n\n\n;Related tasks:\n:* Harshad or Niven series.\n:* palindromic gapful numbers.\n:* largest number divisible by its digits.\n\n\n;Also see:\n:* The OEIS entry: A108343 gapful numbers.\n:* numbersaplenty gapful numbers\n\n", "solution": "#include\n\nvoid generateGaps(unsigned long long int start,int count){\n \n int counter = 0;\n unsigned long long int i = start;\n char str[100];\n \n printf(\"\\nFirst %d Gapful numbers >= %llu :\\n\",count,start);\n\n while(counter\n#include \n#include \n\n#define mat_elem(a, y, x, n) (a + ((y) * (n) + (x)))\n\nvoid swap_row(double *a, double *b, int r1, int r2, int n)\n{\n\tdouble tmp, *p1, *p2;\n\tint i;\n\n\tif (r1 == r2) return;\n\tfor (i = 0; i < n; i++) {\n\t\tp1 = mat_elem(a, r1, i, n);\n\t\tp2 = mat_elem(a, r2, i, n);\n\t\ttmp = *p1, *p1 = *p2, *p2 = tmp;\n\t}\n\ttmp = b[r1], b[r1] = b[r2], b[r2] = tmp;\n}\n\nvoid gauss_eliminate(double *a, double *b, double *x, int n)\n{\n#define A(y, x) (*mat_elem(a, y, x, n))\n\tint i, j, col, row, max_row,dia;\n\tdouble max, tmp;\n\n\tfor (dia = 0; dia < n; dia++) {\n\t\tmax_row = dia, max = A(dia, dia);\n\n\t\tfor (row = dia + 1; row < n; row++)\n\t\t\tif ((tmp = fabs(A(row, dia))) > max)\n\t\t\t\tmax_row = row, max = tmp;\n\n\t\tswap_row(a, b, dia, max_row, n);\n\n\t\tfor (row = dia + 1; row < n; row++) {\n\t\t\ttmp = A(row, dia) / A(dia, dia);\n\t\t\tfor (col = dia+1; col < n; col++)\n\t\t\t\tA(row, col) -= tmp * A(dia, col);\n\t\t\tA(row, dia) = 0;\n\t\t\tb[row] -= tmp * b[dia];\n\t\t}\n\t}\n\tfor (row = n - 1; row >= 0; row--) {\n\t\ttmp = b[row];\n\t\tfor (j = n - 1; j > row; j--)\n\t\t\ttmp -= x[j] * A(row, j);\n\t\tx[row] = tmp / A(row, row);\n\t}\n#undef A\n}\n\nint main(void)\n{\n\tdouble a[] = {\n\t\t1.00, 0.00, 0.00, 0.00, 0.00, 0.00,\n\t\t1.00, 0.63, 0.39, 0.25, 0.16, 0.10,\n\t\t1.00, 1.26, 1.58, 1.98, 2.49, 3.13,\n\t\t1.00, 1.88, 3.55, 6.70, 12.62, 23.80,\n\t\t1.00, 2.51, 6.32, 15.88, 39.90, 100.28,\n\t\t1.00, 3.14, 9.87, 31.01, 97.41, 306.02\n\t};\n\tdouble b[] = { -0.01, 0.61, 0.91, 0.99, 0.60, 0.02 };\n\tdouble x[6];\n\tint i;\n\n\tgauss_eliminate(a, b, x, 6);\n\n\tfor (i = 0; i < 6; i++)\n\t\tprintf(\"%g\\n\", x[i]);\n\n\treturn 0;\n}"} {"title": "Generate Chess960 starting position", "language": "C", "task": "Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:\n\n* as in the standard chess game, all eight white pawns must be placed on the second rank.\n* White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:\n** the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)\n** the King must be between two rooks (with any number of other pieces between them all)\n* Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)\n\n\nWith those constraints there are '''960''' possible starting positions, thus the name of the variant.\n\n\n;Task:\nThe purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: or with the letters '''K'''ing '''Q'''ueen '''R'''ook '''B'''ishop k'''N'''ight.\n\n", "solution": "#include\n#include\n#include\n#include\n#include\n\nchar rank[9];\n\nint pos[8];\n\nvoid swap(int i,int j){\n\tint temp = pos[i];\n\tpos[i] = pos[j];\n\tpos[j] = temp;\n}\n\nvoid generateFirstRank(){\n\t int kPos,qPos,bPos1,bPos2,rPos1,rPos2,nPos1,nPos2,i;\n\t \n\t for(i=0;i<8;i++){\n\t\t rank[i] = 'e';\n\t\t pos[i] = i;\n\t }\n\t\t \n\t do{\n\t\t kPos = rand()%8;\n\t\t rPos1 = rand()%8;\n\t\t rPos2 = rand()%8;\n\t }while((rPos1-kPos<=0 && rPos2-kPos<=0)||(rPos1-kPos>=0 && rPos2-kPos>=0)||(rPos1==rPos2 || kPos==rPos1 || kPos==rPos2));\n\n\t rank[pos[rPos1]] = 'R';\n\t rank[pos[kPos]] = 'K';\n\t rank[pos[rPos2]] = 'R';\n\t \n\t swap(rPos1,7);\n\t swap(rPos2,6);\n\t swap(kPos,5);\n\t \n\t do{\n\t\t bPos1 = rand()%5;\n\t\t bPos2 = rand()%5;\n\t }while(((pos[bPos1]-pos[bPos2])%2==0)||(bPos1==bPos2));\n\n\t rank[pos[bPos1]] = 'B';\n\t rank[pos[bPos2]] = 'B';\n\t \n\t swap(bPos1,4);\n\t swap(bPos2,3);\n\t \n\t do{\n\t\t qPos = rand()%3;\n\t\t nPos1 = rand()%3;\n\t }while(qPos==nPos1);\n\t \n\t rank[pos[qPos]] = 'Q';\n\t rank[pos[nPos1]] = 'N';\n\t \n\t for(i=0;i<8;i++)\n\t\t if(rank[i]=='e'){\n\t\t\t rank[i] = 'N';\n\t\t\t break;\n\t\t }\t\t\n}\n\nvoid printRank(){\n\tint i;\n\t\n\t#ifdef _WIN32\n\t\tprintf(\"%s\\n\",rank);\n\t#else\n\t{\n\t\tsetlocale(LC_ALL,\"\");\n\t\tprintf(\"\\n\");\n\t\tfor(i=0;i<8;i++){\n\t\t\tif(rank[i]=='K')\n\t\t\t\tprintf(\"%lc\",(wint_t)9812);\n\t\t\telse if(rank[i]=='Q')\n\t\t\t\tprintf(\"%lc\",(wint_t)9813);\n\t\t\telse if(rank[i]=='R')\n\t\t\t\tprintf(\"%lc\",(wint_t)9814);\n\t\t\telse if(rank[i]=='B')\n\t\t\t\tprintf(\"%lc\",(wint_t)9815);\n\t\t\tif(rank[i]=='N')\n\t\t\t\tprintf(\"%lc\",(wint_t)9816);\n\t\t}\n\t}\n\t#endif\n}\n\nint main()\n{\n\tint i;\n\t\n\tsrand((unsigned)time(NULL));\n\t\n\tfor(i=0;i<9;i++){\n\t\tgenerateFirstRank();\n\t\tprintRank();\n\t}\n\t\n\treturn 0;\n}\n"} {"title": "Generator/Exponential", "language": "C", "task": "A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.\n \nGenerators are often built on top of coroutines or objects so that the internal state of the object is handled \"naturally\". \n\nGenerators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.\n\n\n;Task:\n* Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).\n* Use it to create a generator of:\n:::* Squares.\n:::* Cubes. \n* Create a new generator that filters all cubes from the generator of squares.\n* Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.\n\n\nNote that this task ''requires'' the use of generators in the calculation of the result.\n\n\n;Also see:\n* Generator\n\n", "solution": "#include \t/* int64_t, PRId64 */\n#include \t/* exit() */\n#include \t/* printf() */\n\n#include \t/* co_{active,create,delete,switch}() */\n\n\n\n/* A generator that yields values of type int64_t. */\nstruct gen64 {\n\tcothread_t giver;\t/* this cothread calls yield64() */\n\tcothread_t taker;\t/* this cothread calls next64() */\n\tint64_t given;\n\tvoid (*free)(struct gen64 *);\n\tvoid *garbage;\n};\n\n/* Yields a value. */\ninline void\nyield64(struct gen64 *gen, int64_t value)\n{\n\tgen->given = value;\n\tco_switch(gen->taker);\n}\n\n/* Returns the next value that the generator yields. */\ninline int64_t\nnext64(struct gen64 *gen)\n{\n\tgen->taker = co_active();\n\tco_switch(gen->giver);\n\treturn gen->given;\n}\n\nstatic void\ngen64_free(struct gen64 *gen)\n{\n\tco_delete(gen->giver);\n}\n\nstruct gen64 *entry64;\n\n/*\n * Creates a cothread for the generator. The first call to next64(gen)\n * will enter the cothread; the entry function must copy the pointer\n * from the global variable struct gen64 *entry64.\n *\n * Use gen->free(gen) to free the cothread.\n */\ninline void\ngen64_init(struct gen64 *gen, void (*entry)(void))\n{\n\tif ((gen->giver = co_create(4096, entry)) == NULL) {\n\t\t/* Perhaps malloc() failed */\n\t\tfputs(\"co_create: Cannot create cothread\\n\", stderr);\n\t\texit(1);\n\t}\n\tgen->free = gen64_free;\n\tentry64 = gen;\n}\n\n\n\n/*\n * Generates the powers 0**m, 1**m, 2**m, ....\n */\nvoid\npowers(struct gen64 *gen, int64_t m)\n{\n\tint64_t base, exponent, n, result;\n\n\tfor (n = 0;; n++) {\n\t\t/*\n\t\t * This computes result = base**exponent, where\n\t\t * exponent is a nonnegative integer. The result\n\t\t * is the product of repeated squares of base.\n\t\t */\n\t\tbase = n;\n\t\texponent = m;\n\t\tfor (result = 1; exponent != 0; exponent >>= 1) {\n\t\t\tif (exponent & 1) result *= base;\n\t\t\tbase *= base;\n\t\t}\n\t\tyield64(gen, result);\n\t}\n\t/* NOTREACHED */\n}\n\n/* stuff for squares_without_cubes() */\n#define ENTRY(name, code) static void name(void) { code; }\nENTRY(enter_squares, powers(entry64, 2))\nENTRY(enter_cubes, powers(entry64, 3))\n\nstruct swc {\n\tstruct gen64 cubes;\n\tstruct gen64 squares;\n\tvoid (*old_free)(struct gen64 *);\n};\n\nstatic void\nswc_free(struct gen64 *gen)\n{\n\tstruct swc *f = gen->garbage;\n\tf->cubes.free(&f->cubes);\n\tf->squares.free(&f->squares);\n\tf->old_free(gen);\n}\n\n/*\n * Generates the squares 0**2, 1**2, 2**2, ..., but removes the squares\n * that equal the cubes 0**3, 1**3, 2**3, ....\n */\nvoid\nsquares_without_cubes(struct gen64 *gen)\n{\n\tstruct swc f;\n\tint64_t c, s;\n\n\tgen64_init(&f.cubes, enter_cubes);\n\tc = next64(&f.cubes);\n\n\tgen64_init(&f.squares, enter_squares);\n\ts = next64(&f.squares);\n\n\t/* Allow other cothread to free this generator. */\n\tf.old_free = gen->free;\n\tgen->garbage = &f;\n\tgen->free = swc_free;\n\n\tfor (;;) {\n\t\twhile (c < s)\n\t\t\tc = next64(&f.cubes);\n\t\tif (c != s)\n\t\t\tyield64(gen, s);\n\t\ts = next64(&f.squares);\n\t}\n\t/* NOTREACHED */\n}\n\nENTRY(enter_squares_without_cubes, squares_without_cubes(entry64))\n\n/*\n * Look at the sequence of numbers that are squares but not cubes.\n * Drop the first 20 numbers, then print the next 10 numbers.\n */\nint\nmain()\n{\n\tstruct gen64 gen;\n\tint i;\n\n\tgen64_init(&gen, enter_squares_without_cubes);\n\n\tfor (i = 0; i < 20; i++)\n\t\tnext64(&gen);\n\tfor (i = 0; i < 9; i++)\n\t\tprintf(\"%\" PRId64 \", \", next64(&gen));\n\tprintf(\"%\" PRId64 \"\\n\", next64(&gen));\n\n\tgen.free(&gen); /* Free memory. */\n\treturn 0;\n}"} {"title": "Get system command output", "language": "C", "task": "Task\nExecute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). \n\n;Related task\n* Execute a system command\n\n", "solution": "#include \n#include \n#include \n\nint main(int argc, char **argv)\n{\n if (argc < 2) return 1;\n\n FILE *fd;\n fd = popen(argv[1], \"r\");\n if (!fd) return 1;\n\n char buffer[256];\n size_t chread;\n /* String to store entire command contents in */\n size_t comalloc = 256;\n size_t comlen = 0;\n char *comout = malloc(comalloc);\n\n /* Use fread so binary data is dealt with correctly */\n while ((chread = fread(buffer, 1, sizeof(buffer), fd)) != 0) {\n if (comlen + chread >= comalloc) {\n comalloc *= 2;\n comout = realloc(comout, comalloc);\n }\n memmove(comout + comlen, buffer, chread);\n comlen += chread;\n }\n\n /* We can now work with the output as we please. Just print\n * out to confirm output is as expected */\n fwrite(comout, 1, comlen, stdout);\n free(comout);\n pclose(fd);\n return 0;\n}\n"} {"title": "Globally replace text in several files", "language": "C", "task": "Replace every occurring instance of a piece of text in a group of text files with another one. \n\n\nFor this task we want to replace the text \"'''Goodbye London!'''\" with \"'''Hello New York!'''\" for a list of files.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nchar * find_match(const char *buf, const char * buf_end, const char *pat, size_t len)\n{\n\tptrdiff_t i;\n\tchar *start = buf;\n\twhile (start + len < buf_end) {\n\t\tfor (i = 0; i < len; i++)\n\t\t\tif (start[i] != pat[i]) break;\n\n\t\tif (i == len) return (char *)start;\n\t\tstart++;\n\t}\n\treturn 0;\n}\n\nint replace(const char *from, const char *to, const char *fname)\n{\n#define bail(msg) { warn(msg\" '%s'\", fname); goto done; }\n\tstruct stat st;\n\tint ret = 0;\n\tchar *buf = 0, *start, *end;\n\tsize_t len = strlen(from), nlen = strlen(to);\n\tint fd = open(fname, O_RDWR);\n\n\tif (fd == -1) bail(\"Can't open\");\n\tif (fstat(fd, &st) == -1) bail(\"Can't stat\");\n\tif (!(buf = malloc(st.st_size))) bail(\"Can't alloc\");\n\tif (read(fd, buf, st.st_size) != st.st_size) bail(\"Bad read\");\n\n\tstart = buf;\n\tend = find_match(start, buf + st.st_size, from, len);\n\tif (!end) goto done; /* no match found, don't change file */\n\n\tftruncate(fd, 0);\n\tlseek(fd, 0, 0);\n\tdo {\n\t\twrite(fd, start, end - start);\t/* write content before match */\n\t\twrite(fd, to, nlen);\t\t/* write replacement of match */\n\t\tstart = end + len;\t\t/* skip to end of match */\n\t\t\t\t\t\t/* find match again */\n\t\tend = find_match(start, buf + st.st_size, from, len);\n\t} while (end);\n\n\t/* write leftover after last match */\n\tif (start < buf + st.st_size)\n\t\twrite(fd, start, buf + st.st_size - start);\n\ndone:\n\tif (fd != -1) close(fd);\n\tif (buf) free(buf);\n\treturn ret;\n}\n\nint main()\n{\n\tconst char *from = \"Goodbye, London!\";\n\tconst char *to = \"Hello, New York!\";\n\tconst char * files[] = { \"test1.txt\", \"test2.txt\", \"test3.txt\" };\n\tint i;\n\n\tfor (i = 0; i < sizeof(files)/sizeof(char*); i++)\n\t\treplace(from, to, files[i]);\n\n\treturn 0;\n}"} {"title": "Gotchas", "language": "C", "task": "Definition\nIn programming, a '''gotcha''' is a valid construct in a system, program or programming language that works as documented but is counter-intuitive and almost invites mistakes because it is both easy to invoke and unexpected or unreasonable in its outcome.\n\n;Task\nGive an example or examples of common gotchas in your programming language and what, if anything, can be done to defend against it or them without using special tools.\n\n", "solution": "if(a=b){} //assigns to \"a\" the value of \"b\". Then, if \"a\" is nonzero, the code in the curly braces is run.\n\nif(a==b){} //runs the code in the curly braces if and only if the value of \"a\" equals the value of \"b\"."} {"title": "Greatest subsequential sum", "language": "C", "task": "Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. \n\n\nAn empty subsequence is considered to have the sum of '''0'''; thus if all elements are negative, the result must be the empty sequence.\n\n", "solution": "#include \"stdio.h\"\n\ntypedef struct Range {\n int start, end, sum;\n} Range;\n\nRange maxSubseq(const int sequence[], const int len) {\n int maxSum = 0, thisSum = 0, i = 0;\n int start = 0, end = -1, j;\n\n for (j = 0; j < len; j++) {\n thisSum += sequence[j];\n if (thisSum < 0) {\n i = j + 1;\n thisSum = 0;\n } else if (thisSum > maxSum) {\n maxSum = thisSum;\n start = i;\n end = j;\n }\n }\n\n Range r;\n if (start <= end && start >= 0 && end >= 0) {\n r.start = start;\n r.end = end + 1;\n r.sum = maxSum;\n } else {\n r.start = 0;\n r.end = 0;\n r.sum = 0;\n }\n return r;\n}\n\nint main(int argc, char **argv) {\n int a[] = {-1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1};\n int alength = sizeof(a)/sizeof(a[0]);\n\n Range r = maxSubseq(a, alength);\n printf(\"Max sum = %d\\n\", r.sum);\n int i;\n for (i = r.start; i < r.end; i++)\n printf(\"%d \", a[i]);\n printf(\"\\n\");\n\n return 0;\n}"} {"title": "Greedy algorithm for Egyptian fractions", "language": "C", "task": "An Egyptian fraction is the sum of distinct unit fractions such as: \n\n:::: \\tfrac{1}{2} + \\tfrac{1}{3} + \\tfrac{1}{16} \\,(= \\tfrac{43}{48}) \n\nEach fraction in the expression has a numerator equal to '''1''' (unity) and a denominator that is a positive integer, and all the denominators are distinct (i.e., no repetitions). \n\nFibonacci's Greedy algorithm for Egyptian fractions expands the fraction \\tfrac{x}{y} to be represented by repeatedly performing the replacement\n\n:::: \\frac{x}{y} = \\frac{1}{\\lceil y/x\\rceil} + \\frac{(-y)\\!\\!\\!\\!\\mod x}{y\\lceil y/x\\rceil} \n\n\n(simplifying the 2nd term in this replacement as necessary, and where \\lceil x \\rceil is the ''ceiling'' function).\n\n\n\nFor this task, Proper and improper fractions must be able to be expressed.\n\n\nProper fractions are of the form \\tfrac{a}{b} where a and b are positive integers, such that a < b, and \n\nimproper fractions are of the form \\tfrac{a}{b} where a and b are positive integers, such that ''a'' >= ''b''. \n\n\n(See the REXX programming example to view one method of expressing the whole number part of an improper fraction.)\n\nFor improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [''n''].\n\n\n;Task requirements:\n* show the Egyptian fractions for: \\tfrac{43}{48} and \\tfrac{5}{121} and \\tfrac{2014}{59} \n* for all proper fractions, \\tfrac{a}{b} where a and b are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:\n::* the largest number of terms,\n::* the largest denominator.\n* for all one-, two-, and three-digit integers, find and show (as above). {extra credit}\n\n\n;Also see:\n* Wolfram MathWorld(tm) entry: Egyptian fraction\n\n", "solution": "#include \n#include \n#include \n\ntypedef int64_t integer;\n\nstruct Pair {\n integer md;\n int tc;\n};\n\ninteger mod(integer x, integer y) {\n return ((x % y) + y) % y;\n}\n\ninteger gcd(integer a, integer b) {\n if (0 == a) return b;\n if (0 == b) return a;\n if (a == b) return a;\n if (a > b) return gcd(a - b, b);\n return gcd(a, b - a);\n}\n\nvoid write0(bool show, char *str) {\n if (show) {\n printf(str);\n }\n}\n\nvoid write1(bool show, char *format, integer a) {\n if (show) {\n printf(format, a);\n }\n}\n\nvoid write2(bool show, char *format, integer a, integer b) {\n if (show) {\n printf(format, a, b);\n }\n}\n\nstruct Pair egyptian(integer x, integer y, bool show) {\n struct Pair ret;\n integer acc = 0;\n bool first = true;\n\n ret.tc = 0;\n ret.md = 0;\n\n write2(show, \"Egyptian fraction for %lld/%lld: \", x, y);\n while (x > 0) {\n integer z = (y + x - 1) / x;\n if (z == 1) {\n acc++;\n } else {\n if (acc > 0) {\n write1(show, \"%lld + \", acc);\n first = false;\n acc = 0;\n ret.tc++;\n } else if (first) {\n first = false;\n } else {\n write0(show, \" + \");\n }\n if (z > ret.md) {\n ret.md = z;\n }\n write1(show, \"1/%lld\", z);\n ret.tc++;\n }\n x = mod(-y, x);\n y = y * z;\n }\n if (acc > 0) {\n write1(show, \"%lld\", acc);\n ret.tc++;\n }\n write0(show, \"\\n\");\n\n return ret;\n}\n\nint main() {\n struct Pair p;\n integer nm = 0, dm = 0, dmn = 0, dmd = 0, den = 0;;\n int tm, i, j;\n\n egyptian(43, 48, true);\n egyptian(5, 121, true); // final term cannot be represented correctly\n egyptian(2014, 59, true);\n\n tm = 0;\n for (i = 1; i < 100; i++) {\n for (j = 1; j < 100; j++) {\n p = egyptian(i, j, false);\n if (p.tc > tm) {\n tm = p.tc;\n nm = i;\n dm = j;\n }\n if (p.md > den) {\n den = p.md;\n dmn = i;\n dmd = j;\n }\n }\n }\n printf(\"Term max is %lld/%lld with %d terms.\\n\", nm, dm, tm); // term max is correct\n printf(\"Denominator max is %lld/%lld\\n\", dmn, dmd); // denominator max is not correct\n egyptian(dmn, dmd, true); // enough digits cannot be represented without bigint\n\n return 0;\n}"} {"title": "Hailstone sequence", "language": "C", "task": "The Hailstone sequence of numbers can be generated from a starting positive integer, n by:\n* If n is '''1''' then the sequence ends.\n* If n is '''even''' then the next n of the sequence = n/2 \n* If n is '''odd''' then the next n of the sequence = (3 * n) + 1 \n\n\nThe (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.\n\n\nThis sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):\n:::* hailstone sequence, hailstone numbers\n:::* 3x + 2 mapping, 3n + 1 problem\n:::* Collatz sequence\n:::* Hasse's algorithm\n:::* Kakutani's problem\n:::* Syracuse algorithm, Syracuse problem\n:::* Thwaites conjecture \n:::* Ulam's problem\n\n\nThe hailstone sequence is also known as ''hailstone numbers'' (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).\n\n\n;Task:\n# Create a routine to generate the hailstone sequence for a number.\n# Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1\n# Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. (But don't show the actual sequence!)\n\n\n;See also:\n* xkcd (humourous).\n* The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).\n* The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).\n\n", "solution": "#include \n#include \n\nint hailstone(int n, int *arry)\n{\n int hs = 1;\n\n while (n!=1) {\n hs++;\n if (arry) *arry++ = n;\n n = (n&1) ? (3*n+1) : (n/2);\n }\n if (arry) *arry++ = n;\n return hs;\n}\n\nint main()\n{\n int j, hmax = 0;\n int jatmax, n;\n int *arry;\n\n for (j=1; j<100000; j++) {\n n = hailstone(j, NULL);\n if (hmax < n) {\n hmax = n;\n jatmax = j;\n }\n }\n n = hailstone(27, NULL);\n arry = malloc(n*sizeof(int));\n n = hailstone(27, arry);\n\n printf(\"[ %d, %d, %d, %d, ...., %d, %d, %d, %d] len=%d\\n\",\n arry[0],arry[1],arry[2],arry[3],\n arry[n-4], arry[n-3], arry[n-2], arry[n-1], n);\n printf(\"Max %d at j= %d\\n\", hmax, jatmax);\n free(arry);\n\n return 0;\n}"} {"title": "Harshad or Niven series", "language": "C", "task": "The Harshad or Niven numbers are positive integers >= 1 that are divisible by the sum of their digits. \n\nFor example, '''42''' is a Harshad number as '''42''' is divisible by ('''4''' + '''2''') without remainder.\n\nAssume that the series is defined as the numbers in increasing order.\n\n\n;Task:\nThe task is to create a function/method/procedure to generate successive members of the Harshad sequence. \n\nUse it to:\n::* list the first '''20''' members of the sequence, and\n::* list the first Harshad number greater than '''1000'''.\n\n\nShow your output here.\n\n\n;Related task\n:* Increasing gaps between consecutive Niven numbers\n\n\n;See also\n* OEIS: A005349\n\n", "solution": "#include \n\nstatic int digsum(int n)\n{\n int sum = 0;\n do { sum += n % 10; } while (n /= 10);\n return sum;\n}\n\nint main(void)\n{\n int n, done, found;\n\n for (n = 1, done = found = 0; !done; ++n) {\n if (n % digsum(n) == 0) {\n if (found++ < 20) printf(\"%d \", n);\n if (n > 1000) done = printf(\"\\n%d\\n\", n);\n }\n }\n\n return 0;\n}"} {"title": "Haversine formula", "language": "C", "task": "{{Wikipedia}}\n\n\nThe '''haversine formula''' is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes. \n\nIt is a special case of a more general formula in spherical trigonometry, the '''law of haversines''', relating the sides and angles of spherical \"triangles\".\n\n\n;Task:\nImplement a great-circle distance function, or use a library function, \nto show the great-circle distance between:\n* Nashville International Airport (BNA) in Nashville, TN, USA, which is: \n '''N''' 36deg7.2', '''W''' 86deg40.2' (36.12, -86.67) -and-\n* Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:\n '''N''' 33deg56.4', '''W''' 118deg24.0' (33.94, -118.40) \n\n\nUser Kaimbridge clarified on the Talk page:\n\n -- 6371.0 km is the authalic radius based on/extracted from surface area;\n -- 6372.8 km is an approximation of the radius of the average circumference\n (i.e., the average great-elliptic or great-circle radius), where the\n boundaries are the meridian (6367.45 km) and the equator (6378.14 km).\n\nUsing either of these values results, of course, in differing distances:\n\n 6371.0 km -> 2886.44444283798329974715782394574671655 km;\n 6372.8 km -> 2887.25995060711033944886005029688505340 km;\n (results extended for accuracy check: Given that the radii are only\n approximations anyways, .01' 1.0621333 km and .001\" .00177 km,\n practical precision required is certainly no greater than about\n .0000001----i.e., .1 mm!)\n\nAs distances are segments of great circles/circumferences, it is\nrecommended that the latter value (r = 6372.8 km) be used (which\nmost of the given solutions have already adopted, anyways). \n\n\nMost of the examples below adopted Kaimbridge's recommended value of\n6372.8 km for the earth radius. However, the derivation of this\nellipsoidal quadratic mean radius\nis wrong (the averaging over azimuth is biased). When applying these\nexamples in real applications, it is better to use the\nmean earth radius,\n6371 km. This value is recommended by the International Union of\nGeodesy and Geophysics and it minimizes the RMS relative error between the\ngreat circle and geodesic distance.\n\n", "solution": "#include \n#include \n#include \n\n#define R 6371\n#define TO_RAD (3.1415926536 / 180)\ndouble dist(double th1, double ph1, double th2, double ph2)\n{\n\tdouble dx, dy, dz;\n\tph1 -= ph2;\n\tph1 *= TO_RAD, th1 *= TO_RAD, th2 *= TO_RAD;\n\n\tdz = sin(th1) - sin(th2);\n\tdx = cos(ph1) * cos(th1) - cos(th2);\n\tdy = sin(ph1) * cos(th1);\n\treturn asin(sqrt(dx * dx + dy * dy + dz * dz) / 2) * 2 * R;\n}\n\nint main()\n{\n\tdouble d = dist(36.12, -86.67, 33.94, -118.4);\n\t/* Americans don't know kilometers */\n\tprintf(\"dist: %.1f km (%.1f mi.)\\n\", d, d / 1.609344);\n\n\treturn 0;\n}"} {"title": "Hello world/Line printer", "language": "C", "task": "Cause a line printer attached to the computer to print a line containing the message: Hello World! \n\n\n;Note:\nA line printer is not the same as standard output. \n\nA line printer was an older-style printer which prints one line at a time to a continuous ream of paper. \n\nWith some systems, a line printer can be any device attached to an appropriate port (such as a parallel port).\n\n", "solution": "#include \n\nint main()\n{\n FILE *lp;\n lp = fopen(\"/dev/lp0\",\"w\");\n fprintf(lp,\"Hello world!\\n\");\n fclose(lp);\n return 0;\n}"} {"title": "Heronian triangles", "language": "C", "task": "Hero's formula for the area of a triangle given the length of its three sides ''a'', ''b'', and ''c'' is given by:\n\n:::: A = \\sqrt{s(s-a)(s-b)(s-c)},\n\nwhere ''s'' is half the perimeter of the triangle; that is,\n\n:::: s=\\frac{a+b+c}{2}.\n\n'''Heronian triangles'''\nare triangles whose sides ''and area'' are all integers.\n: An example is the triangle with sides '''3, 4, 5''' whose area is '''6''' (and whose perimeter is '''12'''). \n\n\nNote that any triangle whose sides are all an integer multiple of '''3, 4, 5'''; such as '''6, 8, 10,''' will also be a Heronian triangle.\n\nDefine a '''Primitive Heronian triangle''' as a Heronian triangle where the greatest common divisor \nof all three sides is '''1''' (unity). \n\nThis will exclude, for example, triangle '''6, 8, 10.'''\n\n\n;Task:\n# Create a named function/method/procedure/... that implements Hero's formula.\n# Use the function to generate all the ''primitive'' Heronian triangles with sides <= 200.\n# Show the count of how many triangles are found.\n# Order the triangles by first increasing area, then by increasing perimeter, then by increasing maximum side lengths\n# Show the first ten ordered triangles in a table of sides, perimeter, and area.\n# Show a similar ordered table for those triangles with area = 210\n\n\nShow all output here.\n\n'''Note''': when generating triangles it may help to restrict a <= b <= c\n", "solution": "#include\n#include\n#include\n\ntypedef struct{\n\tint a,b,c;\n\tint perimeter;\n\tdouble area;\n}triangle;\n\ntypedef struct elem{\n\ttriangle t;\n\tstruct elem* next;\n}cell;\n\ntypedef cell* list;\n\nvoid addAndOrderList(list *a,triangle t){\n\tlist iter,temp;\n\tint flag = 0;\n\t\n\tif(*a==NULL){\n\t\t*a = (list)malloc(sizeof(cell));\n\t\t(*a)->t = t;\n\t\t(*a)->next = NULL;\n\t}\n\t\n\telse{\n\t\ttemp = (list)malloc(sizeof(cell));\n\n\t\t\titer = *a;\n\t\t\twhile(iter->next!=NULL){\n\t\t\t\tif(((iter->t.areat.area==t.area && iter->t.perimetert.area==t.area && iter->t.perimeter==t.perimeter && iter->t.a<=t.a))\n\t\t\t\t&&\n\t\t\t\t(iter->next==NULL||(t.areanext->t.area || t.perimeternext->t.perimeter || t.anext->t.a))){\n\t\t\t\t\ttemp->t = t;\n\t\t\t\t\ttemp->next = iter->next;\n\t\t\t\t\titer->next = temp;\n\t\t\t\t\tflag = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\titer = iter->next;\n\t\t\t}\n\t\t\t\n\t\t\tif(flag!=1){\n\t\t\t\ttemp->t = t;\n\t\t\t\ttemp->next = NULL;\n\t\t\t\titer->next = temp;\n\t\t\t}\n\t}\n}\n\nint gcd(int a,int b){\n\tif(b!=0)\n\t\treturn gcd(b,a%b);\n\treturn a;\n}\n\nvoid calculateArea(triangle *t){\n\t(*t).perimeter = (*t).a + (*t).b + (*t).c;\n\t(*t).area = sqrt(0.5*(*t).perimeter*(0.5*(*t).perimeter - (*t).a)*(0.5*(*t).perimeter - (*t).b)*(0.5*(*t).perimeter - (*t).c));\n}\n\nlist generateTriangleList(int maxSide,int *count){\n\tint a,b,c;\n\ttriangle t;\n\tlist herons = NULL;\n\t\n\t*count = 0;\n\t\n\tfor(a=1;a<=maxSide;a++){\n\t\tfor(b=1;b<=a;b++){\n\t\t\tfor(c=1;c<=b;c++){\n\t\t\t\tif(c+b > a && gcd(gcd(a,b),c)==1){\n\t\t\t\t\tt = (triangle){a,b,c};\n\t\t\t\t\tcalculateArea(&t);\n\t\t\t\t\tif(t.area/(int)t.area == 1){\n\t\t\t\t\t\taddAndOrderList(&herons,t);\n\t\t\t\t\t\t(*count)++;\n\t\t\t\t\t}\t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn herons;\n}\n\nvoid printList(list a,int limit,int area){\n\tlist iter = a;\n\tint count = 1;\n\t\n\tprintf(\"\\nDimensions\\tPerimeter\\tArea\");\n\t\n\twhile(iter!=NULL && count!=limit+1){\n\t\tif(area==-1 ||(area==iter->t.area)){\n\t\t\tprintf(\"\\n%d x %d x %d\\t%d\\t\\t%d\",iter->t.a,iter->t.b,iter->t.c,iter->t.perimeter,(int)iter->t.area);\n\t\t\tcount++;\n\t\t}\n\t\titer = iter->next;\n\t}\n}\n\nint main(int argC,char* argV[])\n{\n\tint count;\n\tlist herons = NULL;\n\t\n\tif(argC!=4)\n\t\tprintf(\"Usage : %s \",argV[0]);\n\telse{\n\t\therons = generateTriangleList(atoi(argV[1]),&count);\n\t\tprintf(\"Triangles found : %d\",count);\n\t\t(atoi(argV[3])==-1)?printf(\"\\nPrinting first %s triangles.\",argV[2]):printf(\"\\nPrinting triangles with area %s square units.\",argV[3]);\n\t\tprintList(herons,atoi(argV[2]),atoi(argV[3]));\n\t\tfree(herons);\n\t}\n\treturn 0;\n}\n"} {"title": "Hofstadter-Conway $10,000 sequence", "language": "C", "task": "The definition of the sequence is colloquially described as:\n* Starting with the list [1,1],\n* Take the last number in the list so far: 1, I'll call it x.\n* Count forward x places from the beginning of the list to find the first number to add (1)\n* Count backward x places from the end of the list to find the second number to add (1)\n* Add the two indexed numbers from the list and the result becomes the next number in the list (1+1)\n* This would then produce [1,1,2] where 2 is the third element of the sequence.\n\nNote that indexing for the description above starts from alternately the left and right ends of the list and starts from an index of ''one''.\n\nA less wordy description of the sequence is:\n a(1)=a(2)=1\n a(n)=a(a(n-1))+a(n-a(n-1))\n\nThe sequence begins:\n 1, 1, 2, 2, 3, 4, 4, 4, 5, ...\n\nInteresting features of the sequence are that:\n* a(n)/n tends to 0.5 as n grows towards infinity.\n* a(n)/n where n is a power of 2 is 0.5\n* For n>4 the maximal value of a(n)/n between successive powers of 2 decreases.\n\na(n) / n for n in 1..256 \n\n\nThe sequence is so named because John Conway offered a prize of $10,000 to the first person who could\nfind the first position, p in the sequence where \n |a(n)/n| < 0.55 for all n > p\nIt was later found that Hofstadter had also done prior work on the sequence.\n\nThe 'prize' was won quite quickly by Dr. Colin L. Mallows who proved the properties of the sequence and allowed him to find the value of n (which is much smaller than the 3,173,375,556 quoted in the NYT article).\n\n\n;Task:\n# Create a routine to generate members of the Hofstadter-Conway $10,000 sequence.\n# Use it to show the maxima of a(n)/n between successive powers of two up to 2**20\n# As a stretch goal: compute the value of n that would have won the prize and confirm it is true for n up to 2**20\n\n\n\n;Also see:\n* Conways Challenge Sequence, Mallows' own account.\n* Mathworld Article.\n\n", "solution": "#include \n#include \n\nint a_list[1<<20 + 1];\n\nint doSqnc( int m)\n{\n int max_df = 0;\n int p2_max = 2;\n int v, n;\n int k1 = 2;\n int lg2 = 1;\n double amax = 0;\n a_list[0] = -50000;\n a_list[1] = a_list[2] = 1;\n v = a_list[2];\n\n for (n=3; n <= m; n++) {\n v = a_list[n] = a_list[v] + a_list[n-v];\n if ( amax < v*1.0/n) amax = v*1.0/n;\n if ( 0 == (k1&n)) {\n printf(\"Maximum between 2^%d and 2^%d was %f\\n\", lg2,lg2+1, amax);\n amax = 0;\n lg2++;\n }\n k1 = n;\n }\n return 1;\n}"} {"title": "Hofstadter Figure-Figure sequences", "language": "C", "task": "These two sequences of positive integers are defined as:\n:::: \\begin{align}\nR(1)&=1\\ ;\\ S(1)=2 \\\\\nR(n)&=R(n-1)+S(n-1), \\quad n>1.\n\\end{align}\n\nThe sequence S(n) is further defined as the sequence of positive integers '''''not''''' present in R(n).\n\nSequence R starts: \n 1, 3, 7, 12, 18, ...\nSequence S starts: \n 2, 4, 5, 6, 8, ...\n\n\n;Task:\n# Create two functions named '''ffr''' and '''ffs''' that when given '''n''' return '''R(n)''' or '''S(n)''' respectively.(Note that R(1) = 1 and S(1) = 2 to avoid off-by-one errors).\n# No maximum value for '''n''' should be assumed.\n# Calculate and show that the first ten values of '''R''' are: 1, 3, 7, 12, 18, 26, 35, 45, 56, and 69\n# Calculate and show that the first 40 values of '''ffr''' plus the first 960 values of '''ffs''' include all the integers from 1 to 1000 exactly once.\n\n\n;References:\n* Sloane's A005228 and A030124.\n* Wolfram MathWorld\n* Wikipedia: Hofstadter Figure-Figure sequences.\n\n", "solution": "#include \n#include \n\n// simple extensible array stuff\ntypedef unsigned long long xint;\n\ntypedef struct {\n\tsize_t len, alloc;\n\txint *buf;\n} xarray;\n\nxarray rs, ss;\n\nvoid setsize(xarray *a, size_t size)\n{\n\tsize_t n = a->alloc;\n\tif (!n) n = 1;\n\n\twhile (n < size) n <<= 1;\n\tif (a->alloc < n) {\n\t\ta->buf = realloc(a->buf, sizeof(xint) * n);\n\t\tif (!a->buf) abort();\n\t\ta->alloc = n;\n\t}\n}\n\nvoid push(xarray *a, xint v)\n{\n\twhile (a->alloc <= a->len)\n\t\tsetsize(a, a->alloc * 2);\n\n\ta->buf[a->len++] = v;\n}\n\n\n// sequence stuff\nvoid RS_append(void);\n\nxint R(int n)\n{\n\twhile (n > rs.len) RS_append();\n\treturn rs.buf[n - 1];\n}\n\nxint S(int n)\n{\n\twhile (n > ss.len) RS_append();\n\treturn ss.buf[n - 1];\n}\n\nvoid RS_append()\n{\n\tint n = rs.len;\n\txint r = R(n) + S(n);\n\txint s = S(ss.len);\n\n\tpush(&rs, r);\n\twhile (++s < r) push(&ss, s);\n\tpush(&ss, r + 1); // pesky 3\n}\n\nint main(void)\n{\n\tpush(&rs, 1);\n\tpush(&ss, 2);\n\n\tint i;\n\tprintf(\"R(1 .. 10):\");\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\" %llu\", R(i));\n\n\tchar seen[1001] = { 0 };\n\tfor (i = 1; i <= 40; i++) seen[ R(i) ] = 1;\n\tfor (i = 1; i <= 960; i++) seen[ S(i) ] = 1;\n\tfor (i = 1; i <= 1000 && seen[i]; i++);\n\n\tif (i <= 1000) {\n\t\tfprintf(stderr, \"%d not seen\\n\", i);\n\t\tabort();\n\t}\n\n\tputs(\"\\nfirst 1000 ok\");\n\treturn 0;\n}"} {"title": "Hofstadter Q sequence", "language": "C", "task": "The Hofstadter Q sequence is defined as:\n:: \\begin{align}\nQ(1)&=Q(2)=1, \\\\\nQ(n)&=Q\\big(n-Q(n-1)\\big)+Q\\big(n-Q(n-2)\\big), \\quad n>2.\n\\end{align}\n\n\nIt is defined like the [[Fibonacci sequence]], but whereas the next term in the Fibonacci sequence is the sum of the previous two terms, in the Q sequence the previous two terms tell you how far to go back in the Q sequence to find the two numbers to sum to make the next term of the sequence.\n\n\n;Task:\n* Confirm and display that the first ten terms of the sequence are: 1, 1, 2, 3, 3, 4, 5, 5, 6, and 6 \n* Confirm and display that the 1000th term is: 502\n\n\n;Optional extra credit\n* Count and display how many times a member of the sequence is less than its preceding term for terms up to and including the 100,000th term.\n* Ensure that the extra credit solution ''safely'' handles being initially asked for an '''n'''th term where '''n''' is large.\n(This point is to ensure that caching and/or recursion limits, if it is a concern, is correctly handled).\n\n", "solution": "#include \n#include \n\n#define N 100000\nint main()\n{\n\tint i, flip, *q = (int*)malloc(sizeof(int) * N) - 1;\n\n\tq[1] = q[2] = 1;\n\n\tfor (i = 3; i <= N; i++)\n\t\tq[i] = q[i - q[i - 1]] + q[i - q[i - 2]];\n\t\t\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\"%d%c\", q[i], i == 10 ? '\\n' : ' ');\n\n\tprintf(\"%d\\n\", q[1000]);\n\n\tfor (flip = 0, i = 1; i < N; i++)\n\t\tflip += q[i] > q[i + 1];\n\n\tprintf(\"flips: %d\\n\", flip);\n\treturn 0;\n}"} {"title": "Honeycombs", "language": "C", "task": "The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five\ncolumns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in columns two and four occupy a lower position within the arrangement. Each hexagon should be the same colour, and should\ndisplay a unique randomly selected single capital letter on the front. The application should now wait for the user to select a hexagon, either by using a pointing device, or by pressing a key that carries a corresponding letter on a hexagon. For platforms that support pointing devices and keyboards, the application should support both methods of selection. A record of the chosen letters should be maintained and the code should be suitably commented, at the point where the the selected letter has been determined. The selected hexagon should now change colour on the display. The cycle repeats until the user has chosen all of the letters. Note that each letter can only be selected once and previously selected hexagons retain their colour after selection. The program terminates when all letters have been chosen.\n\nOptionally: output the list of selected letters and show the last selected letter, cater for a different number of columns or a different number of hexagons in each column, cater for two players, (turns alternate and the hexagons change a different colour depending on whether they were selected by player one or player two and records of both players selections are maintained.)\n\n[[image:honeycomb.gif]]\n\n", "solution": "/* Program for gtk3 */\n/* discovery: essential to use consistent documentation */\n/* compilation on linux: */\n/* $ a=./hexagon && make -k \"CFLAGS=$( pkg-config --cflags gtk+-3.0 )\" \"LOADLIBES=$( pkg-config --libs gtk+-3.0 )\" $a && $a --gtk-debug=all */\n/* search for to do */\n/* The keyboard and mouse callbacks increment the \"selected\" status, */\n/* of the matching hexagon, */\n/* then invalidate the drawing window which triggers a draw event. */\n/* The draw callback redraws the screen and tests for completion, */\n/* upon which the program spits back the characters selected and exits */\n\n#include\n#include\n#include\n#include\n\nstatic GdkPixbuf*create_pixbuf(const gchar*filename) {\n GdkPixbuf*pixbuf;\n GError*error = NULL;\n pixbuf = gdk_pixbuf_new_from_file(filename, &error);\n if(!pixbuf) {\n fprintf(stderr,\"\\n%s\\n\", error->message);\n g_error_free(error);\n }\n return pixbuf;\n}\n\n#define NGON struct ngon\nNGON {\n double Cx,Cy, r;\n int sides, selected;\n char c;\n};\n\nGRand*random_numbers = NULL;\n\n#define R 20\n#define TAU (2*M_PI)\t /* http://laughingsquid.com/pi-is-wrong/ */\n#define OFFSET_X (1+sin(TAU/12))\n#define OFFSET_Y (cos(TAU/12))\n#define ODD(A) ((A)&1)\n\nstatic void initialize_hexagons(NGON*hs,size_t n) {\n NGON*h;\n gint i,broken;\n GQueue*shuffler = g_queue_new();\n if (NULL == shuffler) {\n fputs(\"\\ncannot allocate shuffling queue. quitting!\\n\",stderr);\n exit(EXIT_FAILURE);\n }\n /* randomize characters by stuffing them onto a double end queue\n and popping them off from random positions */\n if ((broken = (NULL == random_numbers)))\n random_numbers = g_rand_new();\n for (i = 'A'; i <= 'Z'; ++i)\n g_queue_push_head(shuffler,GINT_TO_POINTER(i));\n memset(hs,0,n*(sizeof(NGON)));\n hs[n-1].sides = -1;\t\t/* assign the sentinel */\n for (h = hs; !h->sides; ++h) {\n int div = (h-hs)/4, mod = (h-hs)%4;\n h->sides = 6;\n h->c = GPOINTER_TO_INT(\n\t g_queue_pop_nth(\n\t shuffler,\n\t g_rand_int_range(\n\t\t random_numbers,\n\t\t (gint32)0,\n\t\t (gint32)g_queue_get_length(shuffler))));\n fputc(h->c,stderr);\n h->r = R;\n h->Cx = R*(2+div*OFFSET_X), h->Cy = R*(2*(1+mod*OFFSET_Y)+ODD(div)*OFFSET_Y);\n fprintf(stderr,\"(%g,%g)\\n\",h->Cx,h->Cy);\n }\n fputc('\\n',stderr);\n g_queue_free(shuffler);\n if (broken)\n g_rand_free(random_numbers); \n}\n\nstatic void add_loop(cairo_t*cr,NGON*hs,int select) {\n NGON*h;\n double r,Cx,Cy,x,y;\n int i, sides;\n for (h = hs; 0 < (sides = h->sides); ++h)\n if ((select && h->selected) || (select == h->selected)) {\n r = h->r, Cx = h->Cx, Cy = h->Cy;\n i = 0;\n x = Cx+r*cos(TAU*i/sides), y = Cy+r*sin(TAU*i/sides), cairo_move_to(cr,x,y);\n for (i = 1; i < sides; ++i)\n x = Cx+r*cos(TAU*i/sides), y = Cy+r*sin(TAU*i/sides), cairo_line_to(cr,x,y);\n cairo_close_path(cr);\n }\n}\n\nstatic int make_labels(cairo_t*cr,NGON*hs,int select) {\n NGON*h;\n int i = 0;\n char text[2];\n text[1] = 0;\n for (h = hs; 0 < h->sides; ++h)\n if ((select && h->selected) || (select == h->selected))\n /* yuck, need to measure the font. Better to use pango_cairo */\n *text = h->c, cairo_move_to(cr,h->Cx,h->Cy), cairo_show_text(cr,text), ++i;\n return i;\n}\n\nstatic int archive(int a) {\n static GQueue*q = NULL;\n if ((NULL == q) && (NULL == (q = g_queue_new()))) {\n fputs(\"\\ncannot allocate archival queue. quitting!\\n\",stderr);\n exit(EXIT_FAILURE);\n }\n if (a < -1)\t\t\t/* reset */\n return g_queue_free(q), q = NULL, 0;\n if (-1 == a)\t\t\t/* pop off tail */\n return g_queue_is_empty(q) ? 0 : GPOINTER_TO_INT(g_queue_pop_tail(q));\n if (!a)\t\t\t/* peek most recent entry */\n return g_queue_is_empty(q) ? 0 : GPOINTER_TO_INT(g_queue_peek_head(q));\n g_queue_push_head(q,GINT_TO_POINTER(a)); /* store */\n return a;\n}\n\n/* to do: use appropriate sizing, use the cairo transformation matrix */\nstatic gboolean draw(GtkWidget*widget,cairo_t*cr,gpointer data) {\n\n /* unselected fill in yellow */\n cairo_set_source_rgba(cr,0.8,0.8,0,1),\n add_loop(cr,(NGON*)data,0);\n cairo_fill(cr);\n\n /* selected fill, purple */\n cairo_set_source_rgba(cr,0.8,0,0.8,1);\n add_loop(cr,(NGON*)data,1);\n cairo_fill_preserve(cr);\n\n /* all outlines gray, background shows through, fun fun! */\n cairo_set_line_width (cr, 3.0);\n cairo_set_source_rgba(cr,0.7,0.7,0.7,0.7); \n add_loop(cr,(NGON*)data,0);\n cairo_stroke(cr);\n\n /* select labels */\n cairo_set_source_rgba(cr,0,1,0,1);\n make_labels(cr,(NGON*)data,1);\n cairo_stroke(cr);\n\n /* unselected labels */\n cairo_set_source_rgba(cr,1,0,0,1);\n /* to do: clean up this exit code */\n if (!make_labels(cr,(NGON*)data,0)) {\n int c;\n putchar('\\n');\n while ((c = archive(-1)))\n putchar(c);\n puts(\"\\nfinished\");\n archive(-2);\n exit(EXIT_SUCCESS);\n }\n cairo_stroke(cr);\n\n return TRUE;\n}\n\n/*the widget is a GtkDrawingArea*/\nstatic gboolean button_press_event(GtkWidget*widget,const GdkEvent*event,gpointer data) {\n NGON*h,*hs = (NGON*)data;\n gdouble x_win, y_win;\n if (!gdk_event_get_coords(event,&x_win,&y_win))\n fputs(\"\\nBUTTON, gdk_event_get_coords(event,&x_win,&y_win)) failed\\n\",stderr);\n else {\n fprintf(stderr,\"x_win=%g y_win=%g\\n\",(double)x_win,(double)y_win);\n for (h = hs; 0 < h->sides; ++h) /* detection algorithm: */\n /* if mouse click within inner radius of hexagon */\n /* Much easier than all in-order cross products have same sign test! */\n if ((pow((x_win-h->Cx),2)+pow((y_win-h->Cy),2)) < pow((h->r*cos(TAU/(180/h->sides))),2)) {\n\t++h->selected;\n\tarchive(h->c);\n\t/* discovery: gdk_window_invalidate_region with NULL second argument does not work */\n\tgdk_window_invalidate_rect(gtk_widget_get_window(widget),(const GdkRectangle*)NULL,TRUE);\n\tbreak;\n }\n }\n return TRUE;\n}\n\nstatic gboolean key_press_event(GtkWidget*widget,const GdkEvent*event,gpointer data) {\n NGON*h,*hs = (NGON*)data;\n guint keyval;\n int unicode;\n if (!gdk_event_get_keyval(event,&keyval))\n fputs(\"\\nKEY! gdk_event_get_keyval(event,&keyval)) failed.\\n\",stderr);\n else {\n unicode = (int)gdk_keyval_to_unicode(gdk_keyval_to_upper(keyval));\n fprintf(stderr,\"key with unicode value: %d\\n\",unicode);\n for (h = hs; 0 < h->sides; ++h) /* look for a matching character associated with a hexagon */\n if (h->c == unicode) {\n\t++(h->selected);\n\tarchive(h->c);\n\t/* discovery: gdk_window_invalidate_region with NULL second argument does not work */\n\tgdk_window_invalidate_rect(gtk_widget_get_window(widget),(const GdkRectangle*)NULL,TRUE);\n\tbreak;\n }\n }\n return TRUE;\n}\n\nint main(int argc,char*argv[]) {\n GtkWidget *window, *vbox, /* *label, */ *drawing_area;\n NGON ngons[21];\t /* sentinal has negative number of sides */\n\n /* discovery: gtk_init removes gtk debug flags, such as --gtk-debug=all */\n /* also calls gdk_init which handles --display and --screen or other X11 communication issues */\n gtk_init(&argc, &argv);\n\n /* GTK VERSION 3.2.0 */\n fprintf(stderr,\"GTK VERSION %d.%d.%d\\n\",GTK_MAJOR_VERSION,GTK_MINOR_VERSION,GTK_MICRO_VERSION);\n\n window = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n\n /* discovery: to make window transparent I have to use the alpha channel correctly */\n\n /* discovery: GTK_WINDOW(GtkWidget*) casts the widget to window */\n /* discovery: window in the function name? use GTK_WINDOW. g_ in function name? use G_OBJECT */\n gtk_window_set_title(GTK_WINDOW(window), \"Rosetta Code Honeycomb, C with GTK\");\n gtk_window_set_default_size(GTK_WINDOW(window), 308, 308+12+8); /* XxY */\n /* discovery: making the window vanish does not stop the program */\n /* discovery: NULL is placeholder for extra data sent to the callback */\n g_signal_connect_swapped(G_OBJECT(window),\"destroy\",G_CALLBACK(gtk_main_quit),NULL);\n\n /* I created /tmp/favicon.ico from http://rosettacode.org/favicon.ico */\n /* Your window manager could use the icon, if it exists, and you fix the file name */\n gtk_window_set_icon(GTK_WINDOW(window),create_pixbuf(\"/tmp/favicon.ico\"));\n\n vbox = gtk_vbox_new(TRUE,1);\n gtk_container_add(GTK_CONTAINER(window),vbox);\n\n /* to do: fix the label widget */\n /* I did not learn to control multiple box packing, and I was */\n /* too lazy to make the label widget accessible. Plan was to */\n /* insert the most recent character using \"peek\" option of the archive */\n#if 0\n label = gtk_label_new(\"None Selected\");\n gtk_widget_set_size_request(label,308,20);\n gtk_box_pack_end(GTK_BOX(vbox),label,FALSE,TRUE,4);\n#endif\n\n drawing_area = gtk_drawing_area_new();\n gtk_widget_set_events(drawing_area,GDK_BUTTON_PRESS_MASK|GDK_KEY_PRESS_MASK|GDK_EXPOSURE_MASK);\n\n random_numbers = g_rand_new();\n initialize_hexagons(ngons,G_N_ELEMENTS(ngons));\n /* Discovery: expose_event changed to draw signal. We no longer need configure-event */\n g_signal_connect(G_OBJECT(drawing_area),\"draw\",G_CALLBACK(draw),(gpointer)ngons);\n\n g_signal_connect(G_OBJECT(drawing_area),\"button-press-event\",G_CALLBACK(button_press_event),(gpointer)ngons);\n g_signal_connect(G_OBJECT(drawing_area),\"key-press-event\",G_CALLBACK(key_press_event),(gpointer)ngons);\n gtk_widget_set_size_request(drawing_area, 308, 308); /* XxY */\n gtk_box_pack_start(GTK_BOX(vbox),drawing_area,TRUE,TRUE,4);\n\n /* Discovery: must allow focus to receive keyboard events */\n gtk_widget_set_can_focus(drawing_area,TRUE);\n\n /* Discovery: can set show for individual widgets or use show_all */\n gtk_widget_show_all(window);\n gtk_main();\n g_rand_free(random_numbers);\n return EXIT_SUCCESS;\n}\n"} {"title": "ISBN13 check digit", "language": "C", "task": "Validate the check digit of an ISBN-13 code:\n::* Multiply every other digit by '''3'''.\n::* Add these numbers and the other digits.\n::* Take the remainder of this number after division by '''10'''.\n::* If it is '''0''', the ISBN-13 check digit is correct.\n\n\nYou might use the following codes for testing:\n::::* 978-0596528126 (good)\n::::* 978-0596528120 (bad)\n::::* 978-1788399081 (good)\n::::* 978-1788399083 (bad)\n\n\nShow output here, on this page\n\n\n;See also:\n:* for details: 13-digit ISBN method of validation. (installs cookies.)\n\n", "solution": "#include \n\nint check_isbn13(const char *isbn) {\n int ch = *isbn, count = 0, sum = 0;\n /* check isbn contains 13 digits and calculate weighted sum */\n for ( ; ch != 0; ch = *++isbn, ++count) {\n /* skip hyphens or spaces */\n if (ch == ' ' || ch == '-') {\n --count;\n continue;\n }\n if (ch < '0' || ch > '9') {\n return 0;\n }\n if (count & 1) {\n sum += 3 * (ch - '0');\n } else {\n sum += ch - '0';\n }\n }\n if (count != 13) return 0;\n return !(sum%10);\n}\n\nint main() {\n int i;\n const char* isbns[] = {\"978-1734314502\", \"978-1734314509\", \"978-1788399081\", \"978-1788399083\"};\n for (i = 0; i < 4; ++i) {\n printf(\"%s: %s\\n\", isbns[i], check_isbn13(isbns[i]) ? \"good\" : \"bad\");\n }\n return 0;\n}"} {"title": "I before E except after C", "language": "C", "task": "The phrase \"I before E, except after C\" is a \nwidely known mnemonic which is supposed to help when spelling English words.\n\n\n;Task:\nUsing the word list from http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, \ncheck if the two sub-clauses of the phrase are plausible individually:\n:::# ''\"I before E when not preceded by C\"''\n:::# ''\"E before I when preceded by C\"''\n\n\nIf both sub-phrases are plausible then the original phrase can be said to be plausible.\n\nSomething is plausible if the number of words having the feature is more than two times the number of words having the opposite feature (where feature is 'ie' or 'ei' preceded or not by 'c' as appropriate).\n \n\n;Stretch goal:\nAs a stretch goal use the entries from the table of Word Frequencies in Written and Spoken English: based on the British National Corpus, (selecting those rows with three space or tab separated words only), to see if the phrase is plausible when word frequencies are taken into account.\n\n\n''Show your output here as well as your program.''\n\n\n\n\n;cf.:\n* Schools to rethink 'i before e' - BBC news, 20 June 2009\n* I Before E Except After C - QI Series 8 Ep 14, (humorous)\n* Companion website for the book: \"Word Frequencies in Written and Spoken English: based on the British National Corpus\".\n\n", "solution": "%{\n /*\n compilation and example on a GNU linux system:\n \n $ flex --case-insensitive --noyywrap --outfile=cia.c source.l\n $ make LOADLIBES=-lfl cia \n $ ./cia < unixdict.txt \n I before E when not preceded by C: plausible\n E before I when preceded by C: implausible\n Overall, the rule is: implausible \n */\n int cie, cei, ie, ei;\n%}\n \n%%\n \ncie ++cie, ++ie; /* longer patterns are matched preferentially, consuming input */\ncei ++cei, ++ei;\nie ++ie;\nei ++ei;\n.|\\n ;\n \n%%\n \nint main() {\n cie = cei = ie = ei = 0;\n yylex();\n printf(\"%s: %s\\n\",\"I before E when not preceded by C\", (2*ei < ie ? \"plausible\" : \"implausible\"));\n printf(\"%s: %s\\n\",\"E before I when preceded by C\", (2*cie < cei ? \"plausible\" : \"implausible\"));\n printf(\"%s: %s\\n\",\"Overall, the rule is\", (2*(cie+ei) < (cei+ie) ? \"plausible\" : \"implausible\"));\n return 0;\n}\n"} {"title": "Identity matrix", "language": "C", "task": "Build an identity matrix of a size known at run-time. \n\n\nAn ''identity matrix'' is a square matrix of size '''''n'' x ''n''''', \nwhere the diagonal elements are all '''1'''s (ones), \nand all the other elements are all '''0'''s (zeroes).\n\n\nI_n = \\begin{bmatrix}\n 1 & 0 & 0 & \\cdots & 0 \\\\\n 0 & 1 & 0 & \\cdots & 0 \\\\\n 0 & 0 & 1 & \\cdots & 0 \\\\\n \\vdots & \\vdots & \\vdots & \\ddots & \\vdots \\\\\n 0 & 0 & 0 & \\cdots & 1 \\\\\n\\end{bmatrix}\n\n\n;Related tasks:\n* [[Spiral matrix]]\n* [[Zig-zag matrix]] \n* [[Ulam_spiral_(for_primes)]]\n\n", "solution": "#include \n#include \nint main(int argc, char** argv) {\n if (argc < 2) {\n printf(\"usage: identitymatrix \\n\");\n exit(EXIT_FAILURE);\n }\n int rowsize = atoi(argv[1]);\n if (rowsize < 0) {\n printf(\"Dimensions of matrix cannot be negative\\n\");\n exit(EXIT_FAILURE);\n }\n int numElements = rowsize * rowsize;\n if (numElements < rowsize) {\n printf(\"Squaring %d caused result to overflow to %d.\\n\", rowsize, numElements);\n abort();\n }\n int** matrix = calloc(numElements, sizeof(int*));\n if (!matrix) {\n printf(\"Failed to allocate %d elements of %ld bytes each\\n\", numElements, sizeof(int*));\n abort();\n }\n for (unsigned int row = 0;row < rowsize;row++) {\n matrix[row] = calloc(numElements, sizeof(int));\n if (!matrix[row]) {\n printf(\"Failed to allocate %d elements of %ld bytes each\\n\", numElements, sizeof(int));\n abort();\n }\n matrix[row][row] = 1;\n }\n printf(\"Matrix is: \\n\");\n for (unsigned int row = 0;row < rowsize;row++) {\n for (unsigned int column = 0;column < rowsize;column++) {\n printf(\"%d \", matrix[row][column]);\n }\n printf(\"\\n\");\n }\n}\n"} {"title": "Idiomatically determine all the lowercase and uppercase letters", "language": "C", "task": "Idiomatically determine all the lowercase and uppercase letters (of the Latin [English] alphabet) being used currently by a computer programming language.\nThe method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other).\n \n\n;Task requirements\n\nDisplay the set of all:\n::::::* lowercase letters \n::::::* uppercase letters\n\nthat can be used (allowed) by the computer program,\n\nwhere ''letter'' is a member of the Latin (English) alphabet: '''a''' --> '''z''' and '''A''' --> '''Z'''. \n\n\nYou may want to mention what hardware architecture is being used, and if applicable, the operating system.\n\n\n;See also\n* Idiomatically determine all the characters that can be used for symbols.\n\n", "solution": "#include \n\nint main(int argc, char const *argv[]) {\n for (char c = 0x41; c < 0x5b; c ++) putchar(c);\n putchar('\\n');\n for (char c = 0x61; c < 0x7b; c ++) putchar(c);\n putchar('\\n');\n return 0;\n}"} {"title": "Include a file", "language": "C", "task": "Demonstrate the language's ability to include source code from other files.\n\n\n;See Also\n\n* [[Compiler/Simple file inclusion pre processor]]\n\n\n", "solution": "/* Standard and other library header names are enclosed between chevrons */\n#include \n\n/* User/in-project header names are usually enclosed between double-quotes */\n#include \"myutil.h\"\n"} {"title": "Integer overflow", "language": "C", "task": "Some languages support one or more integer types of the underlying processor.\n\nThis integer types have fixed size; usually '''8'''-bit, '''16'''-bit, '''32'''-bit, or '''64'''-bit.\nThe integers supported by such a type can be ''signed'' or ''unsigned''.\n\nArithmetic for machine level integers can often be done by single CPU instructions.\nThis allows high performance and is the main reason to support machine level integers.\n\n\n;Definition:\nAn integer overflow happens when the result of a computation does not fit into the fixed size integer.\nThe result can be too small or too big to be representable in the fixed size integer.\n\n\n;Task:\nWhen a language has fixed size integer types, create a program that\ndoes arithmetic computations for the fixed size integers of the language.\n\nThese computations must be done such that the result would overflow.\n\nThe program should demonstrate what the following expressions do.\n\n\nFor 32-bit signed integers:\n::::: {|class=\"wikitable\"\n!Expression\n!Result that does not fit into a 32-bit signed integer\n|-\n| -(-2147483647-1)\n| 2147483648\n|-\n| 2000000000 + 2000000000\n| 4000000000\n|-\n| -2147483647 - 2147483647\n| -4294967294\n|-\n| 46341 * 46341\n| 2147488281\n|-\n| (-2147483647-1) / -1\n| 2147483648\n|}\n\nFor 64-bit signed integers:\n::: {|class=\"wikitable\"\n!Expression\n!Result that does not fit into a 64-bit signed integer\n|-\n| -(-9223372036854775807-1)\n| 9223372036854775808\n|-\n| 5000000000000000000+5000000000000000000\n| 10000000000000000000\n|-\n| -9223372036854775807 - 9223372036854775807\n| -18446744073709551614\n|-\n| 3037000500 * 3037000500\n| 9223372037000250000\n|-\n| (-9223372036854775807-1) / -1\n| 9223372036854775808\n|}\n\nFor 32-bit unsigned integers:\n::::: {|class=\"wikitable\"\n!Expression\n!Result that does not fit into a 32-bit unsigned integer\n|-\n| -4294967295\n| -4294967295\n|-\n| 3000000000 + 3000000000\n| 6000000000\n|-\n| 2147483647 - 4294967295\n| -2147483648\n|-\n| 65537 * 65537\n| 4295098369\n|}\n\nFor 64-bit unsigned integers:\n::: {|class=\"wikitable\"\n!Expression\n!Result that does not fit into a 64-bit unsigned integer\n|-\n| -18446744073709551615\n| -18446744073709551615\n|-\n| 10000000000000000000 + 10000000000000000000\n| 20000000000000000000\n|-\n| 9223372036854775807 - 18446744073709551615\n| -9223372036854775808\n|-\n| 4294967296 * 4294967296\n| 18446744073709551616\n|}\n\n\n;Notes:\n:* When the integer overflow does trigger an exception show how the exception is caught.\n:* When the integer overflow produces some value, print it.\n:* It should be explicitly noted when an integer overflow is not recognized, the program continues with wrong results.\n:* This should be done for signed and unsigned integers of various sizes supported by the computer programming language.\n:* When a language has no fixed size integer type, or when no integer overflow can occur for other reasons, this should be noted.\n:* It is okay to mention, when a language supports unlimited precision integers, but this task is NOT the place to demonstrate the capabilities of unlimited precision integers.\n\n", "solution": "#include \n\nint main (int argc, char *argv[])\n{\n printf(\"Signed 32-bit:\\n\");\n printf(\"%d\\n\", -(-2147483647-1));\n printf(\"%d\\n\", 2000000000 + 2000000000);\n printf(\"%d\\n\", -2147483647 - 2147483647);\n printf(\"%d\\n\", 46341 * 46341);\n printf(\"%d\\n\", (-2147483647-1) / -1);\n printf(\"Signed 64-bit:\\n\");\n printf(\"%ld\\n\", -(-9223372036854775807-1));\n printf(\"%ld\\n\", 5000000000000000000+5000000000000000000);\n printf(\"%ld\\n\", -9223372036854775807 - 9223372036854775807);\n printf(\"%ld\\n\", 3037000500 * 3037000500);\n printf(\"%ld\\n\", (-9223372036854775807-1) / -1);\n printf(\"Unsigned 32-bit:\\n\");\n printf(\"%u\\n\", -4294967295U);\n printf(\"%u\\n\", 3000000000U + 3000000000U);\n printf(\"%u\\n\", 2147483647U - 4294967295U);\n printf(\"%u\\n\", 65537U * 65537U);\n printf(\"Unsigned 64-bit:\\n\");\n printf(\"%lu\\n\", -18446744073709551615LU);\n printf(\"%lu\\n\", 10000000000000000000LU + 10000000000000000000LU);\n printf(\"%lu\\n\", 9223372036854775807LU - 18446744073709551615LU);\n printf(\"%lu\\n\", 4294967296LU * 4294967296LU);\n return 0;\n}"} {"title": "Integer sequence", "language": "C", "task": "Create a program that, when run, would display all integers from '''1''' to ''' ''' (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.\n\n\nAn example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integers are represented as a 32-bit unsigned value with 0 as the smallest representable value, the largest representable value would be 4,294,967,295. Some languages support arbitrarily-large numbers as a built-in feature, while others make use of a module or library.\n\nIf appropriate, provide an example which reflect the language implementation's common built-in limits as well as an example which supports arbitrarily large numbers, and describe the nature of such limitations--or lack thereof.\n\n", "solution": "#include \t\t/* BN_*() */\n#include \t/* ERR_*() */\n#include \t\t/* fprintf(), puts() */\n\nvoid\nfail(const char *message)\n{\n\tfprintf(stderr, \"%s: error 0x%08lx\\n\", ERR_get_error());\n\texit(1);\n}\n\nint\nmain()\n{\n\tBIGNUM i;\n\tchar *s;\n\n\tBN_init(&i);\n\tfor (;;) {\n\t\tif (BN_add_word(&i, 1) == 0)\n\t\t\tfail(\"BN_add_word\");\n\t\ts = BN_bn2dec(&i);\n\t\tif (s == NULL)\n\t\t\tfail(\"BN_bn2dec\");\n\t\tputs(s);\n\t\tOPENSSL_free(s);\n\t}\n\t/* NOTREACHED */\n}"} {"title": "Intersecting number wheels", "language": "C", "task": "A number wheel has:\n* A ''name'' which is an uppercase letter.\n* A set of ordered ''values'' which are either ''numbers'' or ''names''.\n\nA ''number'' is generated/yielded from a named wheel by:\n:1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a \"wheel\":\n::1.a If the value is a number, yield it.\n::1.b If the value is a name, yield the next value from the named wheel\n::1.c Advance the position of this wheel.\n\nGiven the wheel\n: A: 1 2 3\nthe number 1 is first generated, then 2, then 3, 1, 2, 3, 1, ...\n\n'''Note:''' When more than one wheel is defined as a set of intersecting wheels then the \nfirst named wheel is assumed to be the one that values are generated from.\n\n;Examples:\nGiven the wheels:\n A: 1 B 2\n B: 3 4\nThe series of numbers generated starts:\n 1, 3, 2, 1, 4, 2, 1, 3, 2, 1, 4, 2, 1, 3, 2...\n\nThe intersections of number wheels can be more complex, (and might loop forever),\nand wheels may be multiply connected. \n\n'''Note:''' If a named wheel is referenced more than \nonce by one or many other wheels, then there is only one position of the wheel \nthat is advanced by each and all references to it.\n\nE.g.\n A: 1 D D\n D: 6 7 8\n Generates:\n 1 6 7 1 8 6 1 7 8 1 6 7 1 8 6 1 7 8 1 6 ... \n\n;Task:\nGenerate and show the first twenty terms of the sequence of numbers generated \nfrom these groups:\n\n Intersecting Number Wheel group:\n A: 1 2 3\n \n Intersecting Number Wheel group:\n A: 1 B 2\n B: 3 4\n \n Intersecting Number Wheel group:\n A: 1 D D\n D: 6 7 8\n \n Intersecting Number Wheel group:\n A: 1 B C\n B: 3 4\n C: 5 B\n\nShow your output here, on this page.\n\n\n", "solution": "#include \n#include \n#include \n\nstruct Wheel {\n char *seq;\n int len;\n int pos;\n};\n\nstruct Wheel *create(char *seq) {\n struct Wheel *w = malloc(sizeof(struct Wheel));\n if (w == NULL) {\n return NULL;\n }\n\n w->seq = seq;\n w->len = strlen(seq);\n w->pos = 0;\n\n return w;\n}\n\nchar cycle(struct Wheel *w) {\n char c = w->seq[w->pos];\n w->pos = (w->pos + 1) % w->len;\n return c;\n}\n\nstruct Map {\n struct Wheel *v;\n struct Map *next;\n char k;\n};\n\nstruct Map *insert(char k, struct Wheel *v, struct Map *head) {\n struct Map *m = malloc(sizeof(struct Map));\n if (m == NULL) {\n return NULL;\n }\n\n m->k = k;\n m->v = v;\n m->next = head;\n\n return m;\n}\n\nstruct Wheel *find(char k, struct Map *m) {\n struct Map *ptr = m;\n\n while (ptr != NULL) {\n if (ptr->k == k) {\n return ptr->v;\n }\n ptr = ptr->next;\n }\n\n return NULL;\n}\n\nvoid printOne(char k, struct Map *m) {\n struct Wheel *w = find(k, m);\n char c;\n\n if (w == NULL) {\n printf(\"Missing the wheel for: %c\\n\", k);\n exit(1);\n }\n\n c = cycle(w);\n if ('0' <= c && c <= '9') {\n printf(\" %c\", c);\n } else {\n printOne(c, m);\n }\n}\n\nvoid exec(char start, struct Map *m) {\n struct Wheel *w;\n int i;\n\n if (m == NULL) {\n printf(\"Unable to proceed.\");\n return;\n }\n\n for (i = 0; i < 20; i++) {\n printOne(start, m);\n }\n printf(\"\\n\");\n}\n\nvoid group1() {\n struct Wheel *a = create(\"123\");\n\n struct Map *m = insert('A', a, NULL);\n\n exec('A', m);\n}\n\nvoid group2() {\n struct Wheel *a = create(\"1B2\");\n struct Wheel *b = create(\"34\");\n\n struct Map *m = insert('A', a, NULL);\n m = insert('B', b, m);\n\n exec('A', m);\n}\n\nvoid group3() {\n struct Wheel *a = create(\"1DD\");\n struct Wheel *d = create(\"678\");\n\n struct Map *m = insert('A', a, NULL);\n m = insert('D', d, m);\n\n exec('A', m);\n}\n\nvoid group4() {\n struct Wheel *a = create(\"1BC\");\n struct Wheel *b = create(\"34\");\n struct Wheel *c = create(\"5B\");\n\n struct Map *m = insert('A', a, NULL);\n m = insert('B', b, m);\n m = insert('C', c, m);\n\n exec('A', m);\n}\n\nint main() {\n group1();\n group2();\n group3();\n group4();\n\n return 0;\n}"} {"title": "Inverted syntax", "language": "C", "task": "'''Inverted syntax with conditional expressions'''\n\nIn traditional syntax conditional expressions are usually shown before the action within a statement or code block:\n\n IF raining=true THEN needumbrella=true \n\nIn inverted syntax, the action is listed before the conditional expression in the statement or code block:\n\n needumbrella=true IF raining=true \n\n'''Inverted syntax with assignment'''\n\nIn traditional syntax, assignments are usually expressed with the variable appearing before the expression:\n\n a = 6\n\nIn inverted syntax, the expression appears before the variable:\n 6 = a\n\n'''Task'''\n\nThe task is to demonstrate support for inverted syntax forms within the language by showing both the traditional and inverted forms.\n", "solution": "main()\n{\n int a = 0;\n\n do {\n register int _o = 2;\n do {\n switch (_o) {\n case 1:\n a = 4;\n case 0:\n break;\n case 2:\n _o = !!(foo());\n continue;\n } break;\n } while (1);\n } while (0);\n printf(\"%d\\n\", a);\n exit(0);\n}\n"} {"title": "Iterated digits squaring", "language": "C", "task": "If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:\n15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89\n7 -> 49 -> 97 -> 130 -> 10 -> 1\n\nAn example in Python:\n\n>>> step = lambda x: sum(int(d) ** 2 for d in str(x))\n>>> iterate = lambda x: x if x in [1, 89] else iterate(step(x))\n>>> [iterate(x) for x in xrange(1, 20)]\n[1, 89, 89, 89, 89, 89, 1, 89, 89, 1, 89, 89, 1, 89, 89, 89, 89, 89, 1]\n\n\n;Task:\n: Count how many number chains for integers 1 <= n < 100_000_000 end with a value 89.\nOr, for much less credit - (showing that your algorithm and/or language is slow):\n: Count how many number chains for integers 1 <= n < 1_000_000 end with a value 89.\n\nThis problem derives from the Project Euler problem 92.\n\nFor a quick algorithm for this task see the talk page\n\n\n;Related tasks:\n* [[Combinations with repetitions]]\n* [[Digital root]]\n* [[Digital root/Multiplicative digital root]]\n\n", "solution": "#include \n\ntypedef unsigned long long ull;\n\nint is89(int x)\n{\n\twhile (1) {\n\t\tint s = 0;\n\t\tdo s += (x%10)*(x%10); while ((x /= 10));\n\n\t\tif (s == 89) return 1;\n\t\tif (s == 1) return 0;\n\t\tx = s;\n\t}\n}\n\n\nint main(void)\n{\n\t// array bounds is sort of random here, it's big enough for 64bit unsigned.\n\tull sums[32*81 + 1] = {1, 0};\n\n\tfor (int n = 1; ; n++) {\n\t\tfor (int i = n*81; i; i--) {\n\t\t\tfor (int j = 1; j < 10; j++) {\n\t\t\t\tint s = j*j;\n\t\t\t\tif (s > i) break;\n\t\t\t\tsums[i] += sums[i-s];\n\t\t\t}\n\t\t}\n\n\t\tull count89 = 0;\n\t\tfor (int i = 1; i < n*81 + 1; i++) {\n\t\t\tif (!is89(i)) continue;\n\n\t\t\tif (sums[i] > ~0ULL - count89) {\n\t\t\t\tprintf(\"counter overflow for 10^%d\\n\", n);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tcount89 += sums[i];\n\t\t}\n\n\t\tprintf(\"1->10^%d: %llu\\n\", n, count89);\n\t}\n\n\treturn 0;\n}"} {"title": "Jacobi symbol", "language": "C", "task": "The '''Jacobi symbol''' is a multiplicative function that generalizes the Legendre symbol. Specifically, the Jacobi symbol (a | n) equals the product of the Legendre symbols (a | p_i)^(k_i), where n = p_1^(k_1)*p_2^(k_2)*...*p_i^(k_i) and the Legendre symbol (a | p) denotes the value of a ^ ((p-1)/2) (mod p)\n* (a | p) 1 if a is a square (mod p)\n* (a | p) -1 if a is not a square (mod p)\n* (a | p) 0 if a 0 \n\nIf n is prime, then the Jacobi symbol (a | n) equals the Legendre symbol (a | n).\n\n;Task:\nCalculate the Jacobi symbol (a | n).\n\n;Reference:\n* Wikipedia article on Jacobi symbol.\n\n", "solution": "#include \n#include \n\n#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))\n\nint jacobi(unsigned long a, unsigned long n) {\n\tif (a >= n) a %= n;\n\tint result = 1;\n\twhile (a) {\n\t\twhile ((a & 1) == 0) {\n\t\t\ta >>= 1;\n\t\t\tif ((n & 7) == 3 || (n & 7) == 5) result = -result;\n\t\t}\n\t\tSWAP(a, n);\n\t\tif ((a & 3) == 3 && (n & 3) == 3) result = -result;\n\t\ta %= n;\n\t}\n\tif (n == 1) return result;\n\treturn 0;\n}\n\nvoid print_table(unsigned kmax, unsigned nmax) {\n\tprintf(\"n\\\\k|\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"%'3u\", k);\n\tprintf(\"\\n----\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"---\");\n\tputchar('\\n');\n\tfor (int n = 1; n <= nmax; n += 2) {\n\t\tprintf(\"%-2u |\", n);\n\t\tfor (int k = 0; k <= kmax; ++k)\n\t\t\tprintf(\"%'3d\", jacobi(k, n));\n\t\tputchar('\\n');\n\t}\n}\n\nint main() {\n\tprint_table(20, 21);\n\treturn 0;\n}"} {"title": "Jaro similarity", "language": "C", "task": "The Jaro distance is a measure of edit distance between two strings; its inverse, called the ''Jaro similarity'', is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that '''0''' equates to no similarities and '''1''' is an exact match.\n\n\n;;Definition\n\nThe Jaro similarity d_j of two given strings s_1 and s_2 is\n\n: d_j = \\left\\{\n\n\\begin{array}{l l}\n 0 & \\text{if }m = 0\\\\\n \\frac{1}{3}\\left(\\frac{m}{|s_1|} + \\frac{m}{|s_2|} + \\frac{m-t}{m}\\right) & \\text{otherwise} \\end{array} \\right.\n\nWhere:\n\n* m is the number of ''matching characters'';\n* t is half the number of ''transpositions''.\n\n\nTwo characters from s_1 and s_2 respectively, are considered ''matching'' only if they are the same and not farther apart than \\left\\lfloor\\frac{\\max(|s_1|,|s_2|)}{2}\\right\\rfloor-1 characters.\n\nEach character of s_1 is compared with all its matching characters in s_2. Each difference in position is half a ''transposition''; that is, the number of transpositions is half the number of characters which are common to the two strings but occupy different positions in each one.\n\n\n;;Example\n\nGiven the strings s_1 ''DWAYNE'' and s_2 ''DUANE'' we find:\n\n* m = 4\n* |s_1| = 6\n* |s_2| = 5\n* t = 0\n\n\nWe find a Jaro score of:\n\n: d_j = \\frac{1}{3}\\left(\\frac{4}{6} + \\frac{4}{5} + \\frac{4-0}{4}\\right) = 0.822\n\n\n;Task\n\nImplement the Jaro algorithm and show the similarity scores for each of the following pairs:\n\n* (\"MARTHA\", \"MARHTA\")\n* (\"DIXON\", \"DICKSONX\")\n* (\"JELLYFISH\", \"SMELLYFISH\")\n\n\n; See also\n* Jaro-Winkler distance on Wikipedia.\n\n", "solution": "#include \n#include \n#include \n#include \n\n#define TRUE 1\n#define FALSE 0\n\n#define max(a, b) ((a) > (b) ? (a) : (b))\n#define min(a, b) ((a) < (b) ? (a) : (b))\n\ndouble jaro(const char *str1, const char *str2) {\n // length of the strings\n int str1_len = strlen(str1);\n int str2_len = strlen(str2);\n\n // if both strings are empty return 1\n // if only one of the strings is empty return 0\n if (str1_len == 0) return str2_len == 0 ? 1.0 : 0.0;\n\n // max distance between two chars to be considered matching\n // floor() is ommitted due to integer division rules\n int match_distance = (int) max(str1_len, str2_len)/2 - 1;\n\n // arrays of bools that signify if that char in the matching string has a match\n int *str1_matches = calloc(str1_len, sizeof(int));\n int *str2_matches = calloc(str2_len, sizeof(int));\n\n // number of matches and transpositions\n double matches = 0.0;\n double transpositions = 0.0;\n\n // find the matches\n for (int i = 0; i < str1_len; i++) {\n // start and end take into account the match distance\n int start = max(0, i - match_distance);\n int end = min(i + match_distance + 1, str2_len);\n\n for (int k = start; k < end; k++) {\n // if str2 already has a match continue\n if (str2_matches[k]) continue;\n // if str1 and str2 are not\n if (str1[i] != str2[k]) continue;\n // otherwise assume there is a match\n str1_matches[i] = TRUE;\n str2_matches[k] = TRUE;\n matches++;\n break;\n }\n }\n\n // if there are no matches return 0\n if (matches == 0) {\n free(str1_matches);\n free(str2_matches);\n return 0.0;\n }\n\n // count transpositions\n int k = 0;\n for (int i = 0; i < str1_len; i++) {\n // if there are no matches in str1 continue\n if (!str1_matches[i]) continue;\n // while there is no match in str2 increment k\n while (!str2_matches[k]) k++;\n // increment transpositions\n if (str1[i] != str2[k]) transpositions++;\n k++;\n }\n\n // divide the number of transpositions by two as per the algorithm specs\n // this division is valid because the counted transpositions include both\n // instances of the transposed characters.\n transpositions /= 2.0;\n\n // free the allocated memory\n free(str1_matches);\n free(str2_matches);\n\n // return the Jaro distance\n return ((matches / str1_len) +\n (matches / str2_len) +\n ((matches - transpositions) / matches)) / 3.0;\n}\n\nint main() {\n printf(\"%f\\n\", jaro(\"MARTHA\", \"MARHTA\"));\n printf(\"%f\\n\", jaro(\"DIXON\", \"DICKSONX\"));\n printf(\"%f\\n\", jaro(\"JELLYFISH\", \"SMELLYFISH\"));\n}"} {"title": "Julia set", "language": "C", "task": "Task\nGenerate and draw a Julia set. \n\n\n;Related tasks\n* Mandelbrot Set\n\n", "solution": "#include\n#include\n#include\n\ntypedef struct{\n\tdouble x,y;\n}complex;\n\ncomplex add(complex a,complex b){\n\tcomplex c;\n\tc.x = a.x + b.x;\n\tc.y = a.y + b.y;\n\treturn c;\n}\n\ncomplex sqr(complex a){\n\tcomplex c;\n\tc.x = a.x*a.x - a.y*a.y;\n\tc.y = 2*a.x*a.y;\n\treturn c;\n}\n\ndouble mod(complex a){\n\treturn sqrt(a.x*a.x + a.y*a.y);\n}\n\ncomplex mapPoint(int width,int height,double radius,int x,int y){\n\tcomplex c;\n\tint l = (widthradius){\n\t\t\t\t\tputpixel(x,y,i%15+1);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tz0 = z1;\n\t\t\t}\n\t\t\tif(i>n)\n\t\t\t\tputpixel(x,y,0);\n\t\t}\n}\n\nint main(int argC, char* argV[])\n{\n\tint width, height;\n\tcomplex c;\n\t\n\tif(argC != 7)\n\t\tprintf(\"Usage : %s \");\n\telse{\n\t\twidth = atoi(argV[1]);\n\t\theight = atoi(argV[2]);\n\t\t\n\t\tc.x = atof(argV[3]);\n\t\tc.y = atof(argV[4]);\n\t\t\n\t\tinitwindow(width,height,\"Julia Set\");\n\t\tjuliaSet(width,height,c,atof(argV[5]),atoi(argV[6]));\n\t\t\n\t\tgetch();\n\t}\n\t\n\treturn 0;\n}\n"} {"title": "Jump anywhere", "language": "C", "task": "Imperative programs like to jump around, but some languages restrict these jumps. Many structured languages restrict their [[conditional structures]] and [[loops]] to ''local jumps'' within a function. Some assembly languages limit certain jumps or branches to a small range.\n\nThis task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. \nFor the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different purposes. \nYou may also defer to more specific tasks, like [[Exceptions]] or [[Generator]]. \nThis task provides a \"grab bag\" for several types of jumps. There are ''non-local jumps'' across function calls, or ''long jumps'' to anywhere within a program. Anywhere means not only to the tops of functions!\n\n* Some languages can ''go to'' any global label in a program.\n* Some languages can break multiple function calls, also known as ''unwinding the call stack''.\n* Some languages can save a ''continuation''. The program can later continue from the same place. So you can jump anywhere, but only if you have a previous visit there (to save the continuation).\n\nThese jumps are not all alike. \nA simple ''goto'' never touches the call stack. \nA continuation saves the call stack, so you can continue a function call after it ends.\n\n\n;Task:\nUse your language to demonstrate the various types of jumps that it supports. \n\nBecause the possibilities vary by language, this task is not specific. \nYou have the freedom to use these jumps for different purposes. \nYou may also defer to more specific tasks, like [[Exceptions]] or [[Generator]].\n\n", "solution": "char *str;\n int *array;\n FILE *fp;\n\n str = (char *) malloc(100);\n if(str == NULL) \n goto: exit;\n \n fp=fopen(\"c:\\\\test.csv\", \"r\");\n if(fp== NULL) \n goto: clean_up_str;\n \n array = (int *) malloc(15);\n if(array==NULL)\n goto: clean_up_file;\n ...// read in the csv file and convert to integers\n\n clean_up_array:\n free(array);\n clean_up_file:\n fclose(fp);\n clean_up_str:\n free(str );\n exit:\n return;\n"} {"title": "K-d tree", "language": "C", "task": "{{wikipedia|K-d tree}}\n\nA k-d tree (short for ''k''-dimensional tree) is a space-partitioning data structure for organizing points in a k-dimensional space. k-d trees are a useful data structure for several applications, such as searches involving a multidimensional search key (e.g. range searches and nearest neighbor searches). \nk-d trees are a special case of binary space partitioning trees.\n\nk-d trees are not suitable, however, for efficiently finding the nearest neighbor in high dimensional spaces. As a general rule, if the dimensionality is ''k'', the number of points in the data, ''N'', should be ''N'' 2''k''. \nOtherwise, when k-d trees are used with high-dimensional data, most of the points in the tree will be evaluated and the efficiency is no better than exhaustive search, and other methods such as approximate nearest-neighbor are used instead.\n\n'''Task:''' Construct a k-d tree and perform a nearest neighbor search for two example data sets:\n\n# The Wikipedia example data of [(2,3), (5,4), (9,6), (4,7), (8,1), (7,2)].\n# 1000 3-d points uniformly distributed in a 3-d cube.\n\nFor the Wikipedia example, find the nearest neighbor to point (9, 2)\nFor the random data, pick a random location and find the nearest neighbor.\n\nIn addition, instrument your code to count the number of nodes visited in the nearest neighbor search. Count a node as visited if any field of it is accessed.\n\nOutput should show the point searched for, the point found, \nthe distance to the point, and the number of nodes visited.\n\nThere are variant algorithms for constructing the tree. \nYou can use a simple median strategy or implement something more efficient. \nVariants of the nearest neighbor search include nearest N neighbors, approximate nearest neighbor, and range searches. \nYou do not have to implement these. \nThe requirement for this task is specifically the nearest single neighbor. \nAlso there are algorithms for inserting, deleting, and balancing k-d trees. \nThese are also not required for the task.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\n#define MAX_DIM 3\nstruct kd_node_t{\n double x[MAX_DIM];\n struct kd_node_t *left, *right;\n};\n\n inline double\ndist(struct kd_node_t *a, struct kd_node_t *b, int dim)\n{\n double t, d = 0;\n while (dim--) {\n t = a->x[dim] - b->x[dim];\n d += t * t;\n }\n return d;\n}\ninline void swap(struct kd_node_t *x, struct kd_node_t *y) {\n double tmp[MAX_DIM];\n memcpy(tmp, x->x, sizeof(tmp));\n memcpy(x->x, y->x, sizeof(tmp));\n memcpy(y->x, tmp, sizeof(tmp));\n}\n\n\n/* see quickselect method */\n struct kd_node_t*\nfind_median(struct kd_node_t *start, struct kd_node_t *end, int idx)\n{\n if (end <= start) return NULL;\n if (end == start + 1)\n return start;\n\n struct kd_node_t *p, *store, *md = start + (end - start) / 2;\n double pivot;\n while (1) {\n pivot = md->x[idx];\n\n swap(md, end - 1);\n for (store = p = start; p < end; p++) {\n if (p->x[idx] < pivot) {\n if (p != store)\n swap(p, store);\n store++;\n }\n }\n swap(store, end - 1);\n\n /* median has duplicate values */\n if (store->x[idx] == md->x[idx])\n return md;\n\n if (store > md) end = store;\n else start = store;\n }\n}\n\n struct kd_node_t*\nmake_tree(struct kd_node_t *t, int len, int i, int dim)\n{\n struct kd_node_t *n;\n\n if (!len) return 0;\n\n if ((n = find_median(t, t + len, i))) {\n i = (i + 1) % dim;\n n->left = make_tree(t, n - t, i, dim);\n n->right = make_tree(n + 1, t + len - (n + 1), i, dim);\n }\n return n;\n}\n\n/* global variable, so sue me */\nint visited;\n\nvoid nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim,\n struct kd_node_t **best, double *best_dist)\n{\n double d, dx, dx2;\n\n if (!root) return;\n d = dist(root, nd, dim);\n dx = root->x[i] - nd->x[i];\n dx2 = dx * dx;\n\n visited ++;\n\n if (!*best || d < *best_dist) {\n *best_dist = d;\n *best = root;\n }\n\n /* if chance of exact match is high */\n if (!*best_dist) return;\n\n if (++i >= dim) i = 0;\n\n nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist);\n if (dx2 >= *best_dist) return;\n nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist);\n}\n\n#define N 1000000\n#define rand1() (rand() / (double)RAND_MAX)\n#define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); }\nint main(void)\n{\n int i;\n struct kd_node_t wp[] = {\n {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}}\n };\n struct kd_node_t testNode = {{9, 2}};\n struct kd_node_t *root, *found, *million;\n double best_dist;\n\n root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2);\n\n visited = 0;\n found = 0;\n nearest(root, &testNode, 0, 2, &found, &best_dist);\n\n printf(\">> WP tree\\nsearching for (%g, %g)\\n\"\n \"found (%g, %g) dist %g\\nseen %d nodes\\n\\n\",\n testNode.x[0], testNode.x[1],\n found->x[0], found->x[1], sqrt(best_dist), visited);\n\n million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t));\n srand(time(0));\n for (i = 0; i < N; i++) rand_pt(million[i]);\n\n root = make_tree(million, N, 0, 3);\n rand_pt(testNode);\n\n visited = 0;\n found = 0;\n nearest(root, &testNode, 0, 3, &found, &best_dist);\n\n printf(\">> Million tree\\nsearching for (%g, %g, %g)\\n\"\n \"found (%g, %g, %g) dist %g\\nseen %d nodes\\n\",\n testNode.x[0], testNode.x[1], testNode.x[2],\n found->x[0], found->x[1], found->x[2],\n sqrt(best_dist), visited);\n\n /* search many random points in million tree to see average behavior.\n tree size vs avg nodes visited:\n 10 ~ 7\n 100 ~ 16.5\n 1000 ~ 25.5\n 10000 ~ 32.8\n 100000 ~ 38.3\n 1000000 ~ 42.6\n 10000000 ~ 46.7 */\n int sum = 0, test_runs = 100000;\n for (i = 0; i < test_runs; i++) {\n found = 0;\n visited = 0;\n rand_pt(testNode);\n nearest(root, &testNode, 0, 3, &found, &best_dist);\n sum += visited;\n }\n printf(\"\\n>> Million tree\\n\"\n \"visited %d nodes for %d random findings (%f per lookup)\\n\",\n sum, test_runs, sum/(double)test_runs);\n\n // free(million);\n\n return 0;\n}\n\n"} {"title": "Kaprekar numbers", "language": "C", "task": "A positive integer is a Kaprekar number if:\n* It is '''1''' (unity)\n* The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. \nNote that a split resulting in a part consisting purely of 0s is not valid, \nas 0 is not considered positive.\n\n\n;Example Kaprekar numbers:\n* 2223 is a Kaprekar number, as 2223 * 2223 = 4941729, 4941729 may be split to 494 and 1729, and 494 + 1729 = 2223.\n* The series of Kaprekar numbers is known as A006886, and begins as 1, 9, 45, 55, ....\n\n\n;Example process:\n10000 (1002) splitting from left to right:\n* The first split is [1, 0000], and is invalid; the 0000 element consists entirely of 0s, and 0 is not considered positive.\n* Slight optimization opportunity: When splitting from left to right, once the right part consists entirely of 0s, no further testing is needed; all further splits would also be invalid.\n\n\n;Task:\nGenerate and show all Kaprekar numbers less than 10,000. \n\n\n;Extra credit:\nOptionally, count (and report the count of) how many Kaprekar numbers are less than 1,000,000.\n\n\n;Extra extra credit:\nThe concept of Kaprekar numbers is not limited to base 10 (i.e. decimal numbers); \nif you can, show that Kaprekar numbers exist in other bases too. \n\n\nFor this purpose, do the following:\n* Find all Kaprekar numbers for base 17 between 1 and 1,000,000 (one million);\n* Display each of them in base 10 representation;\n* Optionally, using base 17 representation (use letters 'a' to 'g' for digits 10(10) to 16(10)), display each of the numbers, its square, and where to split the square. \n \nFor example, 225(10) is \"d4\" in base 17, its square \"a52g\", and a5(17) + 2g(17) = d4(17), so the display would be something like:225 d4 a52g a5 + 2g\n\n\n;Reference:\n* The Kaprekar Numbers by Douglas E. Iannucci (2000). PDF version\n\n\n;Related task:\n* [[Casting out nines]]\n\n", "solution": "#include \n#include \ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10) putchar(q + '0');\n\t\telse putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n 1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\"); print_num(i * i, base);\n\t\t\tprintf(\"\\t\"); print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}"} {"title": "Kernighans large earthquake problem", "language": "C", "task": "Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based.\n\n;Problem:\nYou are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event.\n\nExample lines from the file would be lines like:\n8/27/1883 Krakatoa 8.8\n5/18/1980 MountStHelens 7.6\n3/13/2009 CostaRica 5.1\n\n;Task:\n* Create a program or script invocation to find all the events with magnitude greater than 6\n* Assuming an appropriate name e.g. \"data.txt\" for the file:\n:# Either: Show how your program is invoked to process a data file of that name.\n:# Or: Incorporate the file name into the program, (as it is assumed that the program is single use).\n\n", "solution": "#include \n#include \n#include \n\nint main() {\n FILE *fp;\n char *line = NULL;\n size_t len = 0;\n ssize_t read;\n char *lw, *lt;\n fp = fopen(\"data.txt\", \"r\");\n if (fp == NULL) {\n printf(\"Unable to open file\\n\");\n exit(1);\n }\n printf(\"Those earthquakes with a magnitude > 6.0 are:\\n\\n\");\n while ((read = getline(&line, &len, fp)) != EOF) {\n if (read < 2) continue; /* ignore blank lines */\n lw = strrchr(line, ' '); /* look for last space */\n lt = strrchr(line, '\\t'); /* look for last tab */\n if (!lw && !lt) continue; /* ignore lines with no whitespace */\n if (lt > lw) lw = lt; /* lw points to last space or tab */\n if (atof(lw + 1) > 6.0) printf(\"%s\", line);\n }\n fclose(fp);\n if (line) free(line);\n return 0;\n}"} {"title": "Keyboard input/Obtain a Y or N response", "language": "C", "task": "Obtain a valid '''Y''' or '''N''' response from the [[input device::keyboard]]. \n\nThe keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing '''Y''' or '''N''' key-press from being evaluated. \n\nThe response should be obtained as soon as '''Y''' or '''N''' are pressed, and there should be no need to press an enter key.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n \nvoid set_mode(int want_key)\n{\n\tstatic struct termios old, new;\n\tif (!want_key) {\n\t\ttcsetattr(STDIN_FILENO, TCSANOW, &old);\n\t\treturn;\n\t}\n \n\ttcgetattr(STDIN_FILENO, &old);\n\tnew = old;\n\tnew.c_lflag &= ~(ICANON);\n\ttcsetattr(STDIN_FILENO, TCSANOW, &new);\n}\n \nint get_key(int no_timeout)\n{\n\tint c = 0;\n\tstruct timeval tv;\n\tfd_set fs;\n\ttv.tv_usec = tv.tv_sec = 0;\n \n\tFD_ZERO(&fs);\n\tFD_SET(STDIN_FILENO, &fs);\n\n\tselect(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv);\n\tif (FD_ISSET(STDIN_FILENO, &fs)) {\n\t\tc = getchar();\n\t\tset_mode(0);\n\t}\n\treturn c;\n}\n \nint main()\n{\n\tint c;\n\twhile(1) {\n\t\tset_mode(1);\n\t\twhile (get_key(0)); /* clear buffer */\n\t\tprintf(\"Prompt again [Y/N]? \");\n\t\tfflush(stdout);\n\n\t\tc = get_key(1);\n\t\tif (c == 'Y' || c == 'y') {\n\t\t\tprintf(\"\\n\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (c == 'N' || c == 'n') {\n\t\t\tprintf(\"\\nDone\\n\");\n\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"\\nYes or no?\\n\");\n\t}\n\n\treturn 0;\n}"} {"title": "Knight's tour", "language": "C", "task": "Task\nProblem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is ''not'' a requirement that the tour be \"closed\"; that is, the knight need not end within a single move of its start position.\n\nInput and output may be textual or graphical, according to the conventions of the programming environment. If textual, squares should be indicated in algebraic notation. The output should indicate the order in which the knight visits the squares, starting with the initial position. The form of the output may be a diagram of the board with the squares numbered according to visitation sequence, or a textual list of algebraic coordinates in order, or even an actual animation of the knight moving around the chessboard.\n\nInput: starting square\n\nOutput: move sequence\n\n\n;Related tasks\n* [[A* search algorithm]]\n* [[N-queens problem]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Holy Knight's tour]]\n* [[Solve a Hopido puzzle]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "#include \n#include \n#include \n#include \n\ntypedef unsigned char cell;\nint dx[] = { -2, -2, -1, 1, 2, 2, 1, -1 };\nint dy[] = { -1, 1, 2, 2, 1, -1, -2, -2 };\n\nvoid init_board(int w, int h, cell **a, cell **b)\n{\n\tint i, j, k, x, y, p = w + 4, q = h + 4;\n\t/* b is board; a is board with 2 rows padded at each side */\n\ta[0] = (cell*)(a + q);\n\tb[0] = a[0] + 2;\n\n\tfor (i = 1; i < q; i++) {\n\t\ta[i] = a[i-1] + p;\n\t\tb[i] = a[i] + 2;\n\t}\n\n\tmemset(a[0], 255, p * q);\n\tfor (i = 0; i < h; i++) {\n\t\tfor (j = 0; j < w; j++) {\n\t\t\tfor (k = 0; k < 8; k++) {\n\t\t\t\tx = j + dx[k], y = i + dy[k];\n\t\t\t\tif (b[i+2][j] == 255) b[i+2][j] = 0;\n\t\t\t\tb[i+2][j] += x >= 0 && x < w && y >= 0 && y < h;\n\t\t\t}\n\t\t}\n\t}\n}\n\n#define E \"\\033[\"\nint walk_board(int w, int h, int x, int y, cell **b)\n{\n\tint i, nx, ny, least;\n\tint steps = 0;\n\tprintf(E\"H\"E\"J\"E\"%d;%dH\"E\"32m[]\"E\"m\", y + 1, 1 + 2 * x);\n\n\twhile (1) {\n\t\t/* occupy cell */\n\t\tb[y][x] = 255;\n\n\t\t/* reduce all neighbors' neighbor count */\n\t\tfor (i = 0; i < 8; i++)\n\t\t\tb[ y + dy[i] ][ x + dx[i] ]--;\n\n\t\t/* find neighbor with lowest neighbor count */\n\t\tleast = 255;\n\t\tfor (i = 0; i < 8; i++) {\n\t\t\tif (b[ y + dy[i] ][ x + dx[i] ] < least) {\n\t\t\t\tnx = x + dx[i];\n\t\t\t\tny = y + dy[i];\n\t\t\t\tleast = b[ny][nx];\n\t\t\t}\n\t\t}\n\n\t\tif (least > 7) {\n\t\t\tprintf(E\"%dH\", h + 2);\n\t\t\treturn steps == w * h - 1;\n\t\t}\n\n\t\tif (steps++) printf(E\"%d;%dH[]\", y + 1, 1 + 2 * x);\n\t\tx = nx, y = ny;\n\t\tprintf(E\"%d;%dH\"E\"31m[]\"E\"m\", y + 1, 1 + 2 * x);\n\t\tfflush(stdout);\n\t\tusleep(120000);\n\t}\n}\n\nint solve(int w, int h)\n{\n\tint x = 0, y = 0;\n\tcell **a, **b;\n\ta = malloc((w + 4) * (h + 4) + sizeof(cell*) * (h + 4));\n\tb = malloc((h + 4) * sizeof(cell*));\n\n\twhile (1) {\n\t\tinit_board(w, h, a, b);\n\t\tif (walk_board(w, h, x, y, b + 2)) {\n\t\t\tprintf(\"Success!\\n\");\n\t\t\treturn 1;\n\t\t}\n\t\tif (++x >= w) x = 0, y++;\n\t\tif (y >= h) {\n\t\t\tprintf(\"Failed to find a solution\\n\");\n\t\t\treturn 0;\n\t\t}\n\t\tprintf(\"Any key to try next start position\");\n\t\tgetchar();\n\t}\n}\n\nint main(int c, char **v)\n{\n\tint w, h;\n\tif (c < 2 || (w = atoi(v[1])) <= 0) w = 8;\n\tif (c < 3 || (h = atoi(v[2])) <= 0) h = w;\n\tsolve(w, h);\n\n\treturn 0;\n}"} {"title": "Knuth's algorithm S", "language": "C", "task": "This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end.\nThis means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive samples can change).\n\n\n;The algorithm:\n:* Select the first n items as the sample as they become available;\n:* For the i-th item where i > n, have a random chance of n/i of keeping it. If failing this chance, the sample remains the same. If not, have it randomly (1/n) replace one of the previously selected n items of the sample.\n:* Repeat 2nd step for any subsequent items.\n\n\n;The Task:\n:* Create a function s_of_n_creator that given n the maximum sample size, returns a function s_of_n that takes one parameter, item.\n:* Function s_of_n when called with successive items returns an equi-weighted random sample of up to n of its items so far, each time it is called, calculated using Knuths Algorithm S.\n:* Test your functions by printing and showing the frequency of occurrences of the selected digits from 100,000 repetitions of:\n:::# Use the s_of_n_creator with n == 3 to generate an s_of_n.\n:::# call s_of_n with each of the digits 0 to 9 in order, keeping the returned three digits of its random sampling from its last call with argument item=9.\n\n\nNote: A class taking n and generating a callable instance/function might also be used.\n\n\n;Reference:\n* The Art of Computer Programming, Vol 2, 3.4.2 p.142\n\n\n;Related tasks: \n* [[One of n lines in a file]] \n* [[Accumulator factory]]\n\n", "solution": "#include \n#include \n#include \n#include \n\nstruct s_env {\n unsigned int n, i;\n size_t size;\n void *sample;\n};\n\nvoid s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)\n{\n s_env->i = 0;\n s_env->n = n;\n s_env->size = size;\n s_env->sample = malloc(n * size);\n}\n\nvoid sample_set_i(struct s_env *s_env, unsigned int i, void *item)\n{\n memcpy(s_env->sample + i * s_env->size, item, s_env->size);\n}\n\nvoid *s_of_n(struct s_env *s_env, void *item)\n{\n s_env->i++;\n if (s_env->i <= s_env->n)\n sample_set_i(s_env, s_env->i - 1, item);\n else if ((rand() % s_env->i) < s_env->n)\n sample_set_i(s_env, rand() % s_env->n, item);\n return s_env->sample;\n}\n\nint *test(unsigned int n, int *items_set, unsigned int num_items)\n{\n int i;\n struct s_env s_env;\n s_of_n_init(&s_env, sizeof(items_set[0]), n);\n for (i = 0; i < num_items; i++) {\n s_of_n(&s_env, (void *) &items_set[i]);\n }\n return (int *)s_env.sample;\n}\n\nint main()\n{\n unsigned int i, j;\n unsigned int n = 3;\n unsigned int num_items = 10;\n unsigned int *frequencies;\n int *items_set;\n srand(time(NULL));\n items_set = malloc(num_items * sizeof(int));\n frequencies = malloc(num_items * sizeof(int));\n for (i = 0; i < num_items; i++) {\n items_set[i] = i;\n frequencies[i] = 0;\n }\n for (i = 0; i < 100000; i++) {\n int *res = test(n, items_set, num_items);\n for (j = 0; j < n; j++) {\n frequencies[res[j]]++;\n }\n\tfree(res);\n }\n for (i = 0; i < num_items; i++) {\n printf(\" %d\", frequencies[i]);\n }\n puts(\"\");\n return 0;\n}"} {"title": "Koch curve", "language": "C", "task": "Draw a Koch curve. See details: Koch curve\n\n", "solution": "#include\n#include\n#include\n#include\n\n#define pi M_PI\n\ntypedef struct{\n\tdouble x,y;\n}point;\n\nvoid kochCurve(point p1,point p2,int times){\n\tpoint p3,p4,p5;\n\tdouble theta = pi/3;\n\t\n\tif(times>0){\n\t\tp3 = (point){(2*p1.x+p2.x)/3,(2*p1.y+p2.y)/3};\n\t\tp5 = (point){(2*p2.x+p1.x)/3,(2*p2.y+p1.y)/3};\n\t\t\n\t\tp4 = (point){p3.x + (p5.x - p3.x)*cos(theta) + (p5.y - p3.y)*sin(theta),p3.y - (p5.x - p3.x)*sin(theta) + (p5.y - p3.y)*cos(theta)};\n\t\t\n\t\tkochCurve(p1,p3,times-1);\n\t\tkochCurve(p3,p4,times-1);\n\t\tkochCurve(p4,p5,times-1);\n\t\tkochCurve(p5,p2,times-1);\n\t}\n\t\n\telse{\n\t\tline(p1.x,p1.y,p2.x,p2.y);\n\t}\n}\n\nint main(int argC, char** argV)\n{\n\tint w,h,r;\n\tpoint p1,p2;\n\t\n\tif(argC!=4){\n\t\tprintf(\"Usage : %s \",argV[0]);\n\t}\n\t\n\telse{\n\t\tw = atoi(argV[1]);\n\t\th = atoi(argV[2]);\n\t\tr = atoi(argV[3]);\n\t\t\n\t\tinitwindow(w,h,\"Koch Curve\");\n\t\t\n\t\tp1 = (point){10,h-10};\n\t\tp2 = (point){w-10,h-10};\n\t\t\n\t\tkochCurve(p1,p2,r);\n\t\t\n\t\tgetch();\n\t\n\t\tclosegraph();\n\t}\n\t\n\treturn 0;\n}\n"} {"title": "Largest int from concatenated ints", "language": "C", "task": "Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer.\n\nUse the following two sets of integers as tests and show your program output here.\n\n:::::* {1, 34, 3, 98, 9, 76, 45, 4}\n:::::* {54, 546, 548, 60}\n\n\n;Possible algorithms:\n# A solution could be found by trying all combinations and return the best. \n# Another way to solve this is to note that in the best arrangement, for any two adjacent original integers '''X''' and '''Y''', the concatenation '''X''' followed by '''Y''' will be numerically greater than or equal to the concatenation '''Y''' followed by '''X.\n# Yet another way to solve this is to pad the integers to the same size by repeating the digits then sort using these repeated integers as a sort key.\n\n\n;See also:\n* Algorithms: What is the most efficient way to arrange the given numbers to form the biggest number?\n* Constructing the largest number possible by rearranging a list\n\n", "solution": "#include \n#include \n#include \n\nint catcmp(const void *a, const void *b)\n{\n\tchar ab[32], ba[32];\n\tsprintf(ab, \"%d%d\", *(int*)a, *(int*)b);\n\tsprintf(ba, \"%d%d\", *(int*)b, *(int*)a);\n\treturn strcmp(ba, ab);\n}\n\nvoid maxcat(int *a, int len)\n{\n\tint i;\n\tqsort(a, len, sizeof(int), catcmp);\n\tfor (i = 0; i < len; i++)\n\t\tprintf(\"%d\", a[i]);\n\tputchar('\\n');\n}\n\nint main(void)\n{\n\tint x[] = {1, 34, 3, 98, 9, 76, 45, 4};\n\tint y[] = {54, 546, 548, 60};\n\n\tmaxcat(x, sizeof(x)/sizeof(x[0]));\n\tmaxcat(y, sizeof(y)/sizeof(y[0]));\n\n\treturn 0;\n}"} {"title": "Largest number divisible by its digits", "language": "C", "task": "Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.\n\n\nThese numbers are also known as '''Lynch-Bell numbers''', numbers '''n''' such that the\n(base ten) digits are all different (and do not include zero) and '''n''' is divisible by each of its individual digits. \n\n\n;Example:\n'''135''' is evenly divisible by '''1''', '''3''', and '''5'''.\n\n\nNote that the digit zero (0) can not be in the number as integer division by zero is undefined. \n\nThe digits must all be unique so a base ten number will have at most '''9''' digits.\n\nFeel free to use analytics and clever algorithms to reduce the search space your example needs to visit, but it must do an actual search. (Don't just feed it the answer and verify it is correct.)\n\n\n;Stretch goal:\nDo the same thing for hexadecimal.\n\n\n;Related tasks:\n:* gapful numbers.\n:* palindromic gapful numbers. \n\n\n;Also see:\n:* The OEIS sequence: A115569: Lynch-Bell numbers. \n\n", "solution": "#include\n\nint main()\n{\n\tint num = 9876432,diff[] = {4,2,2,2},i,j,k=0;\n\tchar str[10];\n\t\n\t\tstart:snprintf(str,10,\"%d\",num);\n\n\t\tfor(i=0;str[i+1]!=00;i++){\n\t\t\tif(str[i]=='0'||str[i]=='5'||num%(str[i]-'0')!=0){\n\t\t\t\tnum -= diff[k];\n\t\t\t\tk = (k+1)%4;\n\t\t\t\tgoto start;\n\t\t\t}\n\t\t\tfor(j=i+1;str[j]!=00;j++)\n\t\t\t\tif(str[i]==str[j]){\n\t\t\t\t\tnum -= diff[k];\n\t\t\t\t\tk = (k+1)%4;\n\t\t\t\t\tgoto start;\n\t\t\t}\n\t\t}\t\n\t\n\tprintf(\"Number found : %d\",num);\n\treturn 0;\n}\n"} {"title": "Largest proper divisor of n", "language": "C", "task": "a(1) = 1; for n > 1, a(n) = '''largest''' proper divisor of n, where '''n < 101 '''.\n\n", "solution": "#include \n\nunsigned int lpd(unsigned int n) {\n if (n<=1) return 1;\n int i;\n for (i=n-1; i>0; i--)\n if (n%i == 0) return i; \n}\n\nint main() {\n int i;\n for (i=1; i<=100; i++) {\n printf(\"%3d\", lpd(i));\n if (i % 10 == 0) printf(\"\\n\");\n }\n return 0;\n}"} {"title": "Last Friday of each month", "language": "C", "task": "Write a program or a script that returns the date of the last Fridays of each month of a given year. \n\nThe year may be given through any simple input method in your language (command line, std in, etc).\n\n\nExample of an expected output:\n./last_fridays 2012\n2012-01-27\n2012-02-24\n2012-03-30\n2012-04-27\n2012-05-25\n2012-06-29\n2012-07-27\n2012-08-31\n2012-09-28\n2012-10-26\n2012-11-30\n2012-12-28\n\n\n;Related tasks\n* [[Five weekends]]\n* [[Day of the week]]\n* [[Find the last Sunday of each month]]\n\n", "solution": "#include \n#include \n\nint main(int c, char *v[])\n{\n\tint days[] = {31,29,31,30,31,30,31,31,30,31,30,31};\n\tint m, y, w;\n\n\tif (c < 2 || (y = atoi(v[1])) <= 1700) return 1;\n \tdays[1] -= (y % 4) || (!(y % 100) && (y % 400));\n\tw = y * 365 + (y - 1) / 4 - (y - 1) / 100 + (y - 1) / 400 + 6;\n\n\tfor(m = 0; m < 12; m++) {\n\t\tw = (w + days[m]) % 7;\n\t\tprintf(\"%d-%02d-%d\\n\", y, m + 1,\n\t\t\tdays[m] + (w < 5 ? -2 : 5) - w);\n\t}\n\n\treturn 0;\n}"} {"title": "Last letter-first letter", "language": "C", "task": "A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the game. \n\n\nFor example, with \"animals\" as the category,\n\nChild 1: dog \nChild 2: goldfish\nChild 1: hippopotamus\nChild 2: snake\n...\n\n\n\n;Task:\nTake the following selection of 70 English Pokemon names (extracted from Wikipedia's list of Pokemon) and generate the/a sequence with the highest possible number of Pokemon names where the subsequent name starts with the final letter of the preceding name. \n\nNo Pokemon name is to be repeated.\n\n\naudino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon\ncresselia croagunk darmanitan deino emboar emolga exeggcute gabite\ngirafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan\nkricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine\nnosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2\nporygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking\nsealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko\ntyrogue vigoroth vulpix wailord wartortle whismur wingull yamask\n\n\n\nExtra brownie points for dealing with the full list of 646 names.\n\n", "solution": "#include \n#include \n#include \n#include \n\n#define forall(i, n) for (int i = 0; i < n; i++)\ntypedef struct edge { char s, e, *str; struct edge *lnk; } edge;\ntypedef struct { edge* e[26]; int nin, nout, in[26], out[26];} node;\ntypedef struct { edge *e, *tail; int len, has[26]; } chain;\n\nnode nodes[26];\nedge *names, **tmp;\nint n_names;\n\n/* add edge to graph */\nvoid store_edge(edge *g)\n{\n\tif (!g) return;\n\tint i = g->e, j = g->s;\n\tnode *n = nodes + j;\n\n\tg->lnk = n->e[i];\n\n\tn->e[i] = g, n->out[i]++, n->nout++;\n\tn = nodes + i, n->in[j]++, n->nin++;\n}\n\n/* unlink an edge between nodes i and j, and return the edge */\nedge* remove_edge(int i, int j)\n{\n\tnode *n = nodes + i;\n\tedge *g = n->e[j];\n\tif (g) {\n\t\tn->e[j] = g->lnk;\n\t\tg->lnk = 0;\n\t\tn->out[j]--, n->nout--;\n\n\t\tn = nodes + j;\n\t\tn->in[i]--;\n\t\tn->nin--;\n\t}\n\treturn g;\n}\n\nvoid read_names()\n{\n\tFILE *fp = fopen(\"poke646\", \"rt\");\n\tint i, len;\n\tchar *buf;\n\tedge *p;\n\n\tif (!fp) abort();\n\n\tfseek(fp, 0, SEEK_END);\n\tlen = ftell(fp);\n\tbuf = malloc(len + 1);\n\tfseek(fp, 0, SEEK_SET);\n\tfread(buf, 1, len, fp);\n\tfclose(fp);\n\n\tbuf[len] = 0;\n\tfor (n_names = i = 0; i < len; i++)\n\t\tif (isspace(buf[i]))\n\t\t\tbuf[i] = 0, n_names++;\n\n\tif (buf[len-1]) n_names++;\n\n\tmemset(nodes, 0, sizeof(node) * 26);\n\ttmp = calloc(n_names, sizeof(edge*));\n\n\tp = names = malloc(sizeof(edge) * n_names);\n\tfor (i = 0; i < n_names; i++, p++) {\n\t\tif (i)\tp->str = names[i-1].str + len + 1;\n\t\telse\tp->str = buf;\n\n\t\tlen = strlen(p->str);\n\t\tp->s = p->str[0] - 'a';\n\t\tp->e = p->str[len-1] - 'a';\n\t\tif (p->s < 0 || p->s >= 26 || p->e < 0 || p->e >= 26) {\n\t\t\tprintf(\"bad name %s: first/last char must be letter\\n\", \n\t\t\t\tp->str);\n\t\t\tabort();\n\t\t}\n\t}\n\tprintf(\"read %d names\\n\", n_names);\n}\n\nvoid show_chain(chain *c)\n{\n\tprintf(\"%d:\", c->len);\n\tfor (edge * e = c->e; e || !putchar('\\n'); e = e->lnk)\n\t\tprintf(\" %s\", e->str);\n}\n\n/* Which next node has most enter or exit edges. */\nint widest(int n, int out)\n{\n\tif (nodes[n].out[n]) return n;\n\n\tint mm = -1, mi = -1;\n\tforall(i, 26) {\n\t\tif (out) {\n\t\t\tif (nodes[n].out[i] && nodes[i].nout > mm)\n\t\t\t\tmi = i, mm = nodes[i].nout;\n\t\t} else {\n\t\t\tif (nodes[i].out[n] && nodes[i].nin > mm)\n\t\t\t\tmi = i, mm = nodes[i].nin;\n\t\t}\n\t}\n\n\treturn mi;\n}\n\nvoid insert(chain *c, edge *e)\n{\n\te->lnk = c->e;\n\tif (!c->tail) c->tail = e;\n\tc->e = e;\n\tc->len++;\n}\n\nvoid append(chain *c, edge *e)\n{\n\tif (c->tail) c->tail->lnk = e;\n\telse c->e = e;\n\tc->tail = e;\n\tc->len++;\n}\n\nedge * shift(chain *c)\n{\n\tedge *e = c->e;\n\tif (e) {\n\t\tc->e = e->lnk;\n\t\tif (!--c->len) c->tail = 0;\n\t}\n\treturn e;\n}\n\nchain* make_chain(int s)\n{\n\tchain *c = calloc(1, sizeof(chain));\n\t\n\t/* extend backwards */\n\tfor (int i, j = s; (i = widest(j, 0)) >= 0; j = i)\n\t\tinsert(c, remove_edge(i, j));\n\n\t/* extend forwards */\n\tfor (int i, j = s; (i = widest(j, 1)) >= 0; j = i)\n\t\tappend(c, remove_edge(j, i));\n\n\tfor (int step = 0;; step++) {\n\t\tedge *e = c->e;\n\n\t\tfor (int i = 0; i < step; i++)\n\t\t\tif (!(e = e->lnk)) break;\n\t\tif (!e) return c;\n\n\t\tint n = 0;\n\t\tfor (int i, j = e->s; (i = widest(j, 0)) >= 0; j = i) {\n\t\t\tif (!(e = remove_edge(i, j))) break;\n\t\t\ttmp[n++] = e;\n\t\t}\n\n\t\tif (n > step) {\n\t\t\tforall(i, step) store_edge(shift(c));\n\t\t\tforall(i, n) insert(c, tmp[i]);\n\t\t\tstep = -1;\n\t\t} else while (--n >= 0)\n\t\t\tstore_edge(tmp[n]);\n\t}\n\treturn c;\n}\n\nint main(void)\n{\n\tint best = 0;\n\tread_names();\n\n\tforall(i, 26) {\n\t\t/* rebuild the graph */\n\t\tmemset(nodes, 0, sizeof(nodes));\n\t\tforall(j, n_names) store_edge(names + j);\n\n\t\t/* make a chain from node i */\n\t\tchain *c = make_chain(i);\n\t\tif (c->len > best) {\n\t\t\tshow_chain(c);\n\t\t\tbest = c->len;\n\t\t}\n\t\tfree(c);\n\t}\n\n\tprintf(\"longest found: %d\\n\", best);\n\treturn 0;\n}"} {"title": "Law of cosines - triples", "language": "C", "task": "The Law of cosines states that for an angle g, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula:\n A2 + B2 - 2ABcos(g) = C2 \n\n;Specific angles:\nFor an angle of of '''90o''' this becomes the more familiar \"Pythagoras equation\":\n A2 + B2 = C2 \n\nFor an angle of '''60o''' this becomes the less familiar equation:\n A2 + B2 - AB = C2 \n\nAnd finally for an angle of '''120o''' this becomes the equation:\n A2 + B2 + AB = C2 \n\n\n;Task:\n* Find all integer solutions (in order) to the three specific cases, distinguishing between each angle being considered.\n* Restrain all sides to the integers '''1..13''' inclusive.\n* Show how many results there are for each of the three angles mentioned above.\n* Display results on this page.\n\n\nNote: Triangles with the same length sides but different order are to be treated as the same. \n\n;Optional Extra credit:\n* How many 60deg integer triples are there for sides in the range 1..10_000 ''where the sides are not all of the same length''.\n\n\n;Related Task\n* [[Pythagorean triples]]\n\n\n;See also:\n* Visualising Pythagoras: ultimate proofs and crazy contortions Mathlogger Video\n\n", "solution": "/*\n * RossetaCode: Law of cosines - triples\n *\n * An quick and dirty brute force solutions with O(N^3) cost.\n * Anyway it is possible set MAX_SIDE_LENGTH equal to 10000 \n * and use fast computer to obtain the \"extra credit\" badge.\n *\n * Obviously, there are better algorithms.\n */\n\n#include \n#include \n\n#define MAX_SIDE_LENGTH 13\n//#define DISPLAY_TRIANGLES 1\n\nint main(void)\n{\n static char description[3][80] = {\n \"gamma = 90 degrees, a*a + b*b == c*c\",\n \"gamma = 60 degrees, a*a + b*b - a*b == c*c\",\n \"gamma = 120 degrees, a*a + b*b + a*b == c*c\"\n };\n static int coeff[3] = { 0, 1, -1 };\n\n for (int k = 0; k < 3; k++)\n {\n int counter = 0;\n for (int a = 1; a <= MAX_SIDE_LENGTH; a++)\n for (int b = 1; b <= a; b++)\n for (int c = 1; c <= MAX_SIDE_LENGTH; c++)\n if (a * a + b * b - coeff[k] * a * b == c * c)\n {\n counter++;\n#ifdef DISPLAY_TRIANGLES\n printf(\" %d %d %d\\n\", a, b, c);\n#endif\n }\n printf(\"%s, number of triangles = %d\\n\", description[k], counter);\n }\n\n return 0;\n}\n"} {"title": "Least common multiple", "language": "C", "task": "Compute the least common multiple (LCM) of two integers.\n\nGiven ''m'' and ''n'', the least common multiple is the smallest positive integer that has both ''m'' and ''n'' as factors. \n\n\n;Example:\nThe least common multiple of '''12''' and '''18''' is '''36''', because:\n:* '''12''' is a factor ('''12''' x '''3''' = '''36'''), and \n:* '''18''' is a factor ('''18''' x '''2''' = '''36'''), and \n:* there is no positive integer less than '''36''' that has both factors. \n\n\nAs a special case, if either ''m'' or ''n'' is zero, then the least common multiple is zero.\n\n\nOne way to calculate the least common multiple is to iterate all the multiples of ''m'', until you find one that is also a multiple of ''n''.\n\nIf you already have ''gcd'' for [[greatest common divisor]], then this formula calculates ''lcm''.\n\n\n:::: \\operatorname{lcm}(m, n) = \\frac{|m \\times n|}{\\operatorname{gcd}(m, n)}\n\n\nOne can also find ''lcm'' by merging the [[prime decomposition]]s of both ''m'' and ''n''.\n\n\n;Related task\n:* greatest common divisor.\n\n\n;See also:\n* MathWorld entry: Least Common Multiple.\n* Wikipedia entry: Least common multiple.\n\n", "solution": "#include \n\nint gcd(int m, int n)\n{\n int tmp;\n while(m) { tmp = m; m = n % m; n = tmp; } \n return n;\n}\n\nint lcm(int m, int n)\n{\n return m / gcd(m, n) * n;\n}\n\nint main()\n{\n printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n return 0;\n}"} {"title": "Levenshtein distance", "language": "C", "task": "{{Wikipedia}}\n\nIn information theory and computer science, the '''Levenshtein distance''' is a edit distance). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character. \n\n\n;Example:\nThe Levenshtein distance between \"'''kitten'''\" and \"'''sitting'''\" is 3, since the following three edits change one into the other, and there isn't a way to do it with fewer than three edits:\n::# '''k'''itten '''s'''itten (substitution of 'k' with 's')\n::# sitt'''e'''n sitt'''i'''n (substitution of 'e' with 'i')\n::# sittin sittin'''g''' (insert 'g' at the end).\n\n\n''The Levenshtein distance between \"'''rosettacode'''\", \"'''raisethysword'''\" is '''8'''.\n\n''The distance between two strings is same as that when both strings are reversed.''\n\n\n;Task:\nImplements a Levenshtein distance function, or uses a library function, to show the Levenshtein distance between \"kitten\" and \"sitting\". \n\n\n;Related task:\n* [[Longest common subsequence]]\n\n\n\n", "solution": "#include \n#include \n\n/* s, t: two strings; ls, lt: their respective length */\nint levenshtein(const char *s, int ls, const char *t, int lt)\n{\n int a, b, c;\n\n /* if either string is empty, difference is inserting all chars \n * from the other\n */\n if (!ls) return lt;\n if (!lt) return ls;\n\n /* if last letters are the same, the difference is whatever is\n * required to edit the rest of the strings\n */\n if (s[ls - 1] == t[lt - 1])\n return levenshtein(s, ls - 1, t, lt - 1);\n\n /* else try:\n * changing last letter of s to that of t; or\n * remove last letter of s; or\n * remove last letter of t,\n * any of which is 1 edit plus editing the rest of the strings\n */\n a = levenshtein(s, ls - 1, t, lt - 1);\n b = levenshtein(s, ls, t, lt - 1);\n c = levenshtein(s, ls - 1, t, lt );\n\n if (a > b) a = b;\n if (a > c) a = c;\n\n return a + 1;\n}\n\nint main()\n{\n const char *s1 = \"rosettacode\";\n const char *s2 = \"raisethysword\";\n printf(\"distance between `%s' and `%s': %d\\n\", s1, s2,\n levenshtein(s1, strlen(s1), s2, strlen(s2)));\n\n return 0;\n}"} {"title": "Levenshtein distance/Alignment", "language": "C", "task": "The [[Levenshtein distance]] algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order.\n\nAn alignment is a notation used to describe the operations used to turn a string into an other. At some point in the strings, the minus character ('-') is placed in order to signify that a character must be added at this very place. For instance, an alignment between the words 'place' and 'palace' is:\n\n\nP-LACE\nPALACE\n\n\n\n;Task:\nWrite a function that shows the alignment of two strings for the corresponding levenshtein distance. \n\nAs an example, use the words \"rosettacode\" and \"raisethysword\".\n\nYou can either implement an algorithm, or use a dedicated library (thus showing us how it is named in your language).\n\n", "solution": "#include \n#include \n#include \n\ntypedef struct edit_s edit_t, *edit;\nstruct edit_s {\n\tchar c1, c2;\n\tint n;\n\tedit next;\n};\n\nvoid leven(char *a, char *b)\n{\n\tint i, j, la = strlen(a), lb = strlen(b);\n\tedit *tbl = malloc(sizeof(edit) * (1 + la));\n\ttbl[0] = calloc((1 + la) * (1 + lb), sizeof(edit_t));\n\tfor (i = 1; i <= la; i++)\n\t\ttbl[i] = tbl[i-1] + (1+lb);\n\n\tfor (i = la; i >= 0; i--) {\n\t\tchar *aa = a + i;\n\t\tfor (j = lb; j >= 0; j--) {\n\t\t\tchar *bb = b + j;\n\t\t\tif (!*aa && !*bb) continue;\n\n\t\t\tedit e = &tbl[i][j];\n\t\t\tedit repl = &tbl[i+1][j+1];\n\t\t\tedit dela = &tbl[i+1][j];\n\t\t\tedit delb = &tbl[i][j+1];\n\n\t\t\te->c1 = *aa;\n\t\t\te->c2 = *bb;\n\t\t\tif (!*aa) {\n\t\t\t\te->next = delb;\n\t\t\t\te->n = e->next->n + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!*bb) {\n\t\t\t\te->next = dela;\n\t\t\t\te->n = e->next->n + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\te->next = repl;\n\t\t\tif (*aa == *bb) {\n\t\t\t\te->n = e->next->n;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (e->next->n > delb->n) {\n\t\t\t\te->next = delb;\n\t\t\t\te->c1 = 0;\n\t\t\t}\n\t\t\tif (e->next->n > dela->n) {\n\t\t\t\te->next = dela;\n\t\t\t\te->c1 = *aa;\n\t\t\t\te->c2 = 0;\n\t\t\t}\n\t\t\te->n = e->next->n + 1;\n\t\t}\n\t}\n\n\tedit p = tbl[0];\n\tprintf(\"%s -> %s: %d edits\\n\", a, b, p->n);\n\n\twhile (p->next) {\n\t\tif (p->c1 == p->c2)\n\t\t\tprintf(\"%c\", p->c1);\n\t\telse {\n\t\t\tputchar('(');\n\t\t\tif (p->c1) putchar(p->c1);\n\t\t\tputchar(',');\n\t\t\tif (p->c2) putchar(p->c2);\n\t\t\tputchar(')');\n\t\t}\n\n\t\tp = p->next;\n\t}\n\tputchar('\\n');\n\n\tfree(tbl[0]);\n\tfree(tbl);\n}\n\nint main(void)\n{\n\tleven(\"raisethysword\", \"rosettacode\");\n\treturn 0;\n}"} {"title": "List rooted trees", "language": "C", "task": "You came back from grocery shopping. After putting away all the goods, you are left with a pile of plastic bags, which you want to save for later use, so you take one bag and stuff all the others into it, and throw it under the sink. In doing so, you realize that there are various ways of nesting the bags, with all bags viewed as identical.\n\nIf we use a matching pair of parentheses to represent a bag, the ways are:\n\nFor 1 bag, there's one way:\n ()\t<- a bag\n\nfor 2 bags, there's one way:\n (())\t<- one bag in another\n\nfor 3 bags, there are two:\n ((())) <- 3 bags nested Russian doll style\n (()()) <- 2 bags side by side, inside the third\n\nfor 4 bags, four:\n (()()())\n ((())())\n ((()()))\n (((())))\n\nNote that because all bags are identical, the two 4-bag strings ((())()) and (()(())) represent the same configuration.\n\nIt's easy to see that each configuration for ''n'' bags represents a ''n''-node rooted tree, where a bag is a tree node, and a bag with its content forms a subtree. The outermost bag is the tree root. Number of configurations for given ''n'' is given by OEIS A81.\n\n\n;Task: \nWrite a program that, when given ''n'', enumerates all ways of nesting ''n'' bags. You can use the parentheses notation above, or any tree representation that's unambiguous and preferably intuitive.\n\nThis task asks for enumeration of trees only; for counting solutions without enumeration, that OEIS page lists various formulas, but that's not encouraged by this task, especially if implementing it would significantly increase code size.\n\nAs an example output, run 5 bags. There should be 9 ways.\n\n", "solution": "#include \n#include \n\ntypedef unsigned int uint;\ntypedef unsigned long long tree;\n#define B(x) (1ULL<<(x))\n\ntree *list = 0;\nuint cap = 0, len = 0;\nuint offset[32] = {0, 1, 0};\n\nvoid append(tree t)\n{\n\tif (len == cap) {\n\t\tcap = cap ? cap*2 : 2;\n\t\tlist = realloc(list, cap*sizeof(tree));\n\t}\n\tlist[len++] = 1 | t<<1;\n}\n\nvoid show(tree t, uint len)\n{\n\tfor (; len--; t >>= 1)\n\t\tputchar(t&1 ? '(' : ')');\n}\n\nvoid listtrees(uint n)\n{\n\tuint i;\n\tfor (i = offset[n]; i < offset[n+1]; i++) {\n\t\tshow(list[i], n*2);\n\t\tputchar('\\n');\n\t}\n}\n\n/* assemble tree from subtrees\n\tn: length of tree we want to make\n\tt: assembled parts so far\n\tsl: length of subtree we are looking at\n\tpos: offset of subtree we are looking at\n\trem: remaining length to be put together\n*/\nvoid assemble(uint n, tree t, uint sl, uint pos, uint rem)\n{\n\tif (!rem) {\n\t\tappend(t);\n\t\treturn;\n\t}\n\n\tif (sl > rem) // need smaller subtrees\n\t\tpos = offset[sl = rem];\n\telse if (pos >= offset[sl + 1]) {\n\t\t// used up sl-trees, try smaller ones\n\t\tif (!--sl) return;\n\t\tpos = offset[sl];\n\t}\n\n\tassemble(n, t<<(2*sl) | list[pos], sl, pos, rem - sl);\n\tassemble(n, t, sl, pos + 1, rem);\n}\n\nvoid mktrees(uint n)\n{\n\tif (offset[n + 1]) return;\n\tif (n) mktrees(n - 1);\n\n\tassemble(n, 0, n-1, offset[n-1], n-1);\n\toffset[n+1] = len;\n}\n\nint main(int c, char**v)\n{\n\tint n;\n\tif (c < 2 || (n = atoi(v[1])) <= 0 || n > 25) n = 5;\n\n\t// init 1-tree\n\tappend(0);\n\n\tmktrees((uint)n);\n\tfprintf(stderr, \"Number of %d-trees: %u\\n\", n, offset[n+1] - offset[n]);\n\tlisttrees((uint)n);\n\n\treturn 0;\n}"} {"title": "Long year", "language": "C", "task": "Most years have 52 weeks, some have 53, according to ISO8601.\n\n\n;Task:\nWrite a function which determines if a given year is long (53 weeks) or not, and demonstrate it.\n\n", "solution": "#include \n#include \n\n// https://webspace.science.uu.nl/~gent0113/calendar/isocalendar.htm\n\nint p(int year) {\n\treturn (int)((double)year + floor(year/4) - floor(year/100) + floor(year/400)) % 7;\n}\n\nint is_long_year(int year) {\n\treturn p(year) == 4 || p(year - 1) == 3;\n}\n\nvoid print_long_years(int from, int to) {\n\tfor (int year = from; year <= to; ++year) {\n\t\tif (is_long_year(year)) {\n\t\t\tprintf(\"%d \", year);\n\t\t}\n\t}\n}\n\nint main() {\n\n\tprintf(\"Long (53 week) years between 1800 and 2100\\n\\n\");\n\tprint_long_years(1800, 2100);\n\tprintf(\"\\n\");\n\treturn 0;\n}"} {"title": "Longest common subsequence", "language": "C", "task": "'''Introduction'''\n\nDefine a ''subsequence'' to be any output string obtained by deleting zero or more symbols from an input string.\n\nThe '''Longest Common Subsequence''' ('''LCS''') is a subsequence of maximum length common to two or more strings.\n\nLet ''A'' ''A''[0]... ''A''[m - 1] and ''B'' ''B''[0]... ''B''[n - 1], m < n be strings drawn from an alphabet S of size s, containing every distinct symbol in A + B.\n\nAn ordered pair (i, j) will be referred to as a match if ''A''[i] = ''B''[j], where 0 <= i < m and 0 <= j < n.\n\nThe set of matches '''M''' defines a relation over matches: '''M'''[i, j] = (i, j) '''M'''.\n\nDefine a ''non-strict'' product-order (<=) over ordered pairs, such that (i1, j1) <= (i2, j2) = i1 <= i2 and j1 <= j2. We define (>=) similarly.\n\nWe say ordered pairs p1 and p2 are ''comparable'' if either p1 <= p2 or p1 >= p2 holds. If i1 < i2 and j2 < j1 (or i2 < i1 and j1 < j2) then neither p1 <= p2 nor p1 >= p2 are possible, and we say p1 and p2 are ''incomparable''.\n\nDefine the ''strict'' product-order (<) over ordered pairs, such that (i1, j1) < (i2, j2) = i1 < i2 and j1 < j2. We define (>) similarly.\n\nA chain '''C''' is a subset of '''M''' consisting of at least one element m; and where either m1 < m2 or m1 > m2 for every pair of distinct elements m1 and m2. An antichain '''D''' is any subset of '''M''' in which every pair of distinct elements m1 and m2 are incomparable.\n\nA chain can be visualized as a strictly increasing curve that passes through matches (i, j) in the m*n coordinate space of '''M'''[i, j].\n\nEvery Common Sequence of length ''q'' corresponds to a chain of cardinality ''q'', over the set of matches '''M'''. Thus, finding an LCS can be restated as the problem of finding a chain of maximum cardinality ''p''.\n\nAccording to [Dilworth 1950], this cardinality ''p'' equals the minimum number of disjoint antichains into which '''M''' can be decomposed. Note that such a decomposition into the minimal number p of disjoint antichains may not be unique.\n\n'''Background'''\n\nWhere the number of symbols appearing in matches is small relative to the length of the input strings, reuse of the symbols increases; and the number of matches will tend towards O(''m*n'') quadratic growth. This occurs, for example, in the Bioinformatics application of nucleotide and protein sequencing.\n\nThe divide-and-conquer approach of [Hirschberg 1975] limits the space required to O(''n''). However, this approach requires O(''m*n'') time even in the best case.\n\nThis quadratic time dependency may become prohibitive, given very long input strings. Thus, heuristics are often favored over optimal Dynamic Programming solutions.\n\nIn the application of comparing file revisions, records from the input files form a large symbol space; and the number of symbols approaches the length of the LCS. In this case the number of matches reduces to linear, O(''n'') growth.\n\nA binary search optimization due to [Hunt and Szymanski 1977] can be applied to the basic Dynamic Programming approach, resulting in an expected performance of O(''n log m''). Performance can degrade to O(''m*n log m'') time in the worst case, as the number of matches grows to O(''m*n'').\n\n'''Note'''\n\n[Rick 2000] describes a linear-space algorithm with a time bound of O(''n*s + p*min(m, n - p)'').\n\n'''Legend'''\n\n A, B are input strings of lengths m, n respectively\n p is the length of the LCS\n M is the set of matches (i, j) such that A[i] = B[j]\n r is the magnitude of M\n s is the magnitude of the alphabet S of distinct symbols in A + B\n\n'''References'''\n\n[Dilworth 1950] \"A decomposition theorem for partially ordered sets\"\nby Robert P. Dilworth, published January 1950,\nAnnals of Mathematics [Volume 51, Number 1, ''pp.'' 161-166]\n\n[Goeman and Clausen 2002] \"A New Practical Linear Space Algorithm for the Longest Common\nSubsequence Problem\" by Heiko Goeman and Michael Clausen,\npublished 2002, Kybernetika [Volume 38, Issue 1, ''pp.'' 45-66]\n\n[Hirschberg 1975] \"A linear space algorithm for computing maximal common subsequences\"\nby Daniel S. Hirschberg, published June 1975\nCommunications of the ACM [Volume 18, Number 6, ''pp.'' 341-343]\n\n[Hunt and McIlroy 1976] \"An Algorithm for Differential File Comparison\"\nby James W. Hunt and M. Douglas McIlroy, June 1976\nComputing Science Technical Report, Bell Laboratories 41\n\n[Hunt and Szymanski 1977] \"A Fast Algorithm for Computing Longest Common Subsequences\"\nby James W. Hunt and Thomas G. Szymanski, published May 1977\nCommunications of the ACM [Volume 20, Number 5, ''pp.'' 350-353]\n\n[Rick 2000] \"Simple and fast linear space computation of longest common subsequences\"\nby Claus Rick, received 17 March 2000, Information Processing Letters,\nElsevier Science [Volume 75, ''pp.'' 275-281]\n\n\n'''Examples'''\n\nThe sequences \"1234\" and \"1224533324\" have an LCS of \"1234\":\n '''1234'''\n '''12'''245'''3'''332'''4'''\n\nFor a string example, consider the sequences \"thisisatest\" and \"testing123testing\". An LCS would be \"tsitest\":\n '''t'''hi'''si'''sa'''test'''\n '''t'''e'''s'''t'''i'''ng123'''test'''ing\n\nIn this puzzle, your code only needs to deal with strings. Write a function which returns an LCS of two strings (case-sensitive). You don't need to show multiple LCS's.\n\nFor more information on this problem please see Wikipedia.\n\n\n", "solution": "#include \n#include \n\n#define MAX(a, b) (a > b ? a : b)\n\nint lcs (char *a, int n, char *b, int m, char **s) {\n int i, j, k, t;\n int *z = calloc((n + 1) * (m + 1), sizeof (int));\n int **c = calloc((n + 1), sizeof (int *));\n for (i = 0; i <= n; i++) {\n c[i] = &z[i * (m + 1)];\n }\n for (i = 1; i <= n; i++) {\n for (j = 1; j <= m; j++) {\n if (a[i - 1] == b[j - 1]) {\n c[i][j] = c[i - 1][j - 1] + 1;\n }\n else {\n c[i][j] = MAX(c[i - 1][j], c[i][j - 1]);\n }\n }\n }\n t = c[n][m];\n *s = malloc(t);\n for (i = n, j = m, k = t - 1; k >= 0;) {\n if (a[i - 1] == b[j - 1])\n (*s)[k] = a[i - 1], i--, j--, k--;\n else if (c[i][j - 1] > c[i - 1][j])\n j--;\n else\n i--;\n }\n free(c);\n free(z);\n return t;\n}\n"} {"title": "Longest increasing subsequence", "language": "C", "task": "Calculate and show here a longest increasing subsequence of the list:\n:\\{3, 2, 6, 4, 5, 1\\}\nAnd of the list:\n:\\{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15\\}\n\nNote that a list may have more than one subsequence that is of the maximum length.\n\n\n\n;Ref:\n# Dynamic Programming #1: Longest Increasing Subsequence on YouTube\n# An efficient solution can be based on Patience sorting.\n\n", "solution": "#include \n#include \n\nstruct node {\n\tint val, len;\n\tstruct node *next;\n};\n\nvoid lis(int *v, int len)\n{\n\tint i;\n\tstruct node *p, *n = calloc(len, sizeof *n);\n\tfor (i = 0; i < len; i++)\n\t\tn[i].val = v[i];\n\n\tfor (i = len; i--; ) {\n\t\t// find longest chain that can follow n[i]\n\t\tfor (p = n + i; p++ < n + len; ) {\n\t\t\tif (p->val > n[i].val && p->len >= n[i].len) {\n\t\t\t\tn[i].next = p;\n\t\t\t\tn[i].len = p->len + 1;\n\t\t\t}\n\t\t}\n\t}\n\n\t// find longest chain\n\tfor (i = 0, p = n; i < len; i++)\n\t\tif (n[i].len > p->len) p = n + i;\n\n\tdo printf(\" %d\", p->val); while ((p = p->next));\n\tputchar('\\n');\n\n\tfree(n);\n}\n\nint main(void)\n{\n\tint x[] = { 3, 2, 6, 4, 5, 1 };\n\tint y[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };\n\n\tlis(x, sizeof(x) / sizeof(int));\n\tlis(y, sizeof(y) / sizeof(int));\n\treturn 0;\n}"} {"title": "MAC vendor lookup", "language": "C", "task": "Every connected device around the world comes with a unique Media Access Control address, or a MAC address. \n\nA common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address.\n\n\n;Task:\nInterface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address.\n\nA MAC address that does not return a valid result should return the String \"N/A\". An error related to the network connectivity or the API should return a null result.\n\nMany implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls.\n\n'''{\"errors\":{\"detail\":\"Too Many Requests\",\"message\":\"Please slow down your requests or upgrade your plan at https://macvendors.com\"}}'''\n\n", "solution": "#include \n#include \n#include \n#include \n\n/* Length of http://api.macvendors.com/ */\n#define FIXED_LENGTH 16\n\nstruct MemoryStruct {\n char *memory;\n size_t size;\n};\n \nstatic size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp)\n{\n size_t realsize = size * nmemb;\n struct MemoryStruct *mem = (struct MemoryStruct *)userp;\n \n mem->memory = realloc(mem->memory, mem->size + realsize + 1);\n \n memcpy(&(mem->memory[mem->size]), contents, realsize);\n mem->size += realsize;\n mem->memory[mem->size] = 0;\n \n return realsize;\n}\n\nvoid checkResponse(char* str){\n\tchar ref[] = \"Vendor not found\";\n\tint len = strlen(str),flag = 1,i;\n\t\n\tif(len<16)\n\t\tfputs(str,stdout);\n\telse{\n\t\tfor(i=0;i\",argV[0]);\n\t\telse{\n\t\t\tCURL *curl;\n\t\t\tint len = strlen(argV[1]);\n\t\t\tchar* str = (char*)malloc((FIXED_LENGTH + len)*sizeof(char));\n\t\t\tstruct MemoryStruct chunk;\n\t\t\tCURLcode res;\n \n\t\t\tchunk.memory = malloc(1);\n\t\t\tchunk.size = 0; \n \n if ((curl = curl_easy_init()) != NULL) {\n\t\t\t\tsprintf(str,\"http://api.macvendors.com/%s\",argV[1]);\n\n curl_easy_setopt(curl, CURLOPT_URL, str);\n\t\t\t\tcurl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);\n\t\t\t\tcurl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);\n\t\t\t\t\n\t\t\t\tfree(str);\n\t\t\t\t\n\t\t\t\tres = curl_easy_perform(curl);\n\t\t\t\t\n if (res == CURLE_OK) {\n\t\t\t\tcheckResponse(chunk.memory);\n return EXIT_SUCCESS;\n }\n\t\t\t\t\n curl_easy_cleanup(curl);\n\t\t\t}\n\t\t}\n \n return EXIT_FAILURE;\n}\n"} {"title": "MD4", "language": "C", "task": "Find the MD4 message digest of a string of [[octet]]s. \nUse the ASCII encoded string \"Rosetta Code\" (without quotes). \nYou may either call an MD4 library, or implement MD4 in your language.\n\n'''MD4''' is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols.\n\nRFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.\n\n", "solution": "/*\n *\n * Author: George Mossessian\n *\n * The MD4 hash algorithm, as described in https://tools.ietf.org/html/rfc1320\n */\n\n\n#include \n#include \n#include \n\nchar *MD4(char *str, int len); //this is the prototype you want to call. Everything else is internal.\n\ntypedef struct string{\n char *c;\n int len;\n char sign;\n}string;\n\nstatic uint32_t *MD4Digest(uint32_t *w, int len);\nstatic void setMD4Registers(uint32_t AA, uint32_t BB, uint32_t CC, uint32_t DD);\nstatic uint32_t changeEndianness(uint32_t x);\nstatic void resetMD4Registers(void);\nstatic string stringCat(string first, string second);\nstatic string uint32ToString(uint32_t l);\nstatic uint32_t stringToUint32(string s);\n\nstatic const char *BASE16 = \"0123456789abcdef=\";\n\n#define F(X,Y,Z) (((X)&(Y))|((~(X))&(Z)))\n#define G(X,Y,Z) (((X)&(Y))|((X)&(Z))|((Y)&(Z)))\n#define H(X,Y,Z) ((X)^(Y)^(Z))\n\n#define LEFTROTATE(A,N) ((A)<<(N))|((A)>>(32-(N)))\n\n#define MD4ROUND1(a,b,c,d,x,s) a += F(b,c,d) + x; a = LEFTROTATE(a, s);\n#define MD4ROUND2(a,b,c,d,x,s) a += G(b,c,d) + x + (uint32_t)0x5A827999; a = LEFTROTATE(a, s);\n#define MD4ROUND3(a,b,c,d,x,s) a += H(b,c,d) + x + (uint32_t)0x6ED9EBA1; a = LEFTROTATE(a, s);\n\nstatic uint32_t A = 0x67452301;\nstatic uint32_t B = 0xefcdab89;\nstatic uint32_t C = 0x98badcfe;\nstatic uint32_t D = 0x10325476;\n\nstring newString(char * c, int t){\n\tstring r;\n\tint i;\n\tif(c!=NULL){\n\t\tr.len = (t<=0)?strlen(c):t;\n\t\tr.c=(char *)malloc(sizeof(char)*(r.len+1));\n\t\tfor(i=0; i>4)];\n\t\tout.c[j++]=BASE16[(in.c[i] & 0x0F)];\n\t}\n\tout.c[j]='\\0';\n\treturn out;\n}\n\n\nstring uint32ToString(uint32_t l){\n\tstring s = newString(NULL,4);\n\tint i;\n\tfor(i=0; i<4; i++){\n\t\ts.c[i] = (l >> (8*(3-i))) & 0xFF;\n\t}\n\treturn s;\n}\n\nuint32_t stringToUint32(string s){\n\tuint32_t l;\n\tint i;\n\tl=0;\n\tfor(i=0; i<4; i++){\n\t\tl = l|(((uint32_t)((unsigned char)s.c[i]))<<(8*(3-i)));\n\t}\n\treturn l;\n}\n\nchar *MD4(char *str, int len){\n\tstring m=newString(str, len);\n\tstring digest;\n\tuint32_t *w;\n\tuint32_t *hash;\n\tuint64_t mlen=m.len;\n\tunsigned char oneBit = 0x80;\n\tint i, wlen;\n\n\n\tm=stringCat(m, newString((char *)&oneBit,1));\n\n\t//append 0 \u2264 k < 512 bits '0', such that the resulting message length in bits\n\t//\tis congruent to \u221264 \u2261 448 (mod 512)4\n\ti=((56-m.len)%64);\n\tif(i<0) i+=64;\n\tm=stringCat(m,newString(NULL, i));\n\n\tw = malloc(sizeof(uint32_t)*(m.len/4+2));\n\n\t//append length, in bits (hence <<3), least significant word first\n\tfor(i=0; i>29) & 0xFFFFFFFF;\n\n\twlen=i;\n\n\n\t//change endianness, but not for the appended message length, for some reason?\n\tfor(i=0; i> 8) | ((x & 0xFF000000) >> 24);\n}\n\nvoid setMD4Registers(uint32_t AA, uint32_t BB, uint32_t CC, uint32_t DD){\n\tA=AA;\n\tB=BB;\n\tC=CC;\n\tD=DD;\n}\n\nvoid resetMD4Registers(void){\n\tsetMD4Registers(0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476);\n}\n"} {"title": "Machine code", "language": "C", "task": "The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language.\n\nFor example, the following assembly language program is given for x86 (32 bit) architectures:\n\nmov EAX, [ESP+4]\nadd EAX, [ESP+8]\nret\n\nThis would translate into the following opcode bytes:\n139 68 36 4 3 68 36 8 195\n\nOr in hexadecimal:\n8B 44 24 04 03 44 24 08 C3\n\n;Task:\nIf different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language:\n\n* Poke the necessary opcodes into a memory location.\n* Provide a means to pass two values to the machine code.\n* Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19.\n* Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)\n\n\n", "solution": "#include \n#include \n#include \n\nint test (int a, int b)\n{\n /*\n mov EAX, [ESP+4]\n add EAX, [ESP+8]\n ret\n */\n char code[] = {0x8B, 0x44, 0x24, 0x4, 0x3, 0x44, 0x24, 0x8, 0xC3};\n void *buf;\n int c;\n /* copy code to executable buffer */\n buf = mmap (0,sizeof(code),PROT_READ|PROT_WRITE|PROT_EXEC,\n MAP_PRIVATE|MAP_ANON,-1,0);\n\n memcpy (buf, code, sizeof(code));\n /* run code */\n c = ((int (*) (int, int))buf)(a, b);\n /* free buffer */\n munmap (buf, sizeof(code));\n return c;\n}\n\nint main ()\n{\n printf(\"%d\\n\", test(7,12));\n return 0;\n}"} {"title": "Mad Libs", "language": "C", "task": "{{wikipedia}}\n\n\nMad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. \n\n\n;Task;\nWrite a program to create a Mad Libs like story. \n\nThe program should read an arbitrary multiline story from input.\n\nThe story will be terminated with a blank line. \n\nThen, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements.\n\nStop when there are none left and print the final story.\n\n\nThe input should be an arbitrary story in the form:\n\n went for a walk in the park. \nfound a . decided to take it home.\n\nGiven this example, it should then ask for a name, a he or she and a noun ( gets replaced both times with the same value).\n\n\n\n", "solution": "#include \n#include \n#include \n\n#define err(...) fprintf(stderr, ## __VA_ARGS__), exit(1)\n\n/* We create a dynamic string with a few functions which make modifying\n * the string and growing a bit easier */\ntypedef struct {\n char *data;\n size_t alloc;\n size_t length;\n} dstr;\n\ninline int dstr_space(dstr *s, size_t grow_amount)\n{\n return s->length + grow_amount < s->alloc;\n}\n\nint dstr_grow(dstr *s)\n{\n s->alloc *= 2;\n char *attempt = realloc(s->data, s->alloc);\n\n if (!attempt) return 0;\n else s->data = attempt;\n\n return 1;\n}\n\ndstr* dstr_init(const size_t to_allocate)\n{\n dstr *s = malloc(sizeof(dstr));\n if (!s) goto failure;\n\n s->length = 0;\n s->alloc = to_allocate;\n s->data = malloc(s->alloc);\n\n if (!s->data) goto failure;\n\n return s;\n\nfailure:\n if (s->data) free(s->data);\n if (s) free(s);\n return NULL;\n}\n\nvoid dstr_delete(dstr *s)\n{\n if (s->data) free(s->data);\n if (s) free(s);\n}\n\ndstr* readinput(FILE *fd)\n{\n static const size_t buffer_size = 4096;\n char buffer[buffer_size];\n\n dstr *s = dstr_init(buffer_size);\n if (!s) goto failure;\n\n while (fgets(buffer, buffer_size, fd)) {\n while (!dstr_space(s, buffer_size))\n if (!dstr_grow(s)) goto failure;\n\n strncpy(s->data + s->length, buffer, buffer_size);\n s->length += strlen(buffer);\n }\n\n return s;\n\nfailure:\n dstr_delete(s);\n return NULL;\n}\n\nvoid dstr_replace_all(dstr *story, const char *replace, const char *insert)\n{\n const size_t replace_l = strlen(replace);\n const size_t insert_l = strlen(insert);\n char *start = story->data;\n\n while ((start = strstr(start, replace))) {\n if (!dstr_space(story, insert_l - replace_l))\n if (!dstr_grow(story)) err(\"Failed to allocate memory\");\n\n if (insert_l != replace_l) {\n memmove(start + insert_l, start + replace_l, story->length -\n (start + replace_l - story->data));\n\n /* Remember to null terminate the data so we can utilize it\n * as we normally would */\n story->length += insert_l - replace_l;\n story->data[story->length] = 0;\n }\n\n memmove(start, insert, insert_l);\n }\n}\n\nvoid madlibs(dstr *story)\n{\n static const size_t buffer_size = 128;\n char insert[buffer_size];\n char replace[buffer_size];\n\n char *start,\n *end = story->data;\n\n while (start = strchr(end, '<')) {\n if (!(end = strchr(start, '>'))) err(\"Malformed brackets in input\");\n\n /* One extra for current char and another for nul byte */\n strncpy(replace, start, end - start + 1);\n replace[end - start + 1] = '\\0';\n\n printf(\"Enter value for field %s: \", replace);\n\n fgets(insert, buffer_size, stdin);\n const size_t il = strlen(insert) - 1;\n if (insert[il] == '\\n')\n insert[il] = '\\0';\n\n dstr_replace_all(story, replace, insert);\n }\n printf(\"\\n\");\n}\n\nint main(int argc, char *argv[])\n{\n if (argc < 2) return 0;\n\n FILE *fd = fopen(argv[1], \"r\");\n if (!fd) err(\"Could not open file: '%s\\n\", argv[1]);\n\n dstr *story = readinput(fd); fclose(fd);\n if (!story) err(\"Failed to allocate memory\");\n\n madlibs(story);\n printf(\"%s\\n\", story->data);\n dstr_delete(story);\n return 0;\n}\n"} {"title": "Magic squares of doubly even order", "language": "C", "task": "A magic square is an '''NxN''' square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). \n\nA magic square of doubly even order has a size that is a multiple of four (e.g. '''4''', '''8''', '''12'''). \n\nThis means that the subsquares also have an even size, which plays a role in the construction.\n\n \n{| class=\"wikitable\" style=\"float:right;border: 2px solid black; background:lightblue; color:black; margin-left:auto;margin-right:auto;text-align:center;width:22em;height:15em;table-layout:fixed;font-size:100%\"\n|-\n|'''1'''||'''2'''||'''62'''||'''61'''||'''60'''||'''59'''||'''7'''||'''8'''\n|-\n|'''9'''||'''10'''||'''54'''||'''53'''||'''52'''||'''51'''||'''15'''||'''16'''\n|-\n|'''48'''||'''47'''||'''19'''||'''20'''||'''21'''||'''22'''||'''42'''||'''41'''\n|-\n|'''40'''||'''39'''||'''27'''||'''28'''||'''29'''||'''30'''||'''34'''||'''33'''\n|-\n|'''32'''||'''31'''||'''35'''||'''36'''||'''37'''||'''38'''||'''26'''||'''25'''\n|-\n|'''24'''||'''23'''||'''43'''||'''44'''||'''45'''||'''46'''||'''18'''||'''17'''\n|-\n|'''49'''||'''50'''||'''14'''||'''13'''||'''12'''||'''11'''||'''55'''||'''56'''\n|-\n|'''57'''||'''58'''||'''6'''||'''5'''||'''4'''||'''3'''||'''63'''||'''64'''\n|}\n\n;Task\nCreate a magic square of '''8 x 8'''.\n\n\n;Related tasks\n* [[Magic squares of odd order]]\n* [[Magic squares of singly even order]]\n\n\n;See also:\n* Doubly Even Magic Squares (1728.org)\n\n", "solution": "#include\n#include\n#include\n\nint** doublyEvenMagicSquare(int n) {\n\tif (n < 4 || n % 4 != 0)\n\t\treturn NULL;\n\n\tint bits = 38505;\n\tint size = n * n;\n\tint mult = n / 4,i,r,c,bitPos;\n\n\tint** result = (int**)malloc(n*sizeof(int*));\n\t\n\tfor(i=0;i=10){\n\t\tn /= 10;\n\t\tcount++;\n\t}\n\t\n\treturn count;\n}\n\nvoid printMagicSquare(int** square,int rows){\n\tint i,j,baseWidth = numDigits(rows*rows) + 3;\n\t\n\tprintf(\"Doubly Magic Square of Order : %d and Magic Constant : %d\\n\\n\",rows,(rows * rows + 1) * rows / 2);\n\t\n\tfor(i=0;i\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\tprintMagicSquare(doublyEvenMagicSquare(n),n);\n\t}\n\treturn 0;\n}\n"} {"title": "Magic squares of odd order", "language": "C", "task": "A magic square is an '''NxN''' square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both long (main) diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). \n\nThe numbers are usually (but not always) the first '''N'''2 positive integers.\n\nA magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a ''semimagic square''.\n\n{| class=\"wikitable\" style=\"float:right;border: 4px solid blue; background:lightgreen; color:black; margin-left:auto;margin-right:auto;text-align:center;width:15em;height:15em;table-layout:fixed;font-size:150%\"\n|-\n| '''8''' || '''1''' || '''6'''\n|-\n| '''3''' || '''5''' || '''7'''\n|-\n| '''4''' || '''9''' || '''2'''\n|}\n\n\n;Task\nFor any odd '''N''', generate a magic square with the integers ''' 1''' --> '''N''', and show the results here. \n\nOptionally, show the ''magic number''. \n\nYou should demonstrate the generator by showing at least a magic square for '''N''' = '''5'''.\n\n\n; Related tasks\n* [[Magic squares of singly even order]]\n* [[Magic squares of doubly even order]]\n\n\n; See also:\n* MathWorld(tm) entry: Magic_square \n* Odd Magic Squares (1728.org)\n\n", "solution": "#include \n#include \n \nint f(int n, int x, int y)\n{\n\treturn (x + y*2 + 1)%n;\n}\n \nint main(int argc, char **argv)\n{\n\tint i, j, n;\n \n\t//Edit: Add argument checking\n\tif(argc!=2) return 1;\n\n\t//Edit: Input must be odd and not less than 3.\n\tn = atoi(argv[1]);\n\tif (n < 3 || (n%2) == 0) return 2;\n \n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++)\n\t\t\tprintf(\"% 4d\", f(n, n - j - 1, i)*n + f(n, j, i) + 1);\n\t\tputchar('\\n');\n\t}\n\tprintf(\"\\n Magic Constant: %d.\\n\", (n*n+1)/2*n);\n \n\treturn 0;\n}"} {"title": "Magic squares of singly even order", "language": "C", "task": "A magic square is an '''NxN''' square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). \n\nA magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6, 10, 14). This means that the subsquares have an odd size, which plays a role in the construction.\n\n;Task\nCreate a magic square of 6 x 6.\n\n\n; Related tasks\n* [[Magic squares of odd order]]\n* [[Magic squares of doubly even order]]\n\n; See also\n* Singly Even Magic Squares (1728.org)\n\n", "solution": "#include\n #include\n #include\n \n int** oddMagicSquare(int n) {\n if (n < 3 || n % 2 == 0)\n return NULL;\n \n int value = 0;\n int squareSize = n * n;\n int c = n / 2, r = 0,i;\n \n int** result = (int**)malloc(n*sizeof(int*));\n\t\t\n\t\tfor(i=0;i= n - nColsRight\n || (c == nColsLeft && r == nColsLeft)) {\n \n if (c == 0 && r == nColsLeft)\n continue;\n \n int tmp = result[r][c];\n result[r][c] = result[r + halfN][c];\n result[r + halfN][c] = tmp;\n }\n }\n \n return result;\n }\n\t\n\tint numDigits(int n){\n\t\tint count = 1;\n\t\t\n\t\twhile(n>=10){\n\t\t\tn /= 10;\n\t\t\tcount++;\n\t\t}\n\t\t\n\t\treturn count;\n\t}\n\t\n\tvoid printMagicSquare(int** square,int rows){\n\t\tint i,j;\n\t\t\n\t\tfor(i=0;i\",argV[0]);\n\t\telse{\n\t\t\tn = atoi(argV[1]);\n\t\t\tprintMagicSquare(singlyEvenMagicSquare(n),n);\n\t\t}\n\t\treturn 0;\n\t}\n"} {"title": "Map range", "language": "C", "task": "Given two ranges: \n:::* [a_1,a_2] and \n:::* [b_1,b_2]; \n:::* then a value s in range [a_1,a_2]\n:::* is linearly mapped to a value t in range [b_1,b_2]\n where: \n\n\n:::* t = b_1 + {(s - a_1)(b_2 - b_1) \\over (a_2 - a_1)}\n\n\n;Task:\nWrite a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range. \n\nUse this function to map values from the range [0, 10] to the range [-1, 0]. \n\n\n;Extra credit:\nShow additional idiomatic ways of performing the mapping, using tools available to the language.\n\n", "solution": "#include \n\n#define mapRange(a1,a2,b1,b2,s) (b1 + (s-a1)*(b2-b1)/(a2-a1))\n\nint main()\n{\n\tint i;\n\tputs(\"Mapping [0,10] to [-1,0] at intervals of 1:\");\n\t\n\tfor(i=0;i<=10;i++)\n\t{\n\t\tprintf(\"f(%d) = %g\\n\",i,mapRange(0,10,-1,0,i));\n\t}\n\t\n\treturn 0;\n}\n"} {"title": "Matrix digital rain", "language": "C", "task": "Implement the Matrix Digital Rain visual effect from the movie \"The Matrix\" as described in Wikipedia.\n\nProvided is a reference implementation in Common Lisp to be run in a terminal.\n\n", "solution": "/**\n * Loosely emulates the \"digital rain\" effect from The Matrix.\n *\n * @author Dan Ruscoe \n */\n#include \n#include \n#include \n#include \n#include \n\n/* Time between row updates in microseconds.\n Controls the speed of the digital rain effect.\n*/\n#define ROW_DELAY 40000\n\n/**\n * Gets a random integer within a given range.\n *\n * @param int min The low-end of the range.\n * @param int max The high-end of the range.\n *\n * @return int The random integer.\n */\nint get_rand_in_range(int min, int max)\n{\n return (rand() % ((max + 1) - min) + min);\n}\n\nint main(void)\n{\n /* Basic seed for random numbers. */\n srand(time(NULL));\n\n /* Characters to randomly appear in the rain sequence. */\n char chars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};\n\n int total_chars = sizeof(chars);\n\n /* Set up ncurses screen and colors. */\n initscr();\n noecho();\n curs_set(FALSE);\n\n start_color();\n init_pair(1, COLOR_GREEN, COLOR_BLACK);\n attron(COLOR_PAIR(1));\n\n int max_x = 0, max_y = 0;\n\n getmaxyx(stdscr, max_y, max_x);\n\n /* Create arrays of columns based on screen width. */\n\n /* Array containing the current row of each column. */\n int columns_row[max_x];\n\n /* Array containing the active status of each column.\n A column draws characters on a row when active.\n */\n int columns_active[max_x];\n\n int i;\n\n /* Set top row as current row for all columns. */\n for (i = 0; i < max_x; i++)\n {\n columns_row[i] = -1;\n columns_active[i] = 0;\n }\n\n while (1)\n {\n for (i = 0; i < max_x; i++)\n {\n if (columns_row[i] == -1)\n {\n /* If a column is at the top row, pick a\n random starting row and active status.\n */\n columns_row[i] = get_rand_in_range(0, max_y);\n columns_active[i] = get_rand_in_range(0, 1);\n }\n }\n\n /* Loop through columns and draw characters on rows. */\n for (i = 0; i < max_x; i++)\n {\n if (columns_active[i] == 1)\n {\n /* Draw a random character at this column's current row. */\n int char_index = get_rand_in_range(0, total_chars);\n mvprintw(columns_row[i], i, \"%c\", chars[char_index]);\n }\n else\n {\n /* Draw an empty character if the column is inactive. */\n mvprintw(columns_row[i], i, \" \");\n }\n\n columns_row[i]++;\n\n /* When a column reaches the bottom row, reset to top. */\n if (columns_row[i] >= max_y)\n {\n columns_row[i] = -1;\n }\n\n /* Randomly alternate the column's active status. */\n if (get_rand_in_range(0, 1000) == 0)\n {\n columns_active[i] = (columns_active[i] == 0) ? 1 : 0;\n }\n }\n\n usleep(ROW_DELAY);\n refresh();\n }\n\n endwin();\n return 0;\n}\n"} {"title": "Maximum triangle path sum", "language": "C", "task": "Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:\n\n 55\n 94 48\n 95 30 96\n 77 71 26 67\n\n\nOne of such walks is 55 - 94 - 30 - 26. \nYou can compute the total of the numbers you have seen in such walk, \nin this case it's 205.\n\nYour problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321.\n\n\n;Task:\nFind the maximum total in the triangle below:\n\n 55\n 94 48\n 95 30 96\n 77 71 26 67\n 97 13 76 38 45\n 07 36 79 16 37 68\n 48 07 09 18 70 26 06\n 18 72 79 46 59 79 29 90\n 20 76 87 11 32 07 07 49 18\n 27 83 58 35 71 11 25 57 29 85\n 14 64 36 96 27 11 58 56 92 18 55\n 02 90 03 60 48 49 41 46 33 36 47 23\n 92 50 48 02 36 59 42 79 72 20 82 77 42\n 56 78 38 80 39 75 02 71 66 66 01 03 55 72\n 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93\n\n\nSuch numbers can be included in the solution code, or read from a \"triangle.txt\" file.\n\nThis task is derived from the Euler Problem #18.\n\n", "solution": "#include \n#include \n\n#define max(x,y) ((x) > (y) ? (x) : (y))\n\nint tri[] = {\n 55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n};\n\nint main(void)\n{\n const int len = sizeof(tri) / sizeof(tri[0]);\n const int base = (sqrt(8*len + 1) - 1) / 2;\n int step = base - 1;\n int stepc = 0;\n\n int i;\n for (i = len - base - 1; i >= 0; --i) {\n tri[i] += max(tri[i + step], tri[i + step + 1]);\n if (++stepc == step) {\n step--;\n stepc = 0;\n }\n }\n\n printf(\"%d\\n\", tri[0]);\n return 0;\n}\n"} {"title": "McNuggets problem", "language": "C", "task": "From Wikipedia:\n The McNuggets version of the coin problem was introduced by Henri Picciotto,\n who included it in his algebra textbook co-authored with Anita Wah. Picciotto\n thought of the application in the 1980s while dining with his son at\n McDonald's, working the problem out on a napkin. A McNugget number is\n the total number of McDonald's Chicken McNuggets in any number of boxes.\n In the United Kingdom, the original boxes (prior to the introduction of\n the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets.\n\n;Task:\nCalculate (from 0 up to a limit of 100) the largest non-McNuggets\nnumber (a number ''n'' which cannot be expressed with ''6x + 9y + 20z = n''\nwhere ''x'', ''y'' and ''z'' are natural numbers).\n\n", "solution": "#include \n\nint\nmain() {\n int max = 0, i = 0, sixes, nines, twenties;\n\nloopstart: while (i < 100) {\n for (sixes = 0; sixes*6 < i; sixes++) {\n if (sixes*6 == i) {\n i++;\n goto loopstart;\n }\n\n for (nines = 0; nines*9 < i; nines++) {\n if (sixes*6 + nines*9 == i) {\n i++;\n goto loopstart;\n }\n\n for (twenties = 0; twenties*20 < i; twenties++) {\n if (sixes*6 + nines*9 + twenties*20 == i) {\n i++;\n goto loopstart;\n }\n }\n }\n }\n max = i;\n i++;\n }\n\n printf(\"Maximum non-McNuggets number is %d\\n\", max);\n\n return 0;\n}"} {"title": "Memory layout of a data structure", "language": "C", "task": "It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity.\n Pin Settings for Plug\n (Reverse order for socket.)\n __________________________________________\n 1 2 3 4 5 6 7 8 9 10 11 12 13\n 14 15 16 17 18 19 20 21 22 23 24 25\n _________________\n 1 2 3 4 5\n 6 7 8 9\n 25 pin 9 pin\n 1 - PG Protective ground\n 2 - TD Transmitted data 3\n 3 - RD Received data 2\n 4 - RTS Request to send 7\n 5 - CTS Clear to send 8\n 6 - DSR Data set ready 6\n 7 - SG Signal ground 5\n 8 - CD Carrier detect 1\n 9 - + voltage (testing)\n 10 - - voltage (testing)\n 11 -\n 12 - SCD Secondary CD\n 13 - SCS Secondary CTS\n 14 - STD Secondary TD\n 15 - TC Transmit clock\n 16 - SRD Secondary RD\n 17 - RC Receiver clock\n 18 -\n 19 - SRS Secondary RTS \n 20 - DTR Data terminal ready 4\n 21 - SQD Signal quality detector\n 22 - RI Ring indicator 9\n 23 - DRS Data rate select\n 24 - XTC External clock\n 25 -\n", "solution": "struct RS232_data\n{\n unsigned carrier_detect : 1;\n unsigned received_data : 1;\n unsigned transmitted_data : 1;\n unsigned data_terminal_ready : 1;\n unsigned signal_ground : 1;\n unsigned data_set_ready : 1;\n unsigned request_to_send : 1;\n unsigned clear_to_send : 1;\n unsigned ring_indicator : 1;\n};"} {"title": "Metaprogramming", "language": "C", "task": "{{omit from|BBC BASIC}}\nName and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. \n\nFor the purposes of this task, \"support for metaprogramming\" means any way the user can effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.\n\n", "solution": "#include \n\nLIB_GADGET_START\n\nvoid Muestra_archivo_original();\n\nMain\n Assert (Exist_file(\"load_matrix.txt\"), file_not_found);\n\n /* recupero informacion del archivo para su apertura segura */\n F_STAT dataFile = Stat_file(\"load_matrix.txt\");\n Assert (dataFile.is_matrix, file_not_matrixable) // tiene forma de matriz???\n \n New multitype test;\n \n /* The data range to be read is established. \n It is possible to read only part of the file using these ranges. */\n Range for test [0:1:dataFile.total_lines-1, 0:1:dataFile.max_tokens_per_line-1];\n \n /* cargamos el array detectando n\u00fameros enteros como long */\n test = Load_matrix_mt( pSDS(test), \"load_matrix.txt\", dataFile, DET_LONG);\n \n /* modifica algunas cosas del archivo */\n Let( $s-test[0,1], \"Columna 1\");\n $l-test[2,1] = 1000;\n $l-test[2,2] = 2000;\n \n /* inserto filas */\n /* preparo la fila a insertar */\n New multitype nueva_fila;\n sAppend_mt(nueva_fila,\"fila 3.1\"); /* sAppend_mt() and Append_mt() are macros */\n Append_mt(nueva_fila,float,0.0);\n Append_mt(nueva_fila,int,0);\n Append_mt(nueva_fila,double,0.0);\n Append_mt(nueva_fila,long, 0L);\n \n /* insertamos la misma fila en el array, 3 veces */\n test = Insert_row_mt(pSDS(test),pSDS(nueva_fila), 4);\n test = Insert_row_mt(pSDS(test),pSDS(nueva_fila), 4);\n test = Insert_row_mt(pSDS(test),pSDS(nueva_fila), 4);\n Free multitype nueva_fila;\n \n Print \"\\nGuardando archivo en \\\"save_matrix.txt\\\"...\\n\";\n DEC_PREC = 20; /* establece precision decimal */\n \n All range for test;\n Save_matrix_mt(SDS(test), \"save_matrix.txt\" );\n\n Free multitype test;\n \n Print \"\\nArchivo original:\\n\";\n Muestra_archivo_original();\n \n Exception( file_not_found ){\n Msg_red(\"File not found\\n\");\n }\n Exception( file_not_matrixable ){\n Msg_red(\"File is not matrixable\\n\");\n }\n\nEnd\n\nvoid Muestra_archivo_original(){\n String csys;\n csys = `cat load_matrix.txt`;\n Print \"\\n%s\\n\", csys;\n Free secure csys;\n}\n"} {"title": "Metronome", "language": "C", "task": "The task is to implement a metronome. \n\nThe metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable.\n\nFor the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an external player may be used. \n\nHowever, the playing of the sounds should not interfere with the timing of the metronome.\n\nThe visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities. \n\nIf the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstruct timeval start, last;\n\ninline int64_t tv_to_u(struct timeval s)\n{\n\treturn s.tv_sec * 1000000 + s.tv_usec;\n}\n\ninline struct timeval u_to_tv(int64_t x)\n{\n\tstruct timeval s;\n\ts.tv_sec = x / 1000000;\n\ts.tv_usec = x % 1000000;\n\treturn s;\n}\n\nvoid draw(int dir, int64_t period, int64_t cur, int64_t next)\n{\n\tint len = 40 * (next - cur) / period;\n\tint s, i;\n\n\tif (len > 20) len = 40 - len;\n\ts = 20 + (dir ? len : -len);\n\n\tprintf(\"\\033[H\");\n\tfor (i = 0; i <= 40; i++) putchar(i == 20 ? '|': i == s ? '#' : '-');\n}\n\nvoid beat(int delay)\n{\n\tstruct timeval tv = start;\n\tint dir = 0;\n\tint64_t d = 0, corr = 0, slp, cur, next = tv_to_u(start) + delay;\n\tint64_t draw_interval = 20000;\n\tprintf(\"\\033[H\\033[J\");\n\twhile (1) {\n\t\tgettimeofday(&tv, 0);\n\t\tslp = next - tv_to_u(tv) - corr;\n\t\tusleep(slp);\n\t\tgettimeofday(&tv, 0);\n\n\t\tputchar(7); /* bell */\n\t\tfflush(stdout);\n\n\t\tprintf(\"\\033[5;1Hdrift: %d compensate: %d (usec) \",\n\t\t\t(int)d, (int)corr);\n\t\tdir = !dir;\n\n\t\tcur = tv_to_u(tv);\n\t\td = cur - next;\n\t\tcorr = (corr + d) / 2;\n\t\tnext += delay;\n\n\t\twhile (cur + d + draw_interval < next) {\n\t\t\tusleep(draw_interval);\n\t\t\tgettimeofday(&tv, 0);\n\t\t\tcur = tv_to_u(tv);\n\t\t\tdraw(dir, delay, cur, next);\n\t\t\tfflush(stdout);\n\t\t}\n\t}\n}\n\nint main(int c, char**v)\n{\n\tint bpm;\n\n\tif (c < 2 || (bpm = atoi(v[1])) <= 0) bpm = 60;\n\tif (bpm > 600) {\n\t\tfprintf(stderr, \"frequency %d too high\\n\", bpm);\n\t\texit(1);\n\t}\n\n\tgettimeofday(&start, 0);\n\tlast = start;\n\tbeat(60 * 1000000 / bpm);\n\n\treturn 0;\n}"} {"title": "Middle three digits", "language": "C", "task": "Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.\n\nNote: The order of the middle digits should be preserved.\n\nYour function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:\n\n123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345\n1, 2, -1, -10, 2002, -2002, 0\n\nShow your output on this page.\n\n", "solution": "#include \n#include \n#include \n \nvoid midThree(char arg[])\n{\n char output[4];\n int midPoint;\n arg[0]=='-'?midPoint = ((strlen(arg) + 1) / 2):midPoint = ((strlen(arg) + 1) / 2) - 1;\n \n if(strlen(arg) < 3)\n {\n printf(\"Error, %d is too short.\\n\",atoi(arg));\n return ;\n }\n else if(strlen(arg) == 4 || strlen(arg) == 3)\n {\n printf(\"Error, %d has %d digits, no 3 middle digits.\\n\",atoi(arg),arg[0]=='-'?strlen(arg)-1:strlen(arg));\n return ;\n }\n else{\n for(int i=0; i<3; i++)\n {\n output[i] = arg[(midPoint-1) + i];\n }\n output[3] = '\\0';\n printf(\"The middle three digits of %s are %s.\\n\",arg,output);\n}}\n \nint main(int argc, char * argv[])\n{\n char input[50];\n int x[] = {123, 12345, 1234567, 987654321, 10001, -10001,\n\t\t-123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0,\n\t\t1234567890},i;\n\t\t\n if(argc < 2)\n {\n printf(\"Usage: %s \\n\",argv[0]);\n printf(\"Examples with preloaded data shown below :\\n\");\n \n for(i=0;i<18;i++)\n {\n\t midThree(itoa(x[i],argv[0],10));\n\t }\n return 1;\n }\n else\n {\n sprintf(input,\"%d\",atoi(argv[1]));\n midThree(argv[1]);\n return 0;\n \n \n }\n}"} {"title": "Mind boggling card trick", "language": "C", "task": "Matt Parker of the \"Stand Up Maths channel\" has a YouTube video of a card trick that creates a semblance of order from chaos.\n\nThe task is to simulate the trick in a way that mimics the steps shown in the video.\n\n; 1. Cards.\n# Create a common deck of cards of 52 cards (which are half red, half black).\n# Give the pack a good shuffle.\n; 2. Deal from the shuffled deck, you'll be creating three piles.\n# Assemble the cards face down.\n## Turn up the ''top card'' and hold it in your hand. \n### if the card is black, then add the ''next'' card (unseen) to the \"black\" pile. \n### If the card is red, then add the ''next'' card (unseen) to the \"red\" pile.\n## Add the ''top card'' that you're holding to the '''discard''' pile. (You might optionally show these discarded cards to get an idea of the randomness).\n# Repeat the above for the rest of the shuffled deck.\n; 3. Choose a random number (call it '''X''') that will be used to swap cards from the \"red\" and \"black\" piles.\n# Randomly choose '''X''' cards from the \"red\" pile (unseen), let's call this the \"red\" bunch. \n# Randomly choose '''X''' cards from the \"black\" pile (unseen), let's call this the \"black\" bunch.\n# Put the \"red\" bunch into the \"black\" pile.\n# Put the \"black\" bunch into the \"red\" pile.\n# (The above two steps complete the swap of '''X''' cards of the \"red\" and \"black\" piles. (Without knowing what those cards are --- they could be red or black, nobody knows).\n; 4. Order from randomness?\n# Verify (or not) the mathematician's assertion that: \n '''The number of black cards in the \"black\" pile equals the number of red cards in the \"red\" pile.''' \n\n\n(Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.)\n\nShow output on this page.\n\n", "solution": "#include \n#include \n#include \n\n#define SIM_N 5 /* Run 5 simulations */\n#define PRINT_DISCARDED 1 /* Whether or not to print the discard pile */\n\n#define min(x,y) ((x= n);\n return out;\n}\n\n/* Return a random card (0..51) from an uniform distribution */\ncard_t rand_card() {\n return rand_n(52);\n}\n\n/* Print a card */\nvoid print_card(card_t card) {\n static char *suits = \"HCDS\"; /* hearts, clubs, diamonds and spades */\n static char *cards[] = {\"A\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"J\",\"Q\",\"K\"};\n printf(\" %s%c\", cards[card>>2], suits[card&3]);\n}\n\n/* Shuffle a pack */\nvoid shuffle(card_t *pack) {\n int card;\n card_t temp, randpos;\n for (card=0; card<52; card++) {\n randpos = rand_card();\n temp = pack[card];\n pack[card] = pack[randpos];\n pack[randpos] = temp;\n }\n}\n\n/* Do the card trick, return whether cards match */\nint trick() {\n card_t pack[52];\n card_t blacks[52/4], reds[52/4];\n card_t top, x, card;\n int blackn=0, redn=0, blacksw=0, redsw=0, result;\n \n /* Create and shuffle a pack */\n for (card=0; card<52; card++) pack[card] = card;\n shuffle(pack);\n \n /* Deal cards */\n#if PRINT_DISCARDED\n printf(\"Discarded:\"); /* Print the discard pile */\n#endif\n for (card=0; card<52; card += 2) {\n top = pack[card]; /* Take card */\n if (top & 1) { /* Add next card to black or red pile */\n blacks[blackn++] = pack[card+1];\n } else {\n reds[redn++] = pack[card+1];\n }\n#if PRINT_DISCARDED\n print_card(top); /* Show which card is discarded */\n#endif\n }\n#if PRINT_DISCARDED\n printf(\"\\n\");\n#endif\n\n /* Swap an amount of cards */\n x = rand_n(min(blackn, redn));\n for (card=0; card\n\nunsigned digit_sum(unsigned n) {\n unsigned sum = 0;\n do { sum += n % 10; }\n while(n /= 10);\n return sum;\n}\n\nunsigned a131382(unsigned n) {\n unsigned m;\n for (m = 1; n != digit_sum(m*n); m++);\n return m;\n}\n\nint main() {\n unsigned n;\n for (n = 1; n <= 70; n++) {\n printf(\"%9u\", a131382(n));\n if (n % 10 == 0) printf(\"\\n\");\n }\n return 0;\n}"} {"title": "Minimum positive multiple in base 10 using only 0 and 1", "language": "C", "task": "Every positive integer has infinitely many base-10 multiples that only use the digits '''0''' and '''1'''. The goal of this task is to find and display the '''minimum''' multiple that has this property.\n\nThis is simple to do, but can be challenging to do efficiently.\n\nTo avoid repeating long, unwieldy phrases, the operation \"minimum positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1\" will hereafter be referred to as \"'''B10'''\".\n\n;Task:\n\nWrite a routine to find the B10 of a given integer. \n\nE.G. \n \n '''n''' '''B10''' '''n''' x '''multiplier'''\n 1 1 ( 1 x 1 )\n 2 10 ( 2 x 5 )\n 7 1001 ( 7 x 143 )\n 9 111111111 ( 9 x 12345679 )\n 10 10 ( 10 x 1 )\n\nand so on.\n\nUse the routine to find and display here, on this page, the '''B10''' value for: \n\n 1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999\n\nOptionally find '''B10''' for:\n\n 1998, 2079, 2251, 2277\n\nStretch goal; find '''B10''' for:\n\n 2439, 2997, 4878\n\nThere are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you ''do'' use magic numbers, explain briefly why and what they do for your implementation.\n\n\n;See also:\n\n:* OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's.\n:* How to find Minimum Positive Multiple in base 10 using only 0 and 1\n\n", "solution": "#include \n#include \n#include \n#include \n\n__int128 imax(__int128 a, __int128 b) {\n if (a > b) {\n return a;\n }\n return b;\n}\n\n__int128 ipow(__int128 b, __int128 n) {\n __int128 res;\n if (n == 0) {\n return 1;\n }\n if (n == 1) {\n return b;\n }\n res = b;\n while (n > 1) {\n res *= b;\n n--;\n }\n return res;\n}\n\n__int128 imod(__int128 m, __int128 n) {\n __int128 result = m % n;\n if (result < 0) {\n result += n;\n }\n return result;\n}\n\nbool valid(__int128 n) {\n if (n < 0) {\n return false;\n }\n while (n > 0) {\n int r = n % 10;\n if (r > 1) {\n return false;\n }\n n /= 10;\n }\n return true;\n}\n\n__int128 mpm(const __int128 n) {\n __int128 *L;\n __int128 m, k, r, j;\n\n if (n == 1) {\n return 1;\n }\n\n L = calloc(n * n, sizeof(__int128));\n L[0] = 1;\n L[1] = 1;\n m = 0;\n while (true) {\n m++;\n if (L[(m - 1) * n + imod(-ipow(10, m), n)] == 1) {\n break;\n }\n L[m * n + 0] = 1;\n for (k = 1; k < n; k++) {\n L[m * n + k] = imax(L[(m - 1) * n + k], L[(m - 1) * n + imod(k - ipow(10, m), n)]);\n }\n }\n\n r = ipow(10, m);\n k = imod(-r, n);\n\n for (j = m - 1; j >= 1; j--) {\n if (L[(j - 1) * n + k] == 0) {\n r = r + ipow(10, j);\n k = imod(k - ipow(10, j), n);\n }\n }\n\n if (k == 1) {\n r++;\n }\n return r / n;\n}\n\nvoid print128(__int128 n) {\n char buffer[64]; // more then is needed, but is nice and round;\n int pos = (sizeof(buffer) / sizeof(char)) - 1;\n bool negative = false;\n\n if (n < 0) {\n negative = true;\n n = -n;\n }\n\n buffer[pos] = 0;\n while (n > 0) {\n int rem = n % 10;\n buffer[--pos] = rem + '0';\n n /= 10;\n }\n if (negative) {\n buffer[--pos] = '-';\n }\n printf(&buffer[pos]);\n}\n\nvoid test(__int128 n) {\n __int128 mult = mpm(n);\n if (mult > 0) {\n print128(n);\n printf(\" * \");\n print128(mult);\n printf(\" = \");\n print128(n * mult);\n printf(\"\\n\");\n } else {\n print128(n);\n printf(\"(no solution)\\n\");\n }\n}\n\nint main() {\n int i;\n\n // 1-10 (inclusive)\n for (i = 1; i <= 10; i++) {\n test(i);\n }\n // 95-105 (inclusive)\n for (i = 95; i <= 105; i++) {\n test(i);\n }\n test(297);\n test(576);\n test(594); // needs a larger number type (64 bits signed)\n test(891);\n test(909);\n test(999); // needs a larger number type (87 bits signed)\n\n // optional\n test(1998);\n test(2079);\n test(2251);\n test(2277);\n\n // stretch\n test(2439);\n test(2997);\n test(4878);\n\n return 0;\n}"} {"title": "Modular exponentiation", "language": "C", "task": "Find the last '''40''' decimal digits of a^b, where\n\n::* a = 2988348162058574136915891421498819466320163312926952423791023078876139\n::* b = 2351399303373464486466122544523690094744975233415544072992656881240319\n\n\nA computer is too slow to find the entire value of a^b. \n\nInstead, the program must use a fast algorithm for modular exponentiation: a^b \\mod m.\n\nThe algorithm must work for any integers a, b, m, where b \\ge 0 and m > 0.\n\n", "solution": "Given numbers are too big for even 64 bit integers, so might as well take the lazy route and use GMP:\n"} {"title": "Modular inverse", "language": "C", "task": "From Wikipedia:\n\nIn modulo ''m'' is an integer ''x'' such that\n\n::a\\,x \\equiv 1 \\pmod{m}.\n\nOr in other words, such that:\n\n::\\exists k \\in\\Z,\\qquad a\\, x = 1 + k\\,m\n\nIt can be shown that such an inverse exists if and only if ''a'' and ''m'' are coprime, but we will ignore this for this task.\n\n\n;Task:\nEither by implementing the algorithm, by using a dedicated library or by using a built-in function in \nyour language, compute the modular inverse of 42 modulo 2017.\n\n", "solution": "#include \n\nint mul_inv(int a, int b)\n{\n\tint b0 = b, t, q;\n\tint x0 = 0, x1 = 1;\n\tif (b == 1) return 1;\n\twhile (a > 1) {\n\t\tq = a / b;\n\t\tt = b, b = a % b, a = t;\n\t\tt = x0, x0 = x1 - q * x0, x1 = t;\n\t}\n\tif (x1 < 0) x1 += b0;\n\treturn x1;\n}\n\nint main(void) {\n\tprintf(\"%d\\n\", mul_inv(42, 2017));\n\treturn 0;\n}"} {"title": "Monads/List monad", "language": "C", "task": "A Monad is a combination of a data-type with two helper functions written for that type. \n\nThe data-type can be of any kind which can contain values of some other type - common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as '''eta''' and '''mu''', but usually given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type.\n\nThe bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure.\n\nA sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product. \n\nThe natural implementation of bind for the List monad is a composition of '''concat''' and '''map''', which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping.\n\n\nDemonstrate in your programming language the following:\n\n#Construct a List Monad by writing the 'bind' function and the 'pure' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented)\n#Make two functions, each which take a number and return a monadic number, e.g. Int -> List Int and Int -> List String\n#Compose the two functions with bind\n\n", "solution": "#include \n#include \n\n#define MONAD void*\n#define INTBIND(f, g, x) (f((int*)g(x)))\n#define RETURN(type,x) &((type)*)(x)\n\nMONAD boundInt(int *x) {\n return (MONAD)(x);\n}\n\nMONAD boundInt2str(int *x) {\n char buf[100];\n char*str= malloc(1+sprintf(buf, \"%d\", *x));\n sprintf(str, \"%d\", *x);\n return (MONAD)(str);\n}\n\nvoid task(int y) {\n char *z= INTBIND(boundInt2str, boundInt, &y);\n printf(\"%s\\n\", z);\n free(z);\n}\n\nint main() {\n task(13);\n}"} {"title": "Monads/Maybe monad", "language": "C", "task": "Demonstrate in your programming language the following:\n\n#Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented)\n#Make two functions, each which take a number and return a monadic number, e.g. Int -> Maybe Int and Int -> Maybe String\n#Compose the two functions with bind\n\n\nA Monad is a single type which encapsulates several other types, eliminating boilerplate code. In practice it acts like a dynamically typed computational sequence, though in many cases the type issues can be resolved at compile time.\n\nA Maybe Monad is a monad which specifically encapsulates the type of an undefined value.\n\n", "solution": "#include \n#include \n#include \n\ntypedef enum type\n{\n INT,\n STRING\n} Type;\n\ntypedef struct maybe\n{\n int i;\n char *s;\n Type t;\n _Bool is_something;\n} Maybe;\n\nvoid print_Maybe(Maybe *m)\n{\n if (m->t == INT)\n printf(\"Just %d : INT\\n\", m->i);\n\n else if (m->t == STRING)\n printf(\"Just \\\"%s\\\" : STRING\\n\", m->s);\n\n else\n printf(\"Nothing\\n\");\n\n}\n\nMaybe *return_maybe(void *data, Type t)\n{\n Maybe *m = malloc(sizeof(Maybe));\n if (t == INT)\n {\n m->i = *(int *) data;\n m->s = NULL;\n m->t = INT;\n m->is_something = true;\n }\n\n else if (t == STRING)\n {\n m->i = 0;\n m->s = data;\n m->t = STRING;\n m->is_something = true;\n }\n\n else\n {\n m->i = 0;\n m->s = NULL;\n m->t = 0;\n m->is_something = false;\n }\n\n return m;\n}\n\nMaybe *bind_maybe(Maybe *m, Maybe *(*f)(void *))\n{\n Maybe *n = malloc(sizeof(Maybe));\n \n if (f(&(m->i))->is_something)\n {\n n->i = f(&(m->i))->i;\n n->s = f(&(m->i))->s;\n n->t = f(&(m->i))->t;\n n->is_something = true;\n }\n\n else\n {\n n->i = 0;\n n->s = NULL;\n n->t = 0;\n n->is_something = false;\n }\n return n;\n}\n\nMaybe *f_1(void *v) // Int -> Maybe Int\n{\n Maybe *m = malloc(sizeof(Maybe));\n m->i = (*(int *) v) * (*(int *) v);\n m->s = NULL;\n m->t = INT;\n m->is_something = true;\n return m;\n}\n\nMaybe *f_2(void *v) // :: Int -> Maybe String\n{\n Maybe *m = malloc(sizeof(Maybe));\n m->i = 0;\n m->s = malloc(*(int *) v * sizeof(char) + 1);\n for (int i = 0; i < *(int *) v; i++)\n {\n m->s[i] = 'x';\n }\n m->s[*(int *) v + 1] = '\\0';\n m->t = STRING;\n m->is_something = true;\n return m;\n}\n\nint main()\n{\n int i = 7;\n char *s = \"lorem ipsum dolor sit amet\";\n\n Maybe *m_1 = return_maybe(&i, INT);\n Maybe *m_2 = return_maybe(s, STRING);\n\n print_Maybe(m_1); // print value of m_1: Just 49\n print_Maybe(m_2); // print value of m_2 : Just \"lorem ipsum dolor sit amet\"\n\n print_Maybe(bind_maybe(m_1, f_1)); // m_1 `bind` f_1 :: Maybe Int\n print_Maybe(bind_maybe(m_1, f_2)); // m_1 `bind` f_2 :: Maybe String\n\n print_Maybe(bind_maybe(bind_maybe(m_1, f_1), f_2)); // (m_1 `bind` f_1) `bind` f_2 :: Maybe String -- it prints 49 'x' characters in a row\n}\n"} {"title": "Move-to-front algorithm", "language": "C", "task": "Given a symbol table of a ''zero-indexed'' array of all possible input symbols\nthis algorithm reversibly transforms a sequence\nof input symbols into an array of output numbers (indices).\n\nThe transform in many cases acts to give frequently repeated input symbols\nlower indices which is useful in some compression algorithms.\n\n\n;Encoding algorithm:\n\n for each symbol of the input sequence:\n output the index of the symbol in the symbol table\n move that symbol to the front of the symbol table\n\n\n\n;Decoding algorithm:\n\n # Using the same starting symbol table\n for each index of the input sequence:\n output the symbol at that index of the symbol table\n move that symbol to the front of the symbol table\n\n\n\n;Example:\nEncoding the string of character symbols 'broood' using a symbol table of the lowercase characters '''a'''-to-'''z'''\n\n:::::{| class=\"wikitable\" border=\"1\"\n|-\n! Input\n! Output\n! SymbolTable\n|-\n| '''b'''roood\n| 1\n| 'abcdefghijklmnopqrstuvwxyz'\n|-\n| b'''r'''oood\n| 1 17\n| 'bacdefghijklmnopqrstuvwxyz'\n|-\n| br'''o'''ood\n| 1 17 15\n| 'rbacdefghijklmnopqstuvwxyz'\n|-\n| bro'''o'''od\n| 1 17 15 0\n| 'orbacdefghijklmnpqstuvwxyz'\n|-\n| broo'''o'''d\n| 1 17 15 0 0\n| 'orbacdefghijklmnpqstuvwxyz'\n|-\n| brooo'''d'''\n| 1 17 15 0 0 5\n| 'orbacdefghijklmnpqstuvwxyz'\n|}\n\n\nDecoding the indices back to the original symbol order:\n:::::{| class=\"wikitable\" border=\"1\"\n|-\n! Input\n! Output\n! SymbolTable\n|-\n| '''1''' 17 15 0 0 5\n| b\n| 'abcdefghijklmnopqrstuvwxyz'\n|-\n| 1 '''17''' 15 0 0 5\n| br\n| 'bacdefghijklmnopqrstuvwxyz'\n|-\n| 1 17 '''15''' 0 0 5\n| bro\n| 'rbacdefghijklmnopqstuvwxyz'\n|-\n| 1 17 15 '''0''' 0 5\n| broo\n| 'orbacdefghijklmnpqstuvwxyz'\n|-\n| 1 17 15 0 '''0''' 5\n| brooo\n| 'orbacdefghijklmnpqstuvwxyz'\n|-\n| 1 17 15 0 0 '''5''' \n| broood\n| 'orbacdefghijklmnpqstuvwxyz'\n|}\n\n\n;Task:\n:* Encode and decode the following three strings of characters using the symbol table of the lowercase characters '''a'''-to-'''z''' as above. \n:* Show the strings and their encoding here.\n:* Add a check to ensure that the decoded string is the same as the original.\n\n\nThe strings are: \n\n broood \n bananaaa \n hiphophiphop \n(Note the misspellings in the above strings.)\n\n", "solution": "#include\n#include\n#include\n\n#define MAX_SIZE 100\n\nint move_to_front(char *str,char c)\n{\n char *q,*p;\n int shift=0;\n p=(char *)malloc(strlen(str)+1);\n strcpy(p,str);\n q=strchr(p,c); //returns pointer to location of char c in string str\n shift=q-p; // no of characters from 0 to position of c in str\n strncpy(str+1,p,shift);\n str[0]=c;\n free(p);\n // printf(\"\\n%s\\n\",str);\n return shift;\n}\n\nvoid decode(int* pass,int size,char *sym)\n{\n int i,index;\n char c;\n char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n for(i=0;i\n#include\n\n/*The stdlib header file is required for the malloc and free functions*/\n\nint main()\n{\n\t/*Declaring a four fold integer pointer, also called\n\ta pointer to a pointer to a pointer to an integer pointer*/\n\t\n\tint**** hyperCube, i,j,k;\n\n\t/*We will need i,j,k for the memory allocation*/\n\t\n\t/*First the five lines*/\n\t\n\thyperCube = (int****)malloc(5*sizeof(int***));\n\t\n\t/*Now the four planes*/\n\t\n\tfor(i=0;i<5;i++){\n\t\thyperCube[i] = (int***)malloc(4*sizeof(int**));\n\t\t\n\t\t/*Now the 3 cubes*/\n\t\t\n\t\tfor(j=0;j<4;j++){\n\t\t\thyperCube[i][j] = (int**)malloc(3*sizeof(int*));\n\t\t\t\n\t\t\t/*Now the 2 hypercubes (?)*/\n\t\t\t\n\t\t\tfor(k=0;k<3;k++){\n\t\t\t\thyperCube[i][j][k] = (int*)malloc(2*sizeof(int));\n\t\t\t}\n\t\t}\n\t}\n\t\n\t/*All that looping and function calls may seem futile now,\n\tbut imagine real applications when the dimensions of the dataset are\n\tnot known beforehand*/\n\t\n\t/*Yes, I just copied the rest from the first program*/\n\t\n\thyperCube[4][3][2][1] = 1;\n\t\n\t/*IMPORTANT : C ( and hence C++ and Java and everyone of the family ) arrays are zero based. \n\tThe above element is thus actually the last element of the hypercube.*/\n\t\n\t/*Now we print out that element*/\n\t\n\tprintf(\"\\n%d\",hyperCube[4][3][2][1]);\n\t\n\t/*But that's not the only way to get at that element*/\n\tprintf(\"\\n%d\",*(*(*(*(hyperCube + 4) + 3) + 2) + 1));\n\n\t/*Yes, I know, it's beautiful*/\n\t*(*(*(*(hyperCube+3)+2)+1)) = 3;\n\t\n\tprintf(\"\\n%d\",hyperCube[3][2][1][0]);\n\t\n\t/*Always nice to clean up after you, yes memory is cheap, but C is 45+ years old,\n\tand anyways, imagine you are dealing with terabytes of data, or more...*/\n\t\n\tfree(hyperCube);\n\t\n\treturn 0;\n}"} {"title": "Multifactorial", "language": "C", "task": "The factorial of a number, written as n!, is defined as n! = n(n-1)(n-2)...(2)(1).\n\nMultifactorials generalize factorials as follows:\n: n! = n(n-1)(n-2)...(2)(1)\n: n!! = n(n-2)(n-4)...\n: n!! ! = n(n-3)(n-6)...\n: n!! !! = n(n-4)(n-8)...\n: n!! !! ! = n(n-5)(n-10)...\n\nIn all cases, the terms in the products are positive integers.\n\nIf we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: \n# Write a function that given n and the degree, calculates the multifactorial.\n# Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial.\n\n\n'''Note:''' The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.\n\n", "solution": "/* Include statements and constant definitions */\n#include \n#define HIGHEST_DEGREE 5\n#define LARGEST_NUMBER 10\n\n/* Recursive implementation of multifactorial function */\nint multifact(int n, int deg){\n return n <= deg ? n : n * multifact(n - deg, deg);\n}\n\n/* Iterative implementation of multifactorial function */\nint multifact_i(int n, int deg){\n int result = n;\n while (n >= deg + 1){\n result *= (n - deg);\n n -= deg;\n }\n return result;\n}\n\n/* Test function to print out multifactorials */\nint main(void){\n int i, j;\n for (i = 1; i <= HIGHEST_DEGREE; i++){\n printf(\"\\nDegree %d: \", i);\n for (j = 1; j <= LARGEST_NUMBER; j++){\n printf(\"%d \", multifact(j, i));\n }\n }\n}\n"} {"title": "Multiple distinct objects", "language": "C", "task": "Create a [[sequence]] (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime.\n\nBy ''distinct'' we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.\n\nBy ''initialized'' we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to \"zero\" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of \"zero\" for that type.\n\nThis task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the ''same'' mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.\n\nThis task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).\n\nSee also: [[Closures/Value capture]]\n\n", "solution": "foo *foos = malloc(n * sizeof(*foos));\nfor (int i = 0; i < n; i++)\n init_foo(&foos[i]);"} {"title": "Multisplit", "language": "C", "task": "It is often necessary to split a string into pieces \nbased on several different (potentially multi-character) separator strings, \nwhile still retaining the information about which separators were present in the input. \n\nThis is particularly useful when doing small parsing tasks. \nThe task is to write code to demonstrate this.\n\nThe function (or procedure or method, as appropriate) should \ntake an input string and an ordered collection of separators. \n\nThe order of the separators is significant: \nThe delimiter order represents priority in matching, with the first defined delimiter having the highest priority. \nIn cases where there would be an ambiguity as to \nwhich separator to use at a particular point \n(e.g., because one separator is a prefix of another) \nthe separator with the highest priority should be used. \nDelimiters can be reused and the output from the function should be an ordered sequence of substrings.\n\nTest your code using the input string \"a!===b=!=c\" and the separators \"==\", \"!=\" and \"=\".\n\nFor these inputs the string should be parsed as \"a\" (!=) \"\" (==) \"b\" (=) \"\" (!=) \"c\", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is \"a\", empty string, \"b\", empty string, \"c\". \nNote that the quotation marks are shown for clarity and do not form part of the output.\n\n'''Extra Credit:''' provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.\n\n", "solution": "#include \n#include \n\nvoid parse_sep(const char *str, const char *const *pat, int len)\n{\n\tint i, slen;\n\twhile (*str != '\\0') {\n\t\tfor (i = 0; i < len || !putchar(*(str++)); i++) {\n\t\t\tslen = strlen(pat[i]);\n\t\t\tif (strncmp(str, pat[i], slen)) continue;\n\t\t\tprintf(\"{%.*s}\", slen, str);\n\t\t\tstr += slen;\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nint main()\n{\n\tconst char *seps[] = { \"==\", \"!=\", \"=\" };\n\tparse_sep(\"a!===b=!=c\", seps, 3);\n\n\treturn 0;\n}"} {"title": "Munchausen numbers", "language": "C", "task": "A Munchausen number is a natural number ''n'' the sum of whose digits (in base 10), each raised to the power of itself, equals ''n''.\n\n('''Munchausen''' is also spelled: '''Munchhausen'''.) \n\nFor instance: 3435 = 33 + 44 + 33 + 55 \n\n\n;Task\nFind all Munchausen numbers between '''1''' and '''5000'''.\n\n\n;Also see:\n:* The OEIS entry: A046253\n:* The Wikipedia entry: Perfect digit-to-digit invariant, redirected from ''Munchausen Number''\n\n", "solution": "#include \n#include \n\nint main() {\n for (int i = 1; i < 5000; i++) {\n // loop through each digit in i\n // e.g. for 1000 we get 0, 0, 0, 1.\n int sum = 0;\n for (int number = i; number > 0; number /= 10) {\n int digit = number % 10;\n // find the sum of the digits \n // raised to themselves \n sum += pow(digit, digit);\n }\n if (sum == i) {\n // the sum is equal to the number\n // itself; thus it is a \n // munchausen number\n printf(\"%i\\n\", i);\n } \n }\n return 0;\n}"} {"title": "Musical scale", "language": "C", "task": "Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz.\n\nThese are the notes \"C, D, E, F, G, A, B, C(1 octave higher)\", or \"Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)\" on Fixed do Solfege.\n\nFor the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed.\n\nFor languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.\n\n", "solution": "#include\n#include\n#include\n#include\n\ntypedef struct{\n\tchar str[3];\n\tint key;\n\t}note;\n\t\nnote sequence[] = {{\"Do\",0},{\"Re\",2},{\"Mi\",4},{\"Fa\",5},{\"So\",7},{\"La\",9},{\"Ti\",11},{\"Do\",12}};\n\nint main(void)\n{\n\tint i=0;\n\t\n\twhile(!kbhit())\n\t{\n\t\tprintf(\"\\t%s\",sequence[i].str);\n\t\tsound(261.63*pow(2,sequence[i].key/12.0));\n\t\tdelay(sequence[i].key%12==0?500:1000);\n\t\ti = (i+1)%8;\n\t\ti==0?printf(\"\\n\"):printf(\"\");\n\t}\n\tnosound();\n\treturn 0;\n}"} {"title": "N-queens problem", "language": "C", "task": "right\n\nSolve the eight queens puzzle. \n\n\nYou can extend the problem to solve the puzzle with a board of size '''N'''x'''N'''.\n \nFor the number of solutions for small values of '''N''', see OEIS: A000170.\n\n\n;Related tasks:\n* [[A* search algorithm]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Holy Knight's tour]]\n* [[Knight's tour]]\n* [[Peaceful chess queen armies]]\n* [[Solve a Hopido puzzle]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "#include \n#include \n\ntypedef unsigned int uint;\nuint count = 0;\n\n#define ulen sizeof(uint) * 8\n\n/* could have defined as int solve(...), but void may have less\n chance to confuse poor optimizer */\nvoid solve(int n)\n{\n\tint cnt = 0;\n\tconst uint full = -(int)(1 << (ulen - n));\n\tregister uint bits, pos, *m, d, e;\n\n\tuint b0, b1, l[32], r[32], c[32], mm[33] = {0};\n\tn -= 3;\n\t/* require second queen to be left of the first queen, so\n\t we ever only test half of the possible solutions. This\n\t is why we can't handle n=1 here */\n\tfor (b0 = 1U << (ulen - n - 3); b0; b0 <<= 1) {\n\t\tfor (b1 = b0 << 2; b1; b1 <<= 1) {\n\t\t\td = n;\n\t\t\t/* c: columns occupied by previous queens.\n\t\t\t l: columns attacked by left diagonals\n\t\t\t r: by right diagnoals */\n\t\t\tc[n] = b0 | b1;\n\t\t\tl[n] = (b0 << 2) | (b1 << 1);\n\t\t\tr[n] = (b0 >> 2) | (b1 >> 1);\n\n\t\t\t/* availabe columns on current row. m is stack */\n\t\t\tbits = *(m = mm + 1) = full & ~(l[n] | r[n] | c[n]);\n\n\t\t\twhile (bits) {\n\t\t\t\t/* d: depth, aka row. counting backwards\n\t\t\t\t because !d is often faster than d != n */\n\t\t\t\twhile (d) {\n\t\t\t\t\t/* pos is right most nonzero bit */\n\t\t\t\t\tpos = -(int)bits & bits;\n\n\t\t\t\t\t/* mark bit used. only put current bits\n\t\t\t\t\t on stack if not zero, so backtracking\n\t\t\t\t\t will skip exhausted rows (because reading\n\t\t\t\t\t stack variable is sloooow compared to\n\t\t\t\t\t registers) */\n\t\t\t\t\tif ((bits &= ~pos))\n\t\t\t\t\t\t*m++ = bits | d;\n\n\t\t\t\t\t/* faster than l[d+1] = l[d]... */\n\t\t\t\t\te = d--;\n\t\t\t\t\tl[d] = (l[e] | pos) << 1;\n\t\t\t\t\tr[d] = (r[e] | pos) >> 1;\n\t\t\t\t\tc[d] = c[e] | pos;\n\n\t\t\t\t\tbits = full & ~(l[d] | r[d] | c[d]);\n\n\t\t\t\t\tif (!bits) break;\n\t\t\t\t\tif (!d) { cnt++; break; }\n\t\t\t\t}\n\t\t\t\t/* Bottom of stack m is a zero'd field acting\n\t\t\t\t as sentinel. When saving to stack, left\n\t\t\t\t 27 bits are the available columns, while\n\t\t\t\t right 5 bits is the depth. Hence solution\n\t\t\t\t is limited to size 27 board -- not that it\n\t\t\t\t matters in foreseeable future. */\n\t\t\t\td = (bits = *--m) & 31U;\n\t\t\t\tbits &= ~31U;\n\t\t\t}\n\t\t}\n\t}\n\tcount = cnt * 2;\n}\n\nint main(int c, char **v)\n{\n\tint nn;\n\tif (c <= 1 || (nn = atoi(v[1])) <= 0) nn = 8;\n\n\tif (nn > 27) {\n\t\tfprintf(stderr, \"Value too large, abort\\n\");\n\t\texit(1);\n\t}\n\n\t/* Can't solve size 1 board; might as well skip 2 and 3 */\n\tif (nn < 4) count = nn == 1;\n\telse\t solve(nn);\n\n\tprintf(\"\\nSolutions: %d\\n\", count);\n\treturn 0;\n}"} {"title": "Narcissist", "language": "C", "task": "Quoting from the Esolangs wiki page:\n\n\nA '''narcissist''' (or '''Narcissus program''') is the decision-problem version of a [[quine]].\n\nA 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.\n\n\nFor concreteness, in this task we shall assume that symbol = character. \n\nThe narcissist should be able to cope with any finite input, whatever its length. \n\nAny form of output is allowed, as long as the program always halts, and \"accept\", \"reject\" and \"not yet finished\" are distinguishable.\n\n", "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)); }"} {"title": "Narcissistic decimal number", "language": "C", "task": "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.\n\n\nNarcissistic (decimal) numbers are sometimes called '''Armstrong''' numbers, named after Michael F. Armstrong. \nThey are also known as '''Plus Perfect''' numbers.\n\n\n;An example:\n::::* if n is '''153''' \n::::* then m, (the number of decimal digits) is '''3''' \n::::* we have 13 + 53 + 33 = 1 + 125 + 27 = '''153''' \n::::* and so '''153''' is a narcissistic decimal number\n\n\n;Task:\nGenerate and show here the first '''25''' narcissistic decimal numbers.\n\n\n\nNote: 0^1 = 0, the first in the series. \n\n\n;See also:\n* the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers.\n* MathWorld entry: Narcissistic Number.\n* Wikipedia entry: Narcissistic number.\n\n", "solution": "#include \n#include \n\n#define MAX_LEN 81\n\nmpz_t power[10];\nmpz_t dsum[MAX_LEN + 1];\nint cnt[10], len;\n\nvoid check_perm(void)\n{\n\tchar s[MAX_LEN + 1];\n\tint i, c, out[10] = { 0 };\n\n\tmpz_get_str(s, 10, dsum[0]);\n\tfor (i = 0; s[i]; i++) {\n\t\tc = s[i]-'0';\n\t\tif (++out[c] > cnt[c]) return;\n\t}\n\n\tif (i == len)\n\t\tgmp_printf(\" %Zd\", dsum[0]);\n}\n\nvoid narc_(int pos, int d)\n{\n\tif (!pos) {\n\t\tcheck_perm();\n\t\treturn;\n\t}\n\n\tdo {\n\t\tmpz_add(dsum[pos-1], dsum[pos], power[d]);\n\t\t++cnt[d];\n\t\tnarc_(pos - 1, d);\n\t\t--cnt[d];\n\t} while (d--);\n}\n\nvoid narc(int n)\n{\n\tint i;\n\tlen = n;\n\tfor (i = 0; i < 10; i++)\n\t\tmpz_ui_pow_ui(power[i], i, n);\n\n\tmpz_init_set_ui(dsum[n], 0);\n\n\tprintf(\"length %d:\", n);\n\tnarc_(n, 9);\n\tputchar('\\n');\n}\n\nint main(void)\n{\n\tint i;\n\n\tfor (i = 0; i <= 10; i++)\n\t\tmpz_init(power[i]);\n\tfor (i = 1; i <= MAX_LEN; i++) narc(i);\n\n\treturn 0;\n}"} {"title": "Nautical bell", "language": "C", "task": "Task\n\nWrite a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day.\n\nThe bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise.\n\nIt 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. \n\n\n;Related task:\n* [[Sleep]]\n\n", "solution": "#include\n#include\n#include\n\n#define SHORTLAG 1000\n#define LONGLAG 2000\n\nint main(){\n\tint i,times,hour,min,sec,min1,min2;\n\t\n\ttime_t t;\n\tstruct tm* currentTime;\n\t\n\twhile(1){\n\t\ttime(&t);\n\t\tcurrentTime = localtime(&t);\n\t\t\n\t\thour = currentTime->tm_hour;\n\t\tmin = currentTime->tm_min;\n\t\tsec = currentTime->tm_sec;\n\t\t\n\t\thour = 12;\n\t\tmin = 0;\n\t\tsec = 0;\n\t\t\n\t\tif((min==0 || min==30) && sec==0)\n\t\t\ttimes = ((hour*60 + min)%240)%8;\n\t\tif(times==0){\n\t\t\ttimes = 8;\n\t\t}\t\n\n\t\tif(min==0){\n\t\t\tmin1 = 0;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\telse{\n\t\t\tmin1 = 3;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\tif((min==0 || min==30) && sec==0){\n\t\t\tprintf(\"\\nIt is now %d:%d%d %s. Sounding the bell %d times.\",hour,min1,min2,(hour>11)?\"PM\":\"AM\",times);\n\t\t\n\t\t\tfor(i=1;i<=times;i++){\n\t\t\t\tprintf(\"\\a\");\n\t\t\t\t\n\t\t\t\t(i%2==0)?sleep(LONGLAG):sleep(SHORTLAG);\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n\n"} {"title": "Nested function", "language": "C", "task": "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.\n\n\n;Task: \nWrite a program consisting of two nested functions that prints the following text.\n\n 1. first\n 2. second\n 3. third\n\nThe 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.\n\nThe 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.\n\n\n;References:\n:* Nested function\n\n", "solution": "#include\n#include\n\ntypedef struct{\n\tchar str[30];\n}item;\n\nitem* makeList(char* separator){\n\tint counter = 0,i;\n\titem* list = (item*)malloc(3*sizeof(item));\n\t\n\titem makeItem(){\n\t\titem holder;\n\t\t\n\t\tchar names[5][10] = {\"first\",\"second\",\"third\",\"fourth\",\"fifth\"};\n\t\t\n\t\tsprintf(holder.str,\"%d%s%s\",++counter,separator,names[counter]);\n\t\t\n\t\treturn holder;\n\t}\n\t\n\tfor(i=0;i<3;i++)\n\t\tlist[i] = makeItem();\n\t\n\treturn list;\n}\n\nint main()\n{\n\tint i;\n\titem* list = makeList(\". \");\n\t\n\tfor(i=0;i<3;i++)\n\t\tprintf(\"\\n%s\",list[i].str);\n\t\n\treturn 0;\n}\n"} {"title": "Next highest int from digits", "language": "C", "task": "Given a zero or positive integer, the task is to generate the next largest\ninteger using only the given digits*1.\n\n* Numbers will not be padded to the left with zeroes.\n* Use all given digits, with their given multiplicity. (If a digit appears twice in the input number, it should appear twice in the result).\n* If there is no next highest integer return zero.\n\n\n:*1 Alternatively phrased as: \"Find the smallest integer larger than the (positive or zero) integer '''N''' \n:: which can be obtained by reordering the (base ten) digits of '''N'''\".\n\n\n;Algorithm 1:\n# Generate all the permutations of the digits and sort into numeric order.\n# Find the number in the list.\n# Return the next highest number from the list.\n\n\nThe above could prove slow and memory hungry for numbers with large numbers of\ndigits, but should be easy to reason about its correctness.\n\n\n;Algorithm 2:\n# 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.\n# Exchange that digit with the digit on the right that is ''both'' more than it, and closest to it.\n# 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)\n\n\n'''E.g.:'''\n\n n = 12453\n\n 12_4_53\n\n 12_5_43\n\n 12_5_34\n\n return: 12534\n\n\nThis second algorithm is faster and more memory efficient, but implementations\nmay be harder to test. \n\nOne method of testing, (as used in developing the task), is to compare results from both\nalgorithms for random numbers generated from a range that the first algorithm can handle.\n\n\n;Task requirements:\nCalculate the next highest int from the digits of the following numbers:\n:* 0\n:* 9\n:* 12\n:* 21\n:* 12453\n:* 738440\n:* 45072010\n:* 95322020\n\n\n;Optional stretch goal:\n:* 9589776899767587796600\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nvoid swap(char* str, int i, int j) {\n char c = str[i];\n str[i] = str[j];\n str[j] = c;\n}\n\nvoid reverse(char* str, int i, int j) {\n for (; i < j; ++i, --j)\n swap(str, i, j);\n}\n\nbool next_permutation(char* str) {\n int len = strlen(str);\n if (len < 2)\n return false;\n for (int i = len - 1; i > 0; ) {\n int j = i, k;\n if (str[--i] < str[j]) {\n k = len;\n while (str[i] >= str[--k]) {}\n swap(str, i, k);\n reverse(str, j, len - 1);\n return true;\n }\n }\n return false;\n}\n\nuint32_t next_highest_int(uint32_t n) {\n char str[16];\n snprintf(str, sizeof(str), \"%u\", n);\n if (!next_permutation(str))\n return 0;\n return strtoul(str, 0, 10);\n}\n\nint main() {\n uint32_t numbers[] = {0, 9, 12, 21, 12453, 738440, 45072010, 95322020};\n const int count = sizeof(numbers)/sizeof(int);\n for (int i = 0; i < count; ++i)\n printf(\"%d -> %d\\n\", numbers[i], next_highest_int(numbers[i]));\n // Last one is too large to convert to an integer\n const char big[] = \"9589776899767587796600\";\n char next[sizeof(big)];\n memcpy(next, big, sizeof(big));\n next_permutation(next);\n printf(\"%s -> %s\\n\", big, next);\n return 0;\n}"} {"title": "Nim game", "language": "C", "task": "Nim is a simple game where the second player-if they know the trick-will always win.\n\n\nThe game has only 3 rules:\n::* start with '''12''' tokens\n::* each player takes '''1, 2, or 3''' tokens in turn\n::* the player who takes the last token wins.\n\n\nTo 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. \n\n;Task:\nDesign a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.\n\n", "solution": "#include \n\nint playerTurn(int numTokens, int take);\nint computerTurn(int numTokens);\n\nint main(void)\n{\n\tprintf(\"Nim Game\\n\\n\");\n\t\n\tint Tokens = 12;\n\t\n\twhile(Tokens > 0)\n\t{\n\t\tprintf(\"How many tokens would you like to take?: \");\n\t\t\n\t\tint uin;\n\t\tscanf(\"%i\", &uin);\n\t\t\n\t\tint nextTokens = playerTurn(Tokens, uin);\n\t\t\n\t\tif (nextTokens == Tokens)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tTokens = nextTokens;\n\t\t\n\t\tTokens = computerTurn(Tokens);\n\t}\n\tprintf(\"Computer wins.\");\n\t\n\treturn 0;\n}\n\nint playerTurn(int numTokens, int take)\n{\n\tif (take < 1 || take > 3)\n\t{\n\t\tprintf(\"\\nTake must be between 1 and 3.\\n\\n\");\n\t\treturn numTokens;\n\t}\n\tint remainingTokens = numTokens - take;\n\t\n\tprintf(\"\\nPlayer takes %i tokens.\\n\", take);\n\tprintf(\"%i tokens remaining.\\n\\n\", remainingTokens);\n\t\n\treturn remainingTokens;\n}\n\nint computerTurn(int numTokens)\n{\n\tint take = numTokens % 4;\n\tint remainingTokens = numTokens - take;\n\t\n\tprintf(\"Computer takes %u tokens.\\n\", take);\n\tprintf(\"%i tokens remaining.\\n\\n\", remainingTokens);\n\t\n\treturn remainingTokens;\n}\n"} {"title": "Nonoblock", "language": "C", "task": "Nonogram puzzle.\n\n\n;Given:\n* The number of cells in a row.\n* The size of each, (space separated), connected block of cells to fit in the row, in left-to right order.\n\n\n;Task: \n* show all possible positions. \n* show the number of positions of the blocks for the following cases within the row. \n* show all output on this page. \n* use a \"neat\" diagram of the block positions.\n\n\n;Enumerate the following configurations:\n# '''5''' cells and '''[2, 1]''' blocks\n# '''5''' cells and '''[]''' blocks (no blocks)\n# '''10''' cells and '''[8]''' blocks\n# '''15''' cells and '''[2, 3, 2, 3]''' blocks\n# '''5''' cells and '''[2, 3]''' blocks (should give some indication of this not being possible)\n\n\n;Example:\nGiven 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:\n\n |_|_|_|_|_| # 5 cells and [2, 1] blocks\n\nAnd would expand to the following 3 possible rows of block positions:\n\n |A|A|_|B|_|\n |A|A|_|_|B|\n |_|A|A|_|B|\n\n\nNote how the sets of blocks are always separated by a space.\n\nNote also that it is not necessary for each block to have a separate letter. \nOutput approximating\n\nThis:\n |#|#|_|#|_|\n |#|#|_|_|#|\n |_|#|#|_|#|\n\nThis would also work:\n ##.#.\n ##..#\n .##.#\n\n\n;An algorithm:\n* 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).\n* 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.\n* 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.\n\n(This is the algorithm used in the [[Nonoblock#Python]] solution). \n\n\n;Reference:\n* The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its [[Nonoblock#Python]] solution.\n\n", "solution": "#include \n#include \n\nvoid nb(int cells, int total_block_size, int* blocks, int block_count,\n char* output, int offset, int* count) {\n if (block_count == 0) {\n printf(\"%2d %s\\n\", ++*count, output);\n return;\n }\n int block_size = blocks[0];\n int max_pos = cells - (total_block_size + block_count - 1);\n total_block_size -= block_size;\n cells -= block_size + 1;\n ++blocks;\n --block_count;\n for (int i = 0; i <= max_pos; ++i, --cells) {\n memset(output + offset, '.', max_pos + block_size);\n memset(output + offset + i, '#', block_size);\n nb(cells, total_block_size, blocks, block_count, output,\n offset + block_size + i + 1, count);\n }\n}\n\nvoid nonoblock(int cells, int* blocks, int block_count) {\n printf(\"%d cells and blocks [\", cells);\n for (int i = 0; i < block_count; ++i)\n printf(i == 0 ? \"%d\" : \", %d\", blocks[i]);\n printf(\"]:\\n\");\n int total_block_size = 0;\n for (int i = 0; i < block_count; ++i)\n total_block_size += blocks[i];\n if (cells < total_block_size + block_count - 1) {\n printf(\"no solution\\n\");\n return;\n }\n char output[cells + 1];\n memset(output, '.', cells);\n output[cells] = '\\0';\n int count = 0;\n nb(cells, total_block_size, blocks, block_count, output, 0, &count);\n}\n\nint main() {\n int blocks1[] = {2, 1};\n nonoblock(5, blocks1, 2);\n printf(\"\\n\");\n \n nonoblock(5, NULL, 0);\n printf(\"\\n\");\n\n int blocks2[] = {8};\n nonoblock(10, blocks2, 1);\n printf(\"\\n\");\n \n int blocks3[] = {2, 3, 2, 3};\n nonoblock(15, blocks3, 4);\n printf(\"\\n\");\n \n int blocks4[] = {2, 3};\n nonoblock(5, blocks4, 2);\n\n return 0;\n}"} {"title": "Numbers with equal rises and falls", "language": "C", "task": "When a number is written in base 10, adjacent digits may \"rise\" or \"fall\" as the number is read (usually from left to right).\n\n\n;Definition:\nGiven the decimal digits of the number are written as a series d:\n:* A ''rise'' is an index i such that d(i) < d(i+1)\n:* A ''fall'' is an index i such that d(i) > d(i+1)\n\n\n;Examples:\n:* The number '''726,169''' has '''3''' rises and '''2''' falls, so it isn't in the sequence.\n:* The number '''83,548''' has '''2''' rises and '''2''' falls, so it is in the sequence.\n\n\n;Task:\n:* Print the first '''200''' numbers in the sequence \n:* Show that the '''10 millionth''' (10,000,000th) number in the sequence is '''41,909,002'''\n\n\n;See also:\n* OEIS Sequence A296712 describes numbers whose digit sequence in base 10 have equal \"rises\" and \"falls\".\n\n\n;Related tasks:\n* Esthetic numbers\n\n", "solution": "#include \n\n/* Check whether a number has an equal amount of rises\n * and falls\n */\nint riseEqFall(int num) {\n int rdigit = num % 10;\n int netHeight = 0;\n while (num /= 10) {\n netHeight += ((num % 10) > rdigit) - ((num % 10) < rdigit);\n rdigit = num % 10;\n }\n return netHeight == 0;\n}\n\n/* Get the next member of the sequence, in order,\n * starting at 1\n */\nint nextNum() {\n static int num = 0;\n do {num++;} while (!riseEqFall(num));\n return num;\n}\n\nint main(void) {\n int total, num;\n \n /* Generate first 200 numbers */\n printf(\"The first 200 numbers are: \\n\");\n for (total = 0; total < 200; total++)\n printf(\"%d \", nextNum());\n \n /* Generate 10,000,000th number */\n printf(\"\\n\\nThe 10,000,000th number is: \");\n for (; total < 10000000; total++) num = nextNum();\n printf(\"%d\\n\", num);\n \n return 0;\n}"} {"title": "Numeric error propagation", "language": "C", "task": "If '''f''', '''a''', and '''b''' are values with uncertainties sf, sa, and sb, and '''c''' is a constant; \nthen if '''f''' is derived from '''a''', '''b''', and '''c''' in the following ways, \nthen sf can be calculated as follows:\n\n:;Addition/Subtraction\n:* If f = a +- c, or f = c +- a then '''sf = sa'''\n:* If f = a +- b then '''sf2 = sa2 + sb2'''\n\n:;Multiplication/Division\n:* If f = ca or f = ac then '''sf = |csa|'''\n:* If f = ab or f = a / b then '''sf2 = f2( (sa / a)2 + (sb / b)2)'''\n\n:;Exponentiation\n:* If f = ac then '''sf = |fc(sa / a)|'''\n\n\nCaution:\n::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.\n\n\n;Task details:\n# 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.\n# 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 \n# Print and display both '''d''' and its error.\n\n \n\n;References:\n* A Guide to Error Propagation B. Keeney, 2005.\n* Propagation of uncertainty Wikipedia.\n\n\n;Related task:\n* [[Quaternion type]]\n\n", "solution": "#include \n#include \n#include \n#include \n \ntypedef struct{\n double value;\n double delta;\n}imprecise;\n \n#define SQR(x) ((x) * (x))\nimprecise imprecise_add(imprecise a, imprecise b)\n{\n imprecise ret;\n ret.value = a.value + b.value;\n ret.delta = sqrt(SQR(a.delta) + SQR(b.delta));\n return ret;\n}\n \nimprecise imprecise_mul(imprecise a, imprecise b)\n{\n imprecise ret;\n ret.value = a.value * b.value;\n ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta));\n return ret;\n}\n \nimprecise imprecise_div(imprecise a, imprecise b)\n{\n imprecise ret;\n ret.value = a.value / b.value;\n ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta)) / SQR(b.value);\n return ret;\n}\n \nimprecise imprecise_pow(imprecise a, double c)\n{\n imprecise ret;\n ret.value = pow(a.value, c);\n ret.delta = fabs(ret.value * c * a.delta / a.value);\n return ret;\n}\n\nchar* printImprecise(imprecise val)\n{\n\tchar principal[30],error[30],*string,sign[2];\n\tsign[0] = 241; /* ASCII code for \u00b1, technical notation for denoting errors */\n\tsign[1] = 00;\n\t\n\tsprintf(principal,\"%f\",val.value);\n\tsprintf(error,\"%f\",val.delta);\n\t\n\tstring = (char*)malloc((strlen(principal)+1+strlen(error)+1)*sizeof(char));\n\t\n\tstrcpy(string,principal);\n\tstrcat(string,sign);\n\tstrcat(string,error);\n\t\n\treturn string;\n}\n \nint main(void) {\n imprecise x1 = {100, 1.1};\n imprecise y1 = {50, 1.2};\n imprecise x2 = {-200, 2.2};\n imprecise y2 = {-100, 2.3};\n imprecise d;\n \n d = imprecise_pow(imprecise_add(imprecise_pow(imprecise_add(x1, x2), 2),imprecise_pow(imprecise_add(y1, y2), 2)), 0.5);\n printf(\"Distance, d, between the following points :\");\n printf(\"\\n( x1, y1) = ( %s, %s)\",printImprecise(x1),printImprecise(y1));\n printf(\"\\n( x2, y2) = ( %s, %s)\",printImprecise(x2),printImprecise(y2));\n printf(\"\\nis d = %s\", printImprecise(d));\n return 0;\n}\n"} {"title": "Odd word problem", "language": "C", "task": "Write a program that solves the odd word problem with the restrictions given below.\n\n\n;Description:\nYou are promised an input stream consisting of English letters and punctuations. \n\nIt is guaranteed that:\n* the words (sequence of consecutive letters) are delimited by one and only one punctuation,\n* the stream will begin with a word,\n* the words will be at least one letter long, and \n* a full stop (a period, [.]) appears after, and only after, the last word.\n\n\n;Example:\nA stream with six words: \n:: what,is,the;meaning,of:life. \n\n\nThe task is to reverse the letters in every other word while leaving punctuations intact, producing:\n:: what,si,the;gninaem,of:efil. \nwhile observing the following restrictions:\n# 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;\n# You '''are not''' to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;\n# You '''are''' allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.\n\n\n;Test cases:\nWork on both the \"life\" example given above, and also the text:\n:: we,are;not,in,kansas;any,more.\n\n", "solution": "#include \n#include \n\nstatic int \nowp(int odd)\n{\n int ch, ret;\n ch = getc(stdin);\n if (!odd) {\n putc(ch, stdout);\n if (ch == EOF || ch == '.')\n return EOF;\n if (ispunct(ch))\n return 0;\n owp(odd);\n return 0;\n } else {\n if (ispunct(ch))\n return ch; \n ret = owp(odd);\n putc(ch, stdout);\n return ret;\n }\n}\n\nint\nmain(int argc, char **argv)\n{\n int ch = 1;\n while ((ch = owp(!ch)) != EOF) {\n if (ch)\n putc(ch, stdout);\n if (ch == '.')\n break;\n }\n return 0;\n}\n"} {"title": "Old Russian measure of length", "language": "C", "task": "Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).\n\n\nIt is an example of a linear transformation of several variables. \n\n\nThe program should accept a single value in a selected unit of measurement, and convert and return it to the other units: \n''vershoks'', ''arshins'', ''sazhens'', ''versts'', ''meters'', ''centimeters'' and ''kilometers''.\n\n\n;Also see:\n:* Old Russian measure of length\n\n", "solution": "#include\n#include\n#include\n#include\n\n#define UNITS_LENGTH 13\n\nint main(int argC,char* argV[])\n{\n\tint i,reference;\n\tchar *units[UNITS_LENGTH] = {\"kilometer\",\"meter\",\"centimeter\",\"tochka\",\"liniya\",\"diuym\",\"vershok\",\"piad\",\"fut\",\"arshin\",\"sazhen\",\"versta\",\"milia\"};\n 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};\n\t\n\tif(argC!=3)\n\t\tprintf(\"Usage : %s followed by length as \");\n\telse{\n\t\tfor(i=0;argV[2][i]!=00;i++)\n\t\t\targV[2][i] = tolower(argV[2][i]);\n\t\t\n\t\tfor(i=0;i\nstatic char const *animals[] = {\n \"fly\", \n \"spider\", \n \"bird\", \n \"cat\", \n \"dog\", \n \"goat\", \n \"cow\", \n \"horse\"\n};\nstatic char const *verses[] = {\n \"I don't know why she swallowed that fly.\\nPerhaps she'll die\\n\",\n \"That wiggled and jiggled and tickled inside her\",\n \"How absurd, to swallow a bird\",\n \"Imagine that. She swallowed a cat\",\n \"What a hog to swallow a dog\",\n \"She just opened her throat and swallowed that goat\",\n \"I don't know how she swallowed that cow\",\n \"She's dead of course\"\n};\n\n#define LEN(ARR) (sizeof ARR / sizeof *ARR)\n\nint main(void)\n{\n for (size_t i = 0; i < LEN(animals); i++) {\n printf(\"There was an old lady who swallowed a %s\\n%s\\n\", animals[i], verses[i]);\n for (size_t j = i; j > 0 && i < LEN(animals) - 1; j--) {\n printf(\"She swallowed the %s to catch the %s\\n\", animals[j], animals[j-1]);\n if (j == 1) {\n printf(\"%s\\n\", verses[0]);\n }\n }\n }\n}"} {"title": "One of n lines in a file", "language": "C", "task": "A method of choosing a line randomly from a file:\n::* Without reading the file more than once\n::* When substantial parts of the file cannot be held in memory\n::* Without knowing how many lines are in the file\nIs to:\n::* keep the first line of the file as a possible choice, then\n::* 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.\n::* 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.\n::* ...\n::* 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\n\n::* Return the computed possible choice when no further lines exist in the file.\n\n\n;Task:\n# 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.\n# 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.\n# Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.\n\n\nNote: You may choose a smaller number of repetitions if necessary, but mention this up-front.\n\nNote: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling\n\n", "solution": "#include \n#include \n\ninline int irand(int n)\n{\n\tint r, randmax = RAND_MAX/n * n;\n\twhile ((r = rand()) >= randmax);\n\treturn r / (randmax / n);\n}\n\ninline int one_of_n(int n)\n{\n\tint i, r = 0;\n\tfor (i = 1; i < n; i++) if (!irand(i + 1)) r = i;\n\treturn r;\n}\n\nint main(void)\n{\n\tint i, r[10] = {0};\n\n\tfor (i = 0; i < 1000000; i++, r[one_of_n(10)]++);\n\tfor (i = 0; i < 10; i++)\n\t\tprintf(\"%d%c\", r[i], i == 9 ? '\\n':' ');\n\n\treturn 0;\n}"} {"title": "Operator precedence", "language": "C", "task": "Operators in C and C++}}\n\n\n;Task:\nProvide 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. \n\nOperators 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. \n\nState whether arguments are passed by value or by reference.\n\n", "solution": "Same as [http://rosettacode.org/wiki/Operator_precedence#C.2B.2B|See C++].\n\n"} {"title": "Padovan sequence", "language": "C", "task": "The Fibonacci sequence in several ways.\nSome are given in the table below, and the referenced video shows some of the geometric\nsimilarities.\n\n::{| class=\"wikitable\"\n! Comment !! Padovan !! Fibonacci\n|-\n| || || \n|-\n| Named after. || Richard Padovan || Leonardo of Pisa: Fibonacci\n|-\n| || || \n|-\n| Recurrence initial values. || P(0)=P(1)=P(2)=1 || F(0)=0, F(1)=1\n|-\n| Recurrence relation. || P(n)=P(n-2)+P(n-3) || F(n)=F(n-1)+F(n-2)\n|-\n| || || \n|-\n| First 10 terms. || 1,1,1,2,2,3,4,5,7,9 || 0,1,1,2,3,5,8,13,21,34\n|-\n| || || \n|-\n| Ratio of successive terms... || Plastic ratio, p || Golden ratio, g\n|-\n| || 1.324717957244746025960908854... || 1.6180339887498948482...\n|-\n| Exact formula of ratios p and q. || ((9+69**.5)/18)**(1/3) + ((9-69**.5)/18)**(1/3) || (1+5**0.5)/2\n|-\n| Ratio is real root of polynomial. || p: x**3-x-1 || g: x**2-x-1\n|-\n| || || \n|-\n| Spirally tiling the plane using. || Equilateral triangles || Squares\n|-\n| || || \n|-\n| Constants for ... || s= 1.0453567932525329623 || a=5**0.5\n|-\n| ... Computing by truncation. || P(n)=floor(p**(n-1) / s + .5) || F(n)=floor(g**n / a + .5)\n|-\n| || || \n|-\n| L-System Variables. || A,B,C || A,B\n|-\n| L-System Start/Axiom. || A || A\n|-\n| L-System Rules. || A->B,B->C,C->AB || A->B,B->AB\n|}\n\n;Task:\n* Write a function/method/subroutine to compute successive members of the Padovan series using the recurrence relation.\n* Write a function/method/subroutine to compute successive members of the Padovan series using the floor function.\n* Show the first twenty terms of the sequence.\n* Confirm that the recurrence and floor based functions give the same results for 64 terms,\n* Write a function/method/... using the L-system to generate successive strings.\n* Show the first 10 strings produced from the L-system\n* Confirm that the length of the first 32 strings produced is the Padovan sequence.\n\nShow output here, on this page.\n\n;Ref:\n* The Plastic Ratio - Numberphile video.\n\n\n", "solution": "#include \n#include \n#include \n#include \n\n/* Generate (and memoize) the Padovan sequence using\n * the recurrence relationship */\nint pRec(int n) {\n static int *memo = NULL;\n static size_t curSize = 0;\n \n /* grow memoization array when necessary and fill with zeroes */\n if (curSize <= (size_t) n) {\n size_t lastSize = curSize;\n while (curSize <= (size_t) n) curSize += 1024 * sizeof(int);\n memo = realloc(memo, curSize * sizeof(int));\n memset(memo + lastSize, 0, (curSize - lastSize) * sizeof(int));\n }\n \n /* if we don't have the value for N yet, calculate it */\n if (memo[n] == 0) {\n if (n<=2) memo[n] = 1;\n else memo[n] = pRec(n-2) + pRec(n-3);\n }\n \n return memo[n];\n}\n\n/* Calculate the Nth value of the Padovan sequence\n * using the floor function */\nint pFloor(int n) {\n long double p = 1.324717957244746025960908854;\n long double s = 1.0453567932525329623;\n return powl(p, n-1)/s + 0.5;\n}\n\n/* Given the previous value for the L-system, generate the\n * next value */\nvoid nextLSystem(const char *prev, char *buf) {\n while (*prev) {\n switch (*prev++) {\n case 'A': *buf++ = 'B'; break;\n case 'B': *buf++ = 'C'; break;\n case 'C': *buf++ = 'A'; *buf++ = 'B'; break;\n }\n }\n *buf = '\\0';\n}\n\nint main() {\n // 8192 is enough up to P_33.\n #define BUFSZ 8192\n char buf1[BUFSZ], buf2[BUFSZ];\n int i;\n \n /* Print P_0..P_19 */\n printf(\"P_0 .. P_19: \");\n for (i=0; i<20; i++) printf(\"%d \", pRec(i));\n printf(\"\\n\");\n \n /* Check that functions match up to P_63 */\n printf(\"The floor- and recurrence-based functions \");\n for (i=0; i<64; i++) {\n if (pRec(i) != pFloor(i)) {\n printf(\"do not match at %d: %d != %d.\\n\",\n i, pRec(i), pFloor(i));\n break;\n }\n }\n if (i == 64) {\n printf(\"match from P_0 to P_63.\\n\");\n }\n \n /* Show first 10 L-system strings */\n printf(\"\\nThe first 10 L-system strings are:\\n\"); \n for (strcpy(buf1, \"A\"), i=0; i<10; i++) {\n printf(\"%s\\n\", buf1);\n strcpy(buf2, buf1);\n nextLSystem(buf2, buf1);\n }\n \n /* Check lengths of strings against pFloor up to P_31 */\n printf(\"\\nThe floor- and L-system-based functions \");\n for (strcpy(buf1, \"A\"), i=0; i<32; i++) {\n if ((int)strlen(buf1) != pFloor(i)) {\n printf(\"do not match at %d: %d != %d\\n\",\n i, (int)strlen(buf1), pFloor(i));\n break;\n }\n strcpy(buf2, buf1);\n nextLSystem(buf2, buf1);\n }\n if (i == 32) {\n printf(\"match from P_0 to P_31.\\n\");\n }\n \n return 0;\n}"} {"title": "Palindrome dates", "language": "C", "task": "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.\n\n\n;Task\nWrite a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the '''yyyy-mm-dd''' format.\n\n", "solution": "#include \n#include \n#include \n#include \n\nbool is_palindrome(const char* str) {\n size_t n = strlen(str);\n for (size_t i = 0; i + 1 < n; ++i, --n) {\n if (str[i] != str[n - 1])\n return false;\n }\n return true;\n}\n\nint main() {\n time_t timestamp = time(0);\n const int seconds_per_day = 24*60*60;\n int count = 15;\n char str[32];\n printf(\"Next %d palindrome dates:\\n\", count);\n for (; count > 0; timestamp += seconds_per_day) {\n struct tm* ptr = gmtime(×tamp);\n strftime(str, sizeof(str), \"%Y%m%d\", ptr);\n if (is_palindrome(str)) {\n strftime(str, sizeof(str), \"%F\", ptr);\n printf(\"%s\\n\", str);\n --count;\n }\n }\n return 0;\n}"} {"title": "Pangram checker", "language": "C", "task": "A pangram is a sentence that contains all the letters of the English alphabet at least once.\n\nFor example: ''The quick brown fox jumps over the lazy dog''.\n\n\n;Task:\nWrite a function or method to check a sentence to see if it is a pangram (or not) and show its use.\n\n\n;Related tasks:\n:* determine if a string has all the same characters\n:* determine if a string has all unique characters\n\n", "solution": "#include \n\nint is_pangram(const char *s)\n{\n\tconst char *alpha = \"\"\n\t\t\"abcdefghjiklmnopqrstuvwxyz\"\n\t\t\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n\tchar ch, wasused[26] = {0};\n\tint total = 0;\n\n\twhile ((ch = *s++) != '\\0') {\n\t\tconst char *p;\n\t\tint idx;\n\n\t\tif ((p = strchr(alpha, ch)) == NULL)\n\t\t\tcontinue;\n\n\t\tidx = (p - alpha) % 26;\n\n\t\ttotal += !wasused[idx];\n\t\twasused[idx] = 1;\n\t\tif (total == 26)\n\t\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nint main(void)\n{\n\tint i;\n\tconst char *tests[] = {\n\t\t\"The quick brown fox jumps over the lazy dog.\",\n\t\t\"The qu1ck brown fox jumps over the lazy d0g.\"\n\t};\n\n\tfor (i = 0; i < 2; i++)\n\t\tprintf(\"\\\"%s\\\" is %sa pangram\\n\",\n\t\t\ttests[i], is_pangram(tests[i])?\"\":\"not \");\n\treturn 0;\n}"} {"title": "Paraffins", "language": "C", "task": "This organic chemistry task is essentially to implement a tree enumeration algorithm.\n\n\n;Task:\nEnumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes). \n\n\nParaffins 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.\n\nIn 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\n\nBut for all '''n''' >= 4 there are several distinct molecules (\"isomers\") with the same formula but different structures. \n\nThe number of isomers rises rather rapidly when '''n''' increases. \n\nIn 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.\n\n\n;Example:\nWith '''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: \n:::* a straight chain: (CH3)(CH2)(CH2)(CH3) \n:::* a branched chain: (CH3)(CH(CH3))(CH3)\n\nDue to bond rotations, it doesn't matter which direction the branch points in. \n\nThe 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.\n\nThe input is the number '''n''' of carbon atoms of a molecule (for instance '''17'''). \n\nThe output is how many different different paraffins there are with '''n''' carbon atoms (for instance 24,894 if '''n''' = 17).\n\nThe sequence of those results is visible in the OEIS entry: \n::: A00602: number of n-node unrooted quartic trees; number of n-carbon alkanes C(n)H(2n+2) ignoring stereoisomers. \n\nThe sequence is (the index starts from zero, and represents the number of carbon atoms):\n\n 1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159, 355, 802, 1858, 4347, 10359,\n 24894, 60523, 148284, 366319, 910726, 2278658, 5731580, 14490245,\n 36797588, 93839412, 240215803, 617105614, 1590507121, 4111846763,\n 10660307791, 27711253769, ...\n\n\n;Extra credit:\nShow the paraffins in some way. \n\nA flat 1D representation, with arrays or lists is enough, for instance:\n\n*Main> all_paraffins 1\n [CCP H H H H]\n*Main> all_paraffins 2\n [BCP (C H H H) (C H H H)]\n*Main> all_paraffins 3\n [CCP H H (C H H H) (C H H H)]\n*Main> all_paraffins 4\n [BCP (C H H (C H H H)) (C H H (C H H H)),\n CCP H (C H H H) (C H H H) (C H H H)]\n*Main> all_paraffins 5\n [CCP H H (C H H (C H H H)) (C H H (C H H H)),\n CCP H (C H H H) (C H H H) (C H H (C H H H)),\n CCP (C H H H) (C H H H) (C H H H) (C H H H)]\n*Main> all_paraffins 6\n [BCP (C H H (C H H (C H H H))) (C H H (C H H (C H H H))),\n BCP (C H H (C H H (C H H H))) (C H (C H H H) (C H H H)),\n BCP (C H (C H H H) (C H H H)) (C H (C H H H) (C H H H)),\n CCP H (C H H H) (C H H (C H H H)) (C H H (C H H H)),\n CCP (C H H H) (C H H H) (C H H H) (C H H (C H H H))]\nShowing a basic 2D ASCII-art representation of the paraffins is better; for instance (molecule names aren't necessary):\n methane ethane propane isobutane\n \n H H H H H H H H H\n | | | | | | | | |\n H - C - H H - C - C - H H - C - C - C - H H - C - C - C - H\n | | | | | | | | |\n H H H H H H H | H\n |\n H - C - H\n |\n H \n\n;Links:\n* A paper that explains the problem and its solution in a functional language:\nhttp://www.cs.wright.edu/~tkprasad/courses/cs776/paraffins-turner.pdf\n\n* A Haskell implementation:\nhttps://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs\n\n* A Scheme implementation:\nhttp://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm\n\n* A Fortress implementation: (this site has been closed)\nhttp://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005\n\n", "solution": "#include \n\n#define MAX_N 33\t/* max number of tree nodes */\n#define BRANCH 4\t/* max number of edges a single node can have */\n\n/* The basic idea: a paraffin molecule can be thought as a simple tree\n with each node being a carbon atom. Counting molecules is thus the\n problem of counting free (unrooted) trees of given number of nodes.\n\n An unrooted tree needs to be uniquely represented, so we need a way\n to cannonicalize equivalent free trees. For that, we need to first\n define the cannonical form of rooted trees. Since rooted trees can\n be constructed by a root node and up to BRANCH rooted subtrees that\n are arranged in some definite order, we can define it thusly:\n * Given the root of a tree, the weight of each of its branches is\n the number of nodes contained in that branch;\n * A cannonical rooted tree would have its direct subtrees ordered\n in descending order by weight;\n * In case multiple subtrees are the same weight, they are ordered\n by some unstated, but definite, order (this code doesn't really\n care what the ordering is; it only counts the number of choices\n in such a case, not enumerating individual trees.)\n\n A rooted tree of N nodes can then be constructed by adding smaller,\n cannonical rooted trees to a root node, such that:\n * Each subtree has fewer than BRANCH branches (since it must have\n an empty slot for an edge to connect to the new root);\n * Weight of those subtrees added later are no higher than earlier\n ones;\n * Their weight total N-1.\n A rooted tree so constructed would be itself cannonical.\n\n For an unrooted tree, we can define the radius of any of its nodes:\n it's the maximum weight of any of the subtrees if this node is used\n as the root. A node is the center of a tree if it has the smallest\n radius among all the nodes. A tree can have either one or two such\n centers; if two, they must be adjacent (cf. Knuth, tAoCP 2.3.4.4).\n\n An important fact is that, a node in a tree is its sole center, IFF\n its radius times 2 is no greater than the sum of the weights of all\n branches (ibid). While we are making rooted trees, we can add such\n trees encountered to the count of cannonical unrooted trees.\n\n A bi-centered unrooted tree with N nodes can be made by joining two\n trees, each with N/2 nodes and fewer than BRANCH subtrees, at root.\n The pair must be ordered in aforementioned implicit way so that the\n product is cannonical. */\n\ntypedef unsigned long long xint;\n#define FMT \"llu\"\n\nxint rooted[MAX_N] = {1, 1, 0};\nxint unrooted[MAX_N] = {1, 1, 0};\n\n/* choose k out of m possible values; chosen values may repeat, but the\n ordering of them does not matter. It's binomial(m + k - 1, k) */\nxint choose(xint m, xint k)\n{\n\txint i, r;\n\n\tif (k == 1) return m;\n\tfor (r = m, i = 1; i < k; i++)\n\t\tr = r * (m + i) / (i + 1);\n\treturn r;\n}\n\n/* constructing rooted trees of BR branches at root, with at most\n N radius, and SUM nodes in the partial tree already built. It's\n recursive, and CNT and L carry down the number of combinations\n and the tree radius already encountered. */\nvoid tree(xint br, xint n, xint cnt, xint sum, xint l)\n{\n\txint b, c, m, s;\n\n\tfor (b = br + 1; b <= BRANCH; b++) {\n\t\ts = sum + (b - br) * n;\n\t\tif (s >= MAX_N) return;\n\n\t\t/* First B of BR branches are all of weight n; the\n\t\t rest are at most of weight N-1 */\n\t\tc = choose(rooted[n], b - br) * cnt;\n\n\t\t/* This partial tree is singly centered as is */\n\t\tif (l * 2 < s) unrooted[s] += c;\n\n\t\t/* Trees saturate at root can't be used as building\n\t\t blocks for larger trees, so forget them */\n\t\tif (b == BRANCH) return;\n\t\trooted[s] += c;\n\n\t\t/* Build the rest of the branches */\n\t\tfor (m = n; --m; ) tree(b, m, c, s, l);\n\t}\n}\n\nvoid bicenter(int s)\n{\n\tif (s & 1) return;\n\n\t/* Pick two of the half-size building blocks, allowing\n\t repetition. */\n\tunrooted[s] += rooted[s/2] * (rooted[s/2] + 1) / 2;\n}\n\nint main()\n{\n\txint n;\n\tfor (n = 1; n < MAX_N; n++) {\n\t\ttree(0, n, 1, 1, n);\n\t\tbicenter(n);\n\t\tprintf(\"%\"FMT\": %\"FMT\"\\n\", n, unrooted[n]);\n\t}\n\n\treturn 0;\n}"} {"title": "Parsing/RPN calculator algorithm", "language": "C", "task": "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''.\n\n\n* Assume an input of a correct, space separated, string of tokens of an RPN expression\n* Test with the RPN expression generated from the [[Parsing/Shunting-yard algorithm]] task: \n 3 4 2 * 1 5 - 2 3 ^ ^ / + \n* Print or display the output here\n\n\n;Notes:\n* '''^''' means exponentiation in the expression above.\n* '''/''' means division.\n\n\n;See also:\n* [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression.\n* Several solutions to [[24 game/Solve]] make use of RPN evaluators (although tracing how they work is not a part of that task).\n* [[Parsing/RPN to infix conversion]].\n* [[Arithmetic evaluation]].\n\n", "solution": "#include \n#include \n#include \n#include \n\nvoid die(const char *msg)\n{\n\tfprintf(stderr, \"%s\", msg);\n\tabort();\n}\n\n#define MAX_D 256\ndouble stack[MAX_D];\nint depth;\n\nvoid push(double v)\n{\n\tif (depth >= MAX_D) die(\"stack overflow\\n\");\n\tstack[depth++] = v;\n}\n\ndouble pop()\n{\n\tif (!depth) die(\"stack underflow\\n\");\n\treturn stack[--depth];\n}\n\ndouble rpn(char *s)\n{\n\tdouble a, b;\n\tint i;\n\tchar *e, *w = \" \\t\\n\\r\\f\";\n\n\tfor (s = strtok(s, w); s; s = strtok(0, w)) {\n\t\ta = strtod(s, &e);\n\t\tif (e > s)\t\tprintf(\" :\"), push(a);\n#define binop(x) printf(\"%c:\", *s), b = pop(), a = pop(), push(x)\n\t\telse if (*s == '+')\tbinop(a + b);\n\t\telse if (*s == '-')\tbinop(a - b);\n\t\telse if (*s == '*')\tbinop(a * b);\n\t\telse if (*s == '/')\tbinop(a / b);\n\t\telse if (*s == '^')\tbinop(pow(a, b));\n#undef binop\n\t\telse {\n\t\t\tfprintf(stderr, \"'%c': \", *s);\n\t\t\tdie(\"unknown oeprator\\n\");\n\t\t}\n\t\tfor (i = depth; i-- || 0 * putchar('\\n'); )\n\t\t\tprintf(\" %g\", stack[i]);\n\t}\n\n\tif (depth != 1) die(\"stack leftover\\n\");\n\n\treturn pop();\n}\n\nint main(void)\n{\n\tchar s[] = \" 3 4 2 * 1 5 - 2 3 ^ ^ / + \";\n\tprintf(\"%g\\n\", rpn(s));\n\treturn 0;\n}"} {"title": "Parsing/RPN to infix conversion", "language": "C", "task": "Create a program that takes an infix notation.\n\n* Assume an input of a correct, space separated, string of tokens\n* Generate a space separated output string representing the same expression in infix notation\n* Show how the major datastructure of your algorithm changes with each new token parsed.\n* Test with the following input RPN strings then print and display the output here.\n:::::{| class=\"wikitable\"\n! RPN input !! sample output\n|- || align=\"center\"\n| 3 4 2 * 1 5 - 2 3 ^ ^ / +|| 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\n|- || align=\"center\"\n| 1 2 + 3 4 + ^ 5 6 + ^|| ( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )\n|}\n\n* Operator precedence and operator associativity is given in this table:\n::::::::{| class=\"wikitable\"\n\n! operator !! associativity !! operation\n|- || align=\"center\" \n| ^ || 4 || right || exponentiation\n|- || align=\"center\" \n| * || 3 || left || multiplication\n|- || align=\"center\" \n| / || 3 || left || division\n|- || align=\"center\" \n| + || 2 || left || addition\n|- || align=\"center\" \n| - || 2 || left || subtraction\n|}\n\n\n;See also:\n* [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression.\n* [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression.\n* Postfix to infix from the RubyQuiz site.\n\n", "solution": "#include\n#include\n#include\n\nchar** components;\nint counter = 0;\n\ntypedef struct elem{\n\tchar data[10];\n\tstruct elem* left;\n\tstruct elem* right;\n}node;\n\ntypedef node* tree;\n\nint precedenceCheck(char oper1,char oper2){\n\treturn (oper1==oper2)? 0:(oper1=='^')? 1:(oper2=='^')? 2:(oper1=='/')? 1:(oper2=='/')? 2:(oper1=='*')? 1:(oper2=='*')? 2:(oper1=='+')? 1:(oper2=='+')? 2:(oper1=='-')? 1:2;\n}\n\nint isOperator(char c){\n\treturn (c=='+'||c=='-'||c=='*'||c=='/'||c=='^');\n}\n\nvoid inorder(tree t){\n\tif(t!=NULL){\n\t\tif(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]=='^'))){\n\t\t\tprintf(\"(\");\n\t\t\tinorder(t->left);\n\t\t\tprintf(\")\");\n\t\t}\n\t\telse\n\t\t\tinorder(t->left);\n\t\n\t\tprintf(\" %s \",t->data);\n\t\n\t\tif(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]!='^'))){\n\t\t\tprintf(\"(\");\n\t\t\tinorder(t->right);\n\t\t\tprintf(\")\");\n\t\t}\n\t\telse\n\t\t\tinorder(t->right);\n\t}\n}\n\nchar* getNextString(){\n\tif(counter<0){\n\t\tprintf(\"\\nInvalid RPN !\");\n\t\texit(0);\n\t}\n\treturn components[counter--];\n}\n\ntree buildTree(char* obj,char* trace){\n\ttree t = (tree)malloc(sizeof(node));\n\t\n\tstrcpy(t->data,obj);\n\t\n\tt->right = (isOperator(obj[0])==1)?buildTree(getNextString(),trace):NULL;\n\tt->left = (isOperator(obj[0])==1)?buildTree(getNextString(),trace):NULL;\n\t\n\tif(trace!=NULL){\n\t\t\tprintf(\"\\n\");\n\t\t\tinorder(t);\n\t}\n\n\treturn t;\n}\n\nint checkRPN(){\n\tint i, operSum = 0, numberSum = 0;\n\t\n\tif(isOperator(components[counter][0])==0)\n\t\treturn 0;\n\t\n\tfor(i=0;i<=counter;i++)\n\t\t(isOperator(components[i][0])==1)?operSum++:numberSum++;\n\n\treturn (numberSum - operSum == 1);\n}\n\nvoid buildStack(char* str){\n\tint i;\n\tchar* token;\n\t\n\tfor(i=0;str[i]!=00;i++)\n\t\tif(str[i]==' ')\n\t\t\tcounter++;\n\t\t\n\tcomponents = (char**)malloc((counter + 1)*sizeof(char*));\n\t\n\ttoken = strtok(str,\" \");\n\t\n\ti = 0;\n\t\n\twhile(token!=NULL){\n\t\tcomponents[i] = (char*)malloc(strlen(token)*sizeof(char));\n\t\tstrcpy(components[i],token);\n\t\ttoken = strtok(NULL,\" \");\n\t\ti++;\n\t}\n}\n\nint main(int argC,char* argV[]){\n\tint i;\n\ttree t;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s \",argV[0]);\n\telse{\n\t\tbuildStack(argV[1]);\n\t\t\n\t\tif(checkRPN()==0){\n\t\t\tprintf(\"\\nInvalid RPN !\");\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tt = buildTree(getNextString(),argV[2]);\n\t\t\n\t\tprintf(\"\\nFinal infix expression : \");\n\t\tinorder(t);\n\t}\n\t\n\treturn 0;\n}\n"} {"title": "Parsing/Shunting-yard algorithm", "language": "C", "task": "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\nas each individual token is processed.\n\n* Assume an input of a correct, space separated, string of tokens representing an infix expression\n* Generate a space separated output string representing the RPN\n* Test with the input string:\n:::: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 \n* print and display the output here.\n* Operator precedence is given in this table:\n:{| class=\"wikitable\"\n\n! operator !! associativity !! operation\n|- || align=\"center\"\n| ^ || 4 || right || exponentiation \n|- || align=\"center\" \n| * || 3 || left || multiplication\n|- || align=\"center\" \n| / || 3 || left || division\n|- || align=\"center\" \n| + || 2 || left || addition\n|- || align=\"center\"\n| - || 2 || left || subtraction\n|}\n\n\n;Extra credit\nAdd extra text explaining the actions and an optional comment for the action on receipt of each token.\n\n\n;Note\nThe handling of functions and arguments is not required.\n\n\n;See also:\n* [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression.\n* [[Parsing/RPN to infix conversion]].\n\n", "solution": "#include \n#include \n#include \n\ntypedef struct {\n\tconst char *s;\n\tint len, prec, assoc;\n} str_tok_t;\n\ntypedef struct {\n\tconst char * str;\n\tint assoc, prec;\n\tregex_t re;\n} pat_t;\n\nenum assoc { A_NONE, A_L, A_R };\npat_t pat_eos = {\"\", A_NONE, 0};\n\npat_t pat_ops[] = {\n\t{\"^\\\\)\",\tA_NONE, -1},\n\t{\"^\\\\*\\\\*\",\tA_R, 3},\n\t{\"^\\\\^\",\tA_R, 3},\n\t{\"^\\\\*\",\tA_L, 2},\n\t{\"^/\",\t\tA_L, 2},\n\t{\"^\\\\+\",\tA_L, 1},\n\t{\"^-\",\t\tA_L, 1},\n\t{0}\n};\n\npat_t pat_arg[] = {\n\t{\"^[-+]?[0-9]*\\\\.?[0-9]+([eE][-+]?[0-9]+)?\"},\n\t{\"^[a-zA-Z_][a-zA-Z_0-9]*\"},\n\t{\"^\\\\(\", A_L, -1},\n\t{0}\n};\n\nstr_tok_t stack[256]; /* assume these are big enough */\nstr_tok_t queue[256];\nint l_queue, l_stack;\n#define qpush(x) queue[l_queue++] = x\n#define spush(x) stack[l_stack++] = x\n#define spop() stack[--l_stack]\n\nvoid display(const char *s)\n{\n\tint i;\n\tprintf(\"\\033[1;1H\\033[JText | %s\", s);\n\tprintf(\"\\nStack| \");\n\tfor (i = 0; i < l_stack; i++)\n\t\tprintf(\"%.*s \", stack[i].len, stack[i].s); // uses C99 format strings\n\tprintf(\"\\nQueue| \");\n\tfor (i = 0; i < l_queue; i++)\n\t\tprintf(\"%.*s \", queue[i].len, queue[i].s);\n\tputs(\"\\n\\n\");\n\tgetchar();\n}\n\nint prec_booster;\n\n#define fail(s1, s2) {fprintf(stderr, \"[Error %s] %s\\n\", s1, s2); return 0;}\n\nint init(void)\n{\n\tint i;\n\tpat_t *p;\n\n\tfor (i = 0, p = pat_ops; p[i].str; i++)\n\t\tif (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))\n\t\t\tfail(\"comp\", p[i].str);\n\n\tfor (i = 0, p = pat_arg; p[i].str; i++)\n\t\tif (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))\n\t\t\tfail(\"comp\", p[i].str);\n\n\treturn 1;\n}\n\npat_t* match(const char *s, pat_t *p, str_tok_t * t, const char **e)\n{\n\tint i;\n\tregmatch_t m;\n\n\twhile (*s == ' ') s++;\n\t*e = s;\n\n\tif (!*s) return &pat_eos;\n\n\tfor (i = 0; p[i].str; i++) {\n\t\tif (regexec(&(p[i].re), s, 1, &m, REG_NOTEOL))\n\t\t\tcontinue;\n\t\tt->s = s;\n\t\t*e = s + (t->len = m.rm_eo - m.rm_so);\n\t\treturn p + i;\n\t}\n\treturn 0;\n}\n\nint parse(const char *s) {\n\tpat_t *p;\n\tstr_tok_t *t, tok;\n\n\tprec_booster = l_queue = l_stack = 0;\n\tdisplay(s);\n\twhile (*s) {\n\t\tp = match(s, pat_arg, &tok, &s);\n\t\tif (!p || p == &pat_eos) fail(\"parse arg\", s);\n\n\t\t/* Odd logic here. Don't actually stack the parens: don't need to. */\n\t\tif (p->prec == -1) {\n\t\t\tprec_booster += 100;\n\t\t\tcontinue;\n\t\t}\n\t\tqpush(tok);\n\t\tdisplay(s);\n\nre_op:\t\tp = match(s, pat_ops, &tok, &s);\n\t\tif (!p) fail(\"parse op\", s);\n\n\t\ttok.assoc = p->assoc;\n\t\ttok.prec = p->prec;\n\n\t\tif (p->prec > 0)\n\t\t\ttok.prec = p->prec + prec_booster;\n\t\telse if (p->prec == -1) {\n\t\t\tif (prec_booster < 100)\n\t\t\t\tfail(\"unmatched )\", s);\n\t\t\ttok.prec = prec_booster;\n\t\t}\n\n\t\twhile (l_stack) {\n\t\t\tt = stack + l_stack - 1;\n\t\t\tif (!(t->prec == tok.prec && t->assoc == A_L)\n\t\t\t\t\t&& t->prec <= tok.prec)\n\t\t\t\tbreak;\n\t\t\tqpush(spop());\n\t\t\tdisplay(s);\n\t\t}\n\n\t\tif (p->prec == -1) {\n\t\t\tprec_booster -= 100;\n\t\t\tgoto re_op;\n\t\t}\n\n\t\tif (!p->prec) {\n\t\t\tdisplay(s);\n\t\t\tif (prec_booster)\n\t\t\t\tfail(\"unmatched (\", s);\n\t\t\treturn 1;\n\t\t}\n\n\t\tspush(tok);\n\t\tdisplay(s);\n\t}\n\n\tif (p->prec > 0)\n\t\tfail(\"unexpected eol\", s);\n\n\treturn 1;\n}\n\nint main()\n{\n\tint i;\n\tconst char *tests[] = { \n\t\t\"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\",\t/* RC mandated: OK */\n\t\t\"123\",\t\t\t\t\t/* OK */\n\t\t\"3+4 * 2 / ( 1 - 5 ) ^ 2 ^ 3.14\",\t/* OK */\n\t\t\"(((((((1+2+3**(4 + 5))))))\",\t\t/* bad parens */\n\t\t\"a^(b + c/d * .1e5)!\",\t\t\t/* unknown op */\n\t\t\"(1**2)**3\",\t\t\t\t/* OK */\n\t\t\"2 + 2 *\",\t\t\t\t/* unexpected eol */\n\t\t0\n\t};\n\n\tif (!init()) return 1;\n\tfor (i = 0; tests[i]; i++) {\n\t\tprintf(\"Testing string `%s' \\n\", tests[i]);\n\t\tgetchar();\n\n\t\tprintf(\"string `%s': %s\\n\\n\", tests[i],\n\t\t\tparse(tests[i]) ? \"Ok\" : \"Error\");\n\t}\n\n\treturn 0;\n}"} {"title": "Pascal's triangle/Puzzle", "language": "C", "task": "This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers.\n\n [ 151]\n [ ][ ]\n [40][ ][ ]\n [ ][ ][ ][ ]\n [ X][11][ Y][ 4][ Z]\n\nEach brick of the pyramid is the sum of the two bricks situated below it.\nOf the three missing numbers at the base of the pyramid, \nthe middle one is the sum of the other two (that is, Y = X + Z).\n\n\n;Task:\nWrite a program to find a solution to this puzzle.\n\n", "solution": "/* Pascal's pyramid solver\n *\n * [top]\n * [ ] [ ]\n * [mid] [ ] [ ]\n * [ ] [ ] [ ] [ ]\n * [ x ] [ a ] [ y ] [ b ] [ z ]\n * x + z = y\n *\n * This solution makes use of a little bit of mathematical observation, \n * such as the fact that top = 4(a+b) + 7(x+z) and mid = 2x + 2a + z.\n */\n\n#include \n#include \n\nvoid pascal(int a, int b, int mid, int top, int* x, int* y, int* z)\n{\n double ytemp = (top - 4 * (a + b)) / 7.; \n if(fmod(ytemp, 1.) >= 0.0001)\n { \n x = 0;\n return;\n } \n *y = ytemp;\n *x = mid - 2 * a - *y;\n *z = *y - *x;\n}\nint main()\n{\n int a = 11, b = 4, mid = 40, top = 151;\n int x, y, z;\n pascal(a, b, mid, top, &x, &y, &z);\n if(x != 0)\n printf(\"x: %d, y: %d, z: %d\\n\", x, y, z);\n else printf(\"No solution\\n\");\n\n return 0;\n}\n"} {"title": "Pascal matrix generation", "language": "C", "task": "A pascal matrix is a two-dimensional square matrix holding numbers from binomial coefficients and which can be shown as nCr.\n\nShown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4. \n\nA Pascal upper-triangular matrix that is populated with jCi:\n\n[[1, 1, 1, 1, 1],\n [0, 1, 2, 3, 4],\n [0, 0, 1, 3, 6],\n [0, 0, 0, 1, 4],\n [0, 0, 0, 0, 1]]\n\n\nA Pascal lower-triangular matrix that is populated with iCj (the transpose of the upper-triangular matrix):\n\n[[1, 0, 0, 0, 0],\n [1, 1, 0, 0, 0],\n [1, 2, 1, 0, 0],\n [1, 3, 3, 1, 0],\n [1, 4, 6, 4, 1]]\n\n\nA Pascal symmetric matrix that is populated with i+jCi:\n\n[[1, 1, 1, 1, 1],\n [1, 2, 3, 4, 5],\n [1, 3, 6, 10, 15],\n [1, 4, 10, 20, 35],\n [1, 5, 15, 35, 70]]\n\n\n\n;Task:\nWrite functions capable of generating each of the three forms of n-by-n matrices.\n\nUse those functions to display upper, lower, and symmetric Pascal 5-by-5 matrices on this page. \n\nThe 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).\n\n\n;Note: \nThe [[Cholesky decomposition]] of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size. \n\n", "solution": "#include \n#include \n\nvoid pascal_low(int **mat, int n) {\n int i, j;\n\n for (i = 0; i < n; ++i)\n for (j = 0; j < n; ++j)\n if (i < j)\n mat[i][j] = 0;\n else if (i == j || j == 0)\n mat[i][j] = 1;\n else\n mat[i][j] = mat[i - 1][j - 1] + mat[i - 1][j];\n}\n\nvoid pascal_upp(int **mat, int n) {\n int i, j;\n\n for (i = 0; i < n; ++i)\n for (j = 0; j < n; ++j)\n if (i > j)\n mat[i][j] = 0;\n else if (i == j || i == 0)\n mat[i][j] = 1;\n else\n mat[i][j] = mat[i - 1][j - 1] + mat[i][j - 1];\n}\n\nvoid pascal_sym(int **mat, int n) {\n int i, j;\n\n for (i = 0; i < n; ++i)\n for (j = 0; j < n; ++j)\n if (i == 0 || j == 0)\n mat[i][j] = 1;\n else\n mat[i][j] = mat[i - 1][j] + mat[i][j - 1];\n}\n\nint main(int argc, char * argv[]) {\n int **mat;\n int i, j, n;\n\n /* Input size of the matrix */\n n = 5;\n\n /* Matrix allocation */\n mat = calloc(n, sizeof(int *));\n for (i = 0; i < n; ++i)\n mat[i] = calloc(n, sizeof(int));\n\n /* Matrix computation */\n printf(\"=== Pascal upper matrix ===\\n\");\n pascal_upp(mat, n);\n for (i = 0; i < n; i++)\n for (j = 0; j < n; j++)\n printf(\"%4d%c\", mat[i][j], j < n - 1 ? ' ' : '\\n');\n\n printf(\"=== Pascal lower matrix ===\\n\");\n pascal_low(mat, n);\n for (i = 0; i < n; i++)\n for (j = 0; j < n; j++)\n printf(\"%4d%c\", mat[i][j], j < n - 1 ? ' ' : '\\n');\n\n printf(\"=== Pascal symmetric matrix ===\\n\");\n pascal_sym(mat, n);\n for (i = 0; i < n; i++)\n for (j = 0; j < n; j++)\n printf(\"%4d%c\", mat[i][j], j < n - 1 ? ' ' : '\\n');\n\n return 0;\n}\n"} {"title": "Password generator", "language": "C", "task": "Create a password generation program which will generate passwords containing random ASCII characters from the following groups:\n lower-case letters: a --> z\n upper-case letters: A --> Z\n digits: 0 --> 9\n other printable characters: !\"#$%&'()*+,-./:;<=>?@[]^_{|}~ \n (the above character list excludes white-space, backslash and grave) \n\n\nThe generated password(s) must include ''at least one'' (of each of the four groups):\n lower-case letter, \n upper-case letter,\n digit (numeral), and \n one \"other\" character. \n\n\nThe user must be able to specify the password length and the number of passwords to generate. \n\nThe passwords should be displayed or written to a file, one per line.\n\nThe randomness should be from a system source or library. \n\nThe program should implement a help option or button which should describe the program and options when invoked. \n\nYou may also allow the user to specify a seed value, and give the option of excluding visually similar characters.\n\nFor example: Il1 O0 5S 2Z where the characters are: \n::::* capital eye, lowercase ell, the digit one\n::::* capital oh, the digit zero \n::::* the digit five, capital ess\n::::* the digit two, capital zee\n\n\n", "solution": "#include \n#include \n#include \n\n#define DEFAULT_LENGTH 4\n#define DEFAULT_COUNT 1\n\nchar* symbols[] = {\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", \"abcdefghijklmnopqrstuvwxyz\", \"0123456789\", \"!\\\"#$%&'()*+,-./:;<=>?@[]^_{|}~\"};\nint length = DEFAULT_LENGTH;\nint count = DEFAULT_COUNT;\nunsigned seed;\nchar exSymbols = 0;\n\nvoid GetPassword () {\n //create an array of values that determine the number of characters from each category \n int lengths[4] = {1, 1, 1, 1};\n int count = 4;\n while (count < length) {\n lengths[rand()%4]++;\n count++;\n } \n\n //loop through the array of lengths and set the characters in password\n char password[length + 1];\n for (int i = 0; i < length; ) { \n //pick which string to read from\n int str = rand()%4;\n if (!lengths[str])continue; //if the number of characters for that string have been reached, continue to the next interation\n\n char c;\n switch (str) {\n case 2:\n c = symbols[str][rand()%10];\n while (exSymbols && (c == 'I' || c == 'l' || c == '1' || c == 'O' || c == '0' || c == '5' || c == 'S' || c == '2' || c == 'Z'))\n c = symbols[str][rand()%10];\n password[i] = c;\n break;\n\n case 3:\n c = symbols[str][rand()%30];\n while (exSymbols && (c == 'I' || c == 'l' || c == '1' || c == 'O' || c == '0' || c == '5' || c == 'S' || c == '2' || c == 'Z'))\n c = symbols[str][rand()%30];\n password[i] = c;\n break;\n\n default:\n c = symbols[str][rand()%26];\n while (exSymbols && (c == 'I' || c == 'l' || c == '1' || c == 'O' || c == '0' || c == '5' || c == 'S' || c == '2' || c == 'Z')) \n c = symbols[str][rand()%26];\n password[i] = c;\n break;\n }\n\n i++;\n lengths[str]--;\n }\n\n password [length] = '\\0';\n printf (\"%s\\n\", password);\n}\n\nint main (int argc, char* argv[]) {\n seed = (unsigned)time(NULL);\n\n //handle user input from the command line\n for (int i = 1; i < argc; i++) {\n switch (argv[i][1]) {\n case 'l':\n if (sscanf (argv[i+1], \"%d\", &length) != 1) {\n puts (\"Unrecognized input. Syntax: -l [integer]\");\n return -1;\n }\n \n if (length < 4) {\n puts (\"Password length must be at least 4 characters.\");\n return -1;\n }\n i++; \n break;\n\n case 'c':\n if (sscanf (argv[i+1], \"%d\", &count) != 1) {\n puts (\"Unrecognized input. Syntax: -c [integer]\");\n return -1;\n }\n\n if (count <= 0) {\n puts (\"Count must be at least 1.\");\n return -1;\n }\n i++;\n break;\n\n case 's':\n if (sscanf (argv[i+1], \"%d\", &seed) != 1) {\n puts (\"Unrecognized input. Syntax: -s [integer]\");\n return -1;\n }\n i++;\n break;\n\n case 'e':\n exSymbols = 1;\n break;\n\n default:\n help:\n printf (\"Help:\\nThis program generates a random password.\\n\"\n \"Commands:\"\n \"Set password length: -l [integer]\\n\"\n \"Set password count: -c [integer]\\n\"\n \"Set seed: -s [integer]\\n\"\n \"Exclude similiar characters: -e\\n\"\n \"Display help: -h\");\n return 0;\n break;\n } \n }\n\n srand (seed);\n\n for (int i = 0; i < count; i++)\n GetPassword();\n \n return 0;\n}\n"} {"title": "Pathological floating point problems", "language": "C", "task": "Most programmers are familiar with the inexactness of floating point calculations in a binary processor. \n\nThe classic example being:\n\n0.1 + 0.2 = 0.30000000000000004\n\n\nIn many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding.\n\nThere are pathological problems however, where seemingly simple, straight-forward calculations are extremely sensitive to even tiny amounts of imprecision.\n\nThis task's purpose is to show how your language deals with such classes of problems.\n\n\n'''A sequence that seems to converge to a wrong limit.''' \n\nConsider the sequence:\n:::::: v1 = 2 \n:::::: v2 = -4 \n:::::: vn = 111 - 1130 / vn-1 + 3000 / (vn-1 * vn-2) \n\n\nAs '''n''' grows larger, the series should converge to '''6''' but small amounts of error will cause it to approach '''100'''.\n\n\n;Task 1:\nDisplay the values of the sequence where n = 3, 4, 5, 6, 7, 8, 20, 30, 50 & 100 to at least '''16''' decimal places.\n\n n = 3 18.5\n n = 4 9.378378\n n = 5 7.801153\n n = 6 7.154414\n n = 7 6.806785\n n = 8 6.5926328\n n = 20 6.0435521101892689\n n = 30 6.006786093031205758530554\n n = 50 6.0001758466271871889456140207471954695237\n n = 100 6.000000019319477929104086803403585715024350675436952458072592750856521767230266\n\n\n\n;Task 2:\n'''The Chaotic Bank Society''' is offering a new investment account to their customers. \n\nYou first deposit $e - 1 where e is 2.7182818... the base of natural logarithms.\n\nAfter each year, your account balance will be multiplied by the number of years that have passed, and $1 in service charges will be removed. \n\nSo ...\n::* after 1 year, your balance will be multiplied by 1 and $1 will be removed for service charges.\n::* after 2 years your balance will be doubled and $1 removed.\n::* after 3 years your balance will be tripled and $1 removed.\n::* ... \n::* after 10 years, multiplied by 10 and $1 removed, and so on. \n\n\nWhat will your balance be after 25 years?\n Starting balance: $e-1\n Balance = (Balance * year) - 1 for 25 years\n Balance after 25 years: $0.0399387296732302\n\n\n;Task 3, extra credit:\n'''Siegfried Rump's example.''' Consider the following function, designed by Siegfried Rump in 1988.\n:::::: f(a,b) = 333.75b6 + a2( 11a2b2 - b6 - 121b4 - 2 ) + 5.5b8 + a/(2b) \n:::::: compute f(a,b) where a=77617.0 and b=33096.0 \n:::::: f(77617.0, 33096.0) = -0.827396059946821 \n\n\nDemonstrate how to solve at least one of the first two problems, or both, and the third if you're feeling particularly jaunty.\n\n\n;See also;\n* Floating-Point Arithmetic Section 1.3.2 Difficult problems.\n\n", "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 :\n===First two tasks===\n"} {"title": "Pentagram", "language": "C", "task": "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.\n\n\n;Task:\nDraw (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.\n\n\n;See also\n* Angle sum of a pentagram\n\n", "solution": "#include\n#include\n#include\n\n#define pi M_PI\n\nint main(){\n\t\n\tchar colourNames[][14] = { \"BLACK\", \"BLUE\", \"GREEN\", \"CYAN\", \"RED\", \"MAGENTA\", \"BROWN\", \"LIGHTGRAY\", \"DARKGRAY\",\n \"LIGHTBLUE\", \"LIGHTGREEN\", \"LIGHTCYAN\", \"LIGHTRED\", \"LIGHTMAGENTA\", \"YELLOW\", \"WHITE\" };\n\t\t\t \n\tint stroke=0,fill=0,back=0,i;\n\t\n\tdouble centerX = 300,centerY = 300,coreSide,armLength,pentaLength;\n\t\n\tprintf(\"Enter core pentagon side length : \");\n\tscanf(\"%lf\",&coreSide);\n\t\n\tprintf(\"Enter pentagram arm length : \");\n\tscanf(\"%lf\",&armLength);\n\t\n\tprintf(\"Available colours are :\\n\");\n\t\n\tfor(i=0;i<16;i++){\n\t\tprintf(\"%d. %s\\t\",i+1,colourNames[i]);\n\t\tif((i+1) % 3 == 0){\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\twhile(stroke==fill && fill==back){\n\t\tprintf(\"\\nEnter three diffrenet options for stroke, fill and background : \");\n\t\tscanf(\"%d%d%d\",&stroke,&fill,&back);\n\t}\n\t\n\tpentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);\n\t\n\tinitwindow(2*centerX,2*centerY,\"Pentagram\");\n\t\t\n\tsetcolor(stroke-1);\n\t\n\tsetfillstyle(SOLID_FILL,back-1);\n\t\n\tbar(0,0,2*centerX,2*centerY);\n\t\n\tfloodfill(centerX,centerY,back-1);\n\t\n\tsetfillstyle(SOLID_FILL,fill-1);\n\n\tfor(i=0;i<5;i++){\n\t\tline(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)));\n\t\tline(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));\n\t\tline(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));\n\t\t\n\t\tfloodfill(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);\n\t}\n\t\n\tfloodfill(centerX,centerY,stroke-1);\n\t\n\tgetch();\n\t\n\tclosegraph();\n}\n"} {"title": "Perfect shuffle", "language": "C", "task": "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:\n\n\n\n::: 7 8 9 J Q K-7 8 9 J Q K-7 J 8 Q 9 K\n\n\n\nWhen 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:\n\n\n\n::::: {| style=\"border-spacing:0.5em 0;border-collapse:separate;margin:0 1em;text-align:right\"\n|-\n| ''original:'' ||\n1\n2\n3\n4\n5\n6\n7\n8\n|-\n| ''after 1st shuffle:'' ||\n1\n5\n2\n6\n3\n7\n4\n8\n|-\n| ''after 2nd shuffle:'' ||\n1\n3\n5\n7\n2\n4\n6\n8\n|-\n| ''after 3rd shuffle:'' ||\n1\n2\n3\n4\n5\n6\n7\n8\n|}\n\n\n'''''The Task'''''\n\n# Write a function that can perform a perfect shuffle on an even-sized list of values.\n# 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.\n#* 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.\n#* Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases.\n'''''Test Cases'''''\n\n::::: {| class=\"wikitable\"\n|-\n! input ''(deck size)'' !! output ''(number of shuffles required)''\n|-\n| 8 || 3\n|-\n| 24 || 11\n|-\n| 52 || 8\n|-\n| 100 || 30\n|-\n| 1020 || 1018\n|-\n| 1024 || 10\n|-\n| 10000 || 300\n|}\n\n", "solution": "/* ===> INCLUDES <============================================================*/\n#include \n#include \n#include \n\n/* ===> CONSTANTS <===========================================================*/\n#define N_DECKS 7\nconst int kDecks[N_DECKS] = { 8, 24, 52, 100, 1020, 1024, 10000 };\n\n/* ===> FUNCTION PROTOTYPES <=================================================*/\nint CreateDeck( int **deck, int nCards );\nvoid InitDeck( int *deck, int nCards );\nint DuplicateDeck( int **dest, const int *orig, int nCards );\nint InitedDeck( int *deck, int nCards );\nint ShuffleDeck( int *deck, int nCards );\nvoid FreeDeck( int **deck );\n\n/* ===> FUNCTION DEFINITIONS <================================================*/\n\nint main() {\n int i, nCards, nShuffles;\n int *deck = NULL;\n\n for( i=0; i\n#include\n\nlong totient(long n){\n\tlong tot = n,i;\n\t\n\tfor(i=2;i*i<=n;i+=2){\n\t\tif(n%i==0){\n\t\t\twhile(n%i==0)\n\t\t\t\tn/=i;\n\t\t\ttot-=tot/i;\n\t\t}\n\t\t\n\t\tif(i==2)\n\t\t\ti=1;\n\t}\n\t\n\tif(n>1)\n\t\ttot-=tot/n;\n\t\n\treturn tot;\n}\n\nlong* perfectTotients(long n){\n\tlong *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot;\n\t\n\tfor(m=1;count\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\t\n\t\tptList = perfectTotients(n);\n\t\t\n\t\tprintf(\"The first %d perfect Totient numbers are : \\n[\",n);\n\t\t\n\t\tfor(i=0;i 1 1\n* 2 -> 1 18\n* 29 -> 4 11\n* 42 -> 5 6\n* 57 -> 8 4\n* 58 -> 8 5\n* 72 -> 6 4\n* 89 -> 9 4\n\n;Details;\n\nThe 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.\n\nYou may take a look at the atomic number repartitions here.\n\nThe atomic number is at least 1, at most 118.\n\n\n;See also: \n* the periodic table\n* This task was an idea from CompSciFact\n* The periodic table in ascii that was used as template\n\n", "solution": "#include \n\nLIB_GADGET_START\n\n/* prototypes */\nGD_VIDEO put_chemical_cell( GD_VIDEO table, MT_CELL * E, DS_ARRAY E_data );\nMT_CELL* load_chem_elements( MT_CELL * E, DS_ARRAY * E_data );\nint select_box_chemical_elem( RDS(MT_CELL, Elements) );\nvoid put_information(RDS( MT_CELL, elem), int i);\n\nMain\n \n GD_VIDEO table;\n /* las dimensiones del terminal son muy importantes \n para desplegar la tabla */\n Resize_terminal(42,135);\n Init_video( &table );\n \n Gpm_Connect conn;\n\n if ( ! Init_mouse(&conn)){\n Msg_red(\"No se puede conectar al servidor del rat\u00f3n\\n\");\n Stop(1);\n } \n Enable_raw_mode();\n Hide_cursor;\n\n /* I declare a multitype array \"Elements\", and load the file that will populate this array. */\n New multitype Elements;\n Elements = load_chem_elements( pSDS(Elements) );\n Throw( load_fail );\n \n /* I create a \"Button\" object with which the execution will end. */\n New objects Btn_exit;\n Btn_exit = New_object_mouse( SMD(&Btn_exit), BUTTOM, \" Terminar \", 6,44, 15, 0);\n\n /* Fill the space on the screen with the table of chemical elements. */\n table = put_chemical_cell( table, SDS(Elements) );\n\n /* I print the screen and place the mouse object. */\n Refresh(table);\n Put object Btn_exit;\n \n /* I wait for a mouse event. */\n int c;\n Waiting_some_clic(c)\n {\n if( select_box_chemical_elem(SDS(Elements)) ){\n Waiting_some_clic(c) break;\n }\n if (Object_mouse( Btn_exit)) break;\n \n Refresh(table);\n Put object Btn_exit;\n }\n\n Free object Btn_exit;\n Free multitype Elements;\n \n Exception( load_fail ){\n Msg_red(\"No es un archivo matriciable\");\n }\n\n Free video table;\n Disable_raw_mode();\n Close_mouse();\n Show_cursor;\n \n At SIZE_TERM_ROWS,0;\n Prnl;\nEnd\n\nvoid put_information(RDS(MT_CELL, elem), int i)\n{\n At 2,19;\n Box_solid(11,64,67,17);\n Color(15,17);\n At 4,22; Print \"Elemento (%s) = %s\", (char*)$s-elem[i,5],(char*)$s-elem[i,6];\n if (Cell_type(elem,i,7) == double_TYPE ){\n At 5,22; Print \"Peso at\u00f3mico = %f\", $d-elem[i,7];\n }else{\n At 5,22; Print \"Peso at\u00f3mico = (%ld)\", $l-elem[i,7];\n }\n At 6,22; Print \"Posici\u00f3n = (%ld, %ld)\",$l-elem[i,0]+ ($l-elem[i,0]>=8 ? 0:1),$l-elem[i,1]+1;\n At 8,22; Print \"1\u00aa energ\u00eda de\";\n if (Cell_type(elem,i,12) == double_TYPE ){\n At 9,22; Print \"ionizaci\u00f3n (kJ/mol) = %.*f\",2,$d-elem[i,12];\n }else{\n At 9,22; Print \"ionizaci\u00f3n (kJ/mol) = ---\";\n }\n if (Cell_type(elem,i,13) == double_TYPE ){\n At 10,22; Print \"Electronegatividad = %.*f\",2,$d-elem[i,13];\n }else{\n At 10,22; Print \"Electronegatividad = ---\";\n }\n At 4,56; Print \"Conf. electr\u00f3nica:\";\n At 5,56; Print \" %s\", (char*)$s-elem[i,14];\n At 7,56; Print \"Estados de oxidaci\u00f3n:\";\n if ( Cell_type(elem,i,15) == string_TYPE ){\n At 8,56; Print \" %s\", (char*)$s-elem[i,15];\n }else{\n /* Strangely, when the file loader detects a \"+n\", it treats it as a string,\n but when it detects a \"-n\", it treats it as a \"long\". \n I must review that. */\n At 8,56; Print \" %ld\", $l-elem[i,15];\n }\n At 10,56; Print \"N\u00famero At\u00f3mico: %ld\",$l-elem[i,4];\n Reset_color;\n}\n\nint select_box_chemical_elem( RDS(MT_CELL, elem) )\n{\n int i;\n Iterator up i [0:1:Rows(elem)]{\n if ( Is_range_box( $l-elem[i,8], $l-elem[i,9], $l-elem[i,10], $l-elem[i,11]) ){\n Gotoxy( $l-elem[i,8], $l-elem[i,9] );\n Color_fore( 15 ); Color_back( 0 );\n Box( 4,5, DOUB_ALL );\n\n Gotoxy( $l-elem[i,8]+1, $l-elem[i,9]+2); Print \"%ld\",$l-elem[i,4];\n Gotoxy( $l-elem[i,8]+2, $l-elem[i,9]+2); Print \"%s\",(char*)$s-elem[i,5];\n Flush_out;\n Reset_color;\n put_information(SDS(elem),i);\n return 1;\n }\n }\n return 0;\n}\n\nGD_VIDEO put_chemical_cell(GD_VIDEO table, MT_CELL * elem, DS_ARRAY elem_data)\n{\n int i;\n \n /* put each cell */\n Iterator up i [0:1:Rows(elem)]{\n long rx = 2+($l-elem[i,0]*4);\n long cx = 3+($l-elem[i,1]*7);\n long offr = rx+3;\n long offc = cx+6;\n\n Gotoxy(table, rx, cx);\n\n Color_fore(table, $l-elem[i,2]);\n Color_back(table,$l-elem[i,3]);\n\n Box(table, 4,5, SING_ALL );\n\n char Atnum[50], Elem[50];\n sprintf(Atnum,\"\\x1b[3m%ld\\x1b[23m\",$l-elem[i,4]);\n sprintf(Elem, \"\\x1b[1m%s\\x1b[22m\",(char*)$s-elem[i,5]);\n\n Outvid(table,rx+1, cx+2, Atnum);\n Outvid(table,rx+2, cx+2, Elem);\n\n Reset_text(table);\n /* Update positions of each cell to be detected by the mouse. */\n $l-elem[i,8] = rx;\n $l-elem[i,9] = cx;\n $l-elem[i,10] = offr;\n $l-elem[i,11] = offc;\n \n }\n /* put rows and cols */\n Iterator up i [ 1: 1: 19 ]{\n Gotoxy(table, 31, 5+(i-1)*7);\n char num[5]; sprintf( num, \"%d\",i );\n Outvid(table, num );\n }\n Iterator up i [ 1: 1: 8 ]{\n Gotoxy(table, 3+(i-1)*4, 130);\n char num[5]; sprintf( num, \"%d\",i );\n Outvid(table, num );\n }\n Outvid( table, 35,116, \"8\");\n Outvid( table, 39,116, \"9\");\n \n /* others */\n Color_fore(table, 15);\n Color_back(table, 0);\n Outvid(table,35,2,\"Lant\u00e1nidos ->\");\n Outvid(table,39,2,\"Act\u00ednidos ->\");\n Reset_text(table);\n return table;\n}\n\nMT_CELL* load_chem_elements( MT_CELL * E, DS_ARRAY * E_data )\n{\n F_STAT dataFile = Stat_file(\"chem_table.txt\");\n if( dataFile.is_matrix ){\n /* \n Set the ranges to read from the file.\n You can choose the portion of the file that you want to upload.\n */\n Range ptr E [0:1:dataFile.total_lines-1, 0:1:dataFile.max_tokens_per_line-1];\n E = Load_matrix_mt( SDS(E), \"chem_table.txt\", dataFile, DET_LONG);\n }else{\n Is_ok=0;\n }\n return E;\n}\n\n"} {"title": "Perlin noise", "language": "C", "task": "The '''computer graphics, most notably to procedurally generate textures or heightmaps. \n\nThe 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.\n\nEither 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.\n\n\n''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.''\n\n", "solution": "#include\n#include\n#include\n\nint p[512];\n\ndouble fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }\ndouble lerp(double t, double a, double b) { return a + t * (b - a); }\ndouble grad(int hash, double x, double y, double z) {\n int h = hash & 15; \n double u = h<8 ? x : y, \n v = h<4 ? y : h==12||h==14 ? x : z;\n return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);\n }\n \ndouble noise(double x, double y, double z) {\n int X = (int)floor(x) & 255, \n Y = (int)floor(y) & 255, \n Z = (int)floor(z) & 255;\n x -= floor(x); \n y -= floor(y); \n z -= floor(z);\n double u = fade(x), \n v = fade(y), \n w = fade(z);\n int A = p[X ]+Y, AA = p[A]+Z, AB = p[A+1]+Z, \n B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z; \n \n return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ), \n grad(p[BA ], x-1, y , z )),\n lerp(u, grad(p[AB ], x , y-1, z ), \n grad(p[BB ], x-1, y-1, z ))),\n lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ), \n grad(p[BA+1], x-1, y , z-1 )), \n lerp(u, grad(p[AB+1], x , y-1, z-1 ),\n grad(p[BB+1], x-1, y-1, z-1 ))));\n }\n\nvoid loadPermutation(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tint permutation[256],i;\n\t\n\tfor(i=0;i<256;i++)\n\t\tfscanf(fp,\"%d\",&permutation[i]);\n\t\n\tfclose(fp);\n\t\n\tfor (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i];\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=5)\n\t\tprintf(\"Usage : %s \");\n\telse{\n\t\tloadPermutation(argV[1]);\n\t\tprintf(\"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)));\n\t}\n\t\n\treturn 0;\n}\n"} {"title": "Permutations/Derangements", "language": "C", "task": "A derangement is a permutation of the order of distinct items in which ''no item appears in its original place''.\n\nFor example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1).\n\nThe number of derangements of ''n'' distinct items is known as the subfactorial of ''n'', sometimes written as !''n''. \nThere are various ways to calculate !''n''.\n\n\n;Task:\n# Create a named function/method/subroutine/... to generate derangements of the integers ''0..n-1'', (or ''1..n'' if you prefer). \n# Generate ''and show'' all the derangements of 4 integers using the above routine.\n# Create a function that calculates the subfactorial of ''n'', !''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.\n\n\n;Optional stretch goal:\n* Calculate !''20'' \n\n\n;Related tasks:\n* [[Anagrams/Deranged anagrams]]\n* [[Best shuffle]]\n* [[Left_factorials]]\n\n\n\n", "solution": "#include \ntypedef unsigned long long LONG;\n\nLONG deranged(int depth, int len, int *d, int show)\n{\n int i;\n char tmp;\n LONG count = 0;\n\n if (depth == len) {\n if (show) {\n for (i = 0; i < len; i++) putchar(d[i] + 'a');\n putchar('\\n');\n }\n return 1;\n }\n for (i = len - 1; i >= depth; i--) {\n if (i == d[depth]) continue;\n\n tmp = d[i]; d[i] = d[depth]; d[depth] = tmp;\n count += deranged(depth + 1, len, d, show);\n tmp = d[i]; d[i] = d[depth]; d[depth] = tmp;\n }\n return count;\n}\n\nLONG gen_n(int n, int show)\n{\n LONG i;\n int a[1024]; /* 1024 ought to be big enough for anybody */\n\n for (i = 0; i < n; i++) a[i] = i;\n return deranged(0, n, a, show);\n}\n\nLONG sub_fact(int n)\n{\n return n < 2 ? 1 - n : (sub_fact(n - 1) + sub_fact(n - 2)) * (n - 1);\n}\n\nint main()\n{\n int i;\n\n printf(\"Deranged Four:\\n\");\n gen_n(4, 1);\n\n printf(\"\\nCompare list vs calc:\\n\");\n for (i = 0; i < 10; i++)\n printf(\"%d:\\t%llu\\t%llu\\n\", i, gen_n(i, 0), sub_fact(i));\n\n printf(\"\\nfurther calc:\\n\");\n for (i = 10; i <= 20; i++)\n printf(\"%d: %llu\\n\", i, sub_fact(i));\n\n return 0;\n}"} {"title": "Permutations/Rank of a permutation", "language": "C", "task": "A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items. \nFor our purposes the ranking will assign integers 0 .. (n! - 1) to an ordering of all the permutations of the integers 0 .. (n - 1).\n\nFor example, the permutations of the digits zero to 3 arranged lexicographically have the following rank:\n\n PERMUTATION RANK\n (0, 1, 2, 3) -> 0\n (0, 1, 3, 2) -> 1\n (0, 2, 1, 3) -> 2\n (0, 2, 3, 1) -> 3\n (0, 3, 1, 2) -> 4\n (0, 3, 2, 1) -> 5\n (1, 0, 2, 3) -> 6\n (1, 0, 3, 2) -> 7\n (1, 2, 0, 3) -> 8\n (1, 2, 3, 0) -> 9\n (1, 3, 0, 2) -> 10\n (1, 3, 2, 0) -> 11\n (2, 0, 1, 3) -> 12\n (2, 0, 3, 1) -> 13\n (2, 1, 0, 3) -> 14\n (2, 1, 3, 0) -> 15\n (2, 3, 0, 1) -> 16\n (2, 3, 1, 0) -> 17\n (3, 0, 1, 2) -> 18\n (3, 0, 2, 1) -> 19\n (3, 1, 0, 2) -> 20\n (3, 1, 2, 0) -> 21\n (3, 2, 0, 1) -> 22\n (3, 2, 1, 0) -> 23\n\nAlgorithms 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).\n\nOne 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.\n\nA question on the Stack Overflow site asked how to generate one million random and indivudual permutations of 144 items.\n\n\n;Task:\n# Create a function to generate a permutation from a rank.\n# Create the inverse function that given the permutation generates its rank.\n# Show that for n=3 the two functions are indeed inverses of each other.\n# Compute and show here 4 random, individual, samples of permutations of 12 objects.\n\n\n;Stretch goal:\n* State how reasonable it would be to use your program to address the limits of the Stack Overflow question.\n\n\n;References:\n# Ranking and Unranking Permutations in Linear Time by Myrvold & Ruskey. (Also available via Google here).\n# Ranks on the DevData site.\n# Another answer on Stack Overflow to a different question that explains its algorithm in detail.\n\n;Related tasks:\n#[[Factorial_base_numbers_indexing_permutations_of_a_collection]]\n\n", "solution": "#include \n#include \n\n#define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0)\n\nvoid _mr_unrank1(int rank, int n, int *vec) {\n int t, q, r;\n if (n < 1) return;\n\n q = rank / n;\n r = rank % n;\n SWAP(vec[r], vec[n-1]);\n _mr_unrank1(q, n-1, vec);\n}\n\nint _mr_rank1(int n, int *vec, int *inv) {\n int s, t;\n if (n < 2) return 0;\n\n s = vec[n-1];\n SWAP(vec[n-1], vec[inv[n-1]]);\n SWAP(inv[s], inv[n-1]);\n return s + n * _mr_rank1(n-1, vec, inv);\n}\n\n/* Fill the integer array (of size ) with the\n * permutation at rank .\n */\nvoid get_permutation(int rank, int n, int *vec) {\n int i;\n for (i = 0; i < n; ++i) vec[i] = i;\n _mr_unrank1(rank, n, vec);\n}\n\n/* Return the rank of the current permutation of array \n * (of size ).\n */\nint get_rank(int n, int *vec) {\n int i, r, *v, *inv;\n\n v = malloc(n * sizeof(int));\n inv = malloc(n * sizeof(int));\n\n for (i = 0; i < n; ++i) {\n v[i] = vec[i];\n inv[vec[i]] = i;\n }\n r = _mr_rank1(n, v, inv);\n free(inv);\n free(v);\n return r;\n}\n\nint main(int argc, char *argv[]) {\n int i, r, tv[4];\n\n for (r = 0; r < 24; ++r) {\n printf(\"%3d: \", r);\n get_permutation(r, 4, tv);\n\n for (i = 0; i < 4; ++i) {\n if (0 == i) printf(\"[ \");\n else printf(\", \");\n printf(\"%d\", tv[i]);\n }\n printf(\" ] = %d\\n\", get_rank(4, tv));\n }\n}\n"} {"title": "Permutations by swapping", "language": "C", "task": "Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. \n\nAlso 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. \n\nShow the permutations and signs of three items, in order of generation ''here''.\n\nSuch data are of use in generating the determinant of a square matrix and any functions created should bear this in mind.\n\nNote: The Steinhaus-Johnson-Trotter algorithm generates successive permutations where ''adjacent'' items are swapped, but from this discussion adjacency is not a requirement.\n\n\n;References:\n* Steinhaus-Johnson-Trotter algorithm\n* Johnson-Trotter Algorithm Listing All Permutations\n* Heap's algorithm\n* Tintinnalogia\n\n\n;Related tasks:\n* [[Matrix arithmetic]\n* [[Gray code]]\n\n", "solution": "#include\n#include\n#include\n\nint flag = 1;\n\nvoid heapPermute(int n, int arr[],int arrLen){\n\tint temp;\n\tint i;\n\t\n\tif(n==1){\n\t\tprintf(\"\\n[\");\n\t\t\n\t\tfor(i=0;i\",argV[0]);\n\telse{\n\t\twhile(argV[1][i]!=00){\n\t\t\tif(argV[1][i++]==',')\n\t\t\t\tcount++;\n\t\t}\n\t\t\n\t\tarr = (int*)malloc(count*sizeof(int));\n\t\t\n\t\ti = 0;\n\t\t\n\t\ttoken = strtok(argV[1],\",\");\n\t\t\n\t\twhile(token!=NULL){\n\t\t\tarr[i++] = atoi(token);\n\t\t\ttoken = strtok(NULL,\",\");\n\t\t}\n\t\t\n\t\theapPermute(i,arr,count);\n\t}\n\t\t\n\treturn 0;\n}\n"} {"title": "Phrase reversals", "language": "C", "task": "Given a string of space separated words containing the following phrase:\n rosetta code phrase reversal\n\n:# Reverse the characters of the string.\n:# Reverse the characters of each individual word in the string, maintaining original word order within the string.\n:# Reverse the order of each word of the string, maintaining the order of characters in each word.\n\nShow your output here.\n \n\n\n", "solution": "#include \n#include \n\n/* The functions used are destructive, so after each call the string needs\n * to be copied over again. One could easily allocate new strings as\n * required, but this way allows the caller to manage memory themselves */\n\nchar* reverse_section(char *s, size_t length)\n{\n if (length == 0) return s;\n\n size_t i; char temp;\n for (i = 0; i < length / 2 + 1; ++i)\n temp = s[i], s[i] = s[length - i], s[length - i] = temp;\n return s;\n}\n\nchar* reverse_words_in_order(char *s, char delim)\n{\n if (!strlen(s)) return s;\n\n size_t i, j;\n for (i = 0; i < strlen(s) - 1; ++i) {\n for (j = 0; s[i + j] != 0 && s[i + j] != delim; ++j)\n ;\n reverse_section(s + i, j - 1);\n s += j;\n }\n return s;\n}\n\nchar* reverse_string(char *s)\n{\n return strlen(s) ? reverse_section(s, strlen(s) - 1) : s;\n}\n\nchar* reverse_order_of_words(char *s, char delim)\n{\n reverse_string(s);\n reverse_words_in_order(s, delim);\n return s;\n}\n\nint main(void)\n{\n char str[] = \"rosetta code phrase reversal\";\n size_t lenstr = sizeof(str) / sizeof(str[0]);\n char scopy[lenstr];\n char delim = ' ';\n\n /* Original String */\n printf(\"Original: \\\"%s\\\"\\n\", str);\n\n /* Reversed string */\n strncpy(scopy, str, lenstr);\n reverse_string(scopy);\n printf(\"Reversed: \\\"%s\\\"\\n\", scopy);\n\n /* Reversed words in string */\n strncpy(scopy, str, lenstr);\n reverse_words_in_order(scopy, delim);\n printf(\"Reversed words: \\\"%s\\\"\\n\", scopy);\n\n /* Reversed order of words in string */\n strncpy(scopy, str, lenstr);\n reverse_order_of_words(scopy, delim);\n printf(\"Reversed order: \\\"%s\\\"\\n\", scopy);\n\n return 0;\n}\n"} {"title": "Pig the dice game", "language": "C", "task": "The game of Pig is a multiplayer game played with a single six-sided die. The\nobject of the game is to reach '''100''' points or more. \nPlay is taken in turns. On each person's turn that person has the option of either:\n\n:# '''Rolling the dice''': where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of '''1''' loses the player's total points ''for that turn'' and their turn finishes with play passing to the next player.\n:# '''Holding''': the player's score for that round is added to their total and becomes safe from the effects of throwing a '''1''' (one). The player's turn finishes with play passing to the next player.\n\n\n;Task:\nCreate a program to score for, and simulate dice throws for, a two-person game. \n\n\n;Related task:\n* [[Pig the dice game/Player]]\n\n", "solution": "#include \n#include \n#include \n\n\nconst int NUM_PLAYERS = 2;\nconst int MAX_POINTS = 100;\n\n\n//General functions\nint randrange(int min, int max){\n return (rand() % (max - min + 1)) + min;\n}\n\n\n//Game functions\nvoid ResetScores(int *scores){\n for(int i = 0; i < NUM_PLAYERS; i++){\n scores[i] = 0;\n }\n}\n\n\nvoid Play(int *scores){\n int scoredPoints = 0;\n int diceResult;\n int choice;\n\n for(int i = 0; i < NUM_PLAYERS; i++){\n while(1){\n printf(\"Player %d - You have %d total points and %d points this turn \\nWhat do you want to do (1)roll or (2)hold: \", i + 1, scores[i], scoredPoints);\n scanf(\"%d\", &choice);\n\n if(choice == 1){\n diceResult = randrange(1, 6);\n printf(\"\\nYou rolled a %d\\n\", diceResult);\n\n if(diceResult != 1){\n scoredPoints += diceResult;\n }\n else{\n printf(\"You loose all your points from this turn\\n\\n\");\n scoredPoints = 0;\n break;\n }\n }\n else if(choice == 2){\n scores[i] += scoredPoints;\n printf(\"\\nYou holded, you have %d points\\n\\n\", scores[i]);\n\n break;\n }\n }\n\n scoredPoints = 0;\n CheckForWin(scores[i], i + 1);\n\n }\n}\n\n\nvoid CheckForWin(int playerScore, int playerNum){\n if(playerScore >= MAX_POINTS){\n printf(\"\\n\\nCONGRATULATIONS PLAYER %d, YOU WIN\\n\\n!\", playerNum);\n\n exit(EXIT_SUCCESS);\n }\n}\n\n\nint main()\n{\n srand(time(0));\n\n int scores[NUM_PLAYERS];\n ResetScores(scores);\n\n while(1){\n Play(scores);\n }\n\n return 0;\n}\n\n"} {"title": "Plasma effect", "language": "C", "task": "The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.\n\n\n;Task\nCreate a plasma effect.\n\n\n;See also\n* Computer Graphics Tutorial (lodev.org)\n* Plasma (bidouille.org)\n\n", "solution": "#include\n#include\n#include\n#include\n\n#define pi M_PI\n\nvoid plasmaScreen(int width,int height){\n\t\n\tint x,y,sec;\n\tdouble dx,dy,dv;\n\ttime_t t;\n\t\n\tinitwindow(width,height,\"WinBGIm Plasma\");\n\t\n\twhile(1){\n\t\ttime(&t);\n\t\tsec = (localtime(&t))->tm_sec;\n\t\t\n\tfor(x=0;x\",argV[0]);\n\telse{\n\t\tplasmaScreen(atoi(argV[1]),atoi(argV[2]));\n\t}\n\treturn 0;\n}\n"} {"title": "Plot coordinate pairs", "language": "C", "task": "Plot a function represented as x, y numerical arrays.\n\nPost the resulting image for the following input arrays (taken from Python's Example section on ''Time a function''):\n x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};\n\nThis task is intended as a subtask for [[Measure relative performance of sorting algorithms implementations]].\n\n", "solution": "We could use the ''suite'' provided by [[:Category:Raster graphics operations|Raster graphics operations]], but those functions lack a facility to draw text.\n\n"} {"title": "Polyspiral", "language": "C", "task": "A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. \n\n\n;Task\nAnimate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied.\n\nIf animation is not practical in your programming environment, you may show a single frame instead.\n\n\n;Pseudo code\n\n set incr to 0.0\n\n // animation loop\n WHILE true \n\n incr = (incr + 0.05) MOD 360\n x = width / 2\n y = height / 2\n length = 5\n angle = incr\n\n // spiral loop\n FOR 1 TO 150\n drawline\n change direction by angle\n length = length + 3\n angle = (angle + incr) MOD 360\n ENDFOR\n \n\n\n", "solution": "#include\n#include\n\n#define factor M_PI/180\n#define LAG 1000\n\nvoid polySpiral(int windowWidth,int\twindowHeight){\n\tint incr = 0, angle, i, length;\n\tdouble x,y,x1,y1;\n\t\n\twhile(1){\n\t\tincr = (incr + 5)%360; \n\t\t\n\t\tx = windowWidth/2;\n\t\ty = windowHeight/2;\n\t\t\n\t\tlength = 5;\n\t\tangle = incr;\n\t\t\n\t\tfor(i=1;i<=150;i++){\n\t\t\tx1 = x + length*cos(factor*angle);\n\t\t\ty1 = y + length*sin(factor*angle);\n\t\t\tline(x,y,x1,y1);\n\t\t\t\n\t\t\tlength += 3;\n\t\t\t\n\t\t\tangle = (angle + incr)%360;\n\t\t\t\n\t\t\tx = x1;\n\t\t\ty = y1;\n\t\t}\n\t\tdelay(LAG);\n\t\tcleardevice();\t\n\t}\n}\t\n\nint main()\n{\n\tinitwindow(500,500,\"Polyspiral\");\n\t\n\tpolySpiral(500,500);\n\t\n\tclosegraph();\n\t\n\treturn 0;\n}\n"} {"title": "Pragmatic directives", "language": "C", "task": "Pragmatic directives cause the language to operate in a specific manner, allowing support for operational variances within the program code (possibly by the loading of specific or alternative modules).\n\n\n;Task:\nList any pragmatic directives supported by the language, and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.\n\n", "solution": "/*Almost every C program has the below line, \nthe #include preprocessor directive is used to \ninstruct the compiler which files to load before compiling the program.\n\nAll preprocessor commands begin with #\n*/\n#include \n\n/*The #define preprocessor directive is often used to create abbreviations for code segments*/\n#define Hi printf(\"Hi There.\");\n\n/*It can be used, or misused, for rather innovative uses*/\n\n#define start int main(){\n#define end return 0;}\n\nstart\n\nHi\n\n/*And here's the nice part, want your compiler to talk to you ? \nJust use the #warning pragma if you are using a C99 compliant compiler\nlike GCC*/\n#warning \"Don't you have anything better to do ?\"\n\n#ifdef __unix__\n#warning \"What are you doing still working on Unix ?\"\nprintf(\"\\nThis is an Unix system.\");\n#elif _WIN32\n#warning \"You couldn't afford a 64 bit ?\"\nprintf(\"\\nThis is a 32 bit Windows system.\");\n#elif _WIN64\n#warning \"You couldn't afford an Apple ?\"\nprintf(\"\\nThis is a 64 bit Windows system.\");\n#endif\n\nend\n\n/*Enlightened ?*/\n"} {"title": "Prime triangle", "language": "C", "task": "You will require a function f which when given an integer S will return a list of the arrangements of the integers 1 to S such that g1=1 gS=S and generally for n=1 to n=S-1 gn+gn+1 is prime. S=1 is undefined. For S=2 to S=20 print f(S) to form a triangle. Then again for S=2 to S=20 print the number of possible arrangements of 1 to S meeting these requirements.\n\n\n;See also\n:* OEIS:A036440\n\n\n", "solution": "#include \n#include \n#include \n#include \n\nbool is_prime(unsigned int n) {\n assert(n < 64);\n static bool isprime[] = {0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0,\n 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1,\n 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1,\n 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0};\n return isprime[n];\n}\n\nvoid swap(unsigned int* a, size_t i, size_t j) {\n unsigned int tmp = a[i];\n a[i] = a[j];\n a[j] = tmp;\n}\n\nbool prime_triangle_row(unsigned int* a, size_t length) {\n if (length == 2)\n return is_prime(a[0] + a[1]);\n for (size_t i = 1; i + 1 < length; i += 2) {\n if (is_prime(a[0] + a[i])) {\n swap(a, i, 1);\n if (prime_triangle_row(a + 1, length - 1))\n return true;\n swap(a, i, 1);\n }\n }\n return false;\n}\n\nint prime_triangle_count(unsigned int* a, size_t length) {\n int count = 0;\n if (length == 2) {\n if (is_prime(a[0] + a[1]))\n ++count;\n } else {\n for (size_t i = 1; i + 1 < length; i += 2) {\n if (is_prime(a[0] + a[i])) {\n swap(a, i, 1);\n count += prime_triangle_count(a + 1, length - 1);\n swap(a, i, 1);\n }\n }\n }\n return count;\n}\n\nvoid print(unsigned int* a, size_t length) {\n if (length == 0)\n return;\n printf(\"%2u\", a[0]);\n for (size_t i = 1; i < length; ++i)\n printf(\" %2u\", a[i]);\n printf(\"\\n\");\n}\n\nint main() {\n clock_t start = clock();\n for (unsigned int n = 2; n < 21; ++n) {\n unsigned int a[n];\n for (unsigned int i = 0; i < n; ++i)\n a[i] = i + 1;\n if (prime_triangle_row(a, n))\n print(a, n);\n }\n printf(\"\\n\");\n for (unsigned int n = 2; n < 21; ++n) {\n unsigned int a[n];\n for (unsigned int i = 0; i < n; ++i)\n a[i] = i + 1;\n if (n > 2)\n printf(\" \");\n printf(\"%d\", prime_triangle_count(a, n));\n }\n printf(\"\\n\");\n clock_t end = clock();\n double duration = (end - start + 0.0) / CLOCKS_PER_SEC;\n printf(\"\\nElapsed time: %f seconds\\n\", duration);\n return 0;\n}"} {"title": "Priority queue", "language": "C", "task": "A queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order.\n\n\n;Task:\nCreate a priority queue. The queue must support at least two operations:\n:# Insertion. An element is added to the queue with a priority (a numeric value).\n:# Top item removal. Deletes the element or one of the elements with the current top priority and return it.\n\n\nOptionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.\n\n\nTo test your implementation, insert a number of elements into the queue, each with some random priority. \n\nThen dequeue them sequentially; now the elements should be sorted by priority. \n\nYou can use the following task/priority items as input data:\n '''Priority''' '''Task'''\n ---------- ----------------\n 3 Clear drains\n 4 Feed cat\n 5 Make tea\n 1 Solve RC tasks\n 2 Tax return\n\n\nThe implementation should try to be efficient. A typical implementation has '''O(log n)''' insertion and extraction time, where '''n''' is the number of items in the queue. \n\nYou may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.\n\n", "solution": "#include \n#include \n\ntypedef struct {\n int priority;\n char *data;\n} node_t;\n\ntypedef struct {\n node_t *nodes;\n int len;\n int size;\n} heap_t;\n\nvoid push (heap_t *h, int priority, char *data) {\n if (h->len + 1 >= h->size) {\n h->size = h->size ? h->size * 2 : 4;\n h->nodes = (node_t *)realloc(h->nodes, h->size * sizeof (node_t));\n }\n int i = h->len + 1;\n int j = i / 2;\n while (i > 1 && h->nodes[j].priority > priority) {\n h->nodes[i] = h->nodes[j];\n i = j;\n j = j / 2;\n }\n h->nodes[i].priority = priority;\n h->nodes[i].data = data;\n h->len++;\n}\n\nchar *pop (heap_t *h) {\n int i, j, k;\n if (!h->len) {\n return NULL;\n }\n char *data = h->nodes[1].data;\n \n h->nodes[1] = h->nodes[h->len];\n \n h->len--;\n \n i = 1;\n while (i!=h->len+1) {\n k = h->len+1;\n j = 2 * i;\n if (j <= h->len && h->nodes[j].priority < h->nodes[k].priority) {\n k = j;\n }\n if (j + 1 <= h->len && h->nodes[j + 1].priority < h->nodes[k].priority) {\n k = j + 1;\n }\n h->nodes[i] = h->nodes[k];\n i = k;\n }\n return data;\n}\n\nint main () {\n heap_t *h = (heap_t *)calloc(1, sizeof (heap_t));\n push(h, 3, \"Clear drains\");\n push(h, 4, \"Feed cat\");\n push(h, 5, \"Make tea\");\n push(h, 1, \"Solve RC tasks\");\n push(h, 2, \"Tax return\");\n int i;\n for (i = 0; i < 5; i++) {\n printf(\"%s\\n\", pop(h));\n }\n return 0;\n}\n"} {"title": "Pseudo-random numbers/Combined recursive generator MRG32k3a", "language": "C", "task": "MRG32k3a Combined recursive generator (pseudo-code):\n\n /* Constants */\n /* First generator */\n a1 = [0, 1403580, -810728]\n m1 = 2**32 - 209\n /* Second Generator */\n a2 = [527612, 0, -1370589]\n m2 = 2**32 - 22853\n \n d = m1 + 1\n \n class MRG32k3a\n x1 = [0, 0, 0] /* list of three last values of gen #1 */\n x2 = [0, 0, 0] /* list of three last values of gen #2 */\n \n method seed(u64 seed_state)\n assert seed_state in range >0 and < d \n x1 = [seed_state, 0, 0]\n x2 = [seed_state, 0, 0]\n end method\n \n method next_int()\n x1i = (a1[0]*x1[0] + a1[1]*x1[1] + a1[2]*x1[2]) mod m1\n x2i = (a2[0]*x2[0] + a2[1]*x2[1] + a2[2]*x2[2]) mod m2\n x1 = [x1i, x1[0], x1[1]] /* Keep last three */\n x2 = [x2i, x2[0], x2[1]] /* Keep last three */\n z = (x1i - x2i) % m1\n answer = (z + 1)\n \n return answer\n end method\n \n method next_float():\n return float next_int() / d\n end method\n \n end class\n \n:MRG32k3a Use:\n random_gen = instance MRG32k3a\n random_gen.seed(1234567)\n print(random_gen.next_int()) /* 1459213977 */\n print(random_gen.next_int()) /* 2827710106 */\n print(random_gen.next_int()) /* 4245671317 */\n print(random_gen.next_int()) /* 3877608661 */\n print(random_gen.next_int()) /* 2595287583 */\n \n \n;Task\n\n* Generate a class/set of functions that generates pseudo-random\nnumbers as shown above.\n\n* Show that the first five integers generated with the seed `1234567`\nare as shown above \n\n* Show that for an initial seed of '987654321' the counts of 100_000\nrepetitions of\n\n floor(random_gen.next_float() * 5)\n\nIs as follows:\n \n 0: 20002, 1: 20060, 2: 19948, 3: 20059, 4: 19931\n\n* Show your output here, on this page.\n\n\n", "solution": "#include \n#include \n#include \n\nint64_t mod(int64_t x, int64_t y) {\n int64_t m = x % y;\n if (m < 0) {\n if (y < 0) {\n return m - y;\n } else {\n return m + y;\n }\n }\n return m;\n}\n\n// Constants\n// First generator\nconst static int64_t a1[3] = { 0, 1403580, -810728 };\nconst static int64_t m1 = (1LL << 32) - 209;\n// Second generator\nconst static int64_t a2[3] = { 527612, 0, -1370589 };\nconst static int64_t m2 = (1LL << 32) - 22853;\n\nconst static int64_t d = (1LL << 32) - 209 + 1; // m1 + 1\n\n// the last three values of the first generator\nstatic int64_t x1[3];\n// the last three values of the second generator\nstatic int64_t x2[3];\n\nvoid seed(int64_t seed_state) {\n x1[0] = seed_state;\n x1[1] = 0;\n x1[2] = 0;\n\n x2[0] = seed_state;\n x2[1] = 0;\n x2[2] = 0;\n}\n\nint64_t next_int() {\n int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1);\n int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2);\n int64_t z = mod(x1i - x2i, m1);\n\n // keep last three values of the first generator\n x1[2] = x1[1];\n x1[1] = x1[0];\n x1[0] = x1i;\n\n // keep last three values of the second generator\n x2[2] = x2[1];\n x2[1] = x2[0];\n x2[0] = x2i;\n\n return z + 1;\n}\n\ndouble next_float() {\n return (double)next_int() / d;\n}\n\nint main() {\n int counts[5] = { 0, 0, 0, 0, 0 };\n int i;\n\n seed(1234567);\n printf(\"%lld\\n\", next_int());\n printf(\"%lld\\n\", next_int());\n printf(\"%lld\\n\", next_int());\n printf(\"%lld\\n\", next_int());\n printf(\"%lld\\n\", next_int());\n printf(\"\\n\");\n\n seed(987654321);\n for (i = 0; i < 100000; i++) {\n int64_t value = floor(next_float() * 5);\n counts[value]++;\n }\n for (i = 0; i < 5; i++) {\n printf(\"%d: %d\\n\", i, counts[i]);\n }\n\n return 0;\n}"} {"title": "Pseudo-random numbers/Middle-square method", "language": "C", "task": "{{Wikipedia|Middle-square method|en}}\n; The Method:\nTo generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number in the sequence and returned as the result. This process is then repeated to generate more numbers. \n; Pseudo code:\n\nvar seed = 675248\nfunction random()\n var s = str(seed * seed) 'str: turn a number into string\n do while not len(s) = 12\n s = \"0\" + s 'add zeroes before the string\n end do\n seed = val(mid(s, 4, 6)) 'mid: string variable, start, length\n 'val: turn a string into number\n return seed\nend function\n\n; Middle-square method use:\n\nfor i = 1 to 5\n print random()\nend for\n\n;Task:\n\n* Generate a class/set of functions that generates pseudo-random\nnumbers (6 digits) as shown above.\n\n* Show the first five integers generated with the seed 675248 as shown above.\n\n* Show your output here, on this page.\n\n", "solution": "#include\nlong long seed;\nlong long random(){\n seed = seed * seed / 1000 % 1000000;\n return seed;\n}\nint main(){\n seed = 675248;\n for(int i=1;i<=5;i++)\n printf(\"%lld\\n\",random());\n return 0;\n}"} {"title": "Pseudo-random numbers/Xorshift star", "language": "C", "task": "Some definitions to help in the explanation:\n\n:Floor operation\n::https://en.wikipedia.org/wiki/Floor_and_ceiling_functions\n::Greatest integer less than or equal to a real number.\n\n:Bitwise Logical shift operators (c-inspired)\n::https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts\n::Binary bits of value shifted left or right, with zero bits shifted in where appropriate. \n::Examples are shown for 8 bit binary numbers; most significant bit to the left.\n \n:: '''<<''' Logical shift left by given number of bits.\n:::E.g Binary 00110101 '''<<''' 2 == Binary 11010100\n \n:: '''>>''' Logical shift right by given number of bits.\n:::E.g Binary 00110101 '''>>''' 2 == Binary 00001101\n \n:'''^''' Bitwise exclusive-or operator\n::https://en.wikipedia.org/wiki/Exclusive_or\n::Bitwise comparison for if bits differ\n:::E.g Binary 00110101 '''^''' Binary 00110011 == Binary 00000110\n \n;Xorshift_star Generator (pseudo-code):\n\n /* Let u64 denote an unsigned 64 bit integer type. */\n /* Let u32 denote an unsigned 32 bit integer type. */\n \n class Xorshift_star\n u64 state /* Must be seeded to non-zero initial value */\n u64 const = HEX '2545F4914F6CDD1D'\n \n method seed(u64 num):\n state = num\n end method\n \n method next_int():\n u64 x = state\n x = x ^ (x >> 12)\n x = x ^ (x << 25)\n x = x ^ (x >> 27)\n state = x\n u32 answer = ((x * const) >> 32)\n \n return answer\n end method\n \n method next_float():\n return float next_int() / (1 << 32)\n end method\n \n end class\n \n:;Xorshift use:\n\n random_gen = instance Xorshift_star\n random_gen.seed(1234567)\n print(random_gen.next_int()) /* 3540625527 */\n print(random_gen.next_int()) /* 2750739987 */\n print(random_gen.next_int()) /* 4037983143 */\n print(random_gen.next_int()) /* 1993361440 */\n print(random_gen.next_int()) /* 3809424708 */\n\n;Task:\n\n* Generate a class/set of functions that generates pseudo-random\nnumbers as shown above.\n\n* Show that the first five integers genrated with the seed 1234567\nare as shown above \n\n* Show that for an initial seed of 987654321, the counts of 100_000 repetitions of\n\n floor(random_gen.next_float() * 5)\n\n:Is as follows:\n \n 0: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007\n\n* Show your output here, on this page.\n\n\n\n", "solution": "#include \n#include \n#include \n\nstatic uint64_t state;\nstatic const uint64_t STATE_MAGIC = 0x2545F4914F6CDD1D;\n\nvoid seed(uint64_t num) {\n state = num;\n}\n\nuint32_t next_int() {\n uint64_t x;\n uint32_t answer;\n\n x = state;\n x = x ^ (x >> 12);\n x = x ^ (x << 25);\n x = x ^ (x >> 27);\n state = x;\n answer = ((x * STATE_MAGIC) >> 32);\n\n return answer;\n}\n\nfloat next_float() {\n return (float)next_int() / (1LL << 32);\n}\n\nint main() {\n int counts[5] = { 0, 0, 0, 0, 0 };\n int i;\n\n seed(1234567);\n printf(\"%u\\n\", next_int());\n printf(\"%u\\n\", next_int());\n printf(\"%u\\n\", next_int());\n printf(\"%u\\n\", next_int());\n printf(\"%u\\n\", next_int());\n printf(\"\\n\");\n\n seed(987654321);\n for (i = 0; i < 100000; i++) {\n int j = (int)floor(next_float() * 5.0);\n counts[j]++;\n }\n for (i = 0; i < 5; i++) {\n printf(\"%d: %d\\n\", i, counts[i]);\n }\n\n return 0;\n}"} {"title": "Pythagoras tree", "language": "C", "task": "The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. \n\n;Task\nConstruct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions).\n\n;Related tasks\n* Fractal tree\n\n", "solution": "#include\n#include\n#include\n#include\n\ntypedef struct{\n\tdouble x,y;\n}point;\n\nvoid pythagorasTree(point a,point b,int times){\n\t\n\tpoint c,d,e;\n\t\n\tc.x = b.x - (a.y - b.y);\n\tc.y = b.y - (b.x - a.x);\n\t\n\td.x = a.x - (a.y - b.y);\n\td.y = a.y - (b.x - a.x);\n\t\n\te.x = d.x + ( b.x - a.x - (a.y - b.y) ) / 2;\n\te.y = d.y - ( b.x - a.x + a.y - b.y ) / 2;\n\t\n\tif(times>0){\n\t\tsetcolor(rand()%15 + 1);\n\t\t\n\t\tline(a.x,a.y,b.x,b.y);\n\t\tline(c.x,c.y,b.x,b.y);\n\t\tline(c.x,c.y,d.x,d.y);\n\t\tline(a.x,a.y,d.x,d.y);\n\t\t\n\t\tpythagorasTree(d,e,times-1);\n\t\tpythagorasTree(e,c,times-1);\n\t}\n}\n\nint main(){\n\t\n\tpoint a,b;\n\tdouble side;\n\tint iter;\n\t\n\ttime_t t;\n\t\n\tprintf(\"Enter initial side length : \");\n\tscanf(\"%lf\",&side);\n\t\n\tprintf(\"Enter number of iterations : \");\n\tscanf(\"%d\",&iter);\n\t\n\ta.x = 6*side/2 - side/2;\n\ta.y = 4*side;\n\tb.x = 6*side/2 + side/2;\n\tb.y = 4*side;\n\t\n\tinitwindow(6*side,4*side,\"Pythagoras Tree ?\");\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tpythagorasTree(a,b,iter);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n\n}"} {"title": "Pythagorean quadruples", "language": "C", "task": "One form of '''Pythagorean quadruples''' is (for positive integers '''a''', '''b''', '''c''', and '''d'''): \n\n\n:::::::: a2 + b2 + c2 = d2 \n\n\nAn example:\n\n:::::::: 22 + 32 + 62 = 72 \n\n::::: which is:\n\n:::::::: 4 + 9 + 36 = 49 \n\n\n;Task:\n\nFor positive integers up '''2,200''' (inclusive), for all values of '''a''', \n'''b''', '''c''', and '''d''', \nfind (and show here) those values of '''d''' that ''can't'' be represented.\n\nShow the values of '''d''' on one line of output (optionally with a title).\n\n\n;Related tasks:\n* [[Euler's sum of powers conjecture]]. \n* [[Pythagorean triples]].\n\n\n;Reference:\n:* the Wikipedia article: Pythagorean quadruple.\n\n", "solution": "#include \n#include \n#include \n\n#define N 2200\n\nint main(int argc, char **argv){\n int a,b,c,d;\n int r[N+1];\n memset(r,0,sizeof(r));\t// zero solution array\n for(a=1; a<=N; a++){\n for(b=a; b<=N; b++){\n\t int aabb;\n\t if(a&1 && b&1) continue; // for positive odd a and b, no solution.\n\t aabb=a*a + b*b;\n\t for(c=b; c<=N; c++){\n\t int aabbcc=aabb + c*c;\n\t d=(int)sqrt((float)aabbcc);\n\t if(aabbcc == d*d && d<=N) r[d]=1;\t// solution\n\t }\n }\n }\n for(a=1; a<=N; a++)\n if(!r[a]) printf(\"%d \",a);\t// print non solution\n printf(\"\\n\");\n}"} {"title": "Pythagorean triples", "language": "C", "task": "A Pythagorean triple is defined as three positive integers (a, b, c) where a < b < c, and a^2+b^2=c^2.\n\nThey are called primitive triples if a, b, c are co-prime, that is, if their pairwise greatest common divisors {\\rm gcd}(a, b) = {\\rm gcd}(a, c) = {\\rm gcd}(b, c) = 1. \n\nBecause of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ({\\rm gcd}(a, b) = 1). \n\nEach triple forms the length of the sides of a right triangle, whose perimeter is P=a+b+c.\n\n\n;Task:\nThe task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive.\n\n\n;Extra credit: \nDeal with large values. Can your program handle a maximum perimeter of 1,000,000? What about 10,000,000? 100,000,000?\n\nNote: the extra credit is not for you to demonstrate how fast your language is compared to others; you need a proper algorithm to solve them in a timely manner.\n\n\n;Related tasks:\n* [[Euler's sum of powers conjecture]] \n* [[List comprehensions]]\n* [[Pythagorean quadruples]] \n\n", "solution": "#include \n#include \n#include \n\n/* should be 64-bit integers if going over 1 billion */\ntypedef unsigned long xint;\n#define FMT \"%lu\"\n\nxint total, prim, max_peri;\nxint U[][9] = {{ 1, -2, 2, 2, -1, 2, 2, -2, 3},\n { 1, 2, 2, 2, 1, 2, 2, 2, 3},\n {-1, 2, 2, -2, 1, 2, -2, 2, 3}};\n\nvoid new_tri(xint in[])\n{\n int i;\n xint t[3], p = in[0] + in[1] + in[2];\n\n if (p > max_peri) return;\n\n prim ++;\n\n /* for every primitive triangle, its multiples would be right-angled too;\n * count them up to the max perimeter */\n total += max_peri / p;\n\n /* recursively produce next tier by multiplying the matrices */\n for (i = 0; i < 3; i++) {\n t[0] = U[i][0] * in[0] + U[i][1] * in[1] + U[i][2] * in[2];\n t[1] = U[i][3] * in[0] + U[i][4] * in[1] + U[i][5] * in[2];\n t[2] = U[i][6] * in[0] + U[i][7] * in[1] + U[i][8] * in[2];\n new_tri(t);\n }\n}\n\nint main()\n{\n xint seed[3] = {3, 4, 5};\n\n for (max_peri = 10; max_peri <= 100000000; max_peri *= 10) {\n total = prim = 0;\n new_tri(seed);\n\n printf( \"Up to \"FMT\": \"FMT\" triples, \"FMT\" primitives.\\n\",\n max_peri, total, prim);\n }\n return 0;\n}"} {"title": "Quaternion type", "language": "C", "task": "complex numbers.\n\nA complex number has a real and complex part, sometimes written as a + bi, \nwhere a and b stand for real numbers, and i stands for the square root of minus 1.\n\nAn example of a complex number might be -3 + 2i, \nwhere the real part, a is '''-3.0''' and the complex part, b is '''+2.0'''. \n\nA quaternion has one real part and ''three'' imaginary parts, i, j, and k. \n\nA quaternion might be written as a + bi + cj + dk. \n\nIn the quaternion numbering system:\n:::* ii = jj = kk = ijk = -1, or more simply,\n:::* ii = jj = kk = ijk = -1. \n\nThe order of multiplication is important, as, in general, for two quaternions:\n:::: q1 and q2: q1q2 q2q1. \n\nAn example of a quaternion might be 1 +2i +3j +4k \n\nThere is a list form of notation where just the numbers are shown and the imaginary multipliers i, j, and k are assumed by position. \n\nSo the example above would be written as (1, 2, 3, 4) \n\n\n;Task:\nGiven the three quaternions and their components: \n q = (1, 2, 3, 4) = (a, b, c, d)\n q1 = (2, 3, 4, 5) = (a1, b1, c1, d1)\n q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) \nAnd a wholly real number r = 7. \n\n\nCreate functions (or classes) to perform simple maths with quaternions including computing:\n# The norm of a quaternion: = \\sqrt{a^2 + b^2 + c^2 + d^2} \n# The negative of a quaternion: = (-a, -b, -c, -d) \n# The conjugate of a quaternion: = ( a, -b, -c, -d) \n# Addition of a real number r and a quaternion q: r + q = q + r = (a+r, b, c, d) \n# Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) \n# Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) \n# Multiplication of two quaternions q1 and q2 is given by: ( a1a2 - b1b2 - c1c2 - d1d2, a1b2 + b1a2 + c1d2 - d1c2, a1c2 - b1d2 + c1a2 + d1b2, a1d2 + b1c2 - c1b2 + d1a2 ) \n# Show that, for the two quaternions q1 and q2: q1q2 q2q1 \n\nIf a language has built-in support for quaternions, then use it.\n\n\n;C.f.:\n* [[Vector products]]\n* On Quaternions; or on a new System of Imaginaries in Algebra. By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.\n\n", "solution": "#include \n#include \n#include \n#include \n\ntypedef struct quaternion\n{\n double q[4];\n} quaternion_t;\n\n\nquaternion_t *quaternion_new(void)\n{\n return malloc(sizeof(quaternion_t));\n}\n\nquaternion_t *quaternion_new_set(double q1,\n\t\t\t\t double q2,\n\t\t\t\t double q3,\n\t\t\t\t double q4)\n{\n quaternion_t *q = malloc(sizeof(quaternion_t));\n if (q != NULL) {\n q->q[0] = q1; q->q[1] = q2; q->q[2] = q3; q->q[3] = q4;\n }\n return q;\n}\n\n\nvoid quaternion_copy(quaternion_t *r, quaternion_t *q)\n{\n size_t i;\n\n if (r == NULL || q == NULL) return;\n for(i = 0; i < 4; i++) r->q[i] = q->q[i];\n}\n\n\ndouble quaternion_norm(quaternion_t *q)\n{\n size_t i;\n double r = 0.0;\n \n if (q == NULL) {\n fprintf(stderr, \"NULL quaternion in norm\\n\");\n return 0.0;\n }\n\n for(i = 0; i < 4; i++) r += q->q[i] * q->q[i];\n return sqrt(r);\n}\n\n\nvoid quaternion_neg(quaternion_t *r, quaternion_t *q)\n{\n size_t i;\n\n if (q == NULL || r == NULL) return;\n for(i = 0; i < 4; i++) r->q[i] = -q->q[i];\n}\n\n\nvoid quaternion_conj(quaternion_t *r, quaternion_t *q)\n{\n size_t i;\n\n if (q == NULL || r == NULL) return;\n r->q[0] = q->q[0];\n for(i = 1; i < 4; i++) r->q[i] = -q->q[i];\n}\n\n\nvoid quaternion_add_d(quaternion_t *r, quaternion_t *q, double d)\n{\n if (q == NULL || r == NULL) return;\n quaternion_copy(r, q);\n r->q[0] += d;\n}\n\n\nvoid quaternion_add(quaternion_t *r, quaternion_t *a, quaternion_t *b)\n{\n size_t i;\n\n if (r == NULL || a == NULL || b == NULL) return;\n for(i = 0; i < 4; i++) r->q[i] = a->q[i] + b->q[i];\n}\n\n\nvoid quaternion_mul_d(quaternion_t *r, quaternion_t *q, double d)\n{\n size_t i;\n\n if (r == NULL || q == NULL) return;\n for(i = 0; i < 4; i++) r->q[i] = q->q[i] * d;\n}\n\nbool quaternion_equal(quaternion_t *a, quaternion_t *b)\n{\n size_t i;\n \n for(i = 0; i < 4; i++) if (a->q[i] != b->q[i]) return false;\n return true;\n}\n\n\n#define A(N) (a->q[(N)])\n#define B(N) (b->q[(N)])\n#define R(N) (r->q[(N)])\nvoid quaternion_mul(quaternion_t *r, quaternion_t *a, quaternion_t *b)\n{\n size_t i;\n double ri = 0.0;\n\n if (r == NULL || a == NULL || b == NULL) return;\n R(0) = A(0)*B(0) - A(1)*B(1) - A(2)*B(2) - A(3)*B(3);\n R(1) = A(0)*B(1) + A(1)*B(0) + A(2)*B(3) - A(3)*B(2);\n R(2) = A(0)*B(2) - A(1)*B(3) + A(2)*B(0) + A(3)*B(1);\n R(3) = A(0)*B(3) + A(1)*B(2) - A(2)*B(1) + A(3)*B(0);\n}\n#undef A\n#undef B\n#undef R\n\n\nvoid quaternion_print(quaternion_t *q)\n{\n if (q == NULL) return;\n printf(\"(%lf, %lf, %lf, %lf)\\n\", \n\t q->q[0], q->q[1], q->q[2], q->q[3]);\n}"} {"title": "Quine", "language": "C", "task": "A quine is a self-referential program that can, \nwithout any external access, output its own source. \n\n\nA '''quine''' (named after Willard Van Orman Quine) is also known as:\n::* ''self-reproducing automata'' (1972)\n::* ''self-replicating program'' or ''self-replicating computer program''\n::* ''self-reproducing program'' or ''self-reproducing computer program''\n::* ''self-copying program'' or ''self-copying computer program''\n\n\n\nIt is named after the philosopher and logician \nwho studied self-reference and quoting in natural language, \nas for example in the paradox \"'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation.\"\n\n\"Source\" has one of two meanings. It can refer to the text-based program source. \nFor languages in which program source is represented as a data structure, \"source\" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.\n\nThe usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once ''quoted'' in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.\n\n\n;Task:\nWrite a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.\n\nThere are several difficulties that one runs into when writing a quine, mostly dealing with quoting:\n* Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.\n** Some languages have a function for getting the \"source code representation\" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.\n** Another solution is to construct the quote character from its [[character code]], without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.\n* Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. \"\\n\"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.\n** If the language has a way of getting the \"source code representation\", it usually handles the escaping of characters, so this is not a problem.\n** Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.\n** Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.\n\n\n'''Next to the Quines presented here, many other versions can be found on the Quine page.'''\n\n\n;Related task:\n:* print itself.\n\n", "solution": "#include \n\nstatic char sym[] = \"\\n\\t\\\\\\\"\";\n\nint main(void) {\n\tconst char *code = \"#include %c%cstatic char sym[] = %c%cn%ct%c%c%c%c%c;%c%cint main(void) {%c%cconst char *code = %c%s%c;%c%cprintf(code, sym[0], sym[0], sym[3], sym[2], sym[2], sym[2], sym[2], sym[2], sym[3], sym[3], sym[0], sym[0], sym[0], sym[1], sym[3], code, sym[3], sym[0], sym[1], sym[0], sym[0], sym[1], sym[0], sym[0]);%c%c%creturn 0;%c}%c\";\n\tprintf(code, sym[0], sym[0], sym[3], sym[2], sym[2], sym[2], sym[2], sym[2], sym[3], sym[3], sym[0], sym[0], sym[0], sym[1], sym[3], code, sym[3], sym[0], sym[1], sym[0], sym[0], sym[1], sym[0], sym[0]);\n\n\treturn 0;\n}\n"} {"title": "RIPEMD-160", "language": "C", "task": "'''RIPEMD-160''' is another hash function; it computes a 160-bit message digest.\n\nThere is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160. \nFor padding the message, RIPEMD-160 acts like [[MD4]] (RFC 1320).\n\nFind the RIPEMD-160 message digest of a string of [[octet]]s. \nUse the ASCII encoded string \"Rosetta Code\". \nYou may either call an RIPEMD-160 library, or implement RIPEMD-160 in your language.\n\n", "solution": "#ifndef RMDsize\n#define RMDsize 160\n#endif\n\n#include \n#include \n#include \n#include \n#if RMDsize == 128\n#include \"rmd128.h\"\n#include \"rmd128.c\" /* Added to remove errors during compilation */\n#elif RMDsize == 160\n#include \"rmd160.h\"\n#include \"rmd160.c\" /* Added to remove errors during compilation */\n#endif\n\n"} {"title": "Ramer-Douglas-Peucker line simplification", "language": "C", "task": "The '''Ramer-Douglas-Peucker''' algorithm is a line simplification algorithm for reducing the number of points used to define its shape. \n\n\n;Task:\nUsing the '''Ramer-Douglas-Peucker''' algorithm, simplify the 2D line defined by the points:\n (0,0) (1,0.1) (2,-0.1) (3,5) (4,6) (5,7) (6,8.1) (7,9) (8,9) (9,9) \n\nThe error threshold to be used is: '''1.0'''. \n\nDisplay the remaining points here.\n\n\n;Reference:\n:* the Wikipedia article: Ramer-Douglas-Peucker algorithm.\n\n", "solution": "#include \n#include \n#include \n\ntypedef struct point_tag {\n double x;\n double y;\n} point_t;\n\n// Returns the distance from point p to the line between p1 and p2\ndouble perpendicular_distance(point_t p, point_t p1, point_t p2) {\n double dx = p2.x - p1.x;\n double dy = p2.y - p1.y;\n double d = sqrt(dx * dx + dy * dy);\n return fabs(p.x * dy - p.y * dx + p2.x * p1.y - p2.y * p1.x)/d;\n}\n\n// Simplify an array of points using the Ramer\u2013Douglas\u2013Peucker algorithm.\n// Returns the number of output points.\nsize_t douglas_peucker(const point_t* points, size_t n, double epsilon,\n point_t* dest, size_t destlen) {\n assert(n >= 2);\n assert(epsilon >= 0);\n double max_dist = 0;\n size_t index = 0;\n for (size_t i = 1; i + 1 < n; ++i) {\n double dist = perpendicular_distance(points[i], points[0], points[n - 1]);\n if (dist > max_dist) {\n max_dist = dist;\n index = i;\n }\n }\n if (max_dist > epsilon) {\n size_t n1 = douglas_peucker(points, index + 1, epsilon, dest, destlen);\n if (destlen >= n1 - 1) {\n destlen -= n1 - 1;\n dest += n1 - 1;\n } else {\n destlen = 0;\n }\n size_t n2 = douglas_peucker(points + index, n - index, epsilon, dest, destlen);\n return n1 + n2 - 1;\n }\n if (destlen >= 2) {\n dest[0] = points[0];\n dest[1] = points[n - 1];\n }\n return 2;\n}\n\nvoid print_points(const point_t* points, size_t n) {\n for (size_t i = 0; i < n; ++i) {\n if (i > 0)\n printf(\" \");\n printf(\"(%g, %g)\", points[i].x, points[i].y);\n }\n printf(\"\\n\");\n}\n\nint main() {\n point_t points[] = {\n {0,0}, {1,0.1}, {2,-0.1}, {3,5}, {4,6},\n {5,7}, {6,8.1}, {7,9}, {8,9}, {9,9}\n };\n const size_t len = sizeof(points)/sizeof(points[0]);\n point_t out[len];\n size_t n = douglas_peucker(points, len, 1.0, out, len);\n print_points(out, n);\n return 0;\n}"} {"title": "Random number generator (device)", "language": "C", "task": "If your system has a means to generate random numbers involving not only a software algorithm (like the /dev/urandom devices in Unix), then:\n\nshow how to obtain a random 32-bit number from that mechanism.\n\n;Related task\n* [[Random_number_generator_(included)]]\n\n", "solution": "#include \n#include \n\n#define RANDOM_PATH \"/dev/urandom\"\n\nint main(void)\n{\n unsigned char buf[4];\n unsigned long v;\n FILE *fin;\n\n if ((fin = fopen(RANDOM_PATH, \"r\")) == NULL) {\n fprintf(stderr, \"%s: unable to open file\\n\", RANDOM_PATH);\n return EXIT_FAILURE;\n }\n if (fread(buf, 1, sizeof buf, fin) != sizeof buf) {\n fprintf(stderr, \"%s: not enough bytes (expected %u)\\n\",\n RANDOM_PATH, (unsigned) sizeof buf);\n return EXIT_FAILURE;\n }\n fclose(fin);\n v = buf[0] | buf[1] << 8UL | buf[2] << 16UL | buf[3] << 24UL;\n printf(\"%lu\\n\", v);\n return 0;\n}"} {"title": "Random number generator (included)", "language": "C", "task": "The task is to:\n: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.\n: If possible, give a link to a wider explanation of the algorithm used.\n\nNote: the task is ''not'' to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used.\n\nThe main types of pseudo-random number generator (Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a [[cryptographic hash function]] to maximize unpredictability of individual bits. \n\nNote that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.\n\n", "solution": "#include \n#include \n\n/* Flip a coin, 10 times. */\nint\nmain()\n{\n\tint i;\n\tsrand(time(NULL));\n\tfor (i = 0; i < 10; i++)\n\t\tputs((rand() % 2) ? \"heads\" : \"tails\");\n\treturn 0;\n}"} {"title": "Range consolidation", "language": "C", "task": "Define a range of numbers '''R''', with bounds '''b0''' and '''b1''' covering all numbers ''between and including both bounds''. \n\n\nThat range can be shown as:\n::::::::: '''[b0, b1]'''\n:::::::: or equally as:\n::::::::: '''[b1, b0]'''\n\n\nGiven two ranges, the act of consolidation between them compares the two ranges:\n* If one range covers all of the other then the result is that encompassing range.\n* If the ranges touch or intersect then the result is ''one'' new single range covering the overlapping ranges.\n* Otherwise the act of consolidation is to return the two non-touching ranges.\n\n\nGiven '''N''' ranges where '''N > 2''' then the result is the same as repeatedly replacing all combinations of two ranges by their consolidation until no further consolidation between range pairs is possible. \n\nIf '''N < 2''' then range consolidation has no strict meaning and the input can be returned. \n\n\n;Example 1:\n: Given the two ranges '''[1, 2.5]''' and '''[3, 4.2]''' then \n: there is no common region between the ranges and the result is the same as the input.\n\n\n;Example 2:\n: Given the two ranges '''[1, 2.5]''' and '''[1.8, 4.7]''' then \n: there is : an overlap '''[2.5, 1.8]''' between the ranges and \n: the result is the single range '''[1, 4.7]'''. \n: Note that order of bounds in a range is not (yet) stated.\n\n\n;Example 3:\n: Given the two ranges '''[6.1, 7.2]''' and '''[7.2, 8.3]''' then \n: they touch at '''7.2''' and \n: the result is the single range '''[6.1, 8.3]'''. \n\n\n;Example 4:\n: Given the three ranges '''[1, 2]''' and '''[4, 8]''' and '''[2, 5]''' \n: then there is no intersection of the ranges '''[1, 2]''' and '''[4, 8]''' \n: but the ranges '''[1, 2]''' and '''[2, 5]''' overlap and \n: consolidate to produce the range '''[1, 5]'''. \n: This range, in turn, overlaps the other range '''[4, 8]''', and \n: so consolidates to the final output of the single range '''[1, 8]'''.\n\n\n;Task:\nLet a normalized range display show the smaller bound to the left; and show the\nrange with the smaller lower bound to the left of other ranges when showing multiple ranges.\n\nOutput the ''normalized'' result of applying consolidation to these five sets of ranges: \n [1.1, 2.2]\n [6.1, 7.2], [7.2, 8.3]\n [4, 3], [2, 1]\n [4, 3], [2, 1], [-1, -2], [3.9, 10]\n [1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6] \nShow all output here.\n\n\n;See also:\n* [[Set consolidation]]\n* [[Set of real numbers]]\n\n", "solution": "#include \n#include \n\ntypedef struct range_tag {\n double low;\n double high;\n} range_t;\n\nvoid normalize_range(range_t* range) {\n if (range->high < range->low) {\n double tmp = range->low;\n range->low = range->high;\n range->high = tmp;\n }\n}\n\nint range_compare(const void* p1, const void* p2) {\n const range_t* r1 = p1;\n const range_t* r2 = p2;\n if (r1->low < r2->low)\n return -1;\n if (r1->low > r2->low)\n return 1;\n if (r1->high < r2->high)\n return -1;\n if (r1->high > r2->high)\n return 1;\n return 0;\n}\n\nvoid normalize_ranges(range_t* ranges, size_t count) {\n for (size_t i = 0; i < count; ++i)\n normalize_range(&ranges[i]);\n qsort(ranges, count, sizeof(range_t), range_compare);\n}\n\n// Consolidates an array of ranges in-place. Returns the\n// number of ranges after consolidation.\nsize_t consolidate_ranges(range_t* ranges, size_t count) {\n normalize_ranges(ranges, count);\n size_t out_index = 0;\n for (size_t i = 0; i < count; ) {\n size_t j = i;\n while (++j < count && ranges[j].low <= ranges[i].high) {\n if (ranges[i].high < ranges[j].high)\n ranges[i].high = ranges[j].high;\n }\n ranges[out_index++] = ranges[i];\n i = j;\n }\n return out_index;\n}\n\nvoid print_range(const range_t* range) {\n printf(\"[%g, %g]\", range->low, range->high);\n}\n\nvoid print_ranges(const range_t* ranges, size_t count) {\n if (count == 0)\n return;\n print_range(&ranges[0]);\n for (size_t i = 1; i < count; ++i) {\n printf(\", \");\n print_range(&ranges[i]);\n }\n}\n\nvoid test_consolidate_ranges(range_t* ranges, size_t count) {\n print_ranges(ranges, count);\n printf(\" -> \");\n count = consolidate_ranges(ranges, count);\n print_ranges(ranges, count);\n printf(\"\\n\");\n}\n\n#define LENGTHOF(a) sizeof(a)/sizeof(a[0])\n\nint main() {\n range_t test1[] = { {1.1, 2.2} };\n range_t test2[] = { {6.1, 7.2}, {7.2, 8.3} };\n range_t test3[] = { {4, 3}, {2, 1} };\n range_t test4[] = { {4, 3}, {2, 1}, {-1, -2}, {3.9, 10} };\n range_t test5[] = { {1, 3}, {-6, -1}, {-4, -5}, {8, 2}, {-6, -6} };\n test_consolidate_ranges(test1, LENGTHOF(test1));\n test_consolidate_ranges(test2, LENGTHOF(test2));\n test_consolidate_ranges(test3, LENGTHOF(test3));\n test_consolidate_ranges(test4, LENGTHOF(test4));\n test_consolidate_ranges(test5, LENGTHOF(test5));\n return 0;\n}"} {"title": "Range expansion", "language": "C", "task": "{{:Range extraction/Format}}\n\n\n;Task:\nExpand the range description: \n -6,-3--1,3-5,7-11,14,15,17-20 \nNote that the second element above, \nis the '''range from minus 3 to ''minus'' 1'''. \n\n\n;Related task:\n* [[Range extraction]]\n\n", "solution": "#include \n#include \n#include \n\n/* BNFesque\n\trangelist := (range | number) [',' rangelist]\n\trange := number '-' number\t*/\n\nint get_list(const char *, char **);\nint get_rnge(const char *, char **);\n\n/* parser only parses; what to do with parsed items is up to\n* the add_number and and_range functions */\nvoid add_number(int x);\nint add_range(int x, int y);\n\n#define skip_space while(isspace(*s)) s++\n#define get_number(x, s, e) (x = strtol(s, e, 10), *e != s)\nint get_list(const char *s, char **e)\n{\n\tint x;\n\twhile (1) {\n\t\tskip_space;\n\t\tif (!get_rnge(s, e) && !get_number(x, s, e)) break;\n\t\ts = *e;\n\n\t\tskip_space;\n\t\tif ((*s) == '\\0') { putchar('\\n'); return 1; }\n\t\tif ((*s) == ',') { s++; continue; }\n\t\tbreak;\n\t}\n\t*(const char **)e = s;\n\tprintf(\"\\nSyntax error at %s\\n\", s);\n\treturn 0;\n}\n\nint get_rnge(const char *s, char **e)\n{\n\tint x, y;\n\tchar *ee;\n\tif (!get_number(x, s, &ee)) return 0;\n\ts = ee;\n\n\tskip_space;\n\tif (*s != '-') {\n\t\t*(const char **)e = s;\n\t\treturn 0;\n\t}\n\ts++;\n\tif(!get_number(y, s, e)) return 0;\n\treturn add_range(x, y);\n}\n\nvoid add_number(int x)\n{\n\tprintf(\"%d \", x);\n}\n\nint add_range(int x, int y)\n{\n\tif (y <= x) return 0;\n\twhile (x <= y) printf(\"%d \", x++);\n\treturn 1;\n}\n\nint main()\n{\n\tchar *end;\n\n\t/* this is correct */\n\tif (get_list(\"-6,-3--1,3-5,7-11,14,15,17-20\", &end)) puts(\"Ok\");\n\n\t/* this is not. note the subtle error: \"-6 -3\" is parsed\n\t * as range(-6, 3), so synax error comes after that */\n\tget_list(\"-6 -3--1,3-5,7-11,14,15,17-20\", &end);\n\n\treturn 0;\n}"} {"title": "Range extraction", "language": "C", "task": "{{:Range extraction/Format}}\n\n;Task:\n* Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. \n* Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39).\n\n 0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n 37, 38, 39\n* Show the output of your program.\n\n\n;Related task:\n* [[Range expansion]]\n\n", "solution": "#include \n#include \n\nsize_t rprint(char *s, int *x, int len)\n{\n#define sep (a > s ? \",\" : \"\") /* use comma except before first output */\n#define ol (s ? 100 : 0) /* print only if not testing for length */\n\tint i, j;\n\tchar *a = s;\n\tfor (i = j = 0; i < len; i = ++j) {\n\t\tfor (; j < len - 1 && x[j + 1] == x[j] + 1; j++);\n\n\t\tif (i + 1 < j)\n\t\t\ta += snprintf(s?a:s, ol, \"%s%d-%d\", sep, x[i], x[j]);\n\t\telse\n\t\t\twhile (i <= j)\n\t\t\t\ta += snprintf(s?a:s, ol, \"%s%d\", sep, x[i++]);\n\t}\n\treturn a - s;\n#undef sep\n#undef ol\n}\n\nint main()\n{\n\tint x[] = {\t0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n\t\t\t15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n\t\t\t25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n\t\t\t37, 38, 39 };\n\n\tchar *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1);\n\trprint(s, x, sizeof(x) / sizeof(int));\n\tprintf(\"%s\\n\", s);\n\n\treturn 0;\n}"} {"title": "Rate counter", "language": "C", "task": "Counting the frequency at which something occurs is a common activity in measuring performance and managing resources. In this task, we assume that there is some job which we want to perform repeatedly, and we want to know how quickly these jobs are being performed.\nOf interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.\n\nMultiple approaches are allowed (even preferable), so long as they can accomplish these goals:\n\n* Run N seconds worth of jobs and/or Y jobs.\n* Report at least three distinct times.\n\nBe aware of the precision and accuracy limitations of your timing mechanisms, and document them if you can.\n\n'''See also:''' [[System time]], [[Time a function]]\n\n", "solution": "#include \n#include \n\n// We only get one-second precision on most systems, as\n// time_t only holds seconds.\nstruct rate_state_s\n{\n time_t lastFlush;\n time_t period;\n size_t tickCount;\n};\n\nvoid tic_rate(struct rate_state_s* pRate)\n{\n pRate->tickCount += 1;\n\n time_t now = time(NULL);\n\n if((now - pRate->lastFlush) >= pRate->period)\n {\n //TPS Report\n size_t tps = 0.0;\n if(pRate->tickCount > 0)\n tps = pRate->tickCount / (now - pRate->lastFlush);\n\n printf(\"%u tics per second.\\n\", tps);\n\n //Reset\n pRate->tickCount = 0;\n pRate->lastFlush = now;\n }\n}\n\n// A stub function that simply represents whatever it is\n// that we want to multiple times.\nvoid something_we_do()\n{\n // We use volatile here, as many compilers will optimize away\n // the for() loop otherwise, even without optimizations\n // explicitly enabled.\n //\n // volatile tells the compiler not to make any assumptions\n // about the variable, implying that the programmer knows more\n // about that variable than the compiler, in this case.\n volatile size_t anchor = 0;\n size_t x = 0;\n for(x = 0; x < 0xffff; ++x)\n {\n anchor = x;\n }\n}\n\nint main()\n{\n time_t start = time(NULL);\n\n struct rate_state_s rateWatch;\n rateWatch.lastFlush = start;\n rateWatch.tickCount = 0;\n rateWatch.period = 5; // Report every five seconds.\n\n time_t latest = start;\n // Loop for twenty seconds\n for(latest = start; (latest - start) < 20; latest = time(NULL))\n {\n // Do something.\n something_we_do();\n\n // Note that we did something.\n tic_rate(&rateWatch);\n }\n\n return 0;\n}"} {"title": "Read a specific line from a file", "language": "C", "task": "Some languages have special semantics for obtaining a known line number from a file.\n\n\n;Task:\nDemonstrate how to obtain the contents of a specific line within a file. \n\nFor the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (for potential future use within the program if the code were to become embedded). \n\nIf the file does not contain seven lines, or the seventh line is empty, or too big to be retrieved, output an appropriate message. \n\nIf no special semantics are available for obtaining the required line, it is permissible to read line by line. \n\nNote that empty lines are considered and should still be counted.\n\nAlso note that for functional languages or languages without variables or storage, it is permissible to output the extracted data to standard output.\n\n", "solution": "#include \n#include \n\n#define BUF_SIZE ( 256 )\n\nchar *get_nth_line( FILE *f, int line_no )\n{\n char buf[ BUF_SIZE ];\n size_t curr_alloc = BUF_SIZE, curr_ofs = 0;\n char *line = malloc( BUF_SIZE );\n int in_line = line_no == 1;\n size_t bytes_read;\n\n /* Illegal to ask for a line before the first one. */\n if ( line_no < 1 )\n return NULL;\n\n /* Handle out-of-memory by returning NULL */\n if ( !line )\n return NULL;\n\n /* Scan the file looking for newlines */\n while ( line_no && \n ( bytes_read = fread( buf, 1, BUF_SIZE, f ) ) > 0 )\n {\n int i;\n\n for ( i = 0 ; i < bytes_read ; i++ )\n {\n if ( in_line )\n {\n if ( curr_ofs >= curr_alloc )\n {\n curr_alloc <<= 1;\n line = realloc( line, curr_alloc );\n\n if ( !line ) /* out of memory? */\n return NULL;\n }\n line[ curr_ofs++ ] = buf[i];\n }\n\n if ( buf[i] == '\\n' )\n {\n line_no--;\n\n if ( line_no == 1 )\n in_line = 1;\n \n if ( line_no == 0 )\n break;\n }\n }\n }\n\n /* Didn't find the line? */\n if ( line_no != 0 ) \n {\n free( line );\n return NULL;\n }\n\n /* Resize allocated buffer to what's exactly needed by the string \n and the terminating NUL character. Note that this code *keeps*\n the terminating newline as part of the string. \n */\n line = realloc( line, curr_ofs + 1 );\n \n if ( !line ) /* out of memory? */\n return NULL;\n\n /* Add the terminating NUL. */\n line[ curr_ofs ] = '\\0';\n\n /* Return the line. Caller is responsible for freeing it. */\n return line;\n}\n\n\n/* Test program. Prints out the 7th line of input from stdin, if any */\nint main( int argc, char *argv[] )\n{\n char *line7 = get_nth_line( stdin, 7 );\n\n if ( line7 )\n {\n printf(\"The 7th line of input was:\\n%s\\n\", line7 );\n free( line7 );\n } else\n {\n printf(\"Did not find the 7th line of input. Reason: \");\n if ( feof( stdin ) )\n puts(\"End of file reached.\");\n else if ( ferror( stdin ) )\n puts(\"Error reading input.\");\n else\n puts(\"Out of memory.\");\n }\n\n return 0;\n}\n"} {"title": "Remove lines from a file", "language": "C", "task": "Remove a specific line or a number of lines from a file. \n\nThis should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). \n\nFor the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from the file foobar.txt, the parameters should be: foobar.txt, 1, 2\n\nEmpty lines are considered and should still be counted, and if the specified line is empty, it should still be removed. \n\nAn appropriate message should appear if an attempt is made to remove lines beyond the end of the file.\n\n", "solution": "#include \n#include /* for atoi() and malloc() */\n#include /* for memmove() */\n\n/* Conveniently print to standard error and exit nonzero. */\n#define ERROR(fmt, arg) return fprintf(stderr, fmt \"\\n\", arg)\n\nint main(int argc, char **argv)\n{\n FILE *fp;\n char *buf;\n size_t sz;\n int start, count, lines = 1;\n int dest = 0, src = 0, pos = -1;\n\n /* Initialization and sanity checks */\n if (argc != 4)\n ERROR(\"Usage: %s \", argv[0]);\n\n if ((count = atoi(argv[3])) < 1) /* We're a no-op. */\n return 0;\n\n if ((start = atoi(argv[2])) < 1)\n ERROR(\"Error: (%d) must be positive\", start);\n\n if ((fp = fopen(argv[1], \"r\")) == NULL)\n ERROR(\"No such file: %s\", argv[1]);\n\n /* Determine filesize and allocate a buffer accordingly. */\n fseek(fp, 0, SEEK_END);\n sz = ftell(fp);\n buf = malloc(sz + 1);\n rewind(fp);\n\n /* Fill the buffer, count lines, and remember a few important offsets. */\n while ((buf[++pos] = fgetc(fp)) != EOF) {\n if (buf[pos] == '\\n') {\n ++lines;\n if (lines == start) dest = pos + 1;\n if (lines == start + count) src = pos + 1;\n }\n }\n\n /* We've been asked to do something weird; clean up and bail. */\n if (start + count > lines) {\n free(buf);\n fclose(fp);\n ERROR(\"Error: invalid parameters for file with %d lines\", --lines);\n }\n\n /* Overwrite the lines to be deleted with the survivors. */\n memmove(buf + dest, buf + src, pos - src);\n\n /* Reopen the file and write back just enough of the buffer. */\n freopen(argv[1], \"w\", fp);\n fwrite(buf, pos - src + dest, 1, fp);\n\n free(buf);\n fclose(fp);\n return 0;\n}"} {"title": "Rep-string", "language": "C", "task": "Given a series of ones and zeroes in a string, define a repeated string or ''rep-string'' as a string which is created by repeating a substring of the ''first'' N characters of the string ''truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original''.\n\nFor example, the string '''10011001100''' is a rep-string as the leftmost four characters of '''1001''' are repeated three times and truncated on the right to give the original string.\n\nNote that the requirement for having the repeat occur two or more times means that the repeating unit is ''never'' longer than half the length of the input string.\n\n\n;Task:\n* Write a function/subroutine/method/... that takes a string and returns an indication of if it is a rep-string and the repeated string. (Either the string that is repeated, or the number of repeated characters would suffice). \n* There may be multiple sub-strings that make a string a rep-string - in that case an indication of all, or the longest, or the shortest would suffice.\n* Use the function to indicate the repeating substring if any, in the following:\n\n\n1001110011\n1110111011\n0010010010\n1010101010\n1111111111\n0100101101\n0100100\n101\n11\n00\n1\n\n\n* Show your output on this page.\n\n\n\n", "solution": "#include \n#include \n\nint repstr(char *str)\n{\n if (!str) return 0;\n\n size_t sl = strlen(str) / 2;\n while (sl > 0) {\n if (strstr(str, str + sl) == str)\n return sl;\n --sl;\n }\n\n return 0;\n}\n\nint main(void)\n{\n char *strs[] = { \"1001110011\", \"1110111011\", \"0010010010\", \"1111111111\",\n \"0100101101\", \"0100100\", \"101\", \"11\", \"00\", \"1\" };\n\n size_t strslen = sizeof(strs) / sizeof(strs[0]);\n size_t i;\n for (i = 0; i < strslen; ++i) {\n int n = repstr(strs[i]);\n if (n)\n printf(\"\\\"%s\\\" = rep-string \\\"%.*s\\\"\\n\", strs[i], n, strs[i]);\n else\n printf(\"\\\"%s\\\" = not a rep-string\\n\", strs[i]);\n }\n\n return 0;\n}\n"} {"title": "Repeat", "language": "C", "task": "Write a procedure which accepts as arguments another procedure and a positive integer. \n\nThe latter procedure is executed a number of times equal to the accepted integer.\n\n", "solution": "#include \n\nvoid repeat(void (*f)(void), unsigned int n) {\n while (n-->0)\n (*f)(); //or just f()\n}\n\nvoid example() {\n printf(\"Example\\n\");\n}\n\nint main(int argc, char *argv[]) {\n repeat(example, 4);\n return 0;\n}\n"} {"title": "Resistor mesh", "language": "C", "task": "Given 10x10 grid nodes (as shown in the image) interconnected by 1O resistors as shown,\nfind the resistance between points '''A''' and '''B'''.\n\n\n;See also:\n* (humor, nerd sniping) xkcd.com cartoon (you can solve that for extra credits)\n* An article on how to calculate this and an implementation in Mathematica\n\n", "solution": "#include \n#include \n \n#define S 10\ntypedef struct { double v; int fixed; } node;\n \n#define each(i, x) for(i = 0; i < x; i++)\nnode **alloc2(int w, int h)\n{\n\tint i;\n\tnode **a = calloc(1, sizeof(node*)*h + sizeof(node)*w*h);\n\teach(i, h) a[i] = i ? a[i-1] + w : (node*)(a + h);\n\treturn a;\n}\n \nvoid set_boundary(node **m)\n{\n\tm[1][1].fixed = 1; m[1][1].v = 1;\n\tm[6][7].fixed = -1; m[6][7].v = -1;\n}\n \ndouble calc_diff(node **m, node **d, int w, int h)\n{\n\tint i, j, n;\n\tdouble v, total = 0;\n\teach(i, h) each(j, w) {\n\t\tv = 0; n = 0;\n\t\tif (i) v += m[i-1][j].v, n++;\n\t\tif (j) v += m[i][j-1].v, n++;\n\t\tif (i+1 < h) v += m[i+1][j].v, n++;\n\t\tif (j+1 < w) v += m[i][j+1].v, n++;\n \n\t\td[i][j].v = v = m[i][j].v - v / n;\n\t\tif (!m[i][j].fixed) total += v * v;\n\t}\n\treturn total;\n}\n \ndouble iter(node **m, int w, int h)\n{\n\tnode **d = alloc2(w, h);\n\tint i, j;\n\tdouble diff = 1e10;\n\tdouble cur[] = {0, 0, 0};\n\n\twhile (diff > 1e-24) {\n\t\tset_boundary(m);\n\t\tdiff = calc_diff(m, d, w, h);\n\t\teach(i,h) each(j, w) m[i][j].v -= d[i][j].v;\n\t}\n \n\teach(i, h) each(j, w)\n\t\tcur[ m[i][j].fixed + 1 ] += d[i][j].v *\n\t\t\t\t(!!i + !!j + (i < h-1) + (j < w -1));\n \n\tfree(d);\n\treturn (cur[2] - cur[0])/2;\n}\n \nint main()\n{\n\tnode **mesh = alloc2(S, S);\n\tprintf(\"R = %g\\n\", 2 / iter(mesh, S, S));\n\treturn 0;\n}"} {"title": "Reverse words in a string", "language": "C", "task": "Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.\n\n\n;Example:\nHey you, Bub! would be shown reversed as: Bub! you, Hey \n\n\nTokens are any non-space characters separated by spaces (formally, white-space); the visible punctuation form part of the word within which it is located and should not be modified. \n\nYou may assume that there are no significant non-visible characters in the input. Multiple or superfluous spaces may be compressed into a single space.\n\nSome strings have no tokens, so an empty string (or one just containing spaces) would be the result.\n\n'''Display''' the strings in order (1st, 2nd, 3rd, ***), and one string per line. \n\n(You can consider the ten strings as ten lines, and the tokens as words.)\n\n\n;Input data\n\n (ten lines within the box)\n line\n +----------------------------------------+\n 1 | ---------- Ice and Fire ------------ |\n 2 | | <--- a blank line here.\n 3 | fire, in end will world the say Some |\n 4 | ice. in say Some |\n 5 | desire of tasted I've what From |\n 6 | fire. favor who those with hold I |\n 7 | | <--- a blank line here.\n 8 | ... elided paragraph last ... |\n 9 | | <--- a blank line here.\n 10 | Frost Robert ----------------------- |\n +----------------------------------------+\n\n\n;Cf.\n* [[Phrase reversals]]\n\n", "solution": "#include \n#include \n\nvoid rev_print(char *s, int n)\n{\n for (; *s && isspace(*s); s++);\n if (*s) {\n char *e;\n for (e = s; *e && !isspace(*e); e++);\n rev_print(e, 0);\n printf(\"%.*s%s\", (int)(e - s), s, \" \" + n);\n }\n if (n) putchar('\\n');\n}\n\nint main(void)\n{\n char *s[] = {\n \"---------- Ice and Fire ------------\",\n \" \",\n \"fire, in end will world the say Some\",\n \"ice. in say Some \",\n \"desire of tasted I've what From \",\n \"fire. favor who those with hold I \",\n \" \",\n \"... elided paragraph last ... \",\n \" \",\n \"Frost Robert -----------------------\",\n 0\n };\n int i;\n for (i = 0; s[i]; i++) rev_print(s[i], 1);\n\n return 0;\n}"} {"title": "Roman numerals/Decode", "language": "C", "task": "Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. \n\nYou don't need to validate the form of the Roman numeral.\n\nModern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, \nstarting with the leftmost decimal digit and skipping any '''0'''s (zeroes). \n\n'''1990''' is rendered as '''MCMXC''' (1000 = M, 900 = CM, 90 = XC) and \n'''2008''' is rendered as '''MMVIII''' (2000 = MM, 8 = VIII).\n \nThe Roman numeral for '''1666''', '''MDCLXVI''', uses each letter in descending order.\n\n", "solution": "#include \n\nint digits[26] = { 0, 0, 100, 500, 0, 0, 0, 0, 1, 1, 0, 50, 1000, 0, 0, 0, 0, 0, 0, 0, 5, 5, 0, 10, 0, 0 };\n\n/* assuming ASCII, do upper case and get index in alphabet. could also be\n inline int VALUE(char x) { return digits [ (~0x20 & x) - 'A' ]; }\n if you think macros are evil */\n#define VALUE(x) digits[(~0x20 & (x)) - 'A']\n\nint decode(const char * roman)\n{\n const char *bigger;\n int current;\n int arabic = 0;\n while (*roman != '\\0') {\n current = VALUE(*roman);\n /* if (!current) return -1;\n note: -1 can be used as error code; Romans didn't even have zero\n */\n bigger = roman;\n\n /* look for a larger digit, like IV or XM */\n while (VALUE(*bigger) <= current && *++bigger != '\\0');\n\n if (*bigger == '\\0')\n arabic += current;\n else {\n arabic += VALUE(*bigger);\n while (roman < bigger)\n arabic -= VALUE(* (roman++) );\n }\n\n roman ++;\n }\n return arabic;\n}\n\nint main()\n{\n const char * romans[] = { \"MCmxC\", \"MMVIII\", \"MDClXVI\", \"MCXLUJ\" };\n int i;\n\n for (i = 0; i < 4; i++)\n printf(\"%s\\t%d\\n\", romans[i], decode(romans[i]));\n\n return 0;\n}"} {"title": "Roman numerals/Encode", "language": "C", "task": "Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. \n\n\nIn Roman numerals:\n* 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC\n* 2008 is written as 2000=MM, 8=VIII; or MMVIII\n* 1666 uses each Roman symbol in descending order: MDCLXVI\n\n", "solution": "#include \n\n\nint main() {\n int arabic[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};\n\n // There is a bug: \"XL\\0\" is translated into sequence 58 4C 00 00, i.e. it is 4-bytes long...\n // Should be \"XL\" without \\0 etc.\n //\n char roman[13][3] = {\"M\\0\", \"CM\\0\", \"D\\0\", \"CD\\0\", \"C\\0\", \"XC\\0\", \"L\\0\", \"XL\\0\", \"X\\0\", \"IX\\0\", \"V\\0\", \"IV\\0\", \"I\\0\"};\n int N;\n\n printf(\"Enter arabic number:\\n\");\n scanf(\"%d\", &N);\n printf(\"\\nRoman number:\\n\");\n\n for (int i = 0; i < 13; i++) {\n while (N >= arabic[i]) {\n printf(\"%s\", roman[i]);\n N -= arabic[i];\n }\n }\n return 0;\n}\n"} {"title": "Runge-Kutta method", "language": "C", "task": "Given the example Differential equation:\n:y'(t) = t \\times \\sqrt {y(t)}\nWith initial condition:\n:t_0 = 0 and y_0 = y(t_0) = y(0) = 1\nThis equation has an exact solution:\n:y(t) = \\tfrac{1}{16}(t^2 +4)^2\n\n\n;Task\nDemonstrate the commonly used explicit fourth-order Runge-Kutta method to solve the above differential equation.\n* Solve the given differential equation over the range t = 0 \\ldots 10 with a step value of \\delta t=0.1 (101 total points, the first being given)\n* Print the calculated values of y at whole numbered t's (0.0, 1.0, \\ldots 10.0) along with error as compared to the exact solution.\n\n\n;Method summary\nStarting with a given y_n and t_n calculate:\n:\\delta y_1 = \\delta t\\times y'(t_n, y_n)\\quad\n:\\delta y_2 = \\delta t\\times y'(t_n + \\tfrac{1}{2}\\delta t , y_n + \\tfrac{1}{2}\\delta y_1)\n:\\delta y_3 = \\delta t\\times y'(t_n + \\tfrac{1}{2}\\delta t , y_n + \\tfrac{1}{2}\\delta y_2)\n:\\delta y_4 = \\delta t\\times y'(t_n + \\delta t , y_n + \\delta y_3)\\quad\nthen:\n:y_{n+1} = y_n + \\tfrac{1}{6} (\\delta y_1 + 2\\delta y_2 + 2\\delta y_3 + \\delta y_4)\n:t_{n+1} = t_n + \\delta t\\quad\n\n", "solution": "#include \n#include \n#include \n\ndouble rk4(double(*f)(double, double), double dx, double x, double y)\n{\n\tdouble\tk1 = dx * f(x, y),\n\t\tk2 = dx * f(x + dx / 2, y + k1 / 2),\n\t\tk3 = dx * f(x + dx / 2, y + k2 / 2),\n\t\tk4 = dx * f(x + dx, y + k3);\n\treturn y + (k1 + 2 * k2 + 2 * k3 + k4) / 6;\n}\n\ndouble rate(double x, double y)\n{\n\treturn x * sqrt(y);\n}\n\nint main(void)\n{\n\tdouble *y, x, y2;\n\tdouble x0 = 0, x1 = 10, dx = .1;\n\tint i, n = 1 + (x1 - x0)/dx;\n\ty = (double *)malloc(sizeof(double) * n);\n\n\tfor (y[0] = 1, i = 1; i < n; i++)\n\t\ty[i] = rk4(rate, dx, x0 + dx * (i - 1), y[i-1]);\n\n\tprintf(\"x\\ty\\trel. err.\\n------------\\n\");\n\tfor (i = 0; i < n; i += 10) {\n\t\tx = x0 + dx * i;\n\t\ty2 = pow(x * x / 4 + 1, 2);\n\t\tprintf(\"%g\\t%g\\t%g\\n\", x, y[i], y[i]/y2 - 1);\n\t}\n\n\treturn 0;\n}"} {"title": "Sailors, coconuts and a monkey problem", "language": "C", "task": "Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. \n\nThat night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides \"his\" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed.\n\nTo cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey.\n\nIn the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.)\n\n\n;The task:\n# Calculate the minimum possible size of the initial pile of coconuts collected during the first day.\n# Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers ''are'' allowed.)\n# Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course).\n# Show your answers here.\n\n\n;Extra credit (optional):\n* Give some indication of the number of coconuts each sailor hides during the night.\n\n\n;Note:\n* Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics.\n* The tale is also told in a version where the monkey also gets a coconut in the morning. This is ''not'' that tale!\n\n\n;C.f:\n* Monkeys and Coconuts - Numberphile (Video) Analytical solution.\n* A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).\n\n", "solution": "#include \n \nint valid(int n, int nuts)\n{\n\tint k;\n\tfor (k = n; k; k--, nuts -= 1 + nuts/n)\n\t\tif (nuts%n != 1) return 0;\n\treturn nuts && !(nuts%n);\n}\n \nint main(void)\n{\n\tint n, x;\n\tfor (n = 2; n < 10; n++) {\n\t\tfor (x = 0; !valid(n, x); x++);\n\t\tprintf(\"%d: %d\\n\", n, x);\n\t}\n\treturn 0;\n}"} {"title": "Same fringe", "language": "C", "task": "Write a routine that will compare the leaves (\"fringe\") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.\n\nAny solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons.\n\nAny representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).\n\n", "solution": "#include \n#include \n#include \n\ntypedef struct {\n\tucontext_t caller, callee;\n\tchar stack[8192];\n\tvoid *in, *out;\n} co_t;\n\nco_t * co_new(void(*f)(), void *data)\n{\n\tco_t * c = malloc(sizeof(*c));\n\tgetcontext(&c->callee);\n\tc->in = data;\n\n\tc->callee.uc_stack.ss_sp = c->stack;\n\tc->callee.uc_stack.ss_size = sizeof(c->stack);\n\tc->callee.uc_link = &c->caller;\n\tmakecontext(&c->callee, f, 1, (int)c);\n\n\treturn c;\n}\n\nvoid co_del(co_t *c)\n{\n\tfree(c);\n}\n\ninline void\nco_yield(co_t *c, void *data)\n{\n\tc->out = data;\n\tswapcontext(&c->callee, &c->caller);\n}\n\ninline void *\nco_collect(co_t *c)\n{\n\tc->out = 0;\n\tswapcontext(&c->caller, &c->callee);\n\treturn c->out;\n}\n\n// end of coroutine stuff\n\ntypedef struct node node;\nstruct node {\n\tint v;\n\tnode *left, *right;\n};\n\nnode *newnode(int v)\n{\n\tnode *n = malloc(sizeof(node));\n\tn->left = n->right = 0;\n\tn->v = v;\n\treturn n;\n}\n\nvoid tree_insert(node **root, node *n)\n{\n\twhile (*root) root = ((*root)->v > n->v)\n\t\t\t\t? &(*root)->left\n\t\t\t\t: &(*root)->right;\n\t*root = n;\n}\n\nvoid tree_trav(int x)\n{\n\tco_t *c = (co_t *) x;\n\n\tvoid trav(node *root) {\n\t\tif (!root) return;\n\t\ttrav(root->left);\n\t\tco_yield(c, root);\n\t\ttrav(root->right);\n\t}\n\n\ttrav(c->in);\n}\n\nint tree_eq(node *t1, node *t2)\n{\n\tco_t *c1 = co_new(tree_trav, t1);\n\tco_t *c2 = co_new(tree_trav, t2);\n\n\tnode *p = 0, *q = 0;\n\tdo {\n\t\tp = co_collect(c1);\n\t\tq = co_collect(c2);\n\t} while (p && q && (p->v == q->v));\n\n\tco_del(c1);\n\tco_del(c2);\n\treturn !p && !q;\n}\n\nint main()\n{\n\tint x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1 };\n\tint y[] = { 2, 5, 7, 1, 9, 0, 6, 4, 8, 3, -1 };\n\tint z[] = { 0, 1, 2, 3, 4, 5, 6, 8, 9, -1 };\n\n\tnode *t1 = 0, *t2 = 0, *t3 = 0;\n\n\tvoid mktree(int *buf, node **root) {\n\t\tint i;\n\t\tfor (i = 0; buf[i] >= 0; i++)\n\t\t\ttree_insert(root, newnode(buf[i]));\n\t}\n\n\tmktree(x, &t1); // ordered binary tree, result of traversing\n\tmktree(y, &t2); // should be independent of insertion, so t1 == t2\n\tmktree(z, &t3);\n\n\tprintf(\"t1 == t2: %s\\n\", tree_eq(t1, t2) ? \"yes\" : \"no\");\n\tprintf(\"t1 == t3: %s\\n\", tree_eq(t1, t3) ? \"yes\" : \"no\");\n\n\treturn 0;\n}"} {"title": "Selectively replace multiple instances of a character within a string", "language": "C", "task": "Task\nThis is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it.\n\nGiven the string: \"abracadabra\", replace programatically:\n\n* the first 'a' with 'A'\n* the second 'a' with 'B'\n* the fourth 'a' with 'C'\n* the fifth 'a' with 'D'\n* the first 'b' with 'E'\n* the second 'r' with 'F'\n\nNote that there is no replacement for the third 'a', second 'b' or first 'r'.\n\nThe answer should, of course, be : \"AErBcadCbFD\".\n\n\n", "solution": "#include \n#include \n#include \n\nint main(void) {\n const char string[] = \"abracadabra\";\n\n char *replaced = malloc(sizeof(string));\n strcpy(replaced, string);\n\n // Null terminated replacement character arrays\n const char *aRep = \"ABaCD\";\n const char *bRep = \"E\";\n const char *rRep = \"rF\";\n\n for (char *c = replaced; *c; ++c) {\n switch (*c) {\n case 'a':\n if (*aRep)\n *c = *aRep++;\n break;\n case 'b':\n if (*bRep)\n *c = *bRep++;\n break;\n case 'r':\n if (*rRep)\n *c = *rRep++;\n break;\n }\n }\n\n printf(\"%s\\n\", replaced);\n\n free(replaced);\n return 0;\n}\n"} {"title": "Self-describing numbers", "language": "C", "task": "{{task}}There are several so-called \"self-describing\" or \"self-descriptive\" integers.\n\nAn integer is said to be \"self-describing\" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number.\n\nFor example, '''2020''' is a four-digit self describing number:\n\n* position 0 has value 2 and there are two 0s in the number;\n* position 1 has value 0 and there are no 1s in the number;\n* position 2 has value 2 and there are two 2s;\n* position 3 has value 0 and there are zero 3s.\n\n\nSelf-describing numbers < 100.000.000 are: 1210, 2020, 21200, 3211000, 42101000.\n\n\n;Task Description\n# Write a function/routine/method/... that will check whether a given positive integer is self-describing.\n# As an optional stretch goal - generate and display the set of self-describing numbers.\n\n\n;Related tasks:\n* [[Fours is the number of letters in the ...]]\n* [[Look-and-say sequence]]\n* [[Number names]]\n* [[Self-referential sequence]]\n* [[Spelling of ordinal numbers]]\n\n", "solution": "#include \n#include \n#include \n\n#define BASE_MIN 2\n#define BASE_MAX 94\n\nvoid selfdesc(unsigned long);\n\nconst char *ref = \"!\\\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\";\nchar *digs;\nunsigned long *nums, *inds, inds_sum, inds_val, base;\n\nint main(int argc, char *argv[]) {\nint used[BASE_MAX];\nunsigned long digs_n, i;\n\tif (argc != 2) {\n\t\tfprintf(stderr, \"Usage is %s \\n\", argv[0]);\n\t\treturn EXIT_FAILURE;\n\t}\n\tdigs = argv[1];\n\tdigs_n = strlen(digs);\n\tif (digs_n < BASE_MIN || digs_n > BASE_MAX) {\n\t\tfprintf(stderr, \"Invalid number of digits\\n\");\n\t\treturn EXIT_FAILURE;\n\t}\n\tfor (i = 0; i < BASE_MAX; i++) {\n\t\tused[i] = 0;\n\t}\n\tfor (i = 0; i < digs_n && strchr(ref, digs[i]) && !used[digs[i]-*ref]; i++) {\n\t\tused[digs[i]-*ref] = 1;\n\t}\n\tif (i < digs_n) {\n\t\tfprintf(stderr, \"Invalid digits\\n\");\n\t\treturn EXIT_FAILURE;\n\t}\n\tnums = calloc(digs_n, sizeof(unsigned long));\n\tif (!nums) {\n\t\tfprintf(stderr, \"Could not allocate memory for nums\\n\");\n\t\treturn EXIT_FAILURE;\n\t}\n\tinds = malloc(sizeof(unsigned long)*digs_n);\n\tif (!inds) {\n\t\tfprintf(stderr, \"Could not allocate memory for inds\\n\");\n\t\tfree(nums);\n\t\treturn EXIT_FAILURE;\n\t}\n\tinds_sum = 0;\n\tinds_val = 0;\n\tfor (base = BASE_MIN; base <= digs_n; base++) {\n\t\tselfdesc(base);\n\t}\n\tfree(inds);\n\tfree(nums);\n\treturn EXIT_SUCCESS;\n}\n\nvoid selfdesc(unsigned long i) {\nunsigned long diff_sum, upper_min, j, lower, upper, k;\n\tif (i) {\n\t\tdiff_sum = base-inds_sum;\n\t\tupper_min = inds_sum ? diff_sum:base-1;\n\t\tj = i-1;\n\t\tif (j) {\n\t\t\tlower = 0;\n\t\t\tupper = (base-inds_val)/j;\n\t\t}\n\t\telse {\n\t\t\tlower = diff_sum;\n\t\t\tupper = diff_sum;\n\t\t}\n\t\tif (upper < upper_min) {\n\t\t\tupper_min = upper;\n\t\t}\n\t\tfor (inds[j] = lower; inds[j] <= upper_min; inds[j]++) {\n\t\t\tnums[inds[j]]++;\n\t\t\tinds_sum += inds[j];\n\t\t\tinds_val += inds[j]*j;\n\t\t\tfor (k = base-1; k > j && nums[k] <= inds[k] && inds[k]-nums[k] <= i; k--);\n\t\t\tif (k == j) {\n\t\t\t\tselfdesc(i-1);\n\t\t\t}\n\t\t\tinds_val -= inds[j]*j;\n\t\t\tinds_sum -= inds[j];\n\t\t\tnums[inds[j]]--;\n\t\t}\n\t}\n\telse {\n\t\tfor (j = 0; j < base; j++) {\n\t\t\tputchar(digs[inds[j]]);\n\t\t}\n\t\tputs(\"\");\n\t}\n}"} {"title": "Semordnilap", "language": "C", "task": "A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. \"Semordnilap\" is a word that itself is a semordnilap.\n\nExample: ''lager'' and ''regal''\n \n;Task\nThis task does not consider semordnilap phrases, only single words.\nUsing only words from this list, report the total number of unique semordnilap pairs, and print 5 examples.\nTwo matching semordnilaps, such as ''lager'' and ''regal'', should be counted as one unique pair.\n(Note that the word \"semordnilap\" is not in the above dictionary.)\n\n\n\n", "solution": "#include \n#include \n#include /* stdlib.h might not have obliged. */\n#include \n\nstatic void reverse(char *s, int len)\n{\n int i, j;\n char tmp;\n\n for (i = 0, j = len - 1; i < len / 2; ++i, --j)\n tmp = s[i], s[i] = s[j], s[j] = tmp;\n}\n\n/* Wrap strcmp() for qsort(). */\nstatic int strsort(const void *s1, const void *s2)\n{\n return strcmp(*(char *const *) s1, *(char *const *) s2);\n}\n\nint main(void)\n{\n int i, c, ct = 0, len, sem = 0;\n char **words, **drows, tmp[24];\n FILE *dict = fopen(\"unixdict.txt\", \"r\");\n\n /* Determine word count. */\n while ((c = fgetc(dict)) != EOF)\n ct += c == '\\n';\n rewind(dict);\n\n /* Using alloca() is generally discouraged, but we're not doing\n * anything too fancy and the memory gains are significant. */\n words = alloca(ct * sizeof words);\n drows = alloca(ct * sizeof drows);\n\n for (i = 0; fscanf(dict, \"%s%n\", tmp, &len) != EOF; ++i) {\n /* Use just enough memory to store the next word. */\n strcpy(words[i] = alloca(len), tmp);\n\n /* Store it again, then reverse it. */\n strcpy(drows[i] = alloca(len), tmp);\n reverse(drows[i], len - 1);\n }\n\n fclose(dict);\n qsort(drows, ct, sizeof drows, strsort);\n\n /* Walk both sorted lists, checking only the words which could\n * possibly be a semordnilap pair for the current reversed word. */\n for (c = i = 0; i < ct; ++i) {\n while (strcmp(drows[i], words[c]) > 0 && c < ct - 1)\n c++;\n /* We found a semordnilap. */\n if (!strcmp(drows[i], words[c])) {\n strcpy(tmp, drows[i]);\n reverse(tmp, strlen(tmp));\n /* Unless it was a palindrome. */\n if (strcmp(drows[i], tmp) > 0 && sem++ < 5)\n printf(\"%s\\t%s\\n\", drows[i], tmp);\n }\n }\n\n printf(\"Semordnilap pairs: %d\\n\", sem);\n return 0;\n}"} {"title": "Set consolidation", "language": "C", "task": "Given two sets of items then if any item is common to any set then the result of applying ''consolidation'' to those sets is a set of sets whose contents is:\n* The two input sets if no common item exists between the two input sets of items.\n* The single set that is the union of the two input sets if they share a common item.\n\nGiven N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.\nIf N<2 then consolidation has no strict meaning and the input can be returned.\n\n;'''Example 1:'''\n:Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.\n;'''Example 2:'''\n:Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).\n;'''Example 3:'''\n:Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}\n;'''Example 4:'''\n:The consolidation of the five sets:\n::{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}\n:Is the two sets:\n::{A, C, B, D}, and {G, F, I, H, K}\n\n'''See also'''\n* Connected component (graph theory)\n* [[Range consolidation]]\n\n", "solution": "#include \n#include \n#include \n\nstruct edge { int to; struct edge *next; };\nstruct node { int group; struct edge *e; };\n\nint **consolidate(int **x)\n{\n#\tdefine alloc(v, size) v = calloc(size, sizeof(v[0]));\n\tint group, n_groups, n_nodes;\n\tint n_edges = 0;\n\tstruct edge *edges, *ep;\n\tstruct node *nodes;\n\tint pos, *stack, **ret;\n\n\tvoid add_edge(int a, int b) {\n\t\tep->to = b;\n\t\tep->next = nodes[a].e;\n\t\tnodes[a].e = ep;\n\t\tep++;\n\t}\n\n\tvoid traverse(int a) {\n\t\tif (nodes[a].group) return;\n\n\t\tnodes[a].group = group;\n\t\tstack[pos++] = a;\n\n\t\tfor (struct edge *e = nodes[a].e; e; e = e->next)\n\t\t\ttraverse(e->to);\n\t}\n\n\tn_groups = n_nodes = 0;\n\tfor (int i = 0; x[i]; i++, n_groups++)\n\t\tfor (int j = 0; x[i][j]; j++) {\n\t\t\tn_edges ++;\n\t\t\tif (x[i][j] >= n_nodes)\n\t\t\t\tn_nodes = x[i][j] + 1;\n\t\t}\n\n\talloc(ret, n_nodes);\n\talloc(nodes, n_nodes);\n\talloc(stack, n_nodes);\n\tep = alloc(edges, n_edges);\n\n\tfor (int i = 0; x[i]; i++)\n\t\tfor (int *s = x[i], j = 0; s[j]; j++)\n\t\t\tadd_edge(s[j], s[j + 1] ? s[j + 1] : s[0]);\n\n\tgroup = 0;\n\tfor (int i = 1; i < n_nodes; i++) {\n\t\tif (nodes[i].group) continue;\n\n\t\tgroup++, pos = 0;\n\t\ttraverse(i);\n\n\t\tstack[pos++] = 0;\n\t\tret[group - 1] = malloc(sizeof(int) * pos);\n\t\tmemcpy(ret[group - 1], stack, sizeof(int) * pos);\n\t}\n\n\tfree(edges);\n\tfree(stack);\n\tfree(nodes);\n\n\t// caller is responsible for freeing ret\n\treturn realloc(ret, sizeof(ret[0]) * (1 + group));\n#\tundef alloc\n}\n\nvoid show_sets(int **x)\n{\n\tfor (int i = 0; x[i]; i++) {\n\t\tprintf(\"%d: \", i);\n\t\tfor (int j = 0; x[i][j]; j++)\n\t\t\tprintf(\" %d\", x[i][j]);\n\t\tputchar('\\n');\n\t}\n}\n\nint main(void)\n{\n\tint *x[] = {\n\t\t(int[]) {1, 2, 0},\t// 0: end of set\n\t\t(int[]) {3, 4, 0},\n\t\t(int[]) {3, 1, 0},\n\t\t(int[]) {0},\t\t// empty set\n\t\t(int[]) {5, 6, 0},\n\t\t(int[]) {7, 6, 0},\n\t\t(int[]) {3, 9, 10, 0},\n\t\t0\t\t\t// 0: end of sets\n\t};\n\n\tputs(\"input:\");\n\tshow_sets(x);\n\n\tputs(\"components:\");\n\tshow_sets(consolidate(x));\n\n\treturn 0;\n}"} {"title": "Set of real numbers", "language": "C", "task": "All real numbers form the uncountable set R. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers ''a'' and ''b'' where ''a'' <= ''b''. There are actually four cases for the meaning of \"between\", depending on open or closed boundary:\n* [''a'', ''b'']: {''x'' | ''a'' <= ''x'' and ''x'' <= ''b'' }\n* (''a'', ''b''): {''x'' | ''a'' < ''x'' and ''x'' < ''b'' }\n* [''a'', ''b''): {''x'' | ''a'' <= ''x'' and ''x'' < ''b'' }\n* (''a'', ''b'']: {''x'' | ''a'' < ''x'' and ''x'' <= ''b'' }\nNote that if ''a'' = ''b'', of the four only [''a'', ''a''] would be non-empty.\n\n'''Task'''\n* Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below.\n* Provide methods for these common set operations (''x'' is a real number; ''A'' and ''B'' are sets):\n:* ''x'' ''A'': determine if ''x'' is an element of ''A''\n:: example: 1 is in [1, 2), while 2, 3, ... are not.\n:* ''A'' ''B'': union of ''A'' and ''B'', i.e. {''x'' | ''x'' ''A'' or ''x'' ''B''}\n:: example: [0, 2) (1, 3) = [0, 3); [0, 1) (2, 3] = well, [0, 1) (2, 3]\n:* ''A'' ''B'': intersection of ''A'' and ''B'', i.e. {''x'' | ''x'' ''A'' and ''x'' ''B''}\n:: example: [0, 2) (1, 3) = (1, 2); [0, 1) (2, 3] = empty set\n:* ''A'' - ''B'': difference between ''A'' and ''B'', also written as ''A'' \\ ''B'', i.e. {''x'' | ''x'' ''A'' and ''x'' ''B''}\n:: example: [0, 2) - (1, 3) = [0, 1]\n* Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets:\n:* (0, 1] [0, 2)\n:* [0, 2) (1, 2]\n:* [0, 3) - (0, 1)\n:* [0, 3) - [0, 1]\n\n'''Implementation notes'''\n* 'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'. Cantor's set needs not apply.\n* Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored.\n* You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is).\n\n'''Optional work'''\n* Create a function to determine if a given set is empty (contains no element).\n* Define ''A'' = {''x'' | 0 < ''x'' < 10 and |sin(p ''x''2)| > 1/2 }, ''B'' = {''x'' | 0 < ''x'' < 10 and |sin(p ''x'')| > 1/2}, calculate the length of the real axis covered by the set ''A'' - ''B''. Note that \n|sin(p ''x'')| > 1/2 is the same as ''n'' + 1/6 < ''x'' < ''n'' + 5/6 for all integers ''n''; your program does not need to derive this by itself.\n\n", "solution": "#include \n#include \n#include \n#include \n\nstruct RealSet {\n bool(*contains)(struct RealSet*, struct RealSet*, double);\n struct RealSet *left;\n struct RealSet *right;\n double low, high;\n};\n\ntypedef enum {\n CLOSED,\n LEFT_OPEN,\n RIGHT_OPEN,\n BOTH_OPEN,\n} RangeType;\n\ndouble length(struct RealSet *self) {\n const double interval = 0.00001;\n double p = self->low;\n int count = 0;\n\n if (isinf(self->low) || isinf(self->high)) return -1.0;\n if (self->high <= self->low) return 0.0;\n\n do {\n if (self->contains(self, NULL, p)) count++;\n p += interval;\n } while (p < self->high);\n return count * interval;\n}\n\nbool empty(struct RealSet *self) {\n if (self->low == self->high) {\n return !self->contains(self, NULL, self->low);\n }\n return length(self) == 0.0;\n}\n\nstatic bool contains_closed(struct RealSet *self, struct RealSet *_, double d) {\n return self->low <= d && d <= self->high;\n}\n\nstatic bool contains_left_open(struct RealSet *self, struct RealSet *_, double d) {\n return self->low < d && d <= self->high;\n}\n\nstatic bool contains_right_open(struct RealSet *self, struct RealSet *_, double d) {\n return self->low <= d && d < self->high;\n}\n\nstatic bool contains_both_open(struct RealSet *self, struct RealSet *_, double d) {\n return self->low < d && d < self->high;\n}\n\nstatic bool contains_intersect(struct RealSet *self, struct RealSet *_, double d) {\n return self->left->contains(self->left, NULL, d) && self->right->contains(self->right, NULL, d);\n}\n\nstatic bool contains_union(struct RealSet *self, struct RealSet *_, double d) {\n return self->left->contains(self->left, NULL, d) || self->right->contains(self->right, NULL, d);\n}\n\nstatic bool contains_subtract(struct RealSet *self, struct RealSet *_, double d) {\n return self->left->contains(self->left, NULL, d) && !self->right->contains(self->right, NULL, d);\n}\n\nstruct RealSet* makeSet(double low, double high, RangeType type) {\n bool(*contains)(struct RealSet*, struct RealSet*, double);\n struct RealSet *rs;\n\n switch (type) {\n case CLOSED:\n contains = contains_closed;\n break;\n case LEFT_OPEN:\n contains = contains_left_open;\n break;\n case RIGHT_OPEN:\n contains = contains_right_open;\n break;\n case BOTH_OPEN:\n contains = contains_both_open;\n break;\n default:\n return NULL;\n }\n\n rs = malloc(sizeof(struct RealSet));\n rs->contains = contains;\n rs->left = NULL;\n rs->right = NULL;\n rs->low = low;\n rs->high = high;\n return rs;\n}\n\nstruct RealSet* makeIntersect(struct RealSet *left, struct RealSet *right) {\n struct RealSet *rs = malloc(sizeof(struct RealSet));\n rs->contains = contains_intersect;\n rs->left = left;\n rs->right = right;\n rs->low = fmin(left->low, right->low);\n rs->high = fmin(left->high, right->high);\n return rs;\n}\n\nstruct RealSet* makeUnion(struct RealSet *left, struct RealSet *right) {\n struct RealSet *rs = malloc(sizeof(struct RealSet));\n rs->contains = contains_union;\n rs->left = left;\n rs->right = right;\n rs->low = fmin(left->low, right->low);\n rs->high = fmin(left->high, right->high);\n return rs;\n}\n\nstruct RealSet* makeSubtract(struct RealSet *left, struct RealSet *right) {\n struct RealSet *rs = malloc(sizeof(struct RealSet));\n rs->contains = contains_subtract;\n rs->left = left;\n rs->right = right;\n rs->low = left->low;\n rs->high = left->high;\n return rs;\n}\n\nint main() {\n struct RealSet *a = makeSet(0.0, 1.0, LEFT_OPEN);\n struct RealSet *b = makeSet(0.0, 2.0, RIGHT_OPEN);\n struct RealSet *c = makeSet(1.0, 2.0, LEFT_OPEN);\n struct RealSet *d = makeSet(0.0, 3.0, RIGHT_OPEN);\n struct RealSet *e = makeSet(0.0, 1.0, BOTH_OPEN);\n struct RealSet *f = makeSet(0.0, 1.0, CLOSED);\n struct RealSet *g = makeSet(0.0, 0.0, CLOSED);\n int i;\n\n for (i = 0; i < 3; ++i) {\n struct RealSet *t;\n\n t = makeUnion(a, b);\n printf(\"(0, 1] union [0, 2) contains %d is %d\\n\", i, t->contains(t, NULL, i));\n free(t);\n\n t = makeIntersect(b, c);\n printf(\"[0, 2) intersect (1, 2] contains %d is %d\\n\", i, t->contains(t, NULL, i));\n free(t);\n\n t = makeSubtract(d, e);\n printf(\"[0, 3) - (0, 1) contains %d is %d\\n\", i, t->contains(t, NULL, i));\n free(t);\n\n t = makeSubtract(d, f);\n printf(\"[0, 3) - [0, 1] contains %d is %d\\n\", i, t->contains(t, NULL, i));\n free(t);\n\n printf(\"\\n\");\n }\n\n printf(\"[0, 0] is empty %d\\n\", empty(g));\n\n free(a);\n free(b);\n free(c);\n free(d);\n free(e);\n free(f);\n free(g);\n\n return 0;\n}"} {"title": "Shoelace formula for polygonal area", "language": "C", "task": "Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:\n\nabs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -\n (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])\n ) / 2\n(Where abs returns the absolute value)\n\n;Task:\nWrite a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:\n (3,4), (5,11), (12,8), (9,5), and (5,6) \n\n\nShow the answer here, on this page.\n\n", "solution": "#include\n#include\n#include\n\ntypedef struct{\n\tdouble x,y;\n}point;\n\ndouble shoelace(char* inputFile){\n\tint i,numPoints;\n\tdouble leftSum = 0,rightSum = 0;\n\t\n\tpoint* pointSet;\n\tFILE* fp = fopen(inputFile,\"r\");\n\t\n\tfscanf(fp,\"%d\",&numPoints);\n\t\n\tpointSet = (point*)malloc((numPoints + 1)*sizeof(point));\n\t\n\tfor(i=0;i\",argV[0]);\n\t\n\telse\n\t\tprintf(\"The polygon area is %lf square units.\",shoelace(argV[1]));\n\t\n\treturn 0;\n}\n"} {"title": "Shortest common supersequence", "language": "C", "task": "The '''shortest common supersequence''' is a problem closely related to the [[longest common subsequence]], which you can use as an external function for this task.\n\n\n;;Task:\nGiven two strings u and v, find the shortest possible sequence s, which is the shortest common super-sequence of u and v where both u and v are a subsequence of s. Defined as such, s is not necessarily unique.\n\nDemonstrate this by printing s where u = \"abcbdab\" and v = \"bdcaba\".\n\n\n\n;Also see:\n* Wikipedia: shortest common supersequence \n\n", "solution": "#include \n#include \n\ntypedef struct link link_t;\nstruct link {\n\tint len;\n\tchar letter;\n\tlink_t *next;\n};\n\n// Stores a copy of a SCS of x and y in out. Caller needs to make sure out is long enough.\nint scs(char *x, char *y, char *out)\n{\n\tint lx = strlen(x), ly = strlen(y);\n\tlink_t lnk[ly + 1][lx + 1];\n\t\n\tfor (int i = 0; i < ly; i++)\n\t\tlnk[i][lx] = (link_t) {ly - i, y[i], &lnk[i + 1][lx]};\n\n\tfor (int j = 0; j < lx; j++)\n\t\tlnk[ly][j] = (link_t) {lx - j, x[j], &lnk[ly][j + 1]};\n\n\tlnk[ly][lx] = (link_t) {0};\n\n\tfor (int i = ly; i--; ) {\n\t\tfor (int j = lx; j--; ) {\n\t\t\tlink_t *lp = &lnk[i][j];\n\t\t\tif (y[i] == x[j]) {\n\t\t\t\tlp->next = &lnk[i+1][j+1];\n\t\t\t\tlp->letter = x[j];\n\t\t\t} else if (lnk[i][j+1].len < lnk[i+1][j].len) {\n\t\t\t\tlp->next = &lnk[i][j+1];\n\t\t\t\tlp->letter = x[j];\n\t\t\t} else {\n\t\t\t\tlp->next = &lnk[i+1][j];\n\t\t\t\tlp->letter = y[i];\n\t\t\t}\n\t\t\tlp->len = lp->next->len + 1;\n\t\t}\n\t}\n\n\tfor (link_t *lp = &lnk[0][0]; lp; lp = lp->next)\n\t\t*out++ = lp->letter;\n\n\treturn 0;\n}\n\nint main(void)\n{\n\tchar x[] = \"abcbdab\", y[] = \"bdcaba\", res[128];\n\tscs(x, y, res);\n\tprintf(\"SCS(%s, %s) -> %s\\n\", x, y, res);\n\treturn 0;\n}"} {"title": "Show the epoch", "language": "C", "task": "Choose popular date libraries used by your language and show the epoch those libraries use. \n\nA demonstration is preferable (e.g. setting the internal representation of the date to 0 ms/ns/etc., or another way that will still show the epoch even if it is changed behind the scenes by the implementers), but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. \n\nFor consistency's sake, show the date in UTC time where possible.\n\n\n;Related task:\n* [[Date format]]\n\n", "solution": "#include \n#include \n\nint main() {\n time_t t = 0;\n printf(\"%s\", asctime(gmtime(&t)));\n return 0;\n}"} {"title": "Sierpinski pentagon", "language": "C", "task": "Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4.\n\n\n;See also\n* Sierpinski pentagon\n\n", "solution": "#include\n#include\n#include\n#include\n#include\n\n#define pi M_PI\n\nint main(){\n\t\n\ttime_t t;\n\tdouble side, **vertices,seedX,seedY,windowSide = 500,sumX=0,sumY=0;\n\tint i,iter,choice,numSides;\n\t\n\tprintf(\"Enter number of sides : \");\n\tscanf(\"%d\",&numSides);\n\t\n\tprintf(\"Enter polygon side length : \");\n\tscanf(\"%lf\",&side);\n\t\n\tprintf(\"Enter number of iterations : \");\n\tscanf(\"%d\",&iter);\n\n\tinitwindow(windowSide,windowSide,\"Polygon Chaos\");\n\t\n\tvertices = (double**)malloc(numSides*sizeof(double*));\n\t\n\tfor(i=0;i\n#include \n#include \n#include \n \nlong long x, y, dx, dy, scale, clen, cscale;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n \nvoid sc_up()\n{\n\tscale *= 2; x *= 2; y *= 2;\n\tcscale *= 3;\n}\n \nvoid h_rgb(long long x, long long y)\n{\n\trgb *p = &pix[y][x];\n \n#\tdefine SAT 1\n\tdouble h = 6.0 * clen / cscale;\n\tdouble VAL = 1;\n\tdouble c = SAT * VAL;\n\tdouble X = c * (1 - fabs(fmod(h, 2) - 1));\n \n\tswitch((int)h) {\n\tcase 0: p->r += c; p->g += X; return;\n\tcase 1:\tp->r += X; p->g += c; return;\n\tcase 2: p->g += c; p->b += X; return;\n\tcase 3: p->g += X; p->b += c; return;\n\tcase 4: p->r += X; p->b += c; return;\n\tdefault:\n\t\tp->r += c; p->b += X;\n\t}\n}\n \nvoid iter_string(const char * str, int d)\n{\n\tlong long len;\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\n\t\t\tif (d)\titer_string(\"XHXVX\", d - 1);\n\t\t\telse{\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx;\n\t\t\t\ty -= dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'V':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile (len--) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\ty += dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'H':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile(len --) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx -= dx;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t}\n}\n \nvoid sierp(long leng, int depth)\n{\n\tlong i;\n\tlong h = leng + 20, w = leng + 20;\n \n\t/* allocate pixel buffer */\n\trgb *buf = malloc(sizeof(rgb) * w * h);\n\tpix = malloc(sizeof(rgb *) * h);\n\tfor (i = 0; i < h; i++)\n\t\tpix[i] = buf + w * i;\n\tmemset(buf, 0, sizeof(rgb) * w * h);\n \n /* init coords; scale up to desired; exec string */\n\tx = y = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"VXH\", depth);\n \n\t/* write color PNM file */\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\n \n\tfor (i = 3 * w * h - 1; i >= 0; i--)\n\t\tif (dbuf[i] > maxv) maxv = dbuf[i];\n\tfor (i = 3 * h * w - 1; i >= 0; i--)\n\t\tfpix[i] = 255 * dbuf[i] / maxv;\n \n\tprintf(\"P6\\n%ld %ld\\n255\\n\", w, h);\n\tfflush(stdout); /* printf and fwrite may treat buffer differently */\n\tfwrite(fpix, h * w * 3, 1, stdout);\n}\n \nint main(int c, char ** v)\n{\n\tint size, depth;\n \n\tdepth = (c > 1) ? atoi(v[1]) : 10;\n\tsize = 1 << depth;\n \n\tfprintf(stderr, \"size: %d depth: %d\\n\", size, depth);\n\tsierp(size, depth + 2);\n \n\treturn 0;\n}"} {"title": "Soloway's recurring rainfall", "language": "C", "task": "Soloway's Recurring Rainfall is commonly used to assess general programming knowledge by requiring basic program structure, input/output, and program exit procedure.\n\n'''The problem:'''\n\nWrite a program that will read in integers and output their average. Stop reading when the value 99999 is input.\n\nFor languages that aren't traditionally interactive, the program can read in values as makes sense and stopping once 99999 is encountered. The classic rainfall problem comes from identifying success of Computer Science programs with their students, so the original problem statement is written above -- though it may not strictly apply to a given language in the modern era.\n\n'''Implementation Details:'''\n* Only Integers are to be accepted as input\n* Output should be floating point\n* Rainfall can be negative (https://www.geographyrealm.com/what-is-negative-rainfall/)\n* For languages where the user is inputting data, the number of data inputs can be \"infinite\"\n* A complete implementation should handle error cases reasonably (asking the user for more input, skipping the bad value when encountered, etc)\n\nThe purpose of this problem, as originally proposed in the 1980's through its continued use today, is to just show fundamentals of CS: iteration, branching, program structure, termination, management of data types, input/output (where applicable), etc with things like input validation or management of numerical limits being more \"advanced\". It isn't meant to literally be a rainfall calculator so implementations should strive to implement the solution clearly and simply.\n\n'''References:'''\n* http://cs.brown.edu/~kfisler/Pubs/icer14-rainfall/icer14.pdf\n* https://www.curriculumonline.ie/getmedia/8bb01bff-509e-48ed-991e-3ab5dad74a78/Seppletal-2015-DoweknowhowdifficulttheRainfallProblemis.pdf\n* https://en.wikipedia.org/wiki/Moving_average#Cumulative_average\n\n\n", "solution": "#include \n\nint main(int argc, char **argv)\n{\n\t// Unused variables\n\t(void)argc;\n\t(void)argv;\n\t\n\tfloat currentAverage = 0;\n\tunsigned int currentEntryNumber = 0;\n\t\n\tfor (;;)\n\t{\n\t\tint ret, entry;\n\t\t\n\t\tprintf(\"Enter rainfall int, 99999 to quit: \");\n\t\tret = scanf(\"%d\", &entry);\n\t\t\n\t\tif (ret)\n\t\t{\n\t\t\tif (entry == 99999)\n\t\t\t{\n\t\t\t\tprintf(\"User requested quit.\\n\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcurrentEntryNumber++;\n\t\t\t\tcurrentAverage = currentAverage + (1.0f/currentEntryNumber)*entry - (1.0f/currentEntryNumber)*currentAverage;\n\t\t\t\t\n\t\t\t\tprintf(\"New Average: %f\\n\", currentAverage);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tprintf(\"Invalid input\\n\");\n\t\t\twhile (getchar() != '\\n');\t// Clear input buffer before asking again\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n"} {"title": "Solve a Hidato puzzle", "language": "C", "task": "The task is to write a program which solves Hidato (aka Hidoku) puzzles.\n\nThe rules are:\n* You are given a grid with some numbers placed in it. The other squares in the grid will be blank.\n** The grid is not necessarily rectangular.\n** The grid may have holes in it.\n** The grid is always connected.\n** The number \"1\" is always present, as is another number that is equal to the number of squares in the grid. Other numbers are present so as to force the solution to be unique.\n** It may be assumed that the difference between numbers present on the grid is not greater than lucky 13.\n* The aim is to place a natural number in each blank square so that in the sequence of numbered squares from \"1\" upwards, each square is in the [[wp:Moore neighborhood]] of the squares immediately before and after it in the sequence (except for the first and last squares, of course, which only have one-sided constraints).\n** Thus, if the grid was overlaid on a chessboard, a king would be able to make legal moves along the path from first to last square in numerical order.\n** A square may only contain one number.\n* In a proper Hidato puzzle, the solution is unique.\n\nFor example the following problem\nSample Hidato problem, from Wikipedia\n\nhas the following solution, with path marked on it:\n\nSolution to sample Hidato problem\n\n\n;Related tasks:\n* [[A* search algorithm]]\n* [[N-queens problem]]\n* [[Solve a Holy Knight's tour]]\n* [[Solve a Knight's tour]]\n* [[Solve a Hopido puzzle]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]];\n\n", "solution": "#include \n#include \n#include \n#include \n\nint *board, *flood, *known, top = 0, w, h;\n\nstatic inline int idx(int y, int x) { return y * w + x; }\n\nint neighbors(int c, int *p)\n/*\n@c cell\n@p list of neighbours\n@return amount of neighbours\n*/\n{\n\tint i, j, n = 0;\n\tint y = c / w, x = c % w;\n\n\tfor (i = y - 1; i <= y + 1; i++) {\n\t\tif (i < 0 || i >= h) continue;\n\t\tfor (j = x - 1; j <= x + 1; j++)\n\t\t\tif (!(j < 0 || j >= w\n\t\t\t\t|| (j == x && i == y)\n\t\t\t\t|| board[ p[n] = idx(i,j) ] == -1))\n\t\t\t\tn++;\n\t}\n\n\treturn n;\n}\n\nvoid flood_fill(int c)\n/*\nfill all free cells around @c with \u201c1\u201d and write output to variable \u201cflood\u201d\n@c cell\n*/\n{\n\tint i, n[8], nei;\n\n\tnei = neighbors(c, n);\n\tfor (i = 0; i < nei; i++) { // for all neighbours\n\t\tif (board[n[i]] || flood[n[i]]) continue; // if cell is not free, choose another neighbour\n\n\t\tflood[n[i]] = 1;\n\t\tflood_fill(n[i]);\n\t}\n}\n\n/* Check all empty cells are reachable from higher known cells.\n Should really do more checks to make sure cell_x and cell_x+1\n share enough reachable empty cells; I'm lazy. Will implement\n if a good counter example is presented. */\nint check_connectity(int lowerbound)\n{\n\tint c;\n\tmemset(flood, 0, sizeof(flood[0]) * w * h);\n\tfor (c = lowerbound + 1; c <= top; c++)\n\t\tif (known[c]) flood_fill(known[c]); // mark all free cells around known cells\n\n\tfor (c = 0; c < w * h; c++)\n\t\tif (!board[c] && !flood[c]) // if there are free cells which could not be reached from flood_fill\n\t\t\treturn 0;\n\n\treturn 1;\n}\n\nvoid make_board(int x, int y, const char *s)\n{\n\tint i;\n\n\tw = x, h = y;\n top = 0;\n\tx = w * h;\n\n known = calloc(x + 1, sizeof(int));\n board = calloc(x, sizeof(int));\n flood = calloc(x, sizeof(int));\n\n\twhile (x--) board[x] = -1;\n\n\tfor (y = 0; y < h; y++)\n\tfor (x = 0; x < w; x++) {\n\t\ti = idx(y, x);\n\n\t\twhile (isspace(*s)) s++;\n\n\t\tswitch (*s) {\n\t\tcase '_':\tboard[i] = 0;\n\t\tcase '.':\tbreak;\n\t\tdefault:\n\t\t\tknown[ board[i] = strtol(s, 0, 10) ] = i;\n\t\t\tif (board[i] > top) top = board[i];\n\t\t}\n\n\t\twhile (*s && !isspace(*s)) s++;\n\t}\n}\n\nvoid show_board(const char *s)\n{\n\tint i, j, c;\n\n\tprintf(\"\\n%s:\\n\", s);\n\n\tfor (i = 0; i < h; i++, putchar('\\n'))\n\tfor (j = 0; j < w; j++) {\n\t\tc = board[ idx(i, j) ];\n\t\tprintf(!c ? \" __\" : c == -1 ? \" \" : \" %2d\", c);\n\t}\n}\n\nint fill(int c, int n)\n{\n\tint i, nei, p[8], ko, bo;\n\n\tif ((board[c] && board[c] != n) || (known[n] && known[n] != c))\n\t\treturn 0;\n\n\tif (n == top) return 1;\n\n\tko = known[n];\n\tbo = board[c];\n\tboard[c] = n;\n\n\tif (check_connectity(n)) {\n\t\tnei = neighbors(c, p);\n\t\tfor (i = 0; i < nei; i++)\n\t\t\tif (fill(p[i], n + 1))\n\t\t\t\treturn 1;\n\t}\n\n\tboard[c] = bo;\n\tknown[n] = ko;\n\treturn 0;\n}\n\nint main()\n{\n\tmake_board(\n#define USE_E 0\n#if (USE_E == 0)\n\t\t8,8,\t\" __ 33 35 __ __ .. .. ..\"\n\t\t\t\" __ __ 24 22 __ .. .. ..\"\n\t\t\t\" __ __ __ 21 __ __ .. ..\"\n\t\t\t\" __ 26 __ 13 40 11 .. ..\"\n\t\t\t\" 27 __ __ __ 9 __ 1 ..\"\n\t\t\t\" . . __ __ 18 __ __ ..\"\n\t\t\t\" . .. . . __ 7 __ __\"\n\t\t\t\" . .. .. .. . . 5 __\"\n#elif (USE_E == 1)\n\t3, 3,\t\" . 4 .\"\n\t\t\" _ 7 _\"\n\t\t\" 1 _ _\"\n#else\n\t50, 3,\n\t\" 1 _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . 74\"\n\t\" . . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ .\"\n\t\" . . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ .\"\n#endif\n\t);\n\n\tshow_board(\"Before\");\n\tfill(known[1], 1);\n\tshow_board(\"After\"); /* \"40 lbs in two weeks!\" */\n\n\treturn 0;\n}"} {"title": "Sparkline in unicode", "language": "C", "task": "A sparkline is a graph of successive values laid out horizontally \nwhere the height of the line is proportional to the values in succession.\n\n\n;Task:\nUse the following series of Unicode characters to create a program \nthat takes a series of numbers separated by one or more whitespace or comma characters \nand generates a sparkline-type bar graph of the values on a single line of output.\n\nThe eight characters: '########'\n(Unicode values U+2581 through U+2588).\n\nUse your program to show sparklines for the following input, \nhere on this page:\n# 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1\n# 1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 \n:(note the mix of separators in this second case)!\n\n;Notes: \n* A space is not part of the generated sparkline.\n* The sparkline may be accompanied by simple statistics of the data such as its range.\n* A suggestion emerging in later discussion (see Discussion page) is that the bounds between bins should ideally be set to yield the following results for two particular edge cases:\n\n:: \"0, 1, 19, 20\" -> ####\n:: (Aiming to use just two spark levels)\n\n:: \"0, 999, 4000, 4999, 7000, 7999\" -> ######\n:: (Aiming to use just three spark levels)\n\n:: It may be helpful to include these cases in output tests.\n* You may find that the unicode sparklines on this page are rendered less noisily by Google Chrome than by Firefox or Safari.\n\n", "solution": "#include\n#include\n#include\n#include\n#include\n#include\n\nint main(int argC,char* argV[])\n{\n\tdouble* arr,min,max;\n\tchar* str;\n\tint i,len;\n\tif(argC == 1)\n\t\tprintf(\"Usage : %s \",argV[0]);\n\telse{\n\t\tarr = (double*)malloc((argC-1)*sizeof(double));\n\t\tfor(i=1;iarr[i-1]?max:arr[i-1]);\n\t\t\t}\n\t\t}\n\t\t\n\t\tprintf(\"\\n%Max : %lf,Min : %lf,Range : %lf\\n\",max,min,max-min);\n\t\t\n\t\tsetlocale(LC_ALL, \"\");\n\t\t\n\t\tfor(i=1;i\n#include \n#include \nchar *split(char *str);\nint main(int argc,char **argv)\n{\n\tchar input[13]=\"gHHH5YY++///\\\\\";\n\tprintf(\"%s\\n\",split(input));\n}\nchar *split(char *str)\n{\n\tchar last=*str,*result=malloc(3*strlen(str)),*counter=result;\n\tfor (char *c=str;*c;c++) {\n\t\tif (*c!=last) {\n\t\t\tstrcpy(counter,\", \");\n\t\t\tcounter+=2;\n\t\t\tlast=*c;\n\t\t}\n\t\t*counter=*c;\n\t\tcounter++;\n\t}\n\t*(counter--)='\\0';\n\treturn realloc(result,strlen(result));\n}"} {"title": "Square but not cube", "language": "C", "task": "Show the first '''30''' positive integers which are squares but not cubes of such integers.\n\nOptionally, show also the first '''3''' positive integers which are both squares and cubes, and mark them as such.\n\n", "solution": "#include \n#include \n\nint main() {\n int n = 1, count = 0, sq, cr;\n for ( ; count < 30; ++n) {\n sq = n * n;\n cr = (int)cbrt((double)sq);\n if (cr * cr * cr != sq) {\n count++;\n printf(\"%d\\n\", sq);\n }\n else {\n printf(\"%d is square and cube\\n\", sq);\n }\n }\n return 0;\n}"} {"title": "Stair-climbing puzzle", "language": "C", "task": "From Chung-Chieh Shan (LtU):\n\nYour stair-climbing robot has a very simple low-level API: the \"step\" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The \"step\" function detects what happens and returns a boolean flag: true on success, false on failure. \n\nWrite a function \"step_up\" that climbs one step up [from the initial position] (by repeating \"step\" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make \"step_up\"? Can you avoid using variables (even immutable ones) and numbers?\n\nHere's a pseudo-code of a simple recursive solution without using variables:\n\nfunc step_up()\n{\n if not step() {\n step_up();\n step_up();\n }\n}\n\nInductive proof that step_up() steps up one step, if it terminates:\n* Base case (if the step() call returns true): it stepped up one step. QED\n* Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED\n\n\nThe second (tail) recursion above can be turned into an iteration, as follows:\n\nfunc step_up()\n{\n while not step() {\n step_up();\n }\n}\n\n", "solution": "void step_up(void)\n{\n int i = 0;\n\n while (i < 1) {\n if (step()) {\n ++i;\n } else {\n --i;\n }\n }\n}"} {"title": "Start from a main routine", "language": "C", "task": "Some languages (like Gambas and Visual Basic) support two startup modes. Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead. Data driven or event driven languages may also require similar trickery to force a startup procedure to run.\n\n\n;Task:\nDemonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup.\n\nLanguages that always run from main() can be omitted from this task.\n\n", "solution": "#include\n\n#define start main()\n\nint start\n{\n\tprintf(\"Hello World !\");\n\treturn 0;\n}\n"} {"title": "Statistics/Normal distribution", "language": "C", "task": "The derive normally distributed random numbers from a uniform generator.\n\n\n;The task:\n# Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data.\n# Mention any native language support for the generation of normally distributed random numbers.\n\n\n;Reference:\n* You may refer to code in [[Statistics/Basic]] if available.\n\n", "solution": "/*\n * RosettaCode example: Statistics/Normal distribution in C\n *\n * The random number generator rand() of the standard C library is obsolete\n * and should not be used in more demanding applications. There are plenty\n * libraries with advanced features (eg. GSL) with functions to calculate \n * the mean, the standard deviation, generating random numbers etc. \n * However, these features are not the core of the standard C library.\n */\n#include \n#include \n#include \n#include \n#include \n\n\n#define NMAX 10000000\n\n\ndouble mean(double* values, int n)\n{\n int i;\n double s = 0;\n\n for ( i = 0; i < n; i++ )\n s += values[i];\n return s / n;\n}\n\n\ndouble stddev(double* values, int n)\n{\n int i;\n double average = mean(values,n);\n double s = 0;\n\n for ( i = 0; i < n; i++ )\n s += (values[i] - average) * (values[i] - average);\n return sqrt(s / (n - 1));\n}\n\n/*\n * Normal random numbers generator - Marsaglia algorithm.\n */\ndouble* generate(int n)\n{\n int i;\n int m = n + n % 2;\n double* values = (double*)calloc(m,sizeof(double));\n double average, deviation;\n\n if ( values )\n {\n for ( i = 0; i < m; i += 2 )\n {\n double x,y,rsq,f;\n do {\n x = 2.0 * rand() / (double)RAND_MAX - 1.0;\n y = 2.0 * rand() / (double)RAND_MAX - 1.0;\n rsq = x * x + y * y;\n }while( rsq >= 1. || rsq == 0. );\n f = sqrt( -2.0 * log(rsq) / rsq );\n values[i] = x * f;\n values[i+1] = y * f;\n }\n }\n return values;\n}\n\n\nvoid printHistogram(double* values, int n)\n{\n const int width = 50; \n int max = 0;\n\n const double low = -3.05;\n const double high = 3.05;\n const double delta = 0.1;\n\n int i,j,k;\n int nbins = (int)((high - low) / delta);\n int* bins = (int*)calloc(nbins,sizeof(int));\n if ( bins != NULL )\n {\n for ( i = 0; i < n; i++ )\n {\n int j = (int)( (values[i] - low) / delta );\n if ( 0 <= j && j < nbins )\n bins[j]++;\n }\n\n for ( j = 0; j < nbins; j++ )\n if ( max < bins[j] )\n max = bins[j];\n\n for ( j = 0; j < nbins; j++ )\n {\n printf(\"(%5.2f, %5.2f) |\", low + j * delta, low + (j + 1) * delta );\n k = (int)( (double)width * (double)bins[j] / (double)max );\n while(k-- > 0) putchar('*');\n printf(\" %-.1f%%\", bins[j] * 100.0 / (double)n);\n putchar('\\n');\n }\n\n free(bins);\n }\n}\n\n\nint main(void)\n{\n double* seq;\n\n srand((unsigned int)time(NULL));\n\n if ( (seq = generate(NMAX)) != NULL )\n {\n printf(\"mean = %g, stddev = %g\\n\\n\", mean(seq,NMAX), stddev(seq,NMAX));\n printHistogram(seq,NMAX);\n free(seq);\n\n printf(\"\\n%s\\n\", \"press enter\");\n getchar();\n return EXIT_SUCCESS;\n }\n return EXIT_FAILURE;\n}"} {"title": "Stern-Brocot sequence", "language": "C", "task": "For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the [[Fibonacci sequence]].\n\n# The first and second members of the sequence are both 1:\n#* 1, 1\n# Start by considering the second member of the sequence\n# Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:\n#* 1, 1, 2\n# Append the considered member of the sequence to the end of the sequence:\n#* 1, 1, 2, 1\n# Consider the next member of the series, (the third member i.e. 2)\n# GOTO 3\n#*\n#* --- Expanding another loop we get: ---\n#*\n# Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:\n#* 1, 1, 2, 1, 3\n# Append the considered member of the sequence to the end of the sequence:\n#* 1, 1, 2, 1, 3, 2\n# Consider the next member of the series, (the fourth member i.e. 1)\n\n\n;The task is to:\n* Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.\n* Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)\n* Show the (1-based) index of where the numbers 1-to-10 first appear in the sequence.\n* Show the (1-based) index of where the number 100 first appears in the sequence.\n* Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.\n\nShow your output on this page.\n\n\n;Related tasks:\n:* [[Fusc sequence]].\n:* [[Continued fraction/Arithmetic]]\n\n\n;Ref:\n* Infinite Fractions - Numberphile (Video).\n* Trees, Teeth, and Time: The mathematics of clock making.\n* A002487 The On-Line Encyclopedia of Integer Sequences.\n\n", "solution": "#include \n\ntypedef unsigned int uint;\n\n/* the sequence, 0-th member is 0 */\nuint f(uint n)\n{\n\treturn n < 2 ? n : (n&1) ? f(n/2) + f(n/2 + 1) : f(n/2);\n}\n\nuint gcd(uint a, uint b)\n{\n\treturn a ? a < b ? gcd(b%a, a) : gcd(a%b, b) : b;\n}\n\nvoid find(uint from, uint to)\n{\n\tdo {\n\t\tuint n;\n\t\tfor (n = 1; f(n) != from ; n++);\n\t\tprintf(\"%3u at Stern #%u.\\n\", from, n);\n\t} while (++from <= to);\n}\n\nint main(void)\n{\n\tuint n;\n\tfor (n = 1; n < 16; n++) printf(\"%u \", f(n));\n\tputs(\"are the first fifteen.\");\n\n\tfind(1, 10);\n\tfind(100, 0);\n\n\tfor (n = 1; n < 1000 && gcd(f(n), f(n+1)) == 1; n++);\n\tprintf(n == 1000 ? \"All GCDs are 1.\\n\" : \"GCD of #%d and #%d is not 1\", n, n+1);\n\n\treturn 0;\n}"} {"title": "Stirling numbers of the first kind", "language": "C", "task": "Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number\nof cycles (counting fixed points as cycles of length one).\n\nThey may be defined directly to be the number of permutations of '''n'''\nelements with '''k''' disjoint cycles.\n\nStirling numbers of the first kind express coefficients of polynomial expansions of falling or rising factorials.\n\nDepending on the application, Stirling numbers of the first kind may be \"signed\"\nor \"unsigned\". Signed Stirling numbers of the first kind arise when the\npolynomial expansion is expressed in terms of falling factorials; unsigned when\nexpressed in terms of rising factorials. The only substantial difference is that,\nfor signed Stirling numbers of the first kind, values of S1(n, k) are negative\nwhen n + k is odd.\n\nStirling numbers of the first kind follow the simple identities:\n\n S1(0, 0) = 1\n S1(n, 0) = 0 if n > 0\n S1(n, k) = 0 if k > n\n S1(n, k) = S1(n - 1, k - 1) + (n - 1) * S1(n - 1, k) # For unsigned\n ''or''\n S1(n, k) = S1(n - 1, k - 1) - (n - 1) * S1(n - 1, k) # For signed\n\n\n;Task:\n\n:* Write a routine (function, procedure, whatever) to find '''Stirling numbers of the first kind'''. There are several methods to generate Stirling numbers of the first kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.\n\n:* Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the first kind, '''S1(n, k)''', up to '''S1(12, 12)'''. it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S1(n, k) == 0 (when k > n). You may choose to show signed or unsigned Stirling numbers of the first kind, just make a note of which was chosen.\n\n:* If your language supports large integers, find and show here, on this page, the maximum value of '''S1(n, k)''' where '''n == 100'''.\n\n\n;See also:\n\n:* '''Wikipedia - Stirling numbers of the first kind'''\n:* '''OEIS:A008275 - Signed Stirling numbers of the first kind'''\n:* '''OEIS:A130534 - Unsigned Stirling numbers of the first kind'''\n\n\n;Related Tasks:\n\n:* '''Stirling numbers of the second kind'''\n:* '''Lah numbers'''\n\n\n", "solution": "#include \n#include \n#include \n\ntypedef struct stirling_cache_tag {\n int max;\n int* values;\n} stirling_cache;\n\nint stirling_number1(stirling_cache* sc, int n, int k) {\n if (k == 0)\n return n == 0 ? 1 : 0;\n if (n > sc->max || k > n)\n return 0;\n return sc->values[n*(n-1)/2 + k - 1];\n}\n\nbool stirling_cache_create(stirling_cache* sc, int max) {\n int* values = calloc(max * (max + 1)/2, sizeof(int));\n if (values == NULL)\n return false;\n sc->max = max;\n sc->values = values;\n for (int n = 1; n <= max; ++n) {\n for (int k = 1; k <= n; ++k) {\n int s1 = stirling_number1(sc, n - 1, k - 1);\n int s2 = stirling_number1(sc, n - 1, k);\n values[n*(n-1)/2 + k - 1] = s1 + s2 * (n - 1);\n }\n }\n return true;\n}\n\nvoid stirling_cache_destroy(stirling_cache* sc) {\n free(sc->values);\n sc->values = NULL;\n}\n\nvoid print_stirling_numbers(stirling_cache* sc, int max) {\n printf(\"Unsigned Stirling numbers of the first kind:\\nn/k\");\n for (int k = 0; k <= max; ++k)\n printf(k == 0 ? \"%2d\" : \"%10d\", k);\n printf(\"\\n\");\n for (int n = 0; n <= max; ++n) {\n printf(\"%2d \", n);\n for (int k = 0; k <= n; ++k)\n printf(k == 0 ? \"%2d\" : \"%10d\", stirling_number1(sc, n, k));\n printf(\"\\n\");\n }\n}\n\nint main() {\n stirling_cache sc = { 0 };\n const int max = 12;\n if (!stirling_cache_create(&sc, max)) {\n fprintf(stderr, \"Out of memory\\n\");\n return 1;\n }\n print_stirling_numbers(&sc, max);\n stirling_cache_destroy(&sc);\n return 0;\n}"} {"title": "Stirling numbers of the second kind", "language": "C", "task": "Stirling numbers of the second kind, or Stirling partition numbers, are the\nnumber of ways to partition a set of n objects into k non-empty subsets. They are\nclosely related to [[Bell numbers]], and may be derived from them.\n\n\nStirling numbers of the second kind obey the recurrence relation:\n\n S2(n, 0) and S2(0, k) = 0 # for n, k > 0\n S2(n, n) = 1\n S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)\n\n\n\n;Task:\n\n:* Write a routine (function, procedure, whatever) to find '''Stirling numbers of the second kind'''. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.\n\n:* Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, '''S2(n, k)''', up to '''S2(12, 12)'''. it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).\n\n:* If your language supports large integers, find and show here, on this page, the maximum value of '''S2(n, k)''' where '''n == 100'''.\n\n\n;See also:\n\n:* '''Wikipedia - Stirling numbers of the second kind'''\n:* '''OEIS:A008277 - Stirling numbers of the second kind'''\n\n\n;Related Tasks:\n\n:* '''Stirling numbers of the first kind'''\n:* '''Bell numbers'''\n:* '''Lah numbers'''\n\n\n", "solution": "#include \n#include \n#include \n\ntypedef struct stirling_cache_tag {\n int max;\n int* values;\n} stirling_cache;\n\nint stirling_number2(stirling_cache* sc, int n, int k) {\n if (k == n)\n return 1;\n if (k == 0 || k > n || n > sc->max)\n return 0;\n return sc->values[n*(n-1)/2 + k - 1];\n}\n\nbool stirling_cache_create(stirling_cache* sc, int max) {\n int* values = calloc(max * (max + 1)/2, sizeof(int));\n if (values == NULL)\n return false;\n sc->max = max;\n sc->values = values;\n for (int n = 1; n <= max; ++n) {\n for (int k = 1; k < n; ++k) {\n int s1 = stirling_number2(sc, n - 1, k - 1);\n int s2 = stirling_number2(sc, n - 1, k);\n values[n*(n-1)/2 + k - 1] = s1 + s2 * k;\n }\n }\n return true;\n}\n\nvoid stirling_cache_destroy(stirling_cache* sc) {\n free(sc->values);\n sc->values = NULL;\n}\n\nvoid print_stirling_numbers(stirling_cache* sc, int max) {\n printf(\"Stirling numbers of the second kind:\\nn/k\");\n for (int k = 0; k <= max; ++k)\n printf(k == 0 ? \"%2d\" : \"%8d\", k);\n printf(\"\\n\");\n for (int n = 0; n <= max; ++n) {\n printf(\"%2d \", n);\n for (int k = 0; k <= n; ++k)\n printf(k == 0 ? \"%2d\" : \"%8d\", stirling_number2(sc, n, k));\n printf(\"\\n\");\n }\n}\n\nint main() {\n stirling_cache sc = { 0 };\n const int max = 12;\n if (!stirling_cache_create(&sc, max)) {\n fprintf(stderr, \"Out of memory\\n\");\n return 1;\n }\n print_stirling_numbers(&sc, max);\n stirling_cache_destroy(&sc);\n return 0;\n}"} {"title": "Stream merge", "language": "C", "task": " 2-stream merge\n: Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink.\n: Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was.\n\n; ''N''-stream merge\n: The same as above, but reading from ''N'' sources.\n: Common algorithm: same as above, but keep buffered items and their source descriptors in a [[heap]].\n\n\nAssume streams are very big. You must not suck them whole in the memory, but read them as streams.\n\n", "solution": "/*\n * Rosetta Code - stream merge in C.\n * \n * Two streams (text files) with integer numbers, C89, Visual Studio 2010.\n *\n */\n\n#define _CRT_SECURE_NO_WARNINGS\n#include \n#include \n\n#define GET(N) { if(fscanf(f##N,\"%d\",&b##N ) != 1) f##N = NULL; }\n#define PUT(N) { printf(\"%d\\n\", b##N); GET(N) }\n\nvoid merge(FILE* f1, FILE* f2, FILE* out)\n{\n int b1;\n int b2;\n\n if(f1) GET(1)\n if(f2) GET(2)\n\n while ( f1 && f2 )\n {\n if ( b1 <= b2 ) PUT(1)\n else PUT(2)\n }\n while (f1 ) PUT(1)\n while (f2 ) PUT(2)\n}\n\nint main(int argc, char* argv[])\n{\n if ( argc < 3 || argc > 3 )\n {\n puts(\"streammerge filename1 filename2\");\n exit(EXIT_FAILURE);\n }\n else\n merge(fopen(argv[1],\"r\"),fopen(argv[2],\"r\"),stdout);\n\n return EXIT_SUCCESS;\n}\n"} {"title": "Strip control codes and extended characters from a string", "language": "C", "task": "Strip control codes and extended characters from a string. \n\n\nThe solution should demonstrate how to achieve each of the following results:\n:* a string with control codes stripped (but extended characters not stripped)\n:* a string with control codes and extended characters stripped\n\n\nIn ASCII, the control codes have decimal codes 0 through to 31 and 127. \n\nOn an ASCII based system, if the control codes are stripped, the resultant string would have all of its characters within the range of 32 to 126 decimal on the ASCII table.\n\nOn a non-ASCII based system, we consider characters that do not have a corresponding glyph on the ASCII table (within the ASCII range of 32 to 126 decimal) to be an extended character for the purpose of this task.\n\n\n", "solution": "#include \n#include \n#include \n\n#define MAXBUF 256 /* limit */\n#define STR_SZ 100 /* string size */ \n\n\n/* function prototypes */\nint ascii (const unsigned char c);\n\nint ascii_ext (const unsigned char c);\n\nunsigned char* strip(unsigned char* str, const size_t n, int ext );\n\n\n/* check a character \n return 1 for true\n 0 for false\n*/ \nint ascii (const unsigned char c) \n{ \n unsigned char min = 32; /* */\n unsigned char max = 126; /* ~ tilde */\n\n if ( c>=min && c<=max ) return 1;\n\n return 0;\n} \n\n\n/* check if extended character \n return 1 for true\n 0 for false\n*/ \nint ascii_ext (const unsigned char c) \n{ \n unsigned char min_ext = 128; \n unsigned char max_ext = 255;\n\n if ( c>=min_ext && c<=max_ext )\n return 1;\n\n return 0;\n} \n\n\n/* fill buffer with only ASCII valid characters\n then rewrite string from buffer\n limit to n < MAX chars\n*/\n\nunsigned char* strip( unsigned char* str, const size_t n, int ext) \n{ \n\n unsigned char buffer[MAXBUF] = {'\\0'};\n\n size_t i = 0; // source index\n size_t j = 0; // dest index\n\n size_t max = (n\n#include \n\nvoid\nsubleq(int *code)\n{\n\tint ip = 0, a, b, c, nextIP;\n\tchar ch;\n\twhile(0 <= ip) {\n\t\tnextIP = ip + 3;\n\t\ta = code[ip];\n\t\tb = code[ip + 1];\n\t\tc = code[ip + 2];\n\t\tif(a == -1) {\n\t\t\tscanf(\"%c\", &ch);\n\t\t\tcode[b] = (int)ch;\n\t\t} else if(b == -1) {\n\t\t\tprintf(\"%c\", (char)code[a]);\n\t\t} else {\n\t\t\tcode[b] -= code[a];\n\t\t\tif(code[b] <= 0)\n\t\t\t\tnextIP = c;\n\t\t}\n\t\tip = nextIP;\n\t}\n}\n\nvoid\nprocessFile(char *fileName)\n{\n\tint *dataSet, i, num;\n\tFILE *fp = fopen(fileName, \"r\");\n\tfscanf(fp, \"%d\", &num);\n\tdataSet = (int *)malloc(num * sizeof(int));\n\tfor(i = 0; i < num; i++)\n\t\tfscanf(fp, \"%d\", &dataSet[i]);\n\tfclose(fp);\n\tsubleq(dataSet);\n}\n\nint\nmain(int argC, char *argV[])\n{\n\tif(argC != 2)\n\t\tprintf(\"Usage : %s \\n\", argV[0]);\n\telse\n\t\tprocessFile(argV[1]);\n\treturn 0;\n}\n"} {"title": "Substring/Top and tail", "language": "C", "task": "The task is to demonstrate how to remove the first and last characters from a string. \n\nThe solution should demonstrate how to obtain the following results:\n\n* String with first character removed\n* String with last character removed\n* String with both the first and last characters removed\n\n\nIf the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it. \n\nThe program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. \n\nPrograms for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters.\n\n\n\n", "solution": "#include \n#include \n#include \n\nint main( int argc, char ** argv ){\n const char * str_a = \"knight\";\n const char * str_b = \"socks\";\n const char * str_c = \"brooms\";\n\n char * new_a = malloc( strlen( str_a ) - 1 );\n char * new_b = malloc( strlen( str_b ) - 1 );\n char * new_c = malloc( strlen( str_c ) - 2 );\n\n strcpy( new_a, str_a + 1 );\n strncpy( new_b, str_b, strlen( str_b ) - 1 );\n strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );\n\n printf( \"%s\\n%s\\n%s\\n\", new_a, new_b, new_c );\n\n free( new_a );\n free( new_b );\n free( new_c );\n\n return 0;\n}"} {"title": "Sum digits of an integer", "language": "C", "task": "Take a Natural Number in a given base and return the sum of its digits:\n:* '''1'''10 sums to '''1'''\n:* '''1234'''10 sums to '''10'''\n:* '''fe'''16 sums to '''29'''\n:* '''f0e'''16 sums to '''29'''\n\n", "solution": "#include \n\nint SumDigits(unsigned long long n, const int base) {\n int sum = 0;\n for (; n; n /= base)\n \tsum += n % base;\n return sum;\n}\n \nint main() {\n printf(\"%d %d %d %d %d\\n\",\n SumDigits(1, 10),\n SumDigits(12345, 10),\n SumDigits(123045, 10),\n SumDigits(0xfe, 16),\n SumDigits(0xf0e, 16) );\n return 0;\n}"} {"title": "Sum multiples of 3 and 5", "language": "C", "task": "The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below ''n''. \n\nShow output for ''n'' = 1000.\n\nThis is is the same as Project Euler problem 1.\n\n'''Extra credit:''' do this efficiently for ''n'' = 1e20 or higher.\n\n", "solution": "#include \n#include \n\nunsigned long long sum35(unsigned long long limit)\n{\n unsigned long long sum = 0;\n for (unsigned long long i = 0; i < limit; i++)\n if (!(i % 3) || !(i % 5))\n sum += i;\n return sum;\n}\n\nint main(int argc, char **argv)\n{\n unsigned long long limit;\n\n if (argc == 2)\n limit = strtoull(argv[1], NULL, 10);\n else\n limit = 1000;\n\n printf(\"%lld\\n\", sum35(limit));\n return 0;\n}"} {"title": "Sum of elements below main diagonal of matrix", "language": "C", "task": "Find and display the sum of elements that are below the main diagonal of a matrix.\n\nThe matrix should be a square matrix.\n\n\n::: --- Matrix to be used: ---\n\n [[1,3,7,8,10],\n [2,4,16,14,4],\n [3,1,9,18,11],\n [12,14,17,18,20],\n [7,1,3,9,5]] \n\n", "solution": "#include\n#include\n\ntypedef struct{\n\tint rows,cols;\n\tint** dataSet;\n}matrix;\n\nmatrix readMatrix(char* dataFile){\n\tFILE* fp = fopen(dataFile,\"r\");\n\tmatrix rosetta;\n\tint i,j;\n\t\n\tfscanf(fp,\"%d%d\",&rosetta.rows,&rosetta.cols);\n\t\n\trosetta.dataSet = (int**)malloc(rosetta.rows*sizeof(int*));\n\t\n\tfor(i=0;i\",argV[0]);\n\t\n\tmatrix data = readMatrix(argV[1]);\n\t\n\tprintf(\"\\n\\nMatrix is : \\n\\n\");\n\tprintMatrix(data);\n\t\n\tprintf(\"\\n\\nSum below main diagonal : %d\",findSum(data));\n\t\n\treturn 0;\n}\n"} {"title": "Summarize and say sequence", "language": "C", "task": "There are several ways to generate a self-referential sequence. One very common one (the [[Look-and-say sequence]]) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:\n 0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...\nThe terms generated grow in length geometrically and never converge.\n\nAnother way to generate a self-referential sequence is to summarize the previous term.\n\nCount how many of each alike digit there is, then concatenate the sum and digit for each of the sorted enumerated digits. Note that the first five terms are the same as for the previous sequence.\n 0, 10, 1110, 3110, 132110, 13123110, 23124110 ... \nSort the digits largest to smallest. Do not include counts of digits that do not appear in the previous term.\n\nDepending on the seed value, series generated this way always either converge to a stable value or to a short cyclical pattern. (For our purposes, I'll use converge to mean an element matches a previously seen element.) The sequence shown, with a seed value of 0, converges to a stable value of 1433223110 after 11 iterations. The seed value that converges most quickly is 22. It goes stable after the first element. (The next element is 22, which has been seen before.)\n\n\n;Task:\nFind all the positive integer seed values under 1000000, for the above convergent self-referential sequence, that takes the largest number of iterations before converging. Then print out the number of iterations and the sequence they return. Note that different permutations of the digits of the seed will yield the same sequence. For this task, assume leading zeros are not permitted. \n\nSeed Value(s): 9009 9090 9900\n\nIterations: 21 \n\nSequence: (same for all three seeds except for first element)\n9009\n2920\n192210\n19222110\n19323110\n1923123110\n1923224110\n191413323110\n191433125110\n19151423125110\n19251413226110\n1916151413325110\n1916251423127110\n191716151413326110\n191726151423128110\n19181716151413327110\n19182716151423129110\n29181716151413328110\n19281716151423228110\n19281716151413427110\n19182716152413228110\n\n\n;Related tasks:\n* [[Fours is the number of letters in the ...]]\n* [[Look-and-say sequence]]\n* [[Number names]]\n* [[Self-describing numbers]]\n* [[Spelling of ordinal numbers]]\n\n\n\n\n\n;Also see:\n* The On-Line Encyclopedia of Integer Sequences.\n\n", "solution": "#include \n#include \n#include \n\ntypedef struct rec_t rec_t;\nstruct rec_t {\n\tint depth;\n\trec_t * p[10];\n};\n\nrec_t root = {0, {0}};\n\n#define USE_POOL_ALLOC\n#ifdef USE_POOL_ALLOC /* not all that big a deal */\nrec_t *tail = 0, *head = 0;\n#define POOL_SIZE (1 << 20)\ninline rec_t *new_rec()\n{\n\tif (head == tail) {\n\t\thead = calloc(sizeof(rec_t), POOL_SIZE);\n\t\ttail = head + POOL_SIZE;\n\t}\n\treturn head++;\n}\n#else\n#define new_rec() calloc(sizeof(rec_t), 1)\n#endif\n\nrec_t *find_rec(char *s)\n{\n\tint i;\n\trec_t *r = &root;\n\twhile (*s) {\n\t\ti = *s++ - '0';\n\t\tif (!r->p[i]) r->p[i] = new_rec();\n\t\tr = r->p[i];\n\t}\n\treturn r;\n}\n\n/* speed up number to string conversion */\nchar number[100][4];\nvoid init()\n{\n\tint i;\n\tfor (i = 0; i < 100; i++)\n\t\tsprintf(number[i], \"%d\", i);\n}\n\nvoid count(char *buf)\n{\n\tint i, c[10] = {0};\n\tchar *s;\n\n\tfor (s = buf; *s; c[*s++ - '0']++);\n\n\tfor (i = 9; i >= 0; i--) {\n\t\tif (!c[i]) continue;\n\t\ts = number[c[i]];\n\n\t\t*buf++ = s[0];\n\t\tif ((*buf = s[1])) buf++;\n\n\t\t*buf++ = i + '0';\n\t}\n\n\t*buf = '\\0';\n}\n\nint depth(char *in, int d)\n{\n\trec_t *r = find_rec(in);\n\n\tif (r->depth > 0)\n\t\treturn r->depth;\n\n\td++;\n\tif (!r->depth)\tr->depth = -d;\n\telse\t\tr->depth += d;\n\n\tcount(in);\n\td = depth(in, d);\n\n\tif (r->depth <= 0) r->depth = d + 1;\n\treturn r->depth;\n}\n\nint main(void)\n{\n\tchar a[100];\n\tint i, d, best_len = 0, n_best = 0;\n\tint best_ints[32];\n\trec_t *r;\n\n\tinit();\n\n\tfor (i = 0; i < 1000000; i++) {\n\t\tsprintf(a, \"%d\", i);\n\t\td = depth(a, 0);\n\n\t\tif (d < best_len) continue;\n\t\tif (d > best_len) {\n\t\t\tn_best = 0;\n\t\t\tbest_len = d;\n\t\t}\n\t\tif (d == best_len)\n\t\t\tbest_ints[n_best++] = i;\n\t}\n\n\tprintf(\"longest length: %d\\n\", best_len);\n\tfor (i = 0; i < n_best; i++) {\n\t\tprintf(\"%d\\n\", best_ints[i]);\n\t\tsprintf(a, \"%d\", best_ints[i]);\n\t\tfor (d = 0; d <= best_len; d++) {\n\t\t\tr = find_rec(a);\n\t\t\tprintf(\"%3d: %s\\n\", r->depth, a);\n\t\t\tcount(a);\n\t\t}\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}"} {"title": "Superellipse", "language": "C", "task": "A superellipse is a geometric figure defined as the set of all points (x, y) with \n\n\n::: \\left|\\frac{x}{a}\\right|^n\\! + \\left|\\frac{y}{b}\\right|^n\\! = 1,\n\nwhere ''n'', ''a'', and ''b'' are positive numbers.\n\n\n;Task\nDraw a superellipse with n = 2.5, and a = b = 200\n\n", "solution": "#include\n#include\n#include\n\n#define pi M_PI\n\nint main(){\n\t\n\tdouble a,b,n,i,incr = 0.0001;\n\t\n\tprintf(\"Enter major and minor axes of the SuperEllipse : \");\n\tscanf(\"%lf%lf\",&a,&b);\n\t\n\tprintf(\"Enter n : \");\n\tscanf(\"%lf\",&n);\n\t\n\tinitwindow(500,500,\"Superellipse\");\n\t\n\tfor(i=0;i<2*pi;i+=incr){\n\t\tputpixel(250 + a*pow(fabs(cos(i)),2/n)*(pi/2\n#include \n#include \n\n#define MAX 12\nchar *super = 0;\nint pos, cnt[MAX];\n\n// 1! + 2! + ... + n!\nint fact_sum(int n)\n{\n\tint s, x, f;\n\tfor (s = 0, x = 0, f = 1; x < n; f *= ++x, s += f);\n\treturn s;\n}\n\nint r(int n)\n{\n\tif (!n) return 0;\n\n\tchar c = super[pos - n];\n\tif (!--cnt[n]) {\n\t\tcnt[n] = n;\n\t\tif (!r(n-1)) return 0;\n\t}\n\tsuper[pos++] = c;\n\treturn 1;\n}\n\nvoid superperm(int n)\n{\n\tint i, len;\n\n\tpos = n;\n\tlen = fact_sum(n);\n\tsuper = realloc(super, len + 1);\n\tsuper[len] = '\\0';\n\n\tfor (i = 0; i <= n; i++) cnt[i] = i;\n\tfor (i = 1; i <= n; i++) super[i - 1] = i + '0';\n\n\twhile (r(n));\n}\n\nint main(void)\n{\n\tint n;\n\tfor (n = 0; n < MAX; n++) {\n\t\tprintf(\"superperm(%2d) \", n);\n\t\tsuperperm(n);\n\t\tprintf(\"len = %d\", (int)strlen(super));\n\t\t// uncomment next line to see the string itself\n\t\t// printf(\": %s\", super);\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}"} {"title": "Temperature conversion", "language": "C", "task": "There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: \nRankine.\n\nThe Celsius and Kelvin scales have the same magnitude, but different null points.\n \n: 0 degrees Celsius corresponds to 273.15 kelvin.\n: 0 kelvin is absolute zero.\n\nThe Fahrenheit and Rankine scales also have the same magnitude, but different null points.\n\n: 0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.\n: 0 degrees Rankine is absolute zero.\n\nThe Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.\n\n\n;Task\nWrite code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result. \n\n\n;Example:\n\nK 21.00\n\nC -252.15\n\nF -421.87\n\nR 37.80\n\n\n", "solution": "#include \n#include \n\ndouble kelvinToCelsius(double k){\n return k - 273.15;\n}\n\ndouble kelvinToFahrenheit(double k){\n return k * 1.8 - 459.67;\n}\n\ndouble kelvinToRankine(double k){\n return k * 1.8;\n}\nvoid convertKelvin(double kelvin) {\n printf(\"K %.2f\\n\", kelvin);\n printf(\"C %.2f\\n\", kelvinToCelsius(kelvin));\n printf(\"F %.2f\\n\", kelvinToFahrenheit(kelvin));\n printf(\"R %.2f\", kelvinToRankine(kelvin));\n}\n\nint main(int argc, const char * argv[])\n{\n if (argc > 1) {\n double kelvin = atof(argv[1]);\n convertKelvin(kelvin);\n }\n return 0;\n}"} {"title": "Terminal control/Coloured text", "language": "C", "task": "Display a word in various colours on the terminal. \n\nThe system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.\n\n\nOptionally demonstrate:\n* How the system should determine if the terminal supports colour\n* Setting of the background colour\n* How to cause blinking or flashing (if supported by the terminal)\n\n", "solution": "#include \n\nvoid table(const char *title, const char *mode)\n{\n\tint f, b;\n\tprintf(\"\\n\\033[1m%s\\033[m\\n bg\\t fg\\n\", title);\n\tfor (b = 40; b <= 107; b++) {\n\t\tif (b == 48) b = 100;\n\t\tprintf(\"%3d\\t\\033[%s%dm\", b, mode, b);\n\t\tfor (f = 30; f <= 97; f++) {\n\t\t\tif (f == 38) f = 90;\n\t\t\tprintf(\"\\033[%dm%3d \", f, f);\n\t\t}\n\t\tputs(\"\\033[m\");\n\t}\n}\n\nint main(void)\n{\n\tint fg, bg, blink, inverse;\n\n\ttable(\"normal ( ESC[22m or ESC[m )\", \"22;\");\n\ttable(\"bold ( ESC[1m )\", \"1;\");\n\ttable(\"faint ( ESC[2m ), not well supported\", \"2;\");\n\ttable(\"italic ( ESC[3m ), not well supported\", \"3;\");\n\ttable(\"underline ( ESC[4m ), support varies\", \"4;\");\n\ttable(\"blink ( ESC[5m )\", \"5;\");\n\ttable(\"inverted ( ESC[7m )\", \"7;\");\n\treturn 0;\n}"} {"title": "Terminal control/Unicode output", "language": "C", "task": "The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised.\n\nNote that it is permissible to use system configuration data to determine terminal capabilities if the system provides such a facility.\n\n", "solution": "#include\n#include\n\nint\nmain ()\n{\n int i;\n char *str = getenv (\"LANG\");\n\n for (i = 0; str[i + 2] != 00; i++)\n {\n if ((str[i] == 'u' && str[i + 1] == 't' && str[i + 2] == 'f')\n || (str[i] == 'U' && str[i + 1] == 'T' && str[i + 2] == 'F'))\n {\n printf\n (\"Unicode is supported on this terminal and U+25B3 is : \\u25b3\");\n i = -1;\n break;\n }\n }\n\n if (i != -1)\n printf (\"Unicode is not supported on this terminal.\");\n\n return 0;\n}\n"} {"title": "Test integerness", "language": "C", "task": "{| class=\"wikitable\"\n|-\n! colspan=2 | Input\n! colspan=2 | Output\n! rowspan=2 | Comment\n|-\n! Type\n! Value\n! exact\n! tolerance = 0.00001\n|-\n| rowspan=3 | decimal\n| 25.000000\n| colspan=2 | true\n| \n|-\n| 24.999999\n| false\n| true\n| \n|-\n| 25.000100\n| colspan=2 | false\n| \n|-\n| rowspan=4 | floating-point\n| -2.1e120\n| colspan=2 | true\n| This one is tricky, because in most languages it is too large to fit into a native integer type.It is, nonetheless, mathematically an integer, and your code should identify it as such.\n|-\n| -5e-2\n| colspan=2 | false\n| \n|-\n| NaN\n| colspan=2 | false\n| \n|-\n| Inf\n| colspan=2 | false\n| This one is debatable. If your code considers it an integer, that's okay too.\n|-\n| rowspan=2 | complex\n| 5.0+0.0i\n| colspan=2 | true\n| \n|-\n| 5-5i\n| colspan=2 | false\n| \n|}\n\n(The types and notations shown in these tables are merely examples - you should use the native data types and number literals of your programming language and standard library. Use a different set of test-cases, if this one doesn't demonstrate all relevant behavior.)\n\n\n", "solution": "#include \n#include \n#include \n\n/* Testing macros */\n#define FMTSPEC(arg) _Generic((arg), \\\n float: \"%f\", double: \"%f\", \\\n long double: \"%Lf\", unsigned int: \"%u\", \\\n unsigned long: \"%lu\", unsigned long long: \"%llu\", \\\n int: \"%d\", long: \"%ld\", long long: \"%lld\", \\\n default: \"(invalid type (%p)\")\n\n#define CMPPARTS(x, y) ((long double complex)((long double)(x) + \\\n I * (long double)(y)))\n\n#define TEST_CMPL(i, j)\\\n printf(FMTSPEC(i), i), printf(\" + \"), printf(FMTSPEC(j), j), \\\n printf(\"i = %s\\n\", (isint(CMPPARTS(i, j)) ? \"true\" : \"false\"))\n\n#define TEST_REAL(i)\\\n printf(FMTSPEC(i), i), printf(\" = %s\\n\", (isint(i) ? \"true\" : \"false\"))\n\n/* Main code */\nstatic inline int isint(long double complex n)\n{\n return cimagl(n) == 0 && nearbyintl(creall(n)) == creall(n);\n}\n\nint main(void)\n{\n TEST_REAL(0);\n TEST_REAL(-0);\n TEST_REAL(-2);\n TEST_REAL(-2.00000000000001);\n TEST_REAL(5);\n TEST_REAL(7.3333333333333);\n TEST_REAL(3.141592653589);\n TEST_REAL(-9.223372036854776e18);\n TEST_REAL(5e-324);\n TEST_REAL(NAN);\n TEST_CMPL(6, 0);\n TEST_CMPL(0, 1);\n TEST_CMPL(0, 0);\n TEST_CMPL(3.4, 0);\n\n /* Demonstrating that we can use the same function for complex values\n * constructed in the standard way */\n double complex test1 = 5 + 0*I,\n test2 = 3.4f,\n test3 = 3,\n test4 = 0 + 1.2*I;\n\n printf(\"Test 1 (5+i) = %s\\n\", isint(test1) ? \"true\" : \"false\");\n printf(\"Test 2 (3.4+0i) = %s\\n\", isint(test2) ? \"true\" : \"false\");\n printf(\"Test 3 (3+0i) = %s\\n\", isint(test3) ? \"true\" : \"false\");\n printf(\"Test 4 (0+1.2i) = %s\\n\", isint(test4) ? \"true\" : \"false\");\n}\n"} {"title": "The Twelve Days of Christmas", "language": "C", "task": "Write a program that outputs the lyrics of the Christmas carol ''The Twelve Days of Christmas''. \nThe lyrics can be found here. \n\n(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)\n\n\n\n", "solution": "#include\n \nint main()\n{\n int i,j;\n \n char days[12][10] = \n {\n \"First\",\n \"Second\",\n \"Third\",\n \"Fourth\",\n \"Fifth\",\n \"Sixth\",\n \"Seventh\",\n \"Eighth\",\n \"Ninth\",\n \"Tenth\",\n \"Eleventh\",\n \"Twelfth\"\n };\n\n char gifts[12][33] =\n {\n \"Twelve drummers drumming\",\n \"Eleven pipers piping\",\n \"Ten lords a-leaping\",\n \"Nine ladies dancing\",\n \"Eight maids a-milking\",\n \"Seven swans a-swimming\",\n \"Six geese a-laying\",\n \"Five golden rings\",\n \"Four calling birds\",\n \"Three french hens\", \n \"Two turtle doves\", \n \"And a partridge in a pear tree.\"\n };\n \n for(i=0;i<12;i++)\n {\n printf(\"\\n\\nOn the %s day of Christmas\\nMy true love gave to me:\",days[i]);\n \n for(j=i;j>=0;j--)\n {\n (i==0)?printf(\"\\nA partridge in a pear tree.\"):printf(\"\\n%s%c\",gifts[11-j],(j!=0)?',':' ');\n }\n }\n \n return 0;\n}"} {"title": "Top rank per group", "language": "C", "task": "Find the top ''N'' salaries in each department, where ''N'' is provided as a parameter.\n\nUse this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source:\n\nEmployee Name,Employee ID,Salary,Department\nTyler Bennett,E10297,32000,D101\nJohn Rappl,E21437,47000,D050\nGeorge Woltman,E00127,53500,D101\nAdam Smith,E63535,18000,D202\nClaire Buckman,E39876,27800,D202\nDavid McClellan,E04242,41500,D101\nRich Holcomb,E01234,49500,D202\nNathan Adams,E41298,21900,D050\nRichard Potter,E43128,15900,D101\nDavid Motsinger,E27002,19250,D202\nTim Sampair,E03033,27000,D101\nKim Arlich,E10001,57000,D190\nTimothy Grove,E16398,29900,D190\n\n\n", "solution": "#include \n#include \n#include \n\ntypedef struct {\n const char *name, *id, *dept;\n int sal;\n} person;\n\nperson ppl[] = {\n {\"Tyler Bennett\", \"E10297\", \"D101\", 32000},\n {\"John Rappl\", \"E21437\", \"D050\", 47000},\n {\"George Woltman\", \"E00127\", \"D101\", 53500},\n {\"Adam Smith\", \"E63535\", \"D202\", 18000},\n {\"Claire Buckman\", \"E39876\", \"D202\", 27800},\n {\"David McClellan\", \"E04242\", \"D101\", 41500},\n {\"Rich Holcomb\", \"E01234\", \"D202\", 49500},\n {\"Nathan Adams\", \"E41298\", \"D050\", 21900},\n {\"Richard Potter\", \"E43128\", \"D101\", 15900},\n {\"David Motsinger\", \"E27002\", \"D202\", 19250},\n {\"Tim Sampair\", \"E03033\", \"D101\", 27000},\n {\"Kim Arlich\", \"E10001\", \"D190\", 57000},\n {\"Timothy Grove\", \"E16398\", \"D190\", 29900},\n};\n\nint pcmp(const void *a, const void *b)\n{\n const person *aa = a, *bb = b;\n int x = strcmp(aa->dept, bb->dept);\n if (x) return x;\n return aa->sal > bb->sal ? -1 : aa->sal < bb->sal;\n}\n\n#define N sizeof(ppl)/sizeof(person)\nvoid top(int n)\n{\n int i, rank;\n qsort(ppl, N, sizeof(person), pcmp);\n\n for (i = rank = 0; i < N; i++) {\n if (i && strcmp(ppl[i].dept, ppl[i - 1].dept)) {\n rank = 0;\n printf(\"\\n\");\n }\n\n if (rank++ < n)\n printf(\"%s %d: %s\\n\", ppl[i].dept, ppl[i].sal, ppl[i].name);\n }\n}\n\nint main()\n{\n top(2);\n return 0;\n}"} {"title": "Topswops", "language": "C", "task": "Topswops is a card game created by John Conway in the 1970's.\n\n\nAssume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top. \n\nA round is composed of reversing the first m cards where m is the value of the topmost card. \n\nRounds are repeated until the topmost card is the number 1 and the number of swaps is recorded. \n\n\nFor our example the swaps produce:\n \n [2, 4, 1, 3] # Initial shuffle\n [4, 2, 1, 3]\n [3, 1, 2, 4]\n [2, 1, 3, 4]\n [1, 2, 3, 4]\n\n\nFor a total of four swaps from the initial ordering to produce the terminating case where 1 is on top.\n\n\nFor a particular number n of cards, topswops(n) is the maximum swaps needed for any starting permutation of the n cards.\n\n\n;Task:\nThe task is to generate and show here a table of n vs topswops(n) for n in the range 1..10 inclusive.\n\n\n;Note:\nTopswops is also known as Fannkuch from the German word ''Pfannkuchen'' meaning pancake.\n\n\n;Related tasks:\n* [[Number reversal game]]\n* [[Sorting algorithms/Pancake sort]]\n\n", "solution": "#define _GNU_SOURCE\n#include \n#include \n#include \n#include \n\n#define MAX_CPUS 8 // increase this if you got more CPUs/cores\n\ntypedef struct { char v[16]; } deck;\n \nint n, best[16];\n\n// Update a shared variable by spinlock. Since this program really only\n// enters locks dozens of times, a pthread_mutex_lock() would work\n// equally fine, but RC already has plenty of examples for that.\n#define SWAP_OR_RETRY(var, old, new)\t\t\t\t\t\\\n\tif (!__sync_bool_compare_and_swap(&(var), old, new)) {\t\t\\\n\t\tvolatile int spin = 64;\t\t\t\t\t\\\n\t\twhile (spin--);\t\t\t\t\t\t\\\n\t\tcontinue; }\n\nvoid tryswaps(deck *a, int f, int s, int d) {\n#define A a->v\n#define B b->v\n \n\twhile (best[n] < d) {\n\t\tint t = best[n];\n\t\tSWAP_OR_RETRY(best[n], t, d);\n\t}\n\n#define TEST(x)\t\t\t\t\t\t\t\t\t\\\n\tcase x: if ((A[15-x] == 15-x || (A[15-x] == -1 && !(f & 1<<(15-x))))\t\\\n\t\t\t&& (A[15-x] == -1 || d + best[15-x] >= best[n]))\t\\\n\t\t\tbreak;\t\t\t\t\t\t\t\\\n\t\tif (d + best[15-x] <= best[n]) return;\t\t\t\t\\\n\t\ts = 14 - x\n \n\tswitch (15 - s) {\n\t\tTEST(0); TEST(1); TEST(2); TEST(3); TEST(4);\n\t\tTEST(5); TEST(6); TEST(7); TEST(8); TEST(9);\n\t\tTEST(10); TEST(11); TEST(12); TEST(13); TEST(14);\n\t\treturn;\n\t}\n#undef TEST\n \n\tdeck *b = a + 1;\n\t*b = *a;\n\td++;\n \n#define FLIP(x)\t\t\t\t\t\t\t\\\n\tif (A[x] == x || ((A[x] == -1) && !(f & (1<= n) return 0;\n\n\t\tSWAP_OR_RETRY(first_swap, at, at + 1);\n\n\t\tmemset(job->x, -1, sizeof(deck));\n\t\tjob->x[0].v[at] = 0;\n\t\tjob->x[0].v[0] = at;\n\t\ttryswaps(job->x, 1 | (1 << at), n - 1, 1);\n\t}\n}\n\nint main(void) {\n\tint n_cpus = num_cpus();\n\n\tfor (int i = 0; i < MAX_CPUS; i++)\n\t\tjobs[i].id = i;\n\n\tpthread_t tid[MAX_CPUS];\n\n\tfor (n = 2; n <= 14; n++) {\n\t\tint top = n_cpus;\n\t\tif (top > n) top = n;\n\n\t\tfirst_swap = 1;\n\t\tfor (int i = 0; i < top; i++)\n\t\t\tpthread_create(tid + i, 0, thread_start, jobs + i);\n\n\t\tfor (int i = 0; i < top; i++)\n\t\t\tpthread_join(tid[i], 0);\n\n\t\tprintf(\"%2d: %2d\\n\", n, best[n]);\n\t}\n \n\treturn 0;\n}"} {"title": "Total circles area", "language": "C", "task": "Example circles\nExample circles filtered\n\nGiven some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal digits of precision. The area covered by two or more disks needs to be counted only once. \n\nOne point of this Task is also to compare and discuss the relative merits of various solution strategies, their performance, precision and simplicity. This means keeping both slower and faster solutions for a language (like C) is welcome.\n\nTo allow a better comparison of the different implementations, solve the problem with this standard dataset, each line contains the '''x''' and '''y''' coordinates of the centers of the disks and their radii (11 disks are fully contained inside other disks):\n\n xc yc radius\n 1.6417233788 1.6121789534 0.0848270516\n -1.4944608174 1.2077959613 1.1039549836\n 0.6110294452 -0.6907087527 0.9089162485\n 0.3844862411 0.2923344616 0.2375743054\n -0.2495892950 -0.3832854473 1.0845181219\n 1.7813504266 1.6178237031 0.8162655711\n -0.1985249206 -0.8343333301 0.0538864941\n -1.7011985145 -0.1263820964 0.4776976918\n -0.4319462812 1.4104420482 0.7886291537\n 0.2178372997 -0.9499557344 0.0357871187\n -0.6294854565 -1.3078893852 0.7653357688\n 1.7952608455 0.6281269104 0.2727652452\n 1.4168575317 1.0683357171 1.1016025378\n 1.4637371396 0.9463877418 1.1846214562\n -0.5263668798 1.7315156631 1.4428514068\n -1.2197352481 0.9144146579 1.0727263474\n -0.1389358881 0.1092805780 0.7350208828\n 1.5293954595 0.0030278255 1.2472867347\n -0.5258728625 1.3782633069 1.3495508831\n -0.1403562064 0.2437382535 1.3804956588\n 0.8055826339 -0.0482092025 0.3327165165\n -0.6311979224 0.7184578971 0.2491045282\n 1.4685857879 -0.8347049536 1.3670667538\n -0.6855727502 1.6465021616 1.0593087096\n 0.0152957411 0.0638919221 0.9771215985\n\n\nThe result is 21.56503660... .\n\n\n;Related task:\n* [[Circles of given radius through two points]].\n\n\n;See also:\n* http://www.reddit.com/r/dailyprogrammer/comments/zff9o/9062012_challenge_96_difficult_water_droplets/\n* http://stackoverflow.com/a/1667789/10562\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\ntypedef double Fp;\ntypedef struct { Fp x, y, r; } Circle;\n\nCircle circles[] = {\n { 1.6417233788, 1.6121789534, 0.0848270516},\n {-1.4944608174, 1.2077959613, 1.1039549836},\n { 0.6110294452, -0.6907087527, 0.9089162485},\n { 0.3844862411, 0.2923344616, 0.2375743054},\n {-0.2495892950, -0.3832854473, 1.0845181219},\n { 1.7813504266, 1.6178237031, 0.8162655711},\n {-0.1985249206, -0.8343333301, 0.0538864941},\n {-1.7011985145, -0.1263820964, 0.4776976918},\n {-0.4319462812, 1.4104420482, 0.7886291537},\n { 0.2178372997, -0.9499557344, 0.0357871187},\n {-0.6294854565, -1.3078893852, 0.7653357688},\n { 1.7952608455, 0.6281269104, 0.2727652452},\n { 1.4168575317, 1.0683357171, 1.1016025378},\n { 1.4637371396, 0.9463877418, 1.1846214562},\n {-0.5263668798, 1.7315156631, 1.4428514068},\n {-1.2197352481, 0.9144146579, 1.0727263474},\n {-0.1389358881, 0.1092805780, 0.7350208828},\n { 1.5293954595, 0.0030278255, 1.2472867347},\n {-0.5258728625, 1.3782633069, 1.3495508831},\n {-0.1403562064, 0.2437382535, 1.3804956588},\n { 0.8055826339, -0.0482092025, 0.3327165165},\n {-0.6311979224, 0.7184578971, 0.2491045282},\n { 1.4685857879, -0.8347049536, 1.3670667538},\n {-0.6855727502, 1.6465021616, 1.0593087096},\n { 0.0152957411, 0.0638919221, 0.9771215985}};\n\nconst size_t n_circles = sizeof(circles) / sizeof(Circle);\n\nstatic inline Fp min(const Fp a, const Fp b) { return a <= b ? a : b; }\n\nstatic inline Fp max(const Fp a, const Fp b) { return a >= b ? a : b; }\n\nstatic inline Fp sq(const Fp a) { return a * a; }\n\n// Return an uniform random value in [a, b).\nstatic inline double uniform(const double a, const double b) {\n const double r01 = rand() / (double)RAND_MAX;\n return a + (b - a) * r01;\n}\n\nstatic inline bool is_inside_circles(const Fp x, const Fp y) {\n for (size_t i = 0; i < n_circles; i++)\n if (sq(x - circles[i].x) + sq(y - circles[i].y) < circles[i].r)\n return true;\n return false;\n}\n\nint main() {\n // Initialize the bounding box (bbox) of the circles.\n Fp x_min = INFINITY, x_max = -INFINITY;\n Fp y_min = x_min, y_max = x_max;\n\n // Compute the bounding box of the circles.\n for (size_t i = 0; i < n_circles; i++) {\n Circle *c = &circles[i];\n x_min = min(x_min, c->x - c->r);\n x_max = max(x_max, c->x + c->r);\n y_min = min(y_min, c->y - c->r);\n y_max = max(y_max, c->y + c->r);\n\n c->r *= c->r; // Square the radii to speed up testing.\n }\n\n const Fp bbox_area = (x_max - x_min) * (y_max - y_min);\n\n // Montecarlo sampling.\n srand(time(0));\n size_t to_try = 1U << 16;\n size_t n_tries = 0;\n size_t n_hits = 0;\n\n while (true) {\n n_hits += is_inside_circles(uniform(x_min, x_max),\n uniform(y_min, y_max));\n n_tries++;\n\n if (n_tries == to_try) {\n const Fp area = bbox_area * n_hits / n_tries;\n const Fp r = (Fp)n_hits / n_tries;\n const Fp s = area * sqrt(r * (1 - r) / n_tries);\n printf(\"%.4f +/- %.4f (%zd samples)\\n\", area, s, n_tries);\n if (s * 3 <= 1e-3) // Stop at 3 sigmas.\n break;\n to_try *= 2;\n }\n }\n\n return 0;\n}"} {"title": "Trabb Pardo\u2013Knuth algorithm", "language": "C", "task": "The TPK algorithm is an early example of a programming chrestomathy. \nIt was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. \nThe report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm.\n\nFrom the wikipedia entry:\n\n '''ask''' for 11 numbers to be read into a sequence ''S''\n '''reverse''' sequence ''S''\n '''for each''' ''item'' '''in''' sequence ''S''\n ''result'' ''':=''' '''call''' a function to do an ''operation''\n '''if''' ''result'' overflows\n '''alert''' user\n '''else'''\n '''print''' ''result''\n\nThe task is to implement the algorithm:\n# Use the function: f(x) = |x|^{0.5} + 5x^3\n# The overflow condition is an answer of greater than 400.\n# The 'user alert' should not stop processing of other items of the sequence.\n# Print a prompt before accepting '''eleven''', textual, numeric inputs.\n# You may optionally print the item as well as its associated result, but the results must be in reverse order of input.\n# The sequence ''' ''S'' ''' may be 'implied' and so not shown explicitly.\n# ''Print and show the program in action from a typical run here''. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).\n\n", "solution": "#include\n#include\n\nint\nmain ()\n{\n double inputs[11], check = 400, result;\n int i;\n\n printf (\"\\nPlease enter 11 numbers :\");\n\n for (i = 0; i < 11; i++)\n {\n scanf (\"%lf\", &inputs[i]);\n }\n\n printf (\"\\n\\n\\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :\");\n\n for (i = 10; i >= 0; i--)\n {\n result = sqrt (fabs (inputs[i])) + 5 * pow (inputs[i], 3);\n\n printf (\"\\nf(%lf) = \");\n\n if (result > check)\n {\n printf (\"Overflow!\");\n }\n\n else\n {\n printf (\"%lf\", result);\n }\n }\n\n return 0;\n}\n"} {"title": "Truncate a file", "language": "C", "task": "Truncate a file to a specific length. This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes).\n\n\nTruncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available. The file may contain non human readable binary data in an unspecified format, so the routine should be \"binary safe\", leaving the contents of the untruncated part of the file unchanged.\n\nIf the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. \n\nOn some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. \n\nThis task permits the use of such facilities. However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.\n\n", "solution": "===Windows===\nWindows uses SetEndOfFile() to change the length of a file. This program can truncate or extend a file. It can detect and print errors.\n\n* If the file does not exist: \"The system cannot find the file specified.\"\n* If the length is negative: \"An attempt was made to move the file pointer before the beginning of the file.\"\n* If the length is too large: \"There is not enough space on the disk.\"\n\n"} {"title": "UPC", "language": "C", "task": "Goal: \nConvert UPC bar codes to decimal.\n\n\nSpecifically:\n\nThe UPC standard is actually a collection of standards -- physical standards, data format standards, product reference standards... \n\nHere, in this task, we will focus on some of the data format standards, with an imaginary physical+electrical implementation which converts physical UPC bar codes to ASCII (with spaces and '''#''' characters representing the presence or absence of ink).\n\n\n;Sample input:\nBelow, we have a representation of ten different UPC-A bar codes read by our imaginary bar code reader:\n\n # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # \n # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # \n # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # \n # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # \n # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # \n # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # \n # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # \n # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # \n # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # \n # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # \n\nSome of these were entered upside down, and one entry has a timing error.\n\n\n;Task:\nImplement code to find the corresponding decimal representation of each, rejecting the error. \n\nExtra credit for handling the rows entered upside down (the other option is to reject them).\n\n\n;Notes:\nEach digit is represented by 7 bits:\n\n 0: 0 0 0 1 1 0 1\n 1: 0 0 1 1 0 0 1\n 2: 0 0 1 0 0 1 1\n 3: 0 1 1 1 1 0 1\n 4: 0 1 0 0 0 1 1\n 5: 0 1 1 0 0 0 1\n 6: 0 1 0 1 1 1 1\n 7: 0 1 1 1 0 1 1\n 8: 0 1 1 0 1 1 1\n 9: 0 0 0 1 0 1 1\n\nOn the left hand side of the bar code a space represents a '''0''' and a '''#''' represents a '''1'''. \nOn the right hand side of the bar code, a '''#''' represents a '''0''' and a space represents a '''1''' \nAlternatively (for the above): spaces always represent zeros and '''#''' characters always represent ones, but the representation is logically negated -- '''1'''s and '''0'''s are flipped -- on the right hand side of the bar code.\n\n\n\n;The UPC-A bar code structure:\n::* It begins with at least 9 spaces (which our imaginary bar code reader unfortunately doesn't always reproduce properly), \n::* then has a ''' # # ''' sequence marking the start of the sequence, \n::* then has the six \"left hand\" digits, \n::* then has a ''' # # ''' sequence in the middle, \n::* then has the six \"right hand digits\", \n::* then has another ''' # # ''' (end sequence), and finally, \n::* then ends with nine trailing spaces (which might be eaten by wiki edits, and in any event, were not quite captured correctly by our imaginary bar code reader).\n\n\nFinally, the last digit is a checksum digit which may be used to help detect errors. \n\n\n;Verification:\nMultiply each digit in the represented 12 digit sequence by the corresponding number in (3,1,3,1,3,1,3,1,3,1,3,1) and add the products.\n\nThe sum (mod 10) must be '''0''' (must have a zero as its last digit) if the UPC number has been read correctly.\n\n", "solution": "#include \n#include \n#include \n#include \n\ntypedef char const *const string;\n\nbool consume_sentinal(bool middle, string s, size_t *pos) {\n if (middle) {\n if (s[*pos] == ' ' && s[*pos + 1] == '#' && s[*pos + 2] == ' ' && s[*pos + 3] == '#' && s[*pos + 4] == ' ') {\n *pos += 5;\n return true;\n }\n } else {\n if (s[*pos] == '#' && s[*pos + 1] == ' ' && s[*pos + 2] == '#') {\n *pos += 3;\n return true;\n }\n }\n return false;\n}\n\nint consume_digit(bool right, string s, size_t *pos) {\n const char zero = right ? '#' : ' ';\n const char one = right ? ' ' : '#';\n size_t i = *pos;\n int result = -1;\n\n if (s[i] == zero) {\n if (s[i + 1] == zero) {\n if (s[i + 2] == zero) {\n if (s[i + 3] == one) {\n if (s[i + 4] == zero) {\n if (s[i + 5] == one && s[i + 6] == one) {\n result = 9;\n }\n } else if (s[i + 4] == one) {\n if (s[i + 5] == zero && s[i + 6] == one) {\n result = 0;\n }\n }\n }\n } else if (s[i + 2] == one) {\n if (s[i + 3] == zero) {\n if (s[i + 4] == zero && s[i + 5] == one && s[i + 6] == one) {\n result = 2;\n }\n } else if (s[i + 3] == one) {\n if (s[i + 4] == zero && s[i + 5] == zero && s[i + 6] == one) {\n result = 1;\n }\n }\n }\n } else if (s[i + 1] == one) {\n if (s[i + 2] == zero) {\n if (s[i + 3] == zero) {\n if (s[i + 4] == zero && s[i + 5] == one && s[i + 6] == one) {\n result = 4;\n }\n } else if (s[i + 3] == one) {\n if (s[i + 4] == one && s[i + 5] == one && s[i + 6] == one) {\n result = 6;\n }\n }\n } else if (s[i + 2] == one) {\n if (s[i + 3] == zero) {\n if (s[i + 4] == zero) {\n if (s[i + 5] == zero && s[i + 6] == one) {\n result = 5;\n }\n } else if (s[i + 4] == one) {\n if (s[i + 5] == one && s[i + 6] == one) {\n result = 8;\n }\n }\n } else if (s[i + 3] == one) {\n if (s[i + 4] == zero) {\n if (s[i + 5] == one && s[i + 6] == one) {\n result = 7;\n }\n } else if (s[i + 4] == one) {\n if (s[i + 5] == zero && s[i + 6] == one) {\n result = 3;\n }\n }\n }\n }\n }\n }\n\n if (result >= 0) {\n *pos += 7;\n }\n return result;\n}\n\nbool decode_upc(string src, char *buffer) {\n const int one = 1;\n const int three = 3;\n\n size_t pos = 0;\n int sum = 0;\n int digit;\n\n //1) 9 spaces (unreliable)\n while (src[pos] != '#') {\n if (src[pos] == 0) {\n return false;\n }\n pos++;\n }\n\n //2) Start \"# #\"\n if (!consume_sentinal(false, src, &pos)) {\n return false;\n }\n\n //3) 6 left-hand digits (space is zero and hash is one)\n digit = consume_digit(false, src, &pos);\n if (digit < 0) {\n return false;\n }\n sum += three * digit;\n *buffer++ = digit + '0';\n *buffer++ = ' ';\n\n digit = consume_digit(false, src, &pos);\n if (digit < 0) {\n return false;\n }\n sum += one * digit;\n *buffer++ = digit + '0';\n *buffer++ = ' ';\n\n digit = consume_digit(false, src, &pos);\n if (digit < 0) {\n return false;\n }\n sum += three * digit;\n *buffer++ = digit + '0';\n *buffer++ = ' ';\n\n digit = consume_digit(false, src, &pos);\n if (digit < 0) {\n return false;\n }\n sum += one * digit;\n *buffer++ = digit + '0';\n *buffer++ = ' ';\n\n digit = consume_digit(false, src, &pos);\n if (digit < 0) {\n return false;\n }\n sum += three * digit;\n *buffer++ = digit + '0';\n *buffer++ = ' ';\n\n digit = consume_digit(false, src, &pos);\n if (digit < 0) {\n return false;\n }\n sum += one * digit;\n *buffer++ = digit + '0';\n *buffer++ = ' ';\n\n //4) Middle \"# #\"\n if (!consume_sentinal(true, src, &pos)) {\n return false;\n }\n\n //5) 6 right-hand digits (hash is zero and space is one)\n digit = consume_digit(true, src, &pos);\n if (digit < 0) {\n return false;\n }\n sum += three * digit;\n *buffer++ = digit + '0';\n *buffer++ = ' ';\n\n digit = consume_digit(true, src, &pos);\n if (digit < 0) {\n return false;\n }\n sum += one * digit;\n *buffer++ = digit + '0';\n *buffer++ = ' ';\n\n digit = consume_digit(true, src, &pos);\n if (digit < 0) {\n return false;\n }\n sum += three * digit;\n *buffer++ = digit + '0';\n *buffer++ = ' ';\n\n digit = consume_digit(true, src, &pos);\n if (digit < 0) {\n return false;\n }\n sum += one * digit;\n *buffer++ = digit + '0';\n *buffer++ = ' ';\n\n digit = consume_digit(true, src, &pos);\n if (digit < 0) {\n return false;\n }\n sum += three * digit;\n *buffer++ = digit + '0';\n *buffer++ = ' ';\n\n digit = consume_digit(true, src, &pos);\n if (digit < 0) {\n return false;\n }\n sum += one * digit;\n *buffer++ = digit + '0';\n *buffer++ = ' ';\n\n //6) Final \"# #\"\n if (!consume_sentinal(false, src, &pos)) {\n return false;\n }\n\n //7) 9 spaces (unreliable)\n // skip\n\n //8) the dot product of the number and (3, 1)+ sequence mod 10 must be zero\n return sum % 10 == 0;\n}\n\nvoid test(string src) {\n char buffer[24];\n\n if (decode_upc(src, buffer)) {\n buffer[22] = 0;\n printf(\"%sValid\\n\", buffer);\n } else {\n size_t len = strlen(src);\n char *rev = malloc(len + 1);\n size_t i;\n\n if (rev == NULL) {\n exit(1);\n }\n\n for (i = 0; i < len; i++) {\n rev[i] = src[len - i - 1];\n }\n\n#pragma warning(push)\n#pragma warning(disable : 6386)\n // if len + 1 bytes are allocated, and len bytes are writable, there is no buffer overrun\n rev[len] = 0;\n#pragma warning(pop)\n\n if (decode_upc(rev, buffer)) {\n buffer[22] = 0;\n printf(\"%sValid (upside down)\\n\", buffer);\n } else {\n printf(\"Invalid digit(s)\\n\");\n }\n\n free(rev);\n }\n}\n\nint main() {\n int num = 0;\n\n printf(\"%2d: \", ++num);\n test(\" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # \");\n\n printf(\"%2d: \", ++num);\n test(\" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # \");\n\n printf(\"%2d: \", ++num);\n test(\" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # \");\n\n printf(\"%2d: \", ++num);\n test(\" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # \");\n\n printf(\"%2d: \", ++num);\n test(\" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # \");\n\n printf(\"%2d: \", ++num);\n test(\" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # \");\n\n printf(\"%2d: \", ++num);\n test(\" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # \");\n\n printf(\"%2d: \", ++num);\n test(\" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # \");\n\n printf(\"%2d: \", ++num);\n test(\" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # \");\n\n printf(\"%2d: \", ++num);\n test(\" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # \");\n\n return 0;\n}"} {"title": "URL decoding", "language": "C", "task": "This task (the reverse of [[URL encoding]] and distinct from [[URL parser]]) is to provide a function \nor mechanism to convert an URL-encoded string into its original unencoded form.\n\n\n;Test cases:\n* The encoded string \"http%3A%2F%2Ffoo%20bar%2F\" should be reverted to the unencoded form \"http://foo bar/\".\n\n* The encoded string \"google.com/search?q=%60Abdu%27l-Bah%C3%A1\" should revert to the unencoded form \"google.com/search?q=`Abdu'l-Baha\".\n\n* The encoded string \"%25%32%35\" should revert to the unencoded form \"%25\" and '''not''' \"%\".\n\n", "solution": "#include \n#include \n\ninline int ishex(int x)\n{\n\treturn\t(x >= '0' && x <= '9')\t||\n\t\t(x >= 'a' && x <= 'f')\t||\n\t\t(x >= 'A' && x <= 'F');\n}\n\nint decode(const char *s, char *dec)\n{\n\tchar *o;\n\tconst char *end = s + strlen(s);\n\tint c;\n\n\tfor (o = dec; s <= end; o++) {\n\t\tc = *s++;\n\t\tif (c == '+') c = ' ';\n\t\telse if (c == '%' && (\t!ishex(*s++)\t||\n\t\t\t\t\t!ishex(*s++)\t||\n\t\t\t\t\t!sscanf(s - 2, \"%2x\", &c)))\n\t\t\treturn -1;\n\n\t\tif (dec) *o = c;\n\t}\n\n\treturn o - dec;\n}\n\nint main()\n{\n\tconst char *url = \"http%3A%2F%2ffoo+bar%2fabcd\";\n\tchar out[strlen(url) + 1];\n\n\tprintf(\"length: %d\\n\", decode(url, 0));\n\tputs(decode(url, out) < 0 ? \"bad string\" : out);\n\n\treturn 0;\n}"} {"title": "URL encoding", "language": "C", "task": "Provide a function or mechanism to convert a provided string into URL encoding representation.\n\nIn URL encoding, special characters, control characters and extended characters \nare converted into a percent symbol followed by a two digit hexadecimal code, \nSo a space character encodes into %20 within the string.\n\nFor the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default:\n\n* ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal).\n* ASCII symbols (Character ranges 32-47 decimal (20-2F hex))\n* ASCII symbols (Character ranges 58-64 decimal (3A-40 hex))\n* ASCII symbols (Character ranges 91-96 decimal (5B-60 hex))\n* ASCII symbols (Character ranges 123-126 decimal (7B-7E hex))\n* Extended characters with character codes of 128 decimal (80 hex) and above.\n\n\n;Example:\nThe string \"http://foo bar/\" would be encoded as \"http%3A%2F%2Ffoo%20bar%2F\".\n\n\n;Variations:\n* Lowercase escapes are legal, as in \"http%3a%2f%2ffoo%20bar%2f\".\n* Special characters have different encodings for different standards:\n** RFC 3986, ''Uniform Resource Identifier (URI): Generic Syntax'', section 2.3, says to preserve \"-._~\".\n** HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve \"-._*\", and to encode space \" \" to \"+\".\n** encodeURI function in Javascript will preserve \"-._~\" (RFC 3986) and \";,/?:@&=+$!*'()#\".\n\n;Options:\nIt is permissible to use an exception string (containing a set of symbols \nthat do not need to be converted). \nHowever, this is an optional feature and is not a requirement of this task.\n\n\n;Related tasks: \n* [[URL decoding]]\n* [[URL parser]]\n\n", "solution": "#include \n#include \n \nchar rfc3986[256] = {0};\nchar html5[256] = {0};\n\n/* caller responsible for memory */\nvoid encode(const char *s, char *enc, char *tb)\n{\n\tfor (; *s; s++) {\n\t\tif (tb[*s]) sprintf(enc, \"%c\", tb[*s]);\n\t\telse sprintf(enc, \"%%%02X\", *s);\n\t\twhile (*++enc);\n\t}\n}\n \nint main()\n{\n\tconst char url[] = \"http://foo bar/\";\n\tchar enc[(strlen(url) * 3) + 1];\n \n\tint i;\n\tfor (i = 0; i < 256; i++) {\n\t\trfc3986[i] = isalnum(i)||i == '~'||i == '-'||i == '.'||i == '_'\n\t\t\t? i : 0;\n\t\thtml5[i] = isalnum(i)||i == '*'||i == '-'||i == '.'||i == '_'\n\t\t\t? i : (i == ' ') ? '+' : 0;\n\t}\n \n\tencode(url, enc, rfc3986);\n\tputs(enc);\n \n\treturn 0;\n}"} {"title": "UTF-8 encode and decode", "language": "C", "task": "As described in Wikipedia, UTF-8 is a popular encoding of (multi-byte) [[Unicode]] code-points into eight-bit octets.\n\nThe goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the UTF-8 encoding. \n\nThen you have to write the corresponding decoder that takes a sequence of 1-4 UTF-8 encoded bytes and return the corresponding unicode character.\n\nDemonstrate the functionality of your encoder and decoder on the following five characters:\n\n\nCharacter Name Unicode UTF-8 encoding (hex)\n---------------------------------------------------------------------------------\nA LATIN CAPITAL LETTER A U+0041 41\no LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6\nZh CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96\nEUR EURO SIGN U+20AC E2 82 AC\n MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E\n\n\nProvided below is a reference implementation in Common Lisp.\n\n", "solution": "#include \n#include \n#include \n\ntypedef struct {\n\tchar mask; /* char data will be bitwise AND with this */\n\tchar lead; /* start bytes of current char in utf-8 encoded character */\n\tuint32_t beg; /* beginning of codepoint range */\n\tuint32_t end; /* end of codepoint range */\n\tint bits_stored; /* the number of bits from the codepoint that fits in char */\n}utf_t;\n\nutf_t * utf[] = {\n\t/* mask lead beg end bits */\n\t[0] = &(utf_t){0b00111111, 0b10000000, 0, 0, 6 },\n\t[1] = &(utf_t){0b01111111, 0b00000000, 0000, 0177, 7 },\n\t[2] = &(utf_t){0b00011111, 0b11000000, 0200, 03777, 5 },\n\t[3] = &(utf_t){0b00001111, 0b11100000, 04000, 0177777, 4 },\n\t[4] = &(utf_t){0b00000111, 0b11110000, 0200000, 04177777, 3 },\n\t &(utf_t){0},\n};\n\n/* All lengths are in bytes */\nint codepoint_len(const uint32_t cp); /* len of associated utf-8 char */\nint utf8_len(const char ch); /* len of utf-8 encoded char */\n\nchar *to_utf8(const uint32_t cp);\nuint32_t to_cp(const char chr[4]);\n\nint codepoint_len(const uint32_t cp)\n{\n\tint len = 0;\n\tfor(utf_t **u = utf; *u; ++u) {\n\t\tif((cp >= (*u)->beg) && (cp <= (*u)->end)) {\n\t\t\tbreak;\n\t\t}\n\t\t++len;\n\t}\n\tif(len > 4) /* Out of bounds */\n\t\texit(1);\n\n\treturn len;\n}\n\nint utf8_len(const char ch)\n{\n\tint len = 0;\n\tfor(utf_t **u = utf; *u; ++u) {\n\t\tif((ch & ~(*u)->mask) == (*u)->lead) {\n\t\t\tbreak;\n\t\t}\n\t\t++len;\n\t}\n\tif(len > 4) { /* Malformed leading byte */\n\t\texit(1);\n\t}\n\treturn len;\n}\n\nchar *to_utf8(const uint32_t cp)\n{\n\tstatic char ret[5];\n\tconst int bytes = codepoint_len(cp);\n\n\tint shift = utf[0]->bits_stored * (bytes - 1);\n\tret[0] = (cp >> shift & utf[bytes]->mask) | utf[bytes]->lead;\n\tshift -= utf[0]->bits_stored;\n\tfor(int i = 1; i < bytes; ++i) {\n\t\tret[i] = (cp >> shift & utf[0]->mask) | utf[0]->lead;\n\t\tshift -= utf[0]->bits_stored;\n\t}\n\tret[bytes] = '\\0';\n\treturn ret;\n}\n\nuint32_t to_cp(const char chr[4])\n{\n\tint bytes = utf8_len(*chr);\n\tint shift = utf[0]->bits_stored * (bytes - 1);\n\tuint32_t codep = (*chr++ & utf[bytes]->mask) << shift;\n\n\tfor(int i = 1; i < bytes; ++i, ++chr) {\n\t\tshift -= utf[0]->bits_stored;\n\t\tcodep |= ((char)*chr & utf[0]->mask) << shift;\n\t}\n\n\treturn codep;\n}\n\nint main(void)\n{\n\tconst uint32_t *in, input[] = {0x0041, 0x00f6, 0x0416, 0x20ac, 0x1d11e, 0x0};\n\n\tprintf(\"Character Unicode UTF-8 encoding (hex)\\n\");\n\tprintf(\"----------------------------------------\\n\");\n\n\tchar *utf8;\n\tuint32_t codepoint;\n\tfor(in = input; *in; ++in) {\n\t\tutf8 = to_utf8(*in);\n\t\tcodepoint = to_cp(utf8);\n\t\tprintf(\"%s U+%-7.4x\", utf8, codepoint);\n\n\t\tfor(int i = 0; utf8[i] && i < 4; ++i) {\n\t\t\tprintf(\"%hhx \", utf8[i]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\treturn 0;\n}\n"} {"title": "Unbias a random generator", "language": "C", "task": "Given a weighted one-bit generator of random numbers where the probability of a one occurring, P_1, is not the same as P_0, the probability of a zero occurring, the probability of the occurrence of a one followed by a zero is P_1 x P_0, assuming independence. This is the same as the probability of a zero followed by a one: P_0 x P_1.\n\n;Task details:\n* Use your language's random number generator to create a function/method/subroutine/... '''randN''' that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive.\n* Create a function '''unbiased''' that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes.\n* For N over its range, generate and show counts of the outputs of randN and unbiased(randN).\n\n\nThe actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN.\n\nThis task is an implementation of Von Neumann debiasing, first described in a 1951 paper.\n\n", "solution": "#include \n#include \n \nint biased(int bias)\n{\n\t/* balance out the bins, being pedantic */\n\tint r, rand_max = RAND_MAX - (RAND_MAX % bias);\n\twhile ((r = rand()) > rand_max);\n\treturn r < rand_max / bias;\n}\n\nint unbiased(int bias)\n{\n\tint a;\n\twhile ((a = biased(bias)) == biased(bias));\n\treturn a;\n}\n\nint main()\n{\n\tint b, n = 10000, cb, cu, i;\n\tfor (b = 3; b <= 6; b++) {\n\t\tfor (i = cb = cu = 0; i < n; i++) {\n\t\t\tcb += biased(b);\n\t\t\tcu += unbiased(b);\n\t\t}\n\t\tprintf(\"bias %d: %5.3f%% vs %5.3f%%\\n\", b,\n\t\t\t100. * cb / n, 100. * cu / n);\n\t}\n\n\treturn 0;\n}"} {"title": "Unicode strings", "language": "C", "task": "As the world gets smaller each day, internationalization becomes more and more important. For handling multiple languages, [[Unicode]] is your best friend. \n\nIt is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. \n\nHow well prepared is your programming language for Unicode? \n\n\n;Task:\nDiscuss and demonstrate its unicode awareness and capabilities. \n\n\nSome suggested topics:\n:* How easy is it to present Unicode strings in source code? \n:* Can Unicode literals be written directly, or be part of identifiers/keywords/etc?\n:* How well can the language communicate with the rest of the world? \n:* Is it good at input/output with Unicode?\n:* Is it convenient to manipulate Unicode strings in the language?\n:* How broad/deep does the language support Unicode? \n:* What encodings (e.g. UTF-8, UTF-16, etc) can be used? \n:* Does it support normalization?\n\n\n;Note:\nThis task is a bit unusual in that it encourages general discussion rather than clever coding.\n\n\n;See also:\n* [[Unicode variable names]]\n* [[Terminal control/Display an extended character]]\n\n", "solution": "#include \n#include \n#include \n\n/* wchar_t is the standard type for wide chars; what it is internally\n * depends on the compiler.\n */\nwchar_t poker[] = L\"\u2665\u2666\u2663\u2660\";\nwchar_t four_two[] = L\"\\x56db\\x5341\\x4e8c\";\n\nint main() {\n /* Set the locale to alert C's multibyte output routines */\n if (!setlocale(LC_CTYPE, \"\")) {\n fprintf(stderr, \"Locale failure, check your env vars\\n\");\n return 1;\n }\n\n#ifdef __STDC_ISO_10646__\n /* C99 compilers should understand these */\n printf(\"%lc\\n\", 0x2708); /* \u2708 */\n printf(\"%ls\\n\", poker); /* \u2665\u2666\u2663\u2660 */\n printf(\"%ls\\n\", four_two); /* \u56db\u5341\u4e8c */\n#else\n /* oh well */\n printf(\"airplane\\n\");\n printf(\"club diamond club spade\\n\");\n printf(\"for ty two\\n\");\n#endif\n return 0;\n}"} {"title": "Universal Turing machine", "language": "C", "task": "One of the foundational mathematical constructs behind computer science \nis the universal Turing Machine. \n\n\n(Alan Turing introduced the idea of such a machine in 1936-1937.)\n\nIndeed one way to definitively prove that a language \nis turing-complete \nis to implement a universal Turing machine in it.\n\n\n;Task:\nSimulate such a machine capable \nof taking the definition of any other Turing machine and executing it. \n \nOf course, you will not have an infinite tape, \nbut you should emulate this as much as is possible. \n\nThe three permissible actions on the tape are \"left\", \"right\" and \"stay\".\n\nTo test your universal Turing machine (and prove your programming language \nis Turing complete!), you should execute the following two Turing machines \nbased on the following definitions.\n\n\n'''Simple incrementer'''\n* '''States:''' q0, qf\n* '''Initial state:''' q0\n* '''Terminating states:''' qf\n* '''Permissible symbols:''' B, 1\n* '''Blank symbol:''' B\n* '''Rules:'''\n** (q0, 1, 1, right, q0)\n** (q0, B, 1, stay, qf)\n\n\nThe input for this machine should be a tape of 1 1 1\n\n\n'''Three-state busy beaver'''\n* '''States:''' a, b, c, halt\n* '''Initial state:''' a\n* '''Terminating states:''' halt\n* '''Permissible symbols:''' 0, 1\n* '''Blank symbol:''' 0\n* '''Rules:'''\n** (a, 0, 1, right, b)\n** (a, 1, 1, left, c)\n** (b, 0, 1, left, a)\n** (b, 1, 1, right, b)\n** (c, 0, 1, left, b)\n** (c, 1, 1, stay, halt)\n\n\nThe input for this machine should be an empty tape.\n\n\n'''Bonus:'''\n\n'''5-state, 2-symbol probable Busy Beaver machine from Wikipedia'''\n* '''States:''' A, B, C, D, E, H\n* '''Initial state:''' A\n* '''Terminating states:''' H\n* '''Permissible symbols:''' 0, 1\n* '''Blank symbol:''' 0\n* '''Rules:'''\n** (A, 0, 1, right, B)\n** (A, 1, 1, left, C)\n** (B, 0, 1, right, C)\n** (B, 1, 1, right, B)\n** (C, 0, 1, right, D)\n** (C, 1, 0, left, E)\n** (D, 0, 1, left, A)\n** (D, 1, 1, left, D)\n** (E, 0, 1, stay, H)\n** (E, 1, 0, left, A)\n\n\nThe input for this machine should be an empty tape.\n\nThis machine runs for more than 47 millions steps.\n\n", "solution": "#include \n#include \n#include \n#include \n\nenum {\n LEFT,\n RIGHT,\n STAY\n};\n\ntypedef struct {\n int state1;\n int symbol1;\n int symbol2;\n int dir;\n int state2;\n} transition_t;\n\ntypedef struct tape_t tape_t;\nstruct tape_t {\n int symbol;\n tape_t *left;\n tape_t *right;\n};\n\ntypedef struct {\n int states_len;\n char **states;\n int final_states_len;\n int *final_states;\n int symbols_len;\n char *symbols;\n int blank;\n int state;\n int tape_len;\n tape_t *tape;\n int transitions_len;\n transition_t ***transitions;\n} turing_t;\n\nint state_index (turing_t *t, char *state) {\n int i;\n for (i = 0; i < t->states_len; i++) {\n if (!strcmp(t->states[i], state)) {\n return i;\n }\n }\n return 0;\n}\n\nint symbol_index (turing_t *t, char symbol) {\n int i;\n for (i = 0; i < t->symbols_len; i++) {\n if (t->symbols[i] == symbol) {\n return i;\n }\n }\n return 0;\n}\n\nvoid move (turing_t *t, int dir) {\n tape_t *orig = t->tape;\n if (dir == RIGHT) {\n if (orig && orig->right) {\n t->tape = orig->right;\n }\n else {\n t->tape = calloc(1, sizeof (tape_t));\n t->tape->symbol = t->blank;\n if (orig) {\n t->tape->left = orig;\n orig->right = t->tape;\n }\n }\n }\n else if (dir == LEFT) {\n if (orig && orig->left) {\n t->tape = orig->left;\n }\n else {\n t->tape = calloc(1, sizeof (tape_t));\n t->tape->symbol = t->blank;\n if (orig) {\n t->tape->right = orig;\n orig->left = t->tape;\n }\n }\n }\n}\n\nturing_t *create (int states_len, ...) {\n va_list args;\n va_start(args, states_len);\n turing_t *t = malloc(sizeof (turing_t));\n t->states_len = states_len;\n t->states = malloc(states_len * sizeof (char *));\n int i;\n for (i = 0; i < states_len; i++) {\n t->states[i] = va_arg(args, char *);\n }\n t->final_states_len = va_arg(args, int);\n t->final_states = malloc(t->final_states_len * sizeof (int));\n for (i = 0; i < t->final_states_len; i++) {\n t->final_states[i] = state_index(t, va_arg(args, char *));\n }\n t->symbols_len = va_arg(args, int);\n t->symbols = malloc(t->symbols_len);\n for (i = 0; i < t->symbols_len; i++) {\n t->symbols[i] = va_arg(args, int);\n }\n t->blank = symbol_index(t, va_arg(args, int));\n t->state = state_index(t, va_arg(args, char *));\n t->tape_len = va_arg(args, int);\n t->tape = NULL;\n for (i = 0; i < t->tape_len; i++) {\n move(t, RIGHT);\n t->tape->symbol = symbol_index(t, va_arg(args, int));\n }\n if (!t->tape_len) {\n move(t, RIGHT);\n }\n while (t->tape->left) {\n t->tape = t->tape->left;\n }\n t->transitions_len = va_arg(args, int);\n t->transitions = malloc(t->states_len * sizeof (transition_t **));\n for (i = 0; i < t->states_len; i++) {\n t->transitions[i] = malloc(t->symbols_len * sizeof (transition_t *));\n }\n for (i = 0; i < t->transitions_len; i++) {\n transition_t *tran = malloc(sizeof (transition_t));\n tran->state1 = state_index(t, va_arg(args, char *));\n tran->symbol1 = symbol_index(t, va_arg(args, int));\n tran->symbol2 = symbol_index(t, va_arg(args, int));\n tran->dir = va_arg(args, int);\n tran->state2 = state_index(t, va_arg(args, char *));\n t->transitions[tran->state1][tran->symbol1] = tran;\n }\n va_end(args);\n return t;\n}\n\nvoid print_state (turing_t *t) {\n printf(\"%-10s \", t->states[t->state]);\n tape_t *tape = t->tape;\n while (tape->left) {\n tape = tape->left;\n }\n while (tape) {\n if (tape == t->tape) {\n printf(\"[%c]\", t->symbols[tape->symbol]);\n }\n else {\n printf(\" %c \", t->symbols[tape->symbol]);\n }\n tape = tape->right;\n }\n printf(\"\\n\");\n}\n\nvoid run (turing_t *t) {\n int i;\n while (1) {\n print_state(t);\n for (i = 0; i < t->final_states_len; i++) {\n if (t->final_states[i] == t->state) {\n return;\n }\n }\n transition_t *tran = t->transitions[t->state][t->tape->symbol];\n t->tape->symbol = tran->symbol2;\n move(t, tran->dir);\n t->state = tran->state2;\n }\n}\n\nint main () {\n printf(\"Simple incrementer\\n\");\n turing_t *t = create(\n /* states */ 2, \"q0\", \"qf\",\n /* final_states */ 1, \"qf\",\n /* symbols */ 2, 'B', '1',\n /* blank */ 'B',\n /* initial_state */ \"q0\",\n /* initial_tape */ 3, '1', '1', '1',\n /* transitions */ 2,\n \"q0\", '1', '1', RIGHT, \"q0\",\n \"q0\", 'B', '1', STAY, \"qf\"\n );\n run(t);\n printf(\"\\nThree-state busy beaver\\n\");\n t = create(\n /* states */ 4, \"a\", \"b\", \"c\", \"halt\",\n /* final_states */ 1, \"halt\",\n /* symbols */ 2, '0', '1',\n /* blank */ '0',\n /* initial_state */ \"a\",\n /* initial_tape */ 0,\n /* transitions */ 6,\n \"a\", '0', '1', RIGHT, \"b\",\n \"a\", '1', '1', LEFT, \"c\",\n \"b\", '0', '1', LEFT, \"a\",\n \"b\", '1', '1', RIGHT, \"b\",\n \"c\", '0', '1', LEFT, \"b\",\n \"c\", '1', '1', STAY, \"halt\"\n );\n run(t);\n return 0;\n printf(\"\\nFive-state two-symbol probable busy beaver\\n\");\n t = create(\n /* states */ 6, \"A\", \"B\", \"C\", \"D\", \"E\", \"H\",\n /* final_states */ 1, \"H\",\n /* symbols */ 2, '0', '1',\n /* blank */ '0',\n /* initial_state */ \"A\",\n /* initial_tape */ 0,\n /* transitions */ 10,\n \"A\", '0', '1', RIGHT, \"B\",\n \"A\", '1', '1', LEFT, \"C\",\n \"B\", '0', '1', RIGHT, \"C\",\n \"B\", '1', '1', RIGHT, \"B\",\n \"C\", '0', '1', RIGHT, \"D\",\n \"C\", '1', '0', LEFT, \"E\",\n \"D\", '0', '1', LEFT, \"A\",\n \"D\", '1', '1', LEFT, \"D\",\n \"E\", '0', '1', STAY, \"H\",\n \"E\", '1', '0', LEFT, \"A\"\n );\n run(t);\n}\n"} {"title": "Unix/ls", "language": "C", "task": "Write a program that will list everything in the current folder, similar to:\n:::* the Unix utility \"ls\" [http://man7.org/linux/man-pages/man1/ls.1.html] or \n:::* the Windows terminal command \"DIR\" \n\n\nThe output must be sorted, but printing extended details and producing multi-column output is not required.\n\n\n;Example output\nFor the list of paths:\n\n/foo/bar\n/foo/bar/1\n/foo/bar/2\n/foo/bar/a\n/foo/bar/b\n\n\n\nWhen the program is executed in `/foo`, it should print:\n\nbar\n\nand when the program is executed in `/foo/bar`, it should print:\n\n1\n2\na\nb\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nint cmpstr(const void *a, const void *b)\n{\n return strcmp(*(const char**)a, *(const char**)b);\n}\n\nint main(void)\n{\n DIR *basedir;\n char path[PATH_MAX];\n struct dirent *entry;\n char **dirnames;\n int diralloc = 128;\n int dirsize = 0;\n \n if (!(dirnames = malloc(diralloc * sizeof(char*)))) {\n perror(\"malloc error:\");\n return 1;\n }\n\n if (!getcwd(path, PATH_MAX)) {\n perror(\"getcwd error:\");\n return 1;\n }\n\n if (!(basedir = opendir(path))) {\n perror(\"opendir error:\");\n return 1;\n }\n\n while ((entry = readdir(basedir))) {\n if (dirsize >= diralloc) {\n diralloc *= 2;\n if (!(dirnames = realloc(dirnames, diralloc * sizeof(char*)))) {\n perror(\"realloc error:\");\n return 1;\n }\n }\n dirnames[dirsize++] = strdup(entry->d_name);\n }\n\n qsort(dirnames, dirsize, sizeof(char*), cmpstr);\n\n int i;\n for (i = 0; i < dirsize; ++i) {\n if (dirnames[i][0] != '.') {\n printf(\"%s\\n\", dirnames[i]);\n }\n }\n\n for (i = 0; i < dirsize; ++i)\n free(dirnames[i]);\n free(dirnames);\n closedir(basedir);\n return 0;\n}\n"} {"title": "Validate International Securities Identification Number", "language": "C", "task": "An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. \n\n\n;Task:\nWrite a function or program that takes a string as input, and checks whether it is a valid ISIN.\n\nIt is only valid if it has the correct format, ''and'' the embedded checksum is correct.\n\nDemonstrate that your code passes the test-cases listed below.\n\n\n;Details:\nThe format of an ISIN is as follows:\n\n\n\n+------------- a 2-character ISO country code (A-Z)\n| +----------- a 9-character security code (A-Z, 0-9)\n| | +-- a checksum digit (0-9)\nAU0000XVGZA3\n\n\n\n\nFor this task, you may assume that any 2-character alphabetic sequence is a valid country code.\n\nThe checksum can be validated as follows:\n# '''Replace letters with digits''', by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 -1030000033311635103.\n# '''Perform the Luhn test on this base-10 number.'''There is a separate task for this test: ''[[Luhn test of credit card numbers]]''.You don't have to replicate the implementation of this test here --- you can just call the existing function from that task. (Add a comment stating if you did this.)\n\n\n;Test cases:\n:::: {| class=\"wikitable\"\n! ISIN\n! Validity\n! Comment\n|-\n| US0378331005 || valid || \n|-\n| US0373831005 || not valid || The transposition typo is caught by the checksum constraint.\n|-\n| U50378331005 || not valid || The substitution typo is caught by the format constraint.\n|-\n| US03378331005 || not valid || The duplication typo is caught by the format constraint.\n|-\n| AU0000XVGZA3 || valid || \n|-\n| AU0000VXGZA3 || valid || Unfortunately, not ''all'' transposition typos are caught by the checksum constraint.\n|-\n| FR0000988040 || valid || \n|}\n\n(The comments are just informational. Your function should simply return a Boolean result. See [[#Raku]] for a reference solution.)\n\n\nRelated task:\n* [[Luhn test of credit card numbers]]\n\n\n;Also see:\n* Interactive online ISIN validator\n* Wikipedia article: International Securities Identification Number\n\n", "solution": "#include \n\nint check_isin(char *a) {\n int i, j, k, v, s[24];\n \n j = 0;\n for(i = 0; i < 12; i++) {\n k = a[i];\n if(k >= '0' && k <= '9') {\n if(i < 2) return 0;\n s[j++] = k - '0';\n } else if(k >= 'A' && k <= 'Z') {\n if(i == 11) return 0;\n k -= 'A' - 10;\n s[j++] = k / 10;\n s[j++] = k % 10;\n } else {\n return 0;\n }\n }\n \n if(a[i]) return 0;\n \n v = 0;\n for(i = j - 2; i >= 0; i -= 2) {\n k = 2 * s[i];\n v += k > 9 ? k - 9 : k;\n }\n \n for(i = j - 1; i >= 0; i -= 2) {\n v += s[i];\n }\n \n return v % 10 == 0;\n}\n\nint main() {\n char *test[7] = {\"US0378331005\", \"US0373831005\", \"U50378331005\",\n \"US03378331005\", \"AU0000XVGZA3\", \"AU0000VXGZA3\",\n \"FR0000988040\"};\n int i;\n for(i = 0; i < 7; i++) printf(\"%c%c\", check_isin(test[i]) ? 'T' : 'F', i == 6 ? '\\n' : ' ');\n return 0;\n}\n\n/* will print: T F F F T T T */"} {"title": "Van Eck sequence", "language": "C", "task": "The sequence is generated by following this pseudo-code:\n\nA: The first term is zero.\n Repeatedly apply:\n If the last term is *new* to the sequence so far then:\nB: The next term is zero.\n Otherwise:\nC: The next term is how far back this last term occured previously.\n\n\n\n;Example:\nUsing A:\n:0\nUsing B:\n:0 0\nUsing C:\n:0 0 1\nUsing B:\n:0 0 1 0\nUsing C: (zero last occurred two steps back - before the one)\n:0 0 1 0 2\nUsing B:\n:0 0 1 0 2 0\nUsing C: (two last occurred two steps back - before the zero)\n:0 0 1 0 2 0 2 2\nUsing C: (two last occurred one step back)\n:0 0 1 0 2 0 2 2 1\nUsing C: (one last appeared six steps back)\n:0 0 1 0 2 0 2 2 1 6\n...\n\n\n;Task:\n# Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers.\n# Use it to display here, on this page:\n:# The first ten terms of the sequence.\n:# Terms 991 - to - 1000 of the sequence.\n\n\n;References:\n* Don't Know (the Van Eck Sequence) - Numberphile video.\n* Wikipedia Article: Van Eck's Sequence.\n* OEIS sequence: A181391.\n\n", "solution": "#include \n#include \n\nint main(int argc, const char *argv[]) {\n const int max = 1000;\n int *a = malloc(max * sizeof(int));\n for (int n = 0; n < max - 1; n ++) {\n for (int m = n - 1; m >= 0; m --) {\n if (a[m] == a[n]) {\n a[n+1] = n - m;\n break;\n }\n }\n }\n\n printf(\"The first ten terms of the Van Eck sequence are:\\n\");\n for (int i = 0; i < 10; i ++) printf(\"%d \", a[i]);\n printf(\"\\n\\nTerms 991 to 1000 of the sequence are:\\n\");\n for (int i = 990; i < 1000; i ++) printf(\"%d \", a[i]);\n putchar('\\n');\n\n return 0;\n}"} {"title": "Van der Corput sequence", "language": "C", "task": "When counting integers in binary, if you put a (binary) point to the right of the count then the column immediately to the left denotes a digit with a multiplier of 2^0; the digit in the next column to the left has a multiplier of 2^1; and so on.\n\nSo in the following table:\n 0.\n 1.\n 10.\n 11.\n ...\nthe binary number \"10\" is 1 \\times 2^1 + 0 \\times 2^0.\n\nYou can also have binary digits to the right of the \"point\", just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of 2^{-1}, or 1/2. \nThe weight for the second column to the right of the point is 2^{-2} or 1/4. And so on.\n\nIf you take the integer binary count of the first table, and ''reflect'' the digits about the binary point, you end up with '''the van der Corput sequence of numbers in base 2'''.\n\n .0\n .1\n .01\n .11\n ...\n\nThe third member of the sequence, binary 0.01, is therefore 0 \\times 2^{-1} + 1 \\times 2^{-2} or 1/4.\n\n Monte Carlo simulations. \nThis sequence is also a superset of the numbers representable by the \"fraction\" field of an old IEEE floating point standard. In that standard, the \"fraction\" field represented the fractional part of a binary number beginning with \"1.\" e.g. 1.101001101.\n\n'''Hint'''\n\nA ''hint'' at a way to generate members of the sequence is to modify a routine used to change the base of an integer:\n>>> def base10change(n, base):\n\tdigits = []\n\twhile n:\n\t\tn,remainder = divmod(n, base)\n\t\tdigits.insert(0, remainder)\n\treturn digits\n\n>>> base10change(11, 2)\n[1, 0, 1, 1]\nthe above showing that 11 in decimal is 1\\times 2^3 + 0\\times 2^2 + 1\\times 2^1 + 1\\times 2^0.\nReflected this would become .1101 or 1\\times 2^{-1} + 1\\times 2^{-2} + 0\\times 2^{-3} + 1\\times 2^{-4}\n\n\n;Task description:\n* Create a function/method/routine that given ''n'', generates the ''n'''th term of the van der Corput sequence in base 2.\n* Use the function to compute ''and display'' the first ten members of the sequence. (The first member of the sequence is for ''n''=0).\n\n* As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2.\n\n\n\n;See also:\n* The Basic Low Discrepancy Sequences\n* [[Non-decimal radices/Convert]]\n* Van der Corput sequence\n\n", "solution": "#include \n\nvoid vc(int n, int base, int *num, int *denom)\n{\n int p = 0, q = 1;\n\n while (n) {\n p = p * base + (n % base);\n q *= base;\n n /= base;\n }\n\n *num = p; \n *denom = q;\n\n while (p) { n = p; p = q % p; q = n; }\n *num /= q;\n *denom /= q;\n}\n\nint main()\n{\n int d, n, i, b;\n for (b = 2; b < 6; b++) {\n printf(\"base %d:\", b);\n for (i = 0; i < 10; i++) {\n vc(i, b, &n, &d);\n if (n) printf(\" %d/%d\", n, d);\n else printf(\" 0\");\n }\n printf(\"\\n\");\n }\n\n return 0;\n}"} {"title": "Variable declaration reset", "language": "C", "task": "A decidely non-challenging task to highlight a potential difference between programming languages.\n\nUsing a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may be 2,5 for zero-based or 3,6 if one-based. \nThe purpose is to determine whether variable declaration (in block scope) resets the contents on every iteration.\nThere is no particular judgement of right or wrong here, just a plain-speaking statement of subtle differences.\nShould your first attempt bomb with \"unassigned variable\" exceptions, feel free to code it as (say)\n // int prev // crashes with unassigned variable\n int prev = -1 // predictably no output\nIf your programming language does not support block scope (eg assembly) it should be omitted from this task.\n\n", "solution": "#include \n\nint main() {\n int i, gprev = 0;\n int s[7] = {1, 2, 2, 3, 4, 4, 5};\n\n /* There is no output as 'prev' is created anew each time\n around the loop and set explicitly to zero. */\n for (i = 0; i < 7; ++i) {\n// for (int i = 0, prev; i < 7; ++i) { // as below, see note\n int curr = s[i];\n int prev = 0;\n// int prev; // produces same output as second loop\n if (i > 0 && curr == prev) printf(\"%d\\n\", i);\n prev = curr;\n }\n\n /* Now 'gprev' is used and reassigned\n each time around the loop producing the desired output. */\n for (i = 0; i < 7; ++i) {\n int curr = s[i];\n if (i > 0 && curr == gprev) printf(\"%d\\n\", i);\n gprev = curr;\n }\n\n return 0;\n}"} {"title": "Vector products", "language": "C", "task": "A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z). \n\nIf you imagine a graph with the '''x''' and '''y''' axis being at right angles to each other and having a third, '''z''' axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point.\n\nGiven the vectors:\n A = (a1, a2, a3) \n B = (b1, b2, b3) \n C = (c1, c2, c3) \nthen the following common vector products are defined:\n* '''The dot product''' (a scalar quantity)\n:::: A * B = a1b1 + a2b2 + a3b3 \n* '''The cross product''' (a vector quantity)\n:::: A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1) \n* '''The scalar triple product''' (a scalar quantity)\n:::: A * (B x C) \n* '''The vector triple product''' (a vector quantity)\n:::: A x (B x C) \n\n\n;Task:\nGiven the three vectors: \n a = ( 3, 4, 5)\n b = ( 4, 3, 5)\n c = (-5, -12, -13)\n# Create a named function/subroutine/method to compute the dot product of two vectors.\n# Create a function to compute the cross product of two vectors.\n# Optionally create a function to compute the scalar triple product of three vectors.\n# Optionally create a function to compute the vector triple product of three vectors.\n# Compute and display: a * b\n# Compute and display: a x b\n# Compute and display: a * (b x c), the scalar triple product.\n# Compute and display: a x (b x c), the vector triple product.\n\n\n;References:\n* A starting page on Wolfram MathWorld is {{Wolfram|Vector|Multiplication}}.\n* Wikipedia dot product. \n* Wikipedia cross product. \n* Wikipedia triple product.\n\n\n;Related tasks:\n* [[Dot product]]\n* [[Quaternion type]]\n\n", "solution": "#include\n\ntypedef struct{\n\tfloat i,j,k;\n\t}Vector;\n\nVector a = {3, 4, 5},b = {4, 3, 5},c = {-5, -12, -13};\n\nfloat dotProduct(Vector a, Vector b)\n{\n\treturn a.i*b.i+a.j*b.j+a.k*b.k;\n}\n\nVector crossProduct(Vector a,Vector b)\n{\n\tVector c = {a.j*b.k - a.k*b.j, a.k*b.i - a.i*b.k, a.i*b.j - a.j*b.i};\n\t\n\treturn c;\n}\n\nfloat scalarTripleProduct(Vector a,Vector b,Vector c)\n{\n\treturn dotProduct(a,crossProduct(b,c));\n}\n\nVector vectorTripleProduct(Vector a,Vector b,Vector c)\n{\n\treturn crossProduct(a,crossProduct(b,c));\n}\n\nvoid printVector(Vector a)\n{\n\tprintf(\"( %f, %f, %f)\",a.i,a.j,a.k);\n}\n\nint main()\n{\n\tprintf(\"\\n a = \"); printVector(a);\n\tprintf(\"\\n b = \"); printVector(b);\n\tprintf(\"\\n c = \"); printVector(c);\n\tprintf(\"\\n a . b = %f\",dotProduct(a,b));\n\tprintf(\"\\n a x b = \"); printVector(crossProduct(a,b));\n\tprintf(\"\\n a . (b x c) = %f\",scalarTripleProduct(a,b,c));\n\tprintf(\"\\n a x (b x c) = \"); printVector(vectorTripleProduct(a,b,c));\n\t\n\treturn 0;\n}"} {"title": "Verhoeff algorithm", "language": "C", "task": "Description\nThe Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at the time thought impossible with such a code. \n\nAs the workings of the algorithm are clearly described in the linked Wikipedia article they will not be repeated here. \n\n;Task:\nWrite routines, methods, procedures etc. in your language to generate a Verhoeff checksum digit for non-negative integers of any length and to validate the result. A combined routine is also acceptable.\n\nThe more mathematically minded may prefer to generate the 3 tables required from the description provided rather than to hard-code them.\n\nWrite your routines in such a way that they can optionally display digit by digit calculations as in the Wikipedia example.\n\nUse your routines to calculate check digits for the integers: '''236''', '''12345''' and '''123456789012''' and then validate them. Also attempt to validate the same integers if the check digits in all cases were '''9''' rather than what they actually are.\n\nDisplay digit by digit calculations for the first two integers but not for the third. \n\n;Related task:\n* [[Damm algorithm]]\n\n", "solution": "#include \n#include \n#include \n#include \n\nstatic const int d[][10] = {\n {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 2, 3, 4, 0, 6, 7, 8, 9, 5},\n {2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, {3, 4, 0, 1, 2, 8, 9, 5, 6, 7},\n {4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, {5, 9, 8, 7, 6, 0, 4, 3, 2, 1},\n {6, 5, 9, 8, 7, 1, 0, 4, 3, 2}, {7, 6, 5, 9, 8, 2, 1, 0, 4, 3},\n {8, 7, 6, 5, 9, 3, 2, 1, 0, 4}, {9, 8, 7, 6, 5, 4, 3, 2, 1, 0},\n};\n\nstatic const int inv[] = {0, 4, 3, 2, 1, 5, 6, 7, 8, 9};\n\nstatic const int p[][10] = {\n {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 5, 7, 6, 2, 8, 3, 0, 9, 4},\n {5, 8, 0, 3, 7, 9, 6, 1, 4, 2}, {8, 9, 1, 6, 0, 4, 3, 5, 2, 7},\n {9, 4, 5, 3, 1, 2, 6, 8, 7, 0}, {4, 2, 8, 6, 5, 7, 3, 9, 0, 1},\n {2, 7, 9, 3, 8, 0, 6, 4, 1, 5}, {7, 0, 4, 6, 9, 1, 3, 2, 5, 8},\n};\n\nint verhoeff(const char* s, bool validate, bool verbose) {\n if (verbose) {\n const char* t = validate ? \"Validation\" : \"Check digit\";\n printf(\"%s calculations for '%s':\\n\\n\", t, s);\n puts(u8\" i n\\xE1\\xB5\\xA2 p[i,n\\xE1\\xB5\\xA2] c\");\n puts(\"------------------\");\n }\n int len = strlen(s);\n if (validate)\n --len;\n int c = 0;\n for (int i = len; i >= 0; --i) {\n int ni = (i == len && !validate) ? 0 : s[i] - '0';\n assert(ni >= 0 && ni < 10);\n int pi = p[(len - i) % 8][ni];\n c = d[c][pi];\n if (verbose)\n printf(\"%2d %d %d %d\\n\", len - i, ni, pi, c);\n }\n if (verbose && !validate)\n printf(\"\\ninv[%d] = %d\\n\", c, inv[c]);\n return validate ? c == 0 : inv[c];\n}\n\nint main() {\n const char* ss[3] = {\"236\", \"12345\", \"123456789012\"};\n for (int i = 0; i < 3; ++i) {\n const char* s = ss[i];\n bool verbose = i < 2;\n int c = verhoeff(s, false, verbose);\n printf(\"\\nThe check digit for '%s' is '%d'.\\n\", s, c);\n int len = strlen(s);\n char sc[len + 2];\n strncpy(sc, s, len + 2);\n for (int j = 0; j < 2; ++j) {\n sc[len] = (j == 0) ? c + '0' : '9';\n int v = verhoeff(sc, true, verbose);\n printf(\"\\nThe validation for '%s' is %s.\\n\", sc,\n v ? \"correct\" : \"incorrect\");\n }\n }\n return 0;\n}"} {"title": "Visualize a tree", "language": "C", "task": "A tree structure (i.e. a rooted, connected acyclic graph) is often used in programming. \n\nIt's often helpful to visually examine such a structure. \n\nThere are many ways to represent trees to a reader, such as:\n:::* indented text (a la unix tree command)\n:::* nested HTML tables\n:::* hierarchical GUI widgets\n:::* 2D or 3D images\n:::* etc.\n\n;Task:\nWrite a program to produce a visual representation of some tree. \n\nThe content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly. \n\nMake do with the vague term \"friendly\" the best you can.\n\n", "solution": "#include \n#include \n\ntypedef struct stem_t *stem;\nstruct stem_t { const char *str; stem next; };\n\nvoid tree(int root, stem head)\n{\n\tstatic const char *sdown = \" |\", *slast = \" `\", *snone = \" \";\n\tstruct stem_t col = {0, 0}, *tail;\n\n\tfor (tail = head; tail; tail = tail->next) {\n\t\tprintf(\"%s\", tail->str);\n\t\tif (!tail->next) break;\n\t}\n\n\tprintf(\"--%d\\n\", root);\n\n\tif (root <= 1) return;\n\n\tif (tail && tail->str == slast)\n\t\ttail->str = snone;\n\n\tif (!tail)\ttail = head = &col;\n\telse\t\ttail->next = &col;\n\n\twhile (root) { // make a tree by doing something random\n\t\tint r = 1 + (rand() % root);\n\t\troot -= r;\n\t\tcol.str = root ? sdown : slast;\n\n\t\ttree(r, head);\n\t}\n\n\ttail->next = 0;\n}\n\nint main(int c, char**v)\n{\n\tint n;\n\tif (c < 2 || (n = atoi(v[1])) < 0) n = 8;\n\n\ttree(n, 0);\n\treturn 0;\n}"} {"title": "Voronoi diagram", "language": "C", "task": "A Voronoi diagram is a diagram consisting of a number of sites. \n\nEach Voronoi site ''s'' also has a Voronoi cell consisting of all points closest to ''s''.\n\n\n;Task:\nDemonstrate how to generate and display a Voroni diagram. \n\n\nSee algo [[K-means++ clustering]].\n\n", "solution": "#include \n#include \n#include \n\n#define N_SITES 150\ndouble site[N_SITES][2];\nunsigned char rgb[N_SITES][3];\n\nint size_x = 640, size_y = 480;\n\ninline double sq2(double x, double y)\n{\n\treturn x * x + y * y;\n}\n\n#define for_k for (k = 0; k < N_SITES; k++)\nint nearest_site(double x, double y)\n{\n\tint k, ret = 0;\n\tdouble d, dist = 0;\n\tfor_k {\n\t\td = sq2(x - site[k][0], y - site[k][1]);\n\t\tif (!k || d < dist) {\n\t\t\tdist = d, ret = k;\n\t\t}\n\t}\n\treturn ret;\n}\n\n/* see if a pixel is different from any neighboring ones */\nint at_edge(int *color, int y, int x)\n{\n\tint i, j, c = color[y * size_x + x];\n\tfor (i = y - 1; i <= y + 1; i++) {\n\t\tif (i < 0 || i >= size_y) continue;\n\n\t\tfor (j = x - 1; j <= x + 1; j++) {\n\t\t\tif (j < 0 || j >= size_x) continue;\n\t\t\tif (color[i * size_x + j] != c) return 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\n#define AA_RES 4 /* average over 4x4 supersampling grid */\nvoid aa_color(unsigned char *pix, int y, int x)\n{\n\tint i, j, n;\n\tdouble r = 0, g = 0, b = 0, xx, yy;\n\tfor (i = 0; i < AA_RES; i++) {\n\t\tyy = y + 1. / AA_RES * i + .5;\n\t\tfor (j = 0; j < AA_RES; j++) {\n\t\t\txx = x + 1. / AA_RES * j + .5;\n\t\t\tn = nearest_site(xx, yy);\n\t\t\tr += rgb[n][0];\n\t\t\tg += rgb[n][1];\n\t\t\tb += rgb[n][2];\n\t\t}\n\t}\n\tpix[0] = r / (AA_RES * AA_RES);\n\tpix[1] = g / (AA_RES * AA_RES);\n\tpix[2] = b / (AA_RES * AA_RES);\n}\n\n#define for_i for (i = 0; i < size_y; i++)\n#define for_j for (j = 0; j < size_x; j++)\nvoid gen_map()\n{\n\tint i, j, k;\n\tint *nearest = malloc(sizeof(int) * size_y * size_x);\n\tunsigned char *ptr, *buf, color;\n\n\tptr = buf = malloc(3 * size_x * size_y);\n\tfor_i for_j nearest[i * size_x + j] = nearest_site(j, i);\n\n\tfor_i for_j {\n\t\tif (!at_edge(nearest, i, j))\n\t\t\tmemcpy(ptr, rgb[nearest[i * size_x + j]], 3);\n\t\telse\t/* at edge, do anti-alias rastering */\n\t\t\taa_color(ptr, i, j);\n\t\tptr += 3;\n\t}\n\n\t/* draw sites */\n\tfor (k = 0; k < N_SITES; k++) {\n\t\tcolor = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255;\n\n\t\tfor (i = site[k][1] - 1; i <= site[k][1] + 1; i++) {\n\t\t\tif (i < 0 || i >= size_y) continue;\n\n\t\t\tfor (j = site[k][0] - 1; j <= site[k][0] + 1; j++) {\n\t\t\t\tif (j < 0 || j >= size_x) continue;\n\n\t\t\t\tptr = buf + 3 * (i * size_x + j);\n\t\t\t\tptr[0] = ptr[1] = ptr[2] = color;\n\t\t\t}\n\t\t}\n\t}\n\n\tprintf(\"P6\\n%d %d\\n255\\n\", size_x, size_y);\n\tfflush(stdout);\n\tfwrite(buf, size_y * size_x * 3, 1, stdout);\n}\n\n#define frand(x) (rand() / (1. + RAND_MAX) * x)\nint main()\n{\n\tint k;\n\tfor_k {\n\t\tsite[k][0] = frand(size_x);\n\t\tsite[k][1] = frand(size_y);\n\t\trgb [k][0] = frand(256);\n\t\trgb [k][1] = frand(256);\n\t\trgb [k][2] = frand(256);\n\t}\n\n\tgen_map();\n\treturn 0;\n}"} {"title": "Water collected between towers", "language": "C", "task": "In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains, \ncompletely filling all convex enclosures in the chart with water. \n\n \n9 ## 9 ## \n8 ## 8 ## \n7 ## ## 7 #### \n6 ## ## ## 6 ###### \n5 ## ## ## #### 5 ########## \n4 ## ## ######## 4 ############ \n3 ###### ######## 3 ############## \n2 ################ ## 2 ##################\n1 #################### 1 ####################\n \n\nIn the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.\n\nWrite a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.\n\nCalculate the number of water units that could be collected by bar charts representing each of the following seven series:\n\n [[1, 5, 3, 7, 2],\n [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n [5, 5, 5, 5],\n [5, 6, 7, 8],\n [8, 7, 7, 6],\n [6, 7, 10, 7, 6]]\n\n\nSee, also:\n\n* Four Solutions to a Trivial Problem - a Google Tech Talk by Guy Steele\n* Water collected between towers on Stack Overflow, from which the example above is taken)\n* An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.\n\n\n\n", "solution": "#include\n#include\n\nint getWater(int* arr,int start,int end,int cutoff){\n\tint i, sum = 0;\n\t\n\tfor(i=start;i<=end;i++)\n\t\tsum += ((arr[cutoff] > arr[i])?(arr[cutoff] - arr[i]):0);\n\t\n\treturn sum;\n}\n\nint netWater(int* arr,int size){\n\tint i, j, ref1, ref2, marker, markerSet = 0,sum = 0;\n\t\n\tif(size<3)\n\t\treturn 0;\n\n\tfor(i=0;iarr[i+1]){\n\t\t\t\tref1 = i;\n\t\t\t\t\n\t\t\t\tfor(j=ref1+1;j=arr[ref1]){\n\t\t\t\t\t\tref2 = j;\n\t\t\t\t\t\t\n\t\t\t\t\t\tsum += getWater(arr,ref1+1,ref2-1,ref1);\n\n\t\t\t\t\t\ti = ref2;\n\t\t\t\t\t\t\n\t\t\t\t\t\tgoto start;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse if(j!=size-1 && arr[j] < arr[j+1] && (markerSet==0||(arr[j+1]>=arr[marker]))){\n\t\t\t\t\t\tmarker = j+1;\n\t\t\t\t\t\tmarkerSet = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(markerSet==1){\n\t\t\t\t\tsum += getWater(arr,ref1+1,marker-1,marker);\n\n\t\t\t\t\ti = marker;\n\t\t\t\t\t\n\t\t\t\t\tmarkerSet = 0;\n\t\t\t\t\t\n\t\t\t\t\tgoto start;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\treturn sum;\n}\n\nint main(int argC,char* argV[])\n{\n\tint *arr,i;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s \");\n\telse{\n\t\tarr = (int*)malloc((argC-1)*sizeof(int));\n\t\t\n\t\tfor(i=1;i\n#include \n#include \n#include \n\n/* nonsensical hyphens to make greedy wrapping method look bad */\nconst char *string = \"In olden times when wishing still helped one, there lived a king \"\n \"whose daughters were all beautiful, but the youngest was so beautiful \"\n \"that the sun itself, which has seen so much, was astonished whenever \"\n \"it shone-in-her-face. Close-by-the-king's castle lay a great dark \"\n \"forest, and under an old lime-tree in the forest was a well, and when \"\n \"the day was very warm, the king's child went out into the forest and \"\n \"sat down by the side of the cool-fountain, and when she was bored she \"\n \"took a golden ball, and threw it up on high and caught it, and this \"\n \"ball was her favorite plaything.\";\n\n/* Each but the last of wrapped lines comes with some penalty as the square\n of the diff between line length and desired line length. If the line\n is longer than desired length, the penalty is multiplied by 100. This\n pretty much prohibits the wrapping routine from going over right margin.\n If is ok to exceed the margin just a little, something like 20 or 40 will\n do.\n\n Knuth uses a per-paragraph penalty for line-breaking in TeX, which is--\n unlike what I have here--probably bug-free.\n*/\n\n#define PENALTY_LONG 100\n#define PENALTY_SHORT 1\n\ntypedef struct word_t {\n const char *s;\n int len;\n} *word;\n\nword make_word_list(const char *s, int *n)\n{\n int max_n = 0;\n word words = 0;\n\n *n = 0;\n while (1) {\n while (*s && isspace(*s)) s++;\n if (!*s) break;\n\n if (*n >= max_n) {\n if (!(max_n *= 2)) max_n = 2;\n words = realloc(words, max_n * sizeof(*words));\n }\n words[*n].s = s;\n while (*s && !isspace(*s)) s++;\n words[*n].len = s - words[*n].s;\n (*n) ++;\n }\n\n return words;\n}\n\nint greedy_wrap(word words, int count, int cols, int *breaks)\n{\n int score = 0, line, i, j, d;\n\n i = j = line = 0;\n while (1) {\n if (i == count) {\n breaks[j++] = i;\n break;\n }\n\n if (!line) {\n line = words[i++].len;\n continue;\n }\n\n if (line + words[i].len < cols) {\n line += words[i++].len + 1;\n continue;\n }\n\n breaks[j++] = i;\n if (i < count) {\n d = cols - line;\n if (d > 0) score += PENALTY_SHORT * d * d;\n else if (d < 0) score += PENALTY_LONG * d * d;\n }\n\n line = 0;\n }\n breaks[j++] = 0;\n\n return score;\n}\n\n/* tries to make right margin more even; pretty sure there's an off-by-one bug\n here somewhere */\nint balanced_wrap(word words, int count, int cols, int *breaks)\n{\n int *best = malloc(sizeof(int) * (count + 1));\n\n /* do a greedy wrap to have some baseline score to work with, else\n we'll end up with O(2^N) behavior */\n int best_score = greedy_wrap(words, count, cols, breaks);\n\n void test_wrap(int line_no, int start, int score) {\n int line = 0, current_score = -1, d;\n\n while (start <= count) {\n if (line) line ++;\n line += words[start++].len;\n d = cols - line;\n if (start < count || d < 0) {\n if (d > 0)\n current_score = score + PENALTY_SHORT * d * d;\n else\n current_score = score + PENALTY_LONG * d * d;\n } else {\n current_score = score;\n }\n\n if (current_score >= best_score) {\n if (d <= 0) return;\n continue;\n }\n\n best[line_no] = start;\n test_wrap(line_no + 1, start, current_score);\n }\n if (current_score >= 0 && current_score < best_score) {\n best_score = current_score;\n memcpy(breaks, best, sizeof(int) * (line_no));\n }\n }\n test_wrap(0, 0, 0);\n free(best);\n\n return best_score;\n}\n\nvoid show_wrap(word list, int count, int *breaks)\n{\n int i, j;\n for (i = j = 0; i < count && breaks[i]; i++) {\n while (j < breaks[i]) {\n printf(\"%.*s\", list[j].len, list[j].s);\n if (j < breaks[i] - 1)\n putchar(' ');\n j++;\n }\n if (breaks[i]) putchar('\\n');\n }\n}\n\nint main(void)\n{\n int len, score, cols;\n word list = make_word_list(string, &len);\n int *breaks = malloc(sizeof(int) * (len + 1));\n\n cols = 80;\n score = greedy_wrap(list, len, cols, breaks);\n printf(\"\\n== greedy wrap at %d (score %d) ==\\n\\n\", cols, score);\n show_wrap(list, len, breaks);\n\n score = balanced_wrap(list, len, cols, breaks);\n printf(\"\\n== balanced wrap at %d (score %d) ==\\n\\n\", cols, score);\n show_wrap(list, len, breaks);\n\n\n cols = 32;\n score = greedy_wrap(list, len, cols, breaks);\n printf(\"\\n== greedy wrap at %d (score %d) ==\\n\\n\", cols, score);\n show_wrap(list, len, breaks);\n\n score = balanced_wrap(list, len, cols, breaks);\n printf(\"\\n== balanced wrap at %d (score %d) ==\\n\\n\", cols, score);\n show_wrap(list, len, breaks);\n\n return 0;\n}"} {"title": "Write float arrays to a text file", "language": "C", "task": "Write two equal-sized numerical arrays 'x' and 'y' to \na two-column text file named 'filename'.\n\nThe first column of the file contains values from an 'x'-array with a \ngiven 'xprecision', the second -- values from 'y'-array with 'yprecision'.\n\nFor example, considering:\n x = {1, 2, 3, 1e11};\n y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}; \n /* sqrt(x) */\n xprecision = 3;\n yprecision = 5;\n\nThe file should look like:\n 1 1\n 2 1.4142\n 3 1.7321\n 1e+011 3.1623e+005\n\nThis task is intended as a subtask for [[Measure relative performance of sorting algorithms implementations]].\n\n", "solution": "#include \n#include \n\nint main(int argc, char **argv) {\n\n float x[4] = {1,2,3,1e11}, y[4];\n int i = 0;\n FILE *filePtr;\n\n filePtr = fopen(\"floatArray\",\"w\");\n\n for (i = 0; i < 4; i++) {\n y[i] = sqrt(x[i]);\n fprintf(filePtr, \"%.3g\\t%.5g\\n\", x[i], y[i]);\n }\n\n return 0;\n}"} {"title": "Write language name in 3D ASCII", "language": "C", "task": "Write/display a language's name in '''3D''' ASCII. \n\n\n(We can leave the definition of \"3D ASCII\" fuzzy, \nso long as the result is interesting or amusing, \nnot a cheap hack to satisfy the task.)\n\n\n;Related tasks:\n* draw a sphere\n* draw a cuboid\n* draw a rotating cube\n* draw a Deathstar\n\n", "solution": "#include \nconst char*s = \" _____\\n /____/\\\\\\n/ ___\\\\/\\n\\\\ \\\\/__/\\n \\\\____/\";\nint main(){ puts(s); return 0; }"} {"title": "Write to Windows event log", "language": "C", "task": "Write script status to the Windows Event Log\n\n", "solution": "#include\n#include\n\nint main(int argC,char* argV[])\n{\n\tchar str[1000];\n\t\n\tif(argC!=5)\n\t\tprintf(\"Usage : %s < Followed by level, id, source string and description>\",argV[0]);\n\telse{\n\t\tsprintf(str,\"EventCreate /t %s /id %s /l APPLICATION /so %s /d \\\"%s\\\"\",argV[1],argV[2],argV[3],argV[4]);\n\t\tsystem(str);\n\t}\n\t\n\treturn 0;\n}\n"} {"title": "Zeckendorf number representation", "language": "C", "task": "Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.\n\nRecall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. \n\nThe decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.\n\n10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that ''no two consecutive Fibonacci numbers can be used'' which leads to the former unique solution.\n\n\n;Task:\nGenerate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. \n\nThe intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. \n\n\n;Also see:\n* OEIS A014417 for the the sequence of required results.\n* Brown's Criterion - Numberphile\n\n\n;Related task:\n* [[Fibonacci sequence]]\n\n", "solution": "#include \n\ntypedef unsigned long long u64;\n\n#define FIB_INVALID (~(u64)0)\n\nu64 fib[] = {\n\t1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597,\n\t2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418,\n\t317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465,\n\t14930352, 24157817, 39088169, 63245986, 102334155, 165580141,\n\t267914296, 433494437, 701408733, 1134903170, 1836311903,\n\t2971215073ULL, 4807526976ULL, 7778742049ULL, 12586269025ULL,\n\t20365011074ULL, 32951280099ULL, 53316291173ULL, 86267571272ULL,\n\t139583862445ULL, 225851433717ULL, 365435296162ULL, 591286729879ULL,\n\t956722026041ULL, 1548008755920ULL, 2504730781961ULL, 4052739537881ULL,\n\t6557470319842ULL, 10610209857723ULL, 17167680177565ULL,\n\n\t27777890035288ULL // this 65-th one is for range check\n};\n\nu64 fibbinary(u64 n)\n{\n\tif (n >= fib[64]) return FIB_INVALID;\n\n\tu64 ret = 0;\n\tint i;\n\tfor (i = 64; i--; )\n\t\tif (n >= fib[i]) {\n\t\t\tret |= 1ULL << i;\n\t\t\tn -= fib[i];\n\t\t}\n\n\treturn ret;\n}\n\nvoid bprint(u64 n, int width)\n{\n\tif (width > 64) width = 64;\n\n\tu64 b;\n\tfor (b = 1ULL << (width - 1); b; b >>= 1)\n\t\tputchar(b == 1 && !n\n\t\t\t? '0'\n\t\t\t: b > n\t? ' '\n\t\t\t\t: b & n ? '1' : '0');\n\tputchar('\\n');\n}\n\nint main(void)\n{\n\tint i;\n\n\tfor (i = 0; i <= 20; i++)\n\t\tprintf(\"%2d:\", i), bprint(fibbinary(i), 8);\n\n\treturn 0;\n}"} {"title": "Zhang-Suen thinning algorithm", "language": "C", "task": "This is an algorithm used to thin a black and white i.e. one bit per pixel images. \n\nFor example, with an input image of:\n \n ################# ############# \n ################## ################ \n ################### ################## \n ######## ####### ################### \n ###### ####### ####### ###### \n ###### ####### ####### \n ################# ####### \n ################ ####### \n ################# ####### \n ###### ####### ####### \n ###### ####### ####### \n ###### ####### ####### ###### \n ######## ####### ################### \n ######## ####### ###### ################## ###### \n ######## ####### ###### ################ ###### \n ######## ####### ###### ############# ###### \n \nIt produces the thinned output:\n \n \n # ########## ####### \n ## # #### # \n # # ## \n # # # \n # # # \n # # # \n ############ # \n # # # \n # # # \n # # # \n # # # \n # ## \n # ############ \n ### ### \n \n \n\n;Algorithm:\nAssume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes.\n\nThe algorithm operates on all black pixels P1 that can have eight neighbours. \n\nThe neighbours are, in order, arranged as:\n\n\n P9 P2 P3 \n P8 P1 P4 \n P7 P6 P5 \n\n\n\nObviously the boundary pixels of the image cannot have the full eight neighbours.\n\n* Define A(P1) = the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular).\n* Define B(P1) = The number of black pixel neighbours of P1. ( = sum(P2 .. P9) )\n\n\n;Step 1:\nAll pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage.\n* (0) The pixel is black and has eight neighbours\n* (1) 2 <= B(P1) <= 6\n* (2) A(P1) = 1\n* (3) At least one of P2 and P4 and P6 is white\n* (4) At least one of P4 and P6 and P8 is white\n\nAfter iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white.\n\n\n;Step 2:\nAll pixels are again tested and pixels satisfying all the following conditions are just noted at this stage.\n* (0) The pixel is black and has eight neighbours\n* (1) 2 <= B(P1) <= 6\n* (2) A(P1) = 1\n* (3) At least one of P2 and P4 and '''P8''' is white\n* (4) At least one of '''P2''' and P6 and P8 is white\n\nAfter iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white.\n\n\n;Iteration:\nIf any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed.\n\n\n;Task:\n# Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes.\n# Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters. \n\n 00000000000000000000000000000000\n 01111111110000000111111110000000\n 01110001111000001111001111000000\n 01110000111000001110000111000000\n 01110001111000001110000000000000\n 01111111110000001110000000000000\n 01110111100000001110000111000000\n 01110011110011101111001111011100\n 01110001111011100111111110011100\n 00000000000000000000000000000000\n\n\n;Reference:\n* Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza.\n* \"Character Recognition Systems: A Guide for Students and Practitioners\" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen\n\n", "solution": "#include\n#include\n\nchar** imageMatrix;\n\nchar blankPixel,imagePixel;\n\ntypedef struct{\n\tint row,col;\n}pixel;\n\nint getBlackNeighbours(int row,int col){\n\t\n\tint i,j,sum = 0;\n\t\n\tfor(i=-1;i<=1;i++){\n\t\tfor(j=-1;j<=1;j++){\n\t\t\tif(i!=0 || j!=0)\n\t\t\t\tsum+= (imageMatrix[row+i][col+j]==imagePixel);\n\t\t}\n\t}\n\t\n\treturn sum;\n}\n\nint getBWTransitions(int row,int col){\n\treturn \t((imageMatrix[row-1][col]==blankPixel && imageMatrix[row-1][col+1]==imagePixel)\n\t\t\t+(imageMatrix[row-1][col+1]==blankPixel && imageMatrix[row][col+1]==imagePixel)\n\t\t\t+(imageMatrix[row][col+1]==blankPixel && imageMatrix[row+1][col+1]==imagePixel)\n\t\t\t+(imageMatrix[row+1][col+1]==blankPixel && imageMatrix[row+1][col]==imagePixel)\n\t\t\t+(imageMatrix[row+1][col]==blankPixel && imageMatrix[row+1][col-1]==imagePixel)\n\t\t\t+(imageMatrix[row+1][col-1]==blankPixel && imageMatrix[row][col-1]==imagePixel)\n\t\t\t+(imageMatrix[row][col-1]==blankPixel && imageMatrix[row-1][col-1]==imagePixel)\n\t\t\t+(imageMatrix[row-1][col-1]==blankPixel && imageMatrix[row-1][col]==imagePixel));\n}\n\nint zhangSuenTest1(int row,int col){\n\tint neighbours = getBlackNeighbours(row,col);\n\t\n\treturn ((neighbours>=2 && neighbours<=6) \n\t\t&& (getBWTransitions(row,col)==1) \n\t\t&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel) \n\t\t&& (imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col-1]==blankPixel));\n}\n\nint zhangSuenTest2(int row,int col){\n\tint neighbours = getBlackNeighbours(row,col);\n\t\n\treturn ((neighbours>=2 && neighbours<=6) \n\t\t&& (getBWTransitions(row,col)==1) \n\t\t&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row][col-1]==blankPixel) \n\t\t&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel));\n}\n\nvoid zhangSuen(char* inputFile, char* outputFile){\n\t\n\tint startRow = 1,startCol = 1,endRow,endCol,i,j,count,rows,cols,processed;\n\t\n\tpixel* markers;\n\t\n\tFILE* inputP = fopen(inputFile,\"r\");\n\t\n\tfscanf(inputP,\"%d%d\",&rows,&cols);\n\t\n\tfscanf(inputP,\"%d%d\",&blankPixel,&imagePixel);\n\t\n\tblankPixel<=9?blankPixel+='0':blankPixel;\n\timagePixel<=9?imagePixel+='0':imagePixel;\n\t\n\tprintf(\"\\nPrinting original image :\\n\");\n\t\n\timageMatrix = (char**)malloc(rows*sizeof(char*));\n\t\n\tfor(i=0;i0);\n\t\t\n\t\tfor(i=0;i0);\n\t\t\n\t\tfor(i=0;i