diff --git "a/solutions-2023-06-17.jsonl" "b/solutions-2023-06-17.jsonl" new file mode 100644--- /dev/null +++ "b/solutions-2023-06-17.jsonl" @@ -0,0 +1,1284 @@ +{"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 \u00a0''toggle''\u00a0 the door \u00a0(if the door is closed, \u00a0open it; \u00a0 if it is open,\u00a0 close it). \n\nThe second time, only visit every 2nd door \u00a0 (door #2, #4, #6, ...), \u00a0 and toggle it. \n\nThe third time, visit every 3rd door \u00a0 (door #3, #6, #9, ...), etc, \u00a0 until you only visit the 100th door.\n\n\n;Task:\nAnswer the question: \u00a0 what state are the doors in after the last pass? \u00a0 Which are open, which are closed?\n\n\n'''Alternate:''' \nAs noted in this page's \u00a0 discussion page, \u00a0 the only doors that remain open are those whose numbers are perfect squares.\n\nOpening only those doors is an \u00a0 optimization \u00a0 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 doors", "language": "JavaScript", "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 \u00a0''toggle''\u00a0 the door \u00a0(if the door is closed, \u00a0open it; \u00a0 if it is open,\u00a0 close it). \n\nThe second time, only visit every 2nd door \u00a0 (door #2, #4, #6, ...), \u00a0 and toggle it. \n\nThe third time, visit every 3rd door \u00a0 (door #3, #6, #9, ...), etc, \u00a0 until you only visit the 100th door.\n\n\n;Task:\nAnswer the question: \u00a0 what state are the doors in after the last pass? \u00a0 Which are open, which are closed?\n\n\n'''Alternate:''' \nAs noted in this page's \u00a0 discussion page, \u00a0 the only doors that remain open are those whose numbers are perfect squares.\n\nOpening only those doors is an \u00a0 optimization \u00a0 that may also be expressed; \nhowever, as should be obvious, this defeats the intent of comparing implementations across programming languages.\n\n", "solution": "(function (n) {\n \"use strict\";\n function finalDoors(n) {\n var lstRange = range(1, n);\n return lstRange\n .reduce(function (a, _, k) {\n var m = k + 1;\n return a.map(function (x, i) {\n var j = i + 1;\n return [j, j % m ? x[1] : !x[1]];\n });\n }, zip(\n lstRange,\n replicate(n, false)\n ));\n };\n function zip(xs, ys) {\n return xs.length === ys.length ? (\n xs.map(function (x, i) {\n return [x, ys[i]];\n })\n ) : undefined;\n }\n function replicate(n, a) {\n var v = [a],\n o = [];\n if (n < 1) return o;\n while (n > 1) {\n if (n & 1) o = o.concat(v);\n n >>= 1;\n v = v.concat(v);\n }\n return o.concat(v);\n }\n function range(m, n, delta) {\n var d = delta || 1,\n blnUp = n > m,\n lng = Math.floor((blnUp ? n - m : m - n) / d) + 1,\n a = Array(lng),\n i = lng;\n if (blnUp)\n while (i--) a[i] = (d * i) + m;\n else\n while (i--) a[i] = m - (d * i);\n return a;\n }\n return finalDoors(n)\n .filter(function (tuple) {\n return tuple[1];\n })\n .map(function (tuple) {\n return {\n door: tuple[0],\n open: tuple[1]\n };\n });\n\n})(100);"} +{"title": "100 doors", "language": "Python 2.5+", "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 \u00a0''toggle''\u00a0 the door \u00a0(if the door is closed, \u00a0open it; \u00a0 if it is open,\u00a0 close it). \n\nThe second time, only visit every 2nd door \u00a0 (door #2, #4, #6, ...), \u00a0 and toggle it. \n\nThe third time, visit every 3rd door \u00a0 (door #3, #6, #9, ...), etc, \u00a0 until you only visit the 100th door.\n\n\n;Task:\nAnswer the question: \u00a0 what state are the doors in after the last pass? \u00a0 Which are open, which are closed?\n\n\n'''Alternate:''' \nAs noted in this page's \u00a0 discussion page, \u00a0 the only doors that remain open are those whose numbers are perfect squares.\n\nOpening only those doors is an \u00a0 optimization \u00a0 that may also be expressed; \nhowever, as should be obvious, this defeats the intent of comparing implementations across programming languages.\n\n", "solution": "\ndoors = [False] * 100\nfor i in range(100):\n for j in range(i, 100, i+1):\n doors[j] = not doors[j]\n print(\"Door %d:\" % (i+1), 'open' if doors[i] else 'close')\n"} +{"title": "100 doors", "language": "Python 3.x", "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 \u00a0''toggle''\u00a0 the door \u00a0(if the door is closed, \u00a0open it; \u00a0 if it is open,\u00a0 close it). \n\nThe second time, only visit every 2nd door \u00a0 (door #2, #4, #6, ...), \u00a0 and toggle it. \n\nThe third time, visit every 3rd door \u00a0 (door #3, #6, #9, ...), etc, \u00a0 until you only visit the 100th door.\n\n\n;Task:\nAnswer the question: \u00a0 what state are the doors in after the last pass? \u00a0 Which are open, which are closed?\n\n\n'''Alternate:''' \nAs noted in this page's \u00a0 discussion page, \u00a0 the only doors that remain open are those whose numbers are perfect squares.\n\nOpening only those doors is an \u00a0 optimization \u00a0 that may also be expressed; \nhowever, as should be obvious, this defeats the intent of comparing implementations across programming languages.\n\n", "solution": "\nfor i in range(1, 101):\n if i**0.5 % 1:\n state='closed'\n else:\n state='open'\n print(\"Door {}:{}\".format(i, state))\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# [https://www.youtube.com/watch?v=a1DUUnhk3uE The unbelievable solution to the 100 prisoner puzzle] standupmaths (Video).\n# [[wp:100 prisoners problem]]\n# [http://datagenetics.com/blog/december42014/index.html 100 Prisoners Escape Puzzle] DataGenetics.\n# [https://en.wikipedia.org/wiki/Random_permutation_statistics#One_hundred_prisoners Random permutation statistics#One hundred prisoners] on Wikipedia.\n\n", "solution": "\n#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\n$ gcc 100prisoners.c && ./a.out 100 50 10000\nRunning random trials...\n\nGames Played : 10000\nGames Won : 0\nChances : 0.000000 % \n\nRunning strategic trials...\n\nGames Played : 10000\nGames Won : 3051\nChances : 30.510000 % \n\n"} +{"title": "100 prisoners", "language": "Node.js", "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# [https://www.youtube.com/watch?v=a1DUUnhk3uE The unbelievable solution to the 100 prisoner puzzle] standupmaths (Video).\n# [[wp:100 prisoners problem]]\n# [http://datagenetics.com/blog/december42014/index.html 100 Prisoners Escape Puzzle] DataGenetics.\n# [https://en.wikipedia.org/wiki/Random_permutation_statistics#One_hundred_prisoners Random permutation statistics#One hundred prisoners] on Wikipedia.\n\n", "solution": "\nconst _ = require('lodash');\n\nconst numPlays = 100000;\n\nconst setupSecrets = () => {\n\t// setup the drawers with random cards\n\tlet secrets = [];\n\n\tfor (let i = 0; i < 100; i++) {\n\t\tsecrets.push(i);\n\t}\n\n\treturn _.shuffle(secrets);\n}\n\nconst playOptimal = () => {\n\t\n\tlet secrets = setupSecrets();\n\t\n\n\t// Iterate once per prisoner\n\tloop1:\n\tfor (let p = 0; p < 100; p++) {\n\t\t\n\t\t// whether the prisoner succeedss\n\t\tlet success = false;\n\t\t\n\t\t// the drawer number the prisoner chose\n\t\tlet choice = p;\n\t\t\n\t\t\n\t\t// The prisoner can choose up to 50 cards\n\t\tloop2:\n\t\tfor (let i = 0; i < 50; i++) {\n\t\t\t\n\t\t\t// if the card in the drawer that the prisoner chose is his card\n\t\t\tif (secrets[choice] === p){\n\t\t\t\tsuccess = true;\n\t\t\t\tbreak loop2;\n\t\t\t}\n\n\t\t\t// the next drawer the prisoner chooses will be the number of the card he has.\n\t\t\tchoice = secrets[choice];\n\t\t\n\t\t}\t// each prisoner gets 50 chances\n\n\t\t\n\t\tif (!success) return false;\n\n\t} // iterate for each prisoner \n\n\treturn true;\n}\n\nconst playRandom = () => {\n\n\tlet secrets = setupSecrets();\n\n\t// iterate for each prisoner \n\tfor (let p = 0; p < 100; p++) {\n\n\t\tlet choices = setupSecrets();\n\t\t\n\t\tlet success = false;\n\t\t\n\t\tfor (let i = 0; i < 50; i++) {\n\n\t\t\tif (choices[i] === p) {\n\t\t\t\tsuccess = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (!success) return false;\n\t}\n\n\treturn true;\n}\n\nconst execOptimal = () => {\n\n\tlet success = 0;\n\t\n\tfor (let i = 0; i < numPlays; i++) {\n\n\t\tif (playOptimal()) success++;\n\t\t\t\n\t}\n\n\treturn 100.0 * success / 100000;\n}\n\nconst execRandom = () => {\n\n\tlet success = 0;\n\n\tfor (let i = 0; i < numPlays; i++) {\n\n\t\tif (playRandom()) success++;\n\n\t}\n\n\treturn 100.0 * success / 100000;\n}\n\nconsole.log(\"# of executions: \" + numPlays);\nconsole.log(\"Optimal Play Success Rate: \" + execOptimal());\nconsole.log(\"Random Play Success Rate: \" + execRandom());\n"} +{"title": "100 prisoners", "language": "JavaScript Node.js 16.13.0 (LTS)", "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# [https://www.youtube.com/watch?v=a1DUUnhk3uE The unbelievable solution to the 100 prisoner puzzle] standupmaths (Video).\n# [[wp:100 prisoners problem]]\n# [http://datagenetics.com/blog/december42014/index.html 100 Prisoners Escape Puzzle] DataGenetics.\n# [https://en.wikipedia.org/wiki/Random_permutation_statistics#One_hundred_prisoners Random permutation statistics#One hundred prisoners] on Wikipedia.\n\n", "solution": "\"use strict\";\n\n// Simulate several thousand instances of the game:\nconst gamesCount = 2000;\n\n// ...where the prisoners randomly open drawers.\nconst randomResults = playGame(gamesCount, randomStrategy);\n\n// ...where the prisoners use the optimal strategy mentioned in the Wikipedia article.\nconst optimalResults = playGame(gamesCount, optimalStrategy);\n\n// Show and compare the computed probabilities of success for the two strategies.\nconsole.log(`Games count: ${gamesCount}`);\nconsole.log(`Probability of success with \"random\" strategy: ${computeProbability(randomResults, gamesCount)}`);\nconsole.log(`Probability of success with \"optimal\" strategy: ${computeProbability(optimalResults, gamesCount)}`);\n\nfunction playGame(gamesCount, strategy, prisonersCount = 100) {\n const results = new Array();\n\n for (let game = 1; game <= gamesCount; game++) {\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 const drawers = initDrawers(prisonersCount);\n\n // A prisoner tries to find his own number.\n // Prisoners start outside the room.\n // They can decide some strategy before any enter the room.\n let found = 0;\n for (let prisoner = 1; prisoner <= prisonersCount; prisoner++, found++)\n if (!find(prisoner, drawers, strategy)) break;\n\n // If all 100 findings find their own numbers then they will all be pardoned. If any don't then all sentences stand.\n results.push(found == prisonersCount);\n }\n\n return results;\n}\n\nfunction find(prisoner, drawers, strategy) {\n // A prisoner can open no more than 50 drawers.\n const openMax = Math.floor(drawers.length / 2);\n\n // Prisoners start outside the room.\n let card;\n for (let open = 0; open < openMax; open++) {\n // A prisoner tries to find his own number.\n card = strategy(prisoner, drawers, card);\n\n // A prisoner finding his own number is then held apart from the others.\n if (card == prisoner)\n break;\n }\n\n return (card == prisoner);\n}\n\nfunction randomStrategy(prisoner, drawers, card) {\n // Simulate the game where the prisoners randomly open drawers.\n\n const min = 0;\n const max = drawers.length - 1;\n\n return drawers[draw(min, max)];\n}\n\nfunction optimalStrategy(prisoner, drawers, card) {\n // Simulate the game where the prisoners use the optimal strategy mentioned in the Wikipedia article.\n\n // First opening the drawer whose outside number is his prisoner number.\n // If the card within has his number then he succeeds...\n if (typeof card === \"undefined\")\n return drawers[prisoner - 1];\n \n // ...otherwise he opens the drawer with the same number as that of the revealed card.\n return drawers[card - 1];\n}\n\nfunction initDrawers(prisonersCount) {\n const drawers = new Array();\n for (let card = 1; card <= prisonersCount; card++)\n drawers.push(card);\n\n return shuffle(drawers);\n}\n\nfunction shuffle(drawers) {\n const min = 0;\n const max = drawers.length - 1;\n for (let i = min, j; i < max; i++) {\n j = draw(min, max);\n if (i != j)\n [drawers[i], drawers[j]] = [drawers[j], drawers[i]];\n }\n\n return drawers;\n}\n\nfunction draw(min, max) {\n // See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random\n return Math.floor(Math.random() * (max - min + 1)) + min;\n}\n\nfunction computeProbability(results, gamesCount) {\n return Math.round(results.filter(x => x == true).length * 10000 / gamesCount) / 100;\n}"} +{"title": "100 prisoners", "language": "Python", "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# [https://www.youtube.com/watch?v=a1DUUnhk3uE The unbelievable solution to the 100 prisoner puzzle] standupmaths (Video).\n# [[wp:100 prisoners problem]]\n# [http://datagenetics.com/blog/december42014/index.html 100 Prisoners Escape Puzzle] DataGenetics.\n# [https://en.wikipedia.org/wiki/Random_permutation_statistics#One_hundred_prisoners Random permutation statistics#One hundred prisoners] on Wikipedia.\n\n", "solution": "import random\n\ndef play_random(n):\n # using 0-99 instead of ranges 1-100\n pardoned = 0\n in_drawer = list(range(100))\n sampler = list(range(100))\n for _round in range(n):\n random.shuffle(in_drawer)\n found = False\n for prisoner in range(100):\n found = False\n for reveal in random.sample(sampler, 50):\n card = in_drawer[reveal]\n if card == prisoner:\n found = True\n break\n if not found:\n break\n if found:\n pardoned += 1\n return pardoned / n * 100 # %\n\ndef play_optimal(n):\n # using 0-99 instead of ranges 1-100\n pardoned = 0\n in_drawer = list(range(100))\n for _round in range(n):\n random.shuffle(in_drawer)\n for prisoner in range(100):\n reveal = prisoner\n found = False\n for go in range(50):\n card = in_drawer[reveal]\n if card == prisoner:\n found = True\n break\n reveal = card\n if not found:\n break\n if found:\n pardoned += 1\n return pardoned / n * 100 # %\n\nif __name__ == '__main__':\n n = 100_000\n print(\" Simulation count:\", n)\n print(f\" Random play wins: {play_random(n):4.1f}% of simulations\")\n print(f\"Optimal play wins: {play_optimal(n):4.1f}% of simulations\")"} +{"title": "15 puzzle game", "language": "C", "task": "right\n[[Category:Puzzles]]\n[[Category:Games]]\n\n\n;Task:\nImplement the Fifteen Puzzle Game.\n\n\nThe \u00a0 '''15-puzzle''' \u00a0 is also known as: \n:::* \u00a0 '''Fifteen Puzzle'''\n:::* \u00a0 '''Gem Puzzle'''\n:::* \u00a0 '''Boss Puzzle'''\n:::* \u00a0 '''Game of Fifteen'''\n:::* \u00a0 '''Mystic Square'''\n:::* \u00a0 '''14-15 Puzzle'''\n:::* \u00a0 and some others.\n\n\n;Related Tasks:\n:* \u00a0 15 Puzzle Solver\n:* \u00a0 [[16 Puzzle Game]]\n\n", "solution": "/* RosettaCode: Fifteen puzle game, C89, plain vanillia TTY, MVC, \u00a7 22 */\n#define _CRT_SECURE_NO_WARNINGS\n#include \n#include \n#include \n#define N 4\n#define M 4\nenum Move{UP,DOWN,LEFT,RIGHT};int hR;int hC;int cc[N][M];const int nS=100;int\nupdate(enum Move m){const int dx[]={0,0,-1,1};const int dy[]={-1,1,0,0};int i=hR\n+dy[m];int j=hC+dx[m];if(i>= 0&&i=0&&j\n\n===C89, short version, TTY mode===\n/*\n * RosettaCode: Fifteen puzle game, C89, plain vanillia TTY, MVC\n */\n\n#define _CRT_SECURE_NO_WARNINGS /* unlocks printf etc. in MSVC */\n#include \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\n"} +{"title": "15 puzzle game", "language": "Python 3.X", "task": "right\n[[Category:Puzzles]]\n[[Category:Games]]\n\n\n;Task:\nImplement the Fifteen Puzzle Game.\n\n\nThe \u00a0 '''15-puzzle''' \u00a0 is also known as: \n:::* \u00a0 '''Fifteen Puzzle'''\n:::* \u00a0 '''Gem Puzzle'''\n:::* \u00a0 '''Boss Puzzle'''\n:::* \u00a0 '''Game of Fifteen'''\n:::* \u00a0 '''Mystic Square'''\n:::* \u00a0 '''14-15 Puzzle'''\n:::* \u00a0 and some others.\n\n\n;Related Tasks:\n:* \u00a0 15 Puzzle Solver\n:* \u00a0 [[16 Puzzle Game]]\n\n", "solution": "\n''' Python 3.6.5 code using Tkinter graphical user interface.''' \n\nfrom tkinter import *\nfrom tkinter import messagebox\nimport random\n\n# ************************************************\n\nclass Board:\n def __init__(self, playable=True):\n while True:\n # list of text for game squares:\n self.lot = [str(i) for i in range(1,16)] + ['']\n if not playable:\n break\n # list of text for game squares randomized:\n random.shuffle(self.lot)\n if self.is_solvable():\n break\n \n # game board is 2D array of game squares:\n self.bd = []\n i = 0\n for r in range(4):\n row = []\n for c in range(4):\n row.append(Square(r,c,self.lot[i]))\n i += 1\n self.bd.append(row)\n \n # How to check if an instance of a 15 puzzle\n # is solvable is explained here:\n # https://www.geeksforgeeks.org/check-instance-15-puzzle-solvable/\n # I only coded for the case where N is even.\n def is_solvable(self):\n inv = self.get_inversions()\n odd = self.is_odd_row()\n if inv % 2 == 0 and odd:\n return True\n if inv % 2 == 1 and not odd:\n return True\n return False\n \n def get_inversions(self):\n cnt = 0\n for i, x in enumerate(self.lot[:-1]):\n if x != '':\n for y in self.lot[i+1:]:\n if y != '' and int(x) > int(y):\n cnt += 1\n return cnt\n\n # returns True if open square is in odd row from bottom:\n def is_odd_row(self):\n idx = self.lot.index('')\n return idx in [4,5,6,7,12,13,14,15] \n\n # returns name, text, and button object at row & col:\n def get_item(self, r, c):\n return self.bd[r][c].get()\n\n def get_square(self, r, c):\n return self.bd[r][c]\n\n def game_won(self):\n goal = [str(i) for i in range(1,16)] + ['']\n i = 0\n for r in range(4):\n for c in range(4):\n nm, txt, btn = self.get_item(r,c)\n if txt != goal[i]:\n return False\n i += 1\n return True\n \n# ************************************************\n\nclass Square: # ['btn00', '0', None]\n def __init__(self, row, col, txt):\n self.row = row\n self.col = col\n self.name = 'btn' + str(row) + str(col)\n self.txt = txt\n self.btn = None\n \n def get(self):\n return [self.name, self.txt, self.btn]\n\n def set_btn(self, btn):\n self.btn = btn\n\n def set_txt(self, txt):\n self.txt = txt\n\n# ************************************************\n\nclass Game:\n def __init__(self, gw):\n self.window = gw\n\n # game data:\n self.bd = None\n self.playable = False\n\n # top frame:\n self.top_fr = Frame(gw,\n width=600,\n height=100,\n bg='light green')\n self.top_fr.pack(fill=X)\n\n self.hdg = Label(self.top_fr,\n text=' 15 PUZZLE GAME ',\n font='arial 22 bold',\n fg='Navy Blue',\n bg='white')\n self.hdg.place(relx=0.5, rely=0.4,\n anchor=CENTER)\n\n self.dir = Label(self.top_fr,\n text=\"(Click 'New Game' to begin)\",\n font='arial 12 ',\n fg='Navy Blue',\n bg='light green')\n self.dir.place(relx=0.5, rely=0.8,\n anchor=CENTER)\n\n self.play_btn = Button(self.top_fr,\n text='New \\nGame',\n bd=5,\n bg='PaleGreen4',\n fg='White',\n font='times 12 bold',\n command=self.new_game)\n self.play_btn.place(relx=0.92, rely=0.5,\n anchor=E)\n\n # bottom frame:\n self.btm_fr = Frame(gw,\n width=600,\n height=500,\n bg='light steel blue')\n self.btm_fr.pack(fill=X)\n\n # board frame:\n self.bd_fr = Frame(self.btm_fr,\n width=400+2,\n height=400+2,\n relief='solid',\n bd=1,\n bg='lemon chiffon')\n self.bd_fr.place(relx=0.5, rely=0.5,\n anchor=CENTER)\n\n self.play_game()\n\n# ************************************************\n\n def new_game(self):\n self.playable = True\n self.dir.config(text='(Click on a square to move it)')\n self.play_game()\n\n def play_game(self):\n # place squares on board:\n if self.playable:\n btn_state = 'normal'\n else:\n btn_state = 'disable'\n self.bd = Board(self.playable) \n objh = 100 # widget height\n objw = 100 # widget width\n objx = 0 # x-position of widget in frame\n objy = 0 # y-position of widget in frame\n\n for r in range(4):\n for c in range(4):\n nm, txt, btn = self.bd.get_item(r,c)\n bg_color = 'RosyBrown1'\n if txt == '':\n bg_color = 'White' \n game_btn = Button(self.bd_fr,\n text=txt,\n relief='solid',\n bd=1,\n bg=bg_color,\n font='times 12 bold',\n state=btn_state,\n command=lambda x=nm: self.clicked(x))\n game_btn.place(x=objx, y=objy,\n height=objh, width=objw)\n \n sq = self.bd.get_square(r,c)\n sq.set_btn(game_btn)\n \n objx = objx + objw\n objx = 0\n objy = objy + objh\n\n # processing when a square is clicked:\n def clicked(self, nm):\n r, c = int(nm[3]), int(nm[4])\n nm_fr, txt_fr, btn_fr = self.bd.get_item(r,c)\n \n # cannot 'move' open square to itself:\n if not txt_fr:\n messagebox.showerror(\n 'Error Message',\n 'Please select \"square\" to be moved')\n return\n\n # 'move' square to open square if 'adjacent' to it: \n adjs = [(r-1,c), (r, c-1), (r, c+1), (r+1, c)]\n for x, y in adjs:\n if 0 <= x <= 3 and 0 <= y <= 3:\n nm_to, txt_to, btn_to = self.bd.get_item(x,y)\n if not txt_to:\n sq = self.bd.get_square(x,y)\n sq.set_txt(txt_fr)\n sq = self.bd.get_square(r,c)\n sq.set_txt(txt_to)\n btn_to.config(text=txt_fr,\n bg='RosyBrown1')\n btn_fr.config(text=txt_to,\n bg='White')\n # check if game is won: \n if self.bd.game_won():\n ans = messagebox.askquestion(\n 'You won!!! Play again?')\n if ans == 'no':\n self.window.destroy()\n else:\n self.new_game()\n return\n \n # cannot move 'non-adjacent' square to open square:\n messagebox.showerror(\n 'Error Message',\n 'Illigal move, Try again')\n return\n\n# ************************************************\n\nroot = Tk()\nroot.title('15 Puzzle Game')\nroot.geometry('600x600+100+50')\nroot.resizable(False, False)\ng = Game(root)\nroot.mainloop()\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\u00a0total''.\n\nThe game is won by the player whose chosen number causes the ''running\u00a0total''\nto reach ''exactly''\u00a0'''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\u00a0total''. \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\u00a0total''), \n::* display the ''running\u00a0total'', \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": "21 game", "language": "Python 2.X and 3.X", "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\u00a0total''.\n\nThe game is won by the player whose chosen number causes the ''running\u00a0total''\nto reach ''exactly''\u00a0'''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\u00a0total''. \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\u00a0total''), \n::* display the ''running\u00a0total'', \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": "\nfrom random import randint\ndef start():\n\tgame_count=0\n\tprint(\"Enter q to quit at any time.\\nThe computer will choose first.\\nRunning total is now {}\".format(game_count))\n\troundno=1\n\twhile game_count<21:\n\t\tprint(\"\\nROUND {}: \\n\".format(roundno))\n\t\tt = select_count(game_count)\n\t\tgame_count = game_count+t\n\t\tprint(\"Running total is now {}\\n\".format(game_count))\n\t\tif game_count>=21:\n\t\t\tprint(\"So, commiserations, the computer has won!\")\n\t\t\treturn 0\n\t\tt = request_count()\n\t\tif not t:\n\t\t\tprint('OK,quitting the game')\n\t\t\treturn -1\n\t\tgame_count = game_count+t\n\t\tprint(\"Running total is now {}\\n\".format(game_count))\n\t\tif game_count>=21:\n\t\t\tprint(\"So, congratulations, you've won!\")\n\t\t\treturn 1\n\t\troundno+=1\n\ndef select_count(game_count):\n\t'''selects a random number if the game_count is less than 18. otherwise chooses the winning number'''\n\tif game_count<18:\n\t\tt= randint(1,3)\n\telse:\n\t\tt = 21-game_count\n\tprint(\"The computer chooses {}\".format(t))\n\treturn t\n\ndef request_count():\n\t'''request user input between 1,2 and 3. It will continue till either quit(q) or one of those numbers is requested.'''\n\tt=\"\"\n\twhile True:\n\t\ttry:\n\t\t\tt = raw_input('Your choice 1 to 3 :')\n\t\t\tif int(t) in [1,2,3]:\n\t\t\t\treturn int(t)\n\t\t\telse:\n\t\t\t\tprint(\"Out of range, try again\")\n\t\texcept:\n\t\t\tif t==\"q\":\n\t\t\t\treturn None\n\t\t\telse:\n\t\t\t\tprint(\"Invalid Entry, try again\")\n\nc=0\nm=0\nr=True\nwhile r:\n\to = start()\n\tif o==-1:\n\t\tbreak\n\telse:\n\t\tc+=1 if o==0 else 0\n\t\tm+=1 if o==1 else 0\n\tprint(\"Computer wins {0} game, human wins {1} games\".format(c,m))\n\tt = raw_input(\"Another game?(press y to continue):\")\n\tr = (t==\"y\")"} +{"title": "24 game", "language": "C", "task": "[[Category:Puzzles]]\n[[Category:Games]]\n\nThe 24 Game tests one's mental arithmetic. \n\n\n;Task\nWrite a program that displays four digits, each from 1 \u2500\u2500\u25ba 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* [http://www.bbc.co.uk/dna/h2g2/A933121 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", "language": "JavaScript", "task": "[[Category:Puzzles]]\n[[Category:Games]]\n\nThe 24 Game tests one's mental arithmetic. \n\n\n;Task\nWrite a program that displays four digits, each from 1 \u2500\u2500\u25ba 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* [http://www.bbc.co.uk/dna/h2g2/A933121 The 24 Game] on h2g2.\n\n", "solution": "\nfunction twentyfour(numbers, input) {\n var invalidChars = /[^\\d\\+\\*\\/\\s-\\(\\)]/;\n\n var validNums = function(str) {\n // Create a duplicate of our input numbers, so that\n // both lists will be sorted.\n var mnums = numbers.slice();\n mnums.sort();\n\n // Sort after mapping to numbers, to make comparisons valid.\n return str.replace(/[^\\d\\s]/g, \" \")\n .trim()\n .split(/\\s+/)\n .map(function(n) { return parseInt(n, 10); })\n .sort()\n .every(function(v, i) { return v === mnums[i]; });\n };\n\n var validEval = function(input) {\n try {\n return eval(input);\n } catch (e) {\n return {error: e.toString()};\n }\n };\n\n if (input.trim() === \"\") return \"You must enter a value.\";\n if (input.match(invalidChars)) return \"Invalid chars used, try again. Use only:\\n + - * / ( )\";\n if (!validNums(input)) return \"Wrong numbers used, try again.\";\n var calc = validEval(input);\n if (typeof calc !== 'number') return \"That is not a valid input; please try again.\";\n if (calc !== 24) return \"Wrong answer: \" + String(calc) + \"; please try again.\";\n return input + \" == 24. Congratulations!\";\n};\n\n// I/O below.\n\nwhile (true) {\n var numbers = [1, 2, 3, 4].map(function() {\n return Math.floor(Math.random() * 8 + 1);\n });\n\n var input = prompt(\n \"Your numbers are:\\n\" + numbers.join(\" \") +\n \"\\nEnter expression. (use only + - * / and parens).\\n\", +\"'x' to exit.\", \"\");\n\n if (input === 'x') {\n break;\n }\n alert(twentyfour(numbers, input));\n}\n"} +{"title": "24 game", "language": "Python", "task": "[[Category:Puzzles]]\n[[Category:Games]]\n\nThe 24 Game tests one's mental arithmetic. \n\n\n;Task\nWrite a program that displays four digits, each from 1 \u2500\u2500\u25ba 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* [http://www.bbc.co.uk/dna/h2g2/A933121 The 24 Game] on h2g2.\n\n", "solution": "'''\n The 24 Game\n\n Given any four digits in the range 1 to 9, which may have repetitions,\n Using just the +, -, *, and / operators; and the possible use of\n brackets, (), show how to make an answer of 24.\n\n An answer of \"q\" will quit the game.\n An answer of \"!\" will generate a new set of four digits.\n Otherwise you are repeatedly asked for an expression until it evaluates to 24\n\n Note: you cannot form multiple digit numbers from the supplied digits,\n so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n'''\n\nfrom __future__ import division, print_function\nimport random, ast, re\nimport sys\n\nif sys.version_info[0] < 3: input = raw_input\n\ndef choose4():\n 'four random digits >0 as characters'\n return [str(random.randint(1,9)) for i in range(4)]\n\ndef welcome(digits):\n print (__doc__)\n print (\"Your four digits: \" + ' '.join(digits))\n\ndef check(answer, digits):\n allowed = set('() +-*/\\t'+''.join(digits))\n ok = all(ch in allowed for ch in answer) and \\\n all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \\\n and not re.search('\\d\\d', answer)\n if ok:\n try:\n ast.parse(answer)\n except:\n ok = False\n return ok\n\ndef main(): \n digits = choose4()\n welcome(digits)\n trial = 0\n answer = ''\n chk = ans = False\n while not (chk and ans == 24):\n trial +=1\n answer = input(\"Expression %i: \" % trial)\n chk = check(answer, digits)\n if answer.lower() == 'q':\n break\n if answer == '!':\n digits = choose4()\n print (\"New digits:\", ' '.join(digits))\n continue\n if not chk:\n print (\"The input '%s' was wonky!\" % answer)\n else:\n ans = eval(answer)\n print (\" = \", ans)\n if ans == 24:\n print (\"Thats right!\")\n print (\"Thank you and goodbye\") \n\nif __name__ == '__main__': main() "} +{"title": "24 game/Solve", "language": "C", "task": ";task:\nWrite 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* \u00a0 [[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": "24 game/Solve", "language": "JavaScript", "task": ";task:\nWrite 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* \u00a0 [[Arithmetic Evaluator]]\n\n", "solution": "var ar=[],order=[0,1,2],op=[],val=[];\nvar NOVAL=9999,oper=\"+-*/\",out;\n\nfunction rnd(n){return Math.floor(Math.random()*n)}\n\nfunction say(s){\n try{document.write(s+\"\")}\n catch(e){WScript.Echo(s)}\n}\n\nfunction getvalue(x,dir){\n var r=NOVAL;\n if(dir>0)++x;\n while(1){\n if(val[x]!=NOVAL){\n r=val[x];\n val[x]=NOVAL;\n break;\n }\n x+=dir;\n }\n return r*1;\n}\n\nfunction calc(){\n var c=0,l,r,x;\n val=ar.join('/').split('/');\n while(c<3){\n x=order[c];\n l=getvalue(x,-1);\n r=getvalue(x,1);\n switch(op[x]){\n case 0:val[x]=l+r;break;\n case 1:val[x]=l-r;break;\n case 2:val[x]=l*r;break;\n case 3:\n if(!r||l%r)return 0;\n val[x]=l/r;\n }\n ++c;\n }\n return getvalue(-1,1);\n}\n\nfunction shuffle(s,n){\n var x=n,p=eval(s),r,t;\n while(x--){\n r=rnd(n);\n t=p[x];\n p[x]=p[r];\n p[r]=t;\n }\n}\n\nfunction parenth(n){\n while(n>0)--n,out+='(';\n while(n<0)++n,out+=')';\n}\n\nfunction getpriority(x){\n for(var z=3;z--;)if(order[z]==x)return 3-z;\n return 0;\n}\n\nfunction showsolution(){\n var x=0,p=0,lp=0,v=0;\n while(x<4){\n if(x<3){\n lp=p;\n p=getpriority(x);\n v=p-lp;\n if(v>0)parenth(v);\n }\n out+=ar[x];\n if(x<3){\n if(v<0)parenth(v);\n out+=oper.charAt(op[x]);\n }\n ++x;\n }\n parenth(-p);\n say(out);\n}\n\nfunction solve24(s){\n var z=4,r;\n while(z--)ar[z]=s.charCodeAt(z)-48;\n out=\"\";\n for(z=100000;z--;){\n r=rnd(256);\n op[0]=r&3;\n op[1]=(r>>2)&3;\n op[2]=(r>>4)&3;\n shuffle(\"ar\",4);\n shuffle(\"order\",3);\n if(calc()!=24)continue;\n showsolution();\n break;\n }\n}\n\nsolve24(\"1234\");\nsolve24(\"6789\");\nsolve24(\"1127\");"} +{"title": "4-rings or 4-squares puzzle", "language": "C", "task": ";Task:\nReplace \u00a0 \u00a0 \u00a0 '''a, b, c, d, e, f,''' \u00a0 and\n\u00a0 '''g ''' \u00a0 \u00a0 \u00a0 with the decimal\ndigits \u00a0 LOW \u00a0 \u2500\u2500\u2500\u25ba \u00a0 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 \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557 \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n \u2551 \u2551 \u2551 \u2551\n \u2551 a \u2551 \u2551 e \u2551\n \u2551 \u2551 \u2551 \u2551\n \u2551 \u250c\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2510 \u250c\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n \u2551 \u2502 \u2551 \u2551 \u2502 \u2502 \u2551 \u2502\n \u2551 \u2502 b \u2551 \u2551 d \u2502 \u2502 f \u2551 \u2502\n \u2551 \u2502 \u2551 \u2551 \u2502 \u2502 \u2551 \u2502\n \u2551 \u2502 \u2551 \u2551 \u2502 \u2502 \u2551 \u2502\n \u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u255d \u255a\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u255d \u2502\n \u2502 c \u2502 \u2502 g \u2502\n \u2502 \u2502 \u2502 \u2502\n \u2502 \u2502 \u2502 \u2502\n \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\n\nShow all output here.\n\n\n:* \u00a0 Show all solutions for each letter being unique with\n LOW=1 HIGH=7\n:* \u00a0 Show all solutions for each letter being unique with\n LOW=3 HIGH=9\n:* \u00a0 Show only the \u00a0 ''number'' \u00a0 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": "\n#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": "4-rings or 4-squares puzzle", "language": "JavaScript", "task": ";Task:\nReplace \u00a0 \u00a0 \u00a0 '''a, b, c, d, e, f,''' \u00a0 and\n\u00a0 '''g ''' \u00a0 \u00a0 \u00a0 with the decimal\ndigits \u00a0 LOW \u00a0 \u2500\u2500\u2500\u25ba \u00a0 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 \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557 \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n \u2551 \u2551 \u2551 \u2551\n \u2551 a \u2551 \u2551 e \u2551\n \u2551 \u2551 \u2551 \u2551\n \u2551 \u250c\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2510 \u250c\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n \u2551 \u2502 \u2551 \u2551 \u2502 \u2502 \u2551 \u2502\n \u2551 \u2502 b \u2551 \u2551 d \u2502 \u2502 f \u2551 \u2502\n \u2551 \u2502 \u2551 \u2551 \u2502 \u2502 \u2551 \u2502\n \u2551 \u2502 \u2551 \u2551 \u2502 \u2502 \u2551 \u2502\n \u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u255d \u255a\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u255d \u2502\n \u2502 c \u2502 \u2502 g \u2502\n \u2502 \u2502 \u2502 \u2502\n \u2502 \u2502 \u2502 \u2502\n \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\n\nShow all output here.\n\n\n:* \u00a0 Show all solutions for each letter being unique with\n LOW=1 HIGH=7\n:* \u00a0 Show all solutions for each letter being unique with\n LOW=3 HIGH=9\n:* \u00a0 Show only the \u00a0 ''number'' \u00a0 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": "(() => {\n \"use strict\";\n\n // ----------- 4-RINGS OR 4-SQUARES PUZZLE -----------\n\n // rings :: noRepeatedDigits -> DigitList -> solutions\n // rings :: Bool -> [Int] -> [[Int]]\n const rings = uniq =>\n digits => Boolean(digits.length) ? (\n () => {\n const ns = digits.sort(flip(compare));\n\n // CENTRAL DIGIT :: d\n return ns.flatMap(\n ringTriage(uniq)(ns)\n );\n })() : [];\n\n\n const ringTriage = uniq => ns => d => {\n const\n h = head(ns),\n ts = ns.filter(x => (x + d) <= h);\n\n // LEFT OF CENTRE :: c and a\n return (\n uniq ? (delete_(d)(ts)) : ns\n )\n .flatMap(c => {\n const a = c + d;\n\n // RIGHT OF CENTRE :: e and g\n return a > h ? (\n []\n ) : (\n uniq ? (\n difference(ts)([d, c, a])\n ) : ns\n )\n .flatMap(subTriage(uniq)([ns, h, a, c, d]));\n });\n };\n\n\n const subTriage = uniq =>\n ([ns, h, a, c, d]) => e => {\n const g = d + e;\n\n return ((g > h) || (\n uniq && (g === c))\n ) ? (\n []\n ) : (() => {\n const\n agDelta = a - g,\n bfs = uniq ? (\n difference(ns)([\n d, c, e, g, a\n ])\n ) : ns;\n\n // MID LEFT, MID RIGHT :: b and f\n return bfs.flatMap(b => {\n const f = b + agDelta;\n\n return (bfs).includes(f) && (\n !uniq || ![\n a, b, c, d, e, g\n ].includes(f)\n ) ? ([\n [a, b, c, d, e, f, g]\n ]) : [];\n });\n })();\n };\n\n // ---------------------- TEST -----------------------\n const main = () => unlines([\n \"rings(true, enumFromTo(1,7))\\n\",\n unlines(\n rings(true)(\n enumFromTo(1)(7)\n ).map(show)\n ),\n\n \"\\nrings(true, enumFromTo(3, 9))\\n\",\n unlines(\n rings(true)(\n enumFromTo(3)(9)\n ).map(show)\n ),\n\n \"\\nlength(rings(false, enumFromTo(0, 9)))\\n\",\n rings(false)(\n enumFromTo(0)(9)\n )\n .length\n .toString(),\n \"\"\n ]);\n\n\n // ---------------- GENERIC FUNCTIONS ----------------\n\n // compare :: a -> a -> Ordering\n const compare = (a, b) =>\n a < b ? -1 : (a > b ? 1 : 0);\n\n\n // delete :: Eq a => a -> [a] -> [a]\n const delete_ = x => {\n // xs with first instance of x (if any) removed.\n const go = xs =>\n Boolean(xs.length) ? (\n (x === xs[0]) ? (\n xs.slice(1)\n ) : [xs[0]].concat(go(xs.slice(1)))\n ) : [];\n\n return go;\n };\n\n\n // difference :: Eq a => [a] -> [a] -> [a]\n const difference = xs =>\n ys => {\n const s = new Set(ys);\n\n return xs.filter(x => !s.has(x));\n };\n\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = m =>\n n => Array.from({\n length: 1 + n - m\n }, (_, i) => m + i);\n\n\n // flip :: (a -> b -> c) -> b -> a -> c\n const flip = op =>\n // The binary function op with\n // its arguments reversed.\n 1 !== op.length ? (\n (a, b) => op(b, a)\n ) : (a => b => op(b)(a));\n\n\n // head :: [a] -> a\n const head = xs =>\n // The first item (if any) in a list.\n Boolean(xs.length) ? (\n xs[0]\n ) : null;\n\n\n // show :: a -> String\n const show = x =>\n JSON.stringify(x);\n\n\n // unlines :: [String] -> String\n const unlines = xs =>\n // A single string formed by the intercalation\n // of a list of strings with the newline character.\n xs.join(\"\\n\");\n\n\n // MAIN ---\n return main();\n})();"} +{"title": "4-rings or 4-squares puzzle", "language": "Python", "task": ";Task:\nReplace \u00a0 \u00a0 \u00a0 '''a, b, c, d, e, f,''' \u00a0 and\n\u00a0 '''g ''' \u00a0 \u00a0 \u00a0 with the decimal\ndigits \u00a0 LOW \u00a0 \u2500\u2500\u2500\u25ba \u00a0 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 \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557 \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n \u2551 \u2551 \u2551 \u2551\n \u2551 a \u2551 \u2551 e \u2551\n \u2551 \u2551 \u2551 \u2551\n \u2551 \u250c\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2510 \u250c\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n \u2551 \u2502 \u2551 \u2551 \u2502 \u2502 \u2551 \u2502\n \u2551 \u2502 b \u2551 \u2551 d \u2502 \u2502 f \u2551 \u2502\n \u2551 \u2502 \u2551 \u2551 \u2502 \u2502 \u2551 \u2502\n \u2551 \u2502 \u2551 \u2551 \u2502 \u2502 \u2551 \u2502\n \u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u255d \u255a\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u255d \u2502\n \u2502 c \u2502 \u2502 g \u2502\n \u2502 \u2502 \u2502 \u2502\n \u2502 \u2502 \u2502 \u2502\n \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\n\nShow all output here.\n\n\n:* \u00a0 Show all solutions for each letter being unique with\n LOW=1 HIGH=7\n:* \u00a0 Show all solutions for each letter being unique with\n LOW=3 HIGH=9\n:* \u00a0 Show only the \u00a0 ''number'' \u00a0 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": "\ndef foursquares(lo,hi,unique,show):\n\n def acd_iter():\n \"\"\"\n Iterates through all the possible valid values of \n a, c, and d.\n \n a = c + d\n \"\"\"\n for c in range(lo,hi+1):\n for d in range(lo,hi+1):\n if (not unique) or (c <> d):\n a = c + d\n if a >= lo and a <= hi:\n if (not unique) or (c <> 0 and d <> 0):\n yield (a,c,d)\n \n def ge_iter():\n \"\"\"\n Iterates through all the possible valid values of \n g and e.\n \n g = d + e\n \"\"\"\n for e in range(lo,hi+1):\n if (not unique) or (e not in (a,c,d)):\n g = d + e\n if g >= lo and g <= hi:\n if (not unique) or (g not in (a,c,d,e)):\n yield (g,e)\n \n def bf_iter():\n \"\"\"\n Iterates through all the possible valid values of \n b and f.\n \n b = e + f - c\n \"\"\"\n for f in range(lo,hi+1):\n if (not unique) or (f not in (a,c,d,g,e)):\n b = e + f - c\n if b >= lo and b <= hi:\n if (not unique) or (b not in (a,c,d,g,e,f)):\n yield (b,f)\n\n solutions = 0 \n acd_itr = acd_iter() \n for acd in acd_itr:\n a,c,d = acd\n ge_itr = ge_iter()\n for ge in ge_itr:\n g,e = ge\n bf_itr = bf_iter()\n for bf in bf_itr:\n b,f = bf\n solutions += 1\n if show:\n print str((a,b,c,d,e,f,g))[1:-1]\n if unique:\n uorn = \"unique\"\n else:\n uorn = \"non-unique\"\n \n print str(solutions)+\" \"+uorn+\" solutions in \"+str(lo)+\" to \"+str(hi)\n print"} +{"title": "4-rings or 4-squares puzzle", "language": "Python 3.7", "task": ";Task:\nReplace \u00a0 \u00a0 \u00a0 '''a, b, c, d, e, f,''' \u00a0 and\n\u00a0 '''g ''' \u00a0 \u00a0 \u00a0 with the decimal\ndigits \u00a0 LOW \u00a0 \u2500\u2500\u2500\u25ba \u00a0 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 \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557 \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n \u2551 \u2551 \u2551 \u2551\n \u2551 a \u2551 \u2551 e \u2551\n \u2551 \u2551 \u2551 \u2551\n \u2551 \u250c\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2510 \u250c\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n \u2551 \u2502 \u2551 \u2551 \u2502 \u2502 \u2551 \u2502\n \u2551 \u2502 b \u2551 \u2551 d \u2502 \u2502 f \u2551 \u2502\n \u2551 \u2502 \u2551 \u2551 \u2502 \u2502 \u2551 \u2502\n \u2551 \u2502 \u2551 \u2551 \u2502 \u2502 \u2551 \u2502\n \u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u255d \u255a\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u255d \u2502\n \u2502 c \u2502 \u2502 g \u2502\n \u2502 \u2502 \u2502 \u2502\n \u2502 \u2502 \u2502 \u2502\n \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\n\nShow all output here.\n\n\n:* \u00a0 Show all solutions for each letter being unique with\n LOW=1 HIGH=7\n:* \u00a0 Show all solutions for each letter being unique with\n LOW=3 HIGH=9\n:* \u00a0 Show only the \u00a0 ''number'' \u00a0 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": "'''4-rings or 4-squares puzzle'''\n\nfrom itertools import chain\n\n\n# rings :: noRepeatedDigits -> DigitList -> Lists of solutions\n# rings :: Bool -> [Int] -> [[Int]]\ndef rings(uniq):\n '''Sets of unique or non-unique integer values\n (drawn from the `digits` argument)\n for each of the seven names [a..g] such that:\n (a + b) == (b + c + d) == (d + e + f) == (f + g)\n '''\n def go(digits):\n ns = sorted(digits, reverse=True)\n h = ns[0]\n\n # CENTRAL DIGIT :: d\n def central(d):\n xs = list(filter(lambda x: h >= (d + x), ns))\n\n # LEFT NEIGHBOUR AND LEFTMOST :: c and a\n def left(c):\n a = c + d\n if a > h:\n return []\n else:\n # RIGHT NEIGHBOUR AND RIGHTMOST :: e and g\n def right(e):\n g = d + e\n if ((g > h) or (uniq and (g == c))):\n return []\n else:\n agDelta = a - g\n bfs = difference(ns)(\n [d, c, e, g, a]\n ) if uniq else ns\n\n # MID LEFT AND RIGHT :: b and f\n def midLeftRight(b):\n f = b + agDelta\n return [[a, b, c, d, e, f, g]] if (\n (f in bfs) and (\n (not uniq) or (\n f not in [a, b, c, d, e, g]\n )\n )\n ) else []\n\n # CANDIDATE DIGITS BOUND TO POSITIONS [a .. g] --------\n\n return concatMap(midLeftRight)(bfs)\n\n return concatMap(right)(\n difference(xs)([d, c, a]) if uniq else ns\n )\n\n return concatMap(left)(\n delete(d)(xs) if uniq else ns\n )\n\n return concatMap(central)(ns)\n\n return lambda digits: go(digits) if digits else []\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Testing unique digits [1..7], [3..9] and unrestricted digits'''\n\n print(main.__doc__ + ':\\n')\n print(unlines(map(\n lambda tpl: '\\nrings' + repr(tpl) + ':\\n\\n' + unlines(\n map(repr, uncurry(rings)(*tpl))\n ), [\n (True, enumFromTo(1)(7)),\n (True, enumFromTo(3)(9))\n ]\n )))\n tpl = (False, enumFromTo(0)(9))\n print(\n '\\n\\nlen(rings' + repr(tpl) + '):\\n\\n' +\n str(len(uncurry(rings)(*tpl)))\n )\n\n\n# GENERIC -------------------------------------------------\n\n# concatMap :: (a -> [b]) -> [a] -> [b]\ndef concatMap(f):\n '''A concatenated list over which a function has been mapped.\n The list monad can be derived by using a function f which\n wraps its output in a list,\n (using an empty list to represent computational failure).\n '''\n return lambda xs: list(\n chain.from_iterable(map(f, xs))\n )\n\n\n# delete :: Eq a => a -> [a] -> [a]\ndef delete(x):\n '''xs with the first of any instances of x removed.'''\n def go(xs):\n xs.remove(x)\n return xs\n return lambda xs: go(list(xs)) if (\n x in xs\n ) else list(xs)\n\n\n# difference :: Eq a => [a] -> [a] -> [a]\ndef difference(xs):\n '''All elements of ys except any also found in xs'''\n def go(ys):\n s = set(ys)\n return [x for x in xs if x not in s]\n return lambda ys: go(ys)\n\n\n# enumFromTo :: (Int, Int) -> [Int]\ndef enumFromTo(m):\n '''Integer enumeration from m to n.'''\n return lambda n: list(range(m, 1 + n))\n\n\n# uncurry :: (a -> b -> c) -> ((a, b) -> c)\ndef uncurry(f):\n '''A function over a pair of arguments,\n derived from a vanilla or curried function.\n '''\n return lambda x, y: f(x)(y)\n\n\n# unlines :: [String] -> String\ndef unlines(xs):\n '''A single string formed by the intercalation\n of a list of strings with the newline character.\n '''\n return '\\n'.join(xs)\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} +{"title": "99 bottles of beer", "language": "C", "task": ";Task:\nDisplay the complete lyrics for the song: \u00a0 \u00a0 '''99 Bottles of Beer on the Wall'''. \n\n\n;The beer song:\nThe lyrics follow this form:\n\n\n::: 99 bottles of beer on the wall\n::: 99 bottles of beer\n::: Take one down, pass it around\n::: 98 bottles of beer on the wall\n \n::: 98 bottles of beer on the wall\n::: 98 bottles of beer\n::: Take one down, pass it around\n::: 97 bottles of beer on the wall\n\n\n... and so on, until reaching \u00a0 '''0''' \u00a0 \u00a0 (zero).\n\nGrammatical support for \u00a0 ''1 bottle of beer'' \u00a0 is optional. \n\nAs with any puzzle, try to do it in as creative/concise/comical a way \nas possible (simple, obvious solutions allowed, too).\n\n\n\n\n;See also: \n* \u00a0 http://99-bottles-of-beer.net/\n* \u00a0 [[:Category:99_Bottles_of_Beer]]\n* \u00a0 [[:Category:Programming language families]]\n* \u00a0 [https://en.wikipedia.org/wiki/99_Bottles_of_Beer Wikipedia 99 bottles of beer]\n\n", "solution": " int b =99,u =1;\n #include\n char *d[16],y[]\n = \"#:ottle/ of\"\n \":eer_ a_Goy\\x20some6\"\n \"_Take8;down4p\"\n \"a=1rou7_17 _<\"\n \"h;_ m?_nd_ on\"\n \"_085wal\" \"l_ \"\n \"b_e _ t_ss it\"\n \"_?4bu_ore_9, \"\n \"\\060.\"\"@, 9$\";\n # define x c ^=\n #include \n #define or(t,z) else\\\n if(c==t && !(c = 0) &&\\\n (c =! z)); int p(char *t)\n{ char *s = t; int c; for (\nd[c = 0] = y; !t && (d[c +1\n]= strchr(s = d[c], '_'));*\n(d[++c]++) = 0); for(t = s?\ns:t;(c= *s++); c && putchar\n(c)) { if (!((( x 48)& ~0xf\n) && ( x 48)) ) p(d[c]), c=\n0 ; or('$', p(b - 99?\".\\n\":\n\".\" ) && p(b - 99? t : \"\"))\nor ('\\x40', c && p( d[!!b--\n+ 2])) or('/', c && p( b^1?\n\"s\": \"\")) or ('\\043', b++ ?\np(\"So6\" + --b):!printf(\"%d\"\n, b ? --b : (b += 99))) or(\n'S',!(++u % 3) * 32+ 78) or\n('.', puts(\".\"))}return c;}\n int main() {return p(0);}"} +{"title": "99 bottles of beer", "language": "JavaScript", "task": ";Task:\nDisplay the complete lyrics for the song: \u00a0 \u00a0 '''99 Bottles of Beer on the Wall'''. \n\n\n;The beer song:\nThe lyrics follow this form:\n\n\n::: 99 bottles of beer on the wall\n::: 99 bottles of beer\n::: Take one down, pass it around\n::: 98 bottles of beer on the wall\n \n::: 98 bottles of beer on the wall\n::: 98 bottles of beer\n::: Take one down, pass it around\n::: 97 bottles of beer on the wall\n\n\n... and so on, until reaching \u00a0 '''0''' \u00a0 \u00a0 (zero).\n\nGrammatical support for \u00a0 ''1 bottle of beer'' \u00a0 is optional. \n\nAs with any puzzle, try to do it in as creative/concise/comical a way \nas possible (simple, obvious solutions allowed, too).\n\n\n\n\n;See also: \n* \u00a0 http://99-bottles-of-beer.net/\n* \u00a0 [[:Category:99_Bottles_of_Beer]]\n* \u00a0 [[:Category:Programming language families]]\n* \u00a0 [https://en.wikipedia.org/wiki/99_Bottles_of_Beer Wikipedia 99 bottles of beer]\n\n", "solution": "function Bottles(count) {\n this.count = count || 99;\n}\n\nBottles.prototype.take = function() {\n var verse = [\n this.count + \" bottles of beer on the wall,\",\n this.count + \" bottles of beer!\",\n \"Take one down, pass it around\", \n (this.count - 1) + \" bottles of beer on the wall!\"\n ].join(\"\\n\");\n\n console.log(verse);\n\n this.count--;\n};\n\nBottles.prototype.sing = function() {\n while (this.count) { \n this.take(); \n }\n};\n\nvar bar = new Bottles(99);\nbar.sing();"} +{"title": "99 bottles of beer", "language": "Python 3.6+", "task": ";Task:\nDisplay the complete lyrics for the song: \u00a0 \u00a0 '''99 Bottles of Beer on the Wall'''. \n\n\n;The beer song:\nThe lyrics follow this form:\n\n\n::: 99 bottles of beer on the wall\n::: 99 bottles of beer\n::: Take one down, pass it around\n::: 98 bottles of beer on the wall\n \n::: 98 bottles of beer on the wall\n::: 98 bottles of beer\n::: Take one down, pass it around\n::: 97 bottles of beer on the wall\n\n\n... and so on, until reaching \u00a0 '''0''' \u00a0 \u00a0 (zero).\n\nGrammatical support for \u00a0 ''1 bottle of beer'' \u00a0 is optional. \n\nAs with any puzzle, try to do it in as creative/concise/comical a way \nas possible (simple, obvious solutions allowed, too).\n\n\n\n\n;See also: \n* \u00a0 http://99-bottles-of-beer.net/\n* \u00a0 [[:Category:99_Bottles_of_Beer]]\n* \u00a0 [[:Category:Programming language families]]\n* \u00a0 [https://en.wikipedia.org/wiki/99_Bottles_of_Beer Wikipedia 99 bottles of beer]\n\n", "solution": "\nfor i in range(99, 0, -1):b='bottles of beer';w=f' {b} on the wall';print(f'{i}{w}, {i} {b}\\nTake one down and pass it around, {i-1}{w}.\\n')\n"} +{"title": "99 bottles of beer", "language": "Python 3", "task": ";Task:\nDisplay the complete lyrics for the song: \u00a0 \u00a0 '''99 Bottles of Beer on the Wall'''. \n\n\n;The beer song:\nThe lyrics follow this form:\n\n\n::: 99 bottles of beer on the wall\n::: 99 bottles of beer\n::: Take one down, pass it around\n::: 98 bottles of beer on the wall\n \n::: 98 bottles of beer on the wall\n::: 98 bottles of beer\n::: Take one down, pass it around\n::: 97 bottles of beer on the wall\n\n\n... and so on, until reaching \u00a0 '''0''' \u00a0 \u00a0 (zero).\n\nGrammatical support for \u00a0 ''1 bottle of beer'' \u00a0 is optional. \n\nAs with any puzzle, try to do it in as creative/concise/comical a way \nas possible (simple, obvious solutions allowed, too).\n\n\n\n\n;See also: \n* \u00a0 http://99-bottles-of-beer.net/\n* \u00a0 [[:Category:99_Bottles_of_Beer]]\n* \u00a0 [[:Category:Programming language families]]\n* \u00a0 [https://en.wikipedia.org/wiki/99_Bottles_of_Beer Wikipedia 99 bottles of beer]\n\n", "solution": "\"\"\"\n 99 Bottles of Beer on the Wall made functional\n \n Main function accepts a number of parameters, so you can specify a name of \n the drink, its container and other things. English only.\n\"\"\"\n\nfrom functools import partial\nfrom typing import Callable\n\n\ndef regular_plural(noun: str) -> str:\n \"\"\"English rule to get the plural form of a word\"\"\"\n if noun[-1] == \"s\":\n return noun + \"es\"\n \n return noun + \"s\"\n\n\ndef beer_song(\n *,\n location: str = 'on the wall',\n distribution: str = 'Take one down, pass it around',\n solution: str = 'Better go to the store to buy some more!',\n container: str = 'bottle',\n plurifier: Callable[[str], str] = regular_plural,\n liquid: str = \"beer\",\n initial_count: int = 99,\n) -> str:\n \"\"\"\n Return the lyrics of the beer song\n :param location: initial location of the drink\n :param distribution: specifies the process of its distribution\n :param solution: what happens when we run out of drinks\n :param container: bottle/barrel/flask or other containers\n :param plurifier: function converting a word to its plural form\n :param liquid: the name of the drink in the given container\n :param initial_count: how many containers available initially\n \"\"\"\n \n verse = partial(\n get_verse,\n initial_count = initial_count, \n location = location,\n distribution = distribution,\n solution = solution,\n container = container,\n plurifier = plurifier,\n liquid = liquid,\n )\n \n verses = map(verse, range(initial_count, -1, -1))\n return '\\n\\n'.join(verses)\n\n\ndef get_verse(\n count: int,\n *,\n initial_count: str,\n location: str,\n distribution: str,\n solution: str,\n container: str,\n plurifier: Callable[[str], str],\n liquid: str,\n) -> str:\n \"\"\"Returns the verse for the given amount of drinks\"\"\"\n \n asset = partial(\n get_asset,\n container = container,\n plurifier = plurifier,\n liquid = liquid,\n )\n \n current_asset = asset(count)\n next_number = count - 1 if count else initial_count\n next_asset = asset(next_number)\n action = distribution if count else solution\n \n inventory = partial(\n get_inventory,\n location = location,\n )\n \n return '\\n'.join((\n inventory(current_asset),\n current_asset,\n action,\n inventory(next_asset),\n ))\n\n\ndef get_inventory(\n asset: str,\n *,\n location: str,\n) -> str:\n \"\"\"\n Used to return the first or the fourth line of the verse\n\n >>> get_inventory(\"10 bottles of beer\", location=\"on the wall\")\n \"10 bottles of beer on the wall\"\n \"\"\"\n return ' '.join((asset, location))\n\n\ndef get_asset(\n count: int,\n *,\n container: str,\n plurifier: Callable[[str], str],\n liquid: str,\n) -> str:\n \"\"\"\n Quantified asset\n \n >>> get_asset(0, container=\"jar\", plurifier=regular_plural, liquid='milk')\n \"No more jars of milk\"\n \"\"\"\n \n containers = plurifier(container) if count != 1 else container\n spelled_out_quantity = str(count) if count else \"No more\" \n return ' '.join((spelled_out_quantity, containers, \"of\", liquid))\n\n\nif __name__ == '__main__':\n print(beer_song())\n"} +{"title": "99 bottles of beer", "language": "Python 3.7+", "task": ";Task:\nDisplay the complete lyrics for the song: \u00a0 \u00a0 '''99 Bottles of Beer on the Wall'''. \n\n\n;The beer song:\nThe lyrics follow this form:\n\n\n::: 99 bottles of beer on the wall\n::: 99 bottles of beer\n::: Take one down, pass it around\n::: 98 bottles of beer on the wall\n \n::: 98 bottles of beer on the wall\n::: 98 bottles of beer\n::: Take one down, pass it around\n::: 97 bottles of beer on the wall\n\n\n... and so on, until reaching \u00a0 '''0''' \u00a0 \u00a0 (zero).\n\nGrammatical support for \u00a0 ''1 bottle of beer'' \u00a0 is optional. \n\nAs with any puzzle, try to do it in as creative/concise/comical a way \nas possible (simple, obvious solutions allowed, too).\n\n\n\n\n;See also: \n* \u00a0 http://99-bottles-of-beer.net/\n* \u00a0 [[:Category:99_Bottles_of_Beer]]\n* \u00a0 [[:Category:Programming language families]]\n* \u00a0 [https://en.wikipedia.org/wiki/99_Bottles_of_Beer Wikipedia 99 bottles of beer]\n\n", "solution": "'''99 Units of Disposable Asset'''\n\n\nfrom itertools import chain\n\n\n# main :: IO ()\ndef main():\n '''Modalised asset dispersal procedure.'''\n\n # localisation :: (String, String, String)\n localisation = (\n 'on the wall',\n 'Take one down, pass it around',\n 'Better go to the store to buy some more'\n )\n\n print(unlines(map(\n incantation(localisation),\n enumFromThenTo(99)(98)(0)\n )))\n\n\n# incantation :: (String, String, String) -> Int -> String\ndef incantation(localisation):\n '''Versification of asset disposal\n and inventory update.'''\n\n location, distribution, solution = localisation\n\n def inventory(n):\n return unwords([asset(n), location])\n return lambda n: solution if 0 == n else (\n unlines([\n inventory(n),\n asset(n),\n distribution,\n inventory(pred(n))\n ])\n )\n\n\n# asset :: Int -> String\ndef asset(n):\n '''Quantified asset.'''\n def suffix(n):\n return [] if 1 == n else 's'\n return unwords([\n str(n),\n concat(reversed(concat(cons(suffix(n))([\"elttob\"]))))\n ])\n\n\n# GENERIC -------------------------------------------------\n\n# concat :: [[a]] -> [a]\n# concat :: [String] -> String\ndef concat(xxs):\n '''The concatenation of all the elements in a list.'''\n xs = list(chain.from_iterable(xxs))\n unit = '' if isinstance(xs, str) else []\n return unit if not xs else (\n ''.join(xs) if isinstance(xs[0], str) else xs\n )\n\n\n# cons :: a -> [a] -> [a]\ndef cons(x):\n '''Construction of a list from x as head,\n and xs as tail.'''\n return lambda xs: [x] + xs if (\n isinstance(xs, list)\n ) else chain([x], xs)\n\n\n# enumFromThenTo :: Int -> Int -> Int -> [Int]\ndef enumFromThenTo(m):\n '''Integer values enumerated from m to n\n with a step defined by nxt-m.'''\n def go(nxt, n):\n d = nxt - m\n return list(range(m, d + n, d))\n return lambda nxt: lambda n: (\n go(nxt, n)\n )\n\n\n# pred :: Enum a => a -> a\ndef pred(x):\n '''The predecessor of a value. For numeric types, (- 1).'''\n return x - 1 if isinstance(x, int) else (\n chr(ord(x) - 1)\n )\n\n\n# unlines :: [String] -> String\ndef unlines(xs):\n '''A single string derived by the intercalation\n of a list of strings with the newline character.'''\n return '\\n'.join(xs)\n\n\n# unwords :: [String] -> String\ndef unwords(xs):\n '''A space-separated string derived from\n a list of words.'''\n return ' '.join(xs)\n\n\nif __name__ == '__main__':\n main()"} +{"title": "9 billion names of God the integer", "language": "C", "task": "This task is a variation of the short story by Arthur C. Clarke.\n \n(Solvers should be aware of the consequences of completing this task.)\n\nIn detail, to specify what is meant by a \u00a0 \u201cname\u201d:\n:The integer 1 has 1 name \u00a0 \u00a0 \u201c1\u201d.\n:The integer 2 has 2 names \u00a0 \u201c1+1\u201d, \u00a0 and \u00a0 \u201c2\u201d.\n:The integer 3 has 3 names \u00a0 \u201c1+1+1\u201d, \u00a0 \u201c2+1\u201d, \u00a0 and \u00a0 \u201c3\u201d.\n:The integer 4 has 5 names \u00a0 \u201c1+1+1+1\u201d, \u00a0 \u201c2+1+1\u201d, \u00a0 \u201c2+2\u201d, \u00a0 \u201c3+1\u201d, \u00a0 \u201c4\u201d.\n:The integer 5 has 7 names \u00a0 \u201c1+1+1+1+1\u201d, \u00a0 \u201c2+1+1+1\u201d, \u00a0 \u201c2+2+1\u201d, \u00a0 \u201c3+1+1\u201d, \u00a0 \u201c3+2\u201d, \u00a0 \u201c4+1\u201d, \u00a0 \u201c5\u201d.\n\n\n;Task\nDisplay the first 25 rows of a number triangle which begins:\n\n 1\n 1 1\n 1 1 1 \n 1 2 1 1\n 1 2 2 1 1\n 1 3 3 2 1 1\n\n\nWhere row \u00a0 n \u00a0 corresponds to integer \u00a0 n, \u00a0 and each column \u00a0 C \u00a0 in row \u00a0 m \u00a0 from left to right corresponds to the number of names beginning with \u00a0 C.\n\nA function \u00a0 G(n) \u00a0 should return the sum of the \u00a0 n-th \u00a0 row. \n\nDemonstrate this function by displaying: \u00a0 G(23), \u00a0 G(123), \u00a0 G(1234), \u00a0 and \u00a0 G(12345). \n\nOptionally note that the sum of the \u00a0 n-th \u00a0 row \u00a0 P(n) \u00a0 is the \u00a0 [http://mathworld.wolfram.com/PartitionFunctionP.html \u00a0 integer partition function]. \n\nDemonstrate this is equivalent to \u00a0 G(n) \u00a0 by displaying: \u00a0 P(23), \u00a0 P(123), \u00a0 P(1234), \u00a0 and \u00a0 P(12345).\n\n\n;Extra credit\n\nIf your environment is able, plot \u00a0 P(n) \u00a0 against \u00a0 n \u00a0 for \u00a0 n=1\\ldots 999.\n\n;Related tasks\n* [[Partition function P]]\n\n", "solution": "#include \n#include \n\n#define N 100000\nmpz_t p[N + 1];\n\nvoid calc(int n)\n{\n\tmpz_init_set_ui(p[n], 0);\n\n\tfor (int k = 1; k <= n; k++) {\n\t\tint d = n - k * (3 * k - 1) / 2;\n\t\tif (d < 0) break;\n\n\t\tif (k&1)mpz_add(p[n], p[n], p[d]);\n\t\telse\tmpz_sub(p[n], p[n], p[d]);\n\n\t\td -= k;\n\t\tif (d < 0) break;\n\n\t\tif (k&1)mpz_add(p[n], p[n], p[d]);\n\t\telse\tmpz_sub(p[n], p[n], p[d]);\n\t}\n}\n\nint main(void)\n{\n\tint idx[] = { 23, 123, 1234, 12345, 20000, 30000, 40000, 50000, N, 0 };\n\tint at = 0;\n\n\tmpz_init_set_ui(p[0], 1);\n\n\tfor (int i = 1; idx[at]; i++) {\n\t\tcalc(i);\n\t\tif (i != idx[at]) continue;\n\n\t\tgmp_printf(\"%2d:\\t%Zd\\n\", i, p[i]);\n\t\tat++;\n\t}\n}"} +{"title": "9 billion names of God the integer", "language": "JavaScript", "task": "This task is a variation of the short story by Arthur C. Clarke.\n \n(Solvers should be aware of the consequences of completing this task.)\n\nIn detail, to specify what is meant by a \u00a0 \u201cname\u201d:\n:The integer 1 has 1 name \u00a0 \u00a0 \u201c1\u201d.\n:The integer 2 has 2 names \u00a0 \u201c1+1\u201d, \u00a0 and \u00a0 \u201c2\u201d.\n:The integer 3 has 3 names \u00a0 \u201c1+1+1\u201d, \u00a0 \u201c2+1\u201d, \u00a0 and \u00a0 \u201c3\u201d.\n:The integer 4 has 5 names \u00a0 \u201c1+1+1+1\u201d, \u00a0 \u201c2+1+1\u201d, \u00a0 \u201c2+2\u201d, \u00a0 \u201c3+1\u201d, \u00a0 \u201c4\u201d.\n:The integer 5 has 7 names \u00a0 \u201c1+1+1+1+1\u201d, \u00a0 \u201c2+1+1+1\u201d, \u00a0 \u201c2+2+1\u201d, \u00a0 \u201c3+1+1\u201d, \u00a0 \u201c3+2\u201d, \u00a0 \u201c4+1\u201d, \u00a0 \u201c5\u201d.\n\n\n;Task\nDisplay the first 25 rows of a number triangle which begins:\n\n 1\n 1 1\n 1 1 1 \n 1 2 1 1\n 1 2 2 1 1\n 1 3 3 2 1 1\n\n\nWhere row \u00a0 n \u00a0 corresponds to integer \u00a0 n, \u00a0 and each column \u00a0 C \u00a0 in row \u00a0 m \u00a0 from left to right corresponds to the number of names beginning with \u00a0 C.\n\nA function \u00a0 G(n) \u00a0 should return the sum of the \u00a0 n-th \u00a0 row. \n\nDemonstrate this function by displaying: \u00a0 G(23), \u00a0 G(123), \u00a0 G(1234), \u00a0 and \u00a0 G(12345). \n\nOptionally note that the sum of the \u00a0 n-th \u00a0 row \u00a0 P(n) \u00a0 is the \u00a0 [http://mathworld.wolfram.com/PartitionFunctionP.html \u00a0 integer partition function]. \n\nDemonstrate this is equivalent to \u00a0 G(n) \u00a0 by displaying: \u00a0 P(23), \u00a0 P(123), \u00a0 P(1234), \u00a0 and \u00a0 P(12345).\n\n\n;Extra credit\n\nIf your environment is able, plot \u00a0 P(n) \u00a0 against \u00a0 n \u00a0 for \u00a0 n=1\\ldots 999.\n\n;Related tasks\n* [[Partition function P]]\n\n", "solution": "\n(function () {\n var cache = [\n [1]\n ];\n//this was never needed.\n /* function PyRange(start, end, step) {\n step = step || 1;\n if (!end) {\n end = start;\n start = 0;\n }\n var arr = [];\n for (var i = start; i < end; i += step) arr.push(i);\n return arr;\n }*/ \n\n function cumu(n) {\n var /*ra = PyRange(cache.length, n + 1),*/ //Seems there is a better version for this\n r, l, x, Aa, Mi;\n // for (ll in ra) { too pythony\n for (l=cache.length;l\n\n===Solution 2===\nClean and straightforward solution\n\nfunction genTriangle(n){ // O(n^3) time and O(n^2) space\n var a = new Array(n)\n \n for (let i = 0; i < n; i++){\n a[i] = new Array(i+1)\n for (let j = 0; j < i; j++){\n a[i][j] = 0\n let s = i-j-1, k = Math.min(s, j)\n while (k >= 0) a[i][j] += a[s][k--]\n }\n a[i][i] = 1\n }\n \n return a.map(x => x.join(\" \")).join(\"\\n\")\n}\n\nfunction G(n){ // At least O(n^2) time and O(n) space\n var a = new Array(n+1)\n a[0] = 1n\n \n for (let i = 1; i <= n; i++){\n a[i] = 0n\n for (let k = 1, s = 1; s <= i;){\n a[i] += (k & 1 ? a[i-s]:-a[i-s])\n k > 0 ? (s += k, k = -k):(k = -k+1, s = k*(3*k-1)/2)\n }\n }\n \n return a[n]\n}\n\nconsole.log(genTriangle(25))\nconsole.log(\"\")\n\nfor (const x of [23, 123, 1234, 12345]){\n console.log(\"G(\" + x + \") = \" + G(x))\n}\n\n"} +{"title": "9 billion names of God the integer", "language": "Python", "task": "This task is a variation of the short story by Arthur C. Clarke.\n \n(Solvers should be aware of the consequences of completing this task.)\n\nIn detail, to specify what is meant by a \u00a0 \u201cname\u201d:\n:The integer 1 has 1 name \u00a0 \u00a0 \u201c1\u201d.\n:The integer 2 has 2 names \u00a0 \u201c1+1\u201d, \u00a0 and \u00a0 \u201c2\u201d.\n:The integer 3 has 3 names \u00a0 \u201c1+1+1\u201d, \u00a0 \u201c2+1\u201d, \u00a0 and \u00a0 \u201c3\u201d.\n:The integer 4 has 5 names \u00a0 \u201c1+1+1+1\u201d, \u00a0 \u201c2+1+1\u201d, \u00a0 \u201c2+2\u201d, \u00a0 \u201c3+1\u201d, \u00a0 \u201c4\u201d.\n:The integer 5 has 7 names \u00a0 \u201c1+1+1+1+1\u201d, \u00a0 \u201c2+1+1+1\u201d, \u00a0 \u201c2+2+1\u201d, \u00a0 \u201c3+1+1\u201d, \u00a0 \u201c3+2\u201d, \u00a0 \u201c4+1\u201d, \u00a0 \u201c5\u201d.\n\n\n;Task\nDisplay the first 25 rows of a number triangle which begins:\n\n 1\n 1 1\n 1 1 1 \n 1 2 1 1\n 1 2 2 1 1\n 1 3 3 2 1 1\n\n\nWhere row \u00a0 n \u00a0 corresponds to integer \u00a0 n, \u00a0 and each column \u00a0 C \u00a0 in row \u00a0 m \u00a0 from left to right corresponds to the number of names beginning with \u00a0 C.\n\nA function \u00a0 G(n) \u00a0 should return the sum of the \u00a0 n-th \u00a0 row. \n\nDemonstrate this function by displaying: \u00a0 G(23), \u00a0 G(123), \u00a0 G(1234), \u00a0 and \u00a0 G(12345). \n\nOptionally note that the sum of the \u00a0 n-th \u00a0 row \u00a0 P(n) \u00a0 is the \u00a0 [http://mathworld.wolfram.com/PartitionFunctionP.html \u00a0 integer partition function]. \n\nDemonstrate this is equivalent to \u00a0 G(n) \u00a0 by displaying: \u00a0 P(23), \u00a0 P(123), \u00a0 P(1234), \u00a0 and \u00a0 P(12345).\n\n\n;Extra credit\n\nIf your environment is able, plot \u00a0 P(n) \u00a0 against \u00a0 n \u00a0 for \u00a0 n=1\\ldots 999.\n\n;Related tasks\n* [[Partition function P]]\n\n", "solution": "cache = [[1]]\ndef cumu(n):\n for l in range(len(cache), n+1):\n r = [0]\n for x in range(1, l+1):\n r.append(r[-1] + cache[l-x][min(x, l-x)])\n cache.append(r)\n return cache[n]\n\ndef row(n):\n r = cumu(n)\n return [r[i+1] - r[i] for i in range(n)]\n\nprint \"rows:\"\nfor x in range(1, 11): print \"%2d:\"%x, row(x)\n\n\nprint \"\\nsums:\"\nfor x in [23, 123, 1234, 12345]: print x, cumu(x)[-1]"} +{"title": "A+B", "language": "C", "task": "'''A+B''' \u00a0 \u2500\u2500\u2500 a classic problem in programming contests, \u00a0 it's given so contestants can gain familiarity with the online judging system being used.\n\n\n;Task:\nGiven two integers, \u00a0 '''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: \u00a0 the sum of '''A''' and '''B'''.\n\n\n;Example:\n::{|class=\"standard\"\n ! input \u00a0\n ! output \u00a0\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": "A+B", "language": "JavaScript", "task": "'''A+B''' \u00a0 \u2500\u2500\u2500 a classic problem in programming contests, \u00a0 it's given so contestants can gain familiarity with the online judging system being used.\n\n\n;Task:\nGiven two integers, \u00a0 '''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: \u00a0 the sum of '''A''' and '''B'''.\n\n\n;Example:\n::{|class=\"standard\"\n ! input \u00a0\n ! output \u00a0\n |-\n | 2 2 \n | 4 \n |-\n | 3 2 \n | 5 \n |}\n\n", "solution": "process.openStdin().on (\n 'data',\n function (line) {\n var xs = String(line).match(/^\\s*(\\d+)\\s+(\\d+)\\s*/)\n console.log (\n xs ? Number(xs[1]) + Number(xs[2]) : 'usage: '\n )\n process.exit()\n }\n)"} +{"title": "A+B", "language": "Python", "task": "'''A+B''' \u00a0 \u2500\u2500\u2500 a classic problem in programming contests, \u00a0 it's given so contestants can gain familiarity with the online judging system being used.\n\n\n;Task:\nGiven two integers, \u00a0 '''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: \u00a0 the sum of '''A''' and '''B'''.\n\n\n;Example:\n::{|class=\"standard\"\n ! input \u00a0\n ! output \u00a0\n |-\n | 2 2 \n | 4 \n |-\n | 3 2 \n | 5 \n |}\n\n", "solution": "a = int(input(\"First number: \"))\nb = int(input(\"Second number: \"))\nprint(\"Result:\", a+b)"} +{"title": "ABC problem", "language": "C", "task": "You are given a collection of ABC blocks \u00a0 (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::# \u00a0 Once a letter on a block is used that block cannot be used again\n::# \u00a0 The function should be case-insensitive\n::# \u00a0 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": "ABC problem", "language": "JavaScript", "task": "You are given a collection of ABC blocks \u00a0 (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::# \u00a0 Once a letter on a block is used that block cannot be used again\n::# \u00a0 The function should be case-insensitive\n::# \u00a0 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": "var blocks = \"BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM\";\n\nfunction CheckWord(blocks, word) {\n // Makes sure that word only contains letters.\n if(word !== /([a-z]*)/i.exec(word)[1]) return false;\n // Loops through each character to see if a block exists.\n for(var i = 0; i < word.length; ++i)\n {\n // Gets the ith character.\n var letter = word.charAt(i);\n // Stores the length of the blocks to determine if a block was removed.\n var length = blocks.length;\n // The regexp gets constructed by eval to allow more browsers to use the function.\n var reg = eval(\"/([a-z]\"+letter+\"|\"+letter+\"[a-z])/i\");\n // This does the same as above, but some browsers do not support...\n //var reg = new RegExp(\"([a-z]\"+letter+\"|\"+letter+\"[a-z])\", \"i\");\n // Removes all occurrences of the match. \n blocks = blocks.replace(reg, \"\");\n // If the length did not change then a block did not exist.\n if(blocks.length === length) return false;\n }\n // If every character has passed then return true.\n return true;\n};\n\nvar words = [\n \"A\",\n \"BARK\", \n \"BOOK\", \n \"TREAT\", \n \"COMMON\", \n \"SQUAD\", \n \"CONFUSE\" \n];\n\nfor(var i = 0;i\n\nResult:\n\nA: true\nBARK: true\nBOOK: false\nTREAT: true\nCOMMON: false\nSQUAD: true\nCONFUSE: true\n\n\n====Functional====\n(function (strWords) {\n\n var strBlocks =\n 'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM',\n blocks = strBlocks.split(' ');\n\n function abc(lstBlocks, strWord) {\n var lngChars = strWord.length;\n\n if (!lngChars) return [];\n\n var b = lstBlocks[0],\n c = strWord[0];\n\n return chain(lstBlocks, function (b) {\n return (b.indexOf(c.toUpperCase()) !== -1) ? [\n (b + ' ').concat(\n abc(removed(b, lstBlocks), strWord.slice(1)))\n ] : [];\n })\n }\n\n // Monadic bind (chain) for lists\n function chain(xs, f) {\n return [].concat.apply([], xs.map(f));\n }\n\n // a -> [a] -> [a]\n function removed(x, xs) {\n var h = xs.length ? xs[0] : null,\n t = h ? xs.slice(1) : [];\n\n return h ? (\n h === x ? t : [h].concat(removed(x, t))\n ) : [];\n }\n\n function solution(strWord) {\n var strAttempt = abc(blocks, strWord)[0].split(',')[0];\n\n // two chars per block plus one space -> 3\n return strWord + ((strAttempt.length === strWord.length * 3) ?\n ' -> ' + strAttempt : ': [no solution]');\n }\n\n return strWords.split(' ').map(solution).join('\\n');\n\n})('A bark BooK TReAT COMMON squAD conFUSE');\n"} +{"title": "ABC problem", "language": "Python", "task": "You are given a collection of ABC blocks \u00a0 (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::# \u00a0 Once a letter on a block is used that block cannot be used again\n::# \u00a0 The function should be case-insensitive\n::# \u00a0 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": "\n'''\nNote that this code is broken, e.g., it won't work when \nblocks = [(\"A\", \"B\"), (\"A\",\"C\")] and the word is \"AB\", where the answer\nshould be True, but the code returns False.\n'''\nblocks = [(\"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\ndef can_make_word(word, block_collection=blocks):\n \"\"\"\n Return True if `word` can be made from the blocks in `block_collection`.\n\n >>> can_make_word(\"\")\n False\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(\"coNFused\")\n True\n \"\"\"\n if not word:\n return False\n\n blocks_remaining = block_collection[:]\n for char in word.upper():\n for block in blocks_remaining:\n if char in block:\n blocks_remaining.remove(block)\n break\n else:\n return False\n return True\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n print(\", \".join(\"'%s': %s\" % (w, can_make_word(w)) for w in\n [\"\", \"a\", \"baRk\", \"booK\", \"treat\", \n \"COMMON\", \"squad\", \"Confused\"]))\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": "\n#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": "ASCII art diagram converter", "language": "JavaScript", "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": "// ------------------------------------------------------------[ Boilerplate ]--\nconst trimWhitespace = s => s.trim();\nconst isNotEmpty = s => s !== '';\nconst stringLength = s => s.length;\nconst hexToBin4 = s => parseInt(s, 16).toString(2).padStart(4, '0');\nconst concatHexToBin = (binStr, hexStr) => binStr.concat('', hexToBin4(hexStr));\nconst alignRight = n => s => `${s}`.padStart(n, ' ');\nconst alignLeft = n => s => `${s}`.padEnd(n, ' ');\nconst repeatChar = c => n => c.padStart(n, c);\nconst joinWith = c => arr => arr.join(c);\nconst joinNl = joinWith('\\n');\nconst joinSp = joinWith(' ');\n\nconst printDiagramInfo = map => {\n const pName = alignLeft(8);\n const p5 = alignRight(5);\n const line = repeatChar('-');\n const res = [];\n res.push(joinSp([pName('Name'), p5('Size'), p5('Start'), p5('End')]));\n res.push(joinSp([line(8), line(5), line(5), line(5)]));\n [...map.values()].forEach(({label, bitLength, start, end}) => {\n res.push(joinSp([pName(label), p5(bitLength), p5(start), p5(end)]));\n })\n return res;\n}\n\n// -------------------------------------------------------------------[ Main ]--\nconst parseDiagram = dia => {\n\n const arr = dia.split('\\n').map(trimWhitespace).filter(isNotEmpty);\n\n const hLine = arr[0];\n const bitTokens = hLine.split('+').map(trimWhitespace).filter(isNotEmpty);\n const bitWidth = bitTokens.length;\n const bitTokenWidth = bitTokens[0].length;\n\n const fields = arr.filter(e => e !== hLine);\n const allFields = fields.reduce((p, c) => [...p, ...c.split('|')], [])\n .filter(isNotEmpty);\n\n const lookupMap = Array(bitWidth).fill('').reduce((p, c, i) => {\n const v = i + 1;\n const stringWidth = (v * bitTokenWidth) + (v - 1);\n p.set(stringWidth, v);\n return p;\n }, new Map())\n\n const fieldMetaMap = allFields.reduce((p, e, i) => {\n const bitLength = lookupMap.get(e.length);\n const label = trimWhitespace(e);\n const start = i ? p.get(i - 1).end + 1 : 0;\n const end = start - 1 + bitLength;\n p.set(i, {label, bitLength, start, end})\n return p;\n }, new Map());\n\n const pName = alignLeft(8);\n const pBit = alignRight(5);\n const pPat = alignRight(18);\n const line = repeatChar('-');\n const nl = '\\n';\n return hexStr => {\n const binString = [...hexStr].reduce(concatHexToBin, '');\n\n const res = printDiagramInfo(fieldMetaMap);\n res.unshift(joinNl(['Diagram:', ...arr, nl]));\n res.push(joinNl([nl, 'Test string in hex:', hexStr]));\n res.push(joinNl(['Test string in binary:', binString, nl]));\n res.push(joinSp([pName('Name'), pBit('Size'), pPat('Pattern')]));\n res.push(joinSp([line(8), line(5), line(18)]));\n\n [...fieldMetaMap.values()].forEach(({label, bitLength, start, end}) => {\n res.push(joinSp(\n [pName(label), pBit(bitLength),\n pPat(binString.substr(start, bitLength))]))\n })\n return joinNl(res);\n }\n}\n\n// --------------------------------------------------------------[ Run tests ]--\n\nconst dia = `\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`;\n\nconst parser = parseDiagram(dia);\n\nparser('78477bbf5496e12e1bf169a4');"} +{"title": "ASCII art diagram converter", "language": "Python", "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": "\n\"\"\"\nhttp://rosettacode.org/wiki/ASCII_art_diagram_converter\n\nPython example based off Go example:\n\nhttp://rosettacode.org/wiki/ASCII_art_diagram_converter#Go\n\n\"\"\"\n\ndef validate(diagram):\n\n # trim empty lines\n \n rawlines = diagram.splitlines()\n lines = []\n for line in rawlines:\n if line != '':\n lines.append(line)\n \n # validate non-empty lines\n \n if len(lines) == 0:\n print('diagram has no non-empty lines!')\n return None\n \n width = len(lines[0])\n cols = (width - 1) // 3\n \n if cols not in [8, 16, 32, 64]: \n print('number of columns should be 8, 16, 32 or 64')\n return None\n \n if len(lines)%2 == 0:\n print('number of non-empty lines should be odd')\n return None\n \n if lines[0] != (('+--' * cols)+'+'):\n print('incorrect header line')\n return None\n\n for i in range(len(lines)):\n line=lines[i]\n if i == 0:\n continue\n elif i%2 == 0:\n if line != lines[0]:\n print('incorrect separator line')\n return None\n elif len(line) != width:\n print('inconsistent line widths')\n return None\n elif line[0] != '|' or line[width-1] != '|':\n print(\"non-separator lines must begin and end with '|'\") \n return None\n \n return lines\n\n\"\"\"\n\nresults is list of lists like:\n\n[[name, bits, start, end],...\n\n\"\"\"\n\ndef decode(lines):\n print(\"Name Bits Start End\")\n print(\"======= ==== ===== ===\")\n \n startbit = 0\n \n results = []\n \n for line in lines:\n infield=False\n for c in line:\n if not infield and c == '|':\n infield = True\n spaces = 0\n name = ''\n elif infield:\n if c == ' ':\n spaces += 1\n elif c != '|':\n name += c\n else:\n bits = (spaces + len(name) + 1) // 3\n endbit = startbit + bits - 1\n print('{0:7} {1:2d} {2:2d} {3:2d}'.format(name, bits, startbit, endbit))\n reslist = [name, bits, startbit, endbit]\n results.append(reslist)\n spaces = 0\n name = ''\n startbit += bits\n \n return results\n \ndef unpack(results, hex):\n print(\"\\nTest string in hex:\")\n print(hex)\n print(\"\\nTest string in binary:\")\n bin = f'{int(hex, 16):0>{4*len(hex)}b}'\n print(bin)\n print(\"\\nUnpacked:\\n\")\n print(\"Name Size Bit pattern\")\n print(\"======= ==== ================\")\n for r in results:\n name = r[0]\n size = r[1]\n startbit = r[2]\n endbit = r[3]\n bitpattern = bin[startbit:endbit+1]\n print('{0:7} {1:2d} {2:16}'.format(name, size, bitpattern))\n\n\ndiagram = \"\"\"\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\n\"\"\"\n\nlines = validate(diagram)\n\nif lines == None:\n print(\"No lines returned\")\nelse:\n print(\" \")\n print(\"Diagram after trimming whitespace and removal of blank lines:\")\n print(\" \")\n for line in lines:\n print(line)\n \n print(\" \")\n print(\"Decoded:\")\n print(\" \")\n\n results = decode(lines) \n \n # test string\n \n hex = \"78477bbf5496e12e1bf169a4\" \n \n unpack(results, hex)\n"} +{"title": "AVL tree", "language": "Python", "task": "[[Category:Data Structures]]\n\n\nIn computer science, an '''AVL tree''' is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; at no time do they differ by more than one because rebalancing is done ensure this is the case. Lookup, insertion, and deletion all take O(log ''n'') time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more tree rotations. Note the tree of nodes comprise a set, so duplicate node keys are not allowed.\n\nAVL trees are often compared with red-black trees because they support the same set of operations and because red-black trees also take O(log ''n'') time for the basic operations. Because AVL trees are more rigidly balanced, they are faster than red-black trees for lookup-intensive applications. Similar to red-black trees, AVL trees are height-balanced, but in general not weight-balanced nor \u03bc-balanced; that is, sibling nodes can have hugely differing numbers of descendants.\n\n\n;Task:\nImplement an AVL tree in the language of choice, and provide at least basic operations.\n\n;Related task\n[[Red_black_tree_sort]]\n\n", "solution": "\n# Module: calculus.py\n\nimport enum\n\nclass entry_not_found(Exception):\n \"\"\"Raised when an entry is not found in a collection\"\"\"\n pass\n\nclass entry_already_exists(Exception):\n \"\"\"Raised when an entry already exists in a collection\"\"\"\n pass\n\nclass state(enum.Enum):\n header = 0\n left_high = 1\n right_high = 2\n balanced = 3\n\nclass direction(enum.Enum):\n from_left = 0\n from_right = 1\n\nfrom abc import ABC, abstractmethod\n\nclass comparer(ABC):\n\n @abstractmethod\n def compare(self,t):\n pass\n\nclass node(comparer):\n \n def __init__(self):\n self.parent = None\n self.left = self\n self.right = self\n self.balance = state.header\n\n def compare(self,t):\n if self.key < t:\n return -1\n elif t < self.key:\n return 1\n else:\n return 0\n\n def is_header(self):\n return self.balance == state.header\n\n def length(self):\n if self != None:\n if self.left != None:\n left = self.left.length()\n else:\n left = 0\n if self.right != None: \n right = self.right.length()\n else:\n right = 0\n \n return left + right + 1\n else:\n return 0\n \n def rotate_left(self):\n _parent = self.parent\n x = self.right\n self.parent = x\n x.parent = _parent\n if x.left is not None:\n x.left.parent = self\n self.right = x.left\n x.left = self\n return x\n \n \n def rotate_right(self):\n _parent = self.parent\n x = self.left\n self.parent = x\n x.parent = _parent;\n if x.right is not None:\n x.right.parent = self\n self.left = x.right\n x.right = self\n return x\n\n def balance_left(self):\n \n _left = self.left\n\n if _left is None:\n return self;\n \n if _left.balance == state.left_high:\n self.balance = state.balanced\n _left.balance = state.balanced\n self = self.rotate_right()\n elif _left.balance == state.right_high: \n subright = _left.right\n if subright.balance == state.balanced:\n self.balance = state.balanced\n _left.balance = state.balanced\n elif subright.balance == state.right_high:\n self.balance = state.balanced\n _left.balance = state.left_high\n elif subright.balance == left_high:\n root.balance = state.right_high\n _left.balance = state.balanced\n subright.balance = state.balanced\n _left = _left.rotate_left()\n self.left = _left\n self = self.rotate_right()\n elif _left.balance == state.balanced:\n self.balance = state.left_high\n _left.balance = state.right_high\n self = self.rotate_right()\n return self;\n \n def balance_right(self):\n\n _right = self.right\n\n if _right is None:\n return self;\n \n if _right.balance == state.right_high:\n self.balance = state.balanced\n _right.balance = state.balanced\n self = self.rotate_left()\n elif _right.balance == state.left_high:\n subleft = _right.left;\n if subleft.balance == state.balanced:\n self.balance = state.balanced\n _right.balance = state.balanced\n elif subleft.balance == state.left_high:\n self.balance = state.balanced\n _right.balance = state.right_high\n elif subleft.balance == state.right_high:\n self.balance = state.left_high\n _right.balance = state.balanced\n subleft.balance = state.balanced\n _right = _right.rotate_right()\n self.right = _right\n self = self.rotate_left()\n elif _right.balance == state.balanced:\n self.balance = state.right_high\n _right.balance = state.left_high\n self = self.rotate_left()\n return self\n\n\n def balance_tree(self, direct):\n taller = True\n while taller:\n _parent = self.parent;\n if _parent.left == self:\n next_from = direction.from_left\n else:\n next_from = direction.from_right;\n\n if direct == direction.from_left:\n if self.balance == state.left_high:\n if _parent.is_header():\n _parent.parent = _parent.parent.balance_left()\n elif _parent.left == self:\n _parent.left = _parent.left.balance_left()\n else:\n _parent.right = _parent.right.balance_left()\n taller = False\n \n elif self.balance == state.balanced:\n self.balance = state.left_high\n taller = True\n \n elif self.balance == state.right_high:\n self.balance = state.balanced\n taller = False\n else:\n if self.balance == state.left_high:\n self.balance = state.balanced\n taller = False\n \n elif self.balance == state.balanced:\n self.balance = state.right_high\n taller = True\n \n elif self.balance == state.right_high:\n if _parent.is_header():\n _parent.parent = _parent.parent.balance_right()\n elif _parent.left == self:\n _parent.left = _parent.left.balance_right()\n else:\n _parent.right = _parent.right.balance_right()\n taller = False\n \n if taller:\n if _parent.is_header():\n taller = False\n else:\n self = _parent\n direct = next_from\n\n def balance_tree_remove(self, _from):\n \n if self.is_header():\n return;\n\n shorter = True;\n\n while shorter:\n _parent = self.parent;\n if _parent.left == self:\n next_from = direction.from_left\n else:\n next_from = direction.from_right\n\n if _from == direction.from_left:\n if self.balance == state.left_high:\n shorter = True\n \n elif self.balance == state.balanced:\n self.balance = state.right_high;\n shorter = False\n \n elif self.balance == state.right_high:\n if self.right is not None:\n if self.right.balance == state.balanced:\n shorter = False\n else:\n shorter = True\n else:\n shorter = False;\n\n if _parent.is_header():\n _parent.parent = _parent.parent.balance_right()\n elif _parent.left == self:\n _parent.left = _parent.left.balance_right();\n else:\n _parent.right = _parent.right.balance_right()\n \n else:\n if self.balance == state.right_high:\n self.balance = state.balanced\n shorter = True\n \n elif self.balance == state.balanced:\n self.balance = state.left_high\n shorter = False\n \n elif self.balance == state.left_high:\n\n if self.left is not None:\n if self.left.balance == state.balanced:\n shorter = False\n else:\n shorter = True\n else:\n short = False;\n\n if _parent.is_header():\n _parent.parent = _parent.parent.balance_left();\n elif _parent.left == self:\n _parent.left = _parent.left.balance_left();\n else:\n _parent.right = _parent.right.balance_left();\n \n if shorter:\n if _parent.is_header():\n shorter = False\n else: \n _from = next_from\n self = _parent\n\n def previous(self):\n if self.is_header():\n return self.right\n\n if self.left is not None:\n y = self.left\n while y.right is not None:\n y = y.right\n return y\n \n else: \n y = self.parent;\n if y.is_header():\n return y\n\n x = self\n while x == y.left:\n x = y\n y = y.parent\n\n return y\n \n def next(self):\n if self.is_header():\n return self.left\n\n if self.right is not None:\n y = self.right\n while y.left is not None:\n y = y.left\n return y;\n \n else:\n y = self.parent\n if y.is_header():\n return y\n\n x = self; \n while x == y.right:\n x = y\n y = y.parent;\n \n return y\n\n def swap_nodes(a, b):\n \n if b == a.left:\n if b.left is not None:\n b.left.parent = a\n\n if b.right is not None:\n b.right.parent = a\n\n if a.right is not None:\n a.right.parent = b\n\n if not a.parent.is_header():\n if a.parent.left == a:\n a.parent.left = b\n else:\n a.parent.right = b;\n else:\n a.parent.parent = b\n\n b.parent = a.parent\n a.parent = b\n\n a.left = b.left\n b.left = a\n\n temp = a.right\n a.right = b.right\n b.right = temp\n elif b == a.right:\n if b.right is not None:\n b.right.parent = a\n \n if b.left is not None:\n b.left.parent = a\n\n if a.left is not None:\n a.left.parent = b\n\n if not a.parent.is_header(): \n if a.parent.left == a:\n a.parent.left = b\n else:\n a.parent.right = b\n else:\n a.parent.parent = b\n\n b.parent = a.parent\n a.parent = b\n\n a.right = b.right\n b.right = a\n\n temp = a.left\n a.left = b.left\n b.left = temp\n elif a == b.left:\n if a.left is not None:\n a.left.parent = b\n \n if a.right is not None:\n a.right.parent = b\n\n if b.right is not None:\n b.right.parent = a\n\n if not parent.is_header(): \n if b.parent.left == b:\n b.parent.left = a\n else:\n b.parent.right = a\n else:\n b.parent.parent = a\n\n a.parent = b.parent\n b.parent = a\n\n b.left = a.left\n a.left = b\n\n temp = a.right\n a.right = b.right\n b.right = temp\n elif a == b.right:\n if a.right is not None:\n a.right.parent = b\n if a.left is not None:\n a.left.parent = b\n\n if b.left is not None:\n b.left.parent = a\n\n if not b.parent.is_header():\n if b.parent.left == b:\n b.parent.left = a\n else:\n b.parent.right = a\n else:\n b.parent.parent = a\n\n a.parent = b.parent\n b.parent = a\n\n b.right = a.right\n a.right = b\n\n temp = a.left\n a.left = b.left\n b.left = temp\n else:\n if a.parent == b.parent:\n temp = a.parent.left\n a.parent.left = a.parent.right\n a.parent.right = temp\n else:\n if not a.parent.is_header():\n if a.parent.left == a:\n a.parent.left = b\n else:\n a.parent.right = b\n else:\n a.parent.parent = b\n\n if not b.parent.is_header():\n if b.parent.left == b:\n b.parent.left = a\n else:\n b.parent.right = a\n else:\n b.parent.parent = a\n \n if b.left is not None:\n b.left.parent = a\n \n if b.right is not None:\n b.right.parent = a\n\n if a.left is not None:\n a.left.parent = b\n \n if a.right is not None:\n a.right.parent = b\n\n temp1 = a.left\n a.left = b.left\n b.left = temp1\n\n temp2 = a.right\n a.right = b.right\n b.right = temp2\n\n temp3 = a.parent\n a.parent = b.parent\n b.parent = temp3\n \n balance = a.balance\n a.balance = b.balance\n b.balance = balance\n \nclass parent_node(node):\n\n def __init__(self, parent):\n self.parent = parent\n self.left = None\n self.right = None\n self.balance = state.balanced\n\nclass set_node(node):\n\n def __init__(self, parent, key):\n self.parent = parent\n self.left = None\n self.right = None\n self.balance = state.balanced\n self.key = key\n\nclass ordered_set:\n \n def __init__(self):\n self.header = node()\n\n def __iter__(self):\n self.node = self.header\n return self\n \n def __next__(self):\n self.node = self.node.next()\n if self.node.is_header():\n raise StopIteration\n return self.node.key\n\n def __delitem__(self, key):\n self.remove(key)\n\n def __lt__(self, other):\n first1 = self.header.left\n last1 = self.header\n first2 = other.header.left\n last2 = other.header\n\n while (first1 != last1) and (first2 != last2):\n l = first1.key < first2.key\n if not l: \n first1 = first1.next();\n first2 = first2.next();\n else:\n return True;\n \n a = self.__len__()\n b = other.__len__()\n return a < b\n\n def __hash__(self):\n h = 0\n for i in self:\n h = h + i.__hash__()\n return h \n\n def __eq__(self, other):\n if self < other:\n return False\n if other < self:\n return False\n return True\n \n def __ne__(self, other):\n if self < other:\n return True\n if other < self:\n return True\n return False\n\n def __len__(self):\n return self.header.parent.length()\n\n def __getitem__(self, key):\n return self.contains(key)\n\n def __str__(self):\n l = self.header.right\n s = \"{\"\n i = self.header.left\n h = self.header\n while i != h:\n s = s + i.key.__str__()\n if i != l:\n s = s + \",\"\n i = i.next()\n\n s = s + \"}\"\n return s\n\n def __or__(self, other):\n r = ordered_set()\n \n first1 = self.header.left\n last1 = self.header\n first2 = other.header.left\n last2 = other.header\n \n while first1 != last1 and first2 != last2:\n les = first1.key < first2.key\n graater = first2.key < first1.key\n\n if les:\n r.add(first1.key)\n first1 = first1.next()\n elif graater:\n r.add(first2.key)\n first2 = first2.next()\n else:\n r.add(first1.key)\n first1 = first1.next()\n first2 = first2.next()\n \n while first1 != last1:\n r.add(first1.key)\n first1 = first1.next()\n \n while first2 != last2:\n r.add(first2.key)\n first2 = first2.next()\n\n return r\n\n def __and__(self, other):\n r = ordered_set()\n \n first1 = self.header.left\n last1 = self.header\n first2 = other.header.left\n last2 = other.header\n \n while first1 != last1 and first2 != last2:\n les = first1.key < first2.key\n graater = first2.key < first1.key\n\n if les:\n first1 = first1.next()\n elif graater:\n first2 = first2.next()\n else:\n r.add(first1.key)\n first1 = first1.next()\n first2 = first2.next()\n \n return r\n\n def __xor__(self, other):\n r = ordered_set()\n \n first1 = self.header.left\n last1 = self.header\n first2 = other.header.left\n last2 = other.header\n \n while first1 != last1 and first2 != last2:\n les = first1.key < first2.key\n graater = first2.key < first1.key\n\n if les:\n r.add(first1.key)\n first1 = first1.next()\n elif graater:\n r.add(first2.key)\n first2 = first2.next()\n else:\n first1 = first1.next()\n first2 = first2.next()\n \n while first1 != last1:\n r.add(first1.key)\n first1 = first1.next()\n \n while first2 != last2:\n r.add(first2.key)\n first2 = first2.next()\n\n return r\n\n\n def __sub__(self, other):\n r = ordered_set()\n \n first1 = self.header.left\n last1 = self.header\n first2 = other.header.left\n last2 = other.header\n \n while first1 != last1 and first2 != last2:\n les = first1.key < first2.key\n graater = first2.key < first1.key\n\n if les:\n r.add(first1.key)\n first1 = first1.next()\n elif graater:\n r.add(first2.key)\n first2 = first2.next()\n else:\n first1 = first1.next()\n first2 = first2.next()\n \n while first1 != last1:\n r.add(first1.key)\n first1 = first1.next()\n\n return r\n \n def __lshift__(self, data):\n self.add(data)\n return self\n\n def __rshift__(self, data):\n self.remove(data)\n return self\n\n def is_subset(self, other):\n first1 = self.header.left\n last1 = self.header\n first2 = other.header.left\n last2 = other.header\n\n is_subet = True\n\n while first1 != last1 and first2 != last2:\n if first1.key < first2.key:\n is_subset = False\n break\n elif first2.key < first1.key:\n first2 = first2.next()\n else:\n first1 = first1.next()\n first2 = first2.next()\n \n if is_subet:\n if first1 != last1:\n is_subet = False\n \n return is_subet\n\n def is_superset(self,other):\n return other.is_subset(self)\n \n def add(self, data):\n if self.header.parent is None:\n self.header.parent = set_node(self.header,data)\n self.header.left = self.header.parent\n self.header.right = self.header.parent\n else:\n \n root = self.header.parent\n\n while True:\n c = root.compare(data)\n if c >= 0:\n if root.left is not None:\n root = root.left\n else:\n new_node = set_node(root,data)\n root.left = new_node\n \n if self.header.left == root:\n self.header.left = new_node\n root.balance_tree(direction.from_left)\n return\n \n else:\n if root.right is not None:\n root = root.right\n else:\n new_node = set_node(root, data)\n root.right = new_node\n if self.header.right == root:\n self.header.right = new_node\n root.balance_tree(direction.from_right)\n return\n \n def remove(self,data):\n root = self.header.parent;\n\n while True:\n if root is None:\n raise entry_not_found(\"Entry not found in collection\")\n \n c = root.compare(data)\n\n if c < 0:\n root = root.left;\n\n elif c > 0:\n root = root.right;\n\n else:\n \n if root.left is not None:\n if root.right is not None: \n replace = root.left\n while replace.right is not None:\n replace = replace.right\n root.swap_nodes(replace)\n \n _parent = root.parent\n\n if _parent.left == root:\n _from = direction.from_left\n else:\n _from = direction.from_right\n\n if self.header.left == root:\n \n n = root.next();\n \n if n.is_header():\n self.header.left = self.header\n self.header.right = self.header\n else:\n self.header.left = n\n elif self.header.right == root: \n\n p = root.previous();\n\n if p.is_header():\n self.header.left = self.header\n self.header.right = self.header\n else:\n self.header.right = p\n\n if root.left is None:\n if _parent == self.header:\n self.header.parent = root.right\n elif _parent.left == root:\n _parent.left = root.right\n else:\n _parent.right = root.right\n\n if root.right is not None:\n root.right.parent = _parent\n \n else:\n if _parent == self.header:\n self.header.parent = root.left\n elif _parent.left == root:\n _parent.left = root.left\n else:\n _parent.right = root.left\n\n if root.left is not None:\n root.left.parent = _parent;\n\n\n _parent.balance_tree_remove(_from)\n return \n\n def contains(self,data):\n root = self.header.parent;\n\n while True:\n if root == None:\n return False\n\n c = root.compare(data);\n\n if c > 0:\n root = root.left;\n\n elif c < 0:\n root = root.right;\n\n else:\n \n return True \n\n \n def find(self,data):\n root = self.header.parent;\n\n while True:\n if root == None:\n raise entry_not_found(\"An entry is not found in a collection\")\n\n c = root.compare(data);\n\n if c > 0:\n root = root.left;\n\n elif c < 0:\n root = root.right;\n\n else:\n \n return root.key; \n \nclass key_value(comparer):\n\n def __init__(self, key, value):\n self.key = key\n self.value = value\n\n def compare(self,kv):\n if self.key < kv.key:\n return -1\n elif kv.key < self.key:\n return 1\n else:\n return 0\n\n def __lt__(self, other):\n return self.key < other.key\n\n def __str__(self):\n return '(' + self.key.__str__() + ',' + self.value.__str__() + ')'\n\n def __eq__(self, other):\n return self.key == other.key\n\n def __hash__(self):\n return hash(self.key)\n \n\nclass dictionary:\n\n def __init__(self):\n self.set = ordered_set()\n return None\n\n def __lt__(self, other):\n if self.keys() < other.keys():\n return true\n\n if other.keys() < self.keys():\n return false\n \n first1 = self.set.header.left\n last1 = self.set.header\n first2 = other.set.header.left\n last2 = other.set.header\n\n while (first1 != last1) and (first2 != last2):\n l = first1.key.value < first2.key.value\n if not l: \n first1 = first1.next();\n first2 = first2.next();\n else:\n return True;\n \n a = self.__len__()\n b = other.__len__()\n return a < b\n\n\n def add(self, key, value):\n try:\n self.set.remove(key_value(key,None))\n except entry_not_found:\n pass \n self.set.add(key_value(key,value))\n return\n\n def remove(self, key):\n self.set.remove(key_value(key,None))\n return\n\n def clear(self):\n self.set.header = node()\n\n def sort(self):\n \n sort_bag = bag()\n for e in self:\n sort_bag.add(e.value)\n keys_set = self.keys()\n self.clear()\n i = sort_bag.__iter__()\n i = sort_bag.__next__()\n try:\n for e in keys_set:\n self.add(e,i)\n i = sort_bag.__next__()\n except:\n return \n\n def keys(self):\n keys_set = ordered_set()\n for e in self:\n keys_set.add(e.key)\n return keys_set \n \n def __len__(self):\n return self.set.header.parent.length()\n\n def __str__(self):\n l = self.set.header.right;\n s = \"{\"\n i = self.set.header.left;\n h = self.set.header;\n while i != h:\n s = s + \"(\"\n s = s + i.key.key.__str__()\n s = s + \",\"\n s = s + i.key.value.__str__()\n s = s + \")\"\n if i != l:\n s = s + \",\"\n i = i.next()\n\n s = s + \"}\"\n return s;\n\n def __iter__(self):\n \n self.set.node = self.set.header\n return self\n \n def __next__(self):\n self.set.node = self.set.node.next()\n if self.set.node.is_header():\n raise StopIteration\n return key_value(self.set.node.key.key,self.set.node.key.value)\n\n def __getitem__(self, key):\n kv = self.set.find(key_value(key,None))\n return kv.value\n\n def __setitem__(self, key, value):\n self.add(key,value)\n return\n\n def __delitem__(self, key):\n self.set.remove(key_value(key,None))\n\n\nclass array:\n\n def __init__(self):\n self.dictionary = dictionary()\n return None\n \n def __len__(self):\n return self.dictionary.__len__()\n\n def push(self, value):\n k = self.dictionary.set.header.right\n if k == self.dictionary.set.header:\n self.dictionary.add(0,value)\n else:\n self.dictionary.add(k.key.key+1,value)\n return\n\n def pop(self):\n if self.dictionary.set.header.parent != None:\n data = self.dictionary.set.header.right.key.value\n self.remove(self.dictionary.set.header.right.key.key)\n return data\n\n def add(self, key, value):\n try:\n self.dictionary.remove(key)\n except entry_not_found:\n pass\n self.dictionary.add(key,value) \n return\n\n def remove(self, key):\n self.dictionary.remove(key)\n return\n\n def sort(self):\n self.dictionary.sort()\n\n def clear(self):\n self.dictionary.header = node();\n \n\n def __iter__(self):\n self.dictionary.node = self.dictionary.set.header\n return self\n \n def __next__(self):\n self.dictionary.node = self.dictionary.node.next()\n if self.dictionary.node.is_header():\n raise StopIteration\n return self.dictionary.node.key.value\n\n def __getitem__(self, key):\n kv = self.dictionary.set.find(key_value(key,None))\n return kv.value\n\n def __setitem__(self, key, value):\n self.add(key,value)\n return\n\n def __delitem__(self, key):\n self.dictionary.remove(key)\n\n def __lshift__(self, data):\n self.push(data)\n return self\n\n def __lt__(self, other):\n return self.dictionary < other.dictionary\n \n def __str__(self):\n l = self.dictionary.set.header.right;\n s = \"{\"\n i = self.dictionary.set.header.left;\n h = self.dictionary.set.header;\n while i != h:\n s = s + i.key.value.__str__()\n if i != l:\n s = s + \",\"\n i = i.next()\n\n s = s + \"}\"\n return s;\n \n\nclass bag:\n \n def __init__(self):\n self.header = node()\n \n def __iter__(self):\n self.node = self.header\n return self\n\n def __delitem__(self, key):\n self.remove(key)\n \n def __next__(self):\n self.node = self.node.next()\n if self.node.is_header():\n raise StopIteration\n return self.node.key\n\n def __str__(self):\n l = self.header.right;\n s = \"(\"\n i = self.header.left;\n h = self.header;\n while i != h:\n s = s + i.key.__str__()\n if i != l:\n s = s + \",\"\n i = i.next()\n\n s = s + \")\"\n return s;\n\n def __len__(self):\n return self.header.parent.length()\n\n def __lshift__(self, data):\n self.add(data)\n return self\n\n def add(self, data):\n if self.header.parent is None:\n self.header.parent = set_node(self.header,data)\n self.header.left = self.header.parent\n self.header.right = self.header.parent\n else:\n \n root = self.header.parent\n\n while True:\n c = root.compare(data)\n if c >= 0:\n if root.left is not None:\n root = root.left\n else:\n new_node = set_node(root,data)\n root.left = new_node\n \n if self.header.left == root:\n self.header.left = new_node\n\n root.balance_tree(direction.from_left)\n return\n \n else:\n if root.right is not None:\n root = root.right\n else:\n new_node = set_node(root, data)\n root.right = new_node\n\n if self.header.right == root:\n self.header.right = new_node\n\n root.balance_tree(direction.from_right)\n return\n \n def remove_first(self,data):\n \n root = self.header.parent;\n\n while True:\n if root is None:\n return False;\n\n c = root.compare(data);\n\n if c > 0:\n root = root.left;\n\n elif c < 0:\n root = root.right;\n\n else:\n \n if root.left is not None:\n if root.right is not None: \n replace = root.left;\n while replace.right is not None:\n replace = replace.right;\n root.swap_nodes(replace);\n \n _parent = root.parent\n\n if _parent.left == root:\n _from = direction.from_left\n else:\n _from = direction.from_right\n\n if self.header.left == root:\n \n n = root.next();\n \n if n.is_header():\n self.header.left = self.header\n self.header.right = self.header\n else:\n self.header.left = n;\n elif self.header.right == root: \n\n p = root.previous();\n\n if p.is_header():\n self.header.left = self.header\n self.header.right = self.header\n else:\n self.header.right = p\n\n if root.left is None:\n if _parent == self.header:\n self.header.parent = root.right\n elif _parent.left == root:\n _parent.left = root.right\n else:\n _parent.right = root.right\n\n if root.right is not None:\n root.right.parent = _parent\n \n else:\n if _parent == self.header:\n self.header.parent = root.left\n elif _parent.left == root:\n _parent.left = root.left\n else:\n _parent.right = root.left\n\n if root.left is not None:\n root.left.parent = _parent;\n\n\n _parent.balance_tree_remove(_from)\n return True;\n\n def remove(self,data):\n success = self.remove_first(data)\n while success:\n success = self.remove_first(data)\n\n def remove_node(self, root):\n \n if root.left != None and root.right != None:\n replace = root.left\n while replace.right != None:\n replace = replace.right\n root.swap_nodes(replace)\n\n parent = root.parent;\n\n if parent.left == root:\n next_from = direction.from_left\n else:\n next_from = direction.from_right\n\n if self.header.left == root:\n n = root.next()\n\n if n.is_header():\n self.header.left = self.header;\n self.header.right = self.header\n else:\n self.header.left = n\n elif self.header.right == root:\n p = root.previous()\n\n if p.is_header(): \n root.header.left = root.header\n root.header.right = header\n else:\n self.header.right = p\n\n if root.left == None:\n if parent == self.header:\n self.header.parent = root.right\n elif parent.left == root:\n parent.left = root.right\n else:\n parent.right = root.right\n\n if root.right != None:\n root.right.parent = parent\n else:\n if parent == self.header:\n self.header.parent = root.left\n elif parent.left == root:\n parent.left = root.left\n else:\n parent.right = root.left\n\n if root.left != None:\n root.left.parent = parent;\n\n parent.balance_tree_remove(next_from)\n \n def remove_at(self, data, ophset):\n \n p = self.search(data);\n\n if p == None:\n return\n else:\n lower = p\n after = after(data)\n \n s = 0\n while True:\n if ophset == s:\n remove_node(lower);\n return;\n lower = lower.next_node()\n if after == lower:\n break\n s = s+1\n \n return\n\n def search(self, key):\n s = before(key)\n s.next()\n if s.is_header():\n return None\n c = s.compare(s.key)\n if c != 0:\n return None\n return s\n \n \n def before(self, data):\n y = self.header;\n x = self.header.parent;\n\n while x != None:\n if x.compare(data) >= 0:\n x = x.left;\n else:\n y = x;\n x = x.right;\n return y\n \n def after(self, data):\n y = self.header;\n x = self.header.parent;\n\n while x != None:\n if x.compare(data) > 0:\n y = x\n x = x.left\n else:\n x = x.right\n\n return y;\n \n \n def find(self,data):\n root = self.header.parent;\n\n results = array()\n \n while True:\n if root is None:\n break;\n\n p = self.before(data)\n p = p.next()\n if not p.is_header():\n i = p\n l = self.after(data)\n while i != l:\n results.push(i.key)\n i = i.next()\n \n return results\n else:\n break;\n \n return results\n \nclass bag_dictionary:\n\n def __init__(self):\n self.bag = bag()\n return None\n\n def add(self, key, value):\n self.bag.add(key_value(key,value))\n return\n\n def remove(self, key):\n self.bag.remove(key_value(key,None))\n return\n\n def remove_at(self, key, index):\n self.bag.remove_at(key_value(key,None), index)\n return\n\n def clear(self):\n self.bag.header = node()\n\n def __len__(self):\n return self.bag.header.parent.length()\n\n def __str__(self):\n l = self.bag.header.right;\n s = \"{\"\n i = self.bag.header.left;\n h = self.bag.header;\n while i != h:\n s = s + \"(\"\n s = s + i.key.key.__str__()\n s = s + \",\"\n s = s + i.key.value.__str__()\n s = s + \")\"\n if i != l:\n s = s + \",\"\n i = i.next()\n\n s = s + \"}\"\n return s;\n\n def __iter__(self):\n \n self.bag.node = self.bag.header\n return self\n \n def __next__(self):\n self.bag.node = self.bag.node.next()\n if self.bag.node.is_header():\n raise StopIteration\n return key_value(self.bag.node.key.key,self.bag.node.key.value)\n\n def __getitem__(self, key):\n kv_array = self.bag.find(key_value(key,None))\n return kv_array\n\n def __setitem__(self, key, value):\n self.add(key,value)\n return\n\n def __delitem__(self, key):\n self.bag.remove(key_value(key,None))\n\nclass unordered_set:\n\n def __init__(self):\n self.bag_dictionary = bag_dictionary()\n\n def __len__(self):\n return self.bag_dictionary.__len__()\n\n def __hash__(self):\n h = 0\n for i in self:\n h = h + i.__hash__()\n return h \n\n def __eq__(self, other):\n for t in self:\n if not other.contains(t):\n return False\n for u in other:\n if self.contains(u):\n return False\n return true;\n\n def __ne__(self, other):\n return not self == other\n \n def __or__(self, other):\n r = unordered_set()\n \n for t in self:\n r.add(t);\n \n for u in other:\n if not self.contains(u):\n r.add(u);\n\n return r\n\n def __and__(self, other):\n r = unordered_set()\n \n for t in self:\n if other.contains(t):\n r.add(t)\n \n for u in other:\n if self.contains(u) and not r.contains(u):\n r.add(u);\n \n return r\n\n def __xor__(self, other):\n r = unordered_set()\n \n for t in self:\n if not other.contains(t):\n r.add(t)\n \n for u in other:\n if not self.contains(u) and not r.contains(u):\n r.add(u)\n \n return r\n\n\n def __sub__(self, other):\n r = ordered_set()\n \n for t in self:\n if not other.contains(t):\n r.add(t);\n \n return r\n \n def __lshift__(self, data):\n self.add(data)\n return self\n\n def __rshift__(self, data):\n self.remove(data)\n return self\n\n def __getitem__(self, key):\n return self.contains(key)\n\n def is_subset(self, other):\n\n is_subet = True\n\n for t in self:\n if not other.contains(t):\n subset = False\n break\n \n return is_subet\n\n def is_superset(self,other):\n return other.is_subset(self)\n\n\n def add(self, value):\n if not self.contains(value):\n self.bag_dictionary.add(hash(value),value)\n else:\n raise entry_already_exists(\"Entry already exists in the unordered set\")\n\n def contains(self, data):\n if self.bag_dictionary.bag.header.parent == None:\n return False;\n else:\n index = hash(data);\n\n _search = self.bag_dictionary.bag.header.parent;\n\n search_index = _search.key.key;\n\n if index < search_index:\n _search = _search.left\n\n elif index > search_index:\n _search = _search.right\n\n if _search == None:\n return False\n\n while _search != None:\n search_index = _search.key.key;\n\n if index < search_index:\n _search = _search.left\n\n elif index > search_index:\n _search = _search.right\n\n else:\n break\n\n if _search == None:\n return False\n\n return self.contains_node(data, _search)\n \n def contains_node(self,data,_node):\n \n previous = _node.previous()\n save = _node\n\n while not previous.is_header() and previous.key.key == _node.key.key:\n save = previous;\n previous = previous.previous()\n \n c = _node.key.value\n _node = save\n if c == data:\n return True\n\n next = _node.next()\n while not next.is_header() and next.key.key == _node.key.key:\n _node = next\n c = _node.key.value\n if c == data:\n return True;\n next = _node.next()\n \n return False;\n \n def find(self,data,_node):\n \n previous = _node.previous()\n save = _node\n\n while not previous.is_header() and previous.key.key == _node.key.key:\n save = previous;\n previous = previous.previous();\n \n _node = save;\n c = _node.key.value\n if c == data:\n return _node\n\n next = _node.next()\n while not next.is_header() and next.key.key == _node.key.key:\n _node = next\n c = _node.data.value\n if c == data:\n return _node\n next = _node.next()\n \n return None\n \n def search(self, data):\n if self.bag_dictionary.bag.header.parent == None:\n return None\n else:\n index = hash(data)\n\n _search = self.bag_dictionary.bag.header.parent\n\n c = _search.key.key\n\n if index < c:\n _search = _search.left;\n\n elif index > c:\n _search = _search.right;\n\n while _search != None:\n\n if index != c:\n break\n \n c = _search.key.key\n\n if index < c:\n _search = _search.left;\n\n elif index > c:\n _search = _search.right;\n\n else:\n break\n\n if _search == None:\n return None\n\n return self.find(data, _search)\n\n def remove(self,data):\n found = self.search(data);\n if found != None:\n self.bag_dictionary.bag.remove_node(found);\n else:\n raise entry_not_found(\"Entry not found in the unordered set\")\n \n def clear(self):\n self.bag_dictionary.bag.header = node()\n\n def __str__(self):\n l = self.bag_dictionary.bag.header.right;\n s = \"{\"\n i = self.bag_dictionary.bag.header.left;\n h = self.bag_dictionary.bag.header;\n while i != h:\n s = s + i.key.value.__str__()\n if i != l:\n s = s + \",\"\n i = i.next()\n\n s = s + \"}\"\n return s;\n\n def __iter__(self):\n \n self.bag_dictionary.bag.node = self.bag_dictionary.bag.header\n return self\n \n def __next__(self):\n self.bag_dictionary.bag.node = self.bag_dictionary.bag.node.next()\n if self.bag_dictionary.bag.node.is_header():\n raise StopIteration\n return self.bag_dictionary.bag.node.key.value\n\n\nclass map:\n\n def __init__(self):\n self.set = unordered_set()\n return None\n\n def __len__(self):\n return self.set.__len__()\n\n def add(self, key, value):\n try:\n self.set.remove(key_value(key,None))\n except entry_not_found:\n pass \n self.set.add(key_value(key,value))\n return\n\n def remove(self, key):\n self.set.remove(key_value(key,None))\n return\n\n def clear(self):\n self.set.clear()\n\n def __str__(self):\n l = self.set.bag_dictionary.bag.header.right;\n s = \"{\"\n i = self.set.bag_dictionary.bag.header.left;\n h = self.set.bag_dictionary.bag.header;\n while i != h:\n s = s + \"(\"\n s = s + i.key.value.key.__str__()\n s = s + \",\"\n s = s + i.key.value.value.__str__()\n s = s + \")\"\n if i != l:\n s = s + \",\"\n i = i.next()\n\n s = s + \"}\"\n return s;\n\n def __iter__(self):\n \n self.set.node = self.set.bag_dictionary.bag.header\n return self\n \n def __next__(self):\n self.set.node = self.set.node.next()\n if self.set.node.is_header():\n raise StopIteration\n return key_value(self.set.node.key.key,self.set.node.key.value)\n\n def __getitem__(self, key):\n kv = self.set.find(key_value(key,None))\n return kv.value\n\n def __setitem__(self, key, value):\n self.add(key,value)\n return\n\n def __delitem__(self, key):\n self.remove(key)\n"} +{"title": "Abbreviations, automatic", "language": "C", "task": "The use of \u00a0 abbreviations \u00a0 (also sometimes called synonyms, nicknames, AKAs, or aliases) \u00a0 can be an\neasy way to add flexibility when specifying or using commands, sub\u2500commands, options, etc.\n\n\n\nIt would make a list of words easier to maintain \u00a0 (as words are added, changed, and/or deleted) \u00a0 if\nthe minimum abbreviation length of that list could be automatically (programmatically) determined.\n\n\nFor this task, use the list (below) of the days-of-the-week names that are expressed in about a hundred languages \u00a0 (note that there is a blank line in the list).\n\nSunday Monday Tuesday Wednesday Thursday Friday Saturday\nSondag Maandag Dinsdag Woensdag Donderdag Vrydag Saterdag\nE_djel\u00eb E_h\u00ebn\u00eb E_mart\u00eb E_m\u00ebrkur\u00eb E_enjte E_premte E_shtun\u00eb\nEhud Segno Maksegno Erob Hamus Arbe Kedame\nAl_Ahad Al_Ithinin Al_Tholatha'a Al_Arbia'a Al_Kamis Al_Gomia'a Al_Sabit\nGuiragui Yergou_shapti Yerek_shapti Tchorek_shapti Hink_shapti Ourpat Shapat\ndomingu llunes martes mi\u00e9rcoles xueves vienres s\u00e1badu\nBazar_g\u00dcn\u00dc Birinci_g\u00dcn \u00c7kinci_g\u00dcn \u00dc\u00e7\u00dcnc\u00dc_g\u00dcn D\u00d6rd\u00dcnc\u00dc_g\u00dcn Bes,inci_g\u00dcn Alt\u00f2nc\u00f2_g\u00dcn\nIgande Astelehen Astearte Asteazken Ostegun Ostiral Larunbat\nRobi_bar Shom_bar Mongal_bar Budhh_bar BRihashpati_bar Shukro_bar Shoni_bar\nNedjelja Ponedeljak Utorak Srijeda Cxetvrtak Petak Subota\nDisul Dilun Dimeurzh Dimerc'her Diriaou Digwener Disadorn\nnedelia ponedelnik vtornik sriada chetvartak petak sabota\nsing_kei_yaht sing_kei_yat sing_kei_yee sing_kei_saam sing_kei_sie sing_kei_ng sing_kei_luk\nDiumenge Dilluns Dimarts Dimecres Dijous Divendres Dissabte\nDzeenkk-eh Dzeehn_kk-ehreh Dzeehn_kk-ehreh_nah_kay_dzeeneh Tah_neesee_dzeehn_neh Deehn_ghee_dzee-neh Tl-oowey_tts-el_dehlee Dzeentt-ahzee\ndy_Sul dy_Lun dy_Meurth dy_Mergher dy_You dy_Gwener dy_Sadorn\nDimanch Lendi Madi M\u00e8kredi Jedi Vandredi Samdi\nnedjelja ponedjeljak utorak srijeda cxetvrtak petak subota\nnede^le ponde^l\u00ed \u00fater\u00ff str^eda c^tvrtek p\u00e1tek sobota\nSondee Mondee Tiisiday Walansedee TOOsedee Feraadee Satadee\ns0ndag mandag tirsdag onsdag torsdag fredag l0rdag\nzondag maandag dinsdag woensdag donderdag vrijdag zaterdag\nDiman^co Lundo Mardo Merkredo ^Ja\u00f9do Vendredo Sabato\np\u00dchap\u00e4ev esmasp\u00e4ev teisip\u00e4ev kolmap\u00e4ev neljap\u00e4ev reede laup\u00e4ev\n\nDiu_prima Diu_sequima Diu_tritima Diu_quartima Diu_quintima Diu_sextima Diu_sabbata\nsunnudagur m\u00e1nadagur t\u00ffsdaguy mikudagur h\u00f3sdagur friggjadagur leygardagur\nYek_Sham'beh Do_Sham'beh Seh_Sham'beh Cha'har_Sham'beh Panj_Sham'beh Jom'eh Sham'beh\nsunnuntai maanantai tiistai keskiviiko torsktai perjantai lauantai\ndimanche lundi mardi mercredi jeudi vendredi samedi\nSnein Moandei Tiisdei Woansdei Tonersdei Freed Sneon\nDomingo Segunda_feira Martes M\u00e9rcores Joves Venres S\u00e1bado\nk'vira orshabati samshabati otkhshabati khutshabati p'arask'evi shabati\nSonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag\nKiriaki' Defte'ra Tri'ti Teta'rti Pe'mpti Paraskebi' Sa'bato\nravivaar somvaar mangalvaar budhvaar guruvaar shukravaar shanivaar\np\u00f3pule p\u00f3`akahi p\u00f3`alua p\u00f3`akolu p\u00f3`ah\u00e1 p\u00f3`alima p\u00f3`aono\nYom_rishon Yom_sheni Yom_shlishi Yom_revi'i Yom_chamishi Yom_shishi Shabat\nravivara somavar mangalavar budhavara brahaspativar shukravara shanivar\nvas\u00e1rnap h\u00e9tf\u00f6 kedd szerda cs\u00fct\u00f6rt\u00f6k p\u00e9ntek szombat\nSunnudagur M\u00e1nudagur \u255eri\u03b4judagur Mi\u03b4vikudagar Fimmtudagur F\u00d6studagur Laugardagur\nsundio lundio mardio merkurdio jovdio venerdio saturdio\nMinggu Senin Selasa Rabu Kamis Jumat Sabtu\nDominica Lunedi Martedi Mercuridi Jovedi Venerdi Sabbato\nD\u00e9_Domhnaigh D\u00e9_Luain D\u00e9_M\u00e1irt D\u00e9_Ceadaoin D\u00e9_ardaoin D\u00e9_hAoine D\u00e9_Sathairn\ndomenica luned\u00ed marted\u00ed mercoled\u00ed gioved\u00ed venerd\u00ed sabato\nNichiyou_bi Getzuyou_bi Kayou_bi Suiyou_bi Mokuyou_bi Kin'you_bi Doyou_bi\nIl-yo-il Wol-yo-il Hwa-yo-il Su-yo-il Mok-yo-il Kum-yo-il To-yo-il\nDies_Dominica Dies_Lun\u00e6 Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni\nsve-tdien pirmdien otrdien tresvdien ceturtdien piektdien sestdien\nSekmadienis Pirmadienis Antradienis Trec^iadienis Ketvirtadienis Penktadienis S^es^tadienis\nWangu Kazooba Walumbe Mukasa Kiwanuka Nnagawonye Wamunyi\nxing-_qi-_r\u00ec xing-_qi-_yi-. xing-_qi-_\u00e8r xing-_qi-_san-. xing-_qi-_s\u00ec xing-_qi-_wuv. xing-_qi-_li\u00f9\nJedoonee Jelune Jemayrt Jecrean Jardaim Jeheiney Jesam\nJabot Manre Juje Wonje Taije Balaire Jarere\ngeminrongo min\u00f2mishi m\u00e1rtes mi\u00e8rkoles misheushi b\u00e8rnashi mish\u00e1baro\nAhad Isnin Selasa Rabu Khamis Jumaat Sabtu\ns\u03c6ndag mandag tirsdag onsdag torsdag fredag l\u03c6rdag\nlo_dimenge lo_diluns lo_dimar\u00e7 lo_dim\u00e8rcres lo_dij\u00f2us lo_divendres lo_dissabte\ndjadomingo djaluna djamars djarason djaweps djabi\u00e8rna djasabra\nNiedziela Poniedzial/ek Wtorek S,roda Czwartek Pia,tek Sobota\nDomingo segunda-feire ter\u00e7a-feire quarta-feire quinta-feire sexta-feira s\u00e5bado\nDomingo Lunes martes Miercoles Jueves Viernes Sabado\nDuminic\u00aa Luni Mart'i Miercuri Joi Vineri S\u00e2mb\u00aat\u00aa\nvoskresenie ponedelnik vtornik sreda chetverg pyatnitsa subbota\nSunday Di-luain Di-m\u00e0irt Di-ciadain Di-ardaoin Di-haoine Di-sathurne\nnedjelja ponedjeljak utorak sreda cxetvrtak petak subota\nSontaha Mmantaha Labobedi Laboraro Labone Labohlano Moqebelo\nIridha- Sandhudha- Anga.haruwa-dha- Badha-dha- Brahaspa.thindha- Sikura-dha- Sena.sura-dha-\nnedel^a pondelok utorok streda s^tvrtok piatok sobota\nNedelja Ponedeljek Torek Sreda Cxetrtek Petek Sobota\ndomingo lunes martes mi\u00e9rcoles jueves viernes s\u00e1bado\nsonde mundey tude-wroko dride-wroko fode-wroko freyda Saturday\nJumapili Jumatatu Jumanne Jumatano Alhamisi Ijumaa Jumamosi\ns\u00f6ndag m\u00e5ndag tisdag onsdag torsdag fredag lordag\nLinggo Lunes Martes Miyerkoles Huwebes Biyernes Sabado\nL\u00e9-p\u00e0i-j\u00edt P\u00e0i-it P\u00e0i-j\u00ef P\u00e0i-sa\u00f1 P\u00e0i-s\u00ec P\u00e0i-g\u00d6. P\u00e0i-l\u00e1k\nwan-ar-tit wan-tjan wan-ang-kaan wan-phoet wan-pha-ru-hat-sa-boh-die wan-sook wan-sao\nTshipi Mosupologo Labobedi Laboraro Labone Labotlhano Matlhatso\nPazar Pazartesi Sali \u00c7ar,samba Per,sembe Cuma Cumartesi\nnedilya ponedilok vivtorok sereda chetver pyatnytsya subota\nChu?_Nh\u00e2.t Th\u00fa*_Hai Th\u00fa*_Ba Th\u00fa*_Tu* Th\u00fa*_Na'm Th\u00fa*_S\u00e1u Th\u00fa*_Ba?y\ndydd_Sul dyds_Llun dydd_Mawrth dyds_Mercher dydd_Iau dydd_Gwener dyds_Sadwrn\nDibeer Altine Talaata Allarba Al_xebes Aljuma Gaaw\niCawa uMvulo uLwesibini uLwesithathu uLuwesine uLwesihlanu uMgqibelo\nzuntik montik dinstik mitvokh donershtik fraytik shabes\niSonto uMsombuluko uLwesibili uLwesithathu uLwesine uLwesihlanu uMgqibelo\nDies_Dominica Dies_Lun\u00e6 Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni\nBazar_g\u00dcn\u00dc Bazar_\u00e6rt\u00e6si \u00c7\u00e6rs,\u00e6nb\u00e6_axs,am\u00f2 \u00c7\u00e6rs,\u00e6nb\u00e6_g\u00dcn\u00dc C\u00dcm\u00e6_axs,am\u00f2 C\u00dcm\u00e6_g\u00dcn\u00dc C\u00dcm\u00e6_Senb\u00e6\nSun Moon Mars Mercury Jove Venus Saturn\nzondag maandag dinsdag woensdag donderdag vrijdag zaterdag\nKoseEraa GyoOraa BenEraa Kuoraa YOwaaraa FeEraa Memenaa\nSonntag Montag Dienstag Mittwoch Donnerstag Freitag Sonnabend\nDomingo Luns Terza_feira Corta_feira Xoves Venres S\u00e1bado\nDies_Solis Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Sabbatum\nxing-_qi-_ti\u00e0n xing-_qi-_yi-. xing-_qi-_\u00e8r xing-_qi-_san-. xing-_qi-_s\u00ec xing-_qi-_wuv. xing-_qi-_li\u00f9\ndjadomingu djaluna djamars djarason djaweps djabi\u00e8rn\u00e8 djasabra\nKillachau Atichau Quoyllurchau Illapachau Chaskachau Kuychichau Intichau\n\n''Caveat: \u00a0 The list (above) most surely contains errors (or, at the least, differences) of what the actual (or true) names for the days-of-the-week.''\n\n\nTo make this Rosetta Code task page as small as possible, if processing the complete list, read the days-of-the-week from a file (that is created from the above list).\n\n\nNotes concerning the above list of words\n::* \u00a0 each line has a list of days-of-the-week for a language, separated by at least one blank\n::* \u00a0 the words on each line happen to be in order, from Sunday \u2500\u2500\u25ba Saturday\n::* \u00a0 most lines have words in mixed case and some have all manner of accented words and other characters\n::* \u00a0 some words were translated to the nearest character that was available to ''code page'' \u00a0 '''437'''\n::* \u00a0 the characters in the words are not restricted except that they may not have imbedded blanks\n::* \u00a0 for this example, the use of an underscore ('''_''') was used to indicate a blank in a word\n\n\n;Task:\n::* \u00a0 The list of words \u00a0 (days of the week) \u00a0 needn't be verified/validated.\n::* \u00a0 Write a function to find the (numeric) minimum length abbreviation for each line that would make abbreviations unique.\n::* \u00a0 A blank line \u00a0 (or a null line) \u00a0 should return a null string.\n::* \u00a0 Process and show the output for at least the first '''five''' lines of the file.\n::* \u00a0 Show all output here.\n\n\n", "solution": "#include \n#include \n#include \n\nvoid process(int lineNum, char buffer[]) {\n char days[7][64];\n int i = 0, d = 0, j = 0;\n\n while (buffer[i] != 0) {\n if (buffer[i] == ' ') {\n days[d][j] = '\\0';\n ++d;\n j = 0;\n } else if (buffer[i] == '\\n' || buffer[i] == '\\r') {\n days[d][j] = '\\0';\n ++d;\n break;\n } else {\n days[d][j] = buffer[i];\n ++j;\n }\n\n if (d >= 7) {\n printf(\"There aren't 7 days in line %d\\n\", lineNum);\n return;\n }\n ++i;\n }\n if (buffer[i] == '\\0') {\n days[d][j] = '\\0';\n ++d;\n }\n\n if (d < 7) {\n printf(\"There aren't 7 days in line %d\\n\", lineNum);\n return;\n } else {\n int len = 0;\n\n for (len = 1; len < 64; ++len) {\n int d1;\n for (d1 = 0; d1 < 7; ++d1) {\n int d2;\n for (d2 = d1 + 1; d2 < 7; ++d2) {\n int unique = 0;\n for (i = 0; i < len; ++i) {\n if (days[d1][i] != days[d2][i]) {\n unique = 1;\n break;\n }\n }\n if (!unique) {\n goto next_length;\n }\n }\n }\n\n // uniqueness found for this length\n printf(\"%2d \", len);\n for (i = 0; i < 7; ++i) {\n printf(\" %s\", days[i]);\n }\n printf(\"\\n\");\n return;\n\n // a duplication was found at the current length\n next_length: {}\n }\n }\n\n printf(\"Failed to find uniqueness within the bounds.\");\n}\n\nint main() {\n char buffer[1024];\n int lineNum = 1, len;\n FILE *fp;\n\n fp = fopen(\"days_of_week.txt\", \"r\");\n while (1) {\n memset(buffer, 0, sizeof(buffer));\n\n fgets(buffer, sizeof(buffer), fp);\n len = strlen(buffer);\n\n if (len == 0 || buffer[len - 1] == '\\0') {\n break;\n }\n\n process(lineNum++, buffer);\n }\n fclose(fp);\n\n return 0;\n}"} +{"title": "Abbreviations, automatic", "language": "JavaScript", "task": "The use of \u00a0 abbreviations \u00a0 (also sometimes called synonyms, nicknames, AKAs, or aliases) \u00a0 can be an\neasy way to add flexibility when specifying or using commands, sub\u2500commands, options, etc.\n\n\n\nIt would make a list of words easier to maintain \u00a0 (as words are added, changed, and/or deleted) \u00a0 if\nthe minimum abbreviation length of that list could be automatically (programmatically) determined.\n\n\nFor this task, use the list (below) of the days-of-the-week names that are expressed in about a hundred languages \u00a0 (note that there is a blank line in the list).\n\nSunday Monday Tuesday Wednesday Thursday Friday Saturday\nSondag Maandag Dinsdag Woensdag Donderdag Vrydag Saterdag\nE_djel\u00eb E_h\u00ebn\u00eb E_mart\u00eb E_m\u00ebrkur\u00eb E_enjte E_premte E_shtun\u00eb\nEhud Segno Maksegno Erob Hamus Arbe Kedame\nAl_Ahad Al_Ithinin Al_Tholatha'a Al_Arbia'a Al_Kamis Al_Gomia'a Al_Sabit\nGuiragui Yergou_shapti Yerek_shapti Tchorek_shapti Hink_shapti Ourpat Shapat\ndomingu llunes martes mi\u00e9rcoles xueves vienres s\u00e1badu\nBazar_g\u00dcn\u00dc Birinci_g\u00dcn \u00c7kinci_g\u00dcn \u00dc\u00e7\u00dcnc\u00dc_g\u00dcn D\u00d6rd\u00dcnc\u00dc_g\u00dcn Bes,inci_g\u00dcn Alt\u00f2nc\u00f2_g\u00dcn\nIgande Astelehen Astearte Asteazken Ostegun Ostiral Larunbat\nRobi_bar Shom_bar Mongal_bar Budhh_bar BRihashpati_bar Shukro_bar Shoni_bar\nNedjelja Ponedeljak Utorak Srijeda Cxetvrtak Petak Subota\nDisul Dilun Dimeurzh Dimerc'her Diriaou Digwener Disadorn\nnedelia ponedelnik vtornik sriada chetvartak petak sabota\nsing_kei_yaht sing_kei_yat sing_kei_yee sing_kei_saam sing_kei_sie sing_kei_ng sing_kei_luk\nDiumenge Dilluns Dimarts Dimecres Dijous Divendres Dissabte\nDzeenkk-eh Dzeehn_kk-ehreh Dzeehn_kk-ehreh_nah_kay_dzeeneh Tah_neesee_dzeehn_neh Deehn_ghee_dzee-neh Tl-oowey_tts-el_dehlee Dzeentt-ahzee\ndy_Sul dy_Lun dy_Meurth dy_Mergher dy_You dy_Gwener dy_Sadorn\nDimanch Lendi Madi M\u00e8kredi Jedi Vandredi Samdi\nnedjelja ponedjeljak utorak srijeda cxetvrtak petak subota\nnede^le ponde^l\u00ed \u00fater\u00ff str^eda c^tvrtek p\u00e1tek sobota\nSondee Mondee Tiisiday Walansedee TOOsedee Feraadee Satadee\ns0ndag mandag tirsdag onsdag torsdag fredag l0rdag\nzondag maandag dinsdag woensdag donderdag vrijdag zaterdag\nDiman^co Lundo Mardo Merkredo ^Ja\u00f9do Vendredo Sabato\np\u00dchap\u00e4ev esmasp\u00e4ev teisip\u00e4ev kolmap\u00e4ev neljap\u00e4ev reede laup\u00e4ev\n\nDiu_prima Diu_sequima Diu_tritima Diu_quartima Diu_quintima Diu_sextima Diu_sabbata\nsunnudagur m\u00e1nadagur t\u00ffsdaguy mikudagur h\u00f3sdagur friggjadagur leygardagur\nYek_Sham'beh Do_Sham'beh Seh_Sham'beh Cha'har_Sham'beh Panj_Sham'beh Jom'eh Sham'beh\nsunnuntai maanantai tiistai keskiviiko torsktai perjantai lauantai\ndimanche lundi mardi mercredi jeudi vendredi samedi\nSnein Moandei Tiisdei Woansdei Tonersdei Freed Sneon\nDomingo Segunda_feira Martes M\u00e9rcores Joves Venres S\u00e1bado\nk'vira orshabati samshabati otkhshabati khutshabati p'arask'evi shabati\nSonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag\nKiriaki' Defte'ra Tri'ti Teta'rti Pe'mpti Paraskebi' Sa'bato\nravivaar somvaar mangalvaar budhvaar guruvaar shukravaar shanivaar\np\u00f3pule p\u00f3`akahi p\u00f3`alua p\u00f3`akolu p\u00f3`ah\u00e1 p\u00f3`alima p\u00f3`aono\nYom_rishon Yom_sheni Yom_shlishi Yom_revi'i Yom_chamishi Yom_shishi Shabat\nravivara somavar mangalavar budhavara brahaspativar shukravara shanivar\nvas\u00e1rnap h\u00e9tf\u00f6 kedd szerda cs\u00fct\u00f6rt\u00f6k p\u00e9ntek szombat\nSunnudagur M\u00e1nudagur \u255eri\u03b4judagur Mi\u03b4vikudagar Fimmtudagur F\u00d6studagur Laugardagur\nsundio lundio mardio merkurdio jovdio venerdio saturdio\nMinggu Senin Selasa Rabu Kamis Jumat Sabtu\nDominica Lunedi Martedi Mercuridi Jovedi Venerdi Sabbato\nD\u00e9_Domhnaigh D\u00e9_Luain D\u00e9_M\u00e1irt D\u00e9_Ceadaoin D\u00e9_ardaoin D\u00e9_hAoine D\u00e9_Sathairn\ndomenica luned\u00ed marted\u00ed mercoled\u00ed gioved\u00ed venerd\u00ed sabato\nNichiyou_bi Getzuyou_bi Kayou_bi Suiyou_bi Mokuyou_bi Kin'you_bi Doyou_bi\nIl-yo-il Wol-yo-il Hwa-yo-il Su-yo-il Mok-yo-il Kum-yo-il To-yo-il\nDies_Dominica Dies_Lun\u00e6 Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni\nsve-tdien pirmdien otrdien tresvdien ceturtdien piektdien sestdien\nSekmadienis Pirmadienis Antradienis Trec^iadienis Ketvirtadienis Penktadienis S^es^tadienis\nWangu Kazooba Walumbe Mukasa Kiwanuka Nnagawonye Wamunyi\nxing-_qi-_r\u00ec xing-_qi-_yi-. xing-_qi-_\u00e8r xing-_qi-_san-. xing-_qi-_s\u00ec xing-_qi-_wuv. xing-_qi-_li\u00f9\nJedoonee Jelune Jemayrt Jecrean Jardaim Jeheiney Jesam\nJabot Manre Juje Wonje Taije Balaire Jarere\ngeminrongo min\u00f2mishi m\u00e1rtes mi\u00e8rkoles misheushi b\u00e8rnashi mish\u00e1baro\nAhad Isnin Selasa Rabu Khamis Jumaat Sabtu\ns\u03c6ndag mandag tirsdag onsdag torsdag fredag l\u03c6rdag\nlo_dimenge lo_diluns lo_dimar\u00e7 lo_dim\u00e8rcres lo_dij\u00f2us lo_divendres lo_dissabte\ndjadomingo djaluna djamars djarason djaweps djabi\u00e8rna djasabra\nNiedziela Poniedzial/ek Wtorek S,roda Czwartek Pia,tek Sobota\nDomingo segunda-feire ter\u00e7a-feire quarta-feire quinta-feire sexta-feira s\u00e5bado\nDomingo Lunes martes Miercoles Jueves Viernes Sabado\nDuminic\u00aa Luni Mart'i Miercuri Joi Vineri S\u00e2mb\u00aat\u00aa\nvoskresenie ponedelnik vtornik sreda chetverg pyatnitsa subbota\nSunday Di-luain Di-m\u00e0irt Di-ciadain Di-ardaoin Di-haoine Di-sathurne\nnedjelja ponedjeljak utorak sreda cxetvrtak petak subota\nSontaha Mmantaha Labobedi Laboraro Labone Labohlano Moqebelo\nIridha- Sandhudha- Anga.haruwa-dha- Badha-dha- Brahaspa.thindha- Sikura-dha- Sena.sura-dha-\nnedel^a pondelok utorok streda s^tvrtok piatok sobota\nNedelja Ponedeljek Torek Sreda Cxetrtek Petek Sobota\ndomingo lunes martes mi\u00e9rcoles jueves viernes s\u00e1bado\nsonde mundey tude-wroko dride-wroko fode-wroko freyda Saturday\nJumapili Jumatatu Jumanne Jumatano Alhamisi Ijumaa Jumamosi\ns\u00f6ndag m\u00e5ndag tisdag onsdag torsdag fredag lordag\nLinggo Lunes Martes Miyerkoles Huwebes Biyernes Sabado\nL\u00e9-p\u00e0i-j\u00edt P\u00e0i-it P\u00e0i-j\u00ef P\u00e0i-sa\u00f1 P\u00e0i-s\u00ec P\u00e0i-g\u00d6. P\u00e0i-l\u00e1k\nwan-ar-tit wan-tjan wan-ang-kaan wan-phoet wan-pha-ru-hat-sa-boh-die wan-sook wan-sao\nTshipi Mosupologo Labobedi Laboraro Labone Labotlhano Matlhatso\nPazar Pazartesi Sali \u00c7ar,samba Per,sembe Cuma Cumartesi\nnedilya ponedilok vivtorok sereda chetver pyatnytsya subota\nChu?_Nh\u00e2.t Th\u00fa*_Hai Th\u00fa*_Ba Th\u00fa*_Tu* Th\u00fa*_Na'm Th\u00fa*_S\u00e1u Th\u00fa*_Ba?y\ndydd_Sul dyds_Llun dydd_Mawrth dyds_Mercher dydd_Iau dydd_Gwener dyds_Sadwrn\nDibeer Altine Talaata Allarba Al_xebes Aljuma Gaaw\niCawa uMvulo uLwesibini uLwesithathu uLuwesine uLwesihlanu uMgqibelo\nzuntik montik dinstik mitvokh donershtik fraytik shabes\niSonto uMsombuluko uLwesibili uLwesithathu uLwesine uLwesihlanu uMgqibelo\nDies_Dominica Dies_Lun\u00e6 Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni\nBazar_g\u00dcn\u00dc Bazar_\u00e6rt\u00e6si \u00c7\u00e6rs,\u00e6nb\u00e6_axs,am\u00f2 \u00c7\u00e6rs,\u00e6nb\u00e6_g\u00dcn\u00dc C\u00dcm\u00e6_axs,am\u00f2 C\u00dcm\u00e6_g\u00dcn\u00dc C\u00dcm\u00e6_Senb\u00e6\nSun Moon Mars Mercury Jove Venus Saturn\nzondag maandag dinsdag woensdag donderdag vrijdag zaterdag\nKoseEraa GyoOraa BenEraa Kuoraa YOwaaraa FeEraa Memenaa\nSonntag Montag Dienstag Mittwoch Donnerstag Freitag Sonnabend\nDomingo Luns Terza_feira Corta_feira Xoves Venres S\u00e1bado\nDies_Solis Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Sabbatum\nxing-_qi-_ti\u00e0n xing-_qi-_yi-. xing-_qi-_\u00e8r xing-_qi-_san-. xing-_qi-_s\u00ec xing-_qi-_wuv. xing-_qi-_li\u00f9\ndjadomingu djaluna djamars djarason djaweps djabi\u00e8rn\u00e8 djasabra\nKillachau Atichau Quoyllurchau Illapachau Chaskachau Kuychichau Intichau\n\n''Caveat: \u00a0 The list (above) most surely contains errors (or, at the least, differences) of what the actual (or true) names for the days-of-the-week.''\n\n\nTo make this Rosetta Code task page as small as possible, if processing the complete list, read the days-of-the-week from a file (that is created from the above list).\n\n\nNotes concerning the above list of words\n::* \u00a0 each line has a list of days-of-the-week for a language, separated by at least one blank\n::* \u00a0 the words on each line happen to be in order, from Sunday \u2500\u2500\u25ba Saturday\n::* \u00a0 most lines have words in mixed case and some have all manner of accented words and other characters\n::* \u00a0 some words were translated to the nearest character that was available to ''code page'' \u00a0 '''437'''\n::* \u00a0 the characters in the words are not restricted except that they may not have imbedded blanks\n::* \u00a0 for this example, the use of an underscore ('''_''') was used to indicate a blank in a word\n\n\n;Task:\n::* \u00a0 The list of words \u00a0 (days of the week) \u00a0 needn't be verified/validated.\n::* \u00a0 Write a function to find the (numeric) minimum length abbreviation for each line that would make abbreviations unique.\n::* \u00a0 A blank line \u00a0 (or a null line) \u00a0 should return a null string.\n::* \u00a0 Process and show the output for at least the first '''five''' lines of the file.\n::* \u00a0 Show all output here.\n\n\n", "solution": "===Procedural===\nThe list of the names was edited and embedded in the HTML-Document with a \n\n"} +{"title": "Closures/Value capture", "language": "JavaScript ES6", "task": ";Task:\nCreate a list of ten functions, in the simplest manner possible \u00a0 (anonymous functions are encouraged), \u00a0 such that the function at index\u00a0\u00a0 '' i '' \u00a0 (you may choose to start \u00a0 '' i '' \u00a0 from either \u00a0 '''0''' \u00a0 or \u00a0 '''1'''), \u00a0 when run, should return the square of the index, \u00a0 that is, \u00a0 '' 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": "\"use strict\";\nlet funcs = [];\nfor (let i = 0; i < 10; ++i) {\n funcs.push((i => () => i*i)(i));\n}\nconsole.log(funcs[3]());"} +{"title": "Closures/Value capture", "language": "JavaScript ES5", "task": ";Task:\nCreate a list of ten functions, in the simplest manner possible \u00a0 (anonymous functions are encouraged), \u00a0 such that the function at index\u00a0\u00a0 '' i '' \u00a0 (you may choose to start \u00a0 '' i '' \u00a0 from either \u00a0 '''0''' \u00a0 or \u00a0 '''1'''), \u00a0 when run, should return the square of the index, \u00a0 that is, \u00a0 '' 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": "(function () {\n 'use strict';\n\n // Int -> Int -> [Int]\n function range(m, n) {\n return Array.apply(null, Array(n - m + 1))\n .map(function (x, i) {\n return m + i;\n });\n }\n\n var lstFns = range(0, 10)\n .map(function (i) {\n return function () {\n return i * i;\n };\n })\n \n return lstFns[3]();\n\n})();"} +{"title": "Closures/Value capture", "language": "Python", "task": ";Task:\nCreate a list of ten functions, in the simplest manner possible \u00a0 (anonymous functions are encouraged), \u00a0 such that the function at index\u00a0\u00a0 '' i '' \u00a0 (you may choose to start \u00a0 '' i '' \u00a0 from either \u00a0 '''0''' \u00a0 or \u00a0 '''1'''), \u00a0 when run, should return the square of the index, \u00a0 that is, \u00a0 '' 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": "funcs = []\nfor i in range(10):\n funcs.append((lambda i: lambda: i * i)(i))\nprint funcs[3]() # prints 9"} +{"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, (2\u00d74)8, (4\u00d77)28, (7\u00d75)35, (5\u00d73)15, (2\u00d74\u00d77)56, (4\u00d77\u00d75)140, (7\u00d75\u00d73)105, (2\u00d74\u00d77\u00d75)280, (4\u00d77\u00d75\u00d73)420, (2\u00d74\u00d77\u00d75\u00d73)840\n\nEvery product is unique.\n\n\n2346 is '''not''' a colorful number. 2, 3, 4, '''6''', (2\u00d73)'''6''', (3\u00d74)12, (4\u00d76)24, (2\u00d73\u00d74)48, (3\u00d74\u00d76)72, (2\u00d73\u00d74\u00d76)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": "Colorful numbers", "language": "Python", "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, (2\u00d74)8, (4\u00d77)28, (7\u00d75)35, (5\u00d73)15, (2\u00d74\u00d77)56, (4\u00d77\u00d75)140, (7\u00d75\u00d73)105, (2\u00d74\u00d77\u00d75)280, (4\u00d77\u00d75\u00d73)420, (2\u00d74\u00d77\u00d75\u00d73)840\n\nEvery product is unique.\n\n\n2346 is '''not''' a colorful number. 2, 3, 4, '''6''', (2\u00d73)'''6''', (3\u00d74)12, (4\u00d76)24, (2\u00d73\u00d74)48, (3\u00d74\u00d76)72, (2\u00d73\u00d74\u00d76)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": "from math import prod\n\nlargest = [0]\n\ndef iscolorful(n):\n if 0 <= n < 10:\n return True\n dig = [int(c) for c in str(n)]\n if 1 in dig or 0 in dig or len(dig) > len(set(dig)):\n return False\n products = list(set(dig))\n for i in range(len(dig)):\n for j in range(i+2, len(dig)+1):\n p = prod(dig[i:j])\n if p in products:\n return False\n products.append(p)\n\n largest[0] = max(n, largest[0])\n return True\n\nprint('Colorful numbers for 1:25, 26:50, 51:75, and 76:100:')\nfor i in range(1, 101, 25):\n for j in range(25):\n if iscolorful(i + j):\n print(f'{i + j: 5,}', end='')\n print()\n\ncsum = 0\nfor i in range(8):\n j = 0 if i == 0 else 10**i\n k = 10**(i+1) - 1\n n = sum(iscolorful(x) for x in range(j, k+1))\n csum += n\n print(f'The count of colorful numbers between {j} and {k} is {n}.')\n\nprint(f'The largest possible colorful number is {largest[0]}.')\nprint(f'The total number of colorful numbers is {csum}.')\n"} +{"title": "Colour bars/Display", "language": "C", "task": ";Task:\nDisplay a series of vertical color bars across the width of the display. \n\nThe color bars should either use:\n:::* \u00a0 the system palette, \u00a0 or \n:::* \u00a0 the sequence of colors: \n::::::* \u00a0 black\n::::::* \u00a0 red\n::::::* \u00a0 green\n::::::* \u00a0 blue\n::::::* \u00a0 magenta\n::::::* \u00a0 cyan\n::::::* \u00a0 yellow\n::::::* \u00a0 white\n\n", "solution": "\n#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\n===Graphics Mode===\nThe required functions and structures are in graphics.h, conio.h is included for getch().\n\n#include\n#include\n\nint main()\n{\n\tint d=DETECT,m,maxX,maxY,maxColours,i;\n\tinitgraph(&d,&m,\"c:/turboc3/bgi\");\n\tmaxX = getmaxx();\n\tmaxY = getmaxy();\n\tmaxColours = getmaxcolor();\n\n\tfor(i=0;i\n"} +{"title": "Colour bars/Display", "language": "Python", "task": ";Task:\nDisplay a series of vertical color bars across the width of the display. \n\nThe color bars should either use:\n:::* \u00a0 the system palette, \u00a0 or \n:::* \u00a0 the sequence of colors: \n::::::* \u00a0 black\n::::::* \u00a0 red\n::::::* \u00a0 green\n::::::* \u00a0 blue\n::::::* \u00a0 magenta\n::::::* \u00a0 cyan\n::::::* \u00a0 yellow\n::::::* \u00a0 white\n\n", "solution": "\n#!/usr/bin/env python\n#vertical coloured stripes in window in Python 2.7.1\n\nfrom livewires import *\n\nhoriz=640; vert=480\nbegin_graphics(width=horiz,height=vert,title=\"v_stripes\",background=Colour.black)\nNameColors=[\"black\",\"red\",\"green\",\"dark_blue\",\"purple\",\"blue\",\"yellow\",\"white\"]\nstepik=horiz/len(NameColors)\n\nfor index,each in enumerate(NameColors):\n\tExcStrng=\"set_colour(Colour.\"+each+\")\"\n\texec ExcStrng\n\tbox(index*stepik,0,(index+1)*stepik,vert,filled=1)\n\nwhile keys_pressed() != ['x']: # press x key to terminate program\n\tpass\n\nend_graphics()\n"} +{"title": "Colour pinstripe/Printer", "language": "Python", "task": "The task is to create 1 point wide colour vertical pinstripes with a sufficient number of pinstripes to span the entire width of the colour graphics printer. The pinstripes should alternate between each individual cartridge ink and ink pair and black and white pinstripes should be included. A typical pinstripe sequence woud be black, red, green, blue, magenta, cyan, yellow, white.\n\nAfter the first inch of printing, we switch to a wider 2 pixel wide vertical pinstripe pattern. and to 3 point wide vertical for the next inch, and then 4 point wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).\n\nNote that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.\n\nOptionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.\n\n", "solution": "\nfrom turtle import *\nfrom PIL import Image\nimport time\nimport subprocess\n\n\"\"\"\n\nOnly works on Windows. Assumes that you have Ghostscript\ninstalled and in your path.\n\nhttps://www.ghostscript.com/download/gsdnld.html\n\nHard coded to 100 pixels per inch.\n\n\"\"\"\n\ncolors = [\"black\", \"red\", \"green\", \"blue\", \"magenta\", \"cyan\", \"yellow\", \"white\"]\n\nscreen = getscreen()\n\n# width and height in pixels\n# aspect ratio for 11 by 8.5 paper\n\ninch_width = 11.0\ninch_height = 8.5\n\npixels_per_inch = 100\n\npix_width = int(inch_width*pixels_per_inch)\npix_height = int(inch_height*pixels_per_inch)\n\nscreen.setup (width=pix_width, height=pix_height, startx=0, starty=0)\n\nscreen.screensize(pix_width,pix_height)\n\n# center is 0,0\n\n# get coordinates of the edges\n\nleft_edge = -screen.window_width()//2\n\nright_edge = screen.window_width()//2\n\nbottom_edge = -screen.window_height()//2\n\ntop_edge = screen.window_height()//2\n\n# draw quickly\n\nscreen.delay(0)\nscreen.tracer(5)\n\nfor inch in range(int(inch_width)-1):\n line_width = inch + 1\n pensize(line_width)\n colornum = 0\n\n min_x = left_edge + (inch * pixels_per_inch)\n max_x = left_edge + ((inch+1) * pixels_per_inch)\n \n for y in range(bottom_edge,top_edge,line_width):\n penup()\n pencolor(colors[colornum])\n colornum = (colornum + 1) % len(colors)\n setposition(min_x,y)\n pendown()\n setposition(max_x,y)\n \nscreen.getcanvas().postscript(file=\"striped.eps\")\n\n# convert to jpeg\n# won't work without Ghostscript.\n\nim = Image.open(\"striped.eps\")\nim.save(\"striped.jpg\")\n\n# Got idea from http://rosettacode.org/wiki/Colour_pinstripe/Printer#Go\n \nsubprocess.run([\"mspaint\", \"/pt\", \"striped.jpg\"])\n"} +{"title": "Comma quibbling", "language": "C", "task": "Comma quibbling is a task originally set by Eric Lippert in his [http://blogs.msdn.com/b/ericlippert/archive/2009/04/15/comma-quibbling.aspx blog].\n\n\n;Task:\n\nWrite a function to generate a string output which is the concatenation of input words from a list/sequence where:\n# An input of no words produces the output string of just the two brace characters \"{}\".\n# An input of just one word, e.g. [\"ABC\"], produces the output string of the word inside the two braces, e.g. \"{ABC}\".\n# An input of two words, e.g. [\"ABC\", \"DEF\"], produces the output string of the two words inside the two braces with the words separated by the string \" and \", e.g. \"{ABC and DEF}\".\n# An input of three or more words, e.g. [\"ABC\", \"DEF\", \"G\", \"H\"], produces the output string of all but the last word separated by \", \" with the last word separated by \" and \" and all within braces; e.g. \"{ABC, DEF, G and H}\".\n\n\nTest your function with the following series of inputs showing your output here on this page:\n* [] # (No input words).\n* [\"ABC\"]\n* [\"ABC\", \"DEF\"]\n* [\"ABC\", \"DEF\", \"G\", \"H\"]\n\n\nNote: Assume words are non-empty strings of uppercase characters for this task.\n\n", "solution": "#include \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": "Comma quibbling", "language": "JavaScript", "task": "Comma quibbling is a task originally set by Eric Lippert in his [http://blogs.msdn.com/b/ericlippert/archive/2009/04/15/comma-quibbling.aspx blog].\n\n\n;Task:\n\nWrite a function to generate a string output which is the concatenation of input words from a list/sequence where:\n# An input of no words produces the output string of just the two brace characters \"{}\".\n# An input of just one word, e.g. [\"ABC\"], produces the output string of the word inside the two braces, e.g. \"{ABC}\".\n# An input of two words, e.g. [\"ABC\", \"DEF\"], produces the output string of the two words inside the two braces with the words separated by the string \" and \", e.g. \"{ABC and DEF}\".\n# An input of three or more words, e.g. [\"ABC\", \"DEF\", \"G\", \"H\"], produces the output string of all but the last word separated by \", \" with the last word separated by \" and \" and all within braces; e.g. \"{ABC, DEF, G and H}\".\n\n\nTest your function with the following series of inputs showing your output here on this page:\n* [] # (No input words).\n* [\"ABC\"]\n* [\"ABC\", \"DEF\"]\n* [\"ABC\", \"DEF\", \"G\", \"H\"]\n\n\nNote: Assume words are non-empty strings of uppercase characters for this task.\n\n", "solution": "function quibble(words) {\n return \"{\" + \n words.slice(0, words.length-1).join(\",\") +\n (words.length > 1 ? \" and \" : \"\") +\n (words[words.length-1] || '') +\n \"}\";\n}\n\n[[], [\"ABC\"], [\"ABC\", \"DEF\"], [\"ABC\", \"DEF\", \"G\", \"H\"]].forEach(\n function(s) {\n console.log(quibble(s));\n }\n);"} +{"title": "Comma quibbling", "language": "Python", "task": "Comma quibbling is a task originally set by Eric Lippert in his [http://blogs.msdn.com/b/ericlippert/archive/2009/04/15/comma-quibbling.aspx blog].\n\n\n;Task:\n\nWrite a function to generate a string output which is the concatenation of input words from a list/sequence where:\n# An input of no words produces the output string of just the two brace characters \"{}\".\n# An input of just one word, e.g. [\"ABC\"], produces the output string of the word inside the two braces, e.g. \"{ABC}\".\n# An input of two words, e.g. [\"ABC\", \"DEF\"], produces the output string of the two words inside the two braces with the words separated by the string \" and \", e.g. \"{ABC and DEF}\".\n# An input of three or more words, e.g. [\"ABC\", \"DEF\", \"G\", \"H\"], produces the output string of all but the last word separated by \", \" with the last word separated by \" and \" and all within braces; e.g. \"{ABC, DEF, G and H}\".\n\n\nTest your function with the following series of inputs showing your output here on this page:\n* [] # (No input words).\n* [\"ABC\"]\n* [\"ABC\", \"DEF\"]\n* [\"ABC\", \"DEF\", \"G\", \"H\"]\n\n\nNote: Assume words are non-empty strings of uppercase characters for this task.\n\n", "solution": ">>> def strcat(sequence):\n return '{%s}' % ', '.join(sequence)[::-1].replace(',', 'dna ', 1)[::-1]\n\n>>> for seq in ([], [\"ABC\"], [\"ABC\", \"DEF\"], [\"ABC\", \"DEF\", \"G\", \"H\"]):\n print('Input: %-24r -> Output: %r' % (seq, strcat(seq)))\n\n\t\nInput: [] -> Output: '{}'\nInput: ['ABC'] -> Output: '{ABC}'\nInput: ['ABC', 'DEF'] -> Output: '{ABC and DEF}'\nInput: ['ABC', 'DEF', 'G', 'H'] -> Output: '{ABC, DEF, G and H}'\n>>> "} +{"title": "Command-line arguments", "language": "C", "task": "See 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": "Command-line arguments", "language": "Node.js", "task": "See 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": "process.argv.forEach((val, index) => {\n console.log(`${index}: ${val}`);\n});"} +{"title": "Command-line arguments", "language": "JScript", "task": "See 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": "var objArgs = WScript.Arguments;\nfor (var i = 0; i < objArgs.length; i++)\n WScript.Echo(objArgs.Item(i));"} +{"title": "Command-line arguments", "language": "JScript.NET (compiled with jsc.exe)", "task": "See 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": "import System;\nvar argv:String[] = Environment.GetCommandLineArgs();\nfor (var i in argv)\n print(argv[i]);"} +{"title": "Command-line arguments", "language": "SpiderMonkey", "task": "See 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": "for (var i = 0; i < arguments.length; i++)\n print(arguments[i]);"} +{"title": "Command-line arguments", "language": "Python", "task": "See 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": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)"} +{"title": "Compare a list of strings", "language": "C", "task": ";Task:\nGiven a \u00a0 list \u00a0 of arbitrarily many strings, show how to:\n\n* \u00a0 test if they are all lexically '''equal'''\n* \u00a0 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 \u00a0 if \u00a0 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 \u00a0 strings, \u00a0 and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), \u00a0 with as little distractions as possible.\n\nTry to write your solution in a way that does not modify the original list, \u00a0 but if it does then please add a note to make that clear to readers.\n\nIf you need further guidance/clarification, \u00a0 see [[#Perl]] and [[#Python]] for solutions that use implicit short-circuiting loops, \u00a0 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": "Compare a list of strings", "language": "JavaScript", "task": ";Task:\nGiven a \u00a0 list \u00a0 of arbitrarily many strings, show how to:\n\n* \u00a0 test if they are all lexically '''equal'''\n* \u00a0 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 \u00a0 if \u00a0 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 \u00a0 strings, \u00a0 and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), \u00a0 with as little distractions as possible.\n\nTry to write your solution in a way that does not modify the original list, \u00a0 but if it does then please add a note to make that clear to readers.\n\nIf you need further guidance/clarification, \u00a0 see [[#Perl]] and [[#Python]] for solutions that use implicit short-circuiting loops, \u00a0 and [[#Raku]] for a solution that gets away with simply using a built-in language feature. \n\n", "solution": "function allEqual(a) {\n var out = true, i = 0;\n while (++i\n\n===ES6===\n====Functional====\n\nUsing a generic zipWith, and functionally composed predicates:\n(() => {\n 'use strict';\n\n // allEqual :: [String] -> Bool\n let allEqual = xs => and(zipWith(equal, xs, xs.slice(1))),\n\n // azSorted :: [String] -> Bool\n azSorted = xs => and(zipWith(azBefore, xs, xs.slice(1))),\n\n // equal :: a -> a -> Bool\n equal = (a, b) => a === b,\n\n // azBefore :: String -> String -> Bool\n azBefore = (a, b) => a.toLowerCase() <= b.toLowerCase();\n\n\n // GENERIC\n\n // and :: [Bool] -> Bool\n let and = xs => xs.reduceRight((a, x) => a && x, true),\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n zipWith = (f, xs, ys) => {\n let ny = ys.length;\n return (xs.length <= ny ? xs : xs.slice(0, ny))\n .map((x, i) => f(x, ys[i]));\n };\n\n\n // TEST\n\n let lists = [\n ['isiZulu', 'isiXhosa', 'isiNdebele', 'Xitsonga',\n 'Tshivenda', 'Setswana', 'Sesotho sa Leboa', 'Sesotho',\n 'English', 'Afrikaans'\n ],\n ['Afrikaans', 'English', 'isiNdebele', 'isiXhosa',\n 'isiZulu', 'Sesotho', 'Sesotho sa Leboa', 'Setswana',\n 'Tshivenda', 'Xitsonga',\n ],\n ['alpha', 'alpha', 'alpha', 'alpha', 'alpha', 'alpha',\n 'alpha', 'alpha', 'alpha', 'alpha', 'alpha', 'alpha'\n ]\n ];\n\n return {\n allEqual: lists.map(allEqual),\n azSorted: lists.map(azSorted)\n };\n\n})();\n"} +{"title": "Compare a list of strings", "language": "Python", "task": ";Task:\nGiven a \u00a0 list \u00a0 of arbitrarily many strings, show how to:\n\n* \u00a0 test if they are all lexically '''equal'''\n* \u00a0 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 \u00a0 if \u00a0 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 \u00a0 strings, \u00a0 and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), \u00a0 with as little distractions as possible.\n\nTry to write your solution in a way that does not modify the original list, \u00a0 but if it does then please add a note to make that clear to readers.\n\nIf you need further guidance/clarification, \u00a0 see [[#Perl]] and [[#Python]] for solutions that use implicit short-circuiting loops, \u00a0 and [[#Raku]] for a solution that gets away with simply using a built-in language feature. \n\n", "solution": "from operator import (eq, lt)\n\n\nxs = [\"alpha\", \"beta\", \"gamma\", \"delta\", \"epsilon\", \"zeta\",\n \"eta\", \"theta\", \"iota\", \"kappa\", \"lambda\", \"mu\"]\n\nys = [\"alpha\", \"beta\", \"gamma\", \"delta\", \"epsilon\", \"zeta\",\n \"eta\", \"theta\", \"iota\", \"kappa\", \"lambda\", \"mu\"]\n\naz = sorted(xs)\n\nprint (\n all(map(eq, xs, ys)),\n\n all(map(lt, xs, xs[1:])),\n\n all(map(lt, az, az[1:]))\n)"} +{"title": "Compile-time calculation", "language": "C", "task": "Some programming languages allow calculation of values at compile time. \n\n\n;Task:\nCalculate \u00a0 10! \u00a0 (ten factorial) \u00a0 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": "An AST interpreter interprets an [https://en.wikipedia.org/wiki/Abstract_syntax_tree Abstract Syntax Tree (AST)]\nproduced by a Syntax Analyzer.\n\n\nTake the AST output from the Syntax analyzer task, and interpret it as appropriate.\nRefer to the Syntax analyzer task for details of the AST.\n\n;Loading the AST from the syntax analyzer is as simple as (pseudo code):\n\ndef load_ast()\n line = readline()\n # Each line has at least one token\n line_list = tokenize the line, respecting double quotes\n\n text = line_list[0] # first token is always the node type\n\n if text == \";\" # a terminal node\n return NULL\n\n node_type = text # could convert to internal form if desired\n\n # A line with two tokens is a leaf node\n # Leaf nodes are: Identifier, Integer, String\n # The 2nd token is the value\n if len(line_list) > 1\n return make_leaf(node_type, line_list[1])\n\n left = load_ast()\n right = load_ast()\n return make_node(node_type, left, right)\n\n; The interpreter algorithm is relatively simple:\n\ninterp(x)\n if x == NULL return NULL\n elif x.node_type == Integer return x.value converted to an integer\n elif x.node_type == Ident return the current value of variable x.value\n elif x.node_type == String return x.value\n elif x.node_type == Assign\n globals[x.left.value] = interp(x.right)\n return NULL\n elif x.node_type is a binary operator return interp(x.left) operator interp(x.right)\n elif x.node_type is a unary operator, return return operator interp(x.left)\n elif x.node_type == If\n if (interp(x.left)) then interp(x.right.left)\n else interp(x.right.right)\n return NULL\n elif x.node_type == While\n while (interp(x.left)) do interp(x.right)\n return NULL\n elif x.node_type == Prtc\n print interp(x.left) as a character, no newline\n return NULL\n elif x.node_type == Prti\n print interp(x.left) as an integer, no newline\n return NULL\n elif x.node_type == Prts\n print interp(x.left) as a string, respecting newlines (\"\\n\")\n return NULL\n elif x.node_type == Sequence\n interp(x.left)\n interp(x.right)\n return NULL\n else\n error(\"unknown node type\")\n\nNotes:\n\nBecause of the simple nature of our tiny language, Semantic analysis is not needed.\n\nYour interpreter should use C like division semantics, for both division and modulus. For division of positive operands, only the non-fractional portion of the result should be returned. In other words, the result should be truncated towards 0.\n\nThis means, for instance, that 3 / 2 should result in 1.\n\nFor division when one of the operands is negative, the result should be truncated towards 0.\n\nThis means, for instance, that 3 / -2 should result in -1.\n\n; Test program\n\n{| class=\"wikitable\"\n|-\n! prime.t\n! lex = _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/AST interpreter", "language": "Python", "task": "An AST interpreter interprets an [https://en.wikipedia.org/wiki/Abstract_syntax_tree Abstract Syntax Tree (AST)]\nproduced by a Syntax Analyzer.\n\n\nTake the AST output from the Syntax analyzer task, and interpret it as appropriate.\nRefer to the Syntax analyzer task for details of the AST.\n\n;Loading the AST from the syntax analyzer is as simple as (pseudo code):\n\ndef load_ast()\n line = readline()\n # Each line has at least one token\n line_list = tokenize the line, respecting double quotes\n\n text = line_list[0] # first token is always the node type\n\n if text == \";\" # a terminal node\n return NULL\n\n node_type = text # could convert to internal form if desired\n\n # A line with two tokens is a leaf node\n # Leaf nodes are: Identifier, Integer, String\n # The 2nd token is the value\n if len(line_list) > 1\n return make_leaf(node_type, line_list[1])\n\n left = load_ast()\n right = load_ast()\n return make_node(node_type, left, right)\n\n; The interpreter algorithm is relatively simple:\n\ninterp(x)\n if x == NULL return NULL\n elif x.node_type == Integer return x.value converted to an integer\n elif x.node_type == Ident return the current value of variable x.value\n elif x.node_type == String return x.value\n elif x.node_type == Assign\n globals[x.left.value] = interp(x.right)\n return NULL\n elif x.node_type is a binary operator return interp(x.left) operator interp(x.right)\n elif x.node_type is a unary operator, return return operator interp(x.left)\n elif x.node_type == If\n if (interp(x.left)) then interp(x.right.left)\n else interp(x.right.right)\n return NULL\n elif x.node_type == While\n while (interp(x.left)) do interp(x.right)\n return NULL\n elif x.node_type == Prtc\n print interp(x.left) as a character, no newline\n return NULL\n elif x.node_type == Prti\n print interp(x.left) as an integer, no newline\n return NULL\n elif x.node_type == Prts\n print interp(x.left) as a string, respecting newlines (\"\\n\")\n return NULL\n elif x.node_type == Sequence\n interp(x.left)\n interp(x.right)\n return NULL\n else\n error(\"unknown node type\")\n\nNotes:\n\nBecause of the simple nature of our tiny language, Semantic analysis is not needed.\n\nYour interpreter should use C like division semantics, for both division and modulus. For division of positive operands, only the non-fractional portion of the result should be returned. In other words, the result should be truncated towards 0.\n\nThis means, for instance, that 3 / 2 should result in 1.\n\nFor division when one of the operands is negative, the result should be truncated towards 0.\n\nThis means, for instance, that 3 / -2 should result in -1.\n\n; Test program\n\n{| class=\"wikitable\"\n|-\n! prime.t\n! lex interp(x.right)\n elif x.node_type == nd_Leq: return interp(x.left) <= interp(x.right)\n elif x.node_type == nd_Geq: return interp(x.left) >= interp(x.right)\n elif x.node_type == nd_Eql: return interp(x.left) == interp(x.right)\n elif x.node_type == nd_Neq: return interp(x.left) != interp(x.right)\n elif x.node_type == nd_And: return interp(x.left) and interp(x.right)\n elif x.node_type == nd_Or: return interp(x.left) or interp(x.right)\n elif x.node_type == nd_Negate: return -interp(x.left)\n elif x.node_type == nd_Not: return not interp(x.left)\n\n elif x.node_type == nd_If:\n if (interp(x.left)):\n interp(x.right.left)\n else:\n interp(x.right.right)\n return None\n\n elif x.node_type == nd_While:\n while (interp(x.left)):\n interp(x.right)\n return None\n\n elif x.node_type == nd_Prtc:\n print(\"%c\" % (interp(x.left)), end='')\n return None\n\n elif x.node_type == nd_Prti:\n print(\"%d\" % (interp(x.left)), end='')\n return None\n\n elif x.node_type == nd_Prts:\n print(interp(x.left), end='')\n return None\n\n elif x.node_type == nd_Sequence:\n interp(x.left)\n interp(x.right)\n return None\n else:\n error(\"error in code generator - found %d, expecting operator\" % (x.node_type))\n\ndef str_trans(srce):\n dest = \"\"\n i = 0\n srce = srce[1:-1]\n while i < len(srce):\n if srce[i] == '\\\\' and i + 1 < len(srce):\n if srce[i + 1] == 'n':\n dest += '\\n'\n i += 2\n elif srce[i + 1] == '\\\\':\n dest += '\\\\'\n i += 2\n else:\n dest += srce[i]\n i += 1\n\n return dest\n\ndef load_ast():\n line = input_file.readline()\n line_list = shlex.split(line, False, False)\n\n text = line_list[0]\n\n value = None\n if len(line_list) > 1:\n value = line_list[1]\n if value.isdigit():\n value = int(value)\n\n if text == \";\":\n return None\n node_type = all_syms[text]\n if value != None:\n if node_type == nd_String:\n value = str_trans(value)\n\n return make_leaf(node_type, value)\n left = load_ast()\n right = load_ast()\n return make_node(node_type, left, right)\n\n#*** main driver\ninput_file = sys.stdin\nif len(sys.argv) > 1:\n try:\n input_file = open(sys.argv[1], \"r\", 4096)\n except IOError as e:\n error(0, 0, \"Can't open %s\" % sys.argv[1])\n\nn = load_ast()\ninterp(n)"} +{"title": "Compiler/code generator", "language": "C", "task": "A code generator translates the output of the syntax analyzer and/or semantic analyzer\ninto lower level code, either assembly, object, or virtual.\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/code generator", "language": "Python", "task": "A code generator translates the output of the syntax analyzer and/or semantic analyzer\ninto lower level code, either assembly, object, or virtual.\n\n", "solution": "from __future__ import print_function\nimport sys, struct, shlex, operator\n\nnd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While, \\\nnd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq, \\\nnd_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or = range(25)\n\nall_syms = {\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\nFETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT, \\\nJMP, JZ, PRTC, PRTS, PRTI, HALT = range(24)\n\noperators = {nd_Lss: LT, nd_Gtr: GT, nd_Leq: LE, nd_Geq: GE, nd_Eql: EQ, nd_Neq: NE,\n nd_And: AND, nd_Or: OR, nd_Sub: SUB, nd_Add: ADD, nd_Div: DIV, nd_Mul: MUL, nd_Mod: MOD}\n\nunary_operators = {nd_Negate: NEG, nd_Not: NOT}\n\ninput_file = None\ncode = bytearray()\nstring_pool = {}\nglobals = {}\nstring_n = 0\nglobals_n = 0\nword_size = 4\n\n#*** show error and exit\ndef error(msg):\n print(\"%s\" % (msg))\n exit(1)\n\ndef int_to_bytes(val):\n return struct.pack(\" 1:\n value = line_list[1]\n if value.isdigit():\n value = int(value)\n return make_leaf(node_type, value)\n\n left = load_ast()\n right = load_ast()\n return make_node(node_type, left, right)\n\n#*** main driver\ninput_file = sys.stdin\nif len(sys.argv) > 1:\n try:\n input_file = open(sys.argv[1], \"r\", 4096)\n except IOError as e:\n error(\"Can't open %s\" % sys.argv[1])\n\nn = load_ast()\ncode_gen(n)\ncode_finish()\nlist_code()"} +{"title": "Compiler/lexical analyzer", "language": "C", "task": "Definition from [https://en.wikipedia.org/wiki/Lexical_analysis Wikipedia]:\n\n: ''Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified \"meaning\"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though \"scanner\" is also used to refer to the first stage of a lexer).''\n\n\nCreate a lexical analyzer for the simple programming language specified below. The\nprogram should read input from a file and/or stdin, and write output to a file and/or\nstdout. If the language being used has a lexer module/library/class, it would be great\nif two versions of the solution are provided: One without the lexer module, and one with.\n\n\nThe simple programming language to be analyzed is more or less a subset of [[C]]. It supports the following tokens:\n\n;Operators\n\n:::{| class=\"wikitable\"\n|-\n! Name !! Common name !! Character sequence\n|-\n| Op_multiply || multiply || *\n|-\n| Op_divide || divide || /\n|-\n| Op_mod || mod || %\n|-\n| Op_add || plus || +\n|-\n| Op_subtract || minus || -\n|-\n| Op_negate || unary minus || -\n|-\n| Op_less || less than || <\n|-\n| Op_lessequal || less than or equal || <=\n|-\n| Op_greater || greater than || >\n|-\n| Op_greaterequal || greater than or equal || >=\n|-\n| Op_equal || equal || ==\n|-\n| Op_notequal || not equal || !=\n|-\n| Op_not || unary not || !\n|-\n| Op_assign || assignment || =\n|-\n| Op_and || logical and || &&\n|-\n| Op_or || logical or || \u00a6\u00a6\n|}\n\n* The - token should always be interpreted as Op_subtract by the lexer. Turning some Op_subtract into Op_negate will be the job of the syntax analyzer, which is not part of this task.\n\n;Symbols\n\n:::{| class=\"wikitable\"\n|-\n! Name !! Common name !! Character\n|-\n| LeftParen || left parenthesis || (\n|-\n| RightParen || right parenthesis || )\n|-\n| LeftBrace || left brace || {\n|-\n| RightBrace || right brace || }\n|-\n| Semicolon || semi-colon || ;\n|-\n| Comma || comma || ,\n|}\n\n;Keywords\n\n:::{| class=\"wikitable\"\n|-\n! Name || Character sequence\n|-\n| Keyword_if || if\n|-\n| Keyword_else || else\n|-\n| Keyword_while || while\n|-\n| Keyword_print || print\n|-\n| Keyword_putc || putc\n|}\n\n;Identifiers and literals\n\nThese differ from the the previous tokens, in that each occurrence of them has a value associated with it.\n\n:::{| class=\"wikitable\"\n|-\n! Name\n! Common name\n! Format description\n! Format regex\n! Value\n|-\n| Identifier\n| identifier\n| one or more letter/number/underscore characters, but not starting with a number\n| [_a-zA-Z][_a-zA-Z0-9]*\n| as is\n|-\n| Integer\n| integer literal\n| one or more digits\n| [0-9]+\n| as is, interpreted as a number\n|-\n| Integer\n| char literal\n| exactly one character (anything except newline or single quote) or one of the allowed escape sequences, enclosed by single quotes\n| '([^'\\n]|\\\\n|\\\\\\\\)'\n| the ASCII code point number of the character, e.g. 65 for 'A' and 10 for '\\n'\n|-\n| String\n| string literal\n| zero or more characters (anything except newline or double quote), enclosed by double quotes\n| \"[^\"\\n]*\"\n| the characters without the double quotes and with escape sequences converted\n|}\n\n* For char and string literals, the \\n escape sequence is supported to represent a new-line character.\n* For char and string literals, to represent a backslash, use \\\\.\n* No other special sequences are supported. This means that:\n** Char literals cannot represent a single quote character (value 39).\n** String literals cannot represent strings containing double quote characters.\n\n;Zero-width tokens\n\n:::{| class=\"wikitable\"\n|-\n! Name || Location\n|-\n| End_of_input || when the end of the input stream is reached\n|}\n\n;White space\n\n* Zero or more whitespace characters, or comments enclosed in /* ... */, are allowed between any two tokens, with the exceptions noted below.\n* \"Longest token matching\" is used to resolve conflicts (e.g., in order to match '''<=''' as a single token rather than the two tokens '''<''' and '''=''').\n* Whitespace is ''required'' between two tokens that have an alphanumeric character or underscore at the edge.\n** This means: keywords, identifiers, and integer literals.\n** e.g. ifprint is recognized as an identifier, instead of the keywords if and print.\n** e.g. 42fred is invalid, and neither recognized as a number nor an identifier.\n* Whitespace is ''not allowed'' inside of tokens (except for chars and strings where they are part of the value).\n** e.g. & & is invalid, and not interpreted as the && operator.\n\nFor example, the following two program fragments are equivalent, and should produce the same token stream except for the line and column positions:\n\n* if ( p /* meaning n is prime */ ) {\n print ( n , \" \" ) ;\n count = count + 1 ; /* number of primes found so far */\n}\n* if(p){print(n,\" \");count=count+1;}\n\n;Complete list of token names\n\n\nEnd_of_input Op_multiply Op_divide Op_mod Op_add Op_subtract\nOp_negate Op_not Op_less Op_lessequal Op_greater Op_greaterequal\nOp_equal Op_notequal Op_assign Op_and Op_or Keyword_if\nKeyword_else Keyword_while Keyword_print Keyword_putc LeftParen RightParen\nLeftBrace RightBrace Semicolon Comma Identifier Integer\nString\n\n\n\nThe program output should be a sequence of lines, each consisting of the following whitespace-separated fields:\n\n# the line number where the token starts\n# the column number where the token starts\n# the token name\n# the token value (only for Identifier, Integer, and String tokens)\n# the number of spaces between fields is up to you. Neatly aligned is nice, but not a requirement.\n\n\nThis task is intended to be used as part of a pipeline, with the other compiler tasks - for example:\nlex < hello.t | parse | gen | vm\n\nOr possibly:\nlex hello.t lex.out\nparse lex.out parse.out\ngen parse.out gen.out\nvm gen.out\n\nThis implies that the output of this task (the lexical analyzer) should be suitable as input to any of the Syntax Analyzer task programs.\n\n\nThe following error conditions should be caught:\n\n:::{| class=\"wikitable\"\n|-\n! Error\n! Example\n|-\n| Empty character constant\n| ''\n|-\n| Unknown escape sequence.\n| \\r\n|-\n| Multi-character constant.\n| 'xx'\n|-\n| End-of-file in comment. Closing comment characters not found.\n|-\n| End-of-file while scanning string literal. Closing string character not found.\n|-\n| End-of-line while scanning string literal. Closing string character not found before end-of-line.\n|-\n| Unrecognized character.\n| |\n|-\n| Invalid number. Starts like a number, but ends in non-numeric characters.\n| 123abc\n|}\n\n:{| class=\"wikitable\"\n|-\n! Input\n! Output\n|-\n| style=\"vertical-align:top\" |\nTest Case 1:\n/*\n Hello world\n */\nprint(\"Hello, World!\\n\");\n\n| style=\"vertical-align:top\" |\n\n 4 1 Keyword_print\n 4 6 LeftParen\n 4 7 String \"Hello, World!\\n\"\n 4 24 RightParen\n 4 25 Semicolon\n 5 1 End_of_input\n\n\n|-\n| style=\"vertical-align:top\" |\nTest Case 2:\n/*\n Show Ident and Integers\n */\nphoenix_number = 142857;\nprint(phoenix_number, \"\\n\");\n\n| style=\"vertical-align:top\" |\n\n 4 1 Identifier phoenix_number\n 4 16 Op_assign\n 4 18 Integer 142857\n 4 24 Semicolon\n 5 1 Keyword_print\n 5 6 LeftParen\n 5 7 Identifier phoenix_number\n 5 21 Comma\n 5 23 String \"\\n\"\n 5 27 RightParen\n 5 28 Semicolon\n 6 1 End_of_input\n\n\n|-\n| style=\"vertical-align:top\" |\nTest Case 3:\n/*\n All lexical tokens - not syntactically correct, but that will\n have to wait until syntax analysis\n */\n/* Print */ print /* Sub */ -\n/* Putc */ putc /* Lss */ <\n/* If */ if /* Gtr */ >\n/* Else */ else /* Leq */ <=\n/* While */ while /* Geq */ >=\n/* Lbrace */ { /* Eq */ ==\n/* Rbrace */ } /* Neq */ !=\n/* Lparen */ ( /* And */ &&\n/* Rparen */ ) /* Or */ ||\n/* Uminus */ - /* Semi */ ;\n/* Not */ ! /* Comma */ ,\n/* Mul */ * /* Assign */ =\n/* Div */ / /* Integer */ 42\n/* Mod */ % /* String */ \"String literal\"\n/* Add */ + /* Ident */ variable_name\n/* character literal */ '\\n'\n/* character literal */ '\\\\'\n/* character literal */ ' '\n\n| style=\"vertical-align:top\" |\n\n 5 16 Keyword_print\n 5 40 Op_subtract\n 6 16 Keyword_putc\n 6 40 Op_less\n 7 16 Keyword_if\n 7 40 Op_greater\n 8 16 Keyword_else\n 8 40 Op_lessequal\n 9 16 Keyword_while\n 9 40 Op_greaterequal\n 10 16 LeftBrace\n 10 40 Op_equal\n 11 16 RightBrace\n 11 40 Op_notequal\n 12 16 LeftParen\n 12 40 Op_and\n 13 16 RightParen\n 13 40 Op_or\n 14 16 Op_subtract\n 14 40 Semicolon\n 15 16 Op_not\n 15 40 Comma\n 16 16 Op_multiply\n 16 40 Op_assign\n 17 16 Op_divide\n 17 40 Integer 42\n 18 16 Op_mod\n 18 40 String \"String literal\"\n 19 16 Op_add\n 19 40 Identifier variable_name\n 20 26 Integer 10\n 21 26 Integer 92\n 22 26 Integer 32\n 23 1 End_of_input\n\n\n|-\n| style=\"vertical-align:top\" |\nTest Case 4:\n/*** test printing, embedded \\n and comments with lots of '*' ***/\nprint(42);\nprint(\"\\nHello World\\nGood Bye\\nok\\n\");\nprint(\"Print a slash n - \\\\n.\\n\");\n\n| style=\"vertical-align:top\" |\n\n 2 1 Keyword_print\n 2 6 LeftParen\n 2 7 Integer 42\n 2 9 RightParen\n 2 10 Semicolon\n 3 1 Keyword_print\n 3 6 LeftParen\n 3 7 String \"\\nHello World\\nGood Bye\\nok\\n\"\n 3 38 RightParen\n 3 39 Semicolon\n 4 1 Keyword_print\n 4 6 LeftParen\n 4 7 String \"Print a slash n - \\\\n.\\n\"\n 4 33 RightParen\n 4 34 Semicolon\n 5 1 End_of_input\n\n\n|}\n\n;Additional examples\nYour solution should pass all the test cases above and the additional tests found '''Here'''.\n\n\nThe 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/lexical analyzer", "language": "JavaScript", "task": "Definition from [https://en.wikipedia.org/wiki/Lexical_analysis Wikipedia]:\n\n: ''Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified \"meaning\"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though \"scanner\" is also used to refer to the first stage of a lexer).''\n\n\nCreate a lexical analyzer for the simple programming language specified below. The\nprogram should read input from a file and/or stdin, and write output to a file and/or\nstdout. If the language being used has a lexer module/library/class, it would be great\nif two versions of the solution are provided: One without the lexer module, and one with.\n\n\nThe simple programming language to be analyzed is more or less a subset of [[C]]. It supports the following tokens:\n\n;Operators\n\n:::{| class=\"wikitable\"\n|-\n! Name !! Common name !! Character sequence\n|-\n| Op_multiply || multiply || *\n|-\n| Op_divide || divide || /\n|-\n| Op_mod || mod || %\n|-\n| Op_add || plus || +\n|-\n| Op_subtract || minus || -\n|-\n| Op_negate || unary minus || -\n|-\n| Op_less || less than || <\n|-\n| Op_lessequal || less than or equal || <=\n|-\n| Op_greater || greater than || >\n|-\n| Op_greaterequal || greater than or equal || >=\n|-\n| Op_equal || equal || ==\n|-\n| Op_notequal || not equal || !=\n|-\n| Op_not || unary not || !\n|-\n| Op_assign || assignment || =\n|-\n| Op_and || logical and || &&\n|-\n| Op_or || logical or || \u00a6\u00a6\n|}\n\n* The - token should always be interpreted as Op_subtract by the lexer. Turning some Op_subtract into Op_negate will be the job of the syntax analyzer, which is not part of this task.\n\n;Symbols\n\n:::{| class=\"wikitable\"\n|-\n! Name !! Common name !! Character\n|-\n| LeftParen || left parenthesis || (\n|-\n| RightParen || right parenthesis || )\n|-\n| LeftBrace || left brace || {\n|-\n| RightBrace || right brace || }\n|-\n| Semicolon || semi-colon || ;\n|-\n| Comma || comma || ,\n|}\n\n;Keywords\n\n:::{| class=\"wikitable\"\n|-\n! Name || Character sequence\n|-\n| Keyword_if || if\n|-\n| Keyword_else || else\n|-\n| Keyword_while || while\n|-\n| Keyword_print || print\n|-\n| Keyword_putc || putc\n|}\n\n;Identifiers and literals\n\nThese differ from the the previous tokens, in that each occurrence of them has a value associated with it.\n\n:::{| class=\"wikitable\"\n|-\n! Name\n! Common name\n! Format description\n! Format regex\n! Value\n|-\n| Identifier\n| identifier\n| one or more letter/number/underscore characters, but not starting with a number\n| [_a-zA-Z][_a-zA-Z0-9]*\n| as is\n|-\n| Integer\n| integer literal\n| one or more digits\n| [0-9]+\n| as is, interpreted as a number\n|-\n| Integer\n| char literal\n| exactly one character (anything except newline or single quote) or one of the allowed escape sequences, enclosed by single quotes\n| '([^'\\n]|\\\\n|\\\\\\\\)'\n| the ASCII code point number of the character, e.g. 65 for 'A' and 10 for '\\n'\n|-\n| String\n| string literal\n| zero or more characters (anything except newline or double quote), enclosed by double quotes\n| \"[^\"\\n]*\"\n| the characters without the double quotes and with escape sequences converted\n|}\n\n* For char and string literals, the \\n escape sequence is supported to represent a new-line character.\n* For char and string literals, to represent a backslash, use \\\\.\n* No other special sequences are supported. This means that:\n** Char literals cannot represent a single quote character (value 39).\n** String literals cannot represent strings containing double quote characters.\n\n;Zero-width tokens\n\n:::{| class=\"wikitable\"\n|-\n! Name || Location\n|-\n| End_of_input || when the end of the input stream is reached\n|}\n\n;White space\n\n* Zero or more whitespace characters, or comments enclosed in /* ... */, are allowed between any two tokens, with the exceptions noted below.\n* \"Longest token matching\" is used to resolve conflicts (e.g., in order to match '''<=''' as a single token rather than the two tokens '''<''' and '''=''').\n* Whitespace is ''required'' between two tokens that have an alphanumeric character or underscore at the edge.\n** This means: keywords, identifiers, and integer literals.\n** e.g. ifprint is recognized as an identifier, instead of the keywords if and print.\n** e.g. 42fred is invalid, and neither recognized as a number nor an identifier.\n* Whitespace is ''not allowed'' inside of tokens (except for chars and strings where they are part of the value).\n** e.g. & & is invalid, and not interpreted as the && operator.\n\nFor example, the following two program fragments are equivalent, and should produce the same token stream except for the line and column positions:\n\n* if ( p /* meaning n is prime */ ) {\n print ( n , \" \" ) ;\n count = count + 1 ; /* number of primes found so far */\n}\n* if(p){print(n,\" \");count=count+1;}\n\n;Complete list of token names\n\n\nEnd_of_input Op_multiply Op_divide Op_mod Op_add Op_subtract\nOp_negate Op_not Op_less Op_lessequal Op_greater Op_greaterequal\nOp_equal Op_notequal Op_assign Op_and Op_or Keyword_if\nKeyword_else Keyword_while Keyword_print Keyword_putc LeftParen RightParen\nLeftBrace RightBrace Semicolon Comma Identifier Integer\nString\n\n\n\nThe program output should be a sequence of lines, each consisting of the following whitespace-separated fields:\n\n# the line number where the token starts\n# the column number where the token starts\n# the token name\n# the token value (only for Identifier, Integer, and String tokens)\n# the number of spaces between fields is up to you. Neatly aligned is nice, but not a requirement.\n\n\nThis task is intended to be used as part of a pipeline, with the other compiler tasks - for example:\nlex < hello.t | parse | gen | vm\n\nOr possibly:\nlex hello.t lex.out\nparse lex.out parse.out\ngen parse.out gen.out\nvm gen.out\n\nThis implies that the output of this task (the lexical analyzer) should be suitable as input to any of the Syntax Analyzer task programs.\n\n\nThe following error conditions should be caught:\n\n:::{| class=\"wikitable\"\n|-\n! Error\n! Example\n|-\n| Empty character constant\n| ''\n|-\n| Unknown escape sequence.\n| \\r\n|-\n| Multi-character constant.\n| 'xx'\n|-\n| End-of-file in comment. Closing comment characters not found.\n|-\n| End-of-file while scanning string literal. Closing string character not found.\n|-\n| End-of-line while scanning string literal. Closing string character not found before end-of-line.\n|-\n| Unrecognized character.\n| |\n|-\n| Invalid number. Starts like a number, but ends in non-numeric characters.\n| 123abc\n|}\n\n:{| class=\"wikitable\"\n|-\n! Input\n! Output\n|-\n| style=\"vertical-align:top\" |\nTest Case 1:\n/*\n Hello world\n */\nprint(\"Hello, World!\\n\");\n\n| style=\"vertical-align:top\" |\n\n 4 1 Keyword_print\n 4 6 LeftParen\n 4 7 String \"Hello, World!\\n\"\n 4 24 RightParen\n 4 25 Semicolon\n 5 1 End_of_input\n\n\n|-\n| style=\"vertical-align:top\" |\nTest Case 2:\n/*\n Show Ident and Integers\n */\nphoenix_number = 142857;\nprint(phoenix_number, \"\\n\");\n\n| style=\"vertical-align:top\" |\n\n 4 1 Identifier phoenix_number\n 4 16 Op_assign\n 4 18 Integer 142857\n 4 24 Semicolon\n 5 1 Keyword_print\n 5 6 LeftParen\n 5 7 Identifier phoenix_number\n 5 21 Comma\n 5 23 String \"\\n\"\n 5 27 RightParen\n 5 28 Semicolon\n 6 1 End_of_input\n\n\n|-\n| style=\"vertical-align:top\" |\nTest Case 3:\n/*\n All lexical tokens - not syntactically correct, but that will\n have to wait until syntax analysis\n */\n/* Print */ print /* Sub */ -\n/* Putc */ putc /* Lss */ <\n/* If */ if /* Gtr */ >\n/* Else */ else /* Leq */ <=\n/* While */ while /* Geq */ >=\n/* Lbrace */ { /* Eq */ ==\n/* Rbrace */ } /* Neq */ !=\n/* Lparen */ ( /* And */ &&\n/* Rparen */ ) /* Or */ ||\n/* Uminus */ - /* Semi */ ;\n/* Not */ ! /* Comma */ ,\n/* Mul */ * /* Assign */ =\n/* Div */ / /* Integer */ 42\n/* Mod */ % /* String */ \"String literal\"\n/* Add */ + /* Ident */ variable_name\n/* character literal */ '\\n'\n/* character literal */ '\\\\'\n/* character literal */ ' '\n\n| style=\"vertical-align:top\" |\n\n 5 16 Keyword_print\n 5 40 Op_subtract\n 6 16 Keyword_putc\n 6 40 Op_less\n 7 16 Keyword_if\n 7 40 Op_greater\n 8 16 Keyword_else\n 8 40 Op_lessequal\n 9 16 Keyword_while\n 9 40 Op_greaterequal\n 10 16 LeftBrace\n 10 40 Op_equal\n 11 16 RightBrace\n 11 40 Op_notequal\n 12 16 LeftParen\n 12 40 Op_and\n 13 16 RightParen\n 13 40 Op_or\n 14 16 Op_subtract\n 14 40 Semicolon\n 15 16 Op_not\n 15 40 Comma\n 16 16 Op_multiply\n 16 40 Op_assign\n 17 16 Op_divide\n 17 40 Integer 42\n 18 16 Op_mod\n 18 40 String \"String literal\"\n 19 16 Op_add\n 19 40 Identifier variable_name\n 20 26 Integer 10\n 21 26 Integer 92\n 22 26 Integer 32\n 23 1 End_of_input\n\n\n|-\n| style=\"vertical-align:top\" |\nTest Case 4:\n/*** test printing, embedded \\n and comments with lots of '*' ***/\nprint(42);\nprint(\"\\nHello World\\nGood Bye\\nok\\n\");\nprint(\"Print a slash n - \\\\n.\\n\");\n\n| style=\"vertical-align:top\" |\n\n 2 1 Keyword_print\n 2 6 LeftParen\n 2 7 Integer 42\n 2 9 RightParen\n 2 10 Semicolon\n 3 1 Keyword_print\n 3 6 LeftParen\n 3 7 String \"\\nHello World\\nGood Bye\\nok\\n\"\n 3 38 RightParen\n 3 39 Semicolon\n 4 1 Keyword_print\n 4 6 LeftParen\n 4 7 String \"Print a slash n - \\\\n.\\n\"\n 4 33 RightParen\n 4 34 Semicolon\n 5 1 End_of_input\n\n\n|}\n\n;Additional examples\nYour solution should pass all the test cases above and the additional tests found '''Here'''.\n\n\nThe 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": "\n/*\n Token: type, value, line, pos\n*/\n\nconst TokenType = {\n Keyword_if: 1, Keyword_else: 2, Keyword_print: 3, Keyword_putc: 4, Keyword_while: 5,\n Op_add: 6, Op_and: 7, Op_assign: 8, Op_divide: 9, Op_equal: 10, Op_greater: 11,\n Op_greaterequal: 12, Op_less: 13, Op_Lessequal: 14, Op_mod: 15, Op_multiply: 16, Op_not: 17,\n Op_notequal: 18, Op_or: 19, Op_subtract: 20,\n Integer: 21, String: 22, Identifier: 23,\n Semicolon: 24, Comma: 25,\n LeftBrace: 26, RightBrace: 27,\n LeftParen: 28, RightParen: 29,\n End_of_input: 99\n}\n\nclass Lexer {\n constructor(source) {\n this.source = source\n this.pos = 1 // position in line\n this.position = 0 // position in source\n this.line = 1\n this.chr = this.source.charAt(0)\n this.keywords = {\n \"if\": TokenType.Keyword_if,\n \"else\": TokenType.Keyword_else,\n \"print\": TokenType.Keyword_print,\n \"putc\": TokenType.Keyword_putc,\n \"while\": TokenType.Keyword_while\n }\n }\n getNextChar() {\n this.pos++\n this.position++\n \n if (this.position >= this.source.length) {\n this.chr = undefined\n return this.chr\n }\n this.chr = this.source.charAt(this.position)\n if (this.chr === '\\n') {\n this.line++\n this.pos = 0\n }\n return this.chr\n }\n error(line, pos, message) {\n if (line > 0 && pos > 0) {\n console.log(message + \" in line \" + line + \", pos \" + pos + \"\\n\")\n } else {\n console.log(message)\n }\n process.exit(1)\n }\n follow(expect, ifyes, ifno, line, pos) {\n if (this.getNextChar() === expect) {\n this.getNextChar()\n return { type: ifyes, value: \"\", line, pos }\n }\n if (ifno === TokenType.End_of_input) {\n this.error(line, pos, \"follow: unrecognized character: (\" + this.chr.charCodeAt(0) + \") '\" + this.chr + \"'\")\n }\n return { type: ifno, value: \"\", line, pos }\n }\n div_or_comment(line, pos) {\n if (this.getNextChar() !== '*') {\n return { type: TokenType.Op_divide, value: \"/\", line, pos }\n }\n this.getNextChar()\n while (true) { \n if (this.chr === '\\u0000') {\n this.error(line, pos, \"EOF in comment\")\n } else if (this.chr === '*') {\n if (this.getNextChar() === '/') {\n this.getNextChar()\n return this.getToken()\n }\n } else {\n this.getNextChar()\n }\n }\n }\n char_lit(line, pos) {\n let c = this.getNextChar() // skip opening quote\n let n = c.charCodeAt(0)\n if (c === \"\\'\") {\n this.error(line, pos, \"empty character constant\")\n } else if (c === \"\\\\\") {\n c = this.getNextChar()\n if (c == \"n\") {\n n = 10\n } else if (c === \"\\\\\") {\n n = 92\n } else {\n this.error(line, pos, \"unknown escape sequence \\\\\" + c)\n }\n }\n if (this.getNextChar() !== \"\\'\") {\n this.error(line, pos, \"multi-character constant\")\n }\n this.getNextChar()\n return { type: TokenType.Integer, value: n, line, pos }\n }\n string_lit(start, line, pos) {\n let value = \"\"\n while (this.getNextChar() !== start) {\n if (this.chr === undefined) {\n this.error(line, pos, \"EOF while scanning string literal\")\n }\n if (this.chr === \"\\n\") {\n this.error(line, pos, \"EOL while scanning string literal\")\n }\n value += this.chr\n }\n this.getNextChar()\n return { type: TokenType.String, value, line, pos }\n }\n identifier_or_integer(line, pos) {\n let is_number = true\n let text = \"\"\n \n while (/\\w/.test(this.chr) || this.chr === '_') {\n text += this.chr\n if (!/\\d/.test(this.chr)) {\n is_number = false\n }\n this.getNextChar()\n }\n if (text === \"\") {\n this.error(line, pos, \"identifer_or_integer unrecopgnized character: follow: unrecognized character: (\" + this.chr.charCodeAt(0) + \") '\" + this.chr + \"'\")\n }\n \n if (/\\d/.test(text.charAt(0))) {\n if (!is_number) {\n this.error(line, pos, \"invaslid number: \" + text)\n }\n return { type: TokenType.Integer, value: text, line, pos }\n }\n \n if (text in this.keywords) {\n return { type: this.keywords[text], value: \"\", line, pos }\n }\n return { type: TokenType.Identifier, value: text, line, pos }\n }\n getToken() {\n let pos, line\n // Ignore whitespaces\n while (/\\s/.test(this.chr)) { this.getNextChar() }\n line = this.line; pos = this.pos\n switch (this.chr) {\n case undefined: return { type: TokenType.End_of_input, value: \"\", line: this.line, pos: this.pos }\n case \"/\": return this.div_or_comment(line, pos)\n case \"\\'\": return this.char_lit(line, pos)\n case \"\\\"\": return this.string_lit(this.chr, line, pos)\n\n case \"<\": return this.follow(\"=\", TokenType.Op_lessequal, TokenType.Op_less, line, pos)\n case \">\": return this.follow(\"=\", TokenType.Op_greaterequal, TokenType.Op_greater, line, pos)\n case \"=\": return this.follow(\"=\", TokenType.Op_equal, TokenType.Op_assign, line, pos)\n case \"!\": return this.follow(\"=\", TokenType.Op_notequal, TokenType.Op_not, line, pos)\n case \"&\": return this.follow(\"&\", TokenType.Op_and, TokenType.End_of_input, line, pos)\n case \"|\": return this.follow(\"|\", TokenType.Op_or, TokenType.End_of_input, line, pos)\n\n case \"{\": this.getNextChar(); return { type: TokenType.LeftBrace, value: \"{\", line, pos }\n case \"}\": this.getNextChar(); return { type: TokenType.RightBrace, value: \"}\", line, pos }\n case \"(\": this.getNextChar(); return { type: TokenType.LeftParen, value: \"(\", line, pos }\n case \")\": this.getNextChar(); return { type: TokenType.RightParen, value: \")\", line, pos }\n case \"+\": this.getNextChar(); return { type: TokenType.Op_add, value: \"+\", line, pos }\n case \"-\": this.getNextChar(); return { type: TokenType.Op_subtract, value: \"-\", line, pos }\n case \"*\": this.getNextChar(); return { type: TokenType.Op_multiply, value: \"*\", line, pos }\n case \"%\": this.getNextChar(); return { type: TokenType.Op_mod, value: \"%\", line, pos }\n case \";\": this.getNextChar(); return { type: TokenType.Semicolon, value: \";\", line, pos }\n case \",\": this.getNextChar(); return { type: TokenType.Comma, value: \",\", line, pos }\n\n default: return this.identifier_or_integer(line, pos)\n }\n }\n /*\n https://stackoverflow.com/questions/9907419/how-to-get-a-key-in-a-javascript-object-by-its-value\n */\n getTokenType(value) {\n return Object.keys(TokenType).find(key => TokenType[key] === value)\n }\n printToken(t) {\n let result = (\" \" + t.line).substr(t.line.toString().length)\n result += (\" \" + t.pos).substr(t.pos.toString().length)\n result += (\" \" + this.getTokenType(t.type) + \" \").substr(0, 16)\n switch (t.type) {\n case TokenType.Integer:\n result += \" \" + t.value\n break;\n case TokenType.Identifier:\n result += \" \" + t.value\n break;\n case TokenType.String:\n result += \" \\\"\"+ t.value + \"\\\"\"\n break;\n }\n console.log(result)\n }\n printTokens() {\n let t\n while ((t = this.getToken()).type !== TokenType.End_of_input) {\n this.printToken(t)\n }\n this.printToken(t)\n }\n}\nconst fs = require(\"fs\")\nfs.readFile(process.argv[2], \"utf8\", (err, data) => {\n l = new Lexer(data)\n l.printTokens()\n})\n"} +{"title": "Compiler/lexical analyzer", "language": "Python", "task": "Definition from [https://en.wikipedia.org/wiki/Lexical_analysis Wikipedia]:\n\n: ''Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified \"meaning\"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though \"scanner\" is also used to refer to the first stage of a lexer).''\n\n\nCreate a lexical analyzer for the simple programming language specified below. The\nprogram should read input from a file and/or stdin, and write output to a file and/or\nstdout. If the language being used has a lexer module/library/class, it would be great\nif two versions of the solution are provided: One without the lexer module, and one with.\n\n\nThe simple programming language to be analyzed is more or less a subset of [[C]]. It supports the following tokens:\n\n;Operators\n\n:::{| class=\"wikitable\"\n|-\n! Name !! Common name !! Character sequence\n|-\n| Op_multiply || multiply || *\n|-\n| Op_divide || divide || /\n|-\n| Op_mod || mod || %\n|-\n| Op_add || plus || +\n|-\n| Op_subtract || minus || -\n|-\n| Op_negate || unary minus || -\n|-\n| Op_less || less than || <\n|-\n| Op_lessequal || less than or equal || <=\n|-\n| Op_greater || greater than || >\n|-\n| Op_greaterequal || greater than or equal || >=\n|-\n| Op_equal || equal || ==\n|-\n| Op_notequal || not equal || !=\n|-\n| Op_not || unary not || !\n|-\n| Op_assign || assignment || =\n|-\n| Op_and || logical and || &&\n|-\n| Op_or || logical or || \u00a6\u00a6\n|}\n\n* The - token should always be interpreted as Op_subtract by the lexer. Turning some Op_subtract into Op_negate will be the job of the syntax analyzer, which is not part of this task.\n\n;Symbols\n\n:::{| class=\"wikitable\"\n|-\n! Name !! Common name !! Character\n|-\n| LeftParen || left parenthesis || (\n|-\n| RightParen || right parenthesis || )\n|-\n| LeftBrace || left brace || {\n|-\n| RightBrace || right brace || }\n|-\n| Semicolon || semi-colon || ;\n|-\n| Comma || comma || ,\n|}\n\n;Keywords\n\n:::{| class=\"wikitable\"\n|-\n! Name || Character sequence\n|-\n| Keyword_if || if\n|-\n| Keyword_else || else\n|-\n| Keyword_while || while\n|-\n| Keyword_print || print\n|-\n| Keyword_putc || putc\n|}\n\n;Identifiers and literals\n\nThese differ from the the previous tokens, in that each occurrence of them has a value associated with it.\n\n:::{| class=\"wikitable\"\n|-\n! Name\n! Common name\n! Format description\n! Format regex\n! Value\n|-\n| Identifier\n| identifier\n| one or more letter/number/underscore characters, but not starting with a number\n| [_a-zA-Z][_a-zA-Z0-9]*\n| as is\n|-\n| Integer\n| integer literal\n| one or more digits\n| [0-9]+\n| as is, interpreted as a number\n|-\n| Integer\n| char literal\n| exactly one character (anything except newline or single quote) or one of the allowed escape sequences, enclosed by single quotes\n| '([^'\\n]|\\\\n|\\\\\\\\)'\n| the ASCII code point number of the character, e.g. 65 for 'A' and 10 for '\\n'\n|-\n| String\n| string literal\n| zero or more characters (anything except newline or double quote), enclosed by double quotes\n| \"[^\"\\n]*\"\n| the characters without the double quotes and with escape sequences converted\n|}\n\n* For char and string literals, the \\n escape sequence is supported to represent a new-line character.\n* For char and string literals, to represent a backslash, use \\\\.\n* No other special sequences are supported. This means that:\n** Char literals cannot represent a single quote character (value 39).\n** String literals cannot represent strings containing double quote characters.\n\n;Zero-width tokens\n\n:::{| class=\"wikitable\"\n|-\n! Name || Location\n|-\n| End_of_input || when the end of the input stream is reached\n|}\n\n;White space\n\n* Zero or more whitespace characters, or comments enclosed in /* ... */, are allowed between any two tokens, with the exceptions noted below.\n* \"Longest token matching\" is used to resolve conflicts (e.g., in order to match '''<=''' as a single token rather than the two tokens '''<''' and '''=''').\n* Whitespace is ''required'' between two tokens that have an alphanumeric character or underscore at the edge.\n** This means: keywords, identifiers, and integer literals.\n** e.g. ifprint is recognized as an identifier, instead of the keywords if and print.\n** e.g. 42fred is invalid, and neither recognized as a number nor an identifier.\n* Whitespace is ''not allowed'' inside of tokens (except for chars and strings where they are part of the value).\n** e.g. & & is invalid, and not interpreted as the && operator.\n\nFor example, the following two program fragments are equivalent, and should produce the same token stream except for the line and column positions:\n\n* if ( p /* meaning n is prime */ ) {\n print ( n , \" \" ) ;\n count = count + 1 ; /* number of primes found so far */\n}\n* if(p){print(n,\" \");count=count+1;}\n\n;Complete list of token names\n\n\nEnd_of_input Op_multiply Op_divide Op_mod Op_add Op_subtract\nOp_negate Op_not Op_less Op_lessequal Op_greater Op_greaterequal\nOp_equal Op_notequal Op_assign Op_and Op_or Keyword_if\nKeyword_else Keyword_while Keyword_print Keyword_putc LeftParen RightParen\nLeftBrace RightBrace Semicolon Comma Identifier Integer\nString\n\n\n\nThe program output should be a sequence of lines, each consisting of the following whitespace-separated fields:\n\n# the line number where the token starts\n# the column number where the token starts\n# the token name\n# the token value (only for Identifier, Integer, and String tokens)\n# the number of spaces between fields is up to you. Neatly aligned is nice, but not a requirement.\n\n\nThis task is intended to be used as part of a pipeline, with the other compiler tasks - for example:\nlex < hello.t | parse | gen | vm\n\nOr possibly:\nlex hello.t lex.out\nparse lex.out parse.out\ngen parse.out gen.out\nvm gen.out\n\nThis implies that the output of this task (the lexical analyzer) should be suitable as input to any of the Syntax Analyzer task programs.\n\n\nThe following error conditions should be caught:\n\n:::{| class=\"wikitable\"\n|-\n! Error\n! Example\n|-\n| Empty character constant\n| ''\n|-\n| Unknown escape sequence.\n| \\r\n|-\n| Multi-character constant.\n| 'xx'\n|-\n| End-of-file in comment. Closing comment characters not found.\n|-\n| End-of-file while scanning string literal. Closing string character not found.\n|-\n| End-of-line while scanning string literal. Closing string character not found before end-of-line.\n|-\n| Unrecognized character.\n| |\n|-\n| Invalid number. Starts like a number, but ends in non-numeric characters.\n| 123abc\n|}\n\n:{| class=\"wikitable\"\n|-\n! Input\n! Output\n|-\n| style=\"vertical-align:top\" |\nTest Case 1:\n/*\n Hello world\n */\nprint(\"Hello, World!\\n\");\n\n| style=\"vertical-align:top\" |\n\n 4 1 Keyword_print\n 4 6 LeftParen\n 4 7 String \"Hello, World!\\n\"\n 4 24 RightParen\n 4 25 Semicolon\n 5 1 End_of_input\n\n\n|-\n| style=\"vertical-align:top\" |\nTest Case 2:\n/*\n Show Ident and Integers\n */\nphoenix_number = 142857;\nprint(phoenix_number, \"\\n\");\n\n| style=\"vertical-align:top\" |\n\n 4 1 Identifier phoenix_number\n 4 16 Op_assign\n 4 18 Integer 142857\n 4 24 Semicolon\n 5 1 Keyword_print\n 5 6 LeftParen\n 5 7 Identifier phoenix_number\n 5 21 Comma\n 5 23 String \"\\n\"\n 5 27 RightParen\n 5 28 Semicolon\n 6 1 End_of_input\n\n\n|-\n| style=\"vertical-align:top\" |\nTest Case 3:\n/*\n All lexical tokens - not syntactically correct, but that will\n have to wait until syntax analysis\n */\n/* Print */ print /* Sub */ -\n/* Putc */ putc /* Lss */ <\n/* If */ if /* Gtr */ >\n/* Else */ else /* Leq */ <=\n/* While */ while /* Geq */ >=\n/* Lbrace */ { /* Eq */ ==\n/* Rbrace */ } /* Neq */ !=\n/* Lparen */ ( /* And */ &&\n/* Rparen */ ) /* Or */ ||\n/* Uminus */ - /* Semi */ ;\n/* Not */ ! /* Comma */ ,\n/* Mul */ * /* Assign */ =\n/* Div */ / /* Integer */ 42\n/* Mod */ % /* String */ \"String literal\"\n/* Add */ + /* Ident */ variable_name\n/* character literal */ '\\n'\n/* character literal */ '\\\\'\n/* character literal */ ' '\n\n| style=\"vertical-align:top\" |\n\n 5 16 Keyword_print\n 5 40 Op_subtract\n 6 16 Keyword_putc\n 6 40 Op_less\n 7 16 Keyword_if\n 7 40 Op_greater\n 8 16 Keyword_else\n 8 40 Op_lessequal\n 9 16 Keyword_while\n 9 40 Op_greaterequal\n 10 16 LeftBrace\n 10 40 Op_equal\n 11 16 RightBrace\n 11 40 Op_notequal\n 12 16 LeftParen\n 12 40 Op_and\n 13 16 RightParen\n 13 40 Op_or\n 14 16 Op_subtract\n 14 40 Semicolon\n 15 16 Op_not\n 15 40 Comma\n 16 16 Op_multiply\n 16 40 Op_assign\n 17 16 Op_divide\n 17 40 Integer 42\n 18 16 Op_mod\n 18 40 String \"String literal\"\n 19 16 Op_add\n 19 40 Identifier variable_name\n 20 26 Integer 10\n 21 26 Integer 92\n 22 26 Integer 32\n 23 1 End_of_input\n\n\n|-\n| style=\"vertical-align:top\" |\nTest Case 4:\n/*** test printing, embedded \\n and comments with lots of '*' ***/\nprint(42);\nprint(\"\\nHello World\\nGood Bye\\nok\\n\");\nprint(\"Print a slash n - \\\\n.\\n\");\n\n| style=\"vertical-align:top\" |\n\n 2 1 Keyword_print\n 2 6 LeftParen\n 2 7 Integer 42\n 2 9 RightParen\n 2 10 Semicolon\n 3 1 Keyword_print\n 3 6 LeftParen\n 3 7 String \"\\nHello World\\nGood Bye\\nok\\n\"\n 3 38 RightParen\n 3 39 Semicolon\n 4 1 Keyword_print\n 4 6 LeftParen\n 4 7 String \"Print a slash n - \\\\n.\\n\"\n 4 33 RightParen\n 4 34 Semicolon\n 5 1 End_of_input\n\n\n|}\n\n;Additional examples\nYour solution should pass all the test cases above and the additional tests found '''Here'''.\n\n\nThe 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": "from __future__ import print_function\nimport sys\n\n# following two must remain in the same order\n\ntk_EOI, tk_Mul, tk_Div, tk_Mod, tk_Add, tk_Sub, tk_Negate, tk_Not, tk_Lss, tk_Leq, tk_Gtr, \\\ntk_Geq, tk_Eq, tk_Neq, tk_Assign, tk_And, tk_Or, tk_If, tk_Else, tk_While, tk_Print, \\\ntk_Putc, tk_Lparen, tk_Rparen, tk_Lbrace, tk_Rbrace, tk_Semi, tk_Comma, tk_Ident, \\\ntk_Integer, tk_String = range(31)\n\nall_syms = [\"End_of_input\", \"Op_multiply\", \"Op_divide\", \"Op_mod\", \"Op_add\", \"Op_subtract\",\n \"Op_negate\", \"Op_not\", \"Op_less\", \"Op_lessequal\", \"Op_greater\", \"Op_greaterequal\",\n \"Op_equal\", \"Op_notequal\", \"Op_assign\", \"Op_and\", \"Op_or\", \"Keyword_if\",\n \"Keyword_else\", \"Keyword_while\", \"Keyword_print\", \"Keyword_putc\", \"LeftParen\",\n \"RightParen\", \"LeftBrace\", \"RightBrace\", \"Semicolon\", \"Comma\", \"Identifier\",\n \"Integer\", \"String\"]\n\n# single character only symbols\nsymbols = { '{': tk_Lbrace, '}': tk_Rbrace, '(': tk_Lparen, ')': tk_Rparen, '+': tk_Add, '-': tk_Sub,\n '*': tk_Mul, '%': tk_Mod, ';': tk_Semi, ',': tk_Comma }\n\nkey_words = {'if': tk_If, 'else': tk_Else, 'print': tk_Print, 'putc': tk_Putc, 'while': tk_While}\n\nthe_ch = \" \" # dummy first char - but it must be a space\nthe_col = 0\nthe_line = 1\ninput_file = None\n\n#*** show error and exit\ndef error(line, col, msg):\n print(line, col, msg)\n exit(1)\n\n#*** get the next character from the input\ndef next_ch():\n global the_ch, the_col, the_line\n\n the_ch = input_file.read(1)\n the_col += 1\n if the_ch == '\\n':\n the_line += 1\n the_col = 0\n return the_ch\n\n#*** 'x' - character constants\ndef char_lit(err_line, err_col):\n n = ord(next_ch()) # skip opening quote\n if the_ch == '\\'':\n error(err_line, err_col, \"empty character constant\")\n elif the_ch == '\\\\':\n next_ch()\n if the_ch == 'n':\n n = 10\n elif the_ch == '\\\\':\n n = ord('\\\\')\n else:\n error(err_line, err_col, \"unknown escape sequence \\\\%c\" % (the_ch))\n if next_ch() != '\\'':\n error(err_line, err_col, \"multi-character constant\")\n next_ch()\n return tk_Integer, err_line, err_col, n\n\n#*** process divide or comments\ndef div_or_cmt(err_line, err_col):\n if next_ch() != '*':\n return tk_Div, err_line, err_col\n\n # comment found\n next_ch()\n while True:\n if the_ch == '*':\n if next_ch() == '/':\n next_ch()\n return gettok()\n elif len(the_ch) == 0:\n error(err_line, err_col, \"EOF in comment\")\n else:\n next_ch()\n\n#*** \"string\"\ndef string_lit(start, err_line, err_col):\n global the_ch\n text = \"\"\n\n while next_ch() != start:\n if len(the_ch) == 0:\n error(err_line, err_col, \"EOF while scanning string literal\")\n if the_ch == '\\n':\n error(err_line, err_col, \"EOL while scanning string literal\")\n if the_ch == '\\\\':\n next_ch()\n if the_ch != 'n':\n error(err_line, err_col, \"escape sequence unknown \\\\%c\" % the_ch)\n the_ch = '\\n'\n text += the_ch\n\n next_ch()\n return tk_String, err_line, err_col, text\n\n#*** handle identifiers and integers\ndef ident_or_int(err_line, err_col):\n is_number = True\n text = \"\"\n\n while the_ch.isalnum() or the_ch == '_':\n text += the_ch\n if not the_ch.isdigit():\n is_number = False\n next_ch()\n\n if len(text) == 0:\n error(err_line, err_col, \"ident_or_int: unrecognized character: (%d) '%c'\" % (ord(the_ch), the_ch))\n\n if text[0].isdigit():\n if not is_number:\n error(err_line, err_col, \"invalid number: %s\" % (text))\n n = int(text)\n return tk_Integer, err_line, err_col, n\n\n if text in key_words:\n return key_words[text], err_line, err_col\n\n return tk_Ident, err_line, err_col, text\n\n#*** look ahead for '>=', etc.\ndef follow(expect, ifyes, ifno, err_line, err_col):\n if next_ch() == expect:\n next_ch()\n return ifyes, err_line, err_col\n\n if ifno == tk_EOI:\n error(err_line, err_col, \"follow: unrecognized character: (%d) '%c'\" % (ord(the_ch), the_ch))\n\n return ifno, err_line, err_col\n\n#*** return the next token type\ndef gettok():\n while the_ch.isspace():\n next_ch()\n\n err_line = the_line\n err_col = the_col\n\n if len(the_ch) == 0: return tk_EOI, err_line, err_col\n elif the_ch == '/': return div_or_cmt(err_line, err_col)\n elif the_ch == '\\'': return char_lit(err_line, err_col)\n elif the_ch == '<': return follow('=', tk_Leq, tk_Lss, err_line, err_col)\n elif the_ch == '>': return follow('=', tk_Geq, tk_Gtr, err_line, err_col)\n elif the_ch == '=': return follow('=', tk_Eq, tk_Assign, err_line, err_col)\n elif the_ch == '!': return follow('=', tk_Neq, tk_Not, err_line, err_col)\n elif the_ch == '&': return follow('&', tk_And, tk_EOI, err_line, err_col)\n elif the_ch == '|': return follow('|', tk_Or, tk_EOI, err_line, err_col)\n elif the_ch == '\"': return string_lit(the_ch, err_line, err_col)\n elif the_ch in symbols:\n sym = symbols[the_ch]\n next_ch()\n return sym, err_line, err_col\n else: return ident_or_int(err_line, err_col)\n\n#*** main driver\ninput_file = sys.stdin\nif len(sys.argv) > 1:\n try:\n input_file = open(sys.argv[1], \"r\", 4096)\n except IOError as e:\n error(0, 0, \"Can't open %s\" % sys.argv[1])\n\nwhile True:\n t = gettok()\n tok = t[0]\n line = t[1]\n col = t[2]\n\n print(\"%5d %5d %-14s\" % (line, col, all_syms[tok]), end='')\n\n if tok == tk_Integer: print(\" %5d\" % (t[3]))\n elif tok == tk_Ident: print(\" %s\" % (t[3]))\n elif tok == tk_String: print(' \"%s\"' % (t[3]))\n else: print(\"\")\n\n if tok == tk_EOI:\n break"} +{"title": "Compiler/syntax analyzer", "language": "C", "task": "A Syntax analyzer transforms a token stream (from the Lexical analyzer)\ninto a Syntax tree, based on a grammar.\n\n\nTake the output from the Lexical analyzer task,\nand convert it to an [https://en.wikipedia.org/wiki/Abstract_syntax_tree Abstract Syntax Tree (AST)],\nbased on the grammar below. The output should be in a flattened format.\n\nThe program should read input from a file and/or stdin, and write output to a file and/or\nstdout. If the language being used has a parser module/library/class, it would be great\nif two versions of the solution are provided: One without the parser module, and one\nwith.\n\n\nThe simple programming language to be analyzed is more or less a (very tiny) subset of\n[[C]]. The formal grammar in\n[https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_Form Extended Backus-Naur Form (EBNF)]:\n\n\n stmt_list = {stmt} ;\n\n stmt = ';'\n | Identifier '=' expr ';'\n | 'while' paren_expr stmt\n | 'if' paren_expr stmt ['else' stmt]\n | 'print' '(' prt_list ')' ';'\n | 'putc' paren_expr ';'\n | '{' stmt_list '}'\n ;\n\n paren_expr = '(' expr ')' ;\n\n prt_list = (string | expr) {',' (String | expr)} ;\n\n expr = and_expr {'||' and_expr} ;\n and_expr = equality_expr {'&&' equality_expr} ;\n equality_expr = relational_expr [('==' | '!=') relational_expr] ;\n relational_expr = addition_expr [('<' | '<=' | '>' | '>=') addition_expr] ;\n addition_expr = multiplication_expr {('+' | '-') multiplication_expr} ;\n multiplication_expr = primary {('*' | '/' | '%') primary } ;\n primary = Identifier\n | Integer\n | '(' expr ')'\n | ('+' | '-' | '!') primary\n ;\n\nThe resulting AST should be formulated as a Binary Tree.\n\n;Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions\n\n lex < while.t > while.lex\n\n;Run one of the Syntax analyzer solutions:\n\n parse < while.lex > while.ast\n\n;The following table shows the input to lex, lex output, and the AST produced by the parser:\n\n{| class=\"wikitable\"\n|-\n! Input to lex\n! Output from lex, input to parse\n! Output from parse\n|-\n| style=\"vertical-align:top\" |\ncount = 1;\n while (count < 10) {\n print(\"count is: \", count, \"\\n\");\n count = count + 1;\n }\n\n| style=\"vertical-align:top\" |\n\n 1 1 Identifier count\n 1 7 Op_assign\n 1 9 Integer 1\n 1 10 Semicolon\n 2 1 Keyword_while\n 2 7 LeftParen\n 2 8 Identifier count\n 2 14 Op_less\n 2 16 Integer 10\n 2 18 RightParen\n 2 20 LeftBrace\n 3 5 Keyword_print\n 3 10 LeftParen\n 3 11 String \"count is: \"\n 3 23 Comma\n 3 25 Identifier count\n 3 30 Comma\n 3 32 String \"\\n\"\n 3 36 RightParen\n 3 37 Semicolon\n 4 5 Identifier count\n 4 11 Op_assign\n 4 13 Identifier count\n 4 19 Op_add\n 4 21 Integer 1\n 4 22 Semicolon\n 5 1 RightBrace\n 6 1 End_of_input\n\n\n| style=\"vertical-align:top\" |\n\nSequence\nSequence\n;\nAssign\nIdentifier count\nInteger 1\nWhile\nLess\nIdentifier count\nInteger 10\nSequence\nSequence\n;\nSequence\nSequence\nSequence\n;\nPrts\nString \"count is: \"\n;\nPrti\nIdentifier count\n;\nPrts\nString \"\\n\"\n;\nAssign\nIdentifier count\nAdd\nIdentifier count\nInteger 1\n\n|}\n\n;Specifications\n\n;List of node type names:\n\n\nIdentifier String Integer Sequence If Prtc Prts Prti While Assign Negate Not Multiply Divide Mod\nAdd Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or\n\n\nIn the text below, Null/Empty nodes are represented by \";\".\n\n;Non-terminal (internal) nodes:\n\nFor Operators, the following nodes should be created:\n\n Multiply Divide Mod Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or\n\nFor each of the above nodes, the left and right sub-nodes are the operands of the\nrespective operation.\n\nIn pseudo S-Expression format:\n\n (Operator expression expression)\n\nNegate, Not\n\nFor these node types, the left node is the operand, and the right node is null.\n\n (Operator expression ;)\n\nSequence - sub-nodes are either statements or Sequences.\n\nIf - left node is the expression, the right node is If node, with it's left node being the\nif-true statement part, and the right node being the if-false (else) statement part.\n\n (If expression (If statement else-statement))\n\nIf there is not an else, the tree becomes:\n\n (If expression (If statement ;))\n\nPrtc\n\n (Prtc (expression) ;)\n\nPrts\n\n (Prts (String \"the string\") ;)\n\nPrti\n\n (Prti (Integer 12345) ;)\n\nWhile - left node is the expression, the right node is the statement.\n\n (While expression statement)\n\nAssign - left node is the left-hand side of the assignment, the right node is the\nright-hand side of the assignment.\n\n (Assign Identifier expression)\n\nTerminal (leaf) nodes:\n\n Identifier: (Identifier ident_name)\n Integer: (Integer 12345)\n String: (String \"Hello World!\")\n \";\": Empty node\n\n;Some simple examples\nSequences denote a list node; they are used to represent a list. semicolon's represent a null node, e.g., the end of this path.\n\nThis simple program:\n\n a=11;\n\nProduces the following AST, encoded as a binary tree:\n\nUnder each non-leaf node are two '|' lines. The first represents the left sub-node, the second represents the right sub-node:\n\n (1) Sequence\n (2) |-- ;\n (3) |-- Assign\n (4) |-- Identifier: a\n (5) |-- Integer: 11\n\nIn flattened form:\n\n (1) Sequence\n (2) ;\n (3) Assign\n (4) Identifier a\n (5) Integer 11\n\n\nThis program:\n\n a=11;\n b=22;\n c=33;\n\nProduces the following AST:\n\n ( 1) Sequence\n ( 2) |-- Sequence\n ( 3) | |-- Sequence\n ( 4) | | |-- ;\n ( 5) | | |-- Assign\n ( 6) | | |-- Identifier: a\n ( 7) | | |-- Integer: 11\n ( 8) | |-- Assign\n ( 9) | |-- Identifier: b\n (10) | |-- Integer: 22\n (11) |-- Assign\n (12) |-- Identifier: c\n (13) |-- Integer: 33\n\nIn flattened form:\n\n ( 1) Sequence\n ( 2) Sequence\n ( 3) Sequence\n ( 4) ;\n ( 5) Assign\n ( 6) Identifier a\n ( 7) Integer 11\n ( 8) Assign\n ( 9) Identifier b\n (10) Integer 22\n (11) Assign\n (12) Identifier c\n (13) Integer 33\n\n;Pseudo-code for the parser. \n\nUses [https://www.engr.mun.ca/~theo/Misc/exp_parsing.htm Precedence Climbing] for expression parsing, and\n[https://en.wikipedia.org/wiki/Recursive_descent_parser Recursive Descent] for statement parsing. The AST is also built:\n\ndef expr(p)\n if tok is \"(\"\n x = paren_expr()\n elif tok in [\"-\", \"+\", \"!\"]\n gettok()\n y = expr(precedence of operator)\n if operator was \"+\"\n x = y\n else\n x = make_node(operator, y)\n elif tok is an Identifier\n x = make_leaf(Identifier, variable name)\n gettok()\n elif tok is an Integer constant\n x = make_leaf(Integer, integer value)\n gettok()\n else\n error()\n\n while tok is a binary operator and precedence of tok >= p\n save_tok = tok\n gettok()\n q = precedence of save_tok\n if save_tok is not right associative\n q += 1\n x = make_node(Operator save_tok represents, x, expr(q))\n\n return x\n\ndef paren_expr()\n expect(\"(\")\n x = expr(0)\n expect(\")\")\n return x\n\ndef stmt()\n t = NULL\n if accept(\"if\")\n e = paren_expr()\n s = stmt()\n t = make_node(If, e, make_node(If, s, accept(\"else\") ? stmt() : NULL))\n elif accept(\"putc\")\n t = make_node(Prtc, paren_expr())\n expect(\";\")\n elif accept(\"print\")\n expect(\"(\")\n repeat\n if tok is a string\n e = make_node(Prts, make_leaf(String, the string))\n gettok()\n else\n e = make_node(Prti, expr(0))\n\n t = make_node(Sequence, t, e)\n until not accept(\",\")\n expect(\")\")\n expect(\";\")\n elif tok is \";\"\n gettok()\n elif tok is an Identifier\n v = make_leaf(Identifier, variable name)\n gettok()\n expect(\"=\")\n t = make_node(Assign, v, expr(0))\n expect(\";\")\n elif accept(\"while\")\n e = paren_expr()\n t = make_node(While, e, stmt()\n elif accept(\"{\")\n while tok not equal \"}\" and tok not equal end-of-file\n t = make_node(Sequence, t, stmt())\n expect(\"}\")\n elif tok is end-of-file\n pass\n else\n error()\n return t\n\ndef parse()\n t = NULL\n gettok()\n repeat\n t = make_node(Sequence, t, stmt())\n until tok is end-of-file\n return t\n\n;Once the AST is built, it should be output in a flattened format. This can be as simple as the following:\n\ndef prt_ast(t)\n if t == NULL\n print(\";\\n\")\n else\n print(t.node_type)\n if t.node_type in [Identifier, Integer, String] # leaf node\n print the value of the Ident, Integer or String, \"\\n\"\n else\n print(\"\\n\")\n prt_ast(t.left)\n prt_ast(t.right)\n\n;If the AST is correctly built, loading it into a subsequent program should be as simple as:\n\ndef load_ast()\n line = readline()\n # Each line has at least one token\n line_list = tokenize the line, respecting double quotes\n\n text = line_list[0] # first token is always the node type\n\n if text == \";\" # a terminal node\n return NULL\n\n node_type = text # could convert to internal form if desired\n\n # A line with two tokens is a leaf node\n # Leaf nodes are: Identifier, Integer, String\n # The 2nd token is the value\n if len(line_list) > 1\n return make_leaf(node_type, line_list[1])\n\n left = load_ast()\n right = load_ast()\n return make_node(node_type, left, right)\n\nFinally, the AST can also be tested by running it against one of the AST Interpreter solutions.\n\n;Test program, assuming this is in a file called prime.t: lex /*\n Simple prime number generator\n */\ncount = 1;\nn = 1;\nlimit = 100;\nwhile (n < limit) {\n k=3;\n p=1;\n n=n+2;\n while ((k*k<=n) && (p)) {\n p=n/k*k!=n;\n k=k+2;\n }\n if (p) {\n print(n, \" is prime\\n\");\n count = count + 1;\n }\n}\nprint(\"Total primes found: \", count, \"\\n\");\n\n| style=\"vertical-align:top\" |\n\n 4 1 Identifier count\n 4 7 Op_assign\n 4 9 Integer 1\n 4 10 Semicolon\n 5 1 Identifier n\n 5 3 Op_assign\n 5 5 Integer 1\n 5 6 Semicolon\n 6 1 Identifier limit\n 6 7 Op_assign\n 6 9 Integer 100\n 6 12 Semicolon\n 7 1 Keyword_while\n 7 7 LeftParen\n 7 8 Identifier n\n 7 10 Op_less\n 7 12 Identifier limit\n 7 17 RightParen\n 7 19 LeftBrace\n 8 5 Identifier k\n 8 6 Op_assign\n 8 7 Integer 3\n 8 8 Semicolon\n 9 5 Identifier p\n 9 6 Op_assign\n 9 7 Integer 1\n 9 8 Semicolon\n 10 5 Identifier n\n 10 6 Op_assign\n 10 7 Identifier n\n 10 8 Op_add\n 10 9 Integer 2\n 10 10 Semicolon\n 11 5 Keyword_while\n 11 11 LeftParen\n 11 12 LeftParen\n 11 13 Identifier k\n 11 14 Op_multiply\n 11 15 Identifier k\n 11 16 Op_lessequal\n 11 18 Identifier n\n 11 19 RightParen\n 11 21 Op_and\n 11 24 LeftParen\n 11 25 Identifier p\n 11 26 RightParen\n 11 27 RightParen\n 11 29 LeftBrace\n 12 9 Identifier p\n 12 10 Op_assign\n 12 11 Identifier n\n 12 12 Op_divide\n 12 13 Identifier k\n 12 14 Op_multiply\n 12 15 Identifier k\n 12 16 Op_notequal\n 12 18 Identifier n\n 12 19 Semicolon\n 13 9 Identifier k\n 13 10 Op_assign\n 13 11 Identifier k\n 13 12 Op_add\n 13 13 Integer 2\n 13 14 Semicolon\n 14 5 RightBrace\n 15 5 Keyword_if\n 15 8 LeftParen\n 15 9 Identifier p\n 15 10 RightParen\n 15 12 LeftBrace\n 16 9 Keyword_print\n 16 14 LeftParen\n 16 15 Identifier n\n 16 16 Comma\n 16 18 String \" is prime\\n\"\n 16 31 RightParen\n 16 32 Semicolon\n 17 9 Identifier count\n 17 15 Op_assign\n 17 17 Identifier count\n 17 23 Op_add\n 17 25 Integer 1\n 17 26 Semicolon\n 18 5 RightBrace\n 19 1 RightBrace\n 20 1 Keyword_print\n 20 6 LeftParen\n 20 7 String \"Total primes found: \"\n 20 29 Comma\n 20 31 Identifier count\n 20 36 Comma\n 20 38 String \"\\n\"\n 20 42 RightParen\n 20 43 Semicolon\n 21 1 End_of_input\n\n\n| style=\"vertical-align:top\" |\n\nSequence\nSequence\nSequence\nSequence\nSequence\n;\nAssign\nIdentifier count\nInteger 1\nAssign\nIdentifier n\nInteger 1\nAssign\nIdentifier limit\nInteger 100\nWhile\nLess\nIdentifier n\nIdentifier limit\nSequence\nSequence\nSequence\nSequence\nSequence\n;\nAssign\nIdentifier k\nInteger 3\nAssign\nIdentifier p\nInteger 1\nAssign\nIdentifier n\nAdd\nIdentifier n\nInteger 2\nWhile\nAnd\nLessEqual\nMultiply\nIdentifier k\nIdentifier k\nIdentifier n\nIdentifier p\nSequence\nSequence\n;\nAssign\nIdentifier p\nNotEqual\nMultiply\nDivide\nIdentifier n\nIdentifier k\nIdentifier k\nIdentifier n\nAssign\nIdentifier k\nAdd\nIdentifier k\nInteger 2\nIf\nIdentifier p\nIf\nSequence\nSequence\n;\nSequence\nSequence\n;\nPrti\nIdentifier n\n;\nPrts\nString \" is prime\\n\"\n;\nAssign\nIdentifier count\nAdd\nIdentifier count\nInteger 1\n;\nSequence\nSequence\nSequence\n;\nPrts\nString \"Total primes found: \"\n;\nPrti\nIdentifier count\n;\nPrts\nString \"\\n\"\n;\n\n|}\n\n; Additional examples\n\nYour solution should pass all the test cases above and the additional tests found '''Here'''.\n\n\nThe 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/syntax analyzer", "language": "Python", "task": "A Syntax analyzer transforms a token stream (from the Lexical analyzer)\ninto a Syntax tree, based on a grammar.\n\n\nTake the output from the Lexical analyzer task,\nand convert it to an [https://en.wikipedia.org/wiki/Abstract_syntax_tree Abstract Syntax Tree (AST)],\nbased on the grammar below. The output should be in a flattened format.\n\nThe program should read input from a file and/or stdin, and write output to a file and/or\nstdout. If the language being used has a parser module/library/class, it would be great\nif two versions of the solution are provided: One without the parser module, and one\nwith.\n\n\nThe simple programming language to be analyzed is more or less a (very tiny) subset of\n[[C]]. The formal grammar in\n[https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_Form Extended Backus-Naur Form (EBNF)]:\n\n\n stmt_list = {stmt} ;\n\n stmt = ';'\n | Identifier '=' expr ';'\n | 'while' paren_expr stmt\n | 'if' paren_expr stmt ['else' stmt]\n | 'print' '(' prt_list ')' ';'\n | 'putc' paren_expr ';'\n | '{' stmt_list '}'\n ;\n\n paren_expr = '(' expr ')' ;\n\n prt_list = (string | expr) {',' (String | expr)} ;\n\n expr = and_expr {'||' and_expr} ;\n and_expr = equality_expr {'&&' equality_expr} ;\n equality_expr = relational_expr [('==' | '!=') relational_expr] ;\n relational_expr = addition_expr [('<' | '<=' | '>' | '>=') addition_expr] ;\n addition_expr = multiplication_expr {('+' | '-') multiplication_expr} ;\n multiplication_expr = primary {('*' | '/' | '%') primary } ;\n primary = Identifier\n | Integer\n | '(' expr ')'\n | ('+' | '-' | '!') primary\n ;\n\nThe resulting AST should be formulated as a Binary Tree.\n\n;Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions\n\n lex < while.t > while.lex\n\n;Run one of the Syntax analyzer solutions:\n\n parse < while.lex > while.ast\n\n;The following table shows the input to lex, lex output, and the AST produced by the parser:\n\n{| class=\"wikitable\"\n|-\n! Input to lex\n! Output from lex, input to parse\n! Output from parse\n|-\n| style=\"vertical-align:top\" |\ncount = 1;\n while (count < 10) {\n print(\"count is: \", count, \"\\n\");\n count = count + 1;\n }\n\n| style=\"vertical-align:top\" |\n\n 1 1 Identifier count\n 1 7 Op_assign\n 1 9 Integer 1\n 1 10 Semicolon\n 2 1 Keyword_while\n 2 7 LeftParen\n 2 8 Identifier count\n 2 14 Op_less\n 2 16 Integer 10\n 2 18 RightParen\n 2 20 LeftBrace\n 3 5 Keyword_print\n 3 10 LeftParen\n 3 11 String \"count is: \"\n 3 23 Comma\n 3 25 Identifier count\n 3 30 Comma\n 3 32 String \"\\n\"\n 3 36 RightParen\n 3 37 Semicolon\n 4 5 Identifier count\n 4 11 Op_assign\n 4 13 Identifier count\n 4 19 Op_add\n 4 21 Integer 1\n 4 22 Semicolon\n 5 1 RightBrace\n 6 1 End_of_input\n\n\n| style=\"vertical-align:top\" |\n\nSequence\nSequence\n;\nAssign\nIdentifier count\nInteger 1\nWhile\nLess\nIdentifier count\nInteger 10\nSequence\nSequence\n;\nSequence\nSequence\nSequence\n;\nPrts\nString \"count is: \"\n;\nPrti\nIdentifier count\n;\nPrts\nString \"\\n\"\n;\nAssign\nIdentifier count\nAdd\nIdentifier count\nInteger 1\n\n|}\n\n;Specifications\n\n;List of node type names:\n\n\nIdentifier String Integer Sequence If Prtc Prts Prti While Assign Negate Not Multiply Divide Mod\nAdd Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or\n\n\nIn the text below, Null/Empty nodes are represented by \";\".\n\n;Non-terminal (internal) nodes:\n\nFor Operators, the following nodes should be created:\n\n Multiply Divide Mod Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or\n\nFor each of the above nodes, the left and right sub-nodes are the operands of the\nrespective operation.\n\nIn pseudo S-Expression format:\n\n (Operator expression expression)\n\nNegate, Not\n\nFor these node types, the left node is the operand, and the right node is null.\n\n (Operator expression ;)\n\nSequence - sub-nodes are either statements or Sequences.\n\nIf - left node is the expression, the right node is If node, with it's left node being the\nif-true statement part, and the right node being the if-false (else) statement part.\n\n (If expression (If statement else-statement))\n\nIf there is not an else, the tree becomes:\n\n (If expression (If statement ;))\n\nPrtc\n\n (Prtc (expression) ;)\n\nPrts\n\n (Prts (String \"the string\") ;)\n\nPrti\n\n (Prti (Integer 12345) ;)\n\nWhile - left node is the expression, the right node is the statement.\n\n (While expression statement)\n\nAssign - left node is the left-hand side of the assignment, the right node is the\nright-hand side of the assignment.\n\n (Assign Identifier expression)\n\nTerminal (leaf) nodes:\n\n Identifier: (Identifier ident_name)\n Integer: (Integer 12345)\n String: (String \"Hello World!\")\n \";\": Empty node\n\n;Some simple examples\nSequences denote a list node; they are used to represent a list. semicolon's represent a null node, e.g., the end of this path.\n\nThis simple program:\n\n a=11;\n\nProduces the following AST, encoded as a binary tree:\n\nUnder each non-leaf node are two '|' lines. The first represents the left sub-node, the second represents the right sub-node:\n\n (1) Sequence\n (2) |-- ;\n (3) |-- Assign\n (4) |-- Identifier: a\n (5) |-- Integer: 11\n\nIn flattened form:\n\n (1) Sequence\n (2) ;\n (3) Assign\n (4) Identifier a\n (5) Integer 11\n\n\nThis program:\n\n a=11;\n b=22;\n c=33;\n\nProduces the following AST:\n\n ( 1) Sequence\n ( 2) |-- Sequence\n ( 3) | |-- Sequence\n ( 4) | | |-- ;\n ( 5) | | |-- Assign\n ( 6) | | |-- Identifier: a\n ( 7) | | |-- Integer: 11\n ( 8) | |-- Assign\n ( 9) | |-- Identifier: b\n (10) | |-- Integer: 22\n (11) |-- Assign\n (12) |-- Identifier: c\n (13) |-- Integer: 33\n\nIn flattened form:\n\n ( 1) Sequence\n ( 2) Sequence\n ( 3) Sequence\n ( 4) ;\n ( 5) Assign\n ( 6) Identifier a\n ( 7) Integer 11\n ( 8) Assign\n ( 9) Identifier b\n (10) Integer 22\n (11) Assign\n (12) Identifier c\n (13) Integer 33\n\n;Pseudo-code for the parser. \n\nUses [https://www.engr.mun.ca/~theo/Misc/exp_parsing.htm Precedence Climbing] for expression parsing, and\n[https://en.wikipedia.org/wiki/Recursive_descent_parser Recursive Descent] for statement parsing. The AST is also built:\n\ndef expr(p)\n if tok is \"(\"\n x = paren_expr()\n elif tok in [\"-\", \"+\", \"!\"]\n gettok()\n y = expr(precedence of operator)\n if operator was \"+\"\n x = y\n else\n x = make_node(operator, y)\n elif tok is an Identifier\n x = make_leaf(Identifier, variable name)\n gettok()\n elif tok is an Integer constant\n x = make_leaf(Integer, integer value)\n gettok()\n else\n error()\n\n while tok is a binary operator and precedence of tok >= p\n save_tok = tok\n gettok()\n q = precedence of save_tok\n if save_tok is not right associative\n q += 1\n x = make_node(Operator save_tok represents, x, expr(q))\n\n return x\n\ndef paren_expr()\n expect(\"(\")\n x = expr(0)\n expect(\")\")\n return x\n\ndef stmt()\n t = NULL\n if accept(\"if\")\n e = paren_expr()\n s = stmt()\n t = make_node(If, e, make_node(If, s, accept(\"else\") ? stmt() : NULL))\n elif accept(\"putc\")\n t = make_node(Prtc, paren_expr())\n expect(\";\")\n elif accept(\"print\")\n expect(\"(\")\n repeat\n if tok is a string\n e = make_node(Prts, make_leaf(String, the string))\n gettok()\n else\n e = make_node(Prti, expr(0))\n\n t = make_node(Sequence, t, e)\n until not accept(\",\")\n expect(\")\")\n expect(\";\")\n elif tok is \";\"\n gettok()\n elif tok is an Identifier\n v = make_leaf(Identifier, variable name)\n gettok()\n expect(\"=\")\n t = make_node(Assign, v, expr(0))\n expect(\";\")\n elif accept(\"while\")\n e = paren_expr()\n t = make_node(While, e, stmt()\n elif accept(\"{\")\n while tok not equal \"}\" and tok not equal end-of-file\n t = make_node(Sequence, t, stmt())\n expect(\"}\")\n elif tok is end-of-file\n pass\n else\n error()\n return t\n\ndef parse()\n t = NULL\n gettok()\n repeat\n t = make_node(Sequence, t, stmt())\n until tok is end-of-file\n return t\n\n;Once the AST is built, it should be output in a flattened format. This can be as simple as the following:\n\ndef prt_ast(t)\n if t == NULL\n print(\";\\n\")\n else\n print(t.node_type)\n if t.node_type in [Identifier, Integer, String] # leaf node\n print the value of the Ident, Integer or String, \"\\n\"\n else\n print(\"\\n\")\n prt_ast(t.left)\n prt_ast(t.right)\n\n;If the AST is correctly built, loading it into a subsequent program should be as simple as:\n\ndef load_ast()\n line = readline()\n # Each line has at least one token\n line_list = tokenize the line, respecting double quotes\n\n text = line_list[0] # first token is always the node type\n\n if text == \";\" # a terminal node\n return NULL\n\n node_type = text # could convert to internal form if desired\n\n # A line with two tokens is a leaf node\n # Leaf nodes are: Identifier, Integer, String\n # The 2nd token is the value\n if len(line_list) > 1\n return make_leaf(node_type, line_list[1])\n\n left = load_ast()\n right = load_ast()\n return make_node(node_type, left, right)\n\nFinally, the AST can also be tested by running it against one of the AST Interpreter solutions.\n\n;Test program, assuming this is in a file called prime.t: lex /*\n Simple prime number generator\n */\ncount = 1;\nn = 1;\nlimit = 100;\nwhile (n < limit) {\n k=3;\n p=1;\n n=n+2;\n while ((k*k<=n) && (p)) {\n p=n/k*k!=n;\n k=k+2;\n }\n if (p) {\n print(n, \" is prime\\n\");\n count = count + 1;\n }\n}\nprint(\"Total primes found: \", count, \"\\n\");\n\n| style=\"vertical-align:top\" |\n\n 4 1 Identifier count\n 4 7 Op_assign\n 4 9 Integer 1\n 4 10 Semicolon\n 5 1 Identifier n\n 5 3 Op_assign\n 5 5 Integer 1\n 5 6 Semicolon\n 6 1 Identifier limit\n 6 7 Op_assign\n 6 9 Integer 100\n 6 12 Semicolon\n 7 1 Keyword_while\n 7 7 LeftParen\n 7 8 Identifier n\n 7 10 Op_less\n 7 12 Identifier limit\n 7 17 RightParen\n 7 19 LeftBrace\n 8 5 Identifier k\n 8 6 Op_assign\n 8 7 Integer 3\n 8 8 Semicolon\n 9 5 Identifier p\n 9 6 Op_assign\n 9 7 Integer 1\n 9 8 Semicolon\n 10 5 Identifier n\n 10 6 Op_assign\n 10 7 Identifier n\n 10 8 Op_add\n 10 9 Integer 2\n 10 10 Semicolon\n 11 5 Keyword_while\n 11 11 LeftParen\n 11 12 LeftParen\n 11 13 Identifier k\n 11 14 Op_multiply\n 11 15 Identifier k\n 11 16 Op_lessequal\n 11 18 Identifier n\n 11 19 RightParen\n 11 21 Op_and\n 11 24 LeftParen\n 11 25 Identifier p\n 11 26 RightParen\n 11 27 RightParen\n 11 29 LeftBrace\n 12 9 Identifier p\n 12 10 Op_assign\n 12 11 Identifier n\n 12 12 Op_divide\n 12 13 Identifier k\n 12 14 Op_multiply\n 12 15 Identifier k\n 12 16 Op_notequal\n 12 18 Identifier n\n 12 19 Semicolon\n 13 9 Identifier k\n 13 10 Op_assign\n 13 11 Identifier k\n 13 12 Op_add\n 13 13 Integer 2\n 13 14 Semicolon\n 14 5 RightBrace\n 15 5 Keyword_if\n 15 8 LeftParen\n 15 9 Identifier p\n 15 10 RightParen\n 15 12 LeftBrace\n 16 9 Keyword_print\n 16 14 LeftParen\n 16 15 Identifier n\n 16 16 Comma\n 16 18 String \" is prime\\n\"\n 16 31 RightParen\n 16 32 Semicolon\n 17 9 Identifier count\n 17 15 Op_assign\n 17 17 Identifier count\n 17 23 Op_add\n 17 25 Integer 1\n 17 26 Semicolon\n 18 5 RightBrace\n 19 1 RightBrace\n 20 1 Keyword_print\n 20 6 LeftParen\n 20 7 String \"Total primes found: \"\n 20 29 Comma\n 20 31 Identifier count\n 20 36 Comma\n 20 38 String \"\\n\"\n 20 42 RightParen\n 20 43 Semicolon\n 21 1 End_of_input\n\n\n| style=\"vertical-align:top\" |\n\nSequence\nSequence\nSequence\nSequence\nSequence\n;\nAssign\nIdentifier count\nInteger 1\nAssign\nIdentifier n\nInteger 1\nAssign\nIdentifier limit\nInteger 100\nWhile\nLess\nIdentifier n\nIdentifier limit\nSequence\nSequence\nSequence\nSequence\nSequence\n;\nAssign\nIdentifier k\nInteger 3\nAssign\nIdentifier p\nInteger 1\nAssign\nIdentifier n\nAdd\nIdentifier n\nInteger 2\nWhile\nAnd\nLessEqual\nMultiply\nIdentifier k\nIdentifier k\nIdentifier n\nIdentifier p\nSequence\nSequence\n;\nAssign\nIdentifier p\nNotEqual\nMultiply\nDivide\nIdentifier n\nIdentifier k\nIdentifier k\nIdentifier n\nAssign\nIdentifier k\nAdd\nIdentifier k\nInteger 2\nIf\nIdentifier p\nIf\nSequence\nSequence\n;\nSequence\nSequence\n;\nPrti\nIdentifier n\n;\nPrts\nString \" is prime\\n\"\n;\nAssign\nIdentifier count\nAdd\nIdentifier count\nInteger 1\n;\nSequence\nSequence\nSequence\n;\nPrts\nString \"Total primes found: \"\n;\nPrti\nIdentifier count\n;\nPrts\nString \"\\n\"\n;\n\n|}\n\n; Additional examples\n\nYour solution should pass all the test cases above and the additional tests found '''Here'''.\n\n\nThe 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": "from __future__ import print_function\nimport sys, shlex, operator\n\ntk_EOI, tk_Mul, tk_Div, tk_Mod, tk_Add, tk_Sub, tk_Negate, tk_Not, tk_Lss, tk_Leq, tk_Gtr, \\\ntk_Geq, tk_Eql, tk_Neq, tk_Assign, tk_And, tk_Or, tk_If, tk_Else, tk_While, tk_Print, \\\ntk_Putc, tk_Lparen, tk_Rparen, tk_Lbrace, tk_Rbrace, tk_Semi, tk_Comma, tk_Ident, \\\ntk_Integer, tk_String = range(31)\n\nnd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While, \\\nnd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq, \\\nnd_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or = range(25)\n\n# must have same order as above\nTokens = [\n [\"EOI\" , False, False, False, -1, -1 ],\n [\"*\" , False, True, False, 13, nd_Mul ],\n [\"/\" , False, True, False, 13, nd_Div ],\n [\"%\" , False, True, False, 13, nd_Mod ],\n [\"+\" , False, True, False, 12, nd_Add ],\n [\"-\" , False, True, False, 12, nd_Sub ],\n [\"-\" , False, False, True, 14, nd_Negate ],\n [\"!\" , False, False, True, 14, nd_Not ],\n [\"<\" , False, True, False, 10, nd_Lss ],\n [\"<=\" , False, True, False, 10, nd_Leq ],\n [\">\" , False, True, False, 10, nd_Gtr ],\n [\">=\" , False, True, False, 10, nd_Geq ],\n [\"==\" , False, True, False, 9, nd_Eql ],\n [\"!=\" , False, True, False, 9, nd_Neq ],\n [\"=\" , False, False, False, -1, nd_Assign ],\n [\"&&\" , False, True, False, 5, nd_And ],\n [\"||\" , False, True, False, 4, nd_Or ],\n [\"if\" , False, False, False, -1, nd_If ],\n [\"else\" , False, False, False, -1, -1 ],\n [\"while\" , False, False, False, -1, nd_While ],\n [\"print\" , False, False, False, -1, -1 ],\n [\"putc\" , False, False, False, -1, -1 ],\n [\"(\" , False, False, False, -1, -1 ],\n [\")\" , False, False, False, -1, -1 ],\n [\"{\" , False, False, False, -1, -1 ],\n [\"}\" , False, False, False, -1, -1 ],\n [\";\" , False, False, False, -1, -1 ],\n [\",\" , False, False, False, -1, -1 ],\n [\"Ident\" , False, False, False, -1, nd_Ident ],\n [\"Integer literal\" , False, False, False, -1, nd_Integer],\n [\"String literal\" , False, False, False, -1, nd_String ]\n ]\n\nall_syms = {\"End_of_input\" : tk_EOI, \"Op_multiply\" : tk_Mul,\n \"Op_divide\" : tk_Div, \"Op_mod\" : tk_Mod,\n \"Op_add\" : tk_Add, \"Op_subtract\" : tk_Sub,\n \"Op_negate\" : tk_Negate, \"Op_not\" : tk_Not,\n \"Op_less\" : tk_Lss, \"Op_lessequal\" : tk_Leq,\n \"Op_greater\" : tk_Gtr, \"Op_greaterequal\": tk_Geq,\n \"Op_equal\" : tk_Eql, \"Op_notequal\" : tk_Neq,\n \"Op_assign\" : tk_Assign, \"Op_and\" : tk_And,\n \"Op_or\" : tk_Or, \"Keyword_if\" : tk_If,\n \"Keyword_else\" : tk_Else, \"Keyword_while\" : tk_While,\n \"Keyword_print\" : tk_Print, \"Keyword_putc\" : tk_Putc,\n \"LeftParen\" : tk_Lparen, \"RightParen\" : tk_Rparen,\n \"LeftBrace\" : tk_Lbrace, \"RightBrace\" : tk_Rbrace,\n \"Semicolon\" : tk_Semi, \"Comma\" : tk_Comma,\n \"Identifier\" : tk_Ident, \"Integer\" : tk_Integer,\n \"String\" : tk_String}\n\nDisplay_nodes = [\"Identifier\", \"String\", \"Integer\", \"Sequence\", \"If\", \"Prtc\", \"Prts\",\n \"Prti\", \"While\", \"Assign\", \"Negate\", \"Not\", \"Multiply\", \"Divide\", \"Mod\", \"Add\",\n \"Subtract\", \"Less\", \"LessEqual\", \"Greater\", \"GreaterEqual\", \"Equal\", \"NotEqual\",\n \"And\", \"Or\"]\n\nTK_NAME = 0\nTK_RIGHT_ASSOC = 1\nTK_IS_BINARY = 2\nTK_IS_UNARY = 3\nTK_PRECEDENCE = 4\nTK_NODE = 5\n\ninput_file = None\nerr_line = None\nerr_col = None\ntok = None\ntok_text = None\n\n#*** show error and exit\ndef error(msg):\n print(\"(%d, %d) %s\" % (int(err_line), int(err_col), msg))\n exit(1)\n\n#***\ndef gettok():\n global err_line, err_col, tok, tok_text, tok_other\n line = input_file.readline()\n if len(line) == 0:\n error(\"empty line\")\n\n line_list = shlex.split(line, False, False)\n # line col Ident var_name\n # 0 1 2 3\n\n err_line = line_list[0]\n err_col = line_list[1]\n tok_text = line_list[2]\n\n tok = all_syms.get(tok_text)\n if tok == None:\n error(\"Unknown token %s\" % (tok_text))\n\n tok_other = None\n if tok in [tk_Integer, tk_Ident, tk_String]:\n tok_other = line_list[3]\n\nclass Node:\n def __init__(self, node_type, left = None, right = None, value = None):\n self.node_type = node_type\n self.left = left\n self.right = right\n self.value = value\n\n#***\ndef make_node(oper, left, right = None):\n return Node(oper, left, right)\n\n#***\ndef make_leaf(oper, n):\n return Node(oper, value = n)\n\n#***\ndef expect(msg, s):\n if tok == s:\n gettok()\n return\n error(\"%s: Expecting '%s', found '%s'\" % (msg, Tokens[s][TK_NAME], Tokens[tok][TK_NAME]))\n\n#***\ndef expr(p):\n x = None\n\n if tok == tk_Lparen:\n x = paren_expr()\n elif tok in [tk_Sub, tk_Add]:\n op = (tk_Negate if tok == tk_Sub else tk_Add)\n gettok()\n node = expr(Tokens[tk_Negate][TK_PRECEDENCE])\n x = (make_node(nd_Negate, node) if op == tk_Negate else node)\n elif tok == tk_Not:\n gettok()\n x = make_node(nd_Not, expr(Tokens[tk_Not][TK_PRECEDENCE]))\n elif tok == tk_Ident:\n x = make_leaf(nd_Ident, tok_other)\n gettok()\n elif tok == tk_Integer:\n x = make_leaf(nd_Integer, tok_other)\n gettok()\n else:\n error(\"Expecting a primary, found: %s\" % (Tokens[tok][TK_NAME]))\n\n while Tokens[tok][TK_IS_BINARY] and Tokens[tok][TK_PRECEDENCE] >= p:\n op = tok\n gettok()\n q = Tokens[op][TK_PRECEDENCE]\n if not Tokens[op][TK_RIGHT_ASSOC]:\n q += 1\n\n node = expr(q)\n x = make_node(Tokens[op][TK_NODE], x, node)\n\n return x\n\n#***\ndef paren_expr():\n expect(\"paren_expr\", tk_Lparen)\n node = expr(0)\n expect(\"paren_expr\", tk_Rparen)\n return node\n\n#***\ndef stmt():\n t = None\n\n if tok == tk_If:\n gettok()\n e = paren_expr()\n s = stmt()\n s2 = None\n if tok == tk_Else:\n gettok()\n s2 = stmt()\n t = make_node(nd_If, e, make_node(nd_If, s, s2))\n elif tok == tk_Putc:\n gettok()\n e = paren_expr()\n t = make_node(nd_Prtc, e)\n expect(\"Putc\", tk_Semi)\n elif tok == tk_Print:\n gettok()\n expect(\"Print\", tk_Lparen)\n while True:\n if tok == tk_String:\n e = make_node(nd_Prts, make_leaf(nd_String, tok_other))\n gettok()\n else:\n e = make_node(nd_Prti, expr(0))\n\n t = make_node(nd_Sequence, t, e)\n if tok != tk_Comma:\n break\n gettok()\n expect(\"Print\", tk_Rparen)\n expect(\"Print\", tk_Semi)\n elif tok == tk_Semi:\n gettok()\n elif tok == tk_Ident:\n v = make_leaf(nd_Ident, tok_other)\n gettok()\n expect(\"assign\", tk_Assign)\n e = expr(0)\n t = make_node(nd_Assign, v, e)\n expect(\"assign\", tk_Semi)\n elif tok == tk_While:\n gettok()\n e = paren_expr()\n s = stmt()\n t = make_node(nd_While, e, s)\n elif tok == tk_Lbrace:\n gettok()\n while tok != tk_Rbrace and tok != tk_EOI:\n t = make_node(nd_Sequence, t, stmt())\n expect(\"Lbrace\", tk_Rbrace)\n elif tok == tk_EOI:\n pass\n else:\n error(\"Expecting start of statement, found: %s\" % (Tokens[tok][TK_NAME]))\n\n return t\n\n#***\ndef parse():\n t = None\n gettok()\n while True:\n t = make_node(nd_Sequence, t, stmt())\n if tok == tk_EOI or t == None:\n break\n return t\n\ndef prt_ast(t):\n if t == None:\n print(\";\")\n else:\n print(\"%-14s\" % (Display_nodes[t.node_type]), end='')\n if t.node_type in [nd_Ident, nd_Integer]:\n print(\"%s\" % (t.value))\n elif t.node_type == nd_String:\n print(\"%s\" %(t.value))\n else:\n print(\"\")\n prt_ast(t.left)\n prt_ast(t.right)\n\n#*** main driver\ninput_file = sys.stdin\nif len(sys.argv) > 1:\n try:\n input_file = open(sys.argv[1], \"r\", 4096)\n except IOError as e:\n error(0, 0, \"Can't open %s\" % sys.argv[1])\nt = parse()\nprt_ast(t)"} +{"title": "Compiler/virtual machine interpreter", "language": "C", "task": "A virtual machine implements a computer in software.\n\n\nWrite a virtual machine interpreter. This interpreter should be able to run virtual\nassembly language programs created via the task. This is a\nbyte-coded, 32-bit word stack based virtual machine.\n\nThe program should read input from a file and/or stdin, and write output to a file and/or\nstdout.\n\nInput format:\n\nGiven the following program:\n\n count = 1;\n while (count < 10) {\n print(\"count is: \", count, \"\\n\");\n count = count + 1;\n }\n\nThe output from the Code generator is a virtual assembly code program:\n\n{| class=\"wikitable\"\n|-\n! Output from gen, input to VM\n|-\n\n| style=\"vertical-align:top\" |\nDatasize: 1 Strings: 2\n\"count is: \"\n\"\\n\"\n 0 push 1\n 5 store [0]\n 10 fetch [0]\n 15 push 10\n 20 lt\n 21 jz (43) 65\n 26 push 0\n 31 prts\n 32 fetch [0]\n 37 prti\n 38 push 1\n 43 prts\n 44 fetch [0]\n 49 push 1\n 54 add\n 55 store [0]\n 60 jmp (-51) 10\n 65 halt\n|}\n\nThe first line of the input specifies the datasize required and the number of constant\nstrings, in the order that they are reference via the code.\n\nThe data can be stored in a separate array, or the data can be stored at the beginning of\nthe stack. Data is addressed starting at 0. If there are 3 variables, the 3rd one if\nreferenced at address 2.\n\nIf there are one or more constant strings, they come next. The code refers to these\nstrings by their index. The index starts at 0. So if there are 3 strings, and the code\nwants to reference the 3rd string, 2 will be used.\n\nNext comes the actual virtual assembly code. The first number is the code address of that\ninstruction. After that is the instruction mnemonic, followed by optional operands,\ndepending on the instruction.\n\nRegisters:\n\nsp:\n the stack pointer - points to the next top of stack. The stack is a 32-bit integer\n array.\n\npc:\n the program counter - points to the current instruction to be performed. The code is an\n array of bytes.\n\nData:\n data\n string pool\n\nInstructions:\n\nEach instruction is one byte. The following instructions also have a 32-bit integer\noperand:\n\n fetch [index]\n\nwhere index is an index into the data array.\n\n store [index]\n\nwhere index is an index into the data array.\n\n push n\n\nwhere value is a 32-bit integer that will be pushed onto the stack.\n\n jmp (n) addr\n\nwhere (n) is a 32-bit integer specifying the distance between the current location and the\ndesired location. addr is an unsigned value of the actual code address.\n\n jz (n) addr\n\nwhere (n) is a 32-bit integer specifying the distance between the current location and the\ndesired location. addr is an unsigned value of the actual code address.\n\nThe following instructions do not have an operand. They perform their operation directly\nagainst the stack:\n\nFor the following instructions, the operation is performed against the top two entries in\nthe stack:\n\n add\n sub\n mul\n div\n mod\n lt\n gt\n le\n ge\n eq\n ne\n and\n or\n\nFor the following instructions, the operation is performed against the top entry in the\nstack:\n\n neg\n not\n\nPrint the word at stack top as a character.\n\n prtc\n\nPrint the word at stack top as an integer.\n\n prti\n\nStack top points to an index into the string pool. Print that entry.\n\n prts\n\nUnconditional stop.\n\n halt\n\n; A simple example virtual machine:\n\ndef run_vm(data_size)\n int stack[data_size + 1000]\n set stack[0..data_size - 1] to 0\n int pc = 0\n while True:\n op = code[pc]\n pc += 1\n\n if op == FETCH:\n stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]);\n pc += word_size\n elif op == STORE:\n stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop();\n pc += word_size\n elif op == PUSH:\n stack.append(bytes_to_int(code[pc:pc+word_size])[0]);\n pc += word_size\n elif op == ADD: stack[-2] += stack[-1]; stack.pop()\n elif op == SUB: stack[-2] -= stack[-1]; stack.pop()\n elif op == MUL: stack[-2] *= stack[-1]; stack.pop()\n elif op == DIV: stack[-2] /= stack[-1]; stack.pop()\n elif op == MOD: stack[-2] %= stack[-1]; stack.pop()\n elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop()\n elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop()\n elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop()\n elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop()\n elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop()\n elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop()\n elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop()\n elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop()\n elif op == NEG: stack[-1] = -stack[-1]\n elif op == NOT: stack[-1] = not stack[-1]\n elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0]\n elif op == JZ: if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0]\n elif op == PRTC: print stack[-1] as a character; stack.pop()\n elif op == PRTS: print the constant string referred to by stack[-1]; stack.pop()\n elif op == PRTI: print stack[-1] as an integer; stack.pop()\n elif op == HALT: break\n\n; Additional examples\n\nYour solution should pass all the test cases above and the additional tests found '''Here'''.\n\n\nThe 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": "Compiler/virtual machine interpreter", "language": "Python", "task": "A virtual machine implements a computer in software.\n\n\nWrite a virtual machine interpreter. This interpreter should be able to run virtual\nassembly language programs created via the task. This is a\nbyte-coded, 32-bit word stack based virtual machine.\n\nThe program should read input from a file and/or stdin, and write output to a file and/or\nstdout.\n\nInput format:\n\nGiven the following program:\n\n count = 1;\n while (count < 10) {\n print(\"count is: \", count, \"\\n\");\n count = count + 1;\n }\n\nThe output from the Code generator is a virtual assembly code program:\n\n{| class=\"wikitable\"\n|-\n! Output from gen, input to VM\n|-\n\n| style=\"vertical-align:top\" |\nDatasize: 1 Strings: 2\n\"count is: \"\n\"\\n\"\n 0 push 1\n 5 store [0]\n 10 fetch [0]\n 15 push 10\n 20 lt\n 21 jz (43) 65\n 26 push 0\n 31 prts\n 32 fetch [0]\n 37 prti\n 38 push 1\n 43 prts\n 44 fetch [0]\n 49 push 1\n 54 add\n 55 store [0]\n 60 jmp (-51) 10\n 65 halt\n|}\n\nThe first line of the input specifies the datasize required and the number of constant\nstrings, in the order that they are reference via the code.\n\nThe data can be stored in a separate array, or the data can be stored at the beginning of\nthe stack. Data is addressed starting at 0. If there are 3 variables, the 3rd one if\nreferenced at address 2.\n\nIf there are one or more constant strings, they come next. The code refers to these\nstrings by their index. The index starts at 0. So if there are 3 strings, and the code\nwants to reference the 3rd string, 2 will be used.\n\nNext comes the actual virtual assembly code. The first number is the code address of that\ninstruction. After that is the instruction mnemonic, followed by optional operands,\ndepending on the instruction.\n\nRegisters:\n\nsp:\n the stack pointer - points to the next top of stack. The stack is a 32-bit integer\n array.\n\npc:\n the program counter - points to the current instruction to be performed. The code is an\n array of bytes.\n\nData:\n data\n string pool\n\nInstructions:\n\nEach instruction is one byte. The following instructions also have a 32-bit integer\noperand:\n\n fetch [index]\n\nwhere index is an index into the data array.\n\n store [index]\n\nwhere index is an index into the data array.\n\n push n\n\nwhere value is a 32-bit integer that will be pushed onto the stack.\n\n jmp (n) addr\n\nwhere (n) is a 32-bit integer specifying the distance between the current location and the\ndesired location. addr is an unsigned value of the actual code address.\n\n jz (n) addr\n\nwhere (n) is a 32-bit integer specifying the distance between the current location and the\ndesired location. addr is an unsigned value of the actual code address.\n\nThe following instructions do not have an operand. They perform their operation directly\nagainst the stack:\n\nFor the following instructions, the operation is performed against the top two entries in\nthe stack:\n\n add\n sub\n mul\n div\n mod\n lt\n gt\n le\n ge\n eq\n ne\n and\n or\n\nFor the following instructions, the operation is performed against the top entry in the\nstack:\n\n neg\n not\n\nPrint the word at stack top as a character.\n\n prtc\n\nPrint the word at stack top as an integer.\n\n prti\n\nStack top points to an index into the string pool. Print that entry.\n\n prts\n\nUnconditional stop.\n\n halt\n\n; A simple example virtual machine:\n\ndef run_vm(data_size)\n int stack[data_size + 1000]\n set stack[0..data_size - 1] to 0\n int pc = 0\n while True:\n op = code[pc]\n pc += 1\n\n if op == FETCH:\n stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]);\n pc += word_size\n elif op == STORE:\n stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop();\n pc += word_size\n elif op == PUSH:\n stack.append(bytes_to_int(code[pc:pc+word_size])[0]);\n pc += word_size\n elif op == ADD: stack[-2] += stack[-1]; stack.pop()\n elif op == SUB: stack[-2] -= stack[-1]; stack.pop()\n elif op == MUL: stack[-2] *= stack[-1]; stack.pop()\n elif op == DIV: stack[-2] /= stack[-1]; stack.pop()\n elif op == MOD: stack[-2] %= stack[-1]; stack.pop()\n elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop()\n elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop()\n elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop()\n elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop()\n elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop()\n elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop()\n elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop()\n elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop()\n elif op == NEG: stack[-1] = -stack[-1]\n elif op == NOT: stack[-1] = not stack[-1]\n elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0]\n elif op == JZ: if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0]\n elif op == PRTC: print stack[-1] as a character; stack.pop()\n elif op == PRTS: print the constant string referred to by stack[-1]; stack.pop()\n elif op == PRTI: print stack[-1] as an integer; stack.pop()\n elif op == HALT: break\n\n; Additional examples\n\nYour solution should pass all the test cases above and the additional tests found '''Here'''.\n\n\nThe 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": "from __future__ import print_function\nimport sys, struct\n\nFETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT, \\\nJMP, JZ, PRTC, PRTS, PRTI, HALT = range(24)\n\ncode_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 \"not\": NOT,\n \"neg\": NEG,\n \"jmp\": JMP,\n \"jz\": JZ,\n \"prtc\": PRTC,\n \"prts\": PRTS,\n \"prti\": PRTI,\n \"halt\": HALT\n}\n\ninput_file = None\ncode = bytearray()\nstring_pool = []\nword_size = 4\n\n#*** show error and exit\ndef error(msg):\n print(\"%s\" % (msg))\n exit(1)\n\ndef int_to_bytes(val):\n return struct.pack(\" stack[-1]; stack.pop()\n elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop()\n elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop()\n elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop()\n elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop()\n elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop()\n elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop()\n elif op == NEG: stack[-1] = -stack[-1]\n elif op == NOT: stack[-1] = not stack[-1]\n elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0]\n elif op == JZ:\n if stack.pop():\n pc += word_size\n else:\n pc += bytes_to_int(code[pc:pc+word_size])[0]\n elif op == PRTC: print(\"%c\" % (stack[-1]), end=''); stack.pop()\n elif op == PRTS: print(\"%s\" % (string_pool[stack[-1]]), end=''); stack.pop()\n elif op == PRTI: print(\"%d\" % (stack[-1]), end=''); stack.pop()\n elif op == HALT: break\n\ndef str_trans(srce):\n dest = \"\"\n i = 0\n while i < len(srce):\n if srce[i] == '\\\\' and i + 1 < len(srce):\n if srce[i + 1] == 'n':\n dest += '\\n'\n i += 2\n elif srce[i + 1] == '\\\\':\n dest += '\\\\'\n i += 2\n else:\n dest += srce[i]\n i += 1\n\n return dest\n\n#***\ndef load_code():\n global string_pool\n\n line = input_file.readline()\n if len(line) == 0:\n error(\"empty line\")\n\n line_list = line.split()\n data_size = int(line_list[1])\n n_strings = int(line_list[3])\n\n for i in range(n_strings):\n string_pool.append(str_trans(input_file.readline().strip('\"\\n')))\n\n while True:\n line = input_file.readline()\n if len(line) == 0:\n break\n line_list = line.split()\n offset = int(line_list[0])\n instr = line_list[1]\n opcode = code_map.get(instr)\n if opcode == None:\n error(\"Unknown instruction %s at %d\" % (instr, offset))\n emit_byte(opcode)\n if opcode in [JMP, JZ]:\n p = int(line_list[3])\n emit_word(p - (offset + 1))\n elif opcode == PUSH:\n value = int(line_list[2])\n emit_word(value)\n elif opcode in [FETCH, STORE]:\n value = int(line_list[2].strip('[]'))\n emit_word(value)\n\n return data_size\n\n#*** main driver\ninput_file = sys.stdin\nif len(sys.argv) > 1:\n try:\n input_file = open(sys.argv[1], \"r\", 4096)\n except IOError as e:\n error(0, 0, \"Can't open %s\" % sys.argv[1])\n\ndata_size = load_code()\nrun_vm(data_size)"} +{"title": "Composite numbers k with no single digit factors whose factors are all substrings of k", "language": "Python", "task": "Find the composite numbers '''k''' in base 10, that have no single digit prime factors and whose prime factors are all a substring of '''k'''.\n\n\n;Task\n\n* Find and show here, on this page, the first ten elements of the sequence.\n\n\n\n;Stretch\n\n* Find and show the next ten elements.\n\n\n\n\n", "solution": "from sympy import isprime, factorint\n\ndef contains_its_prime_factors_all_over_7(n):\n if n < 10 or isprime(n):\n return False\n strn = str(n)\n pfacs = factorint(n).keys()\n return all(f > 9 and str(f) in strn for f in pfacs)\n\nfound = 0\nfor n in range(1_000_000_000):\n if contains_its_prime_factors_all_over_7(n):\n found += 1\n print(f'{n: 12,}', end = '\\n' if found % 10 == 0 else '')\n if found == 20:\n break\n"} +{"title": "Conjugate transpose", "language": "C", "task": "[[Category:Matrices]]\n\nSuppose 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: [http://mathworld.wolfram.com/ConjugateTranspose.html conjugate transpose]\n* MathWorld entry: [http://mathworld.wolfram.com/HermitianMatrix.html Hermitian matrix]\n* MathWorld entry: [http://mathworld.wolfram.com/NormalMatrix.html normal matrix]\n* MathWorld entry: [http://mathworld.wolfram.com/UnitaryMatrix.html 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": "Conjugate transpose", "language": "Python", "task": "[[Category:Matrices]]\n\nSuppose 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: [http://mathworld.wolfram.com/ConjugateTranspose.html conjugate transpose]\n* MathWorld entry: [http://mathworld.wolfram.com/HermitianMatrix.html Hermitian matrix]\n* MathWorld entry: [http://mathworld.wolfram.com/NormalMatrix.html normal matrix]\n* MathWorld entry: [http://mathworld.wolfram.com/UnitaryMatrix.html unitary matrix]\n\n", "solution": "def conjugate_transpose(m):\n return tuple(tuple(n.conjugate() for n in row) for row in zip(*m))\n\ndef mmul( ma, mb):\n return tuple(tuple(sum( ea*eb for ea,eb in zip(a,b)) for b in zip(*mb)) for a in ma)\n\ndef mi(size):\n 'Complex Identity matrix'\n sz = range(size)\n m = [[0 + 0j for i in sz] for j in sz]\n for i in range(size):\n m[i][i] = 1 + 0j\n return tuple(tuple(row) for row in m)\n\ndef __allsame(vector):\n first, rest = vector[0], vector[1:]\n return all(i == first for i in rest)\n\ndef __allnearsame(vector, eps=1e-14):\n first, rest = vector[0], vector[1:]\n return all(abs(first.real - i.real) < eps and abs(first.imag - i.imag) < eps\n for i in rest)\n\ndef isequal(matrices, eps=1e-14):\n 'Check any number of matrices for equality within eps'\n x = [len(m) for m in matrices]\n if not __allsame(x): return False\n y = [len(m[0]) for m in matrices]\n if not __allsame(y): return False\n for s in range(x[0]):\n for t in range(y[0]):\n if not __allnearsame([m[s][t] for m in matrices], eps): return False\n return True\n \n\ndef ishermitian(m, ct):\n return isequal([m, ct])\n\ndef isnormal(m, ct):\n return isequal([mmul(m, ct), mmul(ct, m)])\n\ndef isunitary(m, ct):\n mct, ctm = mmul(m, ct), mmul(ct, m)\n mctx, mcty, cmx, ctmy = len(mct), len(mct[0]), len(ctm), len(ctm[0])\n ident = mi(mctx)\n return isequal([mct, ctm, ident])\n\ndef printm(comment, m):\n print(comment)\n fields = [['%g%+gj' % (f.real, f.imag) for f in row] for row in m]\n width = max(max(len(f) for f in row) for row in fields)\n lines = (', '.join('%*s' % (width, f) for f in row) for row in fields)\n print('\\n'.join(lines))\n\nif __name__ == '__main__':\n for matrix in [\n ((( 3.000+0.000j), (+2.000+1.000j)), \n (( 2.000-1.000j), (+1.000+0.000j))),\n\n ((( 1.000+0.000j), (+1.000+0.000j), (+0.000+0.000j)), \n (( 0.000+0.000j), (+1.000+0.000j), (+1.000+0.000j)), \n (( 1.000+0.000j), (+0.000+0.000j), (+1.000+0.000j))),\n\n ((( 2**0.5/2+0.000j), (+2**0.5/2+0.000j), (+0.000+0.000j)), \n (( 0.000+2**0.5/2j), (+0.000-2**0.5/2j), (+0.000+0.000j)), \n (( 0.000+0.000j), (+0.000+0.000j), (+0.000+1.000j)))]:\n printm('\\nMatrix:', matrix)\n ct = conjugate_transpose(matrix)\n printm('Its conjugate transpose:', ct)\n print('Hermitian? %s.' % ishermitian(matrix, ct))\n print('Normal? %s.' % isnormal(matrix, ct))\n print('Unitary? %s.' % isunitary(matrix, ct))"} +{"title": "Continued fraction", "language": "ANSI C", "task": ":a_0 + \\cfrac{b_1}{a_1 + \\cfrac{b_2}{a_2 + \\cfrac{b_3}{a_3 + \\ddots}}}\n\nThe task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:\n\nFor the square root of 2, use a_0 = 1 then a_N = 2. b_N is always 1.\n\n:\\sqrt{2} = 1 + \\cfrac{1}{2 + \\cfrac{1}{2 + \\cfrac{1}{2 + \\ddots}}}\n\nFor Napier's Constant, use a_0 = 2, then a_N = N. b_1 = 1 then b_N = N-1.\n\n:e = 2 + \\cfrac{1}{1 + \\cfrac{1}{2 + \\cfrac{2}{3 + \\cfrac{3}{4 + \\ddots}}}}\n\nFor Pi, use a_0 = 3 then a_N = 6. b_N = (2N-1)^2.\n\n:\\pi = 3 + \\cfrac{1}{6 + \\cfrac{9}{6 + \\cfrac{25}{6 + \\ddots}}}\n\n\n;See also:\n:* \u00a0 [[Continued fraction/Arithmetic]] for tasks that do arithmetic over continued fractions.\n\n", "solution": "/* calculate approximations for continued fractions */\n#include \n\n/* kind of function that returns a series of coefficients */\ntypedef double (*coeff_func)(unsigned n);\n\n/* calculates the specified number of expansions of the continued fraction\n * described by the coefficient series f_a and f_b */\ndouble calc(coeff_func f_a, coeff_func f_b, unsigned expansions)\n{\n\tdouble a, b, r;\n\ta = b = r = 0.0;\n\n\tunsigned i;\n\tfor (i = expansions; i > 0; i--) {\n\t\ta = f_a(i);\n\t\tb = f_b(i);\n\t\tr = b / (a + r);\n\t}\n\ta = f_a(0);\n\n\treturn a + r;\n}\n\n/* series for sqrt(2) */\ndouble sqrt2_a(unsigned n)\n{\n\treturn n ? 2.0 : 1.0;\n}\n\ndouble sqrt2_b(unsigned n)\n{\n\treturn 1.0;\n}\n\n/* series for the napier constant */\ndouble napier_a(unsigned n)\n{\n\treturn n ? n : 2.0;\n}\n\ndouble napier_b(unsigned n)\n{\n\treturn n > 1.0 ? n - 1.0 : 1.0;\n}\n\n/* series for pi */\ndouble pi_a(unsigned n)\n{\n\treturn n ? 6.0 : 3.0;\n}\n\ndouble pi_b(unsigned n)\n{\n\tdouble c = 2.0 * n - 1.0;\n\n\treturn c * c;\n}\n\nint main(void)\n{\n\tdouble sqrt2, napier, pi;\n\n\tsqrt2 = calc(sqrt2_a, sqrt2_b, 1000);\n\tnapier = calc(napier_a, napier_b, 1000);\n\tpi = calc(pi_a, pi_b, 1000);\n\n\tprintf(\"%12.10g\\n%12.10g\\n%12.10g\\n\", sqrt2, napier, pi);\n\n\treturn 0;\n}"} +{"title": "Continued fraction", "language": "Python 2.6+ and 3.x", "task": ":a_0 + \\cfrac{b_1}{a_1 + \\cfrac{b_2}{a_2 + \\cfrac{b_3}{a_3 + \\ddots}}}\n\nThe task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:\n\nFor the square root of 2, use a_0 = 1 then a_N = 2. b_N is always 1.\n\n:\\sqrt{2} = 1 + \\cfrac{1}{2 + \\cfrac{1}{2 + \\cfrac{1}{2 + \\ddots}}}\n\nFor Napier's Constant, use a_0 = 2, then a_N = N. b_1 = 1 then b_N = N-1.\n\n:e = 2 + \\cfrac{1}{1 + \\cfrac{1}{2 + \\cfrac{2}{3 + \\cfrac{3}{4 + \\ddots}}}}\n\nFor Pi, use a_0 = 3 then a_N = 6. b_N = (2N-1)^2.\n\n:\\pi = 3 + \\cfrac{1}{6 + \\cfrac{9}{6 + \\cfrac{25}{6 + \\ddots}}}\n\n\n;See also:\n:* \u00a0 [[Continued fraction/Arithmetic]] for tasks that do arithmetic over continued fractions.\n\n", "solution": "from fractions import Fraction\nimport itertools\ntry: zip = itertools.izip\nexcept: pass\n \n# The Continued Fraction\ndef CF(a, b, t):\n terms = list(itertools.islice(zip(a, b), t))\n z = Fraction(1,1)\n for a, b in reversed(terms):\n z = a + b / z\n return z\n \n# Approximates a fraction to a string\ndef pRes(x, d):\n q, x = divmod(x, 1)\n res = str(q)\n res += \".\"\n for i in range(d):\n x *= 10\n q, x = divmod(x, 1)\n res += str(q)\n return res\n \n# Test the Continued Fraction for sqrt2\ndef sqrt2_a():\n yield 1\n for x in itertools.repeat(2):\n yield x\n \ndef sqrt2_b():\n for x in itertools.repeat(1):\n yield x\n \ncf = CF(sqrt2_a(), sqrt2_b(), 950)\nprint(pRes(cf, 200))\n#1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702492483605585073721264412149709993583141322266592750559275579995050115278206057147\n \n \n# Test the Continued Fraction for Napier's Constant\ndef Napier_a():\n yield 2\n for x in itertools.count(1):\n yield x\n \ndef Napier_b():\n yield 1\n for x in itertools.count(1):\n yield x\n \ncf = CF(Napier_a(), Napier_b(), 950)\nprint(pRes(cf, 200))\n#2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642742746639193200305992181741359662904357290033429526059563073813232862794349076323382988075319525101901\n \n# Test the Continued Fraction for Pi\ndef Pi_a():\n yield 3\n for x in itertools.repeat(6):\n yield x\n \ndef Pi_b():\n for x in itertools.count(1,2):\n yield x*x\n \ncf = CF(Pi_a(), Pi_b(), 950)\nprint(pRes(cf, 10))\n#3.1415926532"} +{"title": "Continued fraction/Arithmetic/Construct from rational number", "language": "C", "task": "The 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": "\n#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 \nAnd the run gives :\n\nRunning the examples :\nFor N = 1, D = 2 : 0 2\nFor N = 3, D = 1 : 3\nFor N = 23, D = 8 : 2 1 7\nFor N = 13, D = 11 : 1 5 2\nFor N = 22, D = 7 : 3 7\nFor N = -151, D = 77 : -1 -1 -24 -1 -2\n\nRunning for \u221a2 :\nFor N = 14142, D = 10000 : 1 2 2 2 2 2 1 1 29\nFor N = 141421, D = 100000 : 1 2 2 2 2 2 2 3 1 1 3 1 7 2\nFor N = 1414214, D = 1000000 : 1 2 2 2 2 2 2 2 3 6 1 2 1 12\nFor N = 14142136, D = 10000000 : 1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2\n\nRunning for \u03c0 :\nFor N = 31, D = 10 : 3 10\nFor N = 314, D = 100 : 3 7 7\nFor N = 3142, D = 1000 : 3 7 23 1 2\nFor N = 31428, D = 10000 : 3 7 357\nFor N = 314285, D = 100000 : 3 7 2857\nFor N = 3142857, D = 1000000 : 3 7 142857\nFor N = 31428571, D = 10000000 : 3 7 476190 3\nFor N = 314285714, D = 100000000 : 3 7 7142857\n\n"} +{"title": "Continued fraction/Arithmetic/Construct from rational number", "language": "Python", "task": "The 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": "def r2cf(n1,n2):\n while n2:\n n1, (t1, n2) = n2, divmod(n1, n2)\n yield t1\n\nprint(list(r2cf(1,2))) # => [0, 2]\nprint(list(r2cf(3,1))) # => [3]\nprint(list(r2cf(23,8))) # => [2, 1, 7]\nprint(list(r2cf(13,11))) # => [1, 5, 2]\nprint(list(r2cf(22,7))) # => [3, 7]\nprint(list(r2cf(14142,10000))) # => [1, 2, 2, 2, 2, 2, 1, 1, 29]\nprint(list(r2cf(141421,100000))) # => [1, 2, 2, 2, 2, 2, 2, 3, 1, 1, 3, 1, 7, 2]\nprint(list(r2cf(1414214,1000000))) # => [1, 2, 2, 2, 2, 2, 2, 2, 3, 6, 1, 2, 1, 12]\nprint(list(r2cf(14142136,10000000))) # => [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 6, 1, 2, 4, 1, 1, 2]"} +{"title": "Continued fraction/Arithmetic/G(matrix ng, continued fraction n)", "language": "C", "task": "This task investigates mathmatical operations that can be performed on a single continued fraction. This requires only a baby version of NG:\n: \\begin{bmatrix}\n a_1 & a \\\\\n b_1 & b \n\\end{bmatrix}\nI may perform perform the following operations:\n:Input the next term of N1\n:Output a term of the continued fraction resulting from the operation.\n\nI output a term if the integer parts of \\frac{a}{b} and \\frac{a_1}{b_1} are equal. Otherwise I input a term from N. If I need a term from N but N has no more terms I inject \\infty.\n\nWhen I input a term t my internal state: \\begin{bmatrix}\n a_1 & a \\\\\n b_1 & b \n\\end{bmatrix} is transposed thus \\begin{bmatrix} a + a_1 * t & a_1 \\\\\n b + b_1 * t & b_1 \n\\end{bmatrix}\n\nWhen I output a term t my internal state: \\begin{bmatrix}\n a_1 & a \\\\\n b_1 & b \n\\end{bmatrix} is transposed thus \\begin{bmatrix} b_1 & b \\\\\n a_1 - b_1 * t & a - b * t \n\\end{bmatrix}\n\nWhen I need a term t but there are no more my internal state: \\begin{bmatrix}\n a_1 & a \\\\\n b_1 & b \n\\end{bmatrix} is transposed thus \\begin{bmatrix} a_1 & a_1 \\\\\n b_1 & b_1 \n\\end{bmatrix}\n\nI am done when b1 and b are zero.\n\nDemonstrate your solution by calculating:\n:[1;5,2] + 1/2\n:[3;7] + 1/2 \n:[3;7] divided by 4\nUsing a generator for \\sqrt{2} (e.g., from [[Continued fraction]]) calculate \\frac{1}{\\sqrt{2}}. You are now at the starting line for using Continued Fractions to implement [[Arithmetic-geometric mean]] without ulps and epsilons.\n\nThe first step in implementing [[Arithmetic-geometric mean]] is to calculate \\frac{1 + \\frac{1}{\\sqrt{2}}}{2} do this now to cross the starting line and begin the race.\n\n", "solution": "\n/*------------------------------------------------------------------*/\n/* For C with Boehm GC as garbage collector. */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include /* Boehm GC. */\n\n/*------------------------------------------------------------------*/\n\n/* Let us choose an integer type. */\ntypedef long long int integer;\n\n/* We need consistent definitions of division and remainder. Let us\n set those here. For convenience (because C provides it), we will\n use truncation towards zero. */\n#define DIV(a, b) ((a) / (b))\n#define REM(a, b) ((a) % (b))\n\n/* Choose a memory allocator: Boehm GC. (Ideally one should check for\n NULL return values, but for this pedagogical example let us skip\n that.) */\n#define MALLOC_INIT() GC_INIT ()\n#define MALLOC GC_MALLOC\n#define REALLOC GC_REALLOC\n#define FREE GC_FREE /* Or one could make this a no-op. */\n\n/*------------------------------------------------------------------*/\n/* Some operations on char-strings. (In practice, I would write an m4\n macro to create such repetitive C functions for me. Of course, it\n is also possible to use or some such [generally unsafe]\n mechanism.) */\n\nstatic char *\nstring_append1 (const char *s1)\n{\n size_t n1 = strlen (s1);\n char *s = MALLOC (n1 + 1);\n s[n1] = '\\0';\n memcpy (s, s1, n1);\n return s;\n}\n\nstatic char *\nstring_append2 (const char *s1, const char *s2)\n{\n size_t n1 = strlen (s1);\n size_t n2 = strlen (s2);\n char *s = MALLOC (n1 + n2 + 1);\n s[n1 + n2] = '\\0';\n memcpy (s, s1, n1);\n memcpy (s + n1, s2, n2);\n return s;\n}\n\nstatic char *\nstring_append3 (const char *s1, const char *s2, const char *s3)\n{\n size_t n1 = strlen (s1);\n size_t n2 = strlen (s2);\n size_t n3 = strlen (s3);\n char *s = MALLOC (n1 + n2 + n3 + 1);\n s[n1 + n2 + n3] = '\\0';\n memcpy (s, s1, n1);\n memcpy (s + n1, s2, n2);\n memcpy (s + n1 + n2, s3, n3);\n return s;\n}\n\n/*------------------------------------------------------------------*/\n/* Continued fractions as processes for generating terms. The terms\n are memoized and are accessed by their zero-based index. */\n\ntypedef void cf_generator_func_t (void *env, bool *there_is_a_term,\n integer *term);\n\nstruct _cf_generator /* For practical purposes, this is a closure. */\n{\n cf_generator_func_t *func;\n void *env;\n};\n\ntypedef struct _cf_generator *cf_generator_t;\n\nstruct _cf\n{\n bool terminated; /* No more terms? */\n size_t m; /* The number of terms computed so far. */\n size_t n; /* The size of memo storage. */\n integer *memo; /* Memoized terms. */\n cf_generator_t gen; /* A closure to generate terms. */\n};\n\ntypedef struct _cf *cf_t;\n\ncf_generator_t\ncf_generator_make (cf_generator_func_t func, void *env)\n{\n cf_generator_t gen = MALLOC (sizeof (struct _cf_generator));\n gen->func = func;\n gen->env = env;\n return gen;\n}\n\ncf_t\ncf_make (cf_generator_t gen)\n{\n const size_t start_size = 8;\n integer *memo = MALLOC (start_size * sizeof (integer));\n cf_t cf = MALLOC (sizeof (struct _cf));\n cf->terminated = false;\n cf->m = 0;\n cf->n = start_size;\n cf->memo = memo;\n cf->gen = gen;\n return cf;\n}\n\nstatic void\n_cf_get_more_terms (cf_t cf, size_t needed)\n{\n size_t term_count = cf->m;\n bool done = false;\n while (!done)\n {\n if (term_count == needed)\n {\n cf->m = needed;\n done = true;\n }\n else\n {\n bool there_is_a_term;\n integer term;\n cf->gen->func (cf->gen->env, &there_is_a_term, &term);\n if (there_is_a_term)\n {\n cf->memo[term_count] = term;\n term_count += 1;\n }\n else\n {\n cf->terminated = true;\n cf->m = term_count;\n done = true;\n }\n }\n }\n}\n\nstatic void\n_cf_update (cf_t cf, size_t needed)\n{\n if (cf->terminated || needed <= (cf->m))\n /* Do nothing. */ ;\n else if (needed <= (cf->n))\n _cf_get_more_terms (cf, needed);\n else\n {\n /* Provide twice the needed storage. */\n cf->n = 2 * needed;\n cf->memo = REALLOC (cf->memo, cf->n * sizeof (integer));\n _cf_get_more_terms (cf, needed);\n }\n}\n\nvoid\ncf_get_at (cf_t cf, size_t i, bool *there_is_a_term,\n integer *term)\n{\n _cf_update (cf, i + 1);\n *there_is_a_term = (i < (cf->m));\n if (*there_is_a_term)\n *term = cf->memo[i];\n}\n\nchar *\ncf2string_max_terms (cf_t cf, size_t max_terms)\n{\n char *s = string_append1 (\"[\");\n const char *sep = \"\";\n size_t i = 0;\n bool done = false;\n while (!done)\n {\n if (i == max_terms)\n {\n s = string_append2 (s, \",...]\");\n done = true;\n }\n else\n {\n bool there_is_a_term;\n integer term;\n cf_get_at (cf, i, &there_is_a_term, &term);\n if (there_is_a_term)\n {\n char buf1[1];\n const int numeral_len =\n snprintf (buf1, 1, \"%jd\", (intmax_t) term);\n char buf[numeral_len + 1];\n snprintf (buf, numeral_len + 1, \"%jd\", (intmax_t) term);\n s = string_append3 (s, sep, buf);\n sep = (sep[0] == '\\0') ? \";\" : \",\";\n i += 1;\n }\n else\n {\n s = string_append2 (s, \"]\");\n done = true;\n }\n }\n }\n return s;\n}\n\nchar *\ncf2string (cf_t cf)\n{\n const size_t default_max_terms = 20;\n return cf2string_max_terms (cf, default_max_terms);\n}\n\n/*------------------------------------------------------------------*/\n/* Using a cf_t as a cf_generator_t. */\n\nstruct _cf_gen_env\n{\n cf_t cf;\n size_t i;\n};\n\nstatic void\ncf_gen_run (void *env, bool *there_is_a_term, integer *term)\n{\n struct _cf_gen_env *state = env;\n cf_get_at (state->cf, state->i, there_is_a_term, term);\n state->i += 1;\n}\n\ncf_generator_t\ncf_gen_make (cf_t cf)\n{\n struct _cf_gen_env *state = MALLOC (sizeof (struct _cf_gen_env));\n state->cf = cf;\n state->i = 0;\n return cf_generator_make (cf_gen_run, state);\n}\n\n/*------------------------------------------------------------------*/\n/* A homographic function. */\n\nstruct _hfunc\n{\n integer a1;\n integer a;\n integer b1;\n integer b;\n};\n\ntypedef struct _hfunc *hfunc_t;\n\nstruct _hfunc_gen_env\n{\n struct _hfunc state;\n cf_generator_t gen;\n};\n\nhfunc_t\nhfunc_make (integer a1, integer a, integer b1, integer b)\n{\n hfunc_t f = MALLOC (sizeof (struct _hfunc));\n f->a1 = a1;\n f->a = a;\n f->b1 = b1;\n f->b = b;\n return f;\n}\n\nstatic void\n_take_term_from_ngen (struct _hfunc *state,\n cf_generator_t ngen)\n{\n const integer a1 = state->a1;\n const integer b1 = state->b1;\n\n bool there_is_a_term;\n integer term;\n ngen->func (ngen->env, &there_is_a_term, &term);\n if (there_is_a_term)\n {\n const integer a = state->a;\n const integer b = state->b;\n\n state->a1 = a + (a1 * term);\n state->a = a1;\n state->b1 = b + (b1 * term);\n state->b = b1;\n }\n else\n {\n state->a = a1;\n state->b = b1;\n }\n}\n\nstatic void\n_adjust_state_for_term_output (struct _hfunc *state,\n integer term)\n{\n const integer a1 = state->a1;\n const integer a = state->a;\n const integer b1 = state->b1;\n const integer b = state->b;\n\n state->a1 = b1;\n state->a = b;\n state->b1 = a1 - (b1 * term);\n state->b = a - (b * term);\n}\n\nstatic void\nhfunc_gen_run (void *env, bool *there_is_a_term, integer *term)\n{\n struct _hfunc *state = &(((struct _hfunc_gen_env *) env)->state);\n cf_generator_t ngen = ((struct _hfunc_gen_env *) env)->gen;\n\n bool done = false;\n while (!done)\n {\n const bool b1_iseqz = (state->b1 == 0);\n const bool b_iseqz = (state->b == 0);\n if (b1_iseqz && b_iseqz)\n {\n *there_is_a_term = false;\n done = true;\n }\n else if (!b1_iseqz && !b_iseqz)\n {\n const integer q1 = DIV (state->a1, state->b1);\n const integer q = DIV (state->a, state->b);\n if (q1 == q)\n {\n _adjust_state_for_term_output (state, q);\n *there_is_a_term = true;\n *term = q;\n done = true;\n }\n else\n _take_term_from_ngen (state, ngen);\n }\n else\n _take_term_from_ngen (state, ngen);\n }\n}\n\n/* Make a new generator that applies an hfunc_t to another\n generator. */\ncf_generator_t\nhfunc_gen_make (hfunc_t f, cf_generator_t gen)\n{\n struct _hfunc_gen_env *env =\n MALLOC (sizeof (struct _hfunc_gen_env));\n env->state = *f;\n env->gen = gen;\n return cf_generator_make (hfunc_gen_run, env);\n}\n\n/* Make a new cf_t that applies an hfunc_t to another cf_t. */\ncf_t\nhfunc_apply (hfunc_t f, cf_t cf)\n{\n cf_generator_t gen1 = cf_gen_make (cf);\n cf_generator_t gen2 = hfunc_gen_make (f, gen1);\n return cf_make (gen2);\n}\n\n/*------------------------------------------------------------------*/\n/* Creation of a cf_t for a rational number. */\n\nstruct _r2cf_gen_env\n{\n integer n;\n integer d;\n};\n\nstatic void\nr2cf_gen_run (void *env, bool *there_is_a_term, integer *term)\n{\n struct _r2cf_gen_env *state = env;\n *there_is_a_term = (state->d != 0);\n if (*there_is_a_term)\n {\n const integer q = DIV (state->n, state->d);\n const integer r = REM (state->n, state->d);\n state->n = state->d;\n state->d = r;\n *term = q;\n }\n}\n\ncf_generator_t\nr2cf_gen_make (integer n, integer d)\n{\n struct _r2cf_gen_env *state =\n MALLOC (sizeof (struct _r2cf_gen_env));\n state->n = n;\n state->d = d;\n return cf_generator_make (r2cf_gen_run, state);\n}\n\ncf_t\nr2cf (integer n, integer d)\n{\n return cf_make (r2cf_gen_make (n, d));\n}\n\n/*------------------------------------------------------------------*/\n/* Creation of a cf_t for sqrt(2). */\n\nstruct _sqrt2_gen_env\n{\n integer term;\n};\n\nstatic void\nsqrt2_gen_run (void *env, bool *there_is_a_term, integer *term)\n{\n struct _sqrt2_gen_env *state = env;\n *there_is_a_term = true;\n *term = state->term;\n state->term = 2;\n}\n\ncf_generator_t\nsqrt2_gen_make (void)\n{\n struct _sqrt2_gen_env *state =\n MALLOC (sizeof (struct _sqrt2_gen_env));\n state->term = 1;\n return cf_generator_make (sqrt2_gen_run, state);\n}\n\ncf_t\nsqrt2_make (void)\n{\n return cf_make (sqrt2_gen_make ());\n}\n\n/*------------------------------------------------------------------*/\n\nint\nmain (void)\n{\n MALLOC_INIT ();\n\n hfunc_t add_one_half = hfunc_make (2, 1, 0, 2);\n hfunc_t add_one = hfunc_make (1, 1, 0, 1);\n hfunc_t divide_by_two = hfunc_make (1, 0, 0, 2);\n hfunc_t divide_by_four = hfunc_make (1, 0, 0, 4);\n hfunc_t take_reciprocal = hfunc_make (0, 1, 1, 0);\n hfunc_t add_one_then_div_two = hfunc_make (1, 1, 0, 2);\n hfunc_t add_two_then_div_four = hfunc_make (1, 2, 0, 4);\n\n cf_t cf_13_11 = r2cf (13, 11);\n cf_t cf_22_7 = r2cf (22, 7);\n cf_t cf_sqrt2 = sqrt2_make ();\n\n cf_t cf_13_11_plus_1_2 = hfunc_apply (add_one_half, cf_13_11);\n cf_t cf_22_7_plus_1_2 = hfunc_apply (add_one_half, cf_22_7);\n cf_t cf_22_7_div_4 = hfunc_apply (divide_by_four, cf_22_7);\n\n /* The following two give the same result: */\n cf_t cf_sqrt2_div_2 = hfunc_apply (divide_by_two, cf_sqrt2);\n cf_t cf_1_div_sqrt2 = hfunc_apply (take_reciprocal, cf_sqrt2);\n assert (strcmp (cf2string (cf_sqrt2_div_2),\n cf2string (cf_1_div_sqrt2)) == 0);\n\n /* The following three give the same result: */\n cf_t cf_2_plus_sqrt2_grouped_div_4 =\n hfunc_apply (add_two_then_div_four, cf_sqrt2);\n cf_t cf_half_of_1_plus_half_sqrt2 =\n hfunc_apply (add_one_then_div_two, cf_sqrt2_div_2);\n cf_t cf_half_of_1_plus_1_div_sqrt2 =\n hfunc_apply (divide_by_two,\n hfunc_apply (add_one, cf_sqrt2_div_2));\n assert (strcmp (cf2string (cf_2_plus_sqrt2_grouped_div_4),\n cf2string (cf_half_of_1_plus_half_sqrt2)) == 0);\n assert (strcmp (cf2string (cf_half_of_1_plus_half_sqrt2),\n cf2string (cf_half_of_1_plus_1_div_sqrt2)) == 0);\n\n printf (\"13/11 => %s\\n\", cf2string (cf_13_11));\n printf (\"22/7 => %s\\n\", cf2string (cf_22_7));\n printf (\"sqrt(2) => %s\\n\", cf2string (cf_sqrt2));\n printf (\"13/11 + 1/2 => %s\\n\", cf2string (cf_13_11_plus_1_2));\n printf (\"22/7 + 1/2 => %s\\n\", cf2string (cf_22_7_plus_1_2));\n printf (\"(22/7)/4 => %s\\n\", cf2string (cf_22_7_div_4));\n printf (\"sqrt(2)/2 => %s\\n\", cf2string (cf_sqrt2_div_2));\n printf (\"1/sqrt(2) => %s\\n\", cf2string (cf_1_div_sqrt2));\n printf (\"(2+sqrt(2))/4 => %s\\n\",\n cf2string (cf_2_plus_sqrt2_grouped_div_4));\n printf (\"(1+sqrt(2)/2)/2 => %s\\n\",\n cf2string (cf_half_of_1_plus_half_sqrt2));\n printf (\"(1+1/sqrt(2))/2 => %s\\n\",\n cf2string (cf_half_of_1_plus_1_div_sqrt2));\n\n return 0;\n}\n\n/*------------------------------------------------------------------*/\n"} +{"title": "Continued fraction/Arithmetic/G(matrix ng, continued fraction n)", "language": "Python", "task": "This task investigates mathmatical operations that can be performed on a single continued fraction. This requires only a baby version of NG:\n: \\begin{bmatrix}\n a_1 & a \\\\\n b_1 & b \n\\end{bmatrix}\nI may perform perform the following operations:\n:Input the next term of N1\n:Output a term of the continued fraction resulting from the operation.\n\nI output a term if the integer parts of \\frac{a}{b} and \\frac{a_1}{b_1} are equal. Otherwise I input a term from N. If I need a term from N but N has no more terms I inject \\infty.\n\nWhen I input a term t my internal state: \\begin{bmatrix}\n a_1 & a \\\\\n b_1 & b \n\\end{bmatrix} is transposed thus \\begin{bmatrix} a + a_1 * t & a_1 \\\\\n b + b_1 * t & b_1 \n\\end{bmatrix}\n\nWhen I output a term t my internal state: \\begin{bmatrix}\n a_1 & a \\\\\n b_1 & b \n\\end{bmatrix} is transposed thus \\begin{bmatrix} b_1 & b \\\\\n a_1 - b_1 * t & a - b * t \n\\end{bmatrix}\n\nWhen I need a term t but there are no more my internal state: \\begin{bmatrix}\n a_1 & a \\\\\n b_1 & b \n\\end{bmatrix} is transposed thus \\begin{bmatrix} a_1 & a_1 \\\\\n b_1 & b_1 \n\\end{bmatrix}\n\nI am done when b1 and b are zero.\n\nDemonstrate your solution by calculating:\n:[1;5,2] + 1/2\n:[3;7] + 1/2 \n:[3;7] divided by 4\nUsing a generator for \\sqrt{2} (e.g., from [[Continued fraction]]) calculate \\frac{1}{\\sqrt{2}}. You are now at the starting line for using Continued Fractions to implement [[Arithmetic-geometric mean]] without ulps and epsilons.\n\nThe first step in implementing [[Arithmetic-geometric mean]] is to calculate \\frac{1 + \\frac{1}{\\sqrt{2}}}{2} do this now to cross the starting line and begin the race.\n\n", "solution": "class NG:\n def __init__(self, a1, a, b1, b):\n self.a1, self.a, self.b1, self.b = a1, a, b1, b\n\n def ingress(self, n):\n self.a, self.a1 = self.a1, self.a + self.a1 * n\n self.b, self.b1 = self.b1, self.b + self.b1 * n\n\n @property\n def needterm(self):\n return (self.b == 0 or self.b1 == 0) or not self.a//self.b == self.a1//self.b1\n\n @property\n def egress(self):\n n = self.a // self.b\n self.a, self.b = self.b, self.a - self.b * n\n self.a1, self.b1 = self.b1, self.a1 - self.b1 * n\n return n\n\n @property\n def egress_done(self):\n if self.needterm: self.a, self.b = self.a1, self.b1\n return self.egress\n\n @property\n def done(self):\n return self.b == 0 and self.b1 == 0"} +{"title": "Convert decimal number to rational", "language": "C", "task": "The task is to write a program to transform a decimal number into a fraction in lowest terms.\n\nIt is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333...\n\nBecause of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals:\n* 67 / 74 = 0.9(054) = 0.9054054...\n* 14 / 27 = 0.(518) = 0.518518...\n\nAcceptable output:\n\n* 0.9054054 \u2192 4527027 / 5000000\n* 0.518518 \u2192 259259 / 500000\n\nFinite decimals are of course no problem:\n\n* 0.75 \u2192 3 / 4 \n\n", "solution": "#include \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 decimal number to rational", "language": "JavaScript", "task": "The task is to write a program to transform a decimal number into a fraction in lowest terms.\n\nIt is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333...\n\nBecause of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals:\n* 67 / 74 = 0.9(054) = 0.9054054...\n* 14 / 27 = 0.(518) = 0.518518...\n\nAcceptable output:\n\n* 0.9054054 \u2192 4527027 / 5000000\n* 0.518518 \u2192 259259 / 500000\n\nFinite decimals are of course no problem:\n\n* 0.75 \u2192 3 / 4 \n\n", "solution": "(() => {\n 'use strict';\n\n const main = () =>\n showJSON(\n map( // Using a tolerance epsilon of 1/10000\n n => showRatio(approxRatio(0.0001)(n)),\n [0.9054054, 0.518518, 0.75]\n )\n );\n\n // Epsilon -> Real -> Ratio\n\n // approxRatio :: Real -> Real -> Ratio\n const approxRatio = eps => n => {\n const\n gcde = (e, x, y) => {\n const _gcd = (a, b) => (b < e ? a : _gcd(b, a % b));\n return _gcd(Math.abs(x), Math.abs(y));\n },\n c = gcde(Boolean(eps) ? eps : (1 / 10000), 1, n);\n return Ratio(\n Math.floor(n / c), // numerator\n Math.floor(1 / c) // denominator\n );\n };\n\n // GENERIC FUNCTIONS ----------------------------------\n\n // Ratio :: Int -> Int -> Ratio\n const Ratio = (n, d) => ({\n type: 'Ratio',\n 'n': n, // numerator\n 'd': d // denominator\n });\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) => xs.map(f);\n\n // showJSON :: a -> String\n const showJSON = x => JSON.stringify(x, null, 2);\n\n // showRatio :: Ratio -> String\n const showRatio = nd =>\n nd.n.toString() + '/' + nd.d.toString();\n\n // MAIN ---\n return main();\n})();"} +{"title": "Convert decimal number to rational", "language": "Python 2.6+", "task": "The task is to write a program to transform a decimal number into a fraction in lowest terms.\n\nIt is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333...\n\nBecause of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals:\n* 67 / 74 = 0.9(054) = 0.9054054...\n* 14 / 27 = 0.(518) = 0.518518...\n\nAcceptable output:\n\n* 0.9054054 \u2192 4527027 / 5000000\n* 0.518518 \u2192 259259 / 500000\n\nFinite decimals are of course no problem:\n\n* 0.75 \u2192 3 / 4 \n\n", "solution": ">>> from fractions import Fraction\n>>> for d in (0.9054054, 0.518518, 0.75): print(d, Fraction.from_float(d).limit_denominator(100))\n\n0.9054054 67/74\n0.518518 14/27\n0.75 3/4\n>>> for d in '0.9054054 0.518518 0.75'.split(): print(d, Fraction(d))\n\n0.9054054 4527027/5000000\n0.518518 259259/500000\n0.75 3/4\n>>> "} +{"title": "Convert decimal number to rational", "language": "Python 3.7", "task": "The task is to write a program to transform a decimal number into a fraction in lowest terms.\n\nIt is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333...\n\nBecause of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals:\n* 67 / 74 = 0.9(054) = 0.9054054...\n* 14 / 27 = 0.(518) = 0.518518...\n\nAcceptable output:\n\n* 0.9054054 \u2192 4527027 / 5000000\n* 0.518518 \u2192 259259 / 500000\n\nFinite decimals are of course no problem:\n\n* 0.75 \u2192 3 / 4 \n\n", "solution": "'''Approximate rationals from decimals'''\n\nfrom math import (floor, gcd)\nimport sys\n\n\n# approxRatio :: Float -> Float -> Ratio\ndef approxRatio(epsilon):\n '''The simplest rational approximation to\n n within the margin given by epsilon.\n '''\n def gcde(e, x, y):\n def _gcd(a, b):\n return a if b < e else _gcd(b, a % b)\n return _gcd(abs(x), abs(y))\n return lambda n: (lambda c=(\n gcde(epsilon if 0 < epsilon else (0.0001), 1, n)\n ): ratio(floor(n / c))(floor(1 / c)))()\n\n\n# main :: IO ()\ndef main():\n '''Conversions at different levels of precision.'''\n\n xs = [0.9054054, 0.518518, 0.75]\n print(\n fTable(__doc__ + ' (epsilon of 1/10000):\\n')(str)(\n lambda r: showRatio(r) + ' -> ' + repr(fromRatio(r))\n )(\n approxRatio(1 / 10000)\n )(xs)\n )\n print('\\n')\n\n e = minBound(float)\n print(\n fTable(__doc__ + ' (epsilon of ' + repr(e) + '):\\n')(str)(\n lambda r: showRatio(r) + ' -> ' + repr(fromRatio(r))\n )(\n approxRatio(e)\n )(xs)\n )\n\n\n# GENERIC -------------------------------------------------\n\n# fromRatio :: Ratio Int -> Float\ndef fromRatio(r):\n '''A floating point value derived from a\n a rational value.\n '''\n return r.get('numerator') / r.get('denominator')\n\n\n# minBound :: Bounded Type -> a\ndef minBound(t):\n '''Minimum value for a bounded type.'''\n maxsize = sys.maxsize\n float_infomin = sys.float_info.min\n return {\n int: (-maxsize - 1),\n float: float_infomin,\n bool: False,\n str: chr(0)\n }[t]\n\n\n# ratio :: Int -> Int -> Ratio Int\ndef ratio(n):\n '''Rational value constructed\n from a numerator and a denominator.\n '''\n def go(n, d):\n g = gcd(n, d)\n return {\n 'type': 'Ratio',\n 'numerator': n // g, 'denominator': d // g\n }\n return lambda d: go(n * signum(d), abs(d))\n\n\n# showRatio :: Ratio -> String\ndef showRatio(r):\n '''String representation of the ratio r.'''\n d = r.get('denominator')\n return str(r.get('numerator')) + (\n ' / ' + str(d) if 1 != d else ''\n )\n\n\n# signum :: Num -> Num\ndef signum(n):\n '''The sign of n.'''\n return -1 if 0 > n else (1 if 0 < n else 0)\n\n\n# DISPLAY -------------------------------------------------\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\n '''\n def go(xShow, fxShow, f, xs):\n ys = [xShow(x) for x in xs]\n w = max(map(len, ys))\n return s + '\\n' + '\\n'.join(map(\n lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n xs, ys\n ))\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} +{"title": "Convert seconds to compound duration", "language": "C", "task": "[[Category:Date and time]]\n\n;Task:\nWrite a function or program which:\n* \u00a0 takes a positive integer representing a duration in seconds as input (e.g., 100), and\n* \u00a0 returns a string which shows the same duration decomposed into:\n:::* \u00a0 weeks,\n:::* \u00a0 days, \n:::* \u00a0 hours, \n:::* \u00a0 minutes, \u00a0 and \n:::* \u00a0 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": "\n#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"} +{"title": "Convert seconds to compound duration", "language": "JavaScript", "task": "[[Category:Date and time]]\n\n;Task:\nWrite a function or program which:\n* \u00a0 takes a positive integer representing a duration in seconds as input (e.g., 100), and\n* \u00a0 returns a string which shows the same duration decomposed into:\n:::* \u00a0 weeks,\n:::* \u00a0 days, \n:::* \u00a0 hours, \n:::* \u00a0 minutes, \u00a0 and \n:::* \u00a0 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": "(function () {\n 'use strict';\n\n // angloDuration :: Int -> String\n function angloDuration(intSeconds) {\n return zip(\n weekParts(intSeconds), \n ['wk', 'd', 'hr', 'min','sec']\n )\n .reduce(function (a, x) {\n return a.concat(x[0] ? (\n [(x[0].toString() + ' ' + x[1])]\n ) : []);\n }, [])\n .join(', ');\n }\n \n \n\n // weekParts :: Int -> [Int]\n function weekParts(intSeconds) {\n\n return [undefined, 7, 24, 60, 60]\n .reduceRight(function (a, x) {\n var intRest = a.remaining,\n intMod = isNaN(x) ? intRest : intRest % x;\n\n return {\n remaining:(intRest - intMod) / (x || 1),\n parts: [intMod].concat(a.parts)\n };\n }, {\n remaining: intSeconds,\n parts: []\n })\n .parts\n }\n \n // GENERIC ZIP\n\n // zip :: [a] -> [b] -> [(a,b)]\n function zip(xs, ys) {\n return xs.length === ys.length ? (\n xs.map(function (x, i) {\n return [x, ys[i]];\n })\n ) : undefined;\n }\n \n // TEST\n\n return [7259, 86400, 6000000]\n .map(function (intSeconds) {\n return intSeconds.toString() +\n ' -> ' + angloDuration(intSeconds);\n })\n .join('\\n');\n\n})();\n"} +{"title": "Convert seconds to compound duration", "language": "Python", "task": "[[Category:Date and time]]\n\n;Task:\nWrite a function or program which:\n* \u00a0 takes a positive integer representing a duration in seconds as input (e.g., 100), and\n* \u00a0 returns a string which shows the same duration decomposed into:\n:::* \u00a0 weeks,\n:::* \u00a0 days, \n:::* \u00a0 hours, \n:::* \u00a0 minutes, \u00a0 and \n:::* \u00a0 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": "'''Compound duration'''\n\nfrom functools import reduce\nfrom itertools import chain\n\n\n# compoundDurationFromUnits :: [Num] -> [String] -> Num -> [(Num, String)]\ndef compoundDurationFromUnits(qs):\n '''A list of compound string representions of a number n of time units,\n in terms of the multiples given in qs, and the labels given in ks.\n '''\n return lambda ks: lambda n: list(\n chain.from_iterable(map(\n lambda v, k: [(v, k)] if 0 < v else [],\n mapAccumR(\n lambda a, x: divmod(a, x) if 0 < x else (1, a)\n )(n)(qs)[1],\n ks\n ))\n )\n\n\n# --------------------------TEST---------------------------\n# main :: IO ()\ndef main():\n '''Tests of various durations, with a\n particular set of units and labels.\n '''\n\n print(\n fTable('Compound durations from numbers of seconds:\\n')(str)(\n quoted(\"'\")\n )(\n lambda n: ', '.join([\n str(v) + ' ' + k for v, k in\n compoundDurationFromUnits([0, 7, 24, 60, 60])(\n ['wk', 'd', 'hr', 'min', 'sec']\n )(n)\n ])\n )([7259, 86400, 6000000])\n )\n\n\n# -------------------------GENERIC-------------------------\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\n '''\n def go(xShow, fxShow, f, xs):\n ys = [xShow(x) for x in xs]\n w = max(map(len, ys))\n return s + '\\n' + '\\n'.join(map(\n lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n xs, ys\n ))\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\n# mapAccumR :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])\ndef mapAccumR(f):\n '''A tuple of an accumulation and a list derived by a combined\n map and fold, with accumulation from right to left.\n '''\n def go(a, x):\n acc, y = f(a[0], x)\n return (acc, [y] + a[1])\n return lambda acc: lambda xs: (\n reduce(go, reversed(xs), (acc, []))\n )\n\n\n# quoted :: Char -> String -> String\ndef quoted(c):\n '''A string flanked on both sides\n by a specified quote character.\n '''\n return lambda s: c + s + c\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} +{"title": "Copy stdin to stdout", "language": "C", "task": "Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.\n\n", "solution": "\n#include \n\nint main(){\n char c;\n while ( (c=getchar()) != EOF ){\n putchar(c);\n }\n return 0;\n}\n"} +{"title": "Copy stdin to stdout", "language": "JavaScript", "task": "Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.\n\n", "solution": "process.stdin.resume();\nprocess.stdin.pipe(process.stdout);"} +{"title": "Copy stdin to stdout", "language": "Python", "task": "Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.\n\n", "solution": "
python -c 'import sys; sys.stdout.write(sys.stdin.read())'
\n\n"} +{"title": "Count the coins", "language": "C", "task": "There are four types of common coins in \u00a0 [https://en.wikipedia.org/wiki/United_States US] \u00a0 currency: \n:::# \u00a0 quarters \u00a0 (25 cents)\n:::# \u00a0 dimes \u00a0 (10 cents)\n:::# \u00a0 nickels \u00a0 (5 cents), \u00a0 and \n:::# \u00a0 pennies \u00a0 (1 cent) \n\n\nThere are six ways to make change for 15 cents:\n:::# \u00a0 A dime and a nickel \n:::# \u00a0 A dime and 5 pennies\n:::# \u00a0 3 nickels\n:::# \u00a0 2 nickels and 5 pennies\n:::# \u00a0 A nickel and 10 pennies\n:::# \u00a0 15 pennies\n\n\n;Task:\nHow many ways are there to make change for a dollar using these common coins? \u00a0 \u00a0 (1 dollar = 100 cents).\n\n\n;Optional:\nLess common are dollar coins (100 cents); \u00a0 and very rare are half dollars (50 cents). \u00a0 With the addition of these two coins, how many ways are there to make change for $1000? \n\n(Note: \u00a0 the answer is larger than \u00a0 232).\n\n\n;References:\n* [https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book-Z-H-11.html#%_sec_Temp_52 an algorithm] from the book ''Structure and Interpretation of Computer Programs''.\n* [https://algorithmist.com/wiki/Coin_change 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": "Count the coins", "language": "JavaScript", "task": "There are four types of common coins in \u00a0 [https://en.wikipedia.org/wiki/United_States US] \u00a0 currency: \n:::# \u00a0 quarters \u00a0 (25 cents)\n:::# \u00a0 dimes \u00a0 (10 cents)\n:::# \u00a0 nickels \u00a0 (5 cents), \u00a0 and \n:::# \u00a0 pennies \u00a0 (1 cent) \n\n\nThere are six ways to make change for 15 cents:\n:::# \u00a0 A dime and a nickel \n:::# \u00a0 A dime and 5 pennies\n:::# \u00a0 3 nickels\n:::# \u00a0 2 nickels and 5 pennies\n:::# \u00a0 A nickel and 10 pennies\n:::# \u00a0 15 pennies\n\n\n;Task:\nHow many ways are there to make change for a dollar using these common coins? \u00a0 \u00a0 (1 dollar = 100 cents).\n\n\n;Optional:\nLess common are dollar coins (100 cents); \u00a0 and very rare are half dollars (50 cents). \u00a0 With the addition of these two coins, how many ways are there to make change for $1000? \n\n(Note: \u00a0 the answer is larger than \u00a0 232).\n\n\n;References:\n* [https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book-Z-H-11.html#%_sec_Temp_52 an algorithm] from the book ''Structure and Interpretation of Computer Programs''.\n* [https://algorithmist.com/wiki/Coin_change an article in the algorithmist].\n* Change-making problem on Wikipedia.\n\n", "solution": "function countcoins(t, o) {\n 'use strict';\n var targetsLength = t + 1;\n var operandsLength = o.length;\n t = [1];\n\n for (var a = 0; a < operandsLength; a++) {\n for (var b = 1; b < targetsLength; b++) {\n\n // initialise undefined target\n t[b] = t[b] ? t[b] : 0;\n\n // accumulate target + operand ways\n t[b] += (b < o[a]) ? 0 : t[b - o[a]];\n }\n }\n\n return t[targetsLength - 1];\n}"} +{"title": "Count the coins", "language": "Python", "task": "There are four types of common coins in \u00a0 [https://en.wikipedia.org/wiki/United_States US] \u00a0 currency: \n:::# \u00a0 quarters \u00a0 (25 cents)\n:::# \u00a0 dimes \u00a0 (10 cents)\n:::# \u00a0 nickels \u00a0 (5 cents), \u00a0 and \n:::# \u00a0 pennies \u00a0 (1 cent) \n\n\nThere are six ways to make change for 15 cents:\n:::# \u00a0 A dime and a nickel \n:::# \u00a0 A dime and 5 pennies\n:::# \u00a0 3 nickels\n:::# \u00a0 2 nickels and 5 pennies\n:::# \u00a0 A nickel and 10 pennies\n:::# \u00a0 15 pennies\n\n\n;Task:\nHow many ways are there to make change for a dollar using these common coins? \u00a0 \u00a0 (1 dollar = 100 cents).\n\n\n;Optional:\nLess common are dollar coins (100 cents); \u00a0 and very rare are half dollars (50 cents). \u00a0 With the addition of these two coins, how many ways are there to make change for $1000? \n\n(Note: \u00a0 the answer is larger than \u00a0 232).\n\n\n;References:\n* [https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book-Z-H-11.html#%_sec_Temp_52 an algorithm] from the book ''Structure and Interpretation of Computer Programs''.\n* [https://algorithmist.com/wiki/Coin_change an article in the algorithmist].\n* Change-making problem on Wikipedia.\n\n", "solution": "try:\n import psyco\n psyco.full()\nexcept ImportError:\n pass\n\ndef count_changes(amount_cents, coins):\n n = len(coins)\n # max([]) instead of max() for Psyco\n cycle = max([c+1 for c in coins if c <= amount_cents]) * n\n table = [0] * cycle\n for i in xrange(n):\n table[i] = 1\n\n pos = n\n for s in xrange(1, amount_cents + 1):\n for i in xrange(n):\n if i == 0 and pos >= cycle:\n pos = 0\n if coins[i] <= s:\n q = pos - coins[i] * n\n table[pos]= table[q] if (q >= 0) else table[q + cycle]\n if i:\n table[pos] += table[pos - 1]\n pos += 1\n return table[pos - 1]\n\ndef main():\n us_coins = [100, 50, 25, 10, 5, 1]\n eu_coins = [200, 100, 50, 20, 10, 5, 2, 1]\n\n for coins in (us_coins, eu_coins):\n print count_changes( 100, coins[2:])\n print count_changes( 100000, coins)\n print count_changes( 1000000, coins)\n print count_changes(10000000, coins), \"\\n\"\n\nmain()"} +{"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\"XYZ\");\n\tfor (i = 0; i < 4; i++) {\n\t\tprintf(\"%d%d%d%d\", i,\n\t\t\trand() % 10000, rand() % 10000, rand() % 10000);\n\t}\n\tprintf(\"\");\n\n\treturn 0;\n}"} +{"title": "Create an HTML table", "language": "JavaScript", "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": "(() => {\n 'use strict';\n\n // HTML ---------------------------------------------\n\n // treeHTML :: tree\n // {tag :: String, text :: String, kvs :: Dict}\n // -> String\n const treeHTML = tree =>\n foldTree(\n (x, xs) => `<${x.tag + attribString(x.kvs)}>` + (\n 'text' in x ? (\n x.text\n ) : '\\n'\n ) + concat(xs) + `\\n`)(\n tree\n );\n\n // attribString :: Dict -> String\n const attribString = dct =>\n dct ? (\n ' ' + Object.keys(dct)\n .reduce(\n (a, k) => a + k + '=\"' + dct[k] + '\" ', ''\n ).trim()\n ) : '';\n\n // TEST ---------------------------------------------\n const main = () => {\n const\n tableStyle = {\n style: \"width:25%; border:2px solid silver;\"\n },\n trStyle = {\n style: \"border:1px solid silver;text-align:right;\"\n },\n strCaption = 'Table generated by JS';\n\n const\n n = 3,\n colNames = take(n)(enumFrom('A')),\n dataRows = map(\n x => Tuple(x)(map(randomRInt(100)(9999))(\n colNames\n )))(take(n)(enumFrom(1)));\n\n const\n // TABLE AS TREE STRUCTURE -----------------\n tableTree = Node({\n tag: 'table',\n kvs: tableStyle\n },\n append([\n Node({\n tag: 'caption',\n text: 'Table source generated by JS'\n }),\n // HEADER ROW -----------------------\n Node({\n tag: 'tr',\n },\n map(k => Node({\n tag: 'th',\n kvs: {\n style: \"text-align:right;\"\n },\n text: k\n }))(cons('')(colNames))\n )\n // DATA ROWS ------------------------\n ])(map(tpl => Node({\n tag: 'tr',\n kvs: trStyle\n }, cons(\n Node({\n tag: 'th',\n text: fst(tpl)\n }))(\n map(v => Node({\n tag: 'td',\n text: v.toString()\n }))(snd(tpl))\n )))(dataRows))\n );\n\n // Return a value and/or apply console.log to it.\n // (JS embeddings vary in their IO channels)\n const strHTML = treeHTML(tableTree);\n return (\n console.log(strHTML)\n //strHTML\n );\n };\n\n\n // GENERIC FUNCTIONS --------------------------------\n\n // Node :: a -> [Tree a] -> Tree a\n const Node = (v, xs) => ({\n type: 'Node',\n root: v,\n nest: xs || []\n });\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = a => b => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // append (++) :: [a] -> [a] -> [a]\n // append (++) :: String -> String -> String\n const append = xs => ys => xs.concat(ys);\n\n // chr :: Int -> Char\n const chr = String.fromCodePoint;\n\n // concat :: [[a]] -> [a]\n // concat :: [String] -> String\n const concat = xs =>\n 0 < xs.length ? (() => {\n const unit = 'string' !== typeof xs[0] ? (\n []\n ) : '';\n return unit.concat.apply(unit, xs);\n })() : [];\n\n // cons :: a -> [a] -> [a]\n const cons = x => xs => [x].concat(xs);\n\n // enumFrom :: a -> [a]\n function* enumFrom(x) {\n let v = x;\n while (true) {\n yield v;\n v = succ(v);\n }\n }\n\n // enumFromToChar :: Char -> Char -> [Char]\n const enumFromToChar = m => n => {\n const [intM, intN] = [m, n].map(\n x => x.charCodeAt(0)\n );\n return Array.from({\n length: Math.floor(intN - intM) + 1\n }, (_, i) => String.fromCodePoint(intM + i));\n };\n\n // foldTree :: (a -> [b] -> b) -> Tree a -> b\n const foldTree = f => tree => {\n const go = node =>\n f(node.root, node.nest.map(go));\n return go(tree);\n };\n\n // fst :: (a, b) -> a\n const fst = tpl => tpl[0];\n\n // isChar :: a -> Bool\n const isChar = x =>\n ('string' === typeof x) && (1 === x.length);\n\n // map :: (a -> b) -> [a] -> [b]\n const map = f => xs =>\n (Array.isArray(xs) ? (\n xs\n ) : xs.split('')).map(f);\n\n // ord :: Char -> Int\n const ord = c => c.codePointAt(0);\n\n // randomRInt :: Int -> Int -> () -> Int\n const randomRInt = low => high => () =>\n low + Math.floor(\n (Math.random() * ((high - low) + 1))\n );\n\n // snd :: (a, b) -> b\n const snd = tpl => tpl[1];\n\n // succ :: Enum a => a -> a\n const succ = x =>\n isChar(x) ? (\n chr(1 + ord(x))\n ) : isNaN(x) ? (\n undefined\n ) : 1 + x;\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n => xs =>\n 'GeneratorFunction' !== xs.constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // MAIN ---\n return main();\n})();"} +{"title": "Create an HTML table", "language": "Python", "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": "\nimport random\n\ndef rand9999():\n return random.randint(1000, 9999)\n\ndef tag(attr='', **kwargs):\n for tag, txt in kwargs.items():\n return '<{tag}{attr}>{txt}'.format(**locals())\n\nif __name__ == '__main__':\n header = tag(tr=''.join(tag(th=txt) for txt in ',X,Y,Z'.split(','))) + '\\n'\n rows = '\\n'.join(tag(tr=tag(' style=\"font-weight: bold;\"', td=i)\n + ''.join(tag(td=rand9999())\n for j in range(3)))\n for i in range(1, 6))\n table = tag(table='\\n' + header + rows + '\\n')\n print(table)"} +{"title": "Cullen and Woodall numbers", "language": "Python", "task": "A Cullen number is a number of the form '''n \u00d7 2n + 1''' where '''n''' is a natural number.\n\nA Woodall number is very similar. It is a number of the form '''n \u00d7 2n - 1''' where '''n''' is a natural number.\n\nSo for each '''n''' the associated Cullen number and Woodall number differ by 2.\n\n''Woodall numbers are sometimes referred to as Riesel numbers or Cullen numbers of the second kind.''\n\n\n'''Cullen primes''' are Cullen numbers that are prime. Similarly, '''Woodall primes''' are Woodall numbers that are prime.\n\nIt is common to list the Cullen and Woodall primes by the value of '''n''' rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, '''n''' == 4713, has 1423 digits when evaluated.\n\n\n;Task\n\n* Write procedures to find Cullen numbers and Woodall numbers. \n\n* Use those procedures to find and show here, on this page the first 20 of each.\n\n\n;Stretch\n\n* Find and show the first '''5''' '''Cullen primes''' in terms of '''n'''.\n\n* Find and show the first '''12''' '''Woodall primes''' in terms of '''n'''.\n\n\n;See also\n\n* OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1\n\n* OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1\n\n* OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime\n\n* OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime\n\n\n", "solution": "\nprint(\"working...\")\nprint(\"First 20 Cullen numbers:\")\n\nfor n in range(1,21):\n num = n*pow(2,n)+1\n print(str(num),end= \" \")\n\nprint()\nprint(\"First 20 Woodall numbers:\")\n\nfor n in range(1,21):\n num = n*pow(2,n)-1\n print(str(num),end=\" \")\n\nprint()\nprint(\"done...\")\n"} +{"title": "Currency", "language": "C", "task": ";Task:\nShow 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 \u00a0 '''2.86''' \u00a0 and \u00a0 '''.0765''' \u00a0 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 \u00a0 \u00a0 \u00a0 (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. \u00a0 The number is contrived to exclude na\u00efve 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": "\n\n#include\n#include\n\nint main()\n{\n\tmpf_t burgerUnitPrice, milkshakePrice, burgerTotalPrice, totalPrice, tax, burgerNum, milkshakeNum;\n\t\n\tmpf_inits(burgerUnitPrice, milkshakePrice, burgerTotalPrice, totalPrice, tax,burgerNum, milkshakeNum,NULL);\n\t\n\tmpf_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\t\n\tmpf_mul(burgerTotalPrice,burgerNum,burgerUnitPrice);\n\tmpf_add(totalPrice,burgerTotalPrice,milkshakePrice);\n\t\n\tmpf_set_str(tax,\"0.0765\",10);\n\tmpf_mul(tax,totalPrice,tax);\n\t\n\tgmp_printf(\"\\nTotal price before tax : $ %.*Ff\", 2, totalPrice);\n\tgmp_printf(\"\\nTotal tax : $ %.*Ff\", 2, tax);\n\t\n\tmpf_add(totalPrice,totalPrice,tax);\n\t\n\tgmp_printf(\"\\nTotal price after tax : $ %.*Ff\", 2, totalPrice);\n\t\n\treturn 0;\n}\n"} +{"title": "Currency", "language": "JavaScript", "task": ";Task:\nShow 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 \u00a0 '''2.86''' \u00a0 and \u00a0 '''.0765''' \u00a0 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 \u00a0 \u00a0 \u00a0 (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. \u00a0 The number is contrived to exclude na\u00efve 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": "const money = require('money-math') \n\nlet hamburgers = 4000000000000000 \nlet hamburgerPrice = 5.50 \n\nlet shakes = 2 \nlet shakePrice = 2.86 \n\nlet tax = 7.65 \n\nlet hamburgerTotal = money.mul(hamburgers.toFixed(0), money.floatToAmount(hamburgerPrice)) \nlet shakeTotal = money.mul(shakes.toFixed(0), money.floatToAmount(shakePrice)) \n\nlet subTotal = money.add(hamburgerTotal, shakeTotal) \n\nlet taxTotal = money.percent(subTotal, tax) \n\nlet total = money.add(subTotal, taxTotal) \n\nconsole.log('Hamburger Total:', hamburgerTotal) \nconsole.log('Shake Total:', shakeTotal) \nconsole.log('Sub Total:', subTotal) \nconsole.log('Tax:', taxTotal) \nconsole.log('Total:', total) \n"} +{"title": "Currency", "language": "Python", "task": ";Task:\nShow 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 \u00a0 '''2.86''' \u00a0 and \u00a0 '''.0765''' \u00a0 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 \u00a0 \u00a0 \u00a0 (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. \u00a0 The number is contrived to exclude na\u00efve 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": "from decimal import Decimal as D\nfrom collections import namedtuple\n\nItem = namedtuple('Item', 'price, quant')\n\nitems = dict( hamburger=Item(D('5.50'), D('4000000000000000')),\n milkshake=Item(D('2.86'), D('2')) )\ntax_rate = D('0.0765')\n\nfmt = \"%-10s %8s %18s %22s\"\nprint(fmt % tuple('Item Price Quantity Extension'.upper().split()))\n\ntotal_before_tax = 0\nfor item, (price, quant) in sorted(items.items()):\n ext = price * quant\n print(fmt % (item, price, quant, ext))\n total_before_tax += ext\nprint(fmt % ('', '', '', '--------------------'))\nprint(fmt % ('', '', 'subtotal', total_before_tax))\n\ntax = (tax_rate * total_before_tax).quantize(D('0.00'))\nprint(fmt % ('', '', 'Tax', tax))\n\ntotal = total_before_tax + tax\nprint(fmt % ('', '', '', '--------------------'))\nprint(fmt % ('', '', 'Total', total))"} +{"title": "Currying", "language": "C", "task": ";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[[Category:Functions and subroutines]]\n\n", "solution": "\n#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": "Currying", "language": "JavaScript", "task": ";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[[Category:Functions and subroutines]]\n\n", "solution": "(function () {\n\n // curry :: ((a, b) -> c) -> a -> b -> c\n function curry(f) {\n return function (a) {\n return function (b) {\n return f(a, b);\n };\n };\n }\n\n\n // TESTS\n\n // product :: Num -> Num -> Num\n function product(a, b) {\n return a * b;\n }\n\n // return typeof curry(product);\n // --> function\n\n // return typeof curry(product)(7)\n // --> function\n\n //return typeof curry(product)(7)(9)\n // --> number\n\n return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n .map(curry(product)(7))\n\n // [7, 14, 21, 28, 35, 42, 49, 56, 63, 70]\n\n})();\n"} +{"title": "Currying", "language": "Python", "task": ";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[[Category:Functions and subroutines]]\n\n", "solution": "# AUTOMATIC CURRYING AND UNCURRYING OF EXISTING FUNCTIONS\n\n\n# curry :: ((a, b) -> c) -> a -> b -> c\ndef curry(f):\n return lambda a: lambda b: f(a, b)\n\n\n# uncurry :: (a -> b -> c) -> ((a, b) -> c)\ndef uncurry(f):\n return lambda x, y: f(x)(y)\n\n\n# EXAMPLES --------------------------------------\n\n# A plain uncurried function with 2 arguments,\n\n# justifyLeft :: Int -> String -> String\ndef justifyLeft(n, s):\n return (s + (n * ' '))[:n]\n\n\n# and a similar, but manually curried, function.\n\n# justifyRight :: Int -> String -> String\ndef justifyRight(n):\n return lambda s: (\n ((n * ' ') + s)[-n:]\n )\n\n\n# CURRYING and UNCURRYING at run-time:\n\ndef main():\n for s in [\n 'Manually curried using a lambda:',\n '\\n'.join(map(\n justifyRight(5),\n ['1', '9', '10', '99', '100', '1000']\n )),\n\n '\\nAutomatically uncurried:',\n uncurry(justifyRight)(5, '10000'),\n\n '\\nAutomatically curried',\n '\\n'.join(map(\n curry(justifyLeft)(10),\n ['1', '9', '10', '99', '100', '1000']\n ))\n ]:\n print (s)\n\n\nmain()"} +{"title": "Curzon numbers", "language": "C", "task": "A '''Curzon number''' is defined to be a positive integer '''n''' for which '''2n + 1''' is evenly divisible by '''2 \u00d7 n + 1'''.\n\n'''Generalized Curzon numbers''' are those where the positive integer '''n''', using a base integer '''k''', satisfy the condition that '''kn + 1''' is evenly divisible by '''k \u00d7 n + 1'''.\n\n''Base here does not imply the radix of the counting system; rather the integer the equation is based on. All calculations should be done in base 10.'' \n\nGeneralized Curzon numbers only exist for even base integers. \n\n\n;Task \n\n* Find and show the first '''50 Generalized Curzon numbers''' for even base integers from '''2''' through '''10'''.\n\n\n;Stretch\n\n* Find and show the '''one thousandth'''.\n\n\n;See also\n\n;* [https://www.numbersaplenty.com/set/Curzon_number Numbers Aplenty - Curzon numbers]\n;* OEIS:A224486 - Numbers k such that 2*k+1 divides 2^k+1 (Curzon numbers)\n\n''and even though it is not specifically mentioned that they are Curzon numbers:''\n\n;* OEIS:A230076 - (A007521(n)-1)/4 (Generalized Curzon numbers with a base 4)\n\n", "solution": "#include \n#include \n#include \n#include \n\nuint64_t modPow(uint64_t base, uint64_t exp, uint64_t mod) {\n if (mod == 1) return 0;\n uint64_t result = 1;\n base %= mod;\n for (; exp > 0; exp >>= 1) {\n if ((exp & 1) == 1) result = (result * base) % mod;\n base = (base * base) % mod;\n }\n return result;\n}\n\nbool isCurzon(uint64_t n, uint64_t k) {\n const uint64_t r = k * n;\n return modPow(k, n, r+1) == r;\n}\n\nint main() {\n uint64_t k, n, count;\n setlocale(LC_NUMERIC, \"\");\n for (k = 2; k <= 10; k += 2) {\n printf(\"Curzon numbers with base %ld:\\n\", k);\n for (n = 1, count = 0; count < 50; ++n) {\n if (isCurzon(n, k)) {\n printf(\"%4ld \", n);\n if (++count % 10 == 0) printf(\"\\n\");\n }\n }\n for (;;) {\n if (isCurzon(n, k)) ++count;\n if (count == 1000) break;\n ++n;\n }\n printf(\"1,000th Curzon number with base %ld: %'ld\\n\\n\", k, n);\n }\n return 0;\n}"} +{"title": "Curzon numbers", "language": "Python", "task": "A '''Curzon number''' is defined to be a positive integer '''n''' for which '''2n + 1''' is evenly divisible by '''2 \u00d7 n + 1'''.\n\n'''Generalized Curzon numbers''' are those where the positive integer '''n''', using a base integer '''k''', satisfy the condition that '''kn + 1''' is evenly divisible by '''k \u00d7 n + 1'''.\n\n''Base here does not imply the radix of the counting system; rather the integer the equation is based on. All calculations should be done in base 10.'' \n\nGeneralized Curzon numbers only exist for even base integers. \n\n\n;Task \n\n* Find and show the first '''50 Generalized Curzon numbers''' for even base integers from '''2''' through '''10'''.\n\n\n;Stretch\n\n* Find and show the '''one thousandth'''.\n\n\n;See also\n\n;* [https://www.numbersaplenty.com/set/Curzon_number Numbers Aplenty - Curzon numbers]\n;* OEIS:A224486 - Numbers k such that 2*k+1 divides 2^k+1 (Curzon numbers)\n\n''and even though it is not specifically mentioned that they are Curzon numbers:''\n\n;* OEIS:A230076 - (A007521(n)-1)/4 (Generalized Curzon numbers with a base 4)\n\n", "solution": "def is_Curzon(n, k):\n r = k * n\n return pow(k, n, r + 1) == r\n\nfor k in [2, 4, 6, 8, 10]:\n n, curzons = 1, []\n while len(curzons) < 1000:\n if is_Curzon(n, k):\n curzons.append(n)\n n += 1\n print(f'Curzon numbers with k = {k}:')\n for i, c in enumerate(curzons[:50]):\n print(f'{c: 5,}', end='\\n' if (i + 1) % 25 == 0 else '')\n print(f' Thousandth Curzon with k = {k}: {curzons[999]}.\\n')"} +{"title": "Cut a rectangle", "language": "C", "task": "A given rectangle is made from ''m'' \u00d7 ''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 180\u00b0). All such paths for 2 \u00d7 2 and 4 \u00d7 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'' \u00d7 ''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": "Cut a rectangle", "language": "Python", "task": "A given rectangle is made from ''m'' \u00d7 ''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 180\u00b0). All such paths for 2 \u00d7 2 and 4 \u00d7 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'' \u00d7 ''n'' rectangle. Optionally, show each of the cuts.\n\nPossibly related task: [[Maze generation]] for depth-first search.\n\n", "solution": "def cut_it(h, w):\n dirs = ((1, 0), (-1, 0), (0, -1), (0, 1))\n if h % 2: h, w = w, h\n if h % 2: return 0\n if w == 1: return 1\n count = 0\n\n next = [w + 1, -w - 1, -1, 1]\n blen = (h + 1) * (w + 1) - 1\n grid = [False] * (blen + 1)\n\n def walk(y, x, count):\n if not y or y == h or not x or x == w:\n return count + 1\n\n t = y * (w + 1) + x\n grid[t] = grid[blen - t] = True\n\n if not grid[t + next[0]]:\n count = walk(y + dirs[0][0], x + dirs[0][1], count)\n if not grid[t + next[1]]:\n count = walk(y + dirs[1][0], x + dirs[1][1], count)\n if not grid[t + next[2]]:\n count = walk(y + dirs[2][0], x + dirs[2][1], count)\n if not grid[t + next[3]]:\n count = walk(y + dirs[3][0], x + dirs[3][1], count)\n\n grid[t] = grid[blen - t] = False\n return count\n\n t = h // 2 * (w + 1) + w // 2\n if w % 2:\n grid[t] = grid[t + 1] = True\n count = walk(h // 2, w // 2 - 1, count)\n res = count\n count = 0\n count = walk(h // 2 - 1, w // 2, count)\n return res + count * 2\n else:\n grid[t] = True\n count = walk(h // 2, w // 2 - 1, count)\n if h == w:\n return count * 2\n count = walk(h // 2 - 1, w // 2, count)\n return count\n\ndef main():\n for w in xrange(1, 10):\n for h in xrange(1, w + 1):\n if not((w * h) % 2):\n print \"%d x %d: %d\" % (w, h, cut_it(w, h))\n\nmain()"} +{"title": "Cyclotomic polynomial", "language": "Python", "task": "The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n \u2212 1, and is not a divisor of x^k \u2212 1 for any k < n.\n\n\n;Task:\n* Find and print the first 30 cyclotomic polynomials.\n* Find and print the order of the first 10 cyclotomic polynomials that have n or -n as a coefficient.\n\n\n;See also\n* Wikipedia article, Cyclotomic polynomial, showing ways to calculate them.\n* The sequence A013594 with the smallest order of cyclotomic polynomial containing n or -n as a coefficient.\n\n", "solution": "from itertools import count, chain\nfrom collections import deque\n\ndef primes(_cache=[2, 3]):\n yield from _cache\n for n in count(_cache[-1]+2, 2):\n if isprime(n):\n _cache.append(n)\n yield n\n\ndef isprime(n):\n for p in primes():\n if n%p == 0:\n return False\n if p*p > n:\n return True\n\ndef factors(n):\n for p in primes():\n # prime factoring is such a non-issue for small numbers that, for\n # this example, we might even just say\n # for p in count(2):\n if p*p > n:\n if n > 1:\n yield(n, 1, 1)\n break\n\n if n%p == 0:\n cnt = 0\n while True:\n n, cnt = n//p, cnt+1\n if n%p != 0: break\n yield p, cnt, n\n# ^^ not the most sophisticated prime number routines, because no need\n\n# Returns (list1, list2) representing the division between\n# two polinomials. A list p of integers means the product\n# (x^p[0] - 1) * (x^p[1] - 1) * ...\ndef cyclotomic(n):\n def poly_div(num, den):\n return (num[0] + den[1], num[1] + den[0])\n\n def elevate(poly, n): # replace poly p(x) with p(x**n)\n powerup = lambda p, n: [a*n for a in p]\n return poly if n == 1 else (powerup(poly[0], n), powerup(poly[1], n))\n\n\n if n == 0:\n return ([], [])\n if n == 1:\n return ([1], [])\n\n p, m, r = next(factors(n))\n poly = cyclotomic(r)\n return elevate(poly_div(elevate(poly, p), poly), p**(m-1))\n\ndef to_text(poly):\n def getx(c, e):\n if e == 0:\n return '1'\n elif e == 1:\n return 'x'\n return 'x' + (''.join('\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079'[i] for i in map(int, str(e))))\n\n parts = []\n for (c,e) in (poly):\n if c < 0:\n coef = ' - ' if c == -1 else f' - {-c} '\n else:\n coef = (parts and ' + ' or '') if c == 1 else f' + {c}'\n parts.append(coef + getx(c,e))\n return ''.join(parts)\n\ndef terms(poly):\n # convert above representation of division to (coef, power) pairs\n\n def merge(a, b):\n # a, b should be deques. They may change during the course.\n while a or b:\n l = a[0] if a else (0, -1) # sentinel value\n r = b[0] if b else (0, -1)\n if l[1] > r[1]:\n a.popleft()\n elif l[1] < r[1]:\n b.popleft()\n l = r\n else:\n a.popleft()\n b.popleft()\n l = (l[0] + r[0], l[1])\n yield l\n\n def mul(poly, p): # p means polynomial x^p - 1\n poly = list(poly)\n return merge(deque((c, e+p) for c,e in poly),\n deque((-c, e) for c,e in poly))\n\n def div(poly, p): # p means polynomial x^p - 1\n q = deque()\n for c,e in merge(deque(poly), q):\n if c:\n q.append((c, e - p))\n yield (c, e - p)\n if e == p: break\n\n p = [(1, 0)] # 1*x^0, i.e. 1\n\n for x in poly[0]: # numerator\n p = mul(p, x)\n for x in sorted(poly[1], reverse=True): # denominator\n p = div(p, x)\n return p\n\nfor n in chain(range(11), [2]):\n print(f'{n}: {to_text(terms(cyclotomic(n)))}')\n\nwant = 1\nfor n in count():\n c = [c for c,_ in terms(cyclotomic(n))]\n while want in c or -want in c:\n print(f'C[{want}]: {n}')\n want += 1"} +{"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": "Damm algorithm", "language": "JavaScript", "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": "const table = [\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\nconst lookup = (p, c) => table[p][parseInt(c, 10)]\nconst damm = input => [...input].reduce(lookup, 0) === 0;\n\n// ----------------------------------------------------------[ Tests ]----\nconst test = () => [\"5724\", \"5727\", \"112946\", \"112949\"].forEach(e =>\n console.log(`${e} => ${damm(e) ? 'Pass' : 'Fail'}`)\n);\ntest();\n"} +{"title": "Damm algorithm", "language": "Python", "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": "def damm(num: int) -> bool:\n row = 0\n for digit in str(num):\n row = _matrix[row][int(digit)] \n return row == 0\n\n_matrix = (\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\nif __name__ == '__main__':\n for test in [5724, 5727, 112946]:\n print(f'{test}\\t Validates as: {damm(test)}')"} +{"title": "De Bruijn sequences", "language": "Python", "task": "The sequences are named after the Dutch mathematician \u00a0 Nicolaas Govert de Bruijn.\n\n\nA note on Dutch capitalization: \u00a0 Nicolaas' last name is \u00a0 '''de Bruijn''', \u00a0 the \u00a0 '''de''' \u00a0 isn't normally capitalized\nunless it's the first word in a sentence. \u00a0 Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be\ncapitalized.\n\n\nIn combinatorial mathematics, \u00a0 a \u00a0 '''de Bruijn sequence''' \u00a0 of order \u00a0 ''n'' \u00a0 on\na \u00a0 size-''k'' \u00a0 alphabet (computer science) \u00a0 ''A'' \u00a0 is a cyclic sequence in which every\npossible \u00a0 length-''n'' \u00a0 string (computer science, formal theory) \u00a0 on \u00a0 ''A'' \u00a0 occurs\nexactly once as a contiguous substring.\n\n\nSuch a sequence is denoted by \u00a0 ''B''(''k'', ''n'') \u00a0 and has\nlength \u00a0 ''k''''n'', \u00a0 which is also the number of distinct substrings of\nlength \u00a0 ''n'' \u00a0 on \u00a0 ''A''; \u00a0 \u00a0\nde Bruijn sequences are therefore optimally short.\n\n\nThere are:\n (k!)k(n-1) \u00a0 \u00f7 \u00a0 kn\ndistinct de Bruijn sequences \u00a0 ''B''(''k'', ''n''). \n\n\n;Task:\nFor this Rosetta Code task, \u00a0 a \u00a0 '''de Bruijn''' \u00a0 sequence is to be generated that can be used to shorten a brute-force attack on\na \u00a0 PIN-like \u00a0 code lock that does not have an \"enter\"\nkey and accepts the last \u00a0 ''n'' \u00a0 digits entered.\n\n\nNote: \u00a0 automated teller machines (ATMs) \u00a0 used to work like\nthis, \u00a0 but their software has been updated to not allow a brute-force attack.\n\n\n;Example:\nA \u00a0 digital door lock \u00a0 with a 4-digit code would\nhave ''B''\u2009(10,\u00a04) solutions, \u00a0 with a length of \u00a0 '''10,000''' \u00a0 (digits).\n\nTherefore, only at most \u00a0 \u00a0 '''10,000 + 3''' \u00a0 \u00a0 (as the solutions are cyclic or ''wrap-around'') \u00a0 presses are needed to\nopen the lock.\n\nTrying all 4-digit codes separately would require \u00a0 '''4 \u00d7 10,000''' \u00a0 or \u00a0 '''40,000''' \u00a0 presses.\n\n\n;Task requirements:\n:* \u00a0 Generate a de Bruijn sequence for a 4-digit (decimal) PIN code.\n:::* \u00a0 Show the length of the generated de Bruijn sequence.\n:::* \u00a0 (There are many possible de Bruijn sequences that solve this task, \u00a0 one solution is shown on the ''discussion'' page).\n:::* \u00a0 Show the first and last \u00a0 '''130''' \u00a0 digits of the de Bruijn sequence.\n:* \u00a0 Verify that all four-digit (decimal) \u00a0 '''1,000''' \u00a0 PIN codes are contained within the de Bruijn sequence.\n:::* \u00a0 0000, 0001, 0002, 0003, \u00a0 ... \u00a0 9996, 9997, 9998, 9999 \u00a0 (note the leading zeros).\n:* \u00a0 Reverse the de Bruijn sequence.\n:* \u00a0 Again, perform the (above) verification test.\n:* \u00a0 Replace the 4,444th digit with a period (.) in the original de Bruijn sequence.\n:::* \u00a0 Perform the verification test (again). \u00a0 There should be four PIN codes missing.\n\n\n(The last requirement is to ensure that the verification tests performs correctly. \u00a0 The verification processes should list\nany and all missing PIN codes.)\n\nShow all output here, on this page.\n\n\n\n;References:\n:* \u00a0 Wikipedia entry: \u00a0 de Bruijn sequence.\n:* \u00a0 MathWorld entry: \u00a0 [http://mathworld.wolfram.com/deBruijnSequence.html de Bruijn sequence].\n:* \u00a0 An \u00a0OEIS\u00a0 entry: \u00a0 A166315 lexicographically earliest binary de Bruijn sequences, B(2,n) \u00a0 \u00a0 --- Not B(10,4), \u00a0 but possibly relevant.\n\n", "solution": "\n# from https://en.wikipedia.org/wiki/De_Bruijn_sequence\n\ndef de_bruijn(k, n):\n \"\"\"\n de Bruijn sequence for alphabet k\n and subsequences of length n.\n \"\"\"\n try:\n # let's see if k can be cast to an integer;\n # if so, make our alphabet a list\n _ = int(k)\n alphabet = list(map(str, range(k)))\n\n except (ValueError, TypeError):\n alphabet = k\n k = len(k)\n\n a = [0] * k * n\n sequence = []\n\n def db(t, p):\n if t > n:\n if n % p == 0:\n sequence.extend(a[1:p + 1])\n else:\n a[t] = a[t - p]\n db(t + 1, p)\n for j in range(a[t - p] + 1, k):\n a[t] = j\n db(t + 1, t)\n db(1, 1)\n return \"\".join(alphabet[i] for i in sequence)\n \ndef validate(db):\n \"\"\"\n \n Check that all 10,000 combinations of 0-9 are present in \n De Bruijn string db.\n \n Validating the reversed deBruijn sequence:\n No errors found\n \n Validating the overlaid deBruijn sequence:\n 4 errors found:\n PIN number 1459 missing\n PIN number 4591 missing\n PIN number 5814 missing\n PIN number 8145 missing\n \n \"\"\"\n \n dbwithwrap = db+db[0:3]\n \n digits = '0123456789'\n \n errorstrings = []\n \n for d1 in digits:\n for d2 in digits:\n for d3 in digits:\n for d4 in digits:\n teststring = d1+d2+d3+d4\n if teststring not in dbwithwrap:\n errorstrings.append(teststring)\n \n if len(errorstrings) > 0:\n print(\" \"+str(len(errorstrings))+\" errors found:\")\n for e in errorstrings:\n print(\" PIN number \"+e+\" missing\")\n else:\n print(\" No errors found\")\n\ndb = de_bruijn(10, 4)\n\nprint(\" \")\nprint(\"The length of the de Bruijn sequence is \", str(len(db)))\nprint(\" \")\nprint(\"The first 130 digits of the de Bruijn sequence are: \"+db[0:130])\nprint(\" \")\nprint(\"The last 130 digits of the de Bruijn sequence are: \"+db[-130:])\nprint(\" \")\nprint(\"Validating the deBruijn sequence:\")\nvalidate(db)\ndbreversed = db[::-1]\nprint(\" \")\nprint(\"Validating the reversed deBruijn sequence:\")\nvalidate(dbreversed)\ndboverlaid = db[0:4443]+'.'+db[4444:]\nprint(\" \")\nprint(\"Validating the overlaid deBruijn sequence:\")\nvalidate(dboverlaid)\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;* [https://www.numbersaplenty.com/set/deceptive_number 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": "Deceptive numbers", "language": "Python", "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;* [https://www.numbersaplenty.com/set/deceptive_number Numbers Aplenty - Deceptive numbers]\n;* OEIS:A000864 - Deceptive nonprimes: composite numbers k that divide the repunit R_{k-1}\n\n", "solution": "from itertools import count, islice\nfrom math import isqrt\n\ndef is_deceptive(n):\n if n & 1 and n % 3 and n % 5 and pow(10, n - 1, n) == 1:\n for d in range(7, isqrt(n) + 1, 6):\n if not (n % d and n % (d + 4)): return True\n return False\n\nprint(*islice(filter(is_deceptive, count()), 100))"} +{"title": "Deepcopy", "language": "C", "task": ";Task:\nDemonstrate 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": "\n#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": "Deepcopy", "language": "JavaScript", "task": ";Task:\nDemonstrate 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": "\nvar deepcopy = function(o){\n return JSON.parse(JSON.stringify(src));\n};\n\nvar src = {foo:0,bar:[0,1]};\nprint(JSON.stringify(src));\nvar dst = deepcopy(src);\nprint(JSON.stringify(src));\n"} +{"title": "Deming's funnel", "language": "Python", "task": "W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of \"rules\" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target.\n\n* '''Rule 1''': The funnel remains directly above the target.\n* '''Rule 2''': Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position.\n* '''Rule 3''': As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target.\n* '''Rule 4''': The funnel is moved directly over the last place a marble landed.\n\nApply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. '''Output''': calculate the mean and standard-deviations of the resulting x and y values for each rule. \n\nNote that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples.\n\n'''Stretch goal 1''': Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed.\n\n'''Stretch goal 2''': Show scatter plots of all four results.\n\n\n;Further information:\n* Further [http://blog.newsystemsthinking.com/w-edwards-deming-and-the-funnel-experiment/ explanation and interpretation]\n* [https://www.youtube.com/watch?v=2VogtYRc9dA Video demonstration] of the funnel experiment at the Mayo Clinic.\n\n", "solution": "import math \n\ndxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251,\n -0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915,\n 2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, \n 0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, -0.423,\n -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201, \n 0.034, 0.097, -0.17, 0.054, -0.553, -0.024, -0.181, -0.7, -0.361, -0.789,\n 0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853,\n 0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.31, 0.171, 0.0, 0.106,\n 0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749,\n -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, \n 0.087]\n\ndys = [0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.49, -0.682,\n -0.065, 0.242, -0.288, 0.658, 0.459, 0.0, 0.426, 0.205, -0.765, -2.188, \n -0.742, -0.01, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199,\n 0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, \n 0.009, 0.508, -0.79, 0.723, 0.881, -0.508, 0.393, -0.226, 0.71, 0.038, \n -0.217, 0.831, 0.48, 0.407, 0.447, -0.295, 1.126, 0.38, 0.549, -0.445, \n -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.23, -0.044, \n 0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, \n -0.729, 0.65, -1.103, 0.154, -1.72, 0.051, -0.385, 0.477, 1.537, -0.901, \n 0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032]\n\ndef funnel(dxs, rule):\n x, rxs = 0, []\n for dx in dxs:\n rxs.append(x + dx)\n x = rule(x, dx)\n return rxs\n\ndef mean(xs): return sum(xs) / len(xs)\n\ndef stddev(xs):\n m = mean(xs)\n return math.sqrt(sum((x-m)**2 for x in xs) / len(xs))\n\ndef experiment(label, rule):\n rxs, rys = funnel(dxs, rule), funnel(dys, rule)\n print label\n print 'Mean x, y : %.4f, %.4f' % (mean(rxs), mean(rys))\n print 'Std dev x, y : %.4f, %.4f' % (stddev(rxs), stddev(rys))\n print\n\n\nexperiment('Rule 1:', lambda z, dz: 0)\nexperiment('Rule 2:', lambda z, dz: -dz)\nexperiment('Rule 3:', lambda z, dz: -(z+dz))\nexperiment('Rule 4:', lambda z, dz: z+dz)"} +{"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::* \u00a0 police department\n::* \u00a0 sanitation department\n::* \u00a0 fire department \n\n\nEach department can have a number between \u00a0 '''1''' \u00a0 and \u00a0 '''7''' \u00a0 (inclusive).\n\nThe three department numbers are to be unique (different from each other) and must add up to \u00a0 '''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 \u00a0 (for the 1st and 14th solutions):\n \n --police-- --sanitation-- --fire-- \n 2 3 7 \n 6 5 1\n\n", "solution": "\n#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": "Department numbers", "language": "Python", "task": "There is a highly organized city that has decided to assign a number to each of their departments:\n::* \u00a0 police department\n::* \u00a0 sanitation department\n::* \u00a0 fire department \n\n\nEach department can have a number between \u00a0 '''1''' \u00a0 and \u00a0 '''7''' \u00a0 (inclusive).\n\nThe three department numbers are to be unique (different from each other) and must add up to \u00a0 '''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 \u00a0 (for the 1st and 14th solutions):\n \n --police-- --sanitation-- --fire-- \n 2 3 7 \n 6 5 1\n\n", "solution": "from itertools import permutations\n \ndef solve():\n c, p, f, s = \"\\\\,Police,Fire,Sanitation\".split(',')\n print(f\"{c:>3} {p:^6} {f:^4} {s:^10}\")\n c = 1\n for p, f, s in permutations(range(1, 8), r=3):\n if p + s + f == 12 and p % 2 == 0:\n print(f\"{c:>3}: {p:^6} {f:^4} {s:^10}\")\n c += 1\n \nif __name__ == '__main__':\n solve()"} +{"title": "Descending primes", "language": "C", "task": "Generate and show all primes with strictly descending decimal digits.\n\n;See also\n;* OEIS:A052014 - Primes with distinct digits in descending order\n\n;Related:\n*[[Ascending primes]]\n\n\n", "solution": "#include \n\nint ispr(unsigned int n) {\n if ((n & 1) == 0 || n < 2) return n == 2;\n for (unsigned int j = 3; j * j <= n; j += 2)\n if (n % j == 0) return 0; return 1; }\n\nint main() {\n unsigned int c = 0, nc, pc = 9, i, a, b, l,\n ps[128], nxt[128];\n for (a = 0, b = 1; a < pc; a = b++) ps[a] = b;\n while (1) {\n nc = 0;\n for (i = 0; i < pc; i++) {\n if (ispr(a = ps[i]))\n printf(\"%8d%s\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n for (b = a * 10, l = a % 10 + b++; b < l; b++)\n nxt[nc++] = b;\n }\n if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];\n else break;\n }\n printf(\"\\n%d descending primes found\", c);\n}"} +{"title": "Descending primes", "language": "Python", "task": "Generate and show all primes with strictly descending decimal digits.\n\n;See also\n;* OEIS:A052014 - Primes with distinct digits in descending order\n\n;Related:\n*[[Ascending primes]]\n\n\n", "solution": "from sympy import isprime\n\ndef descending(xs=range(10)):\n for x in xs:\n yield x\n yield from descending(x*10 + d for d in range(x%10))\n\nfor i, p in enumerate(sorted(filter(isprime, descending()))):\n print(f'{p:9d}', end=' ' if (1 + i)%8 else '\\n')\n\nprint()"} +{"title": "Detect division by zero", "language": "C", "task": "[[Category:Simple]]\n;Task:\nWrite a function to detect a \u00a0 ''divide by zero error'' \u00a0 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": "Detect division by zero", "language": "JavaScript", "task": "[[Category:Simple]]\n;Task:\nWrite a function to detect a \u00a0 ''divide by zero error'' \u00a0 without checking if the denominator is zero.\n\n", "solution": "function divByZero(dividend,divisor)\n{\n\tvar quotient=dividend/divisor;\n if(isNaN(quotient)) return 0; //Can be changed to whatever is desired by the programmer to be 0, false, or Infinity\n return quotient; //Will return Infinity or -Infinity in cases of, for example, 5/0 or -7/0 respectively\n}\nalert(divByZero(0,0));"} +{"title": "Detect division by zero", "language": "Python", "task": "[[Category:Simple]]\n;Task:\nWrite a function to detect a \u00a0 ''divide by zero error'' \u00a0 without checking if the denominator is zero.\n\n", "solution": "def div_check(x, y):\n try:\n x / y\n except ZeroDivisionError:\n return True\n else:\n return False"} +{"title": "Determinant and permanent", "language": "C", "task": "For a given matrix, return the 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": "Determinant and permanent", "language": "JavaScript", "task": "For a given matrix, return the 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": "const determinant = arr =>\n arr.length === 1 ? (\n arr[0][0]\n ) : arr[0].reduce(\n (sum, v, i) => sum + v * (-1) ** i * determinant(\n arr.slice(1)\n .map(x => x.filter((_, j) => i !== j))\n ), 0\n );\n\nconst permanent = arr =>\n arr.length === 1 ? (\n arr[0][0]\n ) : arr[0].reduce(\n (sum, v, i) => sum + v * permanent(\n arr.slice(1)\n .map(x => x.filter((_, j) => i !== j))\n ), 0\n );\n\nconst M = [\n [0, 1, 2, 3, 4],\n [5, 6, 7, 8, 9],\n [10, 11, 12, 13, 14],\n [15, 16, 17, 18, 19],\n [20, 21, 22, 23, 24]\n];\nconsole.log(determinant(M));\nconsole.log(permanent(M));"} +{"title": "Determinant and permanent", "language": "Python", "task": "For a given matrix, return the 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": "from itertools import permutations\nfrom operator import mul\nfrom math import fsum\nfrom spermutations import spermutations\n\ndef prod(lst):\n return reduce(mul, lst, 1)\n\ndef perm(a):\n n = len(a)\n r = range(n)\n s = permutations(r)\n return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)\n\ndef det(a):\n n = len(a)\n r = range(n)\n s = spermutations(n)\n return fsum(sign * prod(a[i][sigma[i]] for i in r)\n for sigma, sign in s)\n\nif __name__ == '__main__':\n from pprint import pprint as pp\n\n for a in ( \n [\n [1, 2], \n [3, 4]], \n\n [\n [1, 2, 3, 4],\n [4, 5, 6, 7],\n [7, 8, 9, 10],\n [10, 11, 12, 13]], \n\n [\n [ 0, 1, 2, 3, 4],\n [ 5, 6, 7, 8, 9],\n [10, 11, 12, 13, 14],\n [15, 16, 17, 18, 19],\n [20, 21, 22, 23, 24]],\n ):\n print('')\n pp(a)\n print('Perm: %s Det: %s' % (perm(a), det(a)))"} +{"title": "Determine if a string has all the same characters", "language": "C", "task": ";Task:\n\nGiven a character string \u00a0 (which may be empty, or have a length of zero characters):\n::* \u00a0 create a function/procedure/routine to:\n::::* \u00a0 determine if all the characters in the string are the same\n::::* \u00a0 indicate if or which character is different from the previous character\n::* \u00a0 display each string and its length \u00a0 (as the strings are being examined)\n::* \u00a0 a zero\u2500length (empty) string shall be considered as all the same character(s)\n::* \u00a0 process the strings from left\u2500to\u2500right\n::* \u00a0 if \u00a0 \u00a0 \u00a0 all the same character, \u00a0 display a message saying such\n::* \u00a0 if not all the same character, \u00a0 then:\n::::* \u00a0 display a message saying such\n::::* \u00a0 display what character is different\n::::* \u00a0 only the 1st different character need be displayed\n::::* \u00a0 display where the different character is in the string\n::::* \u00a0 the above messages can be part of a single message\n::::* \u00a0 display the hexadecimal value of the different character\n\n\nUse (at least) these seven test values \u00a0 (strings):\n:::* \u00a0 a string of length \u00a0 0 \u00a0 (an empty string)\n:::* \u00a0 a string of length \u00a0 3 \u00a0 which contains three blanks\n:::* \u00a0 a string of length \u00a0 1 \u00a0 which contains: \u00a0 '''2'''\n:::* \u00a0 a string of length \u00a0 3 \u00a0 which contains: \u00a0 '''333'''\n:::* \u00a0 a string of length \u00a0 3 \u00a0 which contains: \u00a0 '''.55'''\n:::* \u00a0 a string of length \u00a0 6 \u00a0 which contains: \u00a0 '''tttTTT'''\n:::* \u00a0 a string of length \u00a0 9 \u00a0 with a blank in the middle: \u00a0 '''4444 \u00a0 444k'''\n\n\n\nShow all output here on this page.\n\n\n", "solution": "\n#include\n#include\n\nint main(int argc,char** argv)\n{\n int i,len;\n char reference;\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(\"Input string : \\\"%s\\\"\\nLength : %d\\nAll characters are identical.\\n\",argc==1?\"\":argv[1],argc==1?0:(int)strlen(argv[1]));\n return 0;\n }\n\n reference = argv[1][0];\n len = strlen(argv[1]);\n\n for(i=1;i\nOutput :\n\nabhishek_ghosh@Azure:~/doodles$ ./a.out\nInput string : \"\"\nLength : 0\nAll characters are identical.\nabhishek_ghosh@Azure:~/doodles$ ./a.out \" \"\nInput string : \" \"\nLength : 3\nAll characters are identical.\nabhishek_ghosh@Azure:~/doodles$ ./a.out 2\nInput string : \"2\"\nLength : 1\nAll characters are identical.\nabhishek_ghosh@Azure:~/doodles$ ./a.out 333\nInput string : \"333\"\nLength : 3\nAll characters are identical.\nabhishek_ghosh@Azure:~/doodles$ ./a.out .55\nInput string : \".55\"\nLength : 3\nFirst different character : \"5\"(0x35) at position : 2\nabhishek_ghosh@Azure:~/doodles$ ./a.out tttTTT\nInput string : \"tttTTT\"\nLength : 6\nFirst different character : \"T\"(0x54) at position : 4\nabhishek_ghosh@Azure:~/doodles$ ./a.out \"4444 444k\"\nInput string : \"4444 444k\"\nLength : 9\nFirst different character : \" \"(0x20) at position : 5\n\n===Solution with pointers===\n/**\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}\n"} +{"title": "Determine if a string has all the same characters", "language": "JavaScript", "task": ";Task:\n\nGiven a character string \u00a0 (which may be empty, or have a length of zero characters):\n::* \u00a0 create a function/procedure/routine to:\n::::* \u00a0 determine if all the characters in the string are the same\n::::* \u00a0 indicate if or which character is different from the previous character\n::* \u00a0 display each string and its length \u00a0 (as the strings are being examined)\n::* \u00a0 a zero\u2500length (empty) string shall be considered as all the same character(s)\n::* \u00a0 process the strings from left\u2500to\u2500right\n::* \u00a0 if \u00a0 \u00a0 \u00a0 all the same character, \u00a0 display a message saying such\n::* \u00a0 if not all the same character, \u00a0 then:\n::::* \u00a0 display a message saying such\n::::* \u00a0 display what character is different\n::::* \u00a0 only the 1st different character need be displayed\n::::* \u00a0 display where the different character is in the string\n::::* \u00a0 the above messages can be part of a single message\n::::* \u00a0 display the hexadecimal value of the different character\n\n\nUse (at least) these seven test values \u00a0 (strings):\n:::* \u00a0 a string of length \u00a0 0 \u00a0 (an empty string)\n:::* \u00a0 a string of length \u00a0 3 \u00a0 which contains three blanks\n:::* \u00a0 a string of length \u00a0 1 \u00a0 which contains: \u00a0 '''2'''\n:::* \u00a0 a string of length \u00a0 3 \u00a0 which contains: \u00a0 '''333'''\n:::* \u00a0 a string of length \u00a0 3 \u00a0 which contains: \u00a0 '''.55'''\n:::* \u00a0 a string of length \u00a0 6 \u00a0 which contains: \u00a0 '''tttTTT'''\n:::* \u00a0 a string of length \u00a0 9 \u00a0 with a blank in the middle: \u00a0 '''4444 \u00a0 444k'''\n\n\n\nShow all output here on this page.\n\n\n", "solution": "const check = s => {\n const arr = [...s];\n const at = arr.findIndex(\n (v, i) => i === 0 ? false : v !== arr[i - 1]\n )\n const l = arr.length;\n const ok = at === -1;\n const p = ok ? \"\" : at + 1;\n const v = ok ? \"\" : arr[at];\n const vs = v === \"\" ? v : `\"${v}\"`\n const h = ok ? \"\" : `0x${v.codePointAt(0).toString(16)}`;\n console.log(`\"${s}\" => Length:${l}\\tSame:${ok}\\tPos:${p}\\tChar:${vs}\\tHex:${h}`)\n}\n\n['', ' ', '2', '333', '.55', 'tttTTT', '4444 444k', '\ud83d\udc36\ud83d\udc36\ud83d\udc3a\ud83d\udc36', '\ud83c\udf84\ud83c\udf84\ud83c\udf84\ud83c\udf84'].forEach(check)"} +{"title": "Determine if a string has all the same characters", "language": "Python", "task": ";Task:\n\nGiven a character string \u00a0 (which may be empty, or have a length of zero characters):\n::* \u00a0 create a function/procedure/routine to:\n::::* \u00a0 determine if all the characters in the string are the same\n::::* \u00a0 indicate if or which character is different from the previous character\n::* \u00a0 display each string and its length \u00a0 (as the strings are being examined)\n::* \u00a0 a zero\u2500length (empty) string shall be considered as all the same character(s)\n::* \u00a0 process the strings from left\u2500to\u2500right\n::* \u00a0 if \u00a0 \u00a0 \u00a0 all the same character, \u00a0 display a message saying such\n::* \u00a0 if not all the same character, \u00a0 then:\n::::* \u00a0 display a message saying such\n::::* \u00a0 display what character is different\n::::* \u00a0 only the 1st different character need be displayed\n::::* \u00a0 display where the different character is in the string\n::::* \u00a0 the above messages can be part of a single message\n::::* \u00a0 display the hexadecimal value of the different character\n\n\nUse (at least) these seven test values \u00a0 (strings):\n:::* \u00a0 a string of length \u00a0 0 \u00a0 (an empty string)\n:::* \u00a0 a string of length \u00a0 3 \u00a0 which contains three blanks\n:::* \u00a0 a string of length \u00a0 1 \u00a0 which contains: \u00a0 '''2'''\n:::* \u00a0 a string of length \u00a0 3 \u00a0 which contains: \u00a0 '''333'''\n:::* \u00a0 a string of length \u00a0 3 \u00a0 which contains: \u00a0 '''.55'''\n:::* \u00a0 a string of length \u00a0 6 \u00a0 which contains: \u00a0 '''tttTTT'''\n:::* \u00a0 a string of length \u00a0 9 \u00a0 with a blank in the middle: \u00a0 '''4444 \u00a0 444k'''\n\n\n\nShow all output here on this page.\n\n\n", "solution": "\n===Functional===\n\nWhat we are testing here is the cardinality of the set of characters from which a string is drawn, so the first thought might well be to use '''set'''. \n\nOn the other hand, '''itertools.groupby''' has the advantage of yielding richer information (the list of groups is ordered), for less work.\n\n"} +{"title": "Determine if a string has all the same characters", "language": "Python 3.7", "task": ";Task:\n\nGiven a character string \u00a0 (which may be empty, or have a length of zero characters):\n::* \u00a0 create a function/procedure/routine to:\n::::* \u00a0 determine if all the characters in the string are the same\n::::* \u00a0 indicate if or which character is different from the previous character\n::* \u00a0 display each string and its length \u00a0 (as the strings are being examined)\n::* \u00a0 a zero\u2500length (empty) string shall be considered as all the same character(s)\n::* \u00a0 process the strings from left\u2500to\u2500right\n::* \u00a0 if \u00a0 \u00a0 \u00a0 all the same character, \u00a0 display a message saying such\n::* \u00a0 if not all the same character, \u00a0 then:\n::::* \u00a0 display a message saying such\n::::* \u00a0 display what character is different\n::::* \u00a0 only the 1st different character need be displayed\n::::* \u00a0 display where the different character is in the string\n::::* \u00a0 the above messages can be part of a single message\n::::* \u00a0 display the hexadecimal value of the different character\n\n\nUse (at least) these seven test values \u00a0 (strings):\n:::* \u00a0 a string of length \u00a0 0 \u00a0 (an empty string)\n:::* \u00a0 a string of length \u00a0 3 \u00a0 which contains three blanks\n:::* \u00a0 a string of length \u00a0 1 \u00a0 which contains: \u00a0 '''2'''\n:::* \u00a0 a string of length \u00a0 3 \u00a0 which contains: \u00a0 '''333'''\n:::* \u00a0 a string of length \u00a0 3 \u00a0 which contains: \u00a0 '''.55'''\n:::* \u00a0 a string of length \u00a0 6 \u00a0 which contains: \u00a0 '''tttTTT'''\n:::* \u00a0 a string of length \u00a0 9 \u00a0 with a blank in the middle: \u00a0 '''4444 \u00a0 444k'''\n\n\n\nShow all output here on this page.\n\n\n", "solution": "'''Determine if a string has all the same characters'''\n\nfrom itertools import groupby\n\n\n# firstDifferingCharLR :: String -> Either String Dict\ndef firstDifferingCharLR(s):\n '''Either a message reporting that no character changes were\n seen, or a dictionary with details of the first character\n (if any) that differs from that at the head of the string.\n '''\n def details(xs):\n c = xs[1][0]\n return {\n 'char': repr(c),\n 'hex': hex(ord(c)),\n 'index': s.index(c),\n 'total': len(s)\n }\n xs = list(groupby(s))\n return Right(details(xs)) if 1 < len(xs) else (\n Left('Total length ' + str(len(s)) + ' - No character changes.')\n )\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Test of 7 strings'''\n\n print(fTable('First, if any, points of difference:\\n')(repr)(\n either(identity)(\n lambda dct: dct['char'] + ' (' + dct['hex'] +\n ') at character ' + str(1 + dct['index']) +\n ' of ' + str(dct['total']) + '.'\n )\n )(firstDifferingCharLR)([\n '',\n ' ',\n '2',\n '333',\n '.55',\n 'tttTTT',\n '4444 444'\n ]))\n\n\n# GENERIC -------------------------------------------------\n\n# either :: (a -> c) -> (b -> c) -> Either a b -> c\ndef either(fl):\n '''The application of fl to e if e is a Left value,\n or the application of fr to e if e is a Right value.\n '''\n return lambda fr: lambda e: fl(e['Left']) if (\n None is e['Right']\n ) else fr(e['Right'])\n\n\n# identity :: a -> a\ndef identity(x):\n '''The identity function.'''\n return x\n\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\n '''\n def go(xShow, fxShow, f, xs):\n ys = [xShow(x) for x in xs]\n w = max(map(len, ys))\n return s + '\\n' + '\\n'.join(map(\n lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n xs, ys\n ))\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\n# Left :: a -> Either a b\ndef Left(x):\n '''Constructor for an empty Either (option type) value\n with an associated string.\n '''\n return {'type': 'Either', 'Right': None, 'Left': x}\n\n\n# Right :: b -> Either a b\ndef Right(x):\n '''Constructor for a populated Either (option type) value'''\n return {'type': 'Either', 'Left': None, 'Right': x}\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} +{"title": "Determine if a string has all unique characters", "language": "C", "task": ";Task:\n\nGiven a character string \u00a0 (which may be empty, or have a length of zero characters):\n::* \u00a0 create a function/procedure/routine to:\n::::* \u00a0 determine if all the characters in the string are unique\n::::* \u00a0 indicate if or which character is duplicated and where\n::* \u00a0 display each string and its length \u00a0 (as the strings are being examined)\n::* \u00a0 a zero\u2500length (empty) string shall be considered as unique\n::* \u00a0 process the strings from left\u2500to\u2500right\n::* \u00a0 if \u00a0 \u00a0 \u00a0 unique, \u00a0 display a message saying such\n::* \u00a0 if not unique, \u00a0 then:\n::::* \u00a0 display a message saying such\n::::* \u00a0 display what character is duplicated\n::::* \u00a0 only the 1st non\u2500unique character need be displayed\n::::* \u00a0 display where \"both\" duplicated characters are in the string\n::::* \u00a0 the above messages can be part of a single message\n::::* \u00a0 display the hexadecimal value of the duplicated character\n\n\n\nUse (at least) these five test values \u00a0 (strings):\n:::* \u00a0 a string of length \u00a0 \u00a0 0 \u00a0 (an empty string)\n:::* \u00a0 a string of length \u00a0 \u00a0 1 \u00a0 which is a single period \u00a0 ('''.''')\n:::* \u00a0 a string of length \u00a0 \u00a0 6 \u00a0 which contains: \u00a0 '''abcABC'''\n:::* \u00a0 a string of length \u00a0 \u00a0 7 \u00a0 which contains a blank in the middle: \u00a0 '''XYZ\u00a0 ZYX'''\n:::* \u00a0 a string of length \u00a0 36 \u00a0 which \u00a0 ''doesn't'' \u00a0 contain the letter \"oh\":\n:::::::: '''1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ'''\n\n\n\nShow all output here on this page.\n\n\n", "solution": "\n#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\nOutput, test strings from the task [[Determine_if_a_string_has_all_the_same_characters]] are also included :\n\nabhishek_ghosh@Azure:~/doodles$ ./a.out\n\"\" - Length 0 - Contains only unique characters.\nabhishek_ghosh@Azure:~/doodles$ ./a.out .\n\".\" - Length 1 - Contains only unique characters.\nabhishek_ghosh@Azure:~/doodles$ ./a.out abcABC\n\"abcABC\" - Length 6 - Contains only unique characters.\nabhishek_ghosh@Azure:~/doodles$ ./a.out \"XYZ YZX\"\n\"XYZ YZX\" - Length 7 - Contains the following duplicate characters :\n'X' (0x58) at positions : 1 7\n'Y' (0x59) at positions : 2 5\n'Z' (0x5a) at positions : 3 6\nabhishek_ghosh@Azure:~/doodles$ ./a.out 1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\n\"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\" - Length 36 - Contains the following duplicate characters :\n'0' (0x30) at positions : 10 25\nabhishek_ghosh@Azure:~/doodles$ ./a.out \" \"\n\" \" - Length 3 - Contains the following duplicate characters :\n' ' (0x20) at positions : 1 2 3\nabhishek_ghosh@Azure:~/doodles$ ./a.out 2\n\"2\" - Length 1 - Contains only unique characters.\nabhishek_ghosh@Azure:~/doodles$ ./a.out 333\n\"333\" - Length 3 - Contains the following duplicate characters :\n'3' (0x33) at positions : 1 2 3\nabhishek_ghosh@Azure:~/doodles$ ./a.out .55\n\".55\" - Length 3 - Contains the following duplicate characters :\n'5' (0x35) at positions : 2 3\nabhishek_ghosh@Azure:~/doodles$ ./a.out tttTTT\n\"tttTTT\" - Length 6 - Contains the following duplicate characters :\n't' (0x74) at positions : 1 2 3\n'T' (0x54) at positions : 4 5 6\nabhishek_ghosh@Azure:~/doodles$ ./a.out \"4444 444k\"\n\"4444 444k\" - Length 9 - Contains the following duplicate characters :\n'4' (0x34) at positions : 1 2 3 4 6 7 8\n\n"} +{"title": "Determine if a string has all unique characters", "language": "JavaScript", "task": ";Task:\n\nGiven a character string \u00a0 (which may be empty, or have a length of zero characters):\n::* \u00a0 create a function/procedure/routine to:\n::::* \u00a0 determine if all the characters in the string are unique\n::::* \u00a0 indicate if or which character is duplicated and where\n::* \u00a0 display each string and its length \u00a0 (as the strings are being examined)\n::* \u00a0 a zero\u2500length (empty) string shall be considered as unique\n::* \u00a0 process the strings from left\u2500to\u2500right\n::* \u00a0 if \u00a0 \u00a0 \u00a0 unique, \u00a0 display a message saying such\n::* \u00a0 if not unique, \u00a0 then:\n::::* \u00a0 display a message saying such\n::::* \u00a0 display what character is duplicated\n::::* \u00a0 only the 1st non\u2500unique character need be displayed\n::::* \u00a0 display where \"both\" duplicated characters are in the string\n::::* \u00a0 the above messages can be part of a single message\n::::* \u00a0 display the hexadecimal value of the duplicated character\n\n\n\nUse (at least) these five test values \u00a0 (strings):\n:::* \u00a0 a string of length \u00a0 \u00a0 0 \u00a0 (an empty string)\n:::* \u00a0 a string of length \u00a0 \u00a0 1 \u00a0 which is a single period \u00a0 ('''.''')\n:::* \u00a0 a string of length \u00a0 \u00a0 6 \u00a0 which contains: \u00a0 '''abcABC'''\n:::* \u00a0 a string of length \u00a0 \u00a0 7 \u00a0 which contains a blank in the middle: \u00a0 '''XYZ\u00a0 ZYX'''\n:::* \u00a0 a string of length \u00a0 36 \u00a0 which \u00a0 ''doesn't'' \u00a0 contain the letter \"oh\":\n:::::::: '''1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ'''\n\n\n\nShow all output here on this page.\n\n\n", "solution": "(() => {\n 'use strict';\n\n // duplicatedCharIndices :: String -> Maybe (Char, [Int])\n const duplicatedCharIndices = s => {\n const\n duplicates = filter(g => 1 < g.length)(\n groupBy(on(eq)(snd))(\n sortOn(snd)(\n zip(enumFrom(0))(chars(s))\n )\n )\n );\n return 0 < duplicates.length ? Just(\n fanArrow(compose(snd, fst))(map(fst))(\n sortOn(compose(fst, fst))(\n duplicates\n )[0]\n )\n ) : Nothing();\n };\n\n // ------------------------TEST------------------------\n const main = () =>\n console.log(\n fTable('First duplicated character, if any:')(\n s => `'${s}' (${s.length})`\n )(maybe('None')(tpl => {\n const [c, ixs] = Array.from(tpl);\n return `'${c}' (0x${showHex(ord(c))}) at ${ixs.join(', ')}`\n }))(duplicatedCharIndices)([\n \"\", \".\", \"abcABC\", \"XYZ ZYX\",\n \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\"\n ])\n );\n\n\n // -----------------GENERIC FUNCTIONS------------------\n\n // Just :: a -> Maybe a\n const Just = x => ({\n type: 'Maybe',\n Nothing: false,\n Just: x\n });\n\n // Nothing :: Maybe a\n const Nothing = () => ({\n type: 'Maybe',\n Nothing: true,\n });\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = a => b => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // chars :: String -> [Char]\n const chars = s => s.split('');\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (...fs) =>\n x => fs.reduceRight((a, f) => f(a), x);\n\n // enumFrom :: Enum a => a -> [a]\n function* enumFrom(x) {\n let v = x;\n while (true) {\n yield v;\n v = 1 + v;\n }\n }\n\n // eq (==) :: Eq a => a -> a -> Bool\n const eq = a => b => a === b;\n\n // fanArrow (&&&) :: (a -> b) -> (a -> c) -> (a -> (b, c))\n const fanArrow = f =>\n // Compose a function from a simple value to a tuple of\n // the separate outputs of two different functions.\n g => x => Tuple(f(x))(g(x));\n\n // filter :: (a -> Bool) -> [a] -> [a]\n const filter = f => xs => xs.filter(f);\n\n // fst :: (a, b) -> a\n const fst = tpl => tpl[0];\n\n // fTable :: String -> (a -> String) -> (b -> String)\n // -> (a -> b) -> [a] -> String\n const fTable = s => xShow => fxShow => f => xs => {\n // Heading -> x display function ->\n // fx display function ->\n // f -> values -> tabular string\n const\n ys = xs.map(xShow),\n w = Math.max(...ys.map(length));\n return s + '\\n' + zipWith(\n a => b => a.padStart(w, ' ') + ' -> ' + b\n )(ys)(\n xs.map(x => fxShow(f(x)))\n ).join('\\n');\n };\n\n // groupBy :: (a -> a -> Bool) -> [a] -> [[a]]\n const groupBy = fEq =>\n // Typical usage: groupBy(on(eq)(f), xs)\n xs => 0 < xs.length ? (() => {\n const\n tpl = xs.slice(1).reduce(\n (gw, x) => {\n const\n gps = gw[0],\n wkg = gw[1];\n return fEq(wkg[0])(x) ? (\n Tuple(gps)(wkg.concat([x]))\n ) : Tuple(gps.concat([wkg]))([x]);\n },\n Tuple([])([xs[0]])\n );\n return tpl[0].concat([tpl[1]])\n })() : [];\n\n // length :: [a] -> Int\n const length = xs =>\n // Returns Infinity over objects without finite length.\n // This enables zip and zipWith to choose the shorter\n // argument when one is non-finite, like cycle, repeat etc\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n // map :: (a -> b) -> [a] -> [b]\n const map = f => xs =>\n (Array.isArray(xs) ? (\n xs\n ) : xs.split('')).map(f);\n\n // maybe :: b -> (a -> b) -> Maybe a -> b\n const maybe = v =>\n // Default value (v) if m is Nothing, or f(m.Just)\n f => m => m.Nothing ? v : f(m.Just);\n\n // on :: (b -> b -> c) -> (a -> b) -> a -> a -> c\n const on = f =>\n g => a => b => f(g(a))(g(b));\n\n // ord :: Char -> Int\n const ord = c => c.codePointAt(0);\n\n // showHex :: Int -> String\n const showHex = n =>\n n.toString(16);\n\n // snd :: (a, b) -> b\n const snd = tpl => tpl[1];\n\n // sortOn :: Ord b => (a -> b) -> [a] -> [a]\n const sortOn = f =>\n // Equivalent to sortBy(comparing(f)), but with f(x)\n // evaluated only once for each x in xs.\n // ('Schwartzian' decorate-sort-undecorate).\n xs => xs.map(\n x => [f(x), x]\n ).sort(\n (a, b) => a[0] < b[0] ? -1 : (a[0] > b[0] ? 1 : 0)\n ).map(x => x[1]);\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n => xs =>\n 'GeneratorFunction' !== xs.constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // uncurry :: (a -> b -> c) -> ((a, b) -> c)\n const uncurry = f =>\n (x, y) => f(x)(y)\n\n // zip :: [a] -> [b] -> [(a, b)]\n const zip = xs => ys => {\n const\n lng = Math.min(length(xs), length(ys)),\n vs = take(lng)(ys);\n return take(lng)(xs)\n .map((x, i) => Tuple(x)(vs[i]));\n };\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = f =>\n xs => ys => {\n const\n lng = Math.min(length(xs), length(ys)),\n vs = take(lng)(ys);\n return take(lng)(xs)\n .map((x, i) => f(x)(vs[i]));\n };\n\n // MAIN ---\n return main();\n})();"} +{"title": "Determine if a string has all unique characters", "language": "Python", "task": ";Task:\n\nGiven a character string \u00a0 (which may be empty, or have a length of zero characters):\n::* \u00a0 create a function/procedure/routine to:\n::::* \u00a0 determine if all the characters in the string are unique\n::::* \u00a0 indicate if or which character is duplicated and where\n::* \u00a0 display each string and its length \u00a0 (as the strings are being examined)\n::* \u00a0 a zero\u2500length (empty) string shall be considered as unique\n::* \u00a0 process the strings from left\u2500to\u2500right\n::* \u00a0 if \u00a0 \u00a0 \u00a0 unique, \u00a0 display a message saying such\n::* \u00a0 if not unique, \u00a0 then:\n::::* \u00a0 display a message saying such\n::::* \u00a0 display what character is duplicated\n::::* \u00a0 only the 1st non\u2500unique character need be displayed\n::::* \u00a0 display where \"both\" duplicated characters are in the string\n::::* \u00a0 the above messages can be part of a single message\n::::* \u00a0 display the hexadecimal value of the duplicated character\n\n\n\nUse (at least) these five test values \u00a0 (strings):\n:::* \u00a0 a string of length \u00a0 \u00a0 0 \u00a0 (an empty string)\n:::* \u00a0 a string of length \u00a0 \u00a0 1 \u00a0 which is a single period \u00a0 ('''.''')\n:::* \u00a0 a string of length \u00a0 \u00a0 6 \u00a0 which contains: \u00a0 '''abcABC'''\n:::* \u00a0 a string of length \u00a0 \u00a0 7 \u00a0 which contains a blank in the middle: \u00a0 '''XYZ\u00a0 ZYX'''\n:::* \u00a0 a string of length \u00a0 36 \u00a0 which \u00a0 ''doesn't'' \u00a0 contain the letter \"oh\":\n:::::::: '''1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ'''\n\n\n\nShow all output here on this page.\n\n\n", "solution": "'''Determine if a string has all unique characters'''\n\nfrom itertools import groupby\n\n\n# duplicatedCharIndices :: String -> Maybe (Char, [Int])\ndef duplicatedCharIndices(s):\n '''Just the first duplicated character, and\n the indices of its occurrence, or\n Nothing if there are no duplications.\n '''\n def go(xs):\n if 1 < len(xs):\n duplicates = list(filter(lambda kv: 1 < len(kv[1]), [\n (k, list(v)) for k, v in groupby(\n sorted(xs, key=swap),\n key=snd\n )\n ]))\n return Just(second(fmap(fst))(\n sorted(\n duplicates,\n key=lambda kv: kv[1][0]\n )[0]\n )) if duplicates else Nothing()\n else:\n return Nothing()\n return go(list(enumerate(s)))\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Test over various strings.'''\n\n def showSample(s):\n return repr(s) + ' (' + str(len(s)) + ')'\n\n def showDuplicate(cix):\n c, ix = cix\n return repr(c) + (\n ' (' + hex(ord(c)) + ') at ' + repr(ix)\n )\n\n print(\n fTable('First duplicated character, if any:')(\n showSample\n )(maybe('None')(showDuplicate))(duplicatedCharIndices)([\n '', '.', 'abcABC', 'XYZ ZYX',\n '1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ'\n ])\n )\n\n\n# FORMATTING ----------------------------------------------\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\n '''\n def go(xShow, fxShow, f, xs):\n ys = [xShow(x) for x in xs]\n w = max(map(len, ys))\n return s + '\\n' + '\\n'.join(map(\n lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n xs, ys\n ))\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\n# GENERIC -------------------------------------------------\n\n# Just :: a -> Maybe a\ndef Just(x):\n '''Constructor for an inhabited Maybe (option type) value.\n Wrapper containing the result of a computation.\n '''\n return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n# Nothing :: Maybe a\ndef Nothing():\n '''Constructor for an empty Maybe (option type) value.\n Empty wrapper returned where a computation is not possible.\n '''\n return {'type': 'Maybe', 'Nothing': True}\n\n\n# fmap :: (a -> b) -> [a] -> [b]\ndef fmap(f):\n '''fmap over a list.\n f lifted to a function over a list.\n '''\n return lambda xs: [f(x) for x in xs]\n\n\n# fst :: (a, b) -> a\ndef fst(tpl):\n '''First member of a pair.'''\n return tpl[0]\n\n\n# head :: [a] -> a\ndef head(xs):\n '''The first element of a non-empty list.'''\n return xs[0] if isinstance(xs, list) else next(xs)\n\n\n# maybe :: b -> (a -> b) -> Maybe a -> b\ndef maybe(v):\n '''Either the default value v, if m is Nothing,\n or the application of f to x,\n where m is Just(x).\n '''\n return lambda f: lambda m: v if (\n None is m or m.get('Nothing')\n ) else f(m.get('Just'))\n\n\n# second :: (a -> b) -> ((c, a) -> (c, b))\ndef second(f):\n '''A simple function lifted to a function over a tuple,\n with f applied only to the second of two values.\n '''\n return lambda xy: (xy[0], f(xy[1]))\n\n\n# snd :: (a, b) -> b\ndef snd(tpl):\n '''Second member of a pair.'''\n return tpl[1]\n\n\n# swap :: (a, b) -> (b, a)\ndef swap(tpl):\n '''The swapped components of a pair.'''\n return (tpl[1], tpl[0])\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} +{"title": "Determine if a string is collapsible", "language": "C", "task": "Determine if a character string is \u00a0 ''collapsible''.\n\nAnd if so, \u00a0 collapse the string \u00a0 (by removing \u00a0 ''immediately repeated'' \u00a0 characters).\n\n\n\nIf a character string has \u00a0 ''immediately repeated'' \u00a0 character(s), \u00a0 the repeated characters are to be\ndeleted (removed), \u00a0 but not the primary (1st) character(s).\n\n\nAn \u00a0 ''immediately repeated'' \u00a0 character is any character that is \u00a0 immediately \u00a0 followed by an\nidentical character (or characters). \u00a0 Another word choice could've been \u00a0 ''duplicated character'', \u00a0 but that\nmight have ruled out \u00a0 (to some readers) \u00a0 triplicated characters \u00a0 \u00b7\u00b7\u00b7 \u00a0 or more.\n\n\n{This Rosetta Code task was inspired by a newly introduced \u00a0 (as of around November 2019) \u00a0 '''PL/I''' \u00a0 BIF: \u00a0 '''collapse'''.}\n\n\n;Examples:\nIn the following character string:\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 \u00a0 '''t''', \u00a0 '''e''', and \u00a0 '''l''' \u00a0 are repeated characters, \u00a0 indicated\nby underscores (above), \u00a0 even though they (those characters) appear elsewhere in the character string.\n\n\n\nSo, after ''collapsing'' the string, the result would be:\n\n The beter the 4-whel drive, the further you'l be from help when ya get stuck! \n\n\n\n\nAnother example:\nIn the following character string:\n\n headmistressship \n\n\nThe \"collapsed\" string would be:\n\n headmistreship \n\n\n\n;Task:\nWrite a subroutine/function/procedure/routine\u00b7\u00b7\u00b7 \u00a0 to\nlocate \u00a0 ''repeated'' \u00a0 characters and \u00a0 ''collapse'' \u00a0 (delete) \u00a0 them from the character\nstring. \u00a0 The character string can be processed from either direction.\n\n\nShow all output here, on this page:\n:* \u00a0 the \u00a0 original string and its length\n:* \u00a0 the resultant string and its length\n:* \u00a0 the above strings should be \"bracketed\" with \u00a0 '''<<<''' \u00a0 and \u00a0 '''>>>''' \u00a0 (to delineate blanks)\n;* \u00a0 \u00ab\u00ab\u00abGuillemets may be used instead for \"bracketing\" for the more artistic programmers, \u00a0 shown used here\u00bb\u00bb\u00bb\n\n\n\n\nUse (at least) the following five strings, \u00a0 all strings are length seventy-two (characters, including blanks), \u00a0 except\nthe 1st string:\n\n string\n number\n \u2554\u2557\n 1 \u2551\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557 \u25c4\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0 a null string (length zero)\n 2 \u2551\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln \u2551\n 3 \u2551..1111111111111111111111111111111111111111111111111111111111111117777888\u2551\n 4 \u2551I never give 'em hell, I just tell the truth, and they think it's hell. \u2551\n 5 \u2551 --- Harry S Truman \u2551 \u25c4\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0 has many repeated blanks\n \u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d\n\n\n", "solution": "\n#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 collapsible", "language": "JavaScript", "task": "Determine if a character string is \u00a0 ''collapsible''.\n\nAnd if so, \u00a0 collapse the string \u00a0 (by removing \u00a0 ''immediately repeated'' \u00a0 characters).\n\n\n\nIf a character string has \u00a0 ''immediately repeated'' \u00a0 character(s), \u00a0 the repeated characters are to be\ndeleted (removed), \u00a0 but not the primary (1st) character(s).\n\n\nAn \u00a0 ''immediately repeated'' \u00a0 character is any character that is \u00a0 immediately \u00a0 followed by an\nidentical character (or characters). \u00a0 Another word choice could've been \u00a0 ''duplicated character'', \u00a0 but that\nmight have ruled out \u00a0 (to some readers) \u00a0 triplicated characters \u00a0 \u00b7\u00b7\u00b7 \u00a0 or more.\n\n\n{This Rosetta Code task was inspired by a newly introduced \u00a0 (as of around November 2019) \u00a0 '''PL/I''' \u00a0 BIF: \u00a0 '''collapse'''.}\n\n\n;Examples:\nIn the following character string:\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 \u00a0 '''t''', \u00a0 '''e''', and \u00a0 '''l''' \u00a0 are repeated characters, \u00a0 indicated\nby underscores (above), \u00a0 even though they (those characters) appear elsewhere in the character string.\n\n\n\nSo, after ''collapsing'' the string, the result would be:\n\n The beter the 4-whel drive, the further you'l be from help when ya get stuck! \n\n\n\n\nAnother example:\nIn the following character string:\n\n headmistressship \n\n\nThe \"collapsed\" string would be:\n\n headmistreship \n\n\n\n;Task:\nWrite a subroutine/function/procedure/routine\u00b7\u00b7\u00b7 \u00a0 to\nlocate \u00a0 ''repeated'' \u00a0 characters and \u00a0 ''collapse'' \u00a0 (delete) \u00a0 them from the character\nstring. \u00a0 The character string can be processed from either direction.\n\n\nShow all output here, on this page:\n:* \u00a0 the \u00a0 original string and its length\n:* \u00a0 the resultant string and its length\n:* \u00a0 the above strings should be \"bracketed\" with \u00a0 '''<<<''' \u00a0 and \u00a0 '''>>>''' \u00a0 (to delineate blanks)\n;* \u00a0 \u00ab\u00ab\u00abGuillemets may be used instead for \"bracketing\" for the more artistic programmers, \u00a0 shown used here\u00bb\u00bb\u00bb\n\n\n\n\nUse (at least) the following five strings, \u00a0 all strings are length seventy-two (characters, including blanks), \u00a0 except\nthe 1st string:\n\n string\n number\n \u2554\u2557\n 1 \u2551\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557 \u25c4\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0 a null string (length zero)\n 2 \u2551\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln \u2551\n 3 \u2551..1111111111111111111111111111111111111111111111111111111111111117777888\u2551\n 4 \u2551I never give 'em hell, I just tell the truth, and they think it's hell. \u2551\n 5 \u2551 --- Harry S Truman \u2551 \u25c4\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0 has many repeated blanks\n \u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d\n\n\n", "solution": "\nString.prototype.collapse = function() {\n let str = this;\n for (let i = 0; i < str.length; i++) {\n while (str[i] == str[i+1]) str = str.substr(0,i) + str.substr(i+1);\n }\n return str;\n}\n\n// testing\nlet strings = [\n '',\n '\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ',\n '..1111111111111111111111111111111111111111111111111111111111111117777888',\n `I never give 'em hell, I just tell the truth, and they think it's hell. `,\n ' --- Harry S Truman '\n];\nfor (let i = 0; i < strings.length; i++) {\n let str = strings[i], col = str.collapse();\n console.log(`\u00ab\u00ab\u00ab${str}\u00bb\u00bb\u00bb (${str.length})`);\n console.log(`\u00ab\u00ab\u00ab${col}\u00bb\u00bb\u00bb (${col.length})`);\n}\n"} +{"title": "Determine if a string is collapsible", "language": "Python", "task": "Determine if a character string is \u00a0 ''collapsible''.\n\nAnd if so, \u00a0 collapse the string \u00a0 (by removing \u00a0 ''immediately repeated'' \u00a0 characters).\n\n\n\nIf a character string has \u00a0 ''immediately repeated'' \u00a0 character(s), \u00a0 the repeated characters are to be\ndeleted (removed), \u00a0 but not the primary (1st) character(s).\n\n\nAn \u00a0 ''immediately repeated'' \u00a0 character is any character that is \u00a0 immediately \u00a0 followed by an\nidentical character (or characters). \u00a0 Another word choice could've been \u00a0 ''duplicated character'', \u00a0 but that\nmight have ruled out \u00a0 (to some readers) \u00a0 triplicated characters \u00a0 \u00b7\u00b7\u00b7 \u00a0 or more.\n\n\n{This Rosetta Code task was inspired by a newly introduced \u00a0 (as of around November 2019) \u00a0 '''PL/I''' \u00a0 BIF: \u00a0 '''collapse'''.}\n\n\n;Examples:\nIn the following character string:\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 \u00a0 '''t''', \u00a0 '''e''', and \u00a0 '''l''' \u00a0 are repeated characters, \u00a0 indicated\nby underscores (above), \u00a0 even though they (those characters) appear elsewhere in the character string.\n\n\n\nSo, after ''collapsing'' the string, the result would be:\n\n The beter the 4-whel drive, the further you'l be from help when ya get stuck! \n\n\n\n\nAnother example:\nIn the following character string:\n\n headmistressship \n\n\nThe \"collapsed\" string would be:\n\n headmistreship \n\n\n\n;Task:\nWrite a subroutine/function/procedure/routine\u00b7\u00b7\u00b7 \u00a0 to\nlocate \u00a0 ''repeated'' \u00a0 characters and \u00a0 ''collapse'' \u00a0 (delete) \u00a0 them from the character\nstring. \u00a0 The character string can be processed from either direction.\n\n\nShow all output here, on this page:\n:* \u00a0 the \u00a0 original string and its length\n:* \u00a0 the resultant string and its length\n:* \u00a0 the above strings should be \"bracketed\" with \u00a0 '''<<<''' \u00a0 and \u00a0 '''>>>''' \u00a0 (to delineate blanks)\n;* \u00a0 \u00ab\u00ab\u00abGuillemets may be used instead for \"bracketing\" for the more artistic programmers, \u00a0 shown used here\u00bb\u00bb\u00bb\n\n\n\n\nUse (at least) the following five strings, \u00a0 all strings are length seventy-two (characters, including blanks), \u00a0 except\nthe 1st string:\n\n string\n number\n \u2554\u2557\n 1 \u2551\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557 \u25c4\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0 a null string (length zero)\n 2 \u2551\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln \u2551\n 3 \u2551..1111111111111111111111111111111111111111111111111111111111111117777888\u2551\n 4 \u2551I never give 'em hell, I just tell the truth, and they think it's hell. \u2551\n 5 \u2551 --- Harry S Truman \u2551 \u25c4\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0 has many repeated blanks\n \u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d\n\n\n", "solution": "from itertools import groupby\n\ndef collapser(txt):\n return ''.join(item for item, grp in groupby(txt))\n\nif __name__ == '__main__':\n strings = [\n \"\",\n '\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ',\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\",\n \"aardvark\",\n \"\ud83d\ude0d\ud83d\ude00\ud83d\ude4c\ud83d\udc83\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude4c\",\n ]\n for txt in strings:\n this = \"Original\"\n print(f\"\\n{this:14} Size: {len(txt)} \u00ab\u00ab\u00ab{txt}\u00bb\u00bb\u00bb\" )\n this = \"Collapsed\"\n sqz = collapser(txt)\n print(f\"{this:>14} Size: {len(sqz)} \u00ab\u00ab\u00ab{sqz}\u00bb\u00bb\u00bb\" )"} +{"title": "Determine if a string is squeezable", "language": "C", "task": "Determine if a character string is \u00a0 ''squeezable''.\n\nAnd if so, \u00a0 squeeze the string \u00a0 (by removing any number of\na \u00a0 ''specified'' \u00a0 ''immediately repeated'' \u00a0 character).\n\n\nThis task is very similar to the task \u00a0 \u00a0 '''Determine if a character string is collapsible''' \u00a0 \u00a0 except\nthat only a specified character is \u00a0 ''squeezed'' \u00a0 instead of any character that is ''immediately repeated''.\n\n\nIf a character string has a specified \u00a0 ''immediately repeated'' \u00a0 character(s), \u00a0 the repeated characters are to be\ndeleted (removed), \u00a0 but not the primary (1st) character(s).\n\n\nA specified \u00a0 ''immediately repeated'' \u00a0 character is any specified character that is \u00a0 immediately \u00a0\nfollowed by an identical character (or characters). \u00a0 Another word choice could've been \u00a0 ''duplicated\ncharacter'', \u00a0 but that might have ruled out \u00a0 (to some readers) \u00a0 triplicated characters \u00a0 \u00b7\u00b7\u00b7 \u00a0 or more.\n\n\n{This Rosetta Code task was inspired by a newly introduced \u00a0 (as of around\nNovember 2019) \u00a0 '''PL/I''' \u00a0 BIF: \u00a0 '''squeeze'''.}\n\n\n;Examples:\nIn the following character string with a specified \u00a0 ''immediately repeated'' \u00a0 character of \u00a0 '''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 \u00a0 '''e''' \u00a0 is an specified repeated character, \u00a0 indicated by an underscore\n(above), \u00a0 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, \u00a0 using a specified immediately repeated character \u00a0 '''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\u00b7\u00b7\u00b7 \u00a0 to locate a \u00a0 ''specified immediately repeated'' \u00a0 character\nand \u00a0 ''squeeze'' \u00a0 (delete) \u00a0 them from the character string. \u00a0 The\ncharacter string can be processed from either direction.\n\n\nShow all output here, on this page:\n:* \u00a0 the \u00a0 specified repeated character \u00a0 (to be searched for and possibly ''squeezed''):\n:* \u00a0 the \u00a0 original string and its length\n:* \u00a0 the resultant string and its length\n:* \u00a0 the above strings should be \"bracketed\" with \u00a0 '''<<<''' \u00a0 and \u00a0 '''>>>''' \u00a0 (to delineate blanks)\n;* \u00a0 \u00ab\u00ab\u00abGuillemets may be used instead for \"bracketing\" for the more artistic programmers, \u00a0 shown used here\u00bb\u00bb\u00bb\n\n\n\nUse (at least) the following five strings, \u00a0 all strings are length seventy-two (characters, including blanks), \u00a0 except\nthe 1st string:\n\n immediately\n string repeated\n number character\n ( \u2193 a blank, a minus, a seven, a period)\n \u2554\u2557\n 1 \u2551\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557 ' ' \u25c4\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0 a null string (length zero)\n 2 \u2551\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln \u2551 '-'\n 3 \u2551..1111111111111111111111111111111111111111111111111111111111111117777888\u2551 '7'\n 4 \u2551I never give 'em hell, I just tell the truth, and they think it's hell. \u2551 '.'\n 5 \u2551 --- Harry S Truman \u2551 (below) \u25c4\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0 has many repeated blanks\n \u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d \u2191\n \u2502\n \u2502\n For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:\n \u2022 a blank\n \u2022 a minus\n \u2022 a lowercase '''r'''\n\n\nNote: \u00a0 there should be seven results shown, \u00a0 one each for the 1st four strings, \u00a0 and three results for\nthe 5th string.\n\n\n", "solution": "\n#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": "Determine if a string is squeezable", "language": "Python", "task": "Determine if a character string is \u00a0 ''squeezable''.\n\nAnd if so, \u00a0 squeeze the string \u00a0 (by removing any number of\na \u00a0 ''specified'' \u00a0 ''immediately repeated'' \u00a0 character).\n\n\nThis task is very similar to the task \u00a0 \u00a0 '''Determine if a character string is collapsible''' \u00a0 \u00a0 except\nthat only a specified character is \u00a0 ''squeezed'' \u00a0 instead of any character that is ''immediately repeated''.\n\n\nIf a character string has a specified \u00a0 ''immediately repeated'' \u00a0 character(s), \u00a0 the repeated characters are to be\ndeleted (removed), \u00a0 but not the primary (1st) character(s).\n\n\nA specified \u00a0 ''immediately repeated'' \u00a0 character is any specified character that is \u00a0 immediately \u00a0\nfollowed by an identical character (or characters). \u00a0 Another word choice could've been \u00a0 ''duplicated\ncharacter'', \u00a0 but that might have ruled out \u00a0 (to some readers) \u00a0 triplicated characters \u00a0 \u00b7\u00b7\u00b7 \u00a0 or more.\n\n\n{This Rosetta Code task was inspired by a newly introduced \u00a0 (as of around\nNovember 2019) \u00a0 '''PL/I''' \u00a0 BIF: \u00a0 '''squeeze'''.}\n\n\n;Examples:\nIn the following character string with a specified \u00a0 ''immediately repeated'' \u00a0 character of \u00a0 '''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 \u00a0 '''e''' \u00a0 is an specified repeated character, \u00a0 indicated by an underscore\n(above), \u00a0 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, \u00a0 using a specified immediately repeated character \u00a0 '''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\u00b7\u00b7\u00b7 \u00a0 to locate a \u00a0 ''specified immediately repeated'' \u00a0 character\nand \u00a0 ''squeeze'' \u00a0 (delete) \u00a0 them from the character string. \u00a0 The\ncharacter string can be processed from either direction.\n\n\nShow all output here, on this page:\n:* \u00a0 the \u00a0 specified repeated character \u00a0 (to be searched for and possibly ''squeezed''):\n:* \u00a0 the \u00a0 original string and its length\n:* \u00a0 the resultant string and its length\n:* \u00a0 the above strings should be \"bracketed\" with \u00a0 '''<<<''' \u00a0 and \u00a0 '''>>>''' \u00a0 (to delineate blanks)\n;* \u00a0 \u00ab\u00ab\u00abGuillemets may be used instead for \"bracketing\" for the more artistic programmers, \u00a0 shown used here\u00bb\u00bb\u00bb\n\n\n\nUse (at least) the following five strings, \u00a0 all strings are length seventy-two (characters, including blanks), \u00a0 except\nthe 1st string:\n\n immediately\n string repeated\n number character\n ( \u2193 a blank, a minus, a seven, a period)\n \u2554\u2557\n 1 \u2551\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557 ' ' \u25c4\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0 a null string (length zero)\n 2 \u2551\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln \u2551 '-'\n 3 \u2551..1111111111111111111111111111111111111111111111111111111111111117777888\u2551 '7'\n 4 \u2551I never give 'em hell, I just tell the truth, and they think it's hell. \u2551 '.'\n 5 \u2551 --- Harry S Truman \u2551 (below) \u25c4\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0 has many repeated blanks\n \u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d \u2191\n \u2502\n \u2502\n For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:\n \u2022 a blank\n \u2022 a minus\n \u2022 a lowercase '''r'''\n\n\nNote: \u00a0 there should be seven results shown, \u00a0 one each for the 1st four strings, \u00a0 and three results for\nthe 5th string.\n\n\n", "solution": "from itertools import groupby\n\ndef squeezer(s, txt):\n return ''.join(item if item == s else ''.join(grp)\n for item, grp in groupby(txt))\n\nif __name__ == '__main__':\n strings = [\n \"\",\n '\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ',\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\",\n \"aardvark\",\n \"\ud83d\ude0d\ud83d\ude00\ud83d\ude4c\ud83d\udc83\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude4c\",\n ]\n squeezers = ' ,-,7,., -r,e,s,a,\ud83d\ude0d'.split(',')\n for txt, chars in zip(strings, squeezers):\n this = \"Original\"\n print(f\"\\n{this:14} Size: {len(txt)} \u00ab\u00ab\u00ab{txt}\u00bb\u00bb\u00bb\" )\n for ch in chars:\n this = f\"Squeezer '{ch}'\"\n sqz = squeezer(ch, txt)\n print(f\"{this:>14} Size: {len(sqz)} \u00ab\u00ab\u00ab{sqz}\u00bb\u00bb\u00bb\" )"} +{"title": "Determine if two triangles overlap", "language": "C", "task": "Determining if two triangles in the same plane overlap is an important topic in collision detection.\n\n\n;Task:\nDetermine which of these pairs of triangles overlap in 2D:\n\n:::* \u00a0 (0,0),(5,0),(0,5) \u00a0 \u00a0 and \u00a0 (0,0),(5,0),(0,6)\n:::* \u00a0 (0,0),(0,5),(5,0) \u00a0 \u00a0 and \u00a0 (0,0),(0,5),(5,0)\n:::* \u00a0 (0,0),(5,0),(0,5) \u00a0 \u00a0 and \u00a0 (-10,0),(-5,0),(-1,6)\n:::* \u00a0 (0,0),(5,0),(2.5,5) \u00a0 and \u00a0 (0,4),(2.5,-1),(5,4)\n:::* \u00a0 (0,0),(1,1),(0,2) \u00a0 \u00a0 and \u00a0 (2,1),(3,0),(3,2)\n:::* \u00a0 (0,0),(1,1),(0,2) \u00a0 \u00a0 and \u00a0 (2,1),(3,-2),(3,4)\n\n\nOptionally, see what the result is when only a single corner is in contact (there is no definitive correct answer):\n:::* \u00a0 (0,0),(1,0),(0,1) \u00a0 and \u00a0 (1,0),(2,0),(1,1)\n\n", "solution": "#include \n#include \n#include \n#include \n\ntypedef struct {\n double x, y;\n} Point;\n\ndouble det2D(const Point * const p1, const Point * const p2, const Point * const p3) {\n return p1->x * (p2->y - p3->y)\n + p2->x * (p3->y - p1->y)\n + p3->x * (p1->y - p2->y);\n}\n\nvoid checkTriWinding(Point * p1, Point * p2, Point * p3, bool allowReversed) {\n double detTri = det2D(p1, p2, p3);\n if (detTri < 0.0) {\n if (allowReversed) {\n double t = p3->x;\n p3->x = p2->x;\n p2->x = t;\n\n t = p3->y;\n p3->y = p2->y;\n p2->y = t;\n } else {\n errno = 1;\n }\n }\n}\n\nbool boundaryCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) {\n return det2D(p1, p2, p3) < eps;\n}\n\nbool boundaryDoesntCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) {\n return det2D(p1, p2, p3) <= eps;\n}\n\nbool triTri2D(Point t1[], Point t2[], double eps, bool allowReversed, bool onBoundary) {\n bool(*chkEdge)(Point*, Point*, Point*, double);\n int i;\n\n // Triangles must be expressed anti-clockwise\n checkTriWinding(&t1[0], &t1[1], &t1[2], allowReversed);\n if (errno != 0) {\n return false;\n }\n checkTriWinding(&t2[0], &t2[1], &t2[2], allowReversed);\n if (errno != 0) {\n return false;\n }\n\n if (onBoundary) {\n // Points on the boundary are considered as colliding\n chkEdge = boundaryCollideChk;\n } else {\n // Points on the boundary are not considered as colliding\n chkEdge = boundaryDoesntCollideChk;\n }\n\n //For edge E of trangle 1,\n for (i = 0; i < 3; ++i) {\n int j = (i + 1) % 3;\n\n //Check all points of trangle 2 lay on the external side of the edge E. If\n //they do, the triangles do not collide.\n if (chkEdge(&t1[i], &t1[j], &t2[0], eps) &&\n chkEdge(&t1[i], &t1[j], &t2[1], eps) &&\n chkEdge(&t1[i], &t1[j], &t2[2], eps)) {\n return false;\n }\n }\n\n //For edge E of trangle 2,\n for (i = 0; i < 3; i++) {\n int j = (i + 1) % 3;\n\n //Check all points of trangle 1 lay on the external side of the edge E. If\n //they do, the triangles do not collide.\n if (chkEdge(&t2[i], &t2[j], &t1[0], eps) &&\n chkEdge(&t2[i], &t2[j], &t1[1], eps) &&\n chkEdge(&t2[i], &t2[j], &t1[2], eps))\n return false;\n }\n\n //The triangles collide\n return true;\n}\n\nint main() {\n {\n Point t1[] = { {0, 0}, {5, 0}, {0, 5} };\n Point t2[] = { {0, 0}, {5, 0}, {0, 6} };\n printf(\"%d,true\\n\", triTri2D(t1, t2, 0.0, false, true));\n }\n\n {\n Point t1[] = { {0, 0}, {0, 5}, {5, 0} };\n Point t2[] = { {0, 0}, {0, 5}, {5, 0} };\n printf(\"%d,true\\n\", triTri2D(t1, t2, 0.0, true, true));\n }\n\n {\n Point t1[] = { {0, 0}, {5, 0}, {0, 5} };\n Point t2[] = { {-10, 0}, {-5, 0}, {-1, 6} };\n printf(\"%d,false\\n\", triTri2D(t1, t2, 0.0, false, true));\n }\n\n {\n Point t1[] = { {0, 0}, {5, 0}, {2.5, 5} };\n Point t2[] = { {0, 4}, {2.5, -1}, {5, 4} };\n printf(\"%d,true\\n\", triTri2D(t1, t2, 0.0, false, true));\n }\n\n {\n Point t1[] = { {0, 0}, {1, 1}, {0, 2} };\n Point t2[] = { {2, 1}, {3, 0}, {3, 2} };\n printf(\"%d,false\\n\", triTri2D(t1, t2, 0.0, false, true));\n }\n\n {\n Point t1[] = { {0, 0}, {1, 1}, {0, 2} };\n Point t2[] = { {2, 1}, {3, -2}, {3, 4} };\n printf(\"%d,false\\n\", triTri2D(t1, t2, 0.0, false, true));\n }\n\n //Barely touching\n {\n Point t1[] = { {0, 0}, {1, 0}, {0, 1} };\n Point t2[] = { {1, 0}, {2, 0}, {1, 1} };\n printf(\"%d,true\\n\", triTri2D(t1, t2, 0.0, false, true));\n }\n\n //Barely touching\n {\n Point t1[] = { {0, 0}, {1, 0}, {0, 1} };\n Point t2[] = { {1, 0}, {2, 0}, {1, 1} };\n printf(\"%d,false\\n\", triTri2D(t1, t2, 0.0, false, false));\n }\n\n return EXIT_SUCCESS;\n}"} +{"title": "Determine if two triangles overlap", "language": "Python", "task": "Determining if two triangles in the same plane overlap is an important topic in collision detection.\n\n\n;Task:\nDetermine which of these pairs of triangles overlap in 2D:\n\n:::* \u00a0 (0,0),(5,0),(0,5) \u00a0 \u00a0 and \u00a0 (0,0),(5,0),(0,6)\n:::* \u00a0 (0,0),(0,5),(5,0) \u00a0 \u00a0 and \u00a0 (0,0),(0,5),(5,0)\n:::* \u00a0 (0,0),(5,0),(0,5) \u00a0 \u00a0 and \u00a0 (-10,0),(-5,0),(-1,6)\n:::* \u00a0 (0,0),(5,0),(2.5,5) \u00a0 and \u00a0 (0,4),(2.5,-1),(5,4)\n:::* \u00a0 (0,0),(1,1),(0,2) \u00a0 \u00a0 and \u00a0 (2,1),(3,0),(3,2)\n:::* \u00a0 (0,0),(1,1),(0,2) \u00a0 \u00a0 and \u00a0 (2,1),(3,-2),(3,4)\n\n\nOptionally, see what the result is when only a single corner is in contact (there is no definitive correct answer):\n:::* \u00a0 (0,0),(1,0),(0,1) \u00a0 and \u00a0 (1,0),(2,0),(1,1)\n\n", "solution": "from __future__ import print_function\nimport numpy as np\n\ndef CheckTriWinding(tri, allowReversed):\n\ttrisq = np.ones((3,3))\n\ttrisq[:,0:2] = np.array(tri)\n\tdetTri = np.linalg.det(trisq)\n\tif detTri < 0.0:\n\t\tif allowReversed:\n\t\t\ta = trisq[2,:].copy()\n\t\t\ttrisq[2,:] = trisq[1,:]\n\t\t\ttrisq[1,:] = a\n\t\telse: raise ValueError(\"triangle has wrong winding direction\")\n\treturn trisq\n\ndef TriTri2D(t1, t2, eps = 0.0, allowReversed = False, onBoundary = True):\n\t#Trangles must be expressed anti-clockwise\n\tt1s = CheckTriWinding(t1, allowReversed)\n\tt2s = CheckTriWinding(t2, allowReversed)\n\n\tif onBoundary:\n\t\t#Points on the boundary are considered as colliding\n\t\tchkEdge = lambda x: np.linalg.det(x) < eps\n\telse:\n\t\t#Points on the boundary are not considered as colliding\n\t\tchkEdge = lambda x: np.linalg.det(x) <= eps\n\n\t#For edge E of trangle 1,\n\tfor i in range(3):\n\t\tedge = np.roll(t1s, i, axis=0)[:2,:]\n\n\t\t#Check all points of trangle 2 lay on the external side of the edge E. If\n\t\t#they do, the triangles do not collide.\n\t\tif (chkEdge(np.vstack((edge, t2s[0]))) and\n\t\t\tchkEdge(np.vstack((edge, t2s[1]))) and \n\t\t\tchkEdge(np.vstack((edge, t2s[2])))):\n\t\t\treturn False\n\n\t#For edge E of trangle 2,\n\tfor i in range(3):\n\t\tedge = np.roll(t2s, i, axis=0)[:2,:]\n\n\t\t#Check all points of trangle 1 lay on the external side of the edge E. If\n\t\t#they do, the triangles do not collide.\n\t\tif (chkEdge(np.vstack((edge, t1s[0]))) and\n\t\t\tchkEdge(np.vstack((edge, t1s[1]))) and \n\t\t\tchkEdge(np.vstack((edge, t1s[2])))):\n\t\t\treturn False\n\n\t#The triangles collide\n\treturn True\n\nif __name__==\"__main__\":\n\tt1 = [[0,0],[5,0],[0,5]]\n\tt2 = [[0,0],[5,0],[0,6]]\n\tprint (TriTri2D(t1, t2), True)\n\n\tt1 = [[0,0],[0,5],[5,0]]\n\tt2 = [[0,0],[0,6],[5,0]]\n\tprint (TriTri2D(t1, t2, allowReversed = True), True)\n\n\tt1 = [[0,0],[5,0],[0,5]]\n\tt2 = [[-10,0],[-5,0],[-1,6]]\n\tprint (TriTri2D(t1, t2), False)\n\n\tt1 = [[0,0],[5,0],[2.5,5]]\n\tt2 = [[0,4],[2.5,-1],[5,4]]\n\tprint (TriTri2D(t1, t2), True)\n\n\tt1 = [[0,0],[1,1],[0,2]]\n\tt2 = [[2,1],[3,0],[3,2]]\n\tprint (TriTri2D(t1, t2), False)\n\n\tt1 = [[0,0],[1,1],[0,2]]\n\tt2 = [[2,1],[3,-2],[3,4]]\n\tprint (TriTri2D(t1, t2), False)\n\n\t#Barely touching\n\tt1 = [[0,0],[1,0],[0,1]]\n\tt2 = [[1,0],[2,0],[1,1]]\n\tprint (TriTri2D(t1, t2, onBoundary = True), True)\n\n\t#Barely touching\n\tt1 = [[0,0],[1,0],[0,1]]\n\tt2 = [[1,0],[2,0],[1,1]]\n\tprint (TriTri2D(t1, t2, onBoundary = False), False)"} +{"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": "Dice game probabilities", "language": "JavaScript", "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": "\nlet Player = function(dice, faces) {\n this.dice = dice;\n this.faces = faces;\n this.roll = function() {\n let results = [];\n for (let x = 0; x < dice; x++)\n results.push(Math.floor(Math.random() * faces +1));\n return eval(results.join('+'));\n }\n}\n\nfunction contest(player1, player2, rounds) {\n let res = [0, 0, 0];\n for (let x = 1; x <= rounds; x++) {\n let a = player1.roll(),\n b = player2.roll();\n switch (true) {\n case (a > b): res[0]++; break;\n case (a < b): res[1]++; break;\n case (a == b): res[2]++; break;\n }\n }\n document.write(`\n \nPlayer 1 (${player1.dice} \u00d7 d${player1.faces}): ${res[0]} wins\nPlayer 2 (${player2.dice} \u00d7 d${player2.faces}): ${res[1]} wins\nDraws: ${res[2]}\n Chances for Player 1 to win:\n ~${Math.round(res[0] / eval(res.join('+')) * 100)} %\n \n `);\n}\n\nlet p1, p2;\n\np1 = new Player(9, 4),\np2 = new Player(6, 6);\ncontest(p1, p2, 1e6);\n\np1 = new Player(5, 10);\np2 = new Player(6, 7);\ncontest(p1, p2, 1e6);\n"} +{"title": "Dice game probabilities", "language": "Python", "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": "from itertools import product\n\ndef gen_dict(n_faces, n_dice):\n counts = [0] * ((n_faces + 1) * n_dice)\n for t in product(range(1, n_faces + 1), repeat=n_dice):\n counts[sum(t)] += 1\n return counts, n_faces ** n_dice\n\ndef beating_probability(n_sides1, n_dice1, n_sides2, n_dice2):\n c1, p1 = gen_dict(n_sides1, n_dice1)\n c2, p2 = gen_dict(n_sides2, n_dice2)\n p12 = float(p1 * p2)\n\n return sum(p[1] * q[1] / p12\n for p, q in product(enumerate(c1), enumerate(c2))\n if p[0] > q[0])\n\nprint beating_probability(4, 9, 6, 6)\nprint beating_probability(10, 5, 7, 6)"} +{"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": "Digital root", "language": "JavaScript", "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": "/// Digital root of 'x' in base 'b'.\n/// @return {addpers, digrt}\nfunction digitalRootBase(x,b) {\n if (x < b)\n return {addpers:0, digrt:x};\n\n var fauxroot = 0;\n while (b <= x) {\n x = (x / b) | 0;\n fauxroot += x % b;\n }\n \n var rootobj = digitalRootBase(fauxroot,b);\n rootobj.addpers += 1;\n return rootobj;\n}"} +{"title": "Digital root", "language": "Python", "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": "def digital_root (n):\n ap = 0\n n = abs(int(n))\n while n >= 10:\n n = sum(int(digit) for digit in str(n))\n ap += 1\n return ap, n\n\nif __name__ == '__main__':\n for n in [627615, 39390, 588225, 393900588225, 55]:\n persistance, root = digital_root(n)\n print(\"%12i has additive persistance %2i and digital root %i.\" \n % (n, persistance, root))"} +{"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;* [https://www.geeksforgeeks.org/disarium-number/ 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": "Disarium numbers", "language": "JavaScript", "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;* [https://www.geeksforgeeks.org/disarium-number/ 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": "\nfunction is_disarium (num) {\n let n = num\n let len = n.toString().length\n let sum = 0\n while (n > 0) {\n sum += (n % 10) ** len\n n = parseInt(n / 10, 10)\n len--\n }\n return num == sum\n}\nlet count = 0\nlet i = 1\nwhile (count < 18) {\n if (is_disarium(i)) {\n process.stdout.write(i + \" \")\n count++\n }\n i++\n}\n"} +{"title": "Disarium numbers", "language": "Python", "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;* [https://www.geeksforgeeks.org/disarium-number/ 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": "#!/usr/bin/python\n\ndef isDisarium(n):\n digitos = len(str(n))\n suma = 0\n x = n\n while x != 0:\n suma += (x % 10) ** digitos\n digitos -= 1\n x //= 10\n if suma == n:\n return True\n else:\n return False\n\nif __name__ == '__main__':\n limite = 19\n cont = 0\n n = 0\n print(\"The first\",limite,\"Disarium numbers are:\")\n while cont < limite:\n if isDisarium(n):\n print(n, end = \" \")\n cont += 1\n n += 1"} +{"title": "Display a linear combination", "language": "C", "task": ";Task:\nDisplay 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* \u00a0 don't show null terms, unless the whole combination is null. \n::::::: '''e(1)''' \u00a0 \u00a0 is fine, \u00a0 \u00a0 '''e(1) + 0*e(3)''' \u00a0 \u00a0 or \u00a0 \u00a0 '''e(1) + 0''' \u00a0 \u00a0 is wrong.\n* \u00a0 don't show scalars when they are equal to one or minus one. \n::::::: '''e(3)''' \u00a0 \u00a0 is fine, \u00a0 \u00a0 '''1*e(3)''' \u00a0 \u00a0 is wrong.\n* \u00a0 don't prefix by a minus sign if it follows a preceding term. \u00a0 Instead you use subtraction. \n::::::: '''e(4) - e(5)''' \u00a0 \u00a0 is fine, \u00a0 \u00a0 '''e(4) + -e(5)''' \u00a0 \u00a0 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": "\n\n#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": "Display a linear combination", "language": "Python", "task": ";Task:\nDisplay 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* \u00a0 don't show null terms, unless the whole combination is null. \n::::::: '''e(1)''' \u00a0 \u00a0 is fine, \u00a0 \u00a0 '''e(1) + 0*e(3)''' \u00a0 \u00a0 or \u00a0 \u00a0 '''e(1) + 0''' \u00a0 \u00a0 is wrong.\n* \u00a0 don't show scalars when they are equal to one or minus one. \n::::::: '''e(3)''' \u00a0 \u00a0 is fine, \u00a0 \u00a0 '''1*e(3)''' \u00a0 \u00a0 is wrong.\n* \u00a0 don't prefix by a minus sign if it follows a preceding term. \u00a0 Instead you use subtraction. \n::::::: '''e(4) - e(5)''' \u00a0 \u00a0 is fine, \u00a0 \u00a0 '''e(4) + -e(5)''' \u00a0 \u00a0 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": "\ndef linear(x):\n return ' + '.join(['{}e({})'.format('-' if v == -1 else '' if v == 1 else str(v) + '*', i + 1)\n for i, v in enumerate(x) if v] or ['0']).replace(' + -', ' - ')\n\nlist(map(lambda x: print(linear(x)), [[1, 2, 3], [0, 1, 2, 3], [1, 0, 3, 4], [1, 2, 0],\n [0, 0, 0], [0], [1, 1, 1], [-1, -1, -1], [-1, -2, 0, 3], [-1]]))\n"} +{"title": "Display an outline as a nested table", "language": "JavaScript", "task": "{| class=\"wikitable\" style=\"text-align: center;\"\n|-\n| style=\"background: #ffffe6; \" colspan=7 | Display an outline as a nested table.\n|-\n| style=\"background: #ffebd2; \" colspan=3 | Parse the outline to a tree,\n| style=\"background: #f0fff0; \" colspan=2 | count the leaves descending from each node,\n| style=\"background: #e6ffff; \" colspan=2 | and write out a table with 'colspan' values\n|-\n| style=\"background: #ffebd2; \" | measuring the indent of each line,\n| style=\"background: #ffebd2; \" | translating the indentation to a nested structure,\n| style=\"background: #ffebd2; \" | and padding the tree to even depth.\n| style=\"background: #f0fff0; \" | defining the width of a leaf as 1,\n| style=\"background: #f0fff0; \" | and the width of a parent node as a sum.\n| style=\"background: #e6ffff; \" | either as a wiki table,\n| style=\"background: #e6ffff; \" | or as HTML.\n|-\n| | \n| | \n| | \n| | \n| style=\"background: #f0fff0; \" | (The sum of the widths of its children)\n| | \n| | \n|}\n\nThe graphic representation of outlines is a staple of mind-mapping and the planning of papers, reports, and speeches.\n\n;Task:\nGiven a outline with at least 3 levels of indentation, for example:\n\nDisplay an outline as a nested table.\n Parse the outline to a tree,\n measuring the indent of each line,\n translating the indentation to a nested structure,\n and padding the tree to even depth.\n count the leaves descending from each node,\n defining the width of a leaf as 1,\n and the width of a parent node as a sum.\n (The sum of the widths of its children)\n and write out a table with 'colspan' values\n either as a wiki table,\n or as HTML.\n\nwrite a program in your language which translates your outline into a nested table, with WikiTable or HTML colspan values attached (where needed) to parent nodes in the nested table.\n\nThe WikiTable at the top of this page was generated from the indented outline shown above, producing the following markup string:\n\n{| class=\"wikitable\" style=\"text-align: center;\"\n|-\n| style=\"background: #ffffe6; \" colspan=7 | Display an outline as a nested table.\n|-\n| style=\"background: #ffebd2; \" colspan=3 | Parse the outline to a tree,\n| style=\"background: #f0fff0; \" colspan=2 | count the leaves descending from each node,\n| style=\"background: #e6ffff; \" colspan=2 | and write out a table with 'colspan' values\n|-\n| style=\"background: #ffebd2; \" | measuring the indent of each line,\n| style=\"background: #ffebd2; \" | translating the indentation to a nested structure,\n| style=\"background: #ffebd2; \" | and padding the tree to even depth.\n| style=\"background: #f0fff0; \" | defining the width of a leaf as 1,\n| style=\"background: #f0fff0; \" | and the width of a parent node as a sum.\n| style=\"background: #e6ffff; \" | either as a wiki table,\n| style=\"background: #e6ffff; \" | or as HTML.\n|-\n| | \n| | \n| | \n| | \n| style=\"background: #f0fff0; \" | (The sum of the widths of its children)\n| | \n| | \n|}\n\n;Extra credit:\nUse background color to distinguish the main stages of your outline, so that the subtree of each node at level two is consistently colored, and the edges between adjacent subtrees are immediately revealed.\n\n\n;Output:\nDisplay your nested table on this page.\n\n", "solution": "(() => {\n \"use strict\";\n\n // ----------- NESTED TABLES FROM OUTLINE ------------\n\n // wikiTablesFromOutline :: [String] -> String -> String\n const wikiTablesFromOutline = colorSwatch =>\n outline => forestFromIndentedLines(\n indentLevelsFromLines(lines(outline))\n )\n .map(wikiTableFromTree(colorSwatch))\n .join(\"\\n\\n\");\n\n\n // wikiTableFromTree :: [String] -> Tree String -> String\n const wikiTableFromTree = colorSwatch =>\n compose(\n wikiTableFromRows,\n levels,\n paintedTree(colorSwatch),\n widthLabelledTree,\n ap(paddedTree(\"\"))(treeDepth)\n );\n\n // ---------------------- TEST -----------------------\n // main :: IO ()\n const main = () => {\n const outline = `Display an outline as a nested table.\n Parse the outline to a tree,\n measuring the indent of each line,\n translating the indentation to a nested structure,\n and padding the tree to even depth.\n count the leaves descending from each node,\n defining the width of a leaf as 1,\n and the width of a parent node as a sum.\n (The sum of the widths of its children)\n and write out a table with 'colspan' values\n either as a wiki table,\n or as HTML.`;\n\n return wikiTablesFromOutline([\n \"#ffffe6\",\n \"#ffebd2\",\n \"#f0fff0\",\n \"#e6ffff\",\n \"#ffeeff\"\n ])(outline);\n };\n\n // --------- TREE STRUCTURE FROM NESTED TEXT ---------\n\n // forestFromIndentedLines :: [(Int, String)] ->\n // [Tree String]\n const forestFromIndentedLines = tuples => {\n const go = xs =>\n 0 < xs.length ? (() => {\n // First line and its sub-tree,\n const [indented, body] = Array.from(\n xs[0]\n ),\n [tree, rest] = Array.from(\n span(compose(lt(indented), fst))(\n tail(xs)\n )\n );\n\n // followed by the rest.\n return [\n Node(body)(go(tree))\n ].concat(go(rest));\n })() : [];\n\n return go(tuples);\n };\n\n\n // indentLevelsFromLines :: [String] -> [(Int, String)]\n const indentLevelsFromLines = xs => {\n const\n pairs = xs.map(\n x => bimap(length)(cs => cs.join(\"\"))(\n span(isSpace)(list(x))\n )\n ),\n indentUnit = pairs.reduce(\n (a, tpl) => {\n const i = tpl[0];\n\n return 0 < i ? (\n i < a ? i : a\n ) : a;\n },\n Infinity\n );\n\n return [Infinity, 0].includes(indentUnit) ? (\n pairs\n ) : pairs.map(first(n => n / indentUnit));\n };\n\n // ------------ TREE PADDED TO EVEN DEPTH ------------\n\n // paddedTree :: a -> Tree a -> Int -> Tree a\n const paddedTree = padValue =>\n // All descendants expanded to same depth\n // with empty nodes where needed.\n node => depth => {\n const go = n => tree =>\n 1 < n ? (() => {\n const children = nest(tree);\n\n return Node(root(tree))(\n (\n 0 < children.length ? (\n children\n ) : [Node(padValue)([])]\n ).map(go(n - 1))\n );\n })() : tree;\n\n return go(depth)(node);\n };\n\n // treeDepth :: Tree a -> Int\n const treeDepth = tree =>\n foldTree(\n () => xs => 0 < xs.length ? (\n 1 + maximum(xs)\n ) : 1\n )(tree);\n\n // ------------- SUBTREE WIDTHS MEASURED -------------\n\n // widthLabelledTree :: Tree a -> Tree (a, Int)\n const widthLabelledTree = tree =>\n // A tree in which each node is labelled with\n // the width of its own subtree.\n foldTree(x => xs =>\n 0 < xs.length ? (\n Node(Tuple(x)(\n xs.reduce(\n (a, node) => a + snd(root(node)),\n 0\n )\n ))(xs)\n ) : Node(Tuple(x)(1))([])\n )(tree);\n\n // -------------- COLOR SWATCH APPLIED ---------------\n\n // paintedTree :: [String] -> Tree a -> Tree (String, a)\n const paintedTree = colorSwatch =>\n tree => 0 < colorSwatch.length ? (\n Node(\n Tuple(colorSwatch[0])(root(tree))\n )(\n zipWith(compose(fmapTree, Tuple))(\n cycle(colorSwatch.slice(1))\n )(\n nest(tree)\n )\n )\n ) : fmapTree(Tuple(\"\"))(tree);\n\n // --------------- WIKITABLE RENDERED ----------------\n\n // wikiTableFromRows ::\n // [[(String, (String, Int))]] -> String\n const wikiTableFromRows = rows => {\n const\n cw = color => width => {\n const go = w =>\n 1 < w ? (\n `colspan=${w} `\n ) : \"\";\n\n return `style=\"background:${color}; \"` + (\n ` ${go(width)}`\n );\n },\n cellText = ctw => {\n const [color, tw] = Array.from(ctw);\n const [txt, width] = Array.from(tw);\n\n return 0 < txt.length ? (\n `| ${cw(color)(width)}| ${txt}`\n ) : \"| |\";\n },\n classText = \"class=\\\"wikitable\\\"\",\n styleText = \"style=\\\"text-align:center;\\\"\",\n header = `{| ${classText} ${styleText}\\n|-`,\n tableBody = rows.map(\n cells => cells.map(cellText).join(\"\\n\")\n ).join(\"\\n|-\\n\");\n\n return `${header}\\n${tableBody}\\n|}`;\n };\n\n // ------------------ GENERIC TREES ------------------\n\n // Node :: a -> [Tree a] -> Tree a\n const Node = v =>\n // Constructor for a Tree node which connects a\n // value of some kind to a list of zero or\n // more child trees.\n xs => ({\n type: \"Node\",\n root: v,\n nest: xs || []\n });\n\n\n // fmapTree :: (a -> b) -> Tree a -> Tree b\n const fmapTree = f => {\n // A new tree. The result of a\n // structure-preserving application of f\n // to each root in the existing tree.\n const go = t => Node(\n f(t.root)\n )(\n t.nest.map(go)\n );\n\n return go;\n };\n\n\n // foldTree :: (a -> [b] -> b) -> Tree a -> b\n const foldTree = f => {\n // The catamorphism on trees. A summary\n // value obtained by a depth-first fold.\n const go = tree => f(\n root(tree)\n )(\n nest(tree).map(go)\n );\n\n return go;\n };\n\n\n // levels :: Tree a -> [[a]]\n const levels = tree => {\n // A list of lists, grouping the root\n // values of each level of the tree.\n const go = (a, node) => {\n const [h, ...t] = 0 < a.length ? (\n a\n ) : [\n [],\n []\n ];\n\n return [\n [node.root, ...h],\n ...node.nest.slice(0)\n .reverse()\n .reduce(go, t)\n ];\n };\n\n return go([], tree);\n };\n\n\n // nest :: Tree a -> [a]\n const nest = tree => {\n // Allowing for lazy (on-demand) evaluation.\n // If the nest turns out to be a function \u2013\n // rather than a list \u2013 that function is applied\n // here to the root, and returns a list.\n const xs = tree.nest;\n\n return \"function\" !== typeof xs ? (\n xs\n ) : xs(root(tree));\n };\n\n\n // root :: Tree a -> a\n const root = tree =>\n // The value attached to a tree node.\n tree.root;\n\n // --------------------- GENERIC ---------------------\n\n // Just :: a -> Maybe a\n const Just = x => ({\n type: \"Maybe\",\n Nothing: false,\n Just: x\n });\n\n\n // Nothing :: Maybe a\n const Nothing = () => ({\n type: \"Maybe\",\n Nothing: true\n });\n\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = a =>\n b => ({\n type: \"Tuple\",\n \"0\": a,\n \"1\": b,\n length: 2\n });\n\n\n // apFn :: (a -> b -> c) -> (a -> b) -> (a -> c)\n const ap = f =>\n // Applicative instance for functions.\n // f(x) applied to g(x).\n g => x => f(x)(\n g(x)\n );\n\n\n // bimap :: (a -> b) -> (c -> d) -> (a, c) -> (b, d)\n const bimap = f =>\n // Tuple instance of bimap.\n // A tuple of the application of f and g to the\n // first and second values respectively.\n g => tpl => Tuple(f(tpl[0]))(\n g(tpl[1])\n );\n\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (...fs) =>\n // A function defined by the right-to-left\n // composition of all the functions in fs.\n fs.reduce(\n (f, g) => x => f(g(x)),\n x => x\n );\n\n\n // cycle :: [a] -> Generator [a]\n const cycle = function* (xs) {\n // An infinite repetition of xs,\n // from which an arbitrary prefix\n // may be taken.\n const lng = xs.length;\n let i = 0;\n\n while (true) {\n yield xs[i];\n i = (1 + i) % lng;\n }\n };\n\n\n // first :: (a -> b) -> ((a, c) -> (b, c))\n const first = f =>\n // A simple function lifted to one which applies\n // to a tuple, transforming only its first item.\n xy => {\n const tpl = Tuple(f(xy[0]))(xy[1]);\n\n return Array.isArray(xy) ? (\n Array.from(tpl)\n ) : tpl;\n };\n\n\n // fst :: (a, b) -> a\n const fst = tpl =>\n // First member of a pair.\n tpl[0];\n\n\n // isSpace :: Char -> Bool\n const isSpace = c =>\n // True if c is a white space character.\n (/\\s/u).test(c);\n\n\n // length :: [a] -> Int\n const length = xs =>\n // Returns Infinity over objects without finite\n // length. This enables zip and zipWith to choose\n // the shorter argument when one is non-finite,\n // like cycle, repeat etc\n \"GeneratorFunction\" !== xs.constructor\n .constructor.name ? (\n xs.length\n ) : Infinity;\n\n\n // lines :: String -> [String]\n const lines = s =>\n // A list of strings derived from a single\n // string delimited by newline and or CR.\n 0 < s.length ? (\n s.split(/[\\r\\n]+/u)\n ) : [];\n\n\n // list :: StringOrArrayLike b => b -> [a]\n const list = xs =>\n // xs itself, if it is an Array,\n // or an Array derived from xs.\n Array.isArray(xs) ? (\n xs\n ) : Array.from(xs || []);\n\n\n // lt (<) :: Ord a => a -> a -> Bool\n const lt = a =>\n b => a < b;\n\n\n // maximum :: Ord a => [a] -> a\n const maximum = xs => (\n // The largest value in a non-empty list.\n ys => 0 < ys.length ? (\n ys.slice(1).reduce(\n (a, y) => y > a ? (\n y\n ) : a, ys[0]\n )\n ) : undefined\n )(list(xs));\n\n\n // snd :: (a, b) -> b\n const snd = tpl =>\n // Second member of a pair.\n tpl[1];\n\n\n // span :: (a -> Bool) -> [a] -> ([a], [a])\n const span = p =>\n // Longest prefix of xs consisting of elements which\n // all satisfy p, tupled with the remainder of xs.\n xs => {\n const i = xs.findIndex(x => !p(x));\n\n return -1 !== i ? (\n Tuple(xs.slice(0, i))(\n xs.slice(i)\n )\n ) : Tuple(xs)([]);\n };\n\n\n // tail :: [a] -> [a]\n const tail = xs =>\n // A new list consisting of all\n // items of xs except the first.\n \"GeneratorFunction\" !== xs.constructor\n .constructor.name ? (\n (ys => 0 < ys.length ? ys.slice(1) : [])(\n xs\n )\n ) : (take(1)(xs), xs);\n\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n =>\n // The first n elements of a list,\n // string of characters, or stream.\n xs => \"GeneratorFunction\" !== xs\n .constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat(...Array.from({\n length: n\n }, () => {\n const x = xs.next();\n\n return x.done ? [] : [x.value];\n }));\n\n\n // uncons :: [a] -> Maybe (a, [a])\n const uncons = xs => {\n // Just a tuple of the head of xs and its tail,\n // Or Nothing if xs is an empty list.\n const lng = length(xs);\n\n return (0 < lng) ? (\n Infinity > lng ? (\n // Finite list\n Just(Tuple(xs[0])(xs.slice(1)))\n ) : (() => {\n // Lazy generator\n const nxt = take(1)(xs);\n\n return 0 < nxt.length ? (\n Just(Tuple(nxt[0])(xs))\n ) : Nothing();\n })()\n ) : Nothing();\n };\n\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = f =>\n // A list with the length of the shorter of\n // xs and ys, defined by zipping with a\n // custom function, rather than with the\n // default tuple constructor.\n xs => ys => {\n const n = Math.min(length(xs), length(ys));\n\n return Infinity > n ? (\n (([as, bs]) => Array.from({\n length: n\n }, (_, i) => f(as[i])(\n bs[i]\n )))([xs, ys].map(\n take(n)\n ))\n ) : zipWithGen(f)(xs)(ys);\n };\n\n\n // zipWithGen :: (a -> b -> c) ->\n // Gen [a] -> Gen [b] -> Gen [c]\n const zipWithGen = f => ga => gb => {\n const go = function* (ma, mb) {\n let\n a = ma,\n b = mb;\n\n while (!a.Nothing && !b.Nothing) {\n const\n ta = a.Just,\n tb = b.Just;\n\n yield f(fst(ta))(fst(tb));\n a = uncons(snd(ta));\n b = uncons(snd(tb));\n }\n };\n\n return go(uncons(ga), uncons(gb));\n };\n\n // MAIN ---\n return main();\n})();"} +{"title": "Display an outline as a nested table", "language": "Python", "task": "{| class=\"wikitable\" style=\"text-align: center;\"\n|-\n| style=\"background: #ffffe6; \" colspan=7 | Display an outline as a nested table.\n|-\n| style=\"background: #ffebd2; \" colspan=3 | Parse the outline to a tree,\n| style=\"background: #f0fff0; \" colspan=2 | count the leaves descending from each node,\n| style=\"background: #e6ffff; \" colspan=2 | and write out a table with 'colspan' values\n|-\n| style=\"background: #ffebd2; \" | measuring the indent of each line,\n| style=\"background: #ffebd2; \" | translating the indentation to a nested structure,\n| style=\"background: #ffebd2; \" | and padding the tree to even depth.\n| style=\"background: #f0fff0; \" | defining the width of a leaf as 1,\n| style=\"background: #f0fff0; \" | and the width of a parent node as a sum.\n| style=\"background: #e6ffff; \" | either as a wiki table,\n| style=\"background: #e6ffff; \" | or as HTML.\n|-\n| | \n| | \n| | \n| | \n| style=\"background: #f0fff0; \" | (The sum of the widths of its children)\n| | \n| | \n|}\n\nThe graphic representation of outlines is a staple of mind-mapping and the planning of papers, reports, and speeches.\n\n;Task:\nGiven a outline with at least 3 levels of indentation, for example:\n\nDisplay an outline as a nested table.\n Parse the outline to a tree,\n measuring the indent of each line,\n translating the indentation to a nested structure,\n and padding the tree to even depth.\n count the leaves descending from each node,\n defining the width of a leaf as 1,\n and the width of a parent node as a sum.\n (The sum of the widths of its children)\n and write out a table with 'colspan' values\n either as a wiki table,\n or as HTML.\n\nwrite a program in your language which translates your outline into a nested table, with WikiTable or HTML colspan values attached (where needed) to parent nodes in the nested table.\n\nThe WikiTable at the top of this page was generated from the indented outline shown above, producing the following markup string:\n\n{| class=\"wikitable\" style=\"text-align: center;\"\n|-\n| style=\"background: #ffffe6; \" colspan=7 | Display an outline as a nested table.\n|-\n| style=\"background: #ffebd2; \" colspan=3 | Parse the outline to a tree,\n| style=\"background: #f0fff0; \" colspan=2 | count the leaves descending from each node,\n| style=\"background: #e6ffff; \" colspan=2 | and write out a table with 'colspan' values\n|-\n| style=\"background: #ffebd2; \" | measuring the indent of each line,\n| style=\"background: #ffebd2; \" | translating the indentation to a nested structure,\n| style=\"background: #ffebd2; \" | and padding the tree to even depth.\n| style=\"background: #f0fff0; \" | defining the width of a leaf as 1,\n| style=\"background: #f0fff0; \" | and the width of a parent node as a sum.\n| style=\"background: #e6ffff; \" | either as a wiki table,\n| style=\"background: #e6ffff; \" | or as HTML.\n|-\n| | \n| | \n| | \n| | \n| style=\"background: #f0fff0; \" | (The sum of the widths of its children)\n| | \n| | \n|}\n\n;Extra credit:\nUse background color to distinguish the main stages of your outline, so that the subtree of each node at level two is consistently colored, and the edges between adjacent subtrees are immediately revealed.\n\n\n;Output:\nDisplay your nested table on this page.\n\n", "solution": "\"\"\"Display an outline as a nested table. Requires Python >=3.6.\"\"\"\n\nimport itertools\nimport re\nimport sys\n\nfrom collections import deque\nfrom typing import NamedTuple\n\n\nRE_OUTLINE = re.compile(r\"^((?: |\\t)*)(.+)$\", re.M)\n\nCOLORS = itertools.cycle(\n [\n \"#ffffe6\",\n \"#ffebd2\",\n \"#f0fff0\",\n \"#e6ffff\",\n \"#ffeeff\",\n ]\n)\n\n\nclass Node:\n def __init__(self, indent, value, parent, children=None):\n self.indent = indent\n self.value = value\n self.parent = parent\n self.children = children or []\n\n self.color = None\n\n def depth(self):\n if self.parent:\n return self.parent.depth() + 1\n return -1\n\n def height(self):\n \"\"\"Height of the subtree rooted at this node.\"\"\"\n if not self.children:\n return 0\n return max(child.height() for child in self.children) + 1\n\n def colspan(self):\n if self.leaf:\n return 1\n return sum(child.colspan() for child in self.children)\n\n @property\n def leaf(self):\n return not bool(self.children)\n\n def __iter__(self):\n # Level order tree traversal.\n q = deque()\n q.append(self)\n while q:\n node = q.popleft()\n yield node\n q.extend(node.children)\n\n\nclass Token(NamedTuple):\n indent: int\n value: str\n\n\ndef tokenize(outline):\n \"\"\"Generate ``Token``s from the given outline.\"\"\"\n for match in RE_OUTLINE.finditer(outline):\n indent, value = match.groups()\n yield Token(len(indent), value)\n\n\ndef parse(outline):\n \"\"\"Return the given outline as a tree of ``Node``s.\"\"\"\n # Split the outline into lines and count the level of indentation.\n tokens = list(tokenize(outline))\n\n # Parse the tokens into a tree of nodes.\n temp_root = Node(-1, \"\", None)\n _parse(tokens, 0, temp_root)\n\n # Pad the tree so that all branches have the same depth.\n root = temp_root.children[0]\n pad_tree(root, root.height())\n\n return root\n\n\ndef _parse(tokens, index, node):\n \"\"\"Recursively build a tree of nodes.\n\n Args:\n tokens (list): A collection of ``Token``s.\n index (int): Index of the current token.\n node (Node): Potential parent or sibling node.\n \"\"\"\n # Base case. No more lines.\n if index >= len(tokens):\n return\n\n token = tokens[index]\n\n if token.indent == node.indent:\n # A sibling of node\n current = Node(token.indent, token.value, node.parent)\n node.parent.children.append(current)\n _parse(tokens, index + 1, current)\n\n elif token.indent > node.indent:\n # A child of node\n current = Node(token.indent, token.value, node)\n node.children.append(current)\n _parse(tokens, index + 1, current)\n\n elif token.indent < node.indent:\n # Try the node's parent until we find a sibling.\n _parse(tokens, index, node.parent)\n\n\ndef pad_tree(node, height):\n \"\"\"Pad the tree with blank nodes so all branches have the same depth.\"\"\"\n if node.leaf and node.depth() < height:\n pad_node = Node(node.indent + 1, \"\", node)\n node.children.append(pad_node)\n\n for child in node.children:\n pad_tree(child, height)\n\n\ndef color_tree(node):\n \"\"\"Walk the tree and color each node as we go.\"\"\"\n if not node.value:\n node.color = \"#F9F9F9\"\n elif node.depth() <= 1:\n node.color = next(COLORS)\n else:\n node.color = node.parent.color\n\n for child in node.children:\n color_tree(child)\n\n\ndef table_data(node):\n \"\"\"Return an HTML table data element for the given node.\"\"\"\n indent = \" \"\n\n if node.colspan() > 1:\n colspan = f'colspan=\"{node.colspan()}\"'\n else:\n colspan = \"\"\n\n if node.color:\n style = f'style=\"background-color: {node.color};\"'\n else:\n style = \"\"\n\n attrs = \" \".join([colspan, style])\n return f\"{indent}{node.value}\"\n\n\ndef html_table(tree):\n \"\"\"Return the tree as an HTML table.\"\"\"\n # Number of columns in the table.\n table_cols = tree.colspan()\n\n # Running count of columns in the current row.\n row_cols = 0\n\n # HTML buffer\n buf = [\"\"]\n\n # Breadth first iteration.\n for node in tree:\n if row_cols == 0:\n buf.append(\" \")\n\n buf.append(table_data(node))\n row_cols += node.colspan()\n\n if row_cols == table_cols:\n buf.append(\" \")\n row_cols = 0\n\n buf.append(\"\")\n return \"\\n\".join(buf)\n\n\ndef wiki_table_data(node):\n \"\"\"Return an wiki table data string for the given node.\"\"\"\n if not node.value:\n return \"| |\"\n\n if node.colspan() > 1:\n colspan = f\"colspan={node.colspan()}\"\n else:\n colspan = \"\"\n\n if node.color:\n style = f'style=\"background: {node.color};\"'\n else:\n style = \"\"\n\n attrs = \" \".join([colspan, style])\n return f\"| {attrs} | {node.value}\"\n\n\ndef wiki_table(tree):\n \"\"\"Return the tree as a wiki table.\"\"\"\n # Number of columns in the table.\n table_cols = tree.colspan()\n\n # Running count of columns in the current row.\n row_cols = 0\n\n # HTML buffer\n buf = ['{| class=\"wikitable\" style=\"text-align: center;\"']\n\n for node in tree:\n if row_cols == 0:\n buf.append(\"|-\")\n\n buf.append(wiki_table_data(node))\n row_cols += node.colspan()\n\n if row_cols == table_cols:\n row_cols = 0\n\n buf.append(\"|}\")\n return \"\\n\".join(buf)\n\n\ndef example(table_format=\"wiki\"):\n \"\"\"Write an example table to stdout in either HTML or Wiki format.\"\"\"\n\n outline = (\n \"Display an outline as a nested table.\\n\"\n \" Parse the outline to a tree,\\n\"\n \" measuring the indent of each line,\\n\"\n \" translating the indentation to a nested structure,\\n\"\n \" and padding the tree to even depth.\\n\"\n \" count the leaves descending from each node,\\n\"\n \" defining the width of a leaf as 1,\\n\"\n \" and the width of a parent node as a sum.\\n\"\n \" (The sum of the widths of its children)\\n\"\n \" and write out a table with 'colspan' values\\n\"\n \" either as a wiki table,\\n\"\n \" or as HTML.\"\n )\n\n tree = parse(outline)\n color_tree(tree)\n\n if table_format == \"wiki\":\n print(wiki_table(tree))\n else:\n print(html_table(tree))\n\n\nif __name__ == \"__main__\":\n args = sys.argv[1:]\n\n if len(args) == 1:\n table_format = args[0]\n else:\n table_format = \"wiki\"\n\n example(table_format)"} +{"title": "Distance and Bearing", "language": "Python", "task": "It is very important in aviation to have knowledge of the nearby airports at any time in flight. \n;Task:\nDetermine the distance and bearing from an Airplane to the 20 nearest Airports whenever requested.\nUse the non-commercial data from openflights.org [https://raw.githubusercontent.com/jpatokal/openflights/master/data/airports.dat airports.dat] as reference.\n\n\nA request comes from an airplane at position ( latitude, longitude ): ( '''51.514669, 2.198581''' ).\n\n\nYour report should contain the following information from table airports.dat (column shown in brackets):\n\nName(2), Country(4), ICAO(6), Distance and Bearing calculated from Latitude(7) and Longitude(8). \n\n\nDistance is measured in nautical miles (NM). Resolution is 0.1 NM.\n\nBearing is measured in degrees (\u00b0). 0\u00b0 = 360\u00b0 = north then clockwise 90\u00b0 = east, 180\u00b0 = south, 270\u00b0 = west. Resolution is 1\u00b0.\n \n\n;See:\n:* \u00a0 openflights.org/data: \u00a0[https://openflights.org/data.html Airport, airline and route data]\n:* \u00a0 Movable Type Scripts: \u00a0[https://www.movable-type.co.uk/scripts/latlong.html Calculate distance, bearing and more between Latitude/Longitude points]\n\n", "solution": "''' Rosetta Code task Distance_and_Bearing '''\n\nfrom math import radians, degrees, sin, cos, asin, atan2, sqrt\nfrom pandas import read_csv\n\n\nEARTH_RADIUS_KM = 6372.8\nTASK_CONVERT_NM = 0.0094174\nAIRPORT_DATA_FILE = 'airports.dat.txt'\n\nQUERY_LATITUDE, QUERY_LONGITUDE = 51.514669, 2.198581\n\n\ndef haversine(lat1, lon1, lat2, lon2):\n '''\n Given two latitude, longitude pairs in degrees for two points on the Earth,\n get distance (nautical miles) and initial direction of travel (degrees)\n for travel from lat1, lon1 to lat2, lon2\n '''\n rlat1, rlon1, rlat2, rlon2 = [radians(x) for x in [lat1, lon1, lat2, lon2]]\n dlat = rlat2 - rlat1\n dlon = rlon2 - rlon1\n arc = sin(dlat / 2) ** 2 + cos(rlat1) * cos(rlat2) * sin(dlon / 2) ** 2\n clen = 2.0 * degrees(asin(sqrt(arc)))\n theta = atan2(sin(dlon) * cos(rlat2),\n cos(rlat1) * sin(rlat2) - sin(rlat1) * cos(rlat2) * cos(dlon))\n theta = (degrees(theta) + 360) % 360\n return EARTH_RADIUS_KM * clen * TASK_CONVERT_NM, theta\n\n\ndef find_nearest_airports(latitude, longitude, wanted=20, csv=AIRPORT_DATA_FILE):\n ''' Given latitude and longitude, find `wanted` closest airports in database file csv. '''\n airports = read_csv(csv, header=None, usecols=[1, 3, 5, 6, 7], names=[\n 'Name', 'Country', 'ICAO', 'Latitude', 'Longitude'])\n airports['Distance'] = 0.0\n airports['Bearing'] = 0\n for (idx, row) in enumerate(airports.itertuples()):\n distance, bearing = haversine(\n latitude, longitude, row.Latitude, row.Longitude)\n airports.at[idx, 'Distance'] = round(distance, ndigits=1)\n airports.at[idx, 'Bearing'] = int(round(bearing))\n\n airports.sort_values(by=['Distance'], ignore_index=True, inplace=True)\n return airports.loc[0:wanted-1, ['Name', 'Country', 'ICAO', 'Distance', 'Bearing']]\n\n\nprint(find_nearest_airports(QUERY_LATITUDE, QUERY_LONGITUDE))\n"} +{"title": "Diversity prediction theorem", "language": "C", "task": "The \u00a0 ''wisdom of the crowd'' \u00a0 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, \u00a0 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, \u00a0 when the diversity in a group is large, \u00a0 the error of the crowd is small.\n\n\n;Definitions:\n::* \u00a0 Average Individual Error: \u00a0 Average of the individual squared errors\n::* \u00a0 Collective Error: \u00a0 Squared error of the collective prediction\n::* \u00a0 Prediction Diversity: \u00a0 Average squared distance from the individual predictions to the collective prediction\n::* \u00a0 Diversity Prediction Theorem: \u00a0 ''Given a crowd of predictive models'', \u00a0 \u00a0 then\n:::::: \u00a0 Collective Error \u00a0 = \u00a0 Average Individual Error \u00a0 \u2500 \u00a0 Prediction Diversity\n\n;Task:\nFor a given \u00a0 true \u00a0 value and a number of number of estimates (from a crowd), \u00a0 show \u00a0 (here on this page):\n:::* \u00a0 the true value \u00a0 and \u00a0 the crowd estimates\n:::* \u00a0 the average error\n:::* \u00a0 the crowd error\n:::* \u00a0 the prediction diversity\n\n\nUse \u00a0 (at least) \u00a0 these two examples:\n:::* \u00a0 a true value of \u00a0 '''49''' \u00a0 with crowd estimates of: \u00a0 ''' 48 \u00a0 47 \u00a0 51'''\n:::* \u00a0 a true value of \u00a0 '''49''' \u00a0 with crowd estimates of: \u00a0 ''' 48 \u00a0 47 \u00a0 51 \u00a0 42'''\n\n\n\n;Also see:\n:* \u00a0 Wikipedia entry: \u00a0 [https://en.wikipedia.org/wiki/Wisdom_of_the_crowd Wisdom of the crowd]\n:* \u00a0 University of Michigan: [https://web.archive.org/web/20060830201235/http://www.cscs.umich.edu/~spage/teaching_files/modeling_lectures/MODEL5/M18predictnotes.pdf PDF paper] \u00a0 \u00a0 \u00a0 \u00a0 (exists on a web archive, \u00a0 the ''Wayback Machine'').\n\n", "solution": "\n\n#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": "Diversity prediction theorem", "language": "JavaScript", "task": "The \u00a0 ''wisdom of the crowd'' \u00a0 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, \u00a0 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, \u00a0 when the diversity in a group is large, \u00a0 the error of the crowd is small.\n\n\n;Definitions:\n::* \u00a0 Average Individual Error: \u00a0 Average of the individual squared errors\n::* \u00a0 Collective Error: \u00a0 Squared error of the collective prediction\n::* \u00a0 Prediction Diversity: \u00a0 Average squared distance from the individual predictions to the collective prediction\n::* \u00a0 Diversity Prediction Theorem: \u00a0 ''Given a crowd of predictive models'', \u00a0 \u00a0 then\n:::::: \u00a0 Collective Error \u00a0 = \u00a0 Average Individual Error \u00a0 \u2500 \u00a0 Prediction Diversity\n\n;Task:\nFor a given \u00a0 true \u00a0 value and a number of number of estimates (from a crowd), \u00a0 show \u00a0 (here on this page):\n:::* \u00a0 the true value \u00a0 and \u00a0 the crowd estimates\n:::* \u00a0 the average error\n:::* \u00a0 the crowd error\n:::* \u00a0 the prediction diversity\n\n\nUse \u00a0 (at least) \u00a0 these two examples:\n:::* \u00a0 a true value of \u00a0 '''49''' \u00a0 with crowd estimates of: \u00a0 ''' 48 \u00a0 47 \u00a0 51'''\n:::* \u00a0 a true value of \u00a0 '''49''' \u00a0 with crowd estimates of: \u00a0 ''' 48 \u00a0 47 \u00a0 51 \u00a0 42'''\n\n\n\n;Also see:\n:* \u00a0 Wikipedia entry: \u00a0 [https://en.wikipedia.org/wiki/Wisdom_of_the_crowd Wisdom of the crowd]\n:* \u00a0 University of Michigan: [https://web.archive.org/web/20060830201235/http://www.cscs.umich.edu/~spage/teaching_files/modeling_lectures/MODEL5/M18predictnotes.pdf PDF paper] \u00a0 \u00a0 \u00a0 \u00a0 (exists on a web archive, \u00a0 the ''Wayback Machine'').\n\n", "solution": "'use strict';\n\nfunction sum(array) {\n return array.reduce(function (a, b) {\n return a + b;\n });\n}\n\nfunction square(x) {\n return x * x;\n}\n\nfunction mean(array) {\n return sum(array) / array.length;\n}\n\nfunction averageSquareDiff(a, predictions) {\n return mean(predictions.map(function (x) {\n return square(x - a);\n }));\n}\n\nfunction diversityTheorem(truth, predictions) {\n var average = mean(predictions);\n return {\n 'average-error': averageSquareDiff(truth, predictions),\n 'crowd-error': square(truth - average),\n 'diversity': averageSquareDiff(average, predictions)\n };\n}\n\nconsole.log(diversityTheorem(49, [48,47,51]))\nconsole.log(diversityTheorem(49, [48,47,51,42]))\n"} +{"title": "Diversity prediction theorem", "language": "Python 3.7", "task": "The \u00a0 ''wisdom of the crowd'' \u00a0 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, \u00a0 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, \u00a0 when the diversity in a group is large, \u00a0 the error of the crowd is small.\n\n\n;Definitions:\n::* \u00a0 Average Individual Error: \u00a0 Average of the individual squared errors\n::* \u00a0 Collective Error: \u00a0 Squared error of the collective prediction\n::* \u00a0 Prediction Diversity: \u00a0 Average squared distance from the individual predictions to the collective prediction\n::* \u00a0 Diversity Prediction Theorem: \u00a0 ''Given a crowd of predictive models'', \u00a0 \u00a0 then\n:::::: \u00a0 Collective Error \u00a0 = \u00a0 Average Individual Error \u00a0 \u2500 \u00a0 Prediction Diversity\n\n;Task:\nFor a given \u00a0 true \u00a0 value and a number of number of estimates (from a crowd), \u00a0 show \u00a0 (here on this page):\n:::* \u00a0 the true value \u00a0 and \u00a0 the crowd estimates\n:::* \u00a0 the average error\n:::* \u00a0 the crowd error\n:::* \u00a0 the prediction diversity\n\n\nUse \u00a0 (at least) \u00a0 these two examples:\n:::* \u00a0 a true value of \u00a0 '''49''' \u00a0 with crowd estimates of: \u00a0 ''' 48 \u00a0 47 \u00a0 51'''\n:::* \u00a0 a true value of \u00a0 '''49''' \u00a0 with crowd estimates of: \u00a0 ''' 48 \u00a0 47 \u00a0 51 \u00a0 42'''\n\n\n\n;Also see:\n:* \u00a0 Wikipedia entry: \u00a0 [https://en.wikipedia.org/wiki/Wisdom_of_the_crowd Wisdom of the crowd]\n:* \u00a0 University of Michigan: [https://web.archive.org/web/20060830201235/http://www.cscs.umich.edu/~spage/teaching_files/modeling_lectures/MODEL5/M18predictnotes.pdf PDF paper] \u00a0 \u00a0 \u00a0 \u00a0 (exists on a web archive, \u00a0 the ''Wayback Machine'').\n\n", "solution": "'''Diversity prediction theorem'''\n\nfrom itertools import chain\nfrom functools import reduce\n\n\n# diversityValues :: Num a => a -> [a] ->\n# { mean-Error :: a, crowd-error :: a, diversity :: a }\ndef diversityValues(x):\n '''The mean error, crowd error and\n diversity, for a given observation x\n and a non-empty list of predictions ps.\n '''\n def go(ps):\n mp = mean(ps)\n return {\n 'mean-error': meanErrorSquared(x)(ps),\n 'crowd-error': pow(x - mp, 2),\n 'diversity': meanErrorSquared(mp)(ps)\n }\n return go\n\n\n# meanErrorSquared :: Num -> [Num] -> Num\ndef meanErrorSquared(x):\n '''The mean of the squared differences\n between the observed value x and\n a non-empty list of predictions ps.\n '''\n def go(ps):\n return mean([\n pow(p - x, 2) for p in ps\n ])\n return go\n\n\n# ------------------------- TEST -------------------------\n# main :: IO ()\ndef main():\n '''Observed value: 49,\n prediction lists: various.\n '''\n\n print(unlines(map(\n showDiversityValues(49),\n [\n [48, 47, 51],\n [48, 47, 51, 42],\n [50, '?', 50, {}, 50], # Non-numeric values.\n [] # Missing predictions.\n ]\n )))\n print(unlines(map(\n showDiversityValues('49'), # String in place of number.\n [\n [50, 50, 50],\n [40, 35, 40],\n ]\n )))\n\n\n# ---------------------- FORMATTING ----------------------\n\n# showDiversityValues :: Num -> [Num] -> Either String String\ndef showDiversityValues(x):\n '''Formatted string representation\n of diversity values for a given\n observation x and a non-empty\n list of predictions p.\n '''\n def go(ps):\n def showDict(dct):\n w = 4 + max(map(len, dct.keys()))\n\n def showKV(a, kv):\n k, v = kv\n return a + k.rjust(w, ' ') + (\n ' : ' + showPrecision(3)(v) + '\\n'\n )\n return 'Predictions: ' + showList(ps) + ' ->\\n' + (\n reduce(showKV, dct.items(), '')\n )\n\n def showProblem(e):\n return (\n unlines(map(indented(1), e)) if (\n isinstance(e, list)\n ) else indented(1)(repr(e))\n ) + '\\n'\n\n return 'Observation: ' + repr(x) + '\\n' + (\n either(showProblem)(showDict)(\n bindLR(numLR(x))(\n lambda n: bindLR(numsLR(ps))(\n compose(Right, diversityValues(n))\n )\n )\n )\n )\n return go\n\n\n# ------------------ GENERIC FUNCTIONS -------------------\n\n# Left :: a -> Either a b\ndef Left(x):\n '''Constructor for an empty Either (option type) value\n with an associated string.\n '''\n return {'type': 'Either', 'Right': None, 'Left': x}\n\n\n# Right :: b -> Either a b\ndef Right(x):\n '''Constructor for a populated Either (option type) value'''\n return {'type': 'Either', 'Left': None, 'Right': x}\n\n\n# bindLR (>>=) :: Either a -> (a -> Either b) -> Either b\ndef bindLR(m):\n '''Either monad injection operator.\n Two computations sequentially composed,\n with any value produced by the first\n passed as an argument to the second.\n '''\n def go(mf):\n return (\n mf(m.get('Right')) if None is m.get('Left') else m\n )\n return go\n\n\n# compose :: ((a -> a), ...) -> (a -> a)\ndef compose(*fs):\n '''Composition, from right to left,\n of a series of functions.\n '''\n def go(f, g):\n def fg(x):\n return f(g(x))\n return fg\n return reduce(go, fs, identity)\n\n\n# concatMap :: (a -> [b]) -> [a] -> [b]\ndef concatMap(f):\n '''A concatenated list over which a function has been mapped.\n The list monad can be derived by using a function f which\n wraps its output in a list,\n (using an empty list to represent computational failure).\n '''\n def go(xs):\n return chain.from_iterable(map(f, xs))\n return go\n\n\n# either :: (a -> c) -> (b -> c) -> Either a b -> c\ndef either(fl):\n '''The application of fl to e if e is a Left value,\n or the application of fr to e if e is a Right value.\n '''\n return lambda fr: lambda e: fl(e['Left']) if (\n None is e['Right']\n ) else fr(e['Right'])\n\n\n# identity :: a -> a\ndef identity(x):\n '''The identity function.'''\n return x\n\n\n# indented :: Int -> String -> String\ndef indented(n):\n '''String indented by n multiples\n of four spaces.\n '''\n return lambda s: (4 * ' ' * n) + s\n\n# mean :: [Num] -> Float\ndef mean(xs):\n '''Arithmetic mean of a list\n of numeric values.\n '''\n return sum(xs) / float(len(xs))\n\n\n# numLR :: a -> Either String Num\ndef numLR(x):\n '''Either Right x if x is a float or int,\n or a Left explanatory message.'''\n return Right(x) if (\n isinstance(x, (float, int))\n ) else Left(\n 'Expected number, saw: ' + (\n str(type(x)) + ' ' + repr(x)\n )\n )\n\n\n# numsLR :: [a] -> Either String [Num]\ndef numsLR(xs):\n '''Either Right xs if all xs are float or int,\n or a Left explanatory message.'''\n def go(ns):\n ls, rs = partitionEithers(map(numLR, ns))\n return Left(ls) if ls else Right(rs)\n return bindLR(\n Right(xs) if (\n bool(xs) and isinstance(xs, list)\n ) else Left(\n 'Expected a non-empty list, saw: ' + (\n str(type(xs)) + ' ' + repr(xs)\n )\n )\n )(go)\n\n\n# partitionEithers :: [Either a b] -> ([a],[b])\ndef partitionEithers(lrs):\n '''A list of Either values partitioned into a tuple\n of two lists, with all Left elements extracted\n into the first list, and Right elements\n extracted into the second list.\n '''\n def go(a, x):\n ls, rs = a\n r = x.get('Right')\n return (ls + [x.get('Left')], rs) if None is r else (\n ls, rs + [r]\n )\n return reduce(go, lrs, ([], []))\n\n\n# showList :: [a] -> String\ndef showList(xs):\n '''Compact string representation of a list'''\n return '[' + ','.join(str(x) for x in xs) + ']'\n\n\n# showPrecision :: Int -> Float -> String\ndef showPrecision(n):\n '''A string showing a floating point number\n at a given degree of precision.'''\n def go(x):\n return str(round(x, n))\n return go\n\n\n# unlines :: [String] -> String\ndef unlines(xs):\n '''A single string derived by the intercalation\n of a list of strings with the newline character.'''\n return '\\n'.join(xs)\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} +{"title": "Doomsday rule", "language": "C", "task": "[[Category:Date and time]]\n\n; 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* \u00a0 1800-01-06 (January 6, 1800)\n* \u00a0 1875-03-29 (March 29, 1875)\n* \u00a0 1915-12-07 (December 7, 1915)\n* \u00a0 1970-12-23 (December 23, 1970)\n* \u00a0 2043-05-14 (May 14, 2043)\n* \u00a0 2077-02-12 (February 12, 2077)\n* \u00a0 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* \u00a0 Doomsday rule\n* \u00a0 [https://www.archim.org.uk/eureka/archive/Eureka-36.pdf 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": "Doomsday rule", "language": "Python", "task": "[[Category:Date and time]]\n\n; 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* \u00a0 1800-01-06 (January 6, 1800)\n* \u00a0 1875-03-29 (March 29, 1875)\n* \u00a0 1915-12-07 (December 7, 1915)\n* \u00a0 1970-12-23 (December 23, 1970)\n* \u00a0 2043-05-14 (May 14, 2043)\n* \u00a0 2077-02-12 (February 12, 2077)\n* \u00a0 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* \u00a0 Doomsday rule\n* \u00a0 [https://www.archim.org.uk/eureka/archive/Eureka-36.pdf Tomorrow is the Day After Doomsday (p.28)]\n\n\n\n\n", "solution": "from datetime import date\nfrom calendar import isleap\n\ndef weekday(d):\n days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n \"Friday\", \"Saturday\"]\n dooms = [\n [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5],\n [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]\n ]\n \n c = d.year // 100\n r = d.year % 100\n s = r // 12\n t = r % 12\n c_anchor = (5 * (c % 4) + 2) % 7\n doomsday = (s + t + (t // 4) + c_anchor) % 7\n anchorday = dooms[isleap(d.year)][d.month - 1]\n weekday = (doomsday + d.day - anchorday + 7) % 7\n return days[weekday]\n\ndates = [date(*x) for x in\n [(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23),\n (2043, 5, 14), (2077, 2, 12), (2101, 4, 2)]\n]\n\nfor d in dates:\n tense = \"was\" if d < date.today() else \"is\" if d == date.today() else \"will be\"\n print(\"{} {} a {}\".format(d.strftime(\"%B %d, %Y\"), tense, weekday(d)))"} +{"title": "Dot product", "language": "C", "task": ";Task:\nCreate a function/use an in-built function, to compute the \u00a0 '''dot product''', \u00a0 also known as the \u00a0 '''scalar product''' \u00a0 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:::: \u00a0 [1, \u00a03, -5] \u00a0 \u00a0 and \n:::: \u00a0 [4, -2, -1] \n\nIf implementing the dot product of two vectors directly:\n:::* \u00a0 each vector must be the same length\n:::* \u00a0 multiply corresponding terms from each vector\n:::* \u00a0 sum the products \u00a0 (to produce the answer)\n\n\n;Related task:\n* \u00a0 [[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": "Dot product", "language": "JavaScript", "task": ";Task:\nCreate a function/use an in-built function, to compute the \u00a0 '''dot product''', \u00a0 also known as the \u00a0 '''scalar product''' \u00a0 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:::: \u00a0 [1, \u00a03, -5] \u00a0 \u00a0 and \n:::: \u00a0 [4, -2, -1] \n\nIf implementing the dot product of two vectors directly:\n:::* \u00a0 each vector must be the same length\n:::* \u00a0 multiply corresponding terms from each vector\n:::* \u00a0 sum the products \u00a0 (to produce the answer)\n\n\n;Related task:\n* \u00a0 [[Vector products]]\n\n", "solution": "(() => {\n \"use strict\";\n\n // ------------------- DOT PRODUCT -------------------\n\n // dotProduct :: [Num] -> [Num] -> Either Null Num\n const dotProduct = xs =>\n ys => xs.length === ys.length\n ? sum(zipWith(mul)(xs)(ys))\n : null;\n\n\n // ---------------------- TEST -----------------------\n\n // main :: IO ()\n const main = () =>\n dotProduct([1, 3, -5])([4, -2, -1]);\n\n\n // --------------------- GENERIC ---------------------\n\n // mul :: Num -> Num -> Num\n const mul = x =>\n y => x * y;\n\n\n // sum :: [Num] -> Num\n const sum = xs =>\n // The numeric sum of all values in xs.\n xs.reduce((a, x) => a + x, 0);\n\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = f =>\n // A list constructed by zipping with a\n // custom function, rather than with the\n // default tuple constructor.\n xs => ys => xs.map(\n (x, i) => f(x)(ys[i])\n ).slice(\n 0, Math.min(xs.length, ys.length)\n );\n\n // MAIN ---\n return main();\n})();"} +{"title": "Dot product", "language": "Python", "task": ";Task:\nCreate a function/use an in-built function, to compute the \u00a0 '''dot product''', \u00a0 also known as the \u00a0 '''scalar product''' \u00a0 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:::: \u00a0 [1, \u00a03, -5] \u00a0 \u00a0 and \n:::: \u00a0 [4, -2, -1] \n\nIf implementing the dot product of two vectors directly:\n:::* \u00a0 each vector must be the same length\n:::* \u00a0 multiply corresponding terms from each vector\n:::* \u00a0 sum the products \u00a0 (to produce the answer)\n\n\n;Related task:\n* \u00a0 [[Vector products]]\n\n", "solution": "def dotp(a,b):\n assert len(a) == len(b), 'Vector sizes must match'\n return sum(aterm * bterm for aterm,bterm in zip(a, b))\n\nif __name__ == '__main__':\n a, b = [1, 3, -5], [4, -2, -1]\n assert dotp(a,b) == 3"} +{"title": "Dot product", "language": "Python 3.7", "task": ";Task:\nCreate a function/use an in-built function, to compute the \u00a0 '''dot product''', \u00a0 also known as the \u00a0 '''scalar product''' \u00a0 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:::: \u00a0 [1, \u00a03, -5] \u00a0 \u00a0 and \n:::: \u00a0 [4, -2, -1] \n\nIf implementing the dot product of two vectors directly:\n:::* \u00a0 each vector must be the same length\n:::* \u00a0 multiply corresponding terms from each vector\n:::* \u00a0 sum the products \u00a0 (to produce the answer)\n\n\n;Related task:\n* \u00a0 [[Vector products]]\n\n", "solution": "'''Dot product'''\n\nfrom operator import (mul)\n\n\n# dotProduct :: Num a => [a] -> [a] -> Either String a\ndef dotProduct(xs):\n '''Either the dot product of xs and ys,\n or a string reporting unmatched vector sizes.\n '''\n return lambda ys: Left('vector sizes differ') if (\n len(xs) != len(ys)\n ) else Right(sum(map(mul, xs, ys)))\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Dot product of other vectors with [1, 3, -5]'''\n\n print(\n fTable(main.__doc__ + ':\\n')(str)(str)(\n compose(\n either(append('Undefined :: '))(str)\n )(dotProduct([1, 3, -5]))\n )([[4, -2, -1, 8], [4, -2], [4, 2, -1], [4, -2, -1]])\n )\n\n\n# GENERIC -------------------------------------------------\n\n# Left :: a -> Either a b\ndef Left(x):\n '''Constructor for an empty Either (option type) value\n with an associated string.\n '''\n return {'type': 'Either', 'Right': None, 'Left': x}\n\n\n# Right :: b -> Either a b\ndef Right(x):\n '''Constructor for a populated Either (option type) value'''\n return {'type': 'Either', 'Left': None, 'Right': x}\n\n\n# append (++) :: [a] -> [a] -> [a]\n# append (++) :: String -> String -> String\ndef append(xs):\n '''Two lists or strings combined into one.'''\n return lambda ys: xs + ys\n\n\n# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n '''Right to left function composition.'''\n return lambda f: lambda x: g(f(x))\n\n\n# either :: (a -> c) -> (b -> c) -> Either a b -> c\ndef either(fl):\n '''The application of fl to e if e is a Left value,\n or the application of fr to e if e is a Right value.\n '''\n return lambda fr: lambda e: fl(e['Left']) if (\n None is e['Right']\n ) else fr(e['Right'])\n\n\n# FORMATTING ----------------------------------------------\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\n '''\n def go(xShow, fxShow, f, xs):\n ys = [xShow(x) for x in xs]\n w = max(map(len, ys))\n return s + '\\n' + '\\n'.join(map(\n lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n xs, ys\n ))\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} +{"title": "Draw a clock", "language": "C", "task": "[[Category:Date and time]]\n\n;Task:\nDraw 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 clock", "language": "JavaScript", "task": "[[Category:Date and time]]\n\n;Task:\nDraw 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": "var sec_old = 0;\nfunction update_clock() {\n\tvar t = new Date();\n\tvar arms = [t.getHours(), t.getMinutes(), t.getSeconds()];\n\tif (arms[2] == sec_old) return;\n\tsec_old = arms[2];\n\n\tvar c = document.getElementById('clock');\n\tvar ctx = c.getContext('2d');\n\tctx.fillStyle = \"rgb(0,200,200)\";\n\tctx.fillRect(0, 0, c.width, c.height);\n\tctx.fillStyle = \"white\";\n\tctx.fillRect(3, 3, c.width - 6, c.height - 6);\n\tctx.lineCap = 'round';\n\n\tvar orig = { x: c.width / 2, y: c.height / 2 };\n\tarms[1] += arms[2] / 60;\n\tarms[0] += arms[1] / 60;\n\tdraw_arm(ctx, orig, arms[0] * 30, c.width/2.5 - 15, c.width / 20, \"green\");\n\tdraw_arm(ctx, orig, arms[1] * 6, c.width/2.2 - 10, c.width / 30, \"navy\");\n\tdraw_arm(ctx, orig, arms[2] * 6, c.width/2.0 - 6, c.width / 100, \"maroon\");\n}\n\nfunction draw_arm(ctx, orig, deg, len, w, style)\n{\n\tctx.save();\n\tctx.lineWidth = w;\n\tctx.lineCap = 'round';\n\tctx.translate(orig.x, orig.y);\n\tctx.rotate((deg - 90) * Math.PI / 180);\n\tctx.strokeStyle = style;\n\tctx.beginPath();\n\tctx.moveTo(-len / 10, 0);\n\tctx.lineTo(len, 0);\n\tctx.stroke();\n\tctx.restore();\n}\n\nfunction init_clock() {\n\tvar clock = document.createElement('canvas');\n\tclock.width = 100;\n\tclock.height = 100;\n\tclock.id = \"clock\";\n\tdocument.body.appendChild(clock);\n\n\twindow.setInterval(update_clock, 200);\n}"} +{"title": "Draw a clock", "language": "Python", "task": "[[Category:Date and time]]\n\n;Task:\nDraw 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": "[http://www.thinkgeek.com/gadgets/watches/6a17/ Think Geek Binary Clock]\n"} +{"title": "Draw a clock", "language": "Python 2.6+, 3.0+", "task": "[[Category:Date and time]]\n\n;Task:\nDraw 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": "import time\n\ndef chunks(l, n=5):\n return [l[i:i+n] for i in range(0, len(l), n)]\n\ndef binary(n, digits=8):\n n=int(n)\n return '{0:0{1}b}'.format(n, digits)\n\ndef secs(n):\n n=int(n)\n h='x' * n\n return \"|\".join(chunks(h))\n\ndef bin_bit(h):\n h=h.replace(\"1\",\"x\")\n h=h.replace(\"0\",\" \")\n return \"|\".join(list(h))\n\n\nx=str(time.ctime()).split()\ny=x[3].split(\":\")\n\ns=y[-1]\ny=map(binary,y[:-1])\n\nprint bin_bit(y[0])\nprint\nprint bin_bit(y[1])\nprint\nprint secs(s)"} +{"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": "\n#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 rotating cube", "language": "Python 2.7.9", "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": "from visual import *\nscene.title = \"VPython: Draw a rotating cube\"\n\nscene.range = 2\nscene.autocenter = True\n\nprint \"Drag with right mousebutton to rotate view.\"\nprint \"Drag up+down with middle mousebutton to zoom.\"\n\ndeg45 = math.radians(45.0) # 0.785398163397\n\ncube = box() # using defaults, see http://www.vpython.org/contents/docs/defaults.html \ncube.rotate( angle=deg45, axis=(1,0,0) )\ncube.rotate( angle=deg45, axis=(0,0,1) )\n\nwhile True: # Animation-loop\n rate(50)\n cube.rotate( angle=0.005, axis=(0,1,0) )\n"} +{"title": "Draw a sphere", "language": "C", "task": "[[Category:3D]]\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": "Draw a sphere", "language": "JavaScript", "task": "[[Category:3D]]\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": "\n\n\n\nDraw a sphere\n\n\n\nR=\n200\nk=\n4\nambient=\n0.2\nUnsupportive browser...\n\n"} +{"title": "Draw a sphere", "language": "Python", "task": "[[Category:3D]]\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": "import math\n\nshades = ('.',':','!','*','o','e','&','#','%','@')\n\ndef normalize(v):\n\tlen = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)\n\treturn (v[0]/len, v[1]/len, v[2]/len)\n\ndef dot(x,y):\n\td = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n\treturn -d if d < 0 else 0\n\ndef draw_sphere(r, k, ambient, light):\n\tfor i in range(int(math.floor(-r)),int(math.ceil(r)+1)):\n\t\tx = i + 0.5\n\t\tline = ''\n\n\t\tfor j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):\n\t\t\ty = j/2 + 0.5\n\t\t\tif x*x + y*y <= r*r:\n\t\t\t\tvec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))\n\t\t\t\tb = dot(light,vec)**k + ambient\n\t\t\t\tintensity = int((1-b)*(len(shades)-1))\n\t\t\t\tline += shades[intensity] if 0 <= intensity < len(shades) else shades[0]\n\t\t\telse:\n\t\t\t\tline += ' '\n\n\t\tprint(line)\n\nlight = normalize((30,30,-50))\ndraw_sphere(20,4,0.1, light)\ndraw_sphere(10,2,0.4, light)"} +{"title": "Dutch national flag problem", "language": "C", "task": "right\n\nThe Dutch national flag is composed of three coloured bands in the order:\n::* \u00a0 red \u00a0 \u00a0 (top)\n::* \u00a0 then white, \u00a0 and\n::* \u00a0 lastly blue \u00a0 (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* [https://www.google.co.uk/search?rlz=1C1DSGK_enGB472GB472&sugexp=chrome,mod=8&sourceid=chrome&ie=UTF-8&q=Dutch+national+flag+problem#hl=en&rlz=1C1DSGK_enGB472GB472&sclient=psy-ab&q=Probabilistic+analysis+of+algorithms+for+the+Dutch+national+flag+problem&oq=Probabilistic+analysis+of+algorithms+for+the+Dutch+national+flag+problem&gs_l=serp.3...60754.61818.1.62736.1.1.0.0.0.0.72.72.1.1.0...0.0.Pw3RGungndU&psj=1&bav=on.2,or.r_gc.r_pw.r_cp.r_qf.,cf.osb&fp=c33d18147f5082cc&biw=1395&bih=951 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"} +{"title": "Dutch national flag problem", "language": "Python", "task": "right\n\nThe Dutch national flag is composed of three coloured bands in the order:\n::* \u00a0 red \u00a0 \u00a0 (top)\n::* \u00a0 then white, \u00a0 and\n::* \u00a0 lastly blue \u00a0 (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* [https://www.google.co.uk/search?rlz=1C1DSGK_enGB472GB472&sugexp=chrome,mod=8&sourceid=chrome&ie=UTF-8&q=Dutch+national+flag+problem#hl=en&rlz=1C1DSGK_enGB472GB472&sclient=psy-ab&q=Probabilistic+analysis+of+algorithms+for+the+Dutch+national+flag+problem&oq=Probabilistic+analysis+of+algorithms+for+the+Dutch+national+flag+problem&gs_l=serp.3...60754.61818.1.62736.1.1.0.0.0.0.72.72.1.1.0...0.0.Pw3RGungndU&psj=1&bav=on.2,or.r_gc.r_pw.r_cp.r_qf.,cf.osb&fp=c33d18147f5082cc&biw=1395&bih=951 Probabilistic analysis of algorithms for the Dutch national flag problem] by Wei-Mei Chen. (pdf)\n\n", "solution": "import random\n\ncolours_in_order = 'Red White Blue'.split()\n\ndef dutch_flag_sort(items):\n '''\\\n In-place sort of list items using the given order.\n Python idiom is to return None when argument is modified in-place\n\n O(n)? Algorithm from Go language implementation of\n http://www.csse.monash.edu.au/~lloyd/tildeAlgDS/Sort/Flag/'''\n\n lo, mid, hi = 0, 0, len(items)-1\n while mid <= hi:\n colour = items[mid]\n if colour == 'Red':\n items[lo], items[mid] = items[mid], items[lo]\n lo += 1\n mid += 1\n elif colour == 'White':\n mid += 1\n else:\n items[mid], items[hi] = items[hi], items[mid]\n hi -= 1\n\ndef dutch_flag_check(items, order=colours_in_order):\n 'Return True if each item of items is in the given order'\n order_of_items = [order.index(item) for item in items]\n return all(x <= y for x, y in zip(order_of_items, order_of_items[1:]))\n\ndef random_balls(mx=5):\n 'Select from 1 to mx balls of each colour, randomly'\n balls = sum(([[colour] * random.randint(1, mx)\n for colour in colours_in_order]), [])\n random.shuffle(balls)\n return balls\n\ndef main():\n # Ensure we start unsorted\n while 1:\n balls = random_balls()\n if not dutch_flag_check(balls):\n break\n print(\"Original Ball order:\", balls)\n dutch_flag_sort(balls)\n print(\"Sorted Ball Order:\", balls)\n assert dutch_flag_check(balls), 'Whoops. Not sorted!'\n\nif __name__ == '__main__':\n main()"} +{"title": "EKG sequence convergence", "language": "C", "task": "The sequence is from the natural numbers and is defined by:\n* a(1) = 1; \n* a(2) = Start = 2;\n* for n > 2, a(n) shares at least one prime factor with a(n-1) and is the ''smallest'' such natural number ''not already used''.\n\nThe sequence is called the [http://oeis.org/A064740 EKG sequence] (after its visual similarity to an electrocardiogram when graphed).\n\nVariants of the sequence can be generated starting 1, N where N is any natural number larger than one. For the purposes of this task let us call: \n* The sequence described above , starting 1, 2, ... the EKG(2) sequence;\n* the sequence starting 1, 3, ... the EKG(3) sequence; \n* ... the sequence starting 1, N, ... the EKG(N) sequence.\n\n\n;Convergence\nIf an algorithm that keeps track of the minimum amount of numbers and their corresponding prime factors used to generate the next term is used, then this may be known as the generators essential '''state'''. Two EKG generators with differing starts can converge to produce the same sequence after initial differences.\nEKG(N1) and EKG(N2) are said to to have converged at and after generation a(c) if state_of(EKG(N1).a(c)) == state_of(EKG(N2).a(c)).\n\n\n;Task:\n# Calculate and show here the first 10 members of EKG(2).\n# Calculate and show here the first 10 members of EKG(5).\n# Calculate and show here the first 10 members of EKG(7).\n# Calculate and show here the first 10 members of EKG(9).\n# Calculate and show here the first 10 members of EKG(10).\n# Calculate and show here at which term EKG(5) and EKG(7) converge \u00a0 ('''stretch goal''').\n\n;Related Tasks:\n# [[Greatest common divisor]]\n# [[Sieve of Eratosthenes]]\n\n;Reference:\n* [https://www.youtube.com/watch?v=yd2jr30K2R4 The EKG Sequence and the Tree of Numbers]. (Video).\n\n", "solution": "#include \n#include \n\n#define TRUE 1\n#define FALSE 0\n#define LIMIT 100\n\ntypedef int bool;\n\nint compareInts(const void *a, const void *b) {\n int aa = *(int *)a;\n int bb = *(int *)b;\n return aa - bb;\n}\n\nbool contains(int a[], int b, size_t len) {\n int i;\n for (i = 0; i < len; ++i) {\n if (a[i] == b) return TRUE;\n }\n return FALSE;\n}\n\nint gcd(int a, int b) {\n while (a != b) {\n if (a > b)\n a -= b;\n else\n b -= a;\n }\n return a;\n}\n\nbool areSame(int s[], int t[], size_t len) {\n int i;\n qsort(s, len, sizeof(int), compareInts); \n qsort(t, len, sizeof(int), compareInts);\n for (i = 0; i < len; ++i) {\n if (s[i] != t[i]) return FALSE;\n }\n return TRUE;\n}\n\nint main() {\n int s, n, i;\n int starts[5] = {2, 5, 7, 9, 10};\n int ekg[5][LIMIT];\n for (s = 0; s < 5; ++s) {\n ekg[s][0] = 1;\n ekg[s][1] = starts[s];\n for (n = 2; n < LIMIT; ++n) {\n for (i = 2; ; ++i) {\n // a potential sequence member cannot already have been used\n // and must have a factor in common with previous member\n if (!contains(ekg[s], i, n) && gcd(ekg[s][n - 1], i) > 1) {\n ekg[s][n] = i;\n break;\n }\n }\n }\n printf(\"EKG(%2d): [\", starts[s]);\n for (i = 0; i < 30; ++i) printf(\"%d \", ekg[s][i]);\n printf(\"\\b]\\n\");\n }\n \n // now compare EKG5 and EKG7 for convergence\n for (i = 2; i < LIMIT; ++i) {\n if (ekg[1][i] == ekg[2][i] && areSame(ekg[1], ekg[2], i)) {\n printf(\"\\nEKG(5) and EKG(7) converge at term %d\\n\", i + 1);\n return 0;\n }\n }\n printf(\"\\nEKG5(5) and EKG(7) do not converge within %d terms\\n\", LIMIT);\n return 0;\n}"} +{"title": "EKG sequence convergence", "language": "Python", "task": "The sequence is from the natural numbers and is defined by:\n* a(1) = 1; \n* a(2) = Start = 2;\n* for n > 2, a(n) shares at least one prime factor with a(n-1) and is the ''smallest'' such natural number ''not already used''.\n\nThe sequence is called the [http://oeis.org/A064740 EKG sequence] (after its visual similarity to an electrocardiogram when graphed).\n\nVariants of the sequence can be generated starting 1, N where N is any natural number larger than one. For the purposes of this task let us call: \n* The sequence described above , starting 1, 2, ... the EKG(2) sequence;\n* the sequence starting 1, 3, ... the EKG(3) sequence; \n* ... the sequence starting 1, N, ... the EKG(N) sequence.\n\n\n;Convergence\nIf an algorithm that keeps track of the minimum amount of numbers and their corresponding prime factors used to generate the next term is used, then this may be known as the generators essential '''state'''. Two EKG generators with differing starts can converge to produce the same sequence after initial differences.\nEKG(N1) and EKG(N2) are said to to have converged at and after generation a(c) if state_of(EKG(N1).a(c)) == state_of(EKG(N2).a(c)).\n\n\n;Task:\n# Calculate and show here the first 10 members of EKG(2).\n# Calculate and show here the first 10 members of EKG(5).\n# Calculate and show here the first 10 members of EKG(7).\n# Calculate and show here the first 10 members of EKG(9).\n# Calculate and show here the first 10 members of EKG(10).\n# Calculate and show here at which term EKG(5) and EKG(7) converge \u00a0 ('''stretch goal''').\n\n;Related Tasks:\n# [[Greatest common divisor]]\n# [[Sieve of Eratosthenes]]\n\n;Reference:\n* [https://www.youtube.com/watch?v=yd2jr30K2R4 The EKG Sequence and the Tree of Numbers]. (Video).\n\n", "solution": "from itertools import count, islice, takewhile\nfrom math import gcd\n\ndef EKG_gen(start=2):\n \"\"\"\\\n Generate the next term of the EKG together with the minimum cache of \n numbers left in its production; (the \"state\" of the generator).\n Using math.gcd\n \"\"\"\n c = count(start + 1)\n last, so_far = start, list(range(2, start))\n yield 1, []\n yield last, []\n while True:\n for index, sf in enumerate(so_far):\n if gcd(last, sf) > 1:\n last = so_far.pop(index)\n yield last, so_far[::]\n break\n else:\n so_far.append(next(c))\n\ndef find_convergence(ekgs=(5,7)):\n \"Returns the convergence point or zero if not found within the limit\"\n ekg = [EKG_gen(n) for n in ekgs]\n for e in ekg:\n next(e) # skip initial 1 in each sequence\n return 2 + len(list(takewhile(lambda state: not all(state[0] == s for s in state[1:]),\n zip(*ekg))))\n\nif __name__ == '__main__':\n for start in 2, 5, 7, 9, 10:\n print(f\"EKG({start}):\", str([n[0] for n in islice(EKG_gen(start), 10)])[1: -1])\n print(f\"\\nEKG(5) and EKG(7) converge at term {find_convergence(ekgs=(5,7))}!\")"} +{"title": "Earliest difference between prime gaps", "language": "Python", "task": "When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that between some two adjacent primes will be a gap corresponding to every positive even integer.\n\n\n\n{|class=\"wikitable\"\n!gap!!minimalstartingprime!!endingprime\n|-\n|2||3||5\n|-\n|4||7||11\n|-\n|6||23||29\n|-\n|8||89||97\n|-\n|10||139||149\n|-\n|12||199||211\n|-\n|14||113||127\n|-\n|16||1831||1847\n|-\n|18||523||541\n|-\n|20||887||907\n|-\n|22||1129||1151\n|-\n|24||1669||1693\n|-\n|26||2477||2503\n|-\n|28||2971||2999\n|-\n|30||4297||4327\n|}\n\nThis task involves locating the minimal primes corresponding to those gaps.\n\nThough every gap value exists, they don't seem to come in any particular order. For example, this table shows the gaps and minimum starting value primes for 2 through 30:\n\n\nFor the purposes of this task, considering only primes greater than 2, consider prime gaps that differ by exactly two to be adjacent.\n\n\n\n;Task\n\nFor each order of magnitude '''m''' from '''10\u00b9''' through '''10\u2076''':\n\n* Find the first two sets of minimum adjacent prime gaps where the absolute value of the difference between the prime gap start values is greater than '''m'''.\n\n\n;E.G.\n\nFor an '''m''' of '''10\u00b9'''; \n\nThe start value of gap 2 is 3, the start value of gap 4 is 7, the difference is 7 - 3 or 4. 4 < '''10\u00b9''' so keep going.\n\nThe start value of gap 4 is 7, the start value of gap 6 is 23, the difference is 23 - 7, or 16. 16 > '''10\u00b9''' so this the earliest adjacent gap difference > '''10\u00b9'''.\n\n\n;Stretch goal\n\n* Do the same for '''10\u2077''' and '''10\u2078''' (and higher?) orders of magnitude\n\nNote: the earliest value found for each order of magnitude may not be unique, in fact, ''is'' not unique; also, with the gaps in ascending order, the minimal starting values are not strictly ascending.\n\n", "solution": "\"\"\" https://rosettacode.org/wiki/Earliest_difference_between_prime_gaps \"\"\"\n\nfrom primesieve import primes\n\nLIMIT = 10**9\npri = primes(LIMIT * 5)\ngapstarts = {}\nfor i in range(1, len(pri)):\n if pri[i] - pri[i - 1] not in gapstarts:\n gapstarts[pri[i] - pri[i - 1]] = pri[i - 1]\n\nPM, GAP1, = 10, 2\nwhile True:\n while GAP1 not in gapstarts:\n GAP1 += 2\n start1 = gapstarts[GAP1]\n GAP2 = GAP1 + 2\n if GAP2 not in gapstarts:\n GAP1 = GAP2 + 2\n continue\n start2 = gapstarts[GAP2]\n diff = abs(start2 - start1)\n if diff > PM:\n print(f\"Earliest difference >{PM: ,} between adjacent prime gap starting primes:\")\n print(f\"Gap {GAP1} starts at{start1: ,}, gap {GAP2} starts at{start2: ,}, difference is{diff: ,}.\\n\")\n if PM == LIMIT:\n break\n PM *= 10\n else:\n GAP1 = GAP2\n"} +{"title": "Eban numbers", "language": "C", "task": ";Definition:\nAn \u00a0 '''eban''' \u00a0 number is a number that has no letter \u00a0 '''e''' \u00a0 in it when the number is spelled in English.\n\nOr more literally, \u00a0 spelled numbers that contain the letter \u00a0 '''e''' \u00a0 are banned.\n\n\nThe American version of spelling numbers will be used here \u00a0 (as opposed to the British).\n\n'''2,000,000,000''' \u00a0 is two billion, \u00a0 ''not'' \u00a0 two milliard.\n\n\nOnly numbers less than \u00a0 '''one sextillion''' \u00a0 ('''1021''') \u00a0 will be considered in/for this task.\n\nThis will allow optimizations to be used.\n\n\n\n;Task:\n:::* \u00a0 show all eban numbers \u00a0 \u2264 \u00a0 '''1,000''' \u00a0 (in a horizontal format), \u00a0 and a count\n:::* \u00a0 show all eban numbers between \u00a0 '''1,000''' \u00a0 and \u00a0 '''4,000''' \u00a0 (inclusive), \u00a0 and a count\n:::* \u00a0 show a count of all eban numbers up and including \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 '''10,000'''\n:::* \u00a0 show a count of all eban numbers up and including \u00a0 \u00a0 \u00a0 \u00a0 '''100,000'''\n:::* \u00a0 show a count of all eban numbers up and including \u00a0 \u00a0\u00a0 '''1,000,000'''\n:::* \u00a0 show a count of all eban numbers up and including \u00a0\u00a0 '''10,000,000'''\n:::* \u00a0 show all output here.\n\n\n;See also:\n:* \u00a0 The MathWorld entry: \u00a0 [http://mathworld.wolfram.com/EbanNumber.html eban numbers].\n:* \u00a0 The OEIS entry: \u00a0 [http://oeis.org/A006933 A6933, eban numbers].\n:* \u00a0 [[Number names]].\n\n", "solution": "#include \"stdio.h\"\n#include \"stdbool.h\"\n\n#define ARRAY_LEN(a,T) (sizeof(a) / sizeof(T))\n\nstruct Interval {\n int start, end;\n bool print;\n};\n\nint main() {\n struct Interval intervals[] = {\n {2, 1000, true},\n {1000, 4000, true},\n {2, 10000, false},\n {2, 100000, false},\n {2, 1000000, false},\n {2, 10000000, false},\n {2, 100000000, false},\n {2, 1000000000, false},\n };\n int idx;\n\n for (idx = 0; idx < ARRAY_LEN(intervals, struct Interval); ++idx) {\n struct Interval intv = intervals[idx];\n int count = 0, i;\n\n if (intv.start == 2) {\n printf(\"eban numbers up to and including %d:\\n\", intv.end);\n } else {\n printf(\"eban numbers between %d and %d (inclusive:)\", intv.start, intv.end);\n }\n\n for (i = intv.start; i <= intv.end; i += 2) {\n int b = i / 1000000000;\n int r = i % 1000000000;\n int m = r / 1000000;\n int t;\n\n r = i % 1000000;\n t = r / 1000;\n r %= 1000;\n if (m >= 30 && m <= 66) m %= 10;\n if (t >= 30 && t <= 66) t %= 10;\n if (r >= 30 && r <= 66) r %= 10;\n if (b == 0 || b == 2 || b == 4 || b == 6) {\n if (m == 0 || m == 2 || m == 4 || m == 6) {\n if (t == 0 || t == 2 || t == 4 || t == 6) {\n if (r == 0 || r == 2 || r == 4 || r == 6) {\n if (intv.print) printf(\"%d \", i);\n count++;\n }\n }\n }\n }\n }\n if (intv.print) {\n printf(\"\\n\");\n }\n printf(\"count = %d\\n\\n\", count);\n }\n\n return 0;\n}"} +{"title": "Eban numbers", "language": "Python", "task": ";Definition:\nAn \u00a0 '''eban''' \u00a0 number is a number that has no letter \u00a0 '''e''' \u00a0 in it when the number is spelled in English.\n\nOr more literally, \u00a0 spelled numbers that contain the letter \u00a0 '''e''' \u00a0 are banned.\n\n\nThe American version of spelling numbers will be used here \u00a0 (as opposed to the British).\n\n'''2,000,000,000''' \u00a0 is two billion, \u00a0 ''not'' \u00a0 two milliard.\n\n\nOnly numbers less than \u00a0 '''one sextillion''' \u00a0 ('''1021''') \u00a0 will be considered in/for this task.\n\nThis will allow optimizations to be used.\n\n\n\n;Task:\n:::* \u00a0 show all eban numbers \u00a0 \u2264 \u00a0 '''1,000''' \u00a0 (in a horizontal format), \u00a0 and a count\n:::* \u00a0 show all eban numbers between \u00a0 '''1,000''' \u00a0 and \u00a0 '''4,000''' \u00a0 (inclusive), \u00a0 and a count\n:::* \u00a0 show a count of all eban numbers up and including \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 '''10,000'''\n:::* \u00a0 show a count of all eban numbers up and including \u00a0 \u00a0 \u00a0 \u00a0 '''100,000'''\n:::* \u00a0 show a count of all eban numbers up and including \u00a0 \u00a0\u00a0 '''1,000,000'''\n:::* \u00a0 show a count of all eban numbers up and including \u00a0\u00a0 '''10,000,000'''\n:::* \u00a0 show all output here.\n\n\n;See also:\n:* \u00a0 The MathWorld entry: \u00a0 [http://mathworld.wolfram.com/EbanNumber.html eban numbers].\n:* \u00a0 The OEIS entry: \u00a0 [http://oeis.org/A006933 A6933, eban numbers].\n:* \u00a0 [[Number names]].\n\n", "solution": "\n# Use inflect\n\n\"\"\"\n\n show all eban numbers <= 1,000 (in a horizontal format), and a count\n show all eban numbers between 1,000 and 4,000 (inclusive), and a count\n show a count of all eban numbers up and including 10,000\n show a count of all eban numbers up and including 100,000\n show a count of all eban numbers up and including 1,000,000\n show a count of all eban numbers up and including 10,000,000\n \n\"\"\"\n\nimport inflect\nimport time\n\nbefore = time.perf_counter()\n\np = inflect.engine()\n\n# eban numbers <= 1000\n\nprint(' ')\nprint('eban numbers up to and including 1000:')\nprint(' ')\n\ncount = 0\n\nfor i in range(1,1001):\n if not 'e' in p.number_to_words(i):\n print(str(i)+' ',end='')\n count += 1\n \nprint(' ')\nprint(' ')\nprint('count = '+str(count))\nprint(' ')\n\n# eban numbers 1000 to 4000\n\nprint(' ')\nprint('eban numbers between 1000 and 4000 (inclusive):')\nprint(' ')\n\ncount = 0\n\nfor i in range(1000,4001):\n if not 'e' in p.number_to_words(i):\n print(str(i)+' ',end='')\n count += 1\n \nprint(' ')\nprint(' ')\nprint('count = '+str(count))\nprint(' ')\n\n# eban numbers up to 10000\n\nprint(' ')\nprint('eban numbers up to and including 10000:')\nprint(' ')\n\ncount = 0\n\nfor i in range(1,10001):\n if not 'e' in p.number_to_words(i):\n count += 1\n \nprint(' ')\nprint('count = '+str(count))\nprint(' ')\n\n# eban numbers up to 100000\n\nprint(' ')\nprint('eban numbers up to and including 100000:')\nprint(' ')\n\ncount = 0\n\nfor i in range(1,100001):\n if not 'e' in p.number_to_words(i):\n count += 1\n \nprint(' ')\nprint('count = '+str(count))\nprint(' ')\n\n# eban numbers up to 1000000\n\nprint(' ')\nprint('eban numbers up to and including 1000000:')\nprint(' ')\n\ncount = 0\n\nfor i in range(1,1000001):\n if not 'e' in p.number_to_words(i):\n count += 1\n \nprint(' ')\nprint('count = '+str(count))\nprint(' ')\n\n# eban numbers up to 10000000\n\nprint(' ')\nprint('eban numbers up to and including 10000000:')\nprint(' ')\n\ncount = 0\n\nfor i in range(1,10000001):\n if not 'e' in p.number_to_words(i):\n count += 1\n \nprint(' ')\nprint('count = '+str(count))\nprint(' ')\n\nafter = time.perf_counter()\n\nprint(\" \")\nprint(\"Run time in seconds: \"+str(after - before))\n"} +{"title": "Eertree", "language": "Python", "task": "An '''eertree''' is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. \n\nThe data structure has commonalities to both ''tries'' and ''suffix trees''.\n\u00a0 See links below. \n\n\n;Task:\nConstruct an eertree for the string \"eertree\", then output all sub-palindromes by traversing the tree.\n\n\n;See also:\n* \u00a0 Wikipedia entry: \u00a0 [https://en.wikipedia.org/wiki/Trie trie].\n* \u00a0 Wikipedia entry: \u00a0 [https://en.wikipedia.org/wiki/Suffix_tree suffix tree] \n* \u00a0 [https://arxiv.org/abs/1506.04862 Cornell University Library, Computer Science, Data Structures and Algorithms \u2500\u2500\u2500\u25ba EERTREE: An Efficient Data Structure for Processing Palindromes in Strings].\n\n", "solution": "#!/bin/python\nfrom __future__ import print_function\n\nclass Node(object):\n\tdef __init__(self):\n\t\tself.edges = {} # edges (or forward links)\n\t\tself.link = None # suffix link (backward links)\n\t\tself.len = 0 # the length of the node\n\nclass Eertree(object):\n\tdef __init__(self):\n\t\tself.nodes = []\n\t\t# two initial root nodes\n\t\tself.rto = Node() #odd length root node, or node -1\n\t\tself.rte = Node() #even length root node, or node 0\n\n\t\t# Initialize empty tree\n\t\tself.rto.link = self.rte.link = self.rto;\n\t\tself.rto.len = -1\n\t\tself.rte.len = 0\n\t\tself.S = [0] # accumulated input string, T=S[1..i]\n\t\tself.maxSufT = self.rte # maximum suffix of tree T\n\n\tdef get_max_suffix_pal(self, startNode, a):\n\t\t# We traverse the suffix-palindromes of T in the order of decreasing length.\n\t\t# For each palindrome we read its length k and compare T[i-k] against a\n\t\t# until we get an equality or arrive at the -1 node.\n\t\tu = startNode\n\t\ti = len(self.S)\n\t\tk = u.len\n\t\twhile id(u) != id(self.rto) and self.S[i - k - 1] != a:\n\t\t\tassert id(u) != id(u.link) #Prevent infinte loop\n\t\t\tu = u.link\n\t\t\tk = u.len\n\n\t\treturn u\n\t\n\tdef add(self, a):\n\n\t\t# We need to find the maximum suffix-palindrome P of Ta\n\t\t# Start by finding maximum suffix-palindrome Q of T.\n\t\t# To do this, we traverse the suffix-palindromes of T\n\t\t# in the order of decreasing length, starting with maxSuf(T)\n\t\tQ = self.get_max_suffix_pal(self.maxSufT, a)\n\n\t\t# We check Q to see whether it has an outgoing edge labeled by a.\n\t\tcreateANewNode = not a in Q.edges\n\n\t\tif createANewNode:\n\t\t\t# We create the node P of length Q+2\n\t\t\tP = Node()\n\t\t\tself.nodes.append(P)\n\t\t\tP.len = Q.len + 2\n\t\t\tif P.len == 1:\n\t\t\t\t# if P = a, create the suffix link (P,0)\n\t\t\t\tP.link = self.rte\n\t\t\telse:\n\t\t\t\t# It remains to create the suffix link from P if |P|>1. Just\n\t\t\t\t# continue traversing suffix-palindromes of T starting with the suffix \n\t\t\t\t# link of Q.\n\t\t\t\tP.link = self.get_max_suffix_pal(Q.link, a).edges[a]\n\n\t\t\t# create the edge (Q,P)\n\t\t\tQ.edges[a] = P\n\n\t\t#P becomes the new maxSufT\n\t\tself.maxSufT = Q.edges[a]\n\n\t\t#Store accumulated input string\n\t\tself.S.append(a)\n\n\t\treturn createANewNode\n\t\n\tdef get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):\n\t\t#Each node represents a palindrome, which can be reconstructed\n\t\t#by the path from the root node to each non-root node.\n\n\t\t#Traverse all edges, since they represent other palindromes\n\t\tfor lnkName in nd.edges:\n\t\t\tnd2 = nd.edges[lnkName] #The lnkName is the character used for this edge\n\t\t\tself.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)\n\n\t\t#Reconstruct based on charsToHere characters.\n\t\tif id(nd) != id(self.rto) and id(nd) != id(self.rte): #Don't print for root nodes\n\t\t\ttmp = \"\".join(charsToHere)\n\t\t\tif id(nodesToHere[0]) == id(self.rte): #Even string\n\t\t\t\tassembled = tmp[::-1] + tmp\n\t\t\telse: #Odd string\n\t\t\t\tassembled = tmp[::-1] + tmp[1:]\n\t\t\tresult.append(assembled)\n\nif __name__==\"__main__\":\n\tst = \"eertree\"\n\tprint (\"Processing string\", st)\n\teertree = Eertree()\n\tfor ch in st:\n\t\teertree.add(ch)\n\n\tprint (\"Number of sub-palindromes:\", len(eertree.nodes))\n\n\t#Traverse tree to find sub-palindromes\n\tresult = []\n\teertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) #Odd length words\n\teertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) #Even length words\n\tprint (\"Sub-palindromes:\", result)"} +{"title": "Egyptian division", "language": "C", "task": "Egyptian division is a method of dividing integers using addition and \ndoubling that is similar to the algorithm of [[Ethiopian multiplication]]\n\n'''Algorithm:'''\n\nGiven two numbers where the '''dividend''' is to be divided by the '''divisor''':\n\n# Start the construction of a table of two columns: '''powers_of_2''', and '''doublings'''; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.\n# Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order.\n# Continue with successive i\u2019th rows of 2^i and 2^i * divisor.\n# Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend.\n# We now assemble two separate sums that both start as zero, called here '''answer''' and '''accumulator'''\n# Consider each row of the table, in the ''reverse'' order of its construction.\n# If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer.\n# When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend).\n\n\n'''Example: 580 / 34'''\n\n''' Table creation: '''\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n|-\n| 1\n| 34\n|-\n| 2\n| 68\n|-\n| 4\n| 136\n|-\n| 8\n| 272\n|-\n| 16\n| 544\n|}\n\n''' Initialization of sums: '''\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| 16\n| 544\n|\n\n|\n\n|-\n|\n|\n| 0\n| 0\n|}\n\n''' Considering table rows, bottom-up: '''\n\nWhen a row is considered it is shown crossed out if it is not accumulated, or '''bold''' if the row causes summations.\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n| 16\n| 544\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n| 16\n| 544\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n| 16\n| 544\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n| 16\n| 544\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| '''1'''\n| '''34'''\n| 17\n| 578\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n;Answer:\nSo 580 divided by 34 using the Egyptian method is '''17''' remainder (578 - 580) or '''2'''.\n\n\n;Task:\nThe task is to create a function that does [https://en.wikipedia.org/wiki/Ancient_Egyptian_mathematics#Multiplication_and_division Egyptian division]. The function should\nclosely follow the description above in using a list/array of powers of two, and\nanother of doublings.\n\n* Functions should be clear interpretations of the algorithm.\n* Use the function to divide 580 by 34 and show the answer '''here, on this page'''.\n\n\n;Related tasks:\n:* \u00a0 Egyptian fractions\n\n\n;References:\n:* \u00a0 [https://discoveringegypt.com/egyptian-hieroglyphic-writing/egyptian-mathematics-numbers-hieroglyphs/ Egyptian Number System]\n\n", "solution": "\n#include \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": "Egyptian division", "language": "JavaScript", "task": "Egyptian division is a method of dividing integers using addition and \ndoubling that is similar to the algorithm of [[Ethiopian multiplication]]\n\n'''Algorithm:'''\n\nGiven two numbers where the '''dividend''' is to be divided by the '''divisor''':\n\n# Start the construction of a table of two columns: '''powers_of_2''', and '''doublings'''; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.\n# Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order.\n# Continue with successive i\u2019th rows of 2^i and 2^i * divisor.\n# Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend.\n# We now assemble two separate sums that both start as zero, called here '''answer''' and '''accumulator'''\n# Consider each row of the table, in the ''reverse'' order of its construction.\n# If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer.\n# When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend).\n\n\n'''Example: 580 / 34'''\n\n''' Table creation: '''\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n|-\n| 1\n| 34\n|-\n| 2\n| 68\n|-\n| 4\n| 136\n|-\n| 8\n| 272\n|-\n| 16\n| 544\n|}\n\n''' Initialization of sums: '''\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| 16\n| 544\n|\n\n|\n\n|-\n|\n|\n| 0\n| 0\n|}\n\n''' Considering table rows, bottom-up: '''\n\nWhen a row is considered it is shown crossed out if it is not accumulated, or '''bold''' if the row causes summations.\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n| 16\n| 544\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n| 16\n| 544\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n| 16\n| 544\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n| 16\n| 544\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| '''1'''\n| '''34'''\n| 17\n| 578\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n;Answer:\nSo 580 divided by 34 using the Egyptian method is '''17''' remainder (578 - 580) or '''2'''.\n\n\n;Task:\nThe task is to create a function that does [https://en.wikipedia.org/wiki/Ancient_Egyptian_mathematics#Multiplication_and_division Egyptian division]. The function should\nclosely follow the description above in using a list/array of powers of two, and\nanother of doublings.\n\n* Functions should be clear interpretations of the algorithm.\n* Use the function to divide 580 by 34 and show the answer '''here, on this page'''.\n\n\n;Related tasks:\n:* \u00a0 Egyptian fractions\n\n\n;References:\n:* \u00a0 [https://discoveringegypt.com/egyptian-hieroglyphic-writing/egyptian-mathematics-numbers-hieroglyphs/ Egyptian Number System]\n\n", "solution": "(() => {\n 'use strict';\n\n // EGYPTIAN DIVISION --------------------------------\n\n // eqyptianQuotRem :: Int -> Int -> (Int, Int)\n const eqyptianQuotRem = (m, n) => {\n const expansion = ([i, x]) =>\n x > m ? (\n Nothing()\n ) : Just([\n [i, x],\n [i + i, x + x]\n ]);\n const collapse = ([i, x], [q, r]) =>\n x < r ? (\n [q + i, r - x]\n ) : [q, r];\n return foldr(\n collapse,\n [0, m],\n unfoldr(expansion, [1, n])\n );\n };\n\n // TEST ---------------------------------------------\n\n // main :: IO ()\n const main = () =>\n showLog(\n eqyptianQuotRem(580, 34)\n );\n // -> [17, 2]\n\n\n\n // GENERIC FUNCTIONS --------------------------------\n\n // Just :: a -> Maybe a\n const Just = x => ({\n type: 'Maybe',\n Nothing: false,\n Just: x\n });\n\n // Nothing :: Maybe a\n const Nothing = () => ({\n type: 'Maybe',\n Nothing: true,\n });\n\n // flip :: (a -> b -> c) -> b -> a -> c\n const flip = f =>\n 1 < f.length ? (\n (a, b) => f(b, a)\n ) : (x => y => f(y)(x));\n\n\n // foldr :: (a -> b -> b) -> b -> [a] -> b\n const foldr = (f, a, xs) => xs.reduceRight(flip(f), a);\n\n\n // unfoldr :: (b -> Maybe (a, b)) -> b -> [a]\n const unfoldr = (f, v) => {\n let\n xr = [v, v],\n xs = [];\n while (true) {\n const mb = f(xr[1]);\n if (mb.Nothing) {\n return xs\n } else {\n xr = mb.Just;\n xs.push(xr[0])\n }\n }\n };\n\n // showLog :: a -> IO ()\n const showLog = (...args) =>\n console.log(\n args\n .map(JSON.stringify)\n .join(' -> ')\n );\n\n // MAIN ---\n return main();\n})();"} +{"title": "Egyptian division", "language": "Python", "task": "Egyptian division is a method of dividing integers using addition and \ndoubling that is similar to the algorithm of [[Ethiopian multiplication]]\n\n'''Algorithm:'''\n\nGiven two numbers where the '''dividend''' is to be divided by the '''divisor''':\n\n# Start the construction of a table of two columns: '''powers_of_2''', and '''doublings'''; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.\n# Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order.\n# Continue with successive i\u2019th rows of 2^i and 2^i * divisor.\n# Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend.\n# We now assemble two separate sums that both start as zero, called here '''answer''' and '''accumulator'''\n# Consider each row of the table, in the ''reverse'' order of its construction.\n# If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer.\n# When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend).\n\n\n'''Example: 580 / 34'''\n\n''' Table creation: '''\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n|-\n| 1\n| 34\n|-\n| 2\n| 68\n|-\n| 4\n| 136\n|-\n| 8\n| 272\n|-\n| 16\n| 544\n|}\n\n''' Initialization of sums: '''\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| 16\n| 544\n|\n\n|\n\n|-\n|\n|\n| 0\n| 0\n|}\n\n''' Considering table rows, bottom-up: '''\n\nWhen a row is considered it is shown crossed out if it is not accumulated, or '''bold''' if the row causes summations.\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n| 16\n| 544\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n| 16\n| 544\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n| 16\n| 544\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n| 16\n| 544\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| '''1'''\n| '''34'''\n| 17\n| 578\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n;Answer:\nSo 580 divided by 34 using the Egyptian method is '''17''' remainder (578 - 580) or '''2'''.\n\n\n;Task:\nThe task is to create a function that does [https://en.wikipedia.org/wiki/Ancient_Egyptian_mathematics#Multiplication_and_division Egyptian division]. The function should\nclosely follow the description above in using a list/array of powers of two, and\nanother of doublings.\n\n* Functions should be clear interpretations of the algorithm.\n* Use the function to divide 580 by 34 and show the answer '''here, on this page'''.\n\n\n;Related tasks:\n:* \u00a0 Egyptian fractions\n\n\n;References:\n:* \u00a0 [https://discoveringegypt.com/egyptian-hieroglyphic-writing/egyptian-mathematics-numbers-hieroglyphs/ Egyptian Number System]\n\n", "solution": "'''Quotient and remainder of division by the Rhind papyrus method.'''\n\nfrom functools import reduce\n\n\n# eqyptianQuotRem :: Int -> Int -> (Int, Int)\ndef eqyptianQuotRem(m):\n '''Quotient and remainder derived by the Eqyptian method.'''\n\n def expansion(xi):\n '''Doubled value, and next power of two - both by self addition.'''\n x, i = xi\n return Nothing() if x > m else Just(\n ((x + x, i + i), xi)\n )\n\n def collapse(qr, ix):\n '''Addition of a power of two to the quotient,\n and subtraction of a paired value from the remainder.'''\n i, x = ix\n q, r = qr\n return (q + i, r - x) if x < r else qr\n\n return lambda n: reduce(\n collapse,\n unfoldl(expansion)(\n (1, n)\n ),\n (0, m)\n )\n\n\n# ------------------------- TEST --------------------------\n# main :: IO ()\ndef main():\n '''Test'''\n print(\n eqyptianQuotRem(580)(34)\n )\n\n\n# ------------------- GENERIC FUNCTIONS -------------------\n\n# Just :: a -> Maybe a\ndef Just(x):\n '''Constructor for an inhabited Maybe (option type) value.'''\n return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n# Nothing :: Maybe a\ndef Nothing():\n '''Constructor for an empty Maybe (option type) value.'''\n return {'type': 'Maybe', 'Nothing': True}\n\n\n# unfoldl(lambda x: Just(((x - 1), x)) if 0 != x else Nothing())(10)\n# -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n# unfoldl :: (b -> Maybe (b, a)) -> b -> [a]\ndef unfoldl(f):\n '''Dual to reduce or foldl.\n Where these reduce a list to a summary value, unfoldl\n builds a list from a seed value.\n Where f returns Just(a, b), a is appended to the list,\n and the residual b is used as the argument for the next\n application of f.\n When f returns Nothing, the completed list is returned.\n '''\n def go(v):\n x, r = v, v\n xs = []\n while True:\n mb = f(x)\n if mb.get('Nothing'):\n return xs\n else:\n x, r = mb.get('Just')\n xs.insert(0, r)\n return xs\n return go\n\n\n# MAIN ----------------------------------------------------\nif __name__ == '__main__':\n main()"} +{"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* [http://natureofcode.com/book/chapter-7-cellular-automata 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", "language": "JavaScript", "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* [http://natureofcode.com/book/chapter-7-cellular-automata Cellular automata (natureofcode.com)]\n\n", "solution": "const alive = '#';\nconst dead = '.';\n\n// ------------------------------------------------------------[ Bit banging ]--\nconst setBitAt = (val, idx) => BigInt(val) | (1n << BigInt(idx));\nconst clearBitAt = (val, idx) => BigInt(val) & ~(1n << BigInt(idx));\nconst getBitAt = val => idx => (BigInt(val) >> BigInt(idx)) & 1n;\nconst hasBitAt = val => idx => ((BigInt(val) >> BigInt(idx)) & 1n) === 1n;\n\n// ----------------------------------------------------------------[ Utility ]--\nconst makeArr = n => Array(n).fill(0);\nconst reverse = x => Array.from(x).reduce((p, c) => [c, ...p], []);\nconst numToLine = width => int => {\n const test = hasBitAt(int);\n const looper = makeArr(width);\n return reverse(looper.map((_, i) => test(i) ? alive : dead)).join('');\n}\n\n// -------------------------------------------------------------------[ Main ]--\nconst displayCA = (rule, width, lines, startIndex) => {\n const result = [];\n result.push(`Rule:${rule} Width:${width} Gen:${lines}\\n`)\n const ruleTest = hasBitAt(rule);\n const lineLoop = makeArr(lines);\n const looper = makeArr(width);\n const pLine = numToLine(width);\n\n let nTarget = setBitAt(0n, startIndex);\n result.push(pLine(nTarget));\n lineLoop.forEach(() => {\n const bitTest = getBitAt(nTarget);\n looper.forEach((e, i) => {\n const l = bitTest(i === 0 ? width - 1 : i - 1);\n const m = bitTest(i);\n const r = bitTest(i === width - 1 ? 0 : i + 1);\n nTarget = ruleTest(\n parseInt([l, m, r].join(''), 2))\n ? setBitAt(nTarget, i)\n : clearBitAt(nTarget, i);\n });\n result.push(pLine(nTarget));\n });\n return result.join('\\n');\n}\n\ndisplayCA(90, 57, 31, 28);"} +{"title": "Elementary cellular automaton", "language": "Python", "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* [http://natureofcode.com/book/chapter-7-cellular-automata Cellular automata (natureofcode.com)]\n\n", "solution": "def eca(cells, rule):\n lencells = len(cells)\n c = \"0\" + cells + \"0\" # Zero pad the ends\n rulebits = '{0:08b}'.format(rule)\n neighbours2next = {'{0:03b}'.format(n):rulebits[::-1][n] for n in range(8)}\n yield c[1:-1]\n while True:\n c = ''.join(['0',\n ''.join(neighbours2next[c[i-1:i+2]]\n for i in range(1,lencells+1)),\n '0'])\n yield c[1:-1]\n\nif __name__ == '__main__':\n lines, start, rules = 50, '0000000001000000000', (90, 30, 122)\n zipped = [range(lines)] + [eca(start, rule) for rule in rules]\n print('\\n Rules: %r' % (rules,))\n for data in zip(*zipped):\n i = data[0]\n cells = data[1:]\n print('%2i: %s' % (i, ' '.join(cells).replace('0', '.').replace('1', '#')))"} +{"title": "Elementary cellular automaton/Infinite length", "language": "Python", "task": "The purpose of this task is to create a version of an [[Elementary cellular automaton]] whose number of cells is only limited by the memory size of the computer.\n\nTo be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state of the automaton, you need a finite number of adjacent cells, along with their individual state, and you then consider that the individual state of each of all other cells is the negation of the closest individual cell among the previously defined finite number of cells.\n\nExamples:\n\n\n1 -> ..., 0, 0, 1, 0, 0, ...\n0, 1 -> ..., 1, 1, 0, 1, 0, 0, ...\n1, 0, 1 -> ..., 0, 0, 1, 0, 1, 0, 0, ...\n\n\nMore complex methods can be imagined, provided it is possible to somehow encode the infinite sections. But for this task we will stick to this simple version.\n\n", "solution": "def _notcell(c):\n return '0' if c == '1' else '1'\n\ndef eca_infinite(cells, rule):\n lencells = len(cells)\n rulebits = '{0:08b}'.format(rule)\n neighbours2next = {'{0:03b}'.format(n):rulebits[::-1][n] for n in range(8)}\n c = cells\n while True:\n yield c\n c = _notcell(c[0])*2 + c + _notcell(c[-1])*2 # Extend and pad the ends\n\n c = ''.join(neighbours2next[c[i-1:i+2]] for i in range(1,len(c) - 1))\n #yield c[1:-1]\n\nif __name__ == '__main__':\n lines = 25\n for rule in (90, 30):\n print('\\nRule: %i' % rule)\n for i, c in zip(range(lines), eca_infinite('1', rule)):\n print('%2i: %s%s' % (i, ' '*(lines - i), c.replace('0', '.').replace('1', '#')))"} +{"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* [http://www.cs.indiana.edu/~dgerman/2005midwestNKSconference/dgelbm.pdf 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": "Elementary cellular automaton/Random number generator", "language": "Python", "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* [http://www.cs.indiana.edu/~dgerman/2005midwestNKSconference/dgelbm.pdf Cellular automata: Is Rule 30 random]? (PDF).\n\n\n", "solution": "from elementary_cellular_automaton import eca, eca_wrap\n\ndef rule30bytes(lencells=100):\n cells = '1' + '0' * (lencells - 1)\n gen = eca(cells, 30)\n while True:\n yield int(''.join(next(gen)[0] for i in range(8)), 2)\n\nif __name__ == '__main__':\n print([b for i,b in zip(range(10), rule30bytes())])"} +{"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 \u00a0 elliptic curve DSA \u00a0 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:::: \u00a0 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:::: \u00a0 a=0, \u00a0 b=7 \n\nThe most interesting thing about elliptic curves is the fact that it is possible to define a \u00a0 group \u00a0 structure on it. \n\nTo do so we define an \u00a0 internal composition \u00a0 rule with an additive notation '''+''', \u00a0 such that for any three distinct points '''P''', '''Q''' and '''R''' on the curve, whenever these points are aligned, we have:\n\n:::: \u00a0 P + Q + R = 0 \n\nHere \u00a0 '''0''' \u00a0 (zero) \u00a0 is the ''infinity point'', \u00a0 for which the '''x''' and '''y''' values are not defined. \u00a0 It's basically the same kind of point which defines the horizon in \u00a0 projective geometry. \n\nWe'll also assume here that this infinity point is unique and defines the \u00a0 neutral element \u00a0 of the addition.\n\nThis was not the definition of the addition, but only its desired property. \u00a0 For a more accurate definition, we proceed as such:\n\nGiven any three aligned points '''P''', '''Q''' and '''R''', \u00a0 we define the sum \u00a0 '''S = P + Q''' \u00a0 as the point (possibly the infinity point) such that \u00a0 '''S''', '''R''' \u00a0 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 \u00a0 (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. \u00a0 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'': \u00a0 You might need to define a \"doubling\" function, that returns '''P+P''' for any given point '''P'''.\n\n''Extra credit'': \u00a0 define the full elliptic curve arithmetic (still not modular, though) by defining a \"multiply\" function that returns, \nfor any point '''P''' and integer '''n''', \u00a0 the point '''P + P + ... + P''' \u00a0 \u00a0 ('''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": "Elliptic curve arithmetic", "language": "Python", "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 \u00a0 elliptic curve DSA \u00a0 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:::: \u00a0 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:::: \u00a0 a=0, \u00a0 b=7 \n\nThe most interesting thing about elliptic curves is the fact that it is possible to define a \u00a0 group \u00a0 structure on it. \n\nTo do so we define an \u00a0 internal composition \u00a0 rule with an additive notation '''+''', \u00a0 such that for any three distinct points '''P''', '''Q''' and '''R''' on the curve, whenever these points are aligned, we have:\n\n:::: \u00a0 P + Q + R = 0 \n\nHere \u00a0 '''0''' \u00a0 (zero) \u00a0 is the ''infinity point'', \u00a0 for which the '''x''' and '''y''' values are not defined. \u00a0 It's basically the same kind of point which defines the horizon in \u00a0 projective geometry. \n\nWe'll also assume here that this infinity point is unique and defines the \u00a0 neutral element \u00a0 of the addition.\n\nThis was not the definition of the addition, but only its desired property. \u00a0 For a more accurate definition, we proceed as such:\n\nGiven any three aligned points '''P''', '''Q''' and '''R''', \u00a0 we define the sum \u00a0 '''S = P + Q''' \u00a0 as the point (possibly the infinity point) such that \u00a0 '''S''', '''R''' \u00a0 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 \u00a0 (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. \u00a0 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'': \u00a0 You might need to define a \"doubling\" function, that returns '''P+P''' for any given point '''P'''.\n\n''Extra credit'': \u00a0 define the full elliptic curve arithmetic (still not modular, though) by defining a \"multiply\" function that returns, \nfor any point '''P''' and integer '''n''', \u00a0 the point '''P + P + ... + P''' \u00a0 \u00a0 ('''n''' times).\n\n", "solution": "#!/usr/bin/env python3\n\nclass Point:\n b = 7\n def __init__(self, x=float('inf'), y=float('inf')):\n self.x = x\n self.y = y\n\n def copy(self):\n return Point(self.x, self.y)\n\n def is_zero(self):\n return self.x > 1e20 or self.x < -1e20\n\n def neg(self):\n return Point(self.x, -self.y)\n\n def dbl(self):\n if self.is_zero():\n return self.copy()\n try:\n L = (3 * self.x * self.x) / (2 * self.y)\n except ZeroDivisionError:\n return Point()\n x = L * L - 2 * self.x\n return Point(x, L * (self.x - x) - self.y)\n\n def add(self, q):\n if self.x == q.x and self.y == q.y:\n return self.dbl()\n if self.is_zero():\n return q.copy()\n if q.is_zero():\n return self.copy()\n try:\n L = (q.y - self.y) / (q.x - self.x)\n except ZeroDivisionError:\n return Point()\n x = L * L - self.x - q.x\n return Point(x, L * (self.x - x) - self.y)\n\n def mul(self, n):\n p = self.copy()\n r = Point()\n i = 1\n while i <= n:\n if i&n:\n r = r.add(p)\n p = p.dbl()\n i <<= 1\n return r\n\n def __str__(self):\n return \"({:.3f}, {:.3f})\".format(self.x, self.y)\n\ndef show(s, p):\n print(s, \"Zero\" if p.is_zero() else p)\n\ndef from_y(y):\n n = y * y - Point.b\n x = n**(1./3) if n>=0 else -((-n)**(1./3))\n return Point(x, y)\n\n# demonstrate\na = from_y(1)\nb = from_y(2)\nshow(\"a =\", a)\nshow(\"b =\", b)\nc = a.add(b)\nshow(\"c = a + b =\", c)\nd = c.neg()\nshow(\"d = -c =\", d)\nshow(\"c + d =\", c.add(d))\nshow(\"a + b + d =\", a.add(b.add(d)))\nshow(\"a * 12345 =\", a.mul(12345))"} +{"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 \u201c.\u201d and almost every directory contains \u201c..\u201d (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 directory", "language": "JavaScript", "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 \u201c.\u201d and almost every directory contains \u201c..\u201d (except for a root directory); an empty directory contains no other entries.\n\n", "solution": "The ECMAScript standard itself defines no IO interface \u2013 the following example makes use of the Node.js file IO library.\n"} +{"title": "Empty directory", "language": "Node.js", "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 \u201c.\u201d and almost every directory contains \u201c..\u201d (except for a root directory); an empty directory contains no other entries.\n\n", "solution": "// Node.js v14.15.4\nconst { readdirSync } = require(\"fs\");\nconst emptydir = (path) => readdirSync(path).length == 0;\n\n// tests, run like node emptydir.js [directories]\nfor (let i = 2; i < process.argv.length; i ++) {\n let dir = process.argv[i];\n console.log(`${dir}: ${emptydir(dir) ? \"\" : \"not \"}empty`)\n}"} +{"title": "Empty directory", "language": "Python 2.x", "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 \u201c.\u201d and almost every directory contains \u201c..\u201d (except for a root directory); an empty directory contains no other entries.\n\n", "solution": "import os;\nif os.listdir(raw_input(\"directory\")):\n print \"not empty\"\nelse:\n print \"empty\"\n"} +{"title": "Empty string", "language": "C", "task": "[[Category:String manipulation]] [[Category:Simple]]\n\nLanguages may have features for dealing specifically with empty strings \n(those containing no characters).\n\n\n;Task:\n::* \u00a0 Demonstrate how to assign an empty string to a variable.\n::* \u00a0 Demonstrate how to check that a string is empty.\n::* \u00a0 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": "Empty string", "language": "Python", "task": "[[Category:String manipulation]] [[Category:Simple]]\n\nLanguages may have features for dealing specifically with empty strings \n(those containing no characters).\n\n\n;Task:\n::* \u00a0 Demonstrate how to assign an empty string to a variable.\n::* \u00a0 Demonstrate how to check that a string is empty.\n::* \u00a0 Demonstrate how to check that a string is not empty.\n\n\n\n", "solution": "\ns = ''\n# or:\ns = str()\n\nif not s or s == '':\n print(\"String is empty\")\n\nif len(s) == 0:\n print(\"String is empty\")\nelse:\n print(\"String not empty\")\n\n\n# boolean test function for python2 and python3\n# test for regular (non-unicode) strings\n# unicode strings\n# None \ndef emptystring(s):\n if isinstance(s, (''.__class__ , u''.__class__) ):\n if len(s) == 0: \n return True\n else \n return False\n\n elif s is None:\n return True\n"} +{"title": "Entropy/Narcissist", "language": "C", "task": "right\n\n;Task:\nWrite a computer program that computes and shows its own \u00a0 [[entropy]].\n\n\n;Related Tasks: \n:* \u00a0 [[Fibonacci_word]]\n:* \u00a0 [[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"} +{"title": "Entropy/Narcissist", "language": "Python 3.4", "task": "right\n\n;Task:\nWrite a computer program that computes and shows its own \u00a0 [[entropy]].\n\n\n;Related Tasks: \n:* \u00a0 [[Fibonacci_word]]\n:* \u00a0 [[Entropy]]\n\n", "solution": "import math\nfrom collections import Counter\n\ndef entropy(s):\n p, lns = Counter(s), float(len(s))\n return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n\nwith open(__file__) as f:\n b=f.read()\n \nprint(entropy(b))"} +{"title": "Equilibrium index", "language": "C", "task": "An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. \n\n\nFor example, in a sequence \u00a0 A:\n\n::::: \u00a0 A_0 = -7\n::::: \u00a0 A_1 = 1\n::::: \u00a0 A_2 = 5\n::::: \u00a0 A_3 = 2\n::::: \u00a0 A_4 = -4\n::::: \u00a0 A_5 = 3\n::::: \u00a0 A_6 = 0\n\n3 \u00a0 is an equilibrium index, because:\n\n::::: \u00a0 A_0 + A_1 + A_2 = A_4 + A_5 + A_6\n\n6 \u00a0 is also an equilibrium index, because:\n\n::::: \u00a0 A_0 + A_1 + A_2 + A_3 + A_4 + A_5 = 0\n\n(sum of zero elements is zero) \n\n7 \u00a0 is not an equilibrium index, because it is not a valid index of sequence A.\n\n\n;Task;\nWrite a function that, given a sequence, returns its equilibrium indices (if any).\n\nAssume that the sequence may be very long.\n\n", "solution": "#include \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": "Equilibrium index", "language": "JavaScript", "task": "An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. \n\n\nFor example, in a sequence \u00a0 A:\n\n::::: \u00a0 A_0 = -7\n::::: \u00a0 A_1 = 1\n::::: \u00a0 A_2 = 5\n::::: \u00a0 A_3 = 2\n::::: \u00a0 A_4 = -4\n::::: \u00a0 A_5 = 3\n::::: \u00a0 A_6 = 0\n\n3 \u00a0 is an equilibrium index, because:\n\n::::: \u00a0 A_0 + A_1 + A_2 = A_4 + A_5 + A_6\n\n6 \u00a0 is also an equilibrium index, because:\n\n::::: \u00a0 A_0 + A_1 + A_2 + A_3 + A_4 + A_5 = 0\n\n(sum of zero elements is zero) \n\n7 \u00a0 is not an equilibrium index, because it is not a valid index of sequence A.\n\n\n;Task;\nWrite a function that, given a sequence, returns its equilibrium indices (if any).\n\nAssume that the sequence may be very long.\n\n", "solution": "function equilibrium(a) {\n var N = a.length, i, l = [], r = [], e = []\n for (l[0] = a[0], r[N - 1] = a[N - 1], i = 1; i\n"} +{"title": "Equilibrium index", "language": "Python", "task": "An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. \n\n\nFor example, in a sequence \u00a0 A:\n\n::::: \u00a0 A_0 = -7\n::::: \u00a0 A_1 = 1\n::::: \u00a0 A_2 = 5\n::::: \u00a0 A_3 = 2\n::::: \u00a0 A_4 = -4\n::::: \u00a0 A_5 = 3\n::::: \u00a0 A_6 = 0\n\n3 \u00a0 is an equilibrium index, because:\n\n::::: \u00a0 A_0 + A_1 + A_2 = A_4 + A_5 + A_6\n\n6 \u00a0 is also an equilibrium index, because:\n\n::::: \u00a0 A_0 + A_1 + A_2 + A_3 + A_4 + A_5 = 0\n\n(sum of zero elements is zero) \n\n7 \u00a0 is not an equilibrium index, because it is not a valid index of sequence A.\n\n\n;Task;\nWrite a function that, given a sequence, returns its equilibrium indices (if any).\n\nAssume that the sequence may be very long.\n\n", "solution": "\"\"\"Equilibrium index\"\"\"\n\nfrom itertools import (accumulate)\n\n\n# equilibriumIndices :: [Num] -> [Int]\ndef equilibriumIndices(xs):\n '''List indices at which the sum of values to the left\n equals the sum of values to the right.\n '''\n def go(xs):\n '''Left scan from accumulate,\n right scan derived from left\n '''\n ls = list(accumulate(xs))\n n = ls[-1]\n return [\n i for (i, (x, y)) in enumerate(zip(\n ls,\n [n] + [n - x for x in ls[0:-1]]\n )) if x == y\n ]\n return go(xs) if xs else []\n\n\n# ------------------------- TEST -------------------------\n# main :: IO ()\ndef main():\n '''Tabulated test results'''\n print(\n tabulated('Equilibrium indices:\\n')(\n equilibriumIndices\n )([\n [-7, 1, 5, 2, -4, 3, 0],\n [2, 4, 6],\n [2, 9, 2],\n [1, -1, 1, -1, 1, -1, 1],\n [1],\n []\n ])\n )\n\n\n# ----------------------- GENERIC ------------------------\n\n# tabulated :: String -> (a -> b) -> [a] -> String\ndef tabulated(s):\n '''heading -> function -> input List\n -> tabulated output string\n '''\n def go(f):\n def width(x):\n return len(str(x))\n def cols(xs):\n w = width(max(xs, key=width))\n return s + '\\n' + '\\n'.join([\n str(x).rjust(w, ' ') + ' -> ' + str(f(x))\n for x in xs\n ])\n return cols\n return go\n\n\nif __name__ == '__main__':\n main()"} +{"title": "Erd\u0151s-Nicolas numbers", "language": "C", "task": ";Definition\nAn perfect but is equal to the sum of its first '''k''' divisors (arranged in ascending order and including one) for some value of '''k''' greater than one.\n\n;Examples\n24 is an Erd\u0151s\u2013Nicolas number because the sum of its first 6 divisors (1, 2, 3, 4, 6 and 8) is equal to 24 and it is not perfect because 12 is also a divisor.\n\n6 is not an Erd\u0151s\u2013Nicolas number because it is perfect (1 + 2 + 3 = 6).\n\n48 is not an Erd\u0151s\u2013Nicolas number because its divisors are: 1, 2, 3, 4, 6, 8, 12, 16, 24 and 48. The first seven of these add up to 36, but the first eight add up to 52 which is more than 48.\n\n;Task\n\nFind and show here the first 8 Erd\u0151s\u2013Nicolas numbers and the number of divisors needed (i.e. the value of 'k') to satisfy the definition.\n\n;Stretch\nDo the same for any further Erd\u0151s\u2013Nicolas numbers which you have the patience for.\n\n;Note\nAs all known Erd\u0151s\u2013Nicolas numbers are even you may assume this to be generally true in order to quicken up the search. However, it is not obvious (to me at least) why this should necessarily be the case.\n\n;Reference\n* OEIS:A194472 - Erd\u0151s\u2013Nicolas numbers\n\n", "solution": "#include \n#include \n\nint main() {\n const int maxNumber = 100000000;\n int *dsum = (int *)malloc((maxNumber + 1) * sizeof(int));\n int *dcount = (int *)malloc((maxNumber + 1) * sizeof(int));\n int i, j;\n for (i = 0; i <= maxNumber; ++i) {\n dsum[i] = 1;\n dcount[i] = 1;\n }\n for (i = 2; i <= maxNumber; ++i) {\n for (j = i + i; j <= maxNumber; j += i) {\n if (dsum[j] == j) {\n printf(\"%8d equals the sum of its first %d divisors\\n\", j, dcount[j]);\n }\n dsum[j] += i;\n ++dcount[j];\n }\n }\n free(dsum);\n free(dcount);\n return 0;\n}"} +{"title": "Esthetic numbers", "language": "C", "task": "An '''esthetic number''' is a positive integer where every adjacent digit differs from its neighbour by 1.\n\n\n;E.G.\n\n:* '''12''' is an esthetic number. One and two differ by 1.\n\n:* '''5654''' is an esthetic number. Each digit is exactly 1 away from its neighbour.\n\n:* '''890''' is '''not''' an esthetic number. Nine and zero differ by 9.\n\n\nThese examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers ''are'' included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.\n\nEsthetic numbers are also sometimes referred to as stepping numbers.\n\n\n;Task\n\n:* Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.\n\n:* Use that routine to find esthetic numbers in bases '''2''' through '''16''' and display, here on this page, the esthectic numbers from index '''(base \u00d7 4)''' through index '''(base \u00d7 6)''', inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)\n\n:* Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1000''' and '''9999'''.\n\n:* Stretch: Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1.0e8''' and '''1.3e8'''.\n\n\n;Related task:\n* \u00a0 numbers with equal rises and falls\n\n\n;See also:\n:;*OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1\n:;*[http://www.numbersaplenty.com/set/esthetic_number/ Numbers Aplenty - Esthetic numbers]\n:;*[https://www.geeksforgeeks.org/stepping-numbers/ Geeks for Geeks - Stepping numbers]\n\n", "solution": "#include \n#include \n#include \n\ntypedef int bool;\ntypedef unsigned long long ull;\n\n#define TRUE 1\n#define FALSE 0\n\nchar as_digit(int d) { \n return (d >= 0 && d <= 9) ? d + '0' : d - 10 + 'a'; \n}\n\nvoid revstr(char *str) { \n int i, len = strlen(str);\n char t; \n for (i = 0; i < len/2; ++i) { \n t = str[i]; \n str[i] = str[len - i - 1]; \n str[len - i - 1] = t; \n } \n} \n\nchar* to_base(char s[], ull n, int b) { \n int i = 0; \n while (n) { \n s[i++] = as_digit(n % b); \n n /= b; \n } \n s[i] = '\\0'; \n revstr(s);\n return s; \n} \n\null uabs(ull a, ull b) {\n return a > b ? a - b : b - a;\n}\n\nbool is_esthetic(ull n, int b) {\n int i, j;\n if (!n) return FALSE;\n i = n % b;\n n /= b;\n while (n) {\n j = n % b;\n if (uabs(i, j) != 1) return FALSE;\n n /= b;\n i = j;\n }\n return TRUE;\n}\n\null esths[45000];\nint le = 0;\n\nvoid dfs(ull n, ull m, ull i) {\n ull d, i1, i2;\n if (i >= n && i <= m) esths[le++] = i;\n if (i == 0 || i > m) return; \n d = i % 10;\n i1 = i * 10 + d - 1;\n i2 = i1 + 2;\n if (d == 0) {\n dfs(n, m, i2);\n } else if (d == 9) {\n dfs(n, m, i1);\n } else {\n dfs(n, m, i1);\n dfs(n, m, i2);\n }\n}\n\nvoid list_esths(ull n, ull n2, ull m, ull m2, int per_line, bool all) {\n int i;\n le = 0;\n for (i = 0; i < 10; ++i) {\n dfs(n2, m2, i);\n }\n printf(\"Base 10: %'d esthetic numbers between %'llu and %'llu:\\n\", le, n, m);\n if (all) {\n for (i = 0; i < le; ++i) {\n printf(\"%llu \", esths[i]);\n if (!(i+1)%per_line) printf(\"\\n\");\n }\n } else {\n for (i = 0; i < per_line; ++i) printf(\"%llu \", esths[i]);\n printf(\"\\n............\\n\");\n for (i = le - per_line; i < le; ++i) printf(\"%llu \", esths[i]);\n }\n printf(\"\\n\\n\");\n}\n\nint main() {\n ull n;\n int b, c;\n char ch[15] = {0};\n for (b = 2; b <= 16; ++b) {\n printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4*b, 6*b);\n for (n = 1, c = 0; c < 6 * b; ++n) {\n if (is_esthetic(n, b)) {\n if (++c >= 4 * b) printf(\"%s \", to_base(ch, n, b));\n }\n }\n printf(\"\\n\\n\");\n }\n char *oldLocale = setlocale(LC_NUMERIC, NULL);\n setlocale(LC_NUMERIC, \"\"); \n\n // the following all use the obvious range limitations for the numbers in question\n list_esths(1000, 1010, 9999, 9898, 16, TRUE);\n list_esths(1e8, 101010101, 13*1e7, 123456789, 9, TRUE);\n list_esths(1e11, 101010101010, 13*1e10, 123456789898, 7, FALSE);\n list_esths(1e14, 101010101010101, 13*1e13, 123456789898989, 5, FALSE);\n list_esths(1e17, 101010101010101010, 13*1e16, 123456789898989898, 4, FALSE);\n setlocale(LC_NUMERIC, oldLocale);\n return 0;\n}"} +{"title": "Esthetic numbers", "language": "JavaScript", "task": "An '''esthetic number''' is a positive integer where every adjacent digit differs from its neighbour by 1.\n\n\n;E.G.\n\n:* '''12''' is an esthetic number. One and two differ by 1.\n\n:* '''5654''' is an esthetic number. Each digit is exactly 1 away from its neighbour.\n\n:* '''890''' is '''not''' an esthetic number. Nine and zero differ by 9.\n\n\nThese examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers ''are'' included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.\n\nEsthetic numbers are also sometimes referred to as stepping numbers.\n\n\n;Task\n\n:* Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.\n\n:* Use that routine to find esthetic numbers in bases '''2''' through '''16''' and display, here on this page, the esthectic numbers from index '''(base \u00d7 4)''' through index '''(base \u00d7 6)''', inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)\n\n:* Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1000''' and '''9999'''.\n\n:* Stretch: Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1.0e8''' and '''1.3e8'''.\n\n\n;Related task:\n* \u00a0 numbers with equal rises and falls\n\n\n;See also:\n:;*OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1\n:;*[http://www.numbersaplenty.com/set/esthetic_number/ Numbers Aplenty - Esthetic numbers]\n:;*[https://www.geeksforgeeks.org/stepping-numbers/ Geeks for Geeks - Stepping numbers]\n\n", "solution": "function isEsthetic(inp, base = 10) {\n let arr = inp.toString(base).split('');\n if (arr.length == 1) return false;\n for (let i = 0; i < arr.length; i++)\n arr[i] = parseInt(arr[i], base);\n for (i = 0; i < arr.length-1; i++)\n if (Math.abs(arr[i]-arr[i+1]) !== 1) return false;\n return true;\n}\n\nfunction collectEsthetics(base, range) {\n let out = [], x;\n if (range) {\n for (x = range[0]; x < range[1]; x++)\n if (isEsthetic(x)) out.push(x);\n return out;\n } else {\n x = 1;\n while (out.length < base*6) {\n s = x.toString(base);\n if (isEsthetic(s, base)) out.push(s.toUpperCase());\n x++;\n }\n return out.slice(base*4);\n }\n}\n\n// main\nlet d = new Date();\nfor (let x = 2; x <= 36; x++) { // we put b17 .. b36 on top, because we can\n console.log(`${x}:`);\n console.log( collectEsthetics(x),\n (new Date() - d) / 1000 + ' s');\n}\nconsole.log( collectEsthetics(10, [1000, 9999]),\n (new Date() - d) / 1000 + ' s' );\n\nconsole.log( collectEsthetics(10, [1e8, 1.3e8]),\n (new Date() - d) / 1000 + ' s' );"} +{"title": "Esthetic numbers", "language": "Python 3.9.5", "task": "An '''esthetic number''' is a positive integer where every adjacent digit differs from its neighbour by 1.\n\n\n;E.G.\n\n:* '''12''' is an esthetic number. One and two differ by 1.\n\n:* '''5654''' is an esthetic number. Each digit is exactly 1 away from its neighbour.\n\n:* '''890''' is '''not''' an esthetic number. Nine and zero differ by 9.\n\n\nThese examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers ''are'' included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.\n\nEsthetic numbers are also sometimes referred to as stepping numbers.\n\n\n;Task\n\n:* Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.\n\n:* Use that routine to find esthetic numbers in bases '''2''' through '''16''' and display, here on this page, the esthectic numbers from index '''(base \u00d7 4)''' through index '''(base \u00d7 6)''', inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)\n\n:* Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1000''' and '''9999'''.\n\n:* Stretch: Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1.0e8''' and '''1.3e8'''.\n\n\n;Related task:\n* \u00a0 numbers with equal rises and falls\n\n\n;See also:\n:;*OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1\n:;*[http://www.numbersaplenty.com/set/esthetic_number/ Numbers Aplenty - Esthetic numbers]\n:;*[https://www.geeksforgeeks.org/stepping-numbers/ Geeks for Geeks - Stepping numbers]\n\n", "solution": "from collections import deque\nfrom itertools import dropwhile, islice, takewhile\nfrom textwrap import wrap\nfrom typing import Iterable, Iterator\n\n\nDigits = str # Alias for the return type of to_digits()\n\n\ndef esthetic_nums(base: int) -> Iterator[int]:\n \"\"\"Generate the esthetic number sequence for a given base\n\n >>> list(islice(esthetic_nums(base=10), 20))\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 21, 23, 32, 34, 43, 45, 54, 56, 65]\n \"\"\"\n queue: deque[tuple[int, int]] = deque()\n queue.extendleft((d, d) for d in range(1, base))\n while True:\n num, lsd = queue.pop()\n yield num\n new_lsds = (d for d in (lsd - 1, lsd + 1) if 0 <= d < base)\n num *= base # Shift num left one digit\n queue.extendleft((num + d, d) for d in new_lsds)\n\n\ndef to_digits(num: int, base: int) -> Digits:\n \"\"\"Return a representation of an integer as digits in a given base\n\n >>> to_digits(0x3def84f0ce, base=16)\n '3def84f0ce'\n \"\"\"\n digits: list[str] = []\n while num:\n num, d = divmod(num, base)\n digits.append(\"0123456789abcdef\"[d])\n return \"\".join(reversed(digits)) if digits else \"0\"\n\n\ndef pprint_it(it: Iterable[str], indent: int = 4, width: int = 80) -> None:\n \"\"\"Pretty print an iterable which returns strings\n\n >>> pprint_it(map(str, range(20)), indent=0, width=40)\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,\n 12, 13, 14, 15, 16, 17, 18, 19\n \n \"\"\"\n joined = \", \".join(it)\n lines = wrap(joined, width=width - indent)\n for line in lines:\n print(f\"{indent*' '}{line}\")\n print()\n\n\ndef task_2() -> None:\n nums: Iterator[int]\n for base in range(2, 16 + 1):\n start, stop = 4 * base, 6 * base\n nums = esthetic_nums(base)\n nums = islice(nums, start - 1, stop) # start and stop are 1-based indices\n print(\n f\"Base-{base} esthetic numbers from \"\n f\"index {start} through index {stop} inclusive:\\n\"\n )\n pprint_it(to_digits(num, base) for num in nums)\n\n\ndef task_3(lower: int, upper: int, base: int = 10) -> None:\n nums: Iterator[int] = esthetic_nums(base)\n nums = dropwhile(lambda num: num < lower, nums)\n nums = takewhile(lambda num: num <= upper, nums)\n print(\n f\"Base-{base} esthetic numbers with \"\n f\"magnitude between {lower:,} and {upper:,}:\\n\"\n )\n pprint_it(to_digits(num, base) for num in nums)\n\n\nif __name__ == \"__main__\":\n print(\"======\\nTask 2\\n======\\n\")\n task_2()\n\n print(\"======\\nTask 3\\n======\\n\")\n task_3(1_000, 9_999)\n\n print(\"======\\nTask 4\\n======\\n\")\n task_3(100_000_000, 130_000_000)\n\n"} +{"title": "Euclid-Mullin sequence", "language": "Python", "task": ";Definition\nThe [https://en.wikipedia.org/wiki/Euclid%E2%80%93Mullin_sequence Euclid\u2013Mullin sequence] is an infinite sequence of distinct prime numbers, in which each element is the least prime factor of one plus the product of all earlier elements. \n\nThe first element is usually assumed to be 2. So the second element is : (2) + 1 = 3 and the third element is : (2 x 3) + 1 = 7 as this is prime.\n\nAlthough intermingled with smaller elements, the sequence can produce very large elements quite quickly and only the first 51 have been computed at the time of writing.\n\n;Task\nCompute and show here the first '''16''' elements of the sequence or, if your language does not support arbitrary precision arithmetic, as many as you can.\n\n;Stretch goal\nCompute the next '''11''' elements of the sequence.\n\n;Reference\n[https://oeis.org/A000945 OEIS sequence A000945]\n\n", "solution": "\"\"\" Rosetta code task: Euclid-Mullin_sequence \"\"\"\n\nfrom primePy import primes\n\ndef euclid_mullin():\n \"\"\" generate Euclid-Mullin sequence \"\"\"\n total = 1\n while True:\n next_iter = primes.factor(total + 1)\n total *= next_iter\n yield next_iter\n\nGEN = euclid_mullin()\nprint('First 16 Euclid-Mullin numbers:', ', '.join(str(next(GEN)) for _ in range(16)))\n"} +{"title": "Euler's identity", "language": "C", "task": "In 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 = \u22121, 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 identity", "language": "Python", "task": "In 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 = \u22121, 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": ">>> import math\n>>> math.e ** (math.pi * 1j) + 1\n1.2246467991473532e-16j"} +{"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 [http://www.ams.org/journals/mcom/1967-21-097/S0025-5718-1967-0220669-3/S0025-5718-1967-0220669-3.pdf 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": "The trick to speed up was the observation that for any x we have x^5=x modulo 2, 3, and 5, according to the Fermat's little theorem. Thus, based on the Chinese Remainder Theorem we have x^5==x modulo 30 for any x. Therefore, when we have computed the left sum s=a^5+b^5+c^5+d^5, then we know that the right side e^5 must be such that s==e modulo 30. Thus, we do not have to consider all values of e, but only values in the form e=e0+30k, for some starting value e0, and any k. Also, we follow the constraints 1<=a// 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}\n"} +{"title": "Euler's sum of powers conjecture", "language": "JavaScript", "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 [http://www.ams.org/journals/mcom/1967-21-097/S0025-5718-1967-0220669-3/S0025-5718-1967-0220669-3.pdf 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": "var eulers_sum_of_powers = function (iMaxN) {\n\n var aPow5 = [];\n var oPow5ToN = {};\n\n for (var iP = 0; iP <= iMaxN; iP++) {\n var iPow5 = Math.pow(iP, 5);\n aPow5.push(iPow5);\n oPow5ToN[iPow5] = iP;\n }\n\n for (var i0 = 1; i0 <= iMaxN; i0++) {\n for (var i1 = 1; i1 <= i0; i1++) {\n for (var i2 = 1; i2 <= i1; i2++) {\n for (var i3 = 1; i3 <= i2; i3++) {\n var iPow5Sum = aPow5[i0] + aPow5[i1] + aPow5[i2] + aPow5[i3];\n if (typeof oPow5ToN[iPow5Sum] != 'undefined') {\n return {\n i0: i0,\n i1: i1,l\n i2: i2,\n i3: i3,\n iSum: oPow5ToN[iPow5Sum]\n };\n }\n }\n }\n }\n }\n\n};\n\nvar oResult = eulers_sum_of_powers(250);\n\nconsole.log(oResult.i0 + '^5 + ' + oResult.i1 + '^5 + ' + oResult.i2 +\n '^5 + ' + oResult.i3 + '^5 = ' + oResult.iSum + '^5');"} +{"title": "Euler's sum of powers conjecture", "language": "Python", "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 [http://www.ams.org/journals/mcom/1967-21-097/S0025-5718-1967-0220669-3/S0025-5718-1967-0220669-3.pdf 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": "def eulers_sum_of_powers():\n max_n = 250\n pow_5 = [n**5 for n in range(max_n)]\n pow5_to_n = {n**5: n for n in range(max_n)}\n for x0 in range(1, max_n):\n for x1 in range(1, x0):\n for x2 in range(1, x1):\n for x3 in range(1, x2):\n pow_5_sum = sum(pow_5[i] for i in (x0, x1, x2, x3))\n if pow_5_sum in pow5_to_n:\n y = pow5_to_n[pow_5_sum]\n return (x0, x1, x2, x3, y)\n\nprint(\"%i**5 + %i**5 + %i**5 + %i**5 == %i**5\" % eulers_sum_of_powers())"} +{"title": "Even or odd", "language": "C", "task": ";Task:\nTest 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'' \u2261 0 (mod 2) iff ''i'' is even.\n** ''i'' \u2261 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": "Even or odd", "language": "JavaScript", "task": ";Task:\nTest 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'' \u2261 0 (mod 2) iff ''i'' is even.\n** ''i'' \u2261 1 (mod 2) iff ''i'' is odd.\n\n", "solution": "(() => {\n 'use strict';\n\n // even : Integral a => a -> Bool\n const even = x => (x % 2) === 0;\n\n // odd : Integral a => a -> Bool\n const odd = x => !even(x);\n\n\n // TEST ----------------------------------------\n // range :: Int -> Int -> [Int]\n const range = (m, n) =>\n Array.from({\n length: Math.floor(n - m) + 1\n }, (_, i) => m + i);\n\n // show :: a -> String\n const show = JSON.stringify;\n\n // xs :: [Int]\n const xs = range(-6, 6);\n\n return show([xs.filter(even), xs.filter(odd)]);\n})();"} +{"title": "Even or odd", "language": "Python", "task": ";Task:\nTest 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'' \u2261 0 (mod 2) iff ''i'' is even.\n** ''i'' \u2261 1 (mod 2) iff ''i'' is odd.\n\n", "solution": ">>> def is_odd(i): return bool(i & 1)\n\n>>> def is_even(i): return not is_odd(i)\n\n>>> [(j, is_odd(j)) for j in range(10)]\n[(0, False), (1, True), (2, False), (3, True), (4, False), (5, True), (6, False), (7, True), (8, False), (9, True)]\n>>> [(j, is_even(j)) for j in range(10)]\n[(0, True), (1, False), (2, True), (3, False), (4, True), (5, False), (6, True), (7, False), (8, True), (9, False)]\n>>> "} +{"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 \u2018closeness\u2019 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* \u00a0 Wikipedia entry: \u00a0 Weasel algorithm.\n* \u00a0 Wikipedia entry: \u00a0 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": "Evolutionary algorithm", "language": "JavaScript", "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 \u2018closeness\u2019 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* \u00a0 Wikipedia entry: \u00a0 Weasel algorithm.\n* \u00a0 Wikipedia entry: \u00a0 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": "// ------------------------------------- Cross-browser Compatibility -------------------------------------\n\n/* Compatibility code to reduce an array\n * Source: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/Reduce\n */\nif (!Array.prototype.reduce) {\n Array.prototype.reduce = function (fun /*, initialValue */ ) {\n \"use strict\";\n\n if (this === void 0 || this === null) throw new TypeError();\n\n var t = Object(this);\n var len = t.length >>> 0;\n if (typeof fun !== \"function\") throw new TypeError();\n\n // no value to return if no initial value and an empty array\n if (len == 0 && arguments.length == 1) throw new TypeError();\n\n var k = 0;\n var accumulator;\n if (arguments.length >= 2) {\n accumulator = arguments[1];\n } else {\n do {\n if (k in t) {\n accumulator = t[k++];\n break;\n }\n\n // if array contains no values, no initial value to return\n if (++k >= len) throw new TypeError();\n }\n while (true);\n }\n\n while (k < len) {\n if (k in t) accumulator = fun.call(undefined, accumulator, t[k], k, t);\n k++;\n }\n\n return accumulator;\n };\n}\n\n/* Compatibility code to map an array\n * Source: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/Map\n */\nif (!Array.prototype.map) {\n Array.prototype.map = function (fun /*, thisp */ ) {\n \"use strict\";\n\n if (this === void 0 || this === null) throw new TypeError();\n\n var t = Object(this);\n var len = t.length >>> 0;\n if (typeof fun !== \"function\") throw new TypeError();\n\n var res = new Array(len);\n var thisp = arguments[1];\n for (var i = 0; i < len; i++) {\n if (i in t) res[i] = fun.call(thisp, t[i], i, t);\n }\n\n return res;\n };\n}\n\n/* ------------------------------------- Generator -------------------------------------\n * Generates a fixed length gene sequence via a gene strategy object.\n * The gene strategy object must have two functions:\n *\t- \"create\": returns create a new gene \n *\t- \"mutate(existingGene)\": returns mutation of an existing gene \n */\nfunction Generator(length, mutationRate, geneStrategy) {\n this.size = length;\n this.mutationRate = mutationRate;\n this.geneStrategy = geneStrategy;\n}\n\nGenerator.prototype.spawn = function () {\n var genes = [],\n x;\n for (x = 0; x < this.size; x += 1) {\n genes.push(this.geneStrategy.create());\n }\n return genes;\n};\n\nGenerator.prototype.mutate = function (parent) {\n return parent.map(function (char) {\n if (Math.random() > this.mutationRate) {\n return char;\n }\n return this.geneStrategy.mutate(char);\n }, this);\n};\n\n/* ------------------------------------- Population -------------------------------------\n * Helper class that holds and spawns a new population.\n */\nfunction Population(size, generator) {\n this.size = size;\n this.generator = generator;\n\n this.population = [];\n // Build initial popuation;\n for (var x = 0; x < this.size; x += 1) {\n this.population.push(this.generator.spawn());\n }\n}\n\nPopulation.prototype.spawn = function (parent) {\n this.population = [];\n for (var x = 0; x < this.size; x += 1) {\n this.population.push(this.generator.mutate(parent));\n }\n};\n\n/* ------------------------------------- Evolver -------------------------------------\n * Attempts to converge a population based a fitness strategy object.\n * The fitness strategy object must have three function \n *\t- \"score(individual)\": returns a score for an individual.\n *\t- \"compare(scoreA, scoreB)\": return true if scoreA is better (ie more fit) then scoreB\n *\t- \"done( score )\": return true if score is acceptable (ie we have successfully converged). \n */\nfunction Evolver(size, generator, fitness) {\n this.done = false;\n this.fitness = fitness;\n this.population = new Population(size, generator);\n}\n\nEvolver.prototype.getFittest = function () {\n return this.population.population.reduce(function (best, individual) {\n var currentScore = this.fitness.score(individual);\n if (best === null || this.fitness.compare(currentScore, best.score)) {\n return {\n score: currentScore,\n individual: individual\n };\n } else {\n return best;\n }\n }, null);\n};\n\nEvolver.prototype.doGeneration = function () {\n this.fittest = this.getFittest();\n this.done = this.fitness.done(this.fittest.score);\n if (!this.done) {\n this.population.spawn(this.fittest.individual);\n }\n};\n\nEvolver.prototype.run = function (onCheckpoint, checkPointFrequency) {\n checkPointFrequency = checkPointFrequency || 10; // Default to Checkpoints every 10 generations\n var generation = 0;\n while (!this.done) {\n this.doGeneration();\n if (generation % checkPointFrequency === 0) {\n onCheckpoint(generation, this.fittest);\n }\n generation += 1;\n }\n onCheckpoint(generation, this.fittest);\n return this.fittest;\n};\n\n// ------------------------------------- Exports -------------------------------------\nwindow.Generator = Generator;\nwindow.Evolver = Evolver;\n\n\n// helper utitlity to combine elements of two arrays.\nArray.prototype.zip = function (b, func) {\n var result = [],\n max = Math.max(this.length, b.length),\n x;\n for (x = 0; x < max; x += 1) {\n result.push(func(this[x], b[x]));\n }\n return result;\n};\n\nvar target = \"METHINKS IT IS LIKE A WEASEL\", geneStrategy, fitness, target, generator, evolver, result;\n \ngeneStrategy = {\n // The allowed character set (as an array) \n characterSet: \"ABCDEFGHIJKLMNOPQRSTUVWXYZ \".split(\"\"),\n\n /*\n Pick a random character from the characterSet\n */\n create: function getRandomGene() {\n var randomNumber = Math.floor(Math.random() * this.characterSet.length);\n return this.characterSet[randomNumber];\n }\n};\ngeneStrategy.mutate = geneStrategy.create; // Our mutation stragtegy is to simply get a random gene\nfitness = {\n // The target (as an array of characters)\n target: target.split(\"\"),\n equal: function (geneA, geneB) {\n return (geneA === geneB ? 0 : 1);\n },\n sum: function (runningTotal, value) {\n return runningTotal + value;\n },\n\n /*\n We give one point to for each corect letter\n */\n score: function (genes) {\n var diff = genes.zip(this.target, this.equal); // create an array of ones and zeros \n return diff.reduce(this.sum, 0); // Sum the array values together.\n },\n compare: function (scoreA, scoreB) {\n return scoreA <= scoreB; // Lower scores are better\n },\n done: function (score) {\n return score === 0; // We have matched the target string.\n }\n};\n\ngenerator = new Generator(target.length, 0.05, geneStrategy);\nevolver = new Evolver(100, generator, fitness);\n\nfunction showProgress(generation, fittest) {\n document.write(\"Generation: \" + generation + \", Best: \" + fittest.individual.join(\"\") + \", fitness:\" + fittest.score + \"\");\n}\nresult = evolver.run(showProgress);"} +{"title": "Evolutionary algorithm", "language": "Python", "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 \u2018closeness\u2019 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* \u00a0 Wikipedia entry: \u00a0 Weasel algorithm.\n* \u00a0 Wikipedia entry: \u00a0 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": "from string import letters\nfrom random import choice, random\n \ntarget = list(\"METHINKS IT IS LIKE A WEASEL\")\ncharset = letters + ' '\nparent = [choice(charset) for _ in range(len(target))]\nminmutaterate = .09\nC = range(100)\n \nperfectfitness = float(len(target))\n \ndef fitness(trial):\n 'Sum of matching chars by position'\n return sum(t==h for t,h in zip(trial, target))\n \ndef mutaterate():\n 'Less mutation the closer the fit of the parent'\n return 1-((perfectfitness - fitness(parent)) / perfectfitness * (1 - minmutaterate))\n \ndef mutate(parent, rate):\n return [(ch if random() <= rate else choice(charset)) for ch in parent]\n \ndef que():\n '(from the favourite saying of Manuel in Fawlty Towers)'\n print (\"#%-4i, fitness: %4.1f%%, '%s'\" %\n (iterations, fitness(parent)*100./perfectfitness, ''.join(parent)))\n\ndef mate(a, b):\n place = 0\n if choice(xrange(10)) < 7:\n place = choice(xrange(len(target)))\n else:\n return a, b\n \n return a, b, a[:place] + b[place:], b[:place] + a[place:]\n\niterations = 0\ncenter = len(C)/2\nwhile parent != target:\n rate = mutaterate()\n iterations += 1\n if iterations % 100 == 0: que()\n copies = [ mutate(parent, rate) for _ in C ] + [parent]\n parent1 = max(copies[:center], key=fitness)\n parent2 = max(copies[center:], key=fitness)\n parent = max(mate(parent1, parent2), key=fitness)\nque()"} +{"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 \u2264 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": "Executable library", "language": "Python", "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 \u2264 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": "from collections import Counter\n\ndef function_length_frequency(func, hrange):\n return Counter(len(func(n)) for n in hrange).most_common()\n\nif __name__ == '__main__':\n from executable_hailstone_library import hailstone\n\n upto = 100000\n hlen, freq = function_length_frequency(hailstone, range(1, upto))[0]\n print(\"The length of hailstone sequence that is most common for\\n\"\n \"hailstone(n) where 1<=n<%i, is %i. It occurs %i times.\"\n % (upto, hlen, freq))"} +{"title": "Execute Computer/Zero", "language": "Python", "task": ";Task:\nCreate a [[Computer/zero Assembly]] emulator. You may consider [http://edmundgriffiths.com/czero.html this webpage] as a reference implementation. Output the results of the sample programs \"2+2\" and \"7*8\" found there.\n\n:* \u00a0 The virtual machine \"bytecode\" needs to be able to modify itself (or at least act as though it can) while the virtual machine is running, to be consistent with the reference implementation.\n:* \u00a0 For output, it is sufficient to have the implementation of the STP opcode return the accumulator to your actual language, and then use your standard printing routines to output it.\n\n;Bonus Points: Run all 5 sample programs at the aforementioned website and output their results.\n\n\n\n", "solution": "\"\"\"Computer/zero Assembly emulator. Requires Python >= 3.7\"\"\"\n\nimport re\n\nfrom typing import Dict\nfrom typing import Iterable\nfrom typing import List\nfrom typing import NamedTuple\nfrom typing import Optional\nfrom typing import Tuple\n\n\nNOP = 0b000\nLDA = 0b001\nSTA = 0b010\nADD = 0b011\nSUB = 0b100\nBRZ = 0b101\nJMP = 0b110\nSTP = 0b111\n\nOPCODES = {\n \"NOP\": NOP,\n \"LDA\": LDA,\n \"STA\": STA,\n \"ADD\": ADD,\n \"SUB\": SUB,\n \"BRZ\": BRZ,\n \"JMP\": JMP,\n \"STP\": STP,\n}\n\nRE_INSTRUCTION = re.compile(\n r\"\\s*\"\n r\"(?:(?P\\w+):)?\"\n r\"\\s*\"\n rf\"(?P{'|'.join(OPCODES)})?\"\n r\"\\s*\"\n r\"(?P\\w+)?\"\n r\"\\s*\"\n r\"(?:;(?P[\\w\\s]+))?\"\n)\n\n\nclass AssemblySyntaxError(Exception):\n pass\n\n\nclass Instruction(NamedTuple):\n label: Optional[str]\n opcode: Optional[str]\n argument: Optional[str]\n comment: Optional[str]\n\n\ndef parse(assembly: str) -> Tuple[List[Instruction], Dict[str, int]]:\n instructions: List[Instruction] = []\n labels: Dict[str, int] = {}\n linenum: int = 0\n\n for line in assembly.split(\"\\n\"):\n match = RE_INSTRUCTION.match(line)\n\n if not match:\n raise AssemblySyntaxError(f\"{line}: {linenum}\")\n\n instructions.append(Instruction(**match.groupdict()))\n label = match.group(1)\n if label:\n labels[label] = linenum\n\n linenum += 1\n\n return instructions, labels\n\n\ndef compile(instructions: List[Instruction], labels: Dict[str, int]) -> Iterable[int]:\n for instruction in instructions:\n if instruction.argument is None:\n argument = 0\n elif instruction.argument.isnumeric():\n argument = int(instruction.argument)\n else:\n argument = labels[instruction.argument]\n\n if instruction.opcode:\n yield OPCODES[instruction.opcode] << 5 | argument\n else:\n yield argument\n\n\ndef run(bytecode: bytes) -> int:\n accumulator = 0\n program_counter = 0\n memory = list(bytecode)[:32] + [0 for _ in range(32 - len(bytecode))]\n\n while program_counter < 32:\n operation = memory[program_counter] >> 5\n argument = memory[program_counter] & 0b11111\n program_counter += 1\n\n if operation == NOP:\n continue\n elif operation == LDA:\n accumulator = memory[argument]\n elif operation == STA:\n memory[argument] = accumulator\n elif operation == ADD:\n accumulator = (accumulator + memory[argument]) % 256\n elif operation == SUB:\n accumulator = (accumulator - memory[argument]) % 256\n elif operation == BRZ:\n if accumulator == 0:\n program_counter = argument\n elif operation == JMP:\n program_counter = argument\n elif operation == STP:\n break\n else:\n raise Exception(f\"error: {operation} {argument}\")\n\n return accumulator\n\n\nSAMPLES = [\n \"\"\"\\\n LDA x\n ADD y ; accumulator = x + y\n STP\n x: 2\n y: 2\n \"\"\",\n \"\"\"\\\n loop: LDA prodt\n ADD x\n STA prodt\n LDA y\n SUB one\n STA y\n BRZ done\n JMP loop\n done: LDA prodt ; to display it\n STP\n x: 8\n y: 7\n prodt: 0\n one: 1\n \"\"\",\n \"\"\"\\\n loop: LDA n\n STA temp\n ADD m\n STA n\n LDA temp\n STA m\n LDA count\n SUB one\n BRZ done\n STA count\n JMP loop\n done: LDA n ; to display it\n STP\n m: 1\n n: 1\n temp: 0\n count: 8 ; valid range: 1-11\n one: 1\n \"\"\",\n \"\"\"\\\n start: LDA load\n ADD car ; head of list\n STA ldcar\n ADD one\n STA ldcdr ; next CONS cell\n ldcar: NOP\n STA value\n ldcdr: NOP\n BRZ done ; 0 stands for NIL\n STA car\n JMP start\n done: LDA value ; CAR of last CONS\n STP\n load: LDA 0\n value: 0\n car: 28\n one: 1\n ; order of CONS cells\n ; in memory\n ; does not matter\n 6\n 0 ; 0 stands for NIL\n 2 ; (CADR ls)\n 26 ; (CDDR ls) -- etc.\n 5\n 20\n 3\n 30\n 1 ; value of (CAR ls)\n 22 ; points to (CDR ls)\n 4\n 24\n \"\"\",\n \"\"\"\\\n p: 0 ; NOP in first round\n c: 0\n start: STP ; wait for p's move\n pmove: NOP\n LDA pmove\n SUB cmove\n BRZ same\n LDA pmove\n STA cmove ; tit for tat\n BRZ cdeft\n LDA c ; p defected, c did not\n ADD three\n STA c\n JMP start\n cdeft: LDA p\n ADD three\n STA p\n JMP start\n same: LDA pmove\n STA cmove ; tit for tat\n LDA p\n ADD one\n ADD pmove\n STA p\n LDA c\n ADD one\n ADD pmove\n STA c\n JMP start\n cmove: 0 ; co-operate initially\n one: 1\n three: 3\n \"\"\",\n \"\"\"\\\n LDA 3\n SUB 4\n STP 0\n 0\n 255\n \"\"\",\n \"\"\"\\\n LDA 3\n SUB 4\n STP 0\n 0\n 1\n \"\"\",\n \"\"\"\\\n LDA 3\n ADD 4\n STP 0\n 1\n 255\n \"\"\",\n]\n\n\ndef main() -> None:\n for sample in SAMPLES:\n instructions, labels = parse(sample)\n bytecode = bytes(compile(instructions, labels))\n result = run(bytecode)\n print(result)\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"title": "Execute HQ9+", "language": "C", "task": ";Task:\nImplement a \u00a0 ''' [[HQ9+]] ''' \u00a0 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": "Execute HQ9+", "language": "JavaScript", "task": ";Task:\nImplement a \u00a0 ''' [[HQ9+]] ''' \u00a0 interpreter or compiler.\n\n", "solution": "function hq9plus(code) {\n var out = '';\n var acc = 0;\n \n for (var i=0; i1; j--) {\n out += j + \" bottles of beer on the wall, \" + j + \" bottles of beer.\\n\";\n out += \"Take one down and pass it around, \" + (j-1) + \" bottles of beer.\\n\\n\";\n }\n out += \"1 bottle of beer on the wall, 1 bottle of beer.\\n\" +\n \"Take one down and pass it around, no more bottles of beer on the wall.\\n\\n\" +\n \"No more bottles of beer on the wall, no more bottles of beer.\\n\" +\n \"Go to the store and buy some more, 99 bottles of beer on the wall.\\n\";\n break;\n case '+': acc++; break;\n }\n }\n return out;\n}"} +{"title": "Execute SNUSP", "language": "Python", "task": "An implementation need only properly implement the Core SNUSP instructions ('$', '\\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not required. Any extra characters that you implement should be noted in the description of your implementation. Any cell size is allowed, EOF support is optional, as is whether you have bounded or unbounded memory.\n\n", "solution": "#!/usr/bin/env python3\n\nHW = r'''\n/++++!/===========?\\>++.>+.+++++++..+++\\\n\\+++\\ | /+>+++++++>/ /++++++++++<<.++>./\n$+++/ | \\+++++++++>\\ \\+++++.>.+++.-----\\\n \\==-<<<<+>+++/ /=.>.+>.--------.-/'''\n\ndef snusp(store, code):\n ds = bytearray(store) # data store\n dp = 0 # data pointer\n cs = code.splitlines() # 2 dimensional code store\n ipr, ipc = 0, 0 # instruction pointers in row and column\n for r, row in enumerate(cs):\n try:\n ipc = row.index('$')\n ipr = r\n break\n except ValueError:\n pass\n rt, dn, lt, up = range(4)\n id = rt # instruction direction. starting direction is always rt\n def step():\n nonlocal ipr, ipc\n if id&1:\n ipr += 1 - (id&2)\n else:\n ipc += 1 - (id&2)\n while ipr >= 0 and ipr < len(cs) and ipc >= 0 and ipc < len(cs[ipr]):\n op = cs[ipr][ipc]\n if op == '>':\n dp += 1\n elif op == '<':\n dp -= 1\n elif op == '+':\n ds[dp] += 1\n elif op == '-':\n ds[dp] -= 1\n elif op == '.':\n print(chr(ds[dp]), end='')\n elif op == ',':\n ds[dp] = input()\n elif op == '/':\n id = ~id\n elif op == '\\\\':\n id ^= 1\n elif op == '!':\n step()\n elif op == '?':\n if not ds[dp]:\n step()\n step()\n\nif __name__ == '__main__':\n snusp(5, HW)"} +{"title": "Exponentiation order", "language": "C", "task": "This task will demonstrate the order of exponentiation \u00a0 ('''xy''') \u00a0 when there are multiple exponents.\n\n(Many programming languages, \u00a0 especially those with extended\u2500precision integer arithmetic, \u00a0 usually support one of **, ^, \u2191 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::::* \u00a0 5**3**2 \n::::* \u00a0 (5**3)**2\n::::* \u00a0 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: \u00a0 [http://mathworld.wolfram.com/Exponentiation.html exponentiation]\n\n\n;Related tasks:\n* \u00a0 exponentiation operator\n* \u00a0 arbitrary-precision integers (included)\n* \u00a0 [[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": "Exponentiation order", "language": "Python", "task": "This task will demonstrate the order of exponentiation \u00a0 ('''xy''') \u00a0 when there are multiple exponents.\n\n(Many programming languages, \u00a0 especially those with extended\u2500precision integer arithmetic, \u00a0 usually support one of **, ^, \u2191 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::::* \u00a0 5**3**2 \n::::* \u00a0 (5**3)**2\n::::* \u00a0 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: \u00a0 [http://mathworld.wolfram.com/Exponentiation.html exponentiation]\n\n\n;Related tasks:\n* \u00a0 exponentiation operator\n* \u00a0 arbitrary-precision integers (included)\n* \u00a0 [[Exponentiation with infix operators in (or operating on) the base]]\n\n", "solution": ">>> 5**3**2\n1953125\n>>> (5**3)**2\n15625\n>>> 5**(3**2)\n1953125\n>>> # The following is not normally done\n>>> try: from functools import reduce # Py3K\nexcept: pass\n\n>>> reduce(pow, (5, 3, 2))\n15625\n>>> "} +{"title": "Exponentiation with infix operators in (or operating on) the base", "language": "Python", "task": "(Many programming languages, \u00a0 especially those with extended\u2500precision integer arithmetic, \u00a0 usually\nsupport one of **, ^, \u2191 or some such for exponentiation.)\n\n\nSome languages treat/honor infix operators when performing exponentiation \u00a0 (raising\nnumbers to some power by the language's exponentiation operator, \u00a0 if the computer\nprogramming language has one).\n\n\nOther programming languages may make use of the \u00a0 '''POW''' \u00a0 or some other BIF\n\u00a0 ('''B'''uilt\u2500'''I'''n '''F'''function), \u00a0 or some other library service.\n\nIf your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.\n\n\nThis task will deal with the case where there is some form of an \u00a0 ''infix operator'' \u00a0 operating\nin \u00a0 (or operating on) \u00a0 the base.\n\n\n;Example:\nA negative five raised to the 3rd power could be specified as:\n -5 ** 3 or as\n -(5) ** 3 or as\n (-5) ** 3 or as something else\n\n\n(Not all computer programming languages have an exponential operator and/or support these syntax expression(s).\n\n\n;Task:\n:* \u00a0 compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.\n:* \u00a0 Raise the following numbers \u00a0 (integer or real):\n:::* \u00a0 -5 \u00a0 \u00a0 and\n:::* \u00a0 +5\n:* \u00a0 to the following powers:\n:::* \u00a0 2nd \u00a0 \u00a0 and\n:::* \u00a0 3rd\n:* \u00a0 using the following expressions \u00a0 (if applicable in your language):\n:::* \u00a0 -x**p\n:::* \u00a0 -(x)**p\n:::* \u00a0 (-x)**p\n:::* \u00a0 -(x**p)\n:* \u00a0 Show here (on this page) the four (or more) types of symbolic expressions for each number and power.\n\n\nTry to present the results in the same format/manner as the other programming entries to make any differences apparent.\n\n\nThe variables may be of any type(s) that is/are applicable in your language.\n\n\n;Related tasks:\n* \u00a0 [[Exponentiation order]]\n* \u00a0 [[Exponentiation operator]]\n* \u00a0 [[Arbitrary-precision integers (included)]]\n* \u00a0 [[Parsing/RPN to infix conversion]]\n* \u00a0 [[Operator precedence]]\n\n;References:\n* Wikipedia: Order of operations in Programming languages\n\n", "solution": "from itertools import product\n\nxx = '-5 +5'.split()\npp = '2 3'.split()\ntexts = '-x**p -(x)**p (-x)**p -(x**p)'.split()\n\nprint('Integer variable exponentiation')\nfor x, p in product(xx, pp):\n print(f' x,p = {x:2},{p}; ', end=' ')\n x, p = int(x), int(p)\n print('; '.join(f\"{t} =={eval(t):4}\" for t in texts))\n\nprint('\\nBonus integer literal exponentiation')\nX, P = 'xp'\nxx.insert(0, ' 5')\ntexts.insert(0, 'x**p')\nfor x, p in product(xx, pp):\n texts2 = [t.replace(X, x).replace(P, p) for t in texts]\n print(' ', '; '.join(f\"{t2} =={eval(t2):4}\" for t2 in texts2))"} +{"title": "Extend your language", "language": "C", "task": "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": "Extend your language", "language": "Python", "task": "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": "a, b = 1, 0\n\nif (c1 := a == 1) and (c2 := b == 3):\n print('a = 1 and b = 3')\nelif c1:\n print('a = 1 and b <> 3')\nelif c2:\n print('a <> 1 and b = 3')\nelse:\n print('a <> 1 and b <> 3')"} +{"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* \u00a0 [https://www.validlab.com/goldberg/paper.pdf What Every Computer Scientist Should Know About Floating-Point Arithmetic]\n\n\n;Related tasks:\n* \u00a0 [[Infinity]]\n* \u00a0 [[Detect division by zero]]\n* \u00a0 [[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": "Extreme floating point values", "language": "gcc 4.4.3", "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* \u00a0 [https://www.validlab.com/goldberg/paper.pdf What Every Computer Scientist Should Know About Floating-Point Arithmetic]\n\n\n;Related tasks:\n* \u00a0 [[Infinity]]\n* \u00a0 [[Detect division by zero]]\n* \u00a0 [[Literals/Floating point]]\n\n", "solution": "#include \n\nint main()\n{\n double inf = 1/0.0;\n double minus_inf = -1/0.0;\n double minus_zero = -1/ inf ;\n double nan = 0.0/0.0;\n\n printf(\"positive infinity: %f\\n\",inf);\n printf(\"negative infinity: %f\\n\",minus_inf);\n printf(\"negative zero: %f\\n\",minus_zero);\n printf(\"not a number: %f\\n\",nan);\n\n /* some arithmetic */\n\n printf(\"+inf + 2.0 = %f\\n\",inf + 2.0);\n printf(\"+inf - 10.1 = %f\\n\",inf - 10.1);\n printf(\"+inf + -inf = %f\\n\",inf + minus_inf);\n printf(\"0.0 * +inf = %f\\n\",0.0 * inf);\n printf(\"1.0/-0.0 = %f\\n\",1.0/minus_zero);\n printf(\"NaN + 1.0 = %f\\n\",nan + 1.0);\n printf(\"NaN + NaN = %f\\n\",nan + nan);\n\n /* some comparisons */\n\n printf(\"NaN == NaN = %s\\n\",nan == nan ? \"true\" : \"false\");\n printf(\"0.0 == -0.0 = %s\\n\",0.0 == minus_zero ? \"true\" : \"false\");\n\n return 0;\n}"} +{"title": "Extreme floating point values", "language": "Python", "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* \u00a0 [https://www.validlab.com/goldberg/paper.pdf What Every Computer Scientist Should Know About Floating-Point Arithmetic]\n\n\n;Related tasks:\n* \u00a0 [[Infinity]]\n* \u00a0 [[Detect division by zero]]\n* \u00a0 [[Literals/Floating point]]\n\n", "solution": ">>> # Extreme values from expressions\n>>> inf = 1e234 * 1e234\n>>> _inf = 1e234 * -1e234\n>>> _zero = 1 / _inf\n>>> nan = inf + _inf\n>>> inf, _inf, _zero, nan\n(inf, -inf, -0.0, nan)\n>>> # Print\n>>> for value in (inf, _inf, _zero, nan): print (value)\n\ninf\n-inf\n-0.0\nnan\n>>> # Extreme values from other means\n>>> float('nan')\nnan\n>>> float('inf')\ninf\n>>> float('-inf')\n-inf\n>>> -0.\n-0.0\n>>> # Some arithmetic\n>>> nan == nan\nFalse\n>>> nan is nan\nTrue\n>>> 0. == -0.\nTrue\n>>> 0. is -0.\nFalse\n>>> inf + _inf\nnan\n>>> 0.0 * nan\nnan\n>>> nan * 0.0\nnan\n>>> 0.0 * inf\nnan\n>>> inf * 0.0\nnan"} +{"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": "FASTA format", "language": "JavaScript", "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": "\nconst fs = require(\"fs\");\nconst readline = require(\"readline\");\n \nconst args = process.argv.slice(2);\nif (!args.length) {\n console.error(\"must supply file name\");\n process.exit(1);\n}\n \nconst fname = args[0];\n \nconst readInterface = readline.createInterface({\n input: fs.createReadStream(fname),\n console: false,\n});\n \nlet sep = \"\";\nreadInterface.on(\"line\", (line) => {\n if (line.startsWith(\">\")) {\n process.stdout.write(sep);\n sep = \"\\n\";\n process.stdout.write(line.substring(1) + \": \");\n } else {\n process.stdout.write(line);\n }\n});\n\nreadInterface.on(\"close\", () => process.stdout.write(\"\\n\"));\n"} +{"title": "FASTA format", "language": "Python", "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": "import io\n\nFASTA='''\\\n>Rosetta_Example_1\nTHERECANBENOSPACE\n>Rosetta_Example_2\nTHERECANBESEVERAL\nLINESBUTTHEYALLMUST\nBECONCATENATED'''\n\ninfile = io.StringIO(FASTA)\n\ndef fasta_parse(infile):\n key = ''\n for line in infile:\n if line.startswith('>'):\n if key:\n yield key, val\n key, val = line[1:].rstrip().split()[0], ''\n elif key:\n val += line.rstrip()\n if key:\n yield key, val\n\nprint('\\n'.join('%s: %s' % keyval for keyval in fasta_parse(infile)))"} +{"title": "Faces from a mesh", "language": "Python", "task": "A mesh defining a surface has uniquely numbered vertices, and named, \nsimple-polygonal faces described usually by an ordered list of edge numbers \ngoing around the face, \n\n\nFor example:\n[https://drive.google.com/file/d/1qNS_L0LGIKhoo-gmBLlyDGECtjp9l7x8/view External image of two faces]\nRough textual version without edges:\n\n\n 1 \n 17\n 7 A\n B\n\n 11 \n 23\n\n\n\n* A is the triangle (1, 11, 7), or equally (7, 11, 1), going anti-clockwise, or\nany of all the rotations of those ordered vertices.\n 1 \n \n 7 A\n \n\n 11\n\n* B is the four-sided face (1, 17, 23, 11), or equally (23, 17, 1, 11) or any \nof their rotations.\n1 \n 17\n\n B\n\n 11 \n 23\n\nLet's call the above the '''perimeter format''' as it traces around the perimeter.\n\n;A second format:\nA separate algorithm returns polygonal faces consisting of a face name and an unordered \nset of edge definitions for each face.\n* A single edge is described by the vertex numbers at its two ends, always in \nascending order.\n* All edges for the face are given, but in an undefined order.\n\nFor example face A could be described by the edges (1, 11), (7, 11), and (1, 7)\n(The order of each vertex number in an edge is ascending, but the order in \nwhich the edges are stated is arbitrary).\n\nSimilarly face B could be described by the edges (11, 23), (1, 17), (17, 23),\nand (1, 11) in arbitrary order of the edges. \n\nLet's call this second format the '''edge format'''.\n\n\n\n;Task:\n'''1.''' Write a routine to check if two perimeter formatted faces have the same perimeter. Use it to check if the following pairs of perimeters are the same:\n Q: (8, 1, 3)\n R: (1, 3, 8)\n\n U: (18, 8, 14, 10, 12, 17, 19)\n V: (8, 14, 10, 12, 17, 19, 18)\n\n'''2.''' Write a routine and use it to transform the following faces from edge to perimeter format.\n E: {(1, 11), (7, 11), (1, 7)}\n F: {(11, 23), (1, 17), (17, 23), (1, 11)}\n G: {(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)}\n H: {(1, 3), (9, 11), (3, 11), (1, 11)}\n\n\nShow your output here.\n\n", "solution": "def perim_equal(p1, p2):\n # Cheap tests first\n if len(p1) != len(p2) or set(p1) != set(p2):\n return False\n if any(p2 == (p1[n:] + p1[:n]) for n in range(len(p1))):\n return True\n p2 = p2[::-1] # not inplace\n return any(p2 == (p1[n:] + p1[:n]) for n in range(len(p1)))\n\ndef edge_to_periphery(e):\n edges = sorted(e)\n p = list(edges.pop(0)) if edges else []\n last = p[-1] if p else None\n while edges:\n for n, (i, j) in enumerate(edges):\n if i == last:\n p.append(j)\n last = j\n edges.pop(n)\n break\n elif j == last:\n p.append(i)\n last = i\n edges.pop(n)\n break\n else:\n #raise ValueError(f'Invalid edge format: {e}')\n return \">>>Error! Invalid edge format<<<\"\n return p[:-1]\n\nif __name__ == '__main__':\n print('Perimeter format equality checks:')\n for eq_check in [\n { 'Q': (8, 1, 3),\n 'R': (1, 3, 8)},\n { 'U': (18, 8, 14, 10, 12, 17, 19),\n 'V': (8, 14, 10, 12, 17, 19, 18)} ]:\n (n1, p1), (n2, p2) = eq_check.items()\n eq = '==' if perim_equal(p1, p2) else '!='\n print(' ', n1, eq, n2)\n\n print('\\nEdge to perimeter format translations:')\n edge_d = {\n 'E': {(1, 11), (7, 11), (1, 7)},\n 'F': {(11, 23), (1, 17), (17, 23), (1, 11)},\n 'G': {(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)},\n 'H': {(1, 3), (9, 11), (3, 11), (1, 11)}\n }\n for name, edges in edge_d.items():\n print(f\" {name}: {edges}\\n -> {edge_to_periphery(edges)}\")"} +{"title": "Factorial base numbers indexing permutations of a collection", "language": "Python", "task": "You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers.\nThe first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1.1.0, 1.1.1,1.2.0, 1.2.1, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.2.0, 2.2.1, 3.0.0, 3.0.1, 3.1.0, 3.1.1, 3.2.0, 3.2.1, 1.0.0.0\nObserve that the least significant digit is base 2 the next base 3, in general an n-digit factorial base number has digits n..1 in base n+1..2.\n\nI want to produce a 1 to 1 mapping between these numbers and permutations:-\n 0.0.0 -> 0123\n 0.0.1 -> 0132\n 0.1.0 -> 0213\n 0.1.1 -> 0231\n 0.2.0 -> 0312\n 0.2.1 -> 0321\n 1.0.0 -> 1023\n 1.0.1 -> 1032\n 1.1.0 -> 1203\n 1.1.1 -> 1230\n 1.2.0 -> 1302\n 1.2.1 -> 1320\n 2.0.0 -> 2013\n 2.0.1 -> 2031\n 2.1.0 -> 2103\n 2.1.1 -> 2130\n 2.2.0 -> 2301\n 2.2.1 -> 2310\n 3.0.0 -> 3012\n 3.0.1 -> 3021\n 3.1.0 -> 3102\n 3.1.1 -> 3120\n 3.2.0 -> 3201\n 3.2.1 -> 3210\n\nThe following psudo-code will do this:\nStarting with m=0 and \u03a9, an array of elements to be permutated, for each digit g starting with the most significant digit in the factorial base number.\n\nIf g is greater than zero, rotate the elements from m to m+g in \u03a9 (see example)\nIncrement m and repeat the first step using the next most significant digit until the factorial base number is exhausted.\nFor example: using the factorial base number 2.0.1 and \u03a9 = 0 1 2 3 where place 0 in both is the most significant (left-most) digit/element.\n\nStep 1: m=0 g=2; Rotate places 0 through 2. 0 1 2 3 becomes 2 0 1 3\nStep 2: m=1 g=0; No action.\nStep 3: m=2 g=1; Rotate places 2 through 3. 2 0 1 3 becomes 2 0 3 1\n\nLet me work 2.0.1 and 0123\n step 1 n=0 g=2 \u03a9=2013\n step 2 n=1 g=0 so no action\n step 3 n=2 g=1 \u03a9=2031\n\nThe task:\n\n First use your function to recreate the above table.\n Secondly use your function to generate all permutaions of 11 digits, perhaps count them don't display them, compare this method with\n methods in rc's permutations task.\n Thirdly here following are two ramdom 51 digit factorial base numbers I prepared earlier:\n 39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0\n 51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1\n use your function to crate the corresponding permutation of the following shoe of cards:\n A\u2660K\u2660Q\u2660J\u266010\u26609\u26608\u26607\u26606\u26605\u26604\u26603\u26602\u2660A\u2665K\u2665Q\u2665J\u266510\u26659\u26658\u26657\u26656\u26655\u26654\u26653\u26652\u2665A\u2666K\u2666Q\u2666J\u266610\u26669\u26668\u26667\u26666\u26665\u26664\u26663\u26662\u2666A\u2663K\u2663Q\u2663J\u266310\u26639\u26638\u26637\u26636\u26635\u26634\u26633\u26632\u2663\n Finally create your own 51 digit factorial base number and produce the corresponding permutation of the above shoe\n\n", "solution": "\n\"\"\"\n\nhttp://rosettacode.org/wiki/Factorial_base_numbers_indexing_permutations_of_a_collection\n\nhttps://en.wikipedia.org/wiki/Factorial_number_system\n\n\"\"\"\n\nimport math\n\ndef apply_perm(omega,fbn):\n \"\"\"\n \n omega contains a list which will be permuted (scrambled)\n based on fbm.\n \n fbm is a list which represents a factorial base number.\n \n This function just translates the pseudo code in the \n Rosetta Code task.\n \n \"\"\"\n for m in range(len(fbn)):\n g = fbn[m]\n if g > 0:\n # do rotation\n # save last number\n new_first = omega[m+g]\n # move numbers right\n omega[m+1:m+g+1] = omega[m:m+g]\n # put last number first\n omega[m] = new_first\n \n return omega\n \ndef int_to_fbn(i):\n \"\"\"\n \n convert integer i to factorial based number\n \n \"\"\"\n current = i\n divisor = 2\n new_fbn = []\n while current > 0:\n remainder = current % divisor\n current = current // divisor\n new_fbn.append(remainder)\n divisor += 1\n \n return list(reversed(new_fbn))\n \ndef leading_zeros(l,n):\n \"\"\"\n \n If list l has less than n elements returns l with enough 0 elements\n in front of the list to make it length n.\n \n \"\"\"\n if len(l) < n:\n return(([0] * (n - len(l))) + l)\n else:\n return l\n\ndef get_fbn(n):\n \"\"\"\n \n Return the n! + 1 first Factorial Based Numbers starting with zero.\n \n \"\"\"\n max = math.factorial(n)\n \n for i in range(max):\n # from Wikipedia article\n current = i\n divisor = 1\n new_fbn = int_to_fbn(i)\n yield leading_zeros(new_fbn,n-1)\n \ndef print_write(f, line):\n \"\"\"\n\n prints to console and\n output file f\n\n \"\"\"\n print(line)\n f.write(str(line)+'\\n') \n \ndef dot_format(l):\n \"\"\"\n Take a list l that is a factorial based number\n and returns it in dot format.\n \n i.e. [0, 2, 1] becomes 0.2.1\n \"\"\"\n # empty list\n if len(l) < 1:\n return \"\"\n # start with just first element no dot\n dot_string = str(l[0])\n # add rest if any with dots\n for e in l[1:]:\n dot_string += \".\"+str(e)\n \n return dot_string\n \ndef str_format(l):\n \"\"\"\n Take a list l and returns a string\n of those elements converted to strings.\n \"\"\"\n if len(l) < 1:\n return \"\"\n \n new_string = \"\"\n \n for e in l:\n new_string += str(e)\n \n return new_string \n \nwith open(\"output.html\", \"w\", encoding=\"utf-8\") as f:\n f.write(\"\\n\")\n \n # first print list\n \n omega=[0,1,2,3]\n \n four_list = get_fbn(4)\n \n for l in four_list:\n print_write(f,dot_format(l)+' -> '+str_format(apply_perm(omega[:],l)))\n \n print_write(f,\" \")\n \n # now generate this output:\n #\n # Permutations generated = 39916800\n # compared to 11! which = 39916800\n \n \n num_permutations = 0\n \n for p in get_fbn(11):\n num_permutations += 1\n if num_permutations % 1000000 == 0:\n print_write(f,\"permutations so far = \"+str(num_permutations))\n \n print_write(f,\" \")\n print_write(f,\"Permutations generated = \"+str(num_permutations))\n print_write(f,\"compared to 11! which = \"+str(math.factorial(11)))\n \n print_write(f,\" \")\n \n \n \n \"\"\"\n \n u\"\\u2660\" - spade\n \n u\"\\u2665\" - heart\n \n u\"\\u2666\" - diamond\n \n u\"\\u2663\" - club\n \n \"\"\"\n \n shoe = []\n \n for suit in [u\"\\u2660\",u\"\\u2665\",u\"\\u2666\",u\"\\u2663\"]:\n for value in ['A','K','Q','J','10','9','8','7','6','5','4','3','2']:\n shoe.append(value+suit)\n \n print_write(f,str_format(shoe))\n \n p1 = [39,49,7,47,29,30,2,12,10,3,29,37,33,17,12,31,29,34,17,25,2,4,25,4,1,14,20,6,21,18,1,1,1,4,0,5,15,12,4,3,10,10,9,1,6,5,5,3,0,0,0]\n \n p2 = [51,48,16,22,3,0,19,34,29,1,36,30,12,32,12,29,30,26,14,21,8,12,1,3,10,4,7,17,6,21,8,12,15,15,13,15,7,3,12,11,9,5,5,6,6,3,4,0,3,2,1]\n \n print_write(f,\" \")\n print_write(f,dot_format(p1))\n print_write(f,\" \")\n print_write(f,str_format(apply_perm(shoe[:],p1)))\n \n print_write(f,\" \")\n print_write(f,dot_format(p2))\n print_write(f,\" \")\n print_write(f,str_format(apply_perm(shoe[:],p2)))\n\n # generate random 51 digit factorial based number\n \n import random\n \n max = math.factorial(52)\n \n random_int = random.randint(0, max-1)\n\n myperm = leading_zeros(int_to_fbn(random_int),51)\n \n print(len(myperm))\n \n print_write(f,\" \")\n print_write(f,dot_format(myperm))\n print_write(f,\" \")\n print_write(f,str_format(apply_perm(shoe[:],myperm)))\n\n f.write(\"\\n\")\n\n"} +{"title": "Factorial primes", "language": "Python", "task": ";Definition\nA factorial.\n\nIn other words a non-negative integer '''n''' corresponds to a factorial prime if either '''n'''! - 1 or '''n'''! + 1 is prime. \n\n;Examples\n4 corresponds to the factorial prime 4! - 1 = 23.\n\n5 doesn't correspond to a factorial prime because neither 5! - 1 = 119 (7 x 17) nor 5! + 1 = 121 (11 x 11) are prime.\n\n;Task\nFind and show here the first 10 factorial primes. As well as the prime itself show the factorial number '''n''' to which it corresponds and whether 1 is to be added or subtracted. \n\nAs 0! (by convention) and 1! are both 1, ignore the former and start counting from 1!.\n\n;Stretch\nIf your language supports arbitrary sized integers, do the same for at least the next 19 factorial primes.\n\nAs it can take a long time to demonstrate that a large number (above say 2^64) is definitely prime, you may instead use a function which shows that a number is probably prime to a reasonable degree of certainty. Most 'big integer' libraries have such a function.\n\nIf a number has more than 40 digits, do not show the full number. Show instead the first 20 and the last 20 digits and how many digits in total the number has.\n\n;Reference\n* OEIS:A088054 - Factorial primes\n\n;Related task\n* Sequence of primorial primes\n\n", "solution": "\nfrom itertools import count\nfrom itertools import islice\nfrom typing import Iterable\nfrom typing import Tuple\n\nimport gmpy2\n\n\ndef factorials() -> Iterable[int]:\n fact = 1\n for i in count(1):\n yield fact\n fact *= i\n\n\ndef factorial_primes() -> Iterable[Tuple[int, int, str]]:\n for n, fact in enumerate(factorials()):\n if gmpy2.is_prime(fact - 1):\n yield (n, fact - 1, \"-\")\n if gmpy2.is_prime(fact + 1):\n yield (n, fact + 1, \"+\")\n\n\ndef print_factorial_primes(limit=10) -> None:\n print(f\"First {limit} factorial primes.\")\n for n, fact_prime, op in islice(factorial_primes(), 1, limit + 1):\n s = str(fact_prime)\n if len(s) > 40:\n s = f\"{s[:20]}...{s[-20:]} ({len(s)} digits)\"\n print(f\"{n}! {op} 1 = {s}\")\n\n\nif __name__ == \"__main__\":\n import sys\n print_factorial_primes(int(sys.argv[1]) if len(sys.argv) > 1 else 10)\n"} +{"title": "Factorions", "language": "C", "task": ";Definition:\nA factorion is a natural number that equals the sum of the factorials of its digits. \n\n\n;Example: \n'''145''' \u00a0 is a factorion in base '''10''' because:\n\n 1! + 4! + 5! = 1 + 24 + 120 = 145 \n\n\n\nIt can be shown (see talk page) that no factorion in base '''10''' can exceed \u00a0 '''1,499,999'''.\n\n\n;Task:\nWrite a program in your language to demonstrate, by calculating and printing out the factorions, that:\n:* \u00a0 There are \u00a0 '''3''' \u00a0 factorions in base \u00a0 '''9'''\n:* \u00a0 There are \u00a0 '''4''' \u00a0 factorions in base '''10'''\n:* \u00a0 There are \u00a0 '''5''' \u00a0 factorions in base '''11''' \n:* \u00a0 There are \u00a0 '''2''' \u00a0 factorions in base '''12''' \u00a0 \u00a0 (up to the same upper bound as for base '''10''')\n\n\n;See also:\n:* '''Wikipedia article'''\n:* '''OEIS:A014080 - Factorions in base 10'''\n:* '''OEIS:A193163 - Factorions in base n'''\n\n", "solution": "#include \n\nint main() { \n int n, b, d;\n unsigned long long i, j, sum, fact[12];\n // cache factorials from 0 to 11\n fact[0] = 1;\n for (n = 1; n < 12; ++n) {\n fact[n] = fact[n-1] * n;\n }\n\n for (b = 9; b <= 12; ++b) {\n printf(\"The factorions for base %d are:\\n\", b);\n for (i = 1; i < 1500000; ++i) {\n sum = 0;\n j = i;\n while (j > 0) {\n d = j % b;\n sum += fact[d];\n j /= b;\n }\n if (sum == i) printf(\"%llu \", i);\n }\n printf(\"\\n\\n\");\n }\n return 0;\n}"} +{"title": "Factorions", "language": "Python", "task": ";Definition:\nA factorion is a natural number that equals the sum of the factorials of its digits. \n\n\n;Example: \n'''145''' \u00a0 is a factorion in base '''10''' because:\n\n 1! + 4! + 5! = 1 + 24 + 120 = 145 \n\n\n\nIt can be shown (see talk page) that no factorion in base '''10''' can exceed \u00a0 '''1,499,999'''.\n\n\n;Task:\nWrite a program in your language to demonstrate, by calculating and printing out the factorions, that:\n:* \u00a0 There are \u00a0 '''3''' \u00a0 factorions in base \u00a0 '''9'''\n:* \u00a0 There are \u00a0 '''4''' \u00a0 factorions in base '''10'''\n:* \u00a0 There are \u00a0 '''5''' \u00a0 factorions in base '''11''' \n:* \u00a0 There are \u00a0 '''2''' \u00a0 factorions in base '''12''' \u00a0 \u00a0 (up to the same upper bound as for base '''10''')\n\n\n;See also:\n:* '''Wikipedia article'''\n:* '''OEIS:A014080 - Factorions in base 10'''\n:* '''OEIS:A193163 - Factorions in base n'''\n\n", "solution": "fact = [1] # cache factorials from 0 to 11\nfor n in range(1, 12):\n fact.append(fact[n-1] * n)\n\nfor b in range(9, 12+1):\n print(f\"The factorions for base {b} are:\")\n for i in range(1, 1500000):\n fact_sum = 0\n j = i\n while j > 0:\n d = j % b\n fact_sum += fact[d]\n j = j//b\n if fact_sum == i:\n print(i, end=\" \")\n print(\"\\n\")\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; \u00a0 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:* \u00a0 For two people:\n:* \u00a0 For three people\n:* \u00a0 For five people\n:* \u00a0 For eleven people\n\n\n;Related tasks: \n:* \u00a0 [[Non-decimal radices/Convert]]\n:* \u00a0 [[Thue-Morse]]\n\n\n;See also:\n:* \u00a0 [https://oeis.org/A010060 A010060], [https://oeis.org/A053838 A053838], [https://oeis.org/A053840 A053840]: The On-Line Encyclopedia of Integer Sequences\u00ae (OEIS\u00ae)\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": "Fairshare between two and more", "language": "JavaScript", "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; \u00a0 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:* \u00a0 For two people:\n:* \u00a0 For three people\n:* \u00a0 For five people\n:* \u00a0 For eleven people\n\n\n;Related tasks: \n:* \u00a0 [[Non-decimal radices/Convert]]\n:* \u00a0 [[Thue-Morse]]\n\n\n;See also:\n:* \u00a0 [https://oeis.org/A010060 A010060], [https://oeis.org/A053838 A053838], [https://oeis.org/A053840 A053840]: The On-Line Encyclopedia of Integer Sequences\u00ae (OEIS\u00ae)\n\n", "solution": "(() => {\n 'use strict';\n\n // thueMorse :: Int -> [Int]\n const thueMorse = base =>\n // Thue-Morse sequence for a given base\n fmapGen(baseDigitsSumModBase(base))(\n enumFrom(0)\n )\n\n // baseDigitsSumModBase :: Int -> Int -> Int\n const baseDigitsSumModBase = base =>\n // For any integer n, the sum of its digits\n // in a given base, modulo that base.\n n => sum(unfoldl(\n x => 0 < x ? (\n Just(quotRem(x)(base))\n ) : Nothing()\n )(n)) % base\n\n\n // ------------------------TEST------------------------\n const main = () =>\n console.log(\n fTable(\n 'First 25 fairshare terms for a given number of players:'\n )(str)(\n xs => '[' + map(\n compose(justifyRight(2)(' '), str)\n )(xs) + ' ]'\n )(\n compose(take(25), thueMorse)\n )([2, 3, 5, 11])\n );\n\n // -----------------GENERIC FUNCTIONS------------------\n\n // Just :: a -> Maybe a\n const Just = x => ({\n type: 'Maybe',\n Nothing: false,\n Just: x\n });\n\n // Nothing :: Maybe a\n const Nothing = () => ({\n type: 'Maybe',\n Nothing: true,\n });\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = a => b => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (...fs) =>\n x => fs.reduceRight((a, f) => f(a), x);\n\n // enumFrom :: Enum a => a -> [a]\n function* enumFrom(x) {\n // A non-finite succession of enumerable\n // values, starting with the value x.\n let v = x;\n while (true) {\n yield v;\n v = 1 + v;\n }\n }\n\n // fTable :: String -> (a -> String) -> (b -> String)\n // -> (a -> b) -> [a] -> String\n const fTable = s => xShow => fxShow => f => xs => {\n // Heading -> x display function ->\n // fx display function ->\n // f -> values -> tabular string\n const\n ys = xs.map(xShow),\n w = Math.max(...ys.map(length));\n return s + '\\n' + zipWith(\n a => b => a.padStart(w, ' ') + ' -> ' + b\n )(ys)(\n xs.map(x => fxShow(f(x)))\n ).join('\\n');\n };\n\n // fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]\n const fmapGen = f =>\n function*(gen) {\n let v = take(1)(gen);\n while (0 < v.length) {\n yield(f(v[0]))\n v = take(1)(gen)\n }\n };\n\n // justifyRight :: Int -> Char -> String -> String\n const justifyRight = n =>\n // The string s, preceded by enough padding (with\n // the character c) to reach the string length n.\n c => s => n > s.length ? (\n s.padStart(n, c)\n ) : s;\n\n // length :: [a] -> Int\n const length = xs =>\n // Returns Infinity over objects without finite\n // length. This enables zip and zipWith to choose\n // the shorter argument when one is non-finite,\n // like cycle, repeat etc\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n // map :: (a -> b) -> [a] -> [b]\n const map = f =>\n // The list obtained by applying f to each element of xs.\n // (The image of xs under f).\n xs => (Array.isArray(xs) ? (\n xs\n ) : xs.split('')).map(f);\n\n // quotRem :: Int -> Int -> (Int, Int)\n const quotRem = m => n =>\n Tuple(Math.floor(m / n))(\n m % n\n );\n\n // str :: a -> String\n const str = x => x.toString();\n\n // sum :: [Num] -> Num\n const sum = xs =>\n // The numeric sum of all values in xs.\n xs.reduce((a, x) => a + x, 0);\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n =>\n // The first n elements of a list,\n // string of characters, or stream.\n xs => 'GeneratorFunction' !== xs\n .constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n\n // unfoldl :: (b -> Maybe (b, a)) -> b -> [a]\n const unfoldl = f => v => {\n // Dual to reduce or foldl.\n // Where these reduce a list to a summary value, unfoldl\n // builds a list from a seed value.\n // Where f returns Just(a, b), a is appended to the list,\n // and the residual b is used as the argument for the next\n // application of f.\n // Where f returns Nothing, the completed list is returned.\n let\n xr = [v, v],\n xs = [];\n while (true) {\n const mb = f(xr[0]);\n if (mb.Nothing) {\n return xs\n } else {\n xr = mb.Just;\n xs = [xr[1]].concat(xs);\n }\n }\n };\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = f =>\n xs => ys => {\n const\n lng = Math.min(length(xs), length(ys)),\n vs = take(lng)(ys);\n return take(lng)(xs)\n .map((x, i) => f(x)(vs[i]));\n };\n\n // MAIN ---\n return main();\n})();"} +{"title": "Fairshare between two and more", "language": "Python", "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; \u00a0 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:* \u00a0 For two people:\n:* \u00a0 For three people\n:* \u00a0 For five people\n:* \u00a0 For eleven people\n\n\n;Related tasks: \n:* \u00a0 [[Non-decimal radices/Convert]]\n:* \u00a0 [[Thue-Morse]]\n\n\n;See also:\n:* \u00a0 [https://oeis.org/A010060 A010060], [https://oeis.org/A053838 A053838], [https://oeis.org/A053840 A053840]: The On-Line Encyclopedia of Integer Sequences\u00ae (OEIS\u00ae)\n\n", "solution": "from itertools import count, islice\n\ndef _basechange_int(num, b):\n \"\"\"\n Return list of ints representing positive num in base b\n\n >>> b = 3\n >>> print(b, [_basechange_int(num, b) for num in range(11)])\n 3 [[0], [1], [2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2], [1, 0, 0], [1, 0, 1]]\n >>>\n \"\"\"\n if num == 0:\n return [0]\n result = []\n while num != 0:\n num, d = divmod(num, b)\n result.append(d)\n return result[::-1]\n\ndef fairshare(b=2):\n for i in count():\n yield sum(_basechange_int(i, b)) % b\n\nif __name__ == '__main__':\n for b in (2, 3, 5, 11):\n print(f\"{b:>2}: {str(list(islice(fairshare(b), 25)))[1:-1]}\")"} +{"title": "Farey sequence", "language": "C", "task": "The \u00a0 Farey sequence \u00a0 ''' ''F''n''' \u00a0 of order \u00a0 '''n''' \u00a0 is the sequence of completely reduced fractions between \u00a0 '''0''' \u00a0 and \u00a0 '''1''' \u00a0 which, when in lowest terms, have denominators less than or equal to \u00a0 '''n''', \u00a0 arranged in order of increasing size.\n\nThe \u00a0 ''Farey sequence'' \u00a0 is sometimes incorrectly called a \u00a0 ''Farey series''. \n\n\nEach Farey sequence:\n:::* \u00a0 starts with the value \u00a0 '''0''' \u00a0 (zero), \u00a0 denoted by the fraction \u00a0 \u00a0 \\frac{0}{1} \n:::* \u00a0 ends with the value \u00a0 '''1''' \u00a0 (unity), \u00a0 denoted by the fraction \u00a0 \\frac{1}{1}.\n\n\nThe Farey sequences of orders \u00a0 '''1''' \u00a0 to \u00a0 '''5''' \u00a0 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* \u00a0 Compute and show the Farey sequence for orders \u00a0 '''1''' \u00a0 through \u00a0 '''11''' \u00a0 (inclusive).\n* \u00a0 Compute and display the \u00a0 ''number'' \u00a0 of fractions in the Farey sequence for order \u00a0 '''100''' \u00a0 through \u00a0 '''1,000''' \u00a0 (inclusive) \u00a0 by hundreds.\n* \u00a0 Show the fractions as \u00a0 '''n/d''' \u00a0 (using the solidus [or slash] to separate the numerator from the denominator). \n\n\nThe length \u00a0 (the number of fractions) \u00a0 of a Farey sequence asymptotically approaches:\n\n::::::::::: 3 \u00d7 n2 \u00a0 \u00f7 \u00a0 \\pi2 \n\n;See also:\n* \u00a0 OEIS sequence \u00a0 A006842 numerators of Farey series of order 1, 2, \u00b7\u00b7\u00b7 \n* \u00a0 OEIS sequence \u00a0 A006843 denominators of Farey series of order 1, 2, \u00b7\u00b7\u00b7 \n* \u00a0 OEIS sequence \u00a0 A005728 number of fractions in Farey series of order n \n* \u00a0 MathWorld entry \u00a0 [http://mathworld.wolfram.com/FareySequence.html Farey sequence]\n* \u00a0 Wikipedia \u00a0 entry \u00a0 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": "Farey sequence", "language": "Python", "task": "The \u00a0 Farey sequence \u00a0 ''' ''F''n''' \u00a0 of order \u00a0 '''n''' \u00a0 is the sequence of completely reduced fractions between \u00a0 '''0''' \u00a0 and \u00a0 '''1''' \u00a0 which, when in lowest terms, have denominators less than or equal to \u00a0 '''n''', \u00a0 arranged in order of increasing size.\n\nThe \u00a0 ''Farey sequence'' \u00a0 is sometimes incorrectly called a \u00a0 ''Farey series''. \n\n\nEach Farey sequence:\n:::* \u00a0 starts with the value \u00a0 '''0''' \u00a0 (zero), \u00a0 denoted by the fraction \u00a0 \u00a0 \\frac{0}{1} \n:::* \u00a0 ends with the value \u00a0 '''1''' \u00a0 (unity), \u00a0 denoted by the fraction \u00a0 \\frac{1}{1}.\n\n\nThe Farey sequences of orders \u00a0 '''1''' \u00a0 to \u00a0 '''5''' \u00a0 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* \u00a0 Compute and show the Farey sequence for orders \u00a0 '''1''' \u00a0 through \u00a0 '''11''' \u00a0 (inclusive).\n* \u00a0 Compute and display the \u00a0 ''number'' \u00a0 of fractions in the Farey sequence for order \u00a0 '''100''' \u00a0 through \u00a0 '''1,000''' \u00a0 (inclusive) \u00a0 by hundreds.\n* \u00a0 Show the fractions as \u00a0 '''n/d''' \u00a0 (using the solidus [or slash] to separate the numerator from the denominator). \n\n\nThe length \u00a0 (the number of fractions) \u00a0 of a Farey sequence asymptotically approaches:\n\n::::::::::: 3 \u00d7 n2 \u00a0 \u00f7 \u00a0 \\pi2 \n\n;See also:\n* \u00a0 OEIS sequence \u00a0 A006842 numerators of Farey series of order 1, 2, \u00b7\u00b7\u00b7 \n* \u00a0 OEIS sequence \u00a0 A006843 denominators of Farey series of order 1, 2, \u00b7\u00b7\u00b7 \n* \u00a0 OEIS sequence \u00a0 A005728 number of fractions in Farey series of order n \n* \u00a0 MathWorld entry \u00a0 [http://mathworld.wolfram.com/FareySequence.html Farey sequence]\n* \u00a0 Wikipedia \u00a0 entry \u00a0 Farey sequence\n\n", "solution": "from fractions import Fraction\n\n\nclass Fr(Fraction):\n def __repr__(self):\n return '(%s/%s)' % (self.numerator, self.denominator)\n\n\ndef farey(n, length=False):\n if not length:\n return [Fr(0, 1)] + sorted({Fr(m, k) for k in range(1, n+1) for m in range(1, k+1)})\n else:\n #return 1 + len({Fr(m, k) for k in range(1, n+1) for m in range(1, k+1)})\n return (n*(n+3))//2 - sum(farey(n//k, True) for k in range(2, n+1))\n \nif __name__ == '__main__':\n print('Farey sequence for order 1 through 11 (inclusive):')\n for n in range(1, 12): \n print(farey(n))\n print('Number of fractions in the Farey sequence for order 100 through 1,000 (inclusive) by hundreds:')\n print([farey(i, length=True) for i in range(100, 1001, 100)])"} +{"title": "Fast Fourier transform", "language": "C", "task": ";Task:\nCalculate the \u00a0 FFT \u00a0 (Fast Fourier Transform) \u00a0 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 \u00a0 (i.e.: \u00a0 sqrt(re2 + im2)) \u00a0 of the complex result. \n\nThe classic version is the recursive Cooley\u2013Tukey FFT. [http://en.wikipedia.org/wiki/Cooley\u2013Tukey_FFT_algorithm Wikipedia] has pseudo-code for that. \nFurther optimizations are possible but not required.\n\n", "solution": "\n\n#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": "Fast Fourier transform", "language": "JavaScript", "task": ";Task:\nCalculate the \u00a0 FFT \u00a0 (Fast Fourier Transform) \u00a0 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 \u00a0 (i.e.: \u00a0 sqrt(re2 + im2)) \u00a0 of the complex result. \n\nThe classic version is the recursive Cooley\u2013Tukey FFT. [http://en.wikipedia.org/wiki/Cooley\u2013Tukey_FFT_algorithm Wikipedia] has pseudo-code for that. \nFurther optimizations are possible but not required.\n\n", "solution": "/*\ncomplex fast fourier transform and inverse from\nhttp://rosettacode.org/wiki/Fast_Fourier_transform#C.2B.2B\n*/\nfunction icfft(amplitudes)\n{\n\tvar N = amplitudes.length;\n\tvar iN = 1 / N;\n\t\n\t//conjugate if imaginary part is not 0\n\tfor(var i = 0 ; i < N; ++i)\n\t\tif(amplitudes[i] instanceof Complex)\n\t\t\tamplitudes[i].im = -amplitudes[i].im;\n\t\t\t\n\t//apply fourier transform\n\tamplitudes = cfft(amplitudes)\n\t\n\tfor(var i = 0 ; i < N; ++i)\n\t{\n\t\t//conjugate again\n\t\tamplitudes[i].im = -amplitudes[i].im;\n\t\t//scale\n\t\tamplitudes[i].re *= iN;\n\t\tamplitudes[i].im *= iN;\n\t}\n\treturn amplitudes;\n}\n\nfunction cfft(amplitudes)\n{\n\tvar N = amplitudes.length;\n\tif( N <= 1 )\n\t\treturn amplitudes;\n\t\n\tvar hN = N / 2;\n\tvar even = [];\n\tvar odd = [];\n\teven.length = hN;\n\todd.length = hN;\n\tfor(var i = 0; i < hN; ++i)\n\t{\n\t\teven[i] = amplitudes[i*2];\n\t\todd[i] = amplitudes[i*2+1];\n\t}\n\teven = cfft(even);\n\todd = cfft(odd);\n\t\n\tvar a = -2*Math.PI;\n\tfor(var k = 0; k < hN; ++k)\n\t{\n\t\tif(!(even[k] instanceof Complex))\n\t\t\teven[k] = new Complex(even[k], 0);\n\t\tif(!(odd[k] instanceof Complex))\n\t\t\todd[k] = new Complex(odd[k], 0);\n\t\tvar p = k/N;\n\t\tvar t = new Complex(0, a * p);\n\t\tt.cexp(t).mul(odd[k], t);\n\t\tamplitudes[k] = even[k].add(t, odd[k]);\n\t\tamplitudes[k + hN] = even[k].sub(t, even[k]);\n\t}\n\treturn amplitudes;\n}\n\n//test code\n//console.log( cfft([1,1,1,1,0,0,0,0]) );\n//console.log( icfft(cfft([1,1,1,1,0,0,0,0])) );"} +{"title": "Fast Fourier transform", "language": "Python", "task": ";Task:\nCalculate the \u00a0 FFT \u00a0 (Fast Fourier Transform) \u00a0 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 \u00a0 (i.e.: \u00a0 sqrt(re2 + im2)) \u00a0 of the complex result. \n\nThe classic version is the recursive Cooley\u2013Tukey FFT. [http://en.wikipedia.org/wiki/Cooley\u2013Tukey_FFT_algorithm Wikipedia] has pseudo-code for that. \nFurther optimizations are possible but not required.\n\n", "solution": "from cmath import exp, pi\n\ndef fft(x):\n N = len(x)\n if N <= 1: return x\n even = fft(x[0::2])\n odd = fft(x[1::2])\n T= [exp(-2j*pi*k/N)*odd[k] for k in range(N//2)]\n return [even[k] + T[k] for k in range(N//2)] + \\\n [even[k] - T[k] for k in range(N//2)]\n\nprint( ' '.join(\"%5.3f\" % abs(f) \n for f in fft([1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0])) )"} +{"title": "Feigenbaum constant calculation", "language": "C", "task": ";Task:\nCalculate the Feigenbaum constant. \n\n\n;See:\n:* \u00a0 Details in the Wikipedia article: \u00a0 [https://en.wikipedia.org/wiki/Feigenbaum_constants Feigenbaum constant].\n\n", "solution": "#include \n\nvoid feigenbaum() {\n int i, j, k, max_it = 13, max_it_j = 10;\n double a, x, y, d, a1 = 1.0, a2 = 0.0, d1 = 3.2;\n printf(\" i d\\n\");\n for (i = 2; i <= max_it; ++i) {\n a = a1 + (a1 - a2) / d1;\n for (j = 1; j <= max_it_j; ++j) {\n x = 0.0;\n y = 0.0;\n for (k = 1; k <= 1 << i; ++k) {\n y = 1.0 - 2.0 * y * x;\n x = a - x * x;\n }\n a -= x / y;\n }\n d = (a1 - a2) / (a - a1);\n printf(\"%2d %.8f\\n\", i, d);\n d1 = d;\n a2 = a1;\n a1 = a;\n }\n}\n\nint main() {\n feigenbaum();\n return 0;\n}"} +{"title": "Feigenbaum constant calculation", "language": "Python", "task": ";Task:\nCalculate the Feigenbaum constant. \n\n\n;See:\n:* \u00a0 Details in the Wikipedia article: \u00a0 [https://en.wikipedia.org/wiki/Feigenbaum_constants Feigenbaum constant].\n\n", "solution": "max_it = 13\nmax_it_j = 10\na1 = 1.0\na2 = 0.0\nd1 = 3.2\na = 0.0\n\nprint \" i d\"\nfor i in range(2, max_it + 1):\n a = a1 + (a1 - a2) / d1\n for j in range(1, max_it_j + 1):\n x = 0.0\n y = 0.0\n for k in range(1, (1 << i) + 1):\n y = 1.0 - 2.0 * y * x\n x = a - x * x\n a = a - x / y\n d = (a1 - a2) / (a - a1)\n print(\"{0:2d} {1:.8f}\".format(i, d))\n d1 = d\n a2 = a1\n a1 = a"} +{"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* \u00a0 [[Fibonacci sequence]]\n* \u00a0 [http://mathworld.wolfram.com/Fibonaccin-StepNumber.html Wolfram Mathworld]\n* \u00a0 [[Hofstadter Q sequence\u200e]]\n* \u00a0 [[Leonardo numbers]]\n\n\n;Also see:\n* \u00a0 [https://www.youtube.com/watch?v=PeUbRXnbmms Lucas Numbers - Numberphile] (Video)\n* \u00a0 [https://www.youtube.com/watch?v=fMJflV_GUpU Tribonacci Numbers (and the Rauzy Fractal) - Numberphile] (Video)\n* \u00a0 Wikipedia, Lucas number\n* \u00a0 [http://mathworld.wolfram.com/FibonacciNumber.html MathWorld, Fibonacci Number]\n* \u00a0 [http://www.math-cs.ucmo.edu/~curtisc/articles/howardcooper/genfib4.pdf Some identities for r-Fibonacci numbers]\n* \u00a0 OEIS Fibonacci numbers\n* \u00a0 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 n-step number sequences", "language": "JavaScript", "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* \u00a0 [[Fibonacci sequence]]\n* \u00a0 [http://mathworld.wolfram.com/Fibonaccin-StepNumber.html Wolfram Mathworld]\n* \u00a0 [[Hofstadter Q sequence\u200e]]\n* \u00a0 [[Leonardo numbers]]\n\n\n;Also see:\n* \u00a0 [https://www.youtube.com/watch?v=PeUbRXnbmms Lucas Numbers - Numberphile] (Video)\n* \u00a0 [https://www.youtube.com/watch?v=fMJflV_GUpU Tribonacci Numbers (and the Rauzy Fractal) - Numberphile] (Video)\n* \u00a0 Wikipedia, Lucas number\n* \u00a0 [http://mathworld.wolfram.com/FibonacciNumber.html MathWorld, Fibonacci Number]\n* \u00a0 [http://www.math-cs.ucmo.edu/~curtisc/articles/howardcooper/genfib4.pdf Some identities for r-Fibonacci numbers]\n* \u00a0 OEIS Fibonacci numbers\n* \u00a0 OEIS Lucas numbers\n\n", "solution": "function fib(arity, len) {\n return nacci(nacci([1,1], arity, arity), arity, len);\n}\n\nfunction lucas(arity, len) {\n return nacci(nacci([2,1], arity, arity), arity, len);\n}\n\nfunction nacci(a, arity, len) {\n while (a.length < len) {\n var sum = 0;\n for (var i = Math.max(0, a.length - arity); i < a.length; i++)\n sum += a[i];\n a.push(sum);\n }\n return a;\n}\n\nfunction main() {\n for (var arity = 2; arity <= 10; arity++)\n console.log(\"fib(\" + arity + \"): \" + fib(arity, 15));\n for (var arity = 2; arity <= 10; arity++)\n console.log(\"lucas(\" + arity + \"): \" + lucas(arity, 15));\n}\n\nmain();"} +{"title": "Fibonacci n-step number sequences", "language": "Python", "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* \u00a0 [[Fibonacci sequence]]\n* \u00a0 [http://mathworld.wolfram.com/Fibonaccin-StepNumber.html Wolfram Mathworld]\n* \u00a0 [[Hofstadter Q sequence\u200e]]\n* \u00a0 [[Leonardo numbers]]\n\n\n;Also see:\n* \u00a0 [https://www.youtube.com/watch?v=PeUbRXnbmms Lucas Numbers - Numberphile] (Video)\n* \u00a0 [https://www.youtube.com/watch?v=fMJflV_GUpU Tribonacci Numbers (and the Rauzy Fractal) - Numberphile] (Video)\n* \u00a0 Wikipedia, Lucas number\n* \u00a0 [http://mathworld.wolfram.com/FibonacciNumber.html MathWorld, Fibonacci Number]\n* \u00a0 [http://www.math-cs.ucmo.edu/~curtisc/articles/howardcooper/genfib4.pdf Some identities for r-Fibonacci numbers]\n* \u00a0 OEIS Fibonacci numbers\n* \u00a0 OEIS Lucas numbers\n\n", "solution": ">>> class Fiblike():\n\tdef __init__(self, start):\n\t\tself.addnum = len(start)\n\t\tself.memo = start[:]\n\tdef __call__(self, n):\n\t\ttry:\n\t\t\treturn self.memo[n]\n\t\texcept IndexError:\n\t\t\tans = sum(self(i) for i in range(n-self.addnum, n))\n\t\t\tself.memo.append(ans)\n\t\t\treturn ans\n\n\t\t\n>>> fibo = Fiblike([1,1])\n>>> [fibo(i) for i in range(10)]\n[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]\n>>> lucas = Fiblike([2,1])\n>>> [lucas(i) for i in range(10)]\n[2, 1, 3, 4, 7, 11, 18, 29, 47, 76]\n>>> for n, name in zip(range(2,11), 'fibo tribo tetra penta hexa hepta octo nona deca'.split()) :\n\tfibber = Fiblike([1] + [2**i for i in range(n-1)])\n\tprint('n=%2i, %5snacci -> %s ...' % (n, name, ' '.join(str(fibber(i)) for i in range(15))))\n\n\t\nn= 2, fibonacci -> 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...\nn= 3, tribonacci -> 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...\nn= 4, tetranacci -> 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...\nn= 5, pentanacci -> 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...\nn= 6, hexanacci -> 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...\nn= 7, heptanacci -> 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...\nn= 8, octonacci -> 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...\nn= 9, nonanacci -> 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...\nn=10, decanacci -> 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...\n>>> "} +{"title": "Fibonacci word", "language": "C", "task": "The \u00a0 Fibonacci Word \u00a0 may be created in a manner analogous to the \u00a0 Fibonacci Sequence \u00a0 [http://hal.archives-ouvertes.fr/docs/00/36/79/72/PDF/The_Fibonacci_word_fractal.pdf as described here]:\n\n Define \u00a0 F_Word1 \u00a0 as \u00a0 '''1'''\n Define \u00a0 F_Word2 \u00a0 as \u00a0 '''0'''\n Form \u00a0 \u00a0 F_Word3 \u00a0 as \u00a0 F_Word2 \u00a0 \u00a0 concatenated with \u00a0 F_Word1 \u00a0 i.e.: \u00a0 '''01'''\n Form \u00a0 \u00a0 F_Wordn \u00a0 as \u00a0 F_Wordn-1 \u00a0 concatenated with \u00a0 F_wordn-2\n\n\n;Task:\nPerform the above steps for \u00a0 \u00a0 n = 37.\n\nYou may display the first few but not the larger values of \u00a0 n.\n{Doing so will get the task's author into trouble with them what be (again!).} \n\nInstead, create a table for \u00a0 F_Words \u00a0 '''1''' \u00a0 to \u00a0 '''37''' \u00a0 which shows:\n::* \u00a0 The number of characters in the word\n::* \u00a0 The word's [[Entropy]]\n\n\n;Related tasks: \n* \u00a0 Fibonacci word/fractal\n* \u00a0 [[Entropy]]\n* \u00a0 [[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": "Fibonacci word", "language": "JavaScript", "task": "The \u00a0 Fibonacci Word \u00a0 may be created in a manner analogous to the \u00a0 Fibonacci Sequence \u00a0 [http://hal.archives-ouvertes.fr/docs/00/36/79/72/PDF/The_Fibonacci_word_fractal.pdf as described here]:\n\n Define \u00a0 F_Word1 \u00a0 as \u00a0 '''1'''\n Define \u00a0 F_Word2 \u00a0 as \u00a0 '''0'''\n Form \u00a0 \u00a0 F_Word3 \u00a0 as \u00a0 F_Word2 \u00a0 \u00a0 concatenated with \u00a0 F_Word1 \u00a0 i.e.: \u00a0 '''01'''\n Form \u00a0 \u00a0 F_Wordn \u00a0 as \u00a0 F_Wordn-1 \u00a0 concatenated with \u00a0 F_wordn-2\n\n\n;Task:\nPerform the above steps for \u00a0 \u00a0 n = 37.\n\nYou may display the first few but not the larger values of \u00a0 n.\n{Doing so will get the task's author into trouble with them what be (again!).} \n\nInstead, create a table for \u00a0 F_Words \u00a0 '''1''' \u00a0 to \u00a0 '''37''' \u00a0 which shows:\n::* \u00a0 The number of characters in the word\n::* \u00a0 The word's [[Entropy]]\n\n\n;Related tasks: \n* \u00a0 Fibonacci word/fractal\n* \u00a0 [[Entropy]]\n* \u00a0 [[Entropy/Narcissist]]\n\n", "solution": "//makes outputting a table possible in environments \n//that don't support console.table() \nfunction console_table(xs) {\n function pad(n,s) {\n var res = s;\n for (var i = s.length; i < n; i++)\n res += \" \";\n return res;\n }\n\n if (xs.length === 0)\n console.log(\"No data\");\n else {\n var widths = [];\n var cells = [];\n for (var i = 0; i <= xs.length; i++)\n cells.push([]);\n \n for (var s in xs[0]) {\n var len = s.length;\n cells[0].push(s);\n \n for (var i = 0; i < xs.length; i++) {\n var ss = \"\" + xs[i][s];\n len = Math.max(len, ss.length);\n cells[i+1].push(ss);\n }\n widths.push(len);\n }\n var s = \"\";\n for (var x = 0; x < cells.length; x++) {\n for (var y = 0; y < widths.length; y++)\n s += \"|\" + pad(widths[y], cells[x][y]);\n s += \"|\\n\";\n }\n console.log(s);\n }\n}\n\n//returns the entropy of a string as a number \nfunction entropy(s) {\n //create an object containing each individual char\n\t//and the amount of iterations per char \n function prob(s) {\n var h = Object.create(null);\n s.split('').forEach(function(c) {\n h[c] && h[c]++ || (h[c] = 1); \n });\n return h;\n }\n \n s = s.toString(); //just in case \n var e = 0, l = s.length, h = prob(s);\n \n for (var i in h ) {\n var p = h[i]/l;\n e -= p * Math.log(p) / Math.log(2);\n }\n return e;\n}\n\n//creates Fibonacci Word to n as described on Rosetta Code\n//see rosettacode.org/wiki/Fibonacci_word\nfunction fibWord(n) {\n var wOne = \"1\", wTwo = \"0\", wNth = [wOne, wTwo], w = \"\", o = [];\n \n for (var i = 0; i < n; i++) {\n if (i === 0 || i === 1) {\n w = wNth[i];\n } else {\n w = wNth[i - 1] + wNth[i - 2];\n wNth.push(w);\n }\n var l = w.length;\n var e = entropy(w);\n \n if (l <= 21) {\n \to.push({\n \tN: i + 1,\n \tLength: l,\n \tEntropy: e,\n \tWord: w\n \t});\n } else {\n \to.push({\n \tN: i + 1,\n \tLength: l,\n \tEntropy: e,\n \tWord: \"...\"\n \t});\n } \n }\n \n try {\n \tconsole.table(o);\n } catch (err) {\n \tconsole_table(o);\n }\n}\n\nfibWord(37);"} +{"title": "Fibonacci word", "language": "Python", "task": "The \u00a0 Fibonacci Word \u00a0 may be created in a manner analogous to the \u00a0 Fibonacci Sequence \u00a0 [http://hal.archives-ouvertes.fr/docs/00/36/79/72/PDF/The_Fibonacci_word_fractal.pdf as described here]:\n\n Define \u00a0 F_Word1 \u00a0 as \u00a0 '''1'''\n Define \u00a0 F_Word2 \u00a0 as \u00a0 '''0'''\n Form \u00a0 \u00a0 F_Word3 \u00a0 as \u00a0 F_Word2 \u00a0 \u00a0 concatenated with \u00a0 F_Word1 \u00a0 i.e.: \u00a0 '''01'''\n Form \u00a0 \u00a0 F_Wordn \u00a0 as \u00a0 F_Wordn-1 \u00a0 concatenated with \u00a0 F_wordn-2\n\n\n;Task:\nPerform the above steps for \u00a0 \u00a0 n = 37.\n\nYou may display the first few but not the larger values of \u00a0 n.\n{Doing so will get the task's author into trouble with them what be (again!).} \n\nInstead, create a table for \u00a0 F_Words \u00a0 '''1''' \u00a0 to \u00a0 '''37''' \u00a0 which shows:\n::* \u00a0 The number of characters in the word\n::* \u00a0 The word's [[Entropy]]\n\n\n;Related tasks: \n* \u00a0 Fibonacci word/fractal\n* \u00a0 [[Entropy]]\n* \u00a0 [[Entropy/Narcissist]]\n\n", "solution": ">>> import math\n>>> from collections import Counter\n>>> \n>>> def entropy(s):\n... p, lns = Counter(s), float(len(s))\n... return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n... \n>>> \n>>> def fibword(nmax=37):\n... fwords = ['1', '0']\n... print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split()))\n... def pr(n, fwords):\n... while len(fwords) < n:\n... fwords += [''.join(fwords[-2:][::-1])]\n... v = fwords[n-1]\n... print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else ''))\n... for n in range(1, nmax+1): pr(n, fwords)\n... \n>>> fibword()\nN Length Entropy Fibword\n 1 1 -0 1\n 2 1 -0 0\n 3 2 1 01\n 4 3 0.9182958 010\n 5 5 0.9709506 01001\n 6 8 0.954434 01001010\n 7 13 0.9612366 0100101001001\n 8 21 0.9587119 \n 9 34 0.9596869 \n 10 55 0.959316 \n 11 89 0.9594579 \n 12 144 0.9594038 \n 13 233 0.9594244 \n 14 377 0.9594165 \n 15 610 0.9594196 \n 16 987 0.9594184 \n 17 1597 0.9594188 \n 18 2584 0.9594187 \n 19 4181 0.9594187 \n 20 6765 0.9594187 \n 21 10946 0.9594187 \n 22 17711 0.9594187 \n 23 28657 0.9594187 \n 24 46368 0.9594187 \n 25 75025 0.9594187 \n 26 121393 0.9594187 \n 27 196418 0.9594187 \n 28 317811 0.9594187 \n 29 514229 0.9594187 \n 30 832040 0.9594187 \n 31 1346269 0.9594187 \n 32 2178309 0.9594187 \n 33 3524578 0.9594187 \n 34 5702887 0.9594187 \n 35 9227465 0.9594187 \n 36 14930352 0.9594187 \n 37 24157817 0.9594187 \n>>> "} +{"title": "File extension is in extensions list", "language": "C", "task": "Filename extensions are a rudimentary but commonly used way of identifying files types.\n\n\n;Task:\nGiven an arbitrary filename and a list of extensions, tell whether the filename has one of those extensions.\n\n\nNotes:\n* The check should be case insensitive.\n* The extension must occur at the very end of the filename, and be immediately preceded by a dot (.).\n* You may assume that none of the given extensions are the empty string, and none of them contain a dot. Other than that they may be arbitrary strings.\n\n\n;''Extra credit:''\n: Allow extensions to contain dots. This way, users of your function/program have full control over what they consider as the extension in cases like:\n archive.tar.gz\n: Please state clearly whether or not your solution does this.\n\n\nThe following test cases all assume this list of extensions: \u00a0 zip, rar, 7z, gz, archive, A##\n\n:::::::: {| class=\"wikitable\"\n|-\n! Filename\n! Result\n|-\n| MyData.a## || true\n|-\n| MyData.tar.Gz || true\n|-\n| MyData.gzip || false\n|-\n| MyData.7z.backup || false\n|-\n| MyData... || false\n|-\n| MyData || false\n|}\n\nIf your solution does the extra credit requirement, add tar.bz2 to the list of extensions, and check the following additional test cases:\n\n:::::::: {| class=\"wikitable\"\n|-\n! Filename\n! Result\n|-\n| MyData_v1.0.tar.bz2 || true\n|-\n| MyData_v1.0.bz2 || false\n|}\n\n\nChecking 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 extension is in extensions list", "language": "JavaScript", "task": "Filename extensions are a rudimentary but commonly used way of identifying files types.\n\n\n;Task:\nGiven an arbitrary filename and a list of extensions, tell whether the filename has one of those extensions.\n\n\nNotes:\n* The check should be case insensitive.\n* The extension must occur at the very end of the filename, and be immediately preceded by a dot (.).\n* You may assume that none of the given extensions are the empty string, and none of them contain a dot. Other than that they may be arbitrary strings.\n\n\n;''Extra credit:''\n: Allow extensions to contain dots. This way, users of your function/program have full control over what they consider as the extension in cases like:\n archive.tar.gz\n: Please state clearly whether or not your solution does this.\n\n\nThe following test cases all assume this list of extensions: \u00a0 zip, rar, 7z, gz, archive, A##\n\n:::::::: {| class=\"wikitable\"\n|-\n! Filename\n! Result\n|-\n| MyData.a## || true\n|-\n| MyData.tar.Gz || true\n|-\n| MyData.gzip || false\n|-\n| MyData.7z.backup || false\n|-\n| MyData... || false\n|-\n| MyData || false\n|}\n\nIf your solution does the extra credit requirement, add tar.bz2 to the list of extensions, and check the following additional test cases:\n\n:::::::: {| class=\"wikitable\"\n|-\n! Filename\n! Result\n|-\n| MyData_v1.0.tar.bz2 || true\n|-\n| MyData_v1.0.bz2 || false\n|}\n\n\nChecking 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": "\nfunction fileExtensionInExtensionsList(filename) {\n\tlet foundIt = false;\n\tlet filenameLC = filename.toLowerCase();\n\tlet extensions = [\"zip\", \"rar\", \"7z\", \"gz\", \"archive\", \"A##\" ,\"tar.bz2\"];\n\textensions.forEach(extension => {\n\t\tif (filenameLC.endsWith(\".\" + extension.toLowerCase())) { foundIt = true; }\n\t} );\n\treturn foundIt;\n}\n\n// perform tests below\n\nvar fileNamesToTest = [\n\t\"MyData.a##\"\n\t,\"MyData.tar.Gz\"\n\t,\"MyData.gzip\"\n\t,\"MyData.7z.backup\"\n\t,\"MyData...\"\n\t,\"MyData\"\n\t,\"MyData_v1.0.tar.bz2\"\n\t,\"MyData_v1.0.bz2\"\n];\n\nfileNamesToTest.forEach(filename => {\n\tconsole.log(filename + \" -> \" + fileExtensionInExtensionsList(filename));\n});\n"} +{"title": "File extension is in extensions list", "language": "Python", "task": "Filename extensions are a rudimentary but commonly used way of identifying files types.\n\n\n;Task:\nGiven an arbitrary filename and a list of extensions, tell whether the filename has one of those extensions.\n\n\nNotes:\n* The check should be case insensitive.\n* The extension must occur at the very end of the filename, and be immediately preceded by a dot (.).\n* You may assume that none of the given extensions are the empty string, and none of them contain a dot. Other than that they may be arbitrary strings.\n\n\n;''Extra credit:''\n: Allow extensions to contain dots. This way, users of your function/program have full control over what they consider as the extension in cases like:\n archive.tar.gz\n: Please state clearly whether or not your solution does this.\n\n\nThe following test cases all assume this list of extensions: \u00a0 zip, rar, 7z, gz, archive, A##\n\n:::::::: {| class=\"wikitable\"\n|-\n! Filename\n! Result\n|-\n| MyData.a## || true\n|-\n| MyData.tar.Gz || true\n|-\n| MyData.gzip || false\n|-\n| MyData.7z.backup || false\n|-\n| MyData... || false\n|-\n| MyData || false\n|}\n\nIf your solution does the extra credit requirement, add tar.bz2 to the list of extensions, and check the following additional test cases:\n\n:::::::: {| class=\"wikitable\"\n|-\n! Filename\n! Result\n|-\n| MyData_v1.0.tar.bz2 || true\n|-\n| MyData_v1.0.bz2 || false\n|}\n\n\nChecking 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": "'''Check for a specific set of file extensions'''\n\n\n# extensionFound :: [Extension] -> FileName -> Maybe Extension\ndef extensionFound(xs):\n '''Nothing if no matching extension is found,\n or Just the extension (drawn from xs, and\n a suffix of the filename, immediately following\n a dot character).\n '''\n return lambda fn: find(fn.lower().endswith)(\n ['.' + x.lower() for x in xs]\n )\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Check filenames for a particular set of extensions.'''\n\n # checkExtension :: FileName -> Maybe Extension\n def checkExtension(fn):\n return extensionFound([\n 'zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'\n ])(fn)\n\n print(\n fTable(__doc__ + ':\\n')(str)(str)(\n compose(fromMaybe('n/a'))(checkExtension)\n )([\n 'MyData.a##',\n 'MyData.tar.Gz',\n 'MyData.gzip',\n 'MyData.7z.backup',\n 'MyData...',\n 'MyData',\n 'MyData_v1.0.tar.bz2',\n 'MyData_v1.0.bz2'\n ])\n )\n\n\n# GENERIC -------------------------------------------------\n\n# Just :: a -> Maybe a\ndef Just(x):\n '''Constructor for an inhabited Maybe (option type) value.'''\n return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n# Nothing :: Maybe a\ndef Nothing():\n '''Constructor for an empty Maybe (option type) value.'''\n return {'type': 'Maybe', 'Nothing': True}\n\n\n# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n '''Right to left function composition.'''\n return lambda f: lambda x: g(f(x))\n\n\n# find :: (a -> Bool) -> [a] -> Maybe a\ndef find(p):\n '''Just the first element in the list that matches p,\n or Nothing if no elements match.\n '''\n def go(xs):\n for x in xs:\n if p(x):\n return Just(x)\n return Nothing()\n return lambda xs: go(xs)\n\n\n# fromMaybe :: a -> Maybe a -> a\ndef fromMaybe(x):\n '''The default value x if mb is Nothing,\n or the value contained in mb.\n '''\n return lambda mb: x if (\n mb.get('Nothing')\n ) else mb.get('Just')\n\n\n# DISPLAY -------------------------------------------------\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\n '''\n def go(xShow, fxShow, f, xs):\n ys = [xShow(x) for x in xs]\n w = max(map(len, ys))\n return s + '\\n' + '\\n'.join(map(\n lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n xs, ys\n ))\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} +{"title": "File size distribution", "language": "C", "task": ";Task:\nBeginning 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": "\n#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\nInvocation and textual output :\n\nC:\\My Projects\\threeJS>fileSize.exe \"C:\\My Projects\" t\n\nSize Order < 10^ 0 bytes : 1770\nSize Order < 10^ 1 bytes : 1\nSize Order < 10^ 2 bytes : 20\nSize Order < 10^ 3 bytes : 219\nSize Order < 10^ 4 bytes : 1793\nSize Order < 10^ 5 bytes : 1832\nSize Order < 10^ 6 bytes : 631\nSize Order < 10^ 7 bytes : 124\nSize Order < 10^ 8 bytes : 26\nSize Order < 10^ 9 bytes : 0\nSize Order < 10^10 bytes : 0\nSize Order < 10^11 bytes : 0\nSize Order < 10^12 bytes : 0\nSize Order < 10^13 bytes : 0\nSize Order < 10^14 bytes : 0\nSize Order < 10^15 bytes : 0\nSize Order < 10^16 bytes : 0\nSize Order < 10^17 bytes : 0\nSize Order < 10^18 bytes : 0\nSize Order < 10^19 bytes : 0\nSize Order < 10^20 bytes : 0\nSize Order < 10^21 bytes : 0\nSize Order < 10^22 bytes : 0\nSize Order < 10^23 bytes : 0\nSize Order < 10^24 bytes : 0\n\nInvocation and graphical output :\n\nC:\\My Projects\\threeJS>fileSize.exe \"C:\\My Projects\" g\n\nSize Order < 10^ 0 bytes |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u25881770\nSize Order < 10^ 1 bytes |1\nSize Order < 10^ 2 bytes |\u2588\u258820\nSize Order < 10^ 3 bytes |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588219\nSize Order < 10^ 4 bytes |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u25881793\nSize Order < 10^ 5 bytes |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u25881832\nSize Order < 10^ 6 bytes |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588631\nSize Order < 10^ 7 bytes |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588124\nSize Order < 10^ 8 bytes |\u2588\u2588\u258826\nSize Order < 10^ 9 bytes |0\nSize Order < 10^10 bytes |0\nSize Order < 10^11 bytes |0\nSize Order < 10^12 bytes |0\nSize Order < 10^13 bytes |0\nSize Order < 10^14 bytes |0\nSize Order < 10^15 bytes |0\nSize Order < 10^16 bytes |0\nSize Order < 10^17 bytes |0\nSize Order < 10^18 bytes |0\nSize Order < 10^19 bytes |0\nSize Order < 10^20 bytes |0\nSize Order < 10^21 bytes |0\nSize Order < 10^22 bytes |0\nSize Order < 10^23 bytes |0\nSize Order < 10^24 bytes |0\n\nNote that it is possible to track files up to 10^24 (Yottabyte) in size with this implementation, but if you have a file that large, you shouldn't be needing such programs. :)\n\n===POSIX===\nThis works on macOS 10.15. It should be OK for Linux as well.\n#include \n#include \n#include \n#include \n#include \n\nstatic const uintmax_t sizes[] = {\n 0, 1000, 10000, 100000, 1000000, 10000000,\n 100000000, 1000000000, 10000000000\n};\nstatic const size_t nsizes = sizeof(sizes)/sizeof(sizes[0]);\nstatic uintmax_t count[nsizes + 1] = { 0 };\nstatic uintmax_t files = 0;\nstatic uintmax_t total_size = 0;\n\nstatic int callback(const char* file, const struct stat* sp, int flag) {\n if (flag == FTW_F) {\n uintmax_t file_size = sp->st_size;\n ++files;\n total_size += file_size;\n size_t index = 0;\n for (; index < nsizes && sizes[index] < file_size; ++index);\n ++count[index];\n } else if (flag == FTW_DNR) {\n fprintf(stderr, \"Cannot read directory %s.\\n\", file);\n }\n return 0;\n}\n\nint main(int argc, char** argv) {\n setlocale(LC_ALL, \"\");\n const char* directory = argc > 1 ? argv[1] : \".\";\n if (ftw(directory, callback, 512) != 0) {\n perror(directory);\n return EXIT_FAILURE;\n }\n printf(\"File size distribution for '%s':\\n\", directory);\n for (size_t i = 0; i <= nsizes; ++i) {\n if (i == nsizes)\n printf(\"> %'lu\", sizes[i - 1]);\n else\n printf(\"%'16lu\", sizes[i]);\n printf(\" bytes: %'lu\\n\", count[i]);\n }\n printf(\"Number of files: %'lu\\n\", files);\n printf(\"Total file size: %'lu\\n\", total_size);\n return EXIT_SUCCESS;\n}\n"} +{"title": "File size distribution", "language": "Python", "task": ";Task:\nBeginning 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": "import sys, os\nfrom collections import Counter\n\ndef dodir(path):\n global h\n\n for name in os.listdir(path):\n p = os.path.join(path, name)\n\n if os.path.islink(p):\n pass\n elif os.path.isfile(p):\n h[os.stat(p).st_size] += 1\n elif os.path.isdir(p):\n dodir(p)\n else:\n pass\n\ndef main(arg):\n global h\n h = Counter()\n for dir in arg:\n dodir(dir)\n\n s = n = 0\n for k, v in sorted(h.items()):\n print(\"Size %d -> %d file(s)\" % (k, v))\n n += v\n s += k * v\n print(\"Total %d bytes for %d files\" % (s, n))\n\nmain(sys.argv[1:])"} +{"title": "Find Chess960 starting position identifier", "language": "Python 3.10.5 2022-06-28", "task": "As described on the '''Starting Position Identifier number (\"SP-ID\"), and generate the corresponding position. \n\n;Task:\nThis task is to go the other way: given a starting array of pieces (provided in any form that suits your implementation, whether string or list or array, of letters or Unicode chess symbols or enum values, etc.), derive its unique SP-ID. For example, given the starting array '''QNRBBNKR''' (or '''\u2655\u2658\u2656\u2657\u2657\u2658\u2654\u2656''' or '''\u265b\u265e\u265c\u265d\u265d\u265e\u265a\u265c'''), which we assume is given as seen from White's side of the board from left to right, your (sub)program should return 105; given the starting lineup of standard chess, it should return 518.\n\nYou may assume the input is a valid Chess960 position; detecting invalid input (including illegal characters or starting arrays with the bishops on the same color square or the king not between the two rooks) is optional.\n\n;Algorithm:\n\nThe derivation is the inverse of the algorithm given at Wikipedia, and goes like this (we'll use the standard chess setup as an example).\n\n1. Ignoring the Queen and Bishops, find the positions of the Knights within the remaining five spaces (in the standard array they're in the second and fourth positions), and then find the index number of that combination. There's a table at the above Wikipedia article, but it's just the possible positions sorted left to right and numbered 0 to 9: 0='''NN---''', 1='''N-N--''', 2='''N--N-''', 3='''N---N''', 4='''-NN--''', etc; our pair is combination number 5. Call this number N. '''N=5'''\n\n2. Still ignoring the Bishops, find the position of the Queen in the remaining 6 spaces; number them 0..5 from left to right and call the index of the Queen's position Q. In our example, '''Q=2'''.\n\n3. Finally, find the positions of the two bishops within their respective sets of four like-colored squares. It's important to note here that the board in chess is placed such that the leftmost position on the home row is on a dark square and the rightmost a light. So if we number the squares of each color 0..3 from left to right, the dark bishop in the standard position is on square 1 ('''D=1'''), and the light bishop is on square 2 ('''L=2''').\n\n4. Then the position number is given by '''4(4(6N + Q)+D)+L''', which reduces to '''96N + 16Q + 4D + L'''. In our example, that's 96\u00d75 + 16\u00d72 + 4\u00d71 + 2 = 480 + 32 + 4 + 2 = 518.\n\nNote that an earlier iteration of this page contained an incorrect description of the algorithm which would give the same SP-ID for both of the following two positions.\n\n RQNBBKRN = 601\n RNQBBKRN = 617\n\n", "solution": "# optional, but task function depends on it as written\ndef validate_position(candidate: str):\n assert (\n len(candidate) == 8\n ), f\"candidate position has invalide len = {len(candidate)}\"\n\n valid_pieces = {\"R\": 2, \"N\": 2, \"B\": 2, \"Q\": 1, \"K\": 1}\n assert {\n piece for piece in candidate\n } == valid_pieces.keys(), f\"candidate position contains invalid pieces\"\n for piece_type in valid_pieces.keys():\n assert (\n candidate.count(piece_type) == valid_pieces[piece_type]\n ), f\"piece type '{piece_type}' has invalid count\"\n\n bishops_pos = [index for index, \n value in enumerate(candidate) if value == \"B\"]\n assert (\n bishops_pos[0] % 2 != bishops_pos[1] % 2\n ), f\"candidate position has both bishops in the same color\"\n\n assert [piece for piece in candidate if piece in \"RK\"] == [\n \"R\",\n \"K\",\n \"R\",\n ], \"candidate position has K outside of RR\"\n\n\ndef calc_position(start_pos: str):\n try:\n validate_position(start_pos)\n except AssertionError:\n raise AssertionError\n # step 1\n subset_step1 = [piece for piece in start_pos if piece not in \"QB\"]\n nights_positions = [\n index for index, value in enumerate(subset_step1) if value == \"N\"\n ]\n nights_table = {\n (0, 1): 0,\n (0, 2): 1,\n (0, 3): 2,\n (0, 4): 3,\n (1, 2): 4,\n (1, 3): 5,\n (1, 4): 6,\n (2, 3): 7,\n (2, 4): 8,\n (3, 4): 9,\n }\n N = nights_table.get(tuple(nights_positions))\n\n # step 2\n subset_step2 = [piece for piece in start_pos if piece != \"B\"]\n Q = subset_step2.index(\"Q\")\n\n # step 3\n dark_squares = [\n piece for index, piece in enumerate(start_pos) if index in range(0, 9, 2)\n ]\n light_squares = [\n piece for index, piece in enumerate(start_pos) if index in range(1, 9, 2)\n ]\n D = dark_squares.index(\"B\")\n L = light_squares.index(\"B\")\n\n return 4 * (4 * (6*N + Q) + D) + L\n\nif __name__ == '__main__':\n for example in [\"QNRBBNKR\", \"RNBQKBNR\", \"RQNBBKRN\", \"RNQBBKRN\"]:\n print(f'Position: {example}; Chess960 PID= {calc_position(example)}')"} +{"title": "Find duplicate files", "language": "Python", "task": "In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion. \n\n\n;Task:\nCreate a program which, given a minimum size and a folder/directory, will find all files of at least ''size'' bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.\n\nThe program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data. \n\nSpecify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements. \n\nIdentify hard links (filenames referencing the same content) in the output if applicable for the filesystem. \n\nFor extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.\n\n", "solution": "from __future__ import print_function\nimport os\nimport hashlib\nimport datetime\n\ndef FindDuplicateFiles(pth, minSize = 0, hashName = \"md5\"):\n knownFiles = {}\n\n #Analyse files\n for root, dirs, files in os.walk(pth):\n for fina in files:\n fullFina = os.path.join(root, fina)\n isSymLink = os.path.islink(fullFina)\n if isSymLink:\n continue # Skip symlinks\n si = os.path.getsize(fullFina)\n if si < minSize:\n continue\n if si not in knownFiles:\n knownFiles[si] = {}\n h = hashlib.new(hashName)\n h.update(open(fullFina, \"rb\").read())\n hashed = h.digest()\n if hashed in knownFiles[si]:\n fileRec = knownFiles[si][hashed]\n fileRec.append(fullFina)\n else:\n knownFiles[si][hashed] = [fullFina]\n\n #Print result\n sizeList = list(knownFiles.keys())\n sizeList.sort(reverse=True)\n for si in sizeList:\n filesAtThisSize = knownFiles[si]\n for hashVal in filesAtThisSize:\n if len(filesAtThisSize[hashVal]) < 2:\n continue\n fullFinaLi = filesAtThisSize[hashVal]\n print (\"=======Duplicate=======\")\n for fullFina in fullFinaLi:\n st = os.stat(fullFina)\n isHardLink = st.st_nlink > 1 \n infoStr = []\n if isHardLink:\n infoStr.append(\"(Hard linked)\")\n fmtModTime = datetime.datetime.utcfromtimestamp(st.st_mtime).strftime('%Y-%m-%dT%H:%M:%SZ')\n print (fmtModTime, si, os.path.relpath(fullFina, pth), \" \".join(infoStr))\n\nif __name__==\"__main__\":\n\n FindDuplicateFiles('/home/tim/Dropbox', 1024*1024)\n"} +{"title": "Find if a point is within a triangle", "language": "C", "task": "[[Category:Geometry]]\n[[Category:Collision detection]]\n\nFind if a point is within a triangle.\n\n\n;Task:\n \n::* \u00a0 Assume points are on a plane defined by (x, y) real number coordinates.\n\n::* \u00a0 Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC. \n\n::* \u00a0 You may use any algorithm. \n\n::* \u00a0 Bonus: explain why the algorithm you chose works.\n\n\n;Related tasks:\n* \u00a0 [[Determine_if_two_triangles_overlap]]\n\n\n;Also see:\n:* Discussion of several methods. [[http://totologic.blogspot.com/2014/01/accurate-point-in-triangle-test.html]]\n:* Determine if a point is in a polygon [[https://en.wikipedia.org/wiki/Point_in_polygon]]\n:* Triangle based coordinate systems [[https://en.wikipedia.org/wiki/Barycentric_coordinate_system]]\n:* Wolfram entry [[https://mathworld.wolfram.com/TriangleInterior.html]]\n\n", "solution": "#include \n#include \n#include \n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = 0.000001;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n double xMin = min(x1, min(x2, x3)) - EPS;\n double xMax = max(x1, max(x2, x3)) + EPS;\n double yMin = min(y1, min(y2, y3)) - EPS;\n double yMax = max(y1, max(y2, y3)) + EPS;\n return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n if (dotProduct < 0) {\n return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n } else if (dotProduct <= 1) {\n double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n } else {\n return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n return false;\n }\n if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n return true;\n }\n if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n return true;\n }\n if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n return true;\n }\n if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n return true;\n }\n return false;\n}\n\nvoid printPoint(double x, double y) {\n printf(\"(%f, %f)\", x, y);\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n printf(\"Triangle is [\");\n printPoint(x1, y1);\n printf(\", \");\n printPoint(x2, y2);\n printf(\", \");\n printPoint(x3, y3);\n printf(\"] \\n\");\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n printTriangle(x1, y1, x2, y2, x3, y3);\n printf(\"Point \");\n printPoint(x, y);\n printf(\" is within triangle? \");\n if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n printf(\"true\\n\");\n } else {\n printf(\"false\\n\");\n }\n}\n\nint main() {\n test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n printf(\"\\n\");\n\n test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n printf(\"\\n\");\n\n test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n printf(\"\\n\");\n\n return 0;\n}"} +{"title": "Find if a point is within a triangle", "language": "Python", "task": "[[Category:Geometry]]\n[[Category:Collision detection]]\n\nFind if a point is within a triangle.\n\n\n;Task:\n \n::* \u00a0 Assume points are on a plane defined by (x, y) real number coordinates.\n\n::* \u00a0 Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC. \n\n::* \u00a0 You may use any algorithm. \n\n::* \u00a0 Bonus: explain why the algorithm you chose works.\n\n\n;Related tasks:\n* \u00a0 [[Determine_if_two_triangles_overlap]]\n\n\n;Also see:\n:* Discussion of several methods. [[http://totologic.blogspot.com/2014/01/accurate-point-in-triangle-test.html]]\n:* Determine if a point is in a polygon [[https://en.wikipedia.org/wiki/Point_in_polygon]]\n:* Triangle based coordinate systems [[https://en.wikipedia.org/wiki/Barycentric_coordinate_system]]\n:* Wolfram entry [[https://mathworld.wolfram.com/TriangleInterior.html]]\n\n", "solution": "\n\"\"\" find if point is in a triangle \"\"\"\n\nfrom sympy.geometry import Point, Triangle\n\ndef sign(pt1, pt2, pt3):\n \"\"\" which side of plane cut by line (pt2, pt3) is pt1 on? \"\"\"\n return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y)\n\n\ndef iswithin(point, pt1, pt2, pt3):\n \"\"\" \n Determine if point is within triangle formed by points p1, p2, p3.\n If so, the point will be on the same side of each of the half planes\n defined by vectors p1p2, p2p3, and p3p1. zval is positive if outside,\n negative if inside such a plane. All should be positive or all negative\n if point is within the triangle.\n \"\"\"\n zval1 = sign(point, pt1, pt2)\n zval2 = sign(point, pt2, pt3)\n zval3 = sign(point, pt3, pt1)\n notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0\n notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0\n return notanyneg or notanypos\n\nif __name__ == \"__main__\":\n POINTS = [Point(0, 0)]\n TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5))\n for pnt in POINTS:\n a, b, c = TRI.vertices\n isornot = \"is\" if iswithin(pnt, a, b, c) else \"is not\"\n print(\"Point\", pnt, isornot, \"within the triangle\", TRI)\n"} +{"title": "Find limit of recursion", "language": "C", "task": "[[Category:Basic language learning]]\n[[Category:Programming environment operations]] \n[[Category:Simple]]\n\n;Task:\nFind the limit of recursion.\n\n", "solution": "#include \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 limit of recursion", "language": "JavaScript", "task": "[[Category:Basic language learning]]\n[[Category:Programming environment operations]] \n[[Category:Simple]]\n\n;Task:\nFind the limit of recursion.\n\n", "solution": "\nfunction recurse(depth)\n{\n try\n {\n return recurse(depth + 1);\n }\n catch(ex)\n {\n return depth;\n }\n}\n\nvar maxRecursion = recurse(1);\ndocument.write(\"Recursion depth on this system is \" + maxRecursion);"} +{"title": "Find limit of recursion", "language": "Python", "task": "[[Category:Basic language learning]]\n[[Category:Programming environment operations]] \n[[Category:Simple]]\n\n;Task:\nFind the limit of recursion.\n\n", "solution": "def recurseDeeper(counter):\n try:\n print(counter)\n recurseDeeper(counter + 1)\n except RecursionError:\n print(\"RecursionError at depth\", counter)\n recurseDeeper(counter + 1)"} +{"title": "Find palindromic numbers in both binary and ternary bases", "language": "C", "task": ";Task:\n\n* \u00a0 Find and show (in decimal) the first six numbers (non-negative integers) that are \u00a0 palindromes \u00a0 in \u00a0 ''both'':\n:::* \u00a0 base 2\n:::* \u00a0 base 3\n* \u00a0 Display \u00a0 '''0''' \u00a0 (zero) as the first number found, even though some other definitions ignore it.\n* \u00a0 Optionally, show the decimal number found in its binary and ternary form.\n* \u00a0 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* \u00a0 Sequence A60792, \u00a0 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 palindromic numbers in both binary and ternary bases", "language": "JavaScript", "task": ";Task:\n\n* \u00a0 Find and show (in decimal) the first six numbers (non-negative integers) that are \u00a0 palindromes \u00a0 in \u00a0 ''both'':\n:::* \u00a0 base 2\n:::* \u00a0 base 3\n* \u00a0 Display \u00a0 '''0''' \u00a0 (zero) as the first number found, even though some other definitions ignore it.\n* \u00a0 Optionally, show the decimal number found in its binary and ternary form.\n* \u00a0 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* \u00a0 Sequence A60792, \u00a0 numbers that are palindromic in bases 2 and 3 on ''The On-Line Encyclopedia of Integer Sequences''.\n\n", "solution": "(() => {\n 'use strict';\n\n // GENERIC FUNCTIONS\n\n // range :: Int -> Int -> [Int]\n const range = (m, n) =>\n Array.from({\n length: Math.floor(n - m) + 1\n }, (_, i) => m + i);\n\n // compose :: (b -> c) -> (a -> b) -> (a -> c)\n const compose = (f, g) => x => f(g(x));\n\n // listApply :: [(a -> b)] -> [a] -> [b]\n const listApply = (fs, xs) =>\n [].concat.apply([], fs.map(f =>\n [].concat.apply([], xs.map(x => [f(x)]))));\n\n // pure :: a -> [a]\n const pure = x => [x];\n\n // curry :: Function -> Function\n const curry = (f, ...args) => {\n const go = xs => xs.length >= f.length ? (f.apply(null, xs)) :\n function () {\n return go(xs.concat([].slice.apply(arguments)));\n };\n return go([].slice.call(args, 1));\n };\n\n // transpose :: [[a]] -> [[a]]\n const transpose = xs =>\n xs[0].map((_, iCol) => xs.map(row => row[iCol]));\n\n // reverse :: [a] -> [a]\n const reverse = xs =>\n typeof xs === 'string' ? (\n xs.split('')\n .reverse()\n .join('')\n ) : xs.slice(0)\n .reverse();\n\n // take :: Int -> [a] -> [a]\n const take = (n, xs) => xs.slice(0, n);\n\n // drop :: Int -> [a] -> [a]\n const drop = (n, xs) => xs.slice(n);\n\n // maximum :: [a] -> a\n const maximum = xs =>\n xs.reduce((a, x) => (x > a || a === undefined ? x : a), undefined);\n\n // quotRem :: Integral a => a -> a -> (a, a)\n const quotRem = (m, n) => [Math.floor(m / n), m % n];\n\n // length :: [a] -> Int\n const length = xs => xs.length;\n\n // justifyLeft :: Int -> Char -> Text -> Text\n const justifyLeft = (n, cFiller, strText) =>\n n > strText.length ? (\n (strText + cFiller.repeat(n))\n .substr(0, n)\n ) : strText;\n\n // unwords :: [String] -> String\n const unwords = xs => xs.join(' ');\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n\n // BASES AND PALINDROMES\n\n // show, showBinary, showTernary :: Int -> String\n const show = n => n.toString(10);\n const showBinary = n => n.toString(2);\n const showTernary = n => n.toString(3);\n\n // readBase3 :: String -> Int\n const readBase3 = s => parseInt(s, 3);\n\n // base3Palindrome :: Int -> String\n const base3Palindrome = n => {\n const s = showTernary(n);\n return s + '1' + reverse(s);\n };\n\n // isBinPal :: Int -> Bool\n const isBinPal = n => {\n const\n s = showBinary(n),\n [q, r] = quotRem(s.length, 2);\n return (r !== 0) && drop(q + 1, s) === reverse(take(q, s));\n };\n\n // solutions :: [Int]\n const solutions = [0, 1].concat(range(1, 10E5)\n .map(compose(readBase3, base3Palindrome))\n .filter(isBinPal));\n\n // TABULATION\n\n // cols :: [[Int]]\n const cols = transpose(\n [\n ['Decimal', 'Ternary', 'Binary']\n ].concat(\n solutions.map(\n compose(\n xs => listApply([show, showTernary, showBinary], xs),\n pure\n )\n )\n )\n );\n\n return unlines(\n transpose(cols.map(col => col.map(\n curry(justifyLeft)(maximum(col.map(length)) + 1, ' ')\n )))\n .map(unwords));\n})();"} +{"title": "Find palindromic numbers in both binary and ternary bases", "language": "Python", "task": ";Task:\n\n* \u00a0 Find and show (in decimal) the first six numbers (non-negative integers) that are \u00a0 palindromes \u00a0 in \u00a0 ''both'':\n:::* \u00a0 base 2\n:::* \u00a0 base 3\n* \u00a0 Display \u00a0 '''0''' \u00a0 (zero) as the first number found, even though some other definitions ignore it.\n* \u00a0 Optionally, show the decimal number found in its binary and ternary form.\n* \u00a0 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* \u00a0 Sequence A60792, \u00a0 numbers that are palindromic in bases 2 and 3 on ''The On-Line Encyclopedia of Integer Sequences''.\n\n", "solution": "from itertools import islice\n\ndigits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n\ndef baseN(num,b):\n if num == 0: return \"0\"\n result = \"\"\n while num != 0:\n num, d = divmod(num, b)\n result += digits[d]\n return result[::-1] # reverse\n\ndef pal2(num):\n if num == 0 or num == 1: return True\n based = bin(num)[2:]\n return based == based[::-1]\n\ndef pal_23():\n yield 0\n yield 1\n n = 1\n while True:\n n += 1\n b = baseN(n, 3)\n revb = b[::-1]\n #if len(b) > 12: break\n for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),\n '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):\n t = int(trial, 3)\n if pal2(t):\n yield t\n\nfor pal23 in islice(pal_23(), 6):\n print(pal23, baseN(pal23, 3), baseN(pal23, 2))"} +{"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 \u00a0 (0,\u00a0-1,\u00a0-1) \u00a0 passing through position \u00a0 (0,\u00a00,\u00a010) \u00a0 with the infinite plane with a normal vector of \u00a0 (0,\u00a00,\u00a01) \u00a0 and which passes through [0,\u00a00,\u00a05].\n\n", "solution": "\n#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 a line with a plane", "language": "Python", "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 \u00a0 (0,\u00a0-1,\u00a0-1) \u00a0 passing through position \u00a0 (0,\u00a00,\u00a010) \u00a0 with the infinite plane with a normal vector of \u00a0 (0,\u00a00,\u00a01) \u00a0 and which passes through [0,\u00a00,\u00a05].\n\n", "solution": "#!/bin/python\nfrom __future__ import print_function\nimport numpy as np\n\ndef LinePlaneCollision(planeNormal, planePoint, rayDirection, rayPoint, epsilon=1e-6):\n\n\tndotu = planeNormal.dot(rayDirection)\n\tif abs(ndotu) < epsilon:\n\t\traise RuntimeError(\"no intersection or line is within plane\")\n\n\tw = rayPoint - planePoint\n\tsi = -planeNormal.dot(w) / ndotu\n\tPsi = w + si * rayDirection + planePoint\n\treturn Psi\n\n\nif __name__==\"__main__\":\n\t#Define plane\n\tplaneNormal = np.array([0, 0, 1])\n\tplanePoint = np.array([0, 0, 5]) #Any point on the plane\n\n\t#Define ray\n\trayDirection = np.array([0, -1, -1])\n\trayPoint = np.array([0, 0, 10]) #Any point along the ray\n\n\tPsi = LinePlaneCollision(planeNormal, planePoint, rayDirection, rayPoint)\n\tprint (\"intersection at\", Psi)"} +{"title": "Find the intersection of two lines", "language": "C", "task": ";Task:\nFind the point of intersection of two lines in 2D. \n\n\nThe 1st line passes though \u00a0 (4,0) \u00a0 and \u00a0 (6,10) . \nThe 2nd line passes though \u00a0 (0,3) \u00a0 and \u00a0 (10,7) .\n\n", "solution": "\n#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 intersection of two lines", "language": "JavaScript", "task": ";Task:\nFind the point of intersection of two lines in 2D. \n\n\nThe 1st line passes though \u00a0 (4,0) \u00a0 and \u00a0 (6,10) . \nThe 2nd line passes though \u00a0 (0,3) \u00a0 and \u00a0 (10,7) .\n\n", "solution": "(() => {\n 'use strict';\n // INTERSECTION OF TWO LINES ----------------------------------------------\n\n // intersection :: Line -> Line -> Either String (Float, Float)\n const intersection = (ab, pq) => {\n const\n delta = f => x => f(fst(x)) - f(snd(x)),\n [abDX, pqDX, abDY, pqDY] = apList(\n [delta(fst), delta(snd)], [ab, pq]\n ),\n determinant = abDX * pqDY - abDY * pqDX;\n\n return determinant !== 0 ? Right((() => {\n const [abD, pqD] = map(\n ([a, b]) => fst(a) * snd(b) - fst(b) * snd(a),\n [ab, pq]\n );\n return apList(\n [([pq, ab]) =>\n (abD * pq - ab * pqD) / determinant\n ], [\n [pqDX, abDX],\n [pqDY, abDY]\n ]\n );\n })()) : Left('(Parallel lines \u2013 no intersection)');\n };\n\n // GENERIC FUNCTIONS ------------------------------------------------------\n\n // Left :: a -> Either a b\n const Left = x => ({\n type: 'Either',\n Left: x\n });\n\n // Right :: b -> Either a b\n const Right = x => ({\n type: 'Either',\n Right: x\n });\n\n // A list of functions applied to a list of arguments\n // <*> :: [(a -> b)] -> [a] -> [b]\n const apList = (fs, xs) => //\n [].concat.apply([], fs.map(f => //\n [].concat.apply([], xs.map(x => [f(x)]))));\n\n // fst :: (a, b) -> a\n const fst = tpl => tpl[0];\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) => xs.map(f);\n\n // snd :: (a, b) -> b\n const snd = tpl => tpl[1];\n\n // show :: a -> String\n const show = x => JSON.stringify(x); //, null, 2);\n\n\n // TEST --------------------------------------------------\n\n // lrIntersection ::Either String Point\n const lrIntersection = intersection([\n [4.0, 0.0],\n [6.0, 10.0]\n ], [\n [0.0, 3.0],\n [10.0, 7.0]\n ]);\n return show(lrIntersection.Left || lrIntersection.Right);\n})();"} +{"title": "Find the intersection of two lines", "language": "Python", "task": ";Task:\nFind the point of intersection of two lines in 2D. \n\n\nThe 1st line passes though \u00a0 (4,0) \u00a0 and \u00a0 (6,10) . \nThe 2nd line passes though \u00a0 (0,3) \u00a0 and \u00a0 (10,7) .\n\n", "solution": "def line_intersect(Ax1, Ay1, Ax2, Ay2, Bx1, By1, Bx2, By2):\n \"\"\" returns a (x, y) tuple or None if there is no intersection \"\"\"\n d = (By2 - By1) * (Ax2 - Ax1) - (Bx2 - Bx1) * (Ay2 - Ay1)\n if d:\n uA = ((Bx2 - Bx1) * (Ay1 - By1) - (By2 - By1) * (Ax1 - Bx1)) / d\n uB = ((Ax2 - Ax1) * (Ay1 - By1) - (Ay2 - Ay1) * (Ax1 - Bx1)) / d\n else:\n return\n if not(0 <= uA <= 1 and 0 <= uB <= 1):\n return\n x = Ax1 + uA * (Ax2 - Ax1)\n y = Ay1 + uA * (Ay2 - Ay1)\n \n return x, y\n\nif __name__ == '__main__':\n (a, b), (c, d) = (4, 0), (6, 10) # try (4, 0), (6, 4)\n (e, f), (g, h) = (0, 3), (10, 7) # for non intersecting test\n pt = line_intersect(a, b, c, d, e, f, g, h)\n print(pt)"} +{"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": "\n#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 last Sunday of each month", "language": "JavaScript", "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": "function lastSundayOfEachMonths(year) {\n\tvar lastDay = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n\tvar sundays = [];\n\tvar date, month;\n\tif (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) {\n\t\tlastDay[2] = 29;\n\t}\n\tfor (date = new Date(), month = 0; month < 12; month += 1) {\n\t\tdate.setFullYear(year, month, lastDay[month]);\n\t\tdate.setDate(date.getDate() - date.getDay());\n\t\tsundays.push(date.toISOString().substring(0, 10));\n\t}\n\treturn sundays;\n}\n\nconsole.log(lastSundayOfEachMonths(2013).join('\\n'));"} +{"title": "Find the last Sunday of each month", "language": "Python", "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": "\nimport sys\nimport calendar\n\nyear = 2013\nif len(sys.argv) > 1:\n try:\n year = int(sys.argv[-1])\n except ValueError:\n pass\n\nfor month in range(1, 13):\n last_sunday = max(week[-1] for week in calendar.monthcalendar(year, month))\n print('{}-{}-{:2}'.format(year, calendar.month_abbr[month], last_sunday))\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 \u00a0 all-but-one \u00a0 of the permutations of the symbols \u00a0 '''A''', \u00a0 '''B''', \u00a0 '''C''', \u00a0 and \u00a0 '''D''', \u00a0 ''except'' \u00a0 for one permutation that's \u00a0 ''not'' \u00a0 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* \u00a0 [[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": "Find the missing permutation", "language": "JavaScript", "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 \u00a0 all-but-one \u00a0 of the permutations of the symbols \u00a0 '''A''', \u00a0 '''B''', \u00a0 '''C''', \u00a0 and \u00a0 '''D''', \u00a0 ''except'' \u00a0 for one permutation that's \u00a0 ''not'' \u00a0 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* \u00a0 [[Permutations]])\n\n", "solution": "(function (strList) {\n\n // [a] -> [[a]]\n function permutations(xs) {\n return xs.length ? (\n chain(xs, function (x) {\n return chain(permutations(deleted(x, xs)), function (ys) {\n return [[x].concat(ys).join('')];\n })\n })) : [[]];\n }\n\n // Monadic bind/chain for lists\n // [a] -> (a -> b) -> [b]\n function chain(xs, f) {\n return [].concat.apply([], xs.map(f));\n }\n\n // a -> [a] -> [a]\n function deleted(x, xs) {\n return xs.length ? (\n x === xs[0] ? xs.slice(1) : [xs[0]].concat(\n deleted(x, xs.slice(1))\n )\n ) : [];\n }\n\n // Provided subset\n var lstSubSet = strList.split('\\n');\n\n // Any missing permutations\n // (we can use fold/reduce, filter, or chain (concat map) here)\n return chain(permutations('ABCD'.split('')), function (x) {\n return lstSubSet.indexOf(x) === -1 ? [x] : [];\n });\n\n})(\n 'ABCD\\nCABD\\nACDB\\nDACB\\nBCDA\\nACBD\\nADCB\\nCDAB\\nDABC\\nBCAD\\nCADB\\n\\\nCDBA\\nCBAD\\nABDC\\nADBC\\nBDCA\\nDCBA\\nBACD\\nBADC\\nBDAC\\nCBDA\\nDBCA\\nDCAB'\n);"} +{"title": "Find the missing permutation", "language": "Python", "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 \u00a0 all-but-one \u00a0 of the permutations of the symbols \u00a0 '''A''', \u00a0 '''B''', \u00a0 '''C''', \u00a0 and \u00a0 '''D''', \u00a0 ''except'' \u00a0 for one permutation that's \u00a0 ''not'' \u00a0 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* \u00a0 [[Permutations]])\n\n", "solution": "===Python: Calculate difference when compared to all permutations===\n"} +{"title": "Find the missing permutation", "language": "Python 2.6+", "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 \u00a0 all-but-one \u00a0 of the permutations of the symbols \u00a0 '''A''', \u00a0 '''B''', \u00a0 '''C''', \u00a0 and \u00a0 '''D''', \u00a0 ''except'' \u00a0 for one permutation that's \u00a0 ''not'' \u00a0 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* \u00a0 [[Permutations]])\n\n", "solution": "\ndef missing_permutation(arr):\n \"Find the missing permutation in an array of N! - 1 permutations.\"\n \n # We won't validate every precondition, but we do have some basic\n # guards.\n if len(arr) == 0: raise Exception(\"Need more data\")\n if len(arr) == 1:\n return [arr[0][1] + arr[0][0]]\n \n # Now we know that for each position in the string, elements should appear\n # an even number of times (N-1 >= 2). We can use a set to detect the element appearing\n # an odd number of times. Detect odd occurrences by toggling admission/expulsion\n # to and from the set for each value encountered. At the end of each pass one element\n # will remain in the set.\n missing_permutation = ''\n for pos in range(len(arr[0])):\n s = set()\n for permutation in arr:\n c = permutation[pos]\n if c in s:\n s.remove(c)\n else:\n s.add(c)\n missing_permutation += list(s)[0]\n return missing_permutation\n \ngiven = '''ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA\n CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB'''.split()\n \nprint missing_permutation(given)\n"} +{"title": "First-class functions/Use numbers analogously", "language": "JavaScript", "task": "In [[First-class functions]], a language is showing how its manipulation of functions is similar to its manipulation of other types.\n\nThis tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.\n\n\nWrite a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections:\n x = 2.0\n xi = 0.5\n y = 4.0\n yi = 0.25\n z = x + y\n zi = 1.0 / ( x + y )\n\nCreate a function ''multiplier'', that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call:\n new_function = multiplier(n1,n2)\n # where new_function(m) returns the result of n1 * n2 * m\n\nApplying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one.\n'''Compare and contrast the resultant program with the corresponding entry in [[First-class functions]].''' They should be close.\n\nTo paraphrase the task description: Do what was done before, but with numbers rather than functions\n\n", "solution": "const x = 2.0;\nconst xi = 0.5;\nconst y = 4.0;\nconst yi = 0.25;\nconst z = x + y;\nconst zi = 1.0 / (x + y);\nconst pairs = [[x, xi], [y, yi], [z, zi]];\nconst testVal = 0.5;\n\nconst multiplier = (a, b) => m => a * b * m;\n\nconst test = () => {\n return pairs.map(([a, b]) => {\n const f = multiplier(a, b);\n const result = f(testVal);\n return `${a} * ${b} * ${testVal} = ${result}`;\n });\n}\n\ntest().join('\\n');"} +{"title": "First-class functions/Use numbers analogously", "language": "Python", "task": "In [[First-class functions]], a language is showing how its manipulation of functions is similar to its manipulation of other types.\n\nThis tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.\n\n\nWrite a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections:\n x = 2.0\n xi = 0.5\n y = 4.0\n yi = 0.25\n z = x + y\n zi = 1.0 / ( x + y )\n\nCreate a function ''multiplier'', that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call:\n new_function = multiplier(n1,n2)\n # where new_function(m) returns the result of n1 * n2 * m\n\nApplying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one.\n'''Compare and contrast the resultant program with the corresponding entry in [[First-class functions]].''' They should be close.\n\nTo paraphrase the task description: Do what was done before, but with numbers rather than functions\n\n", "solution": ">>> # Some built in functions and their inverses\n>>> from math import sin, cos, acos, asin\n>>> # Add a user defined function and its inverse\n>>> cube = lambda x: x * x * x\n>>> croot = lambda x: x ** (1/3.0)\n>>> # First class functions allow run-time creation of functions from functions\n>>> # return function compose(f,g)(x) == f(g(x))\n>>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) )\n>>> # first class functions should be able to be members of collection types\n>>> funclist = [sin, cos, cube]\n>>> funclisti = [asin, acos, croot]\n>>> # Apply functions from lists as easily as integers\n>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]\n[0.5, 0.4999999999999999, 0.5]\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''' ('''32043\u00b2''').\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": "First perfect square in base n with n unique digits", "language": "JavaScript", "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''' ('''32043\u00b2''').\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": "(() => {\n 'use strict';\n\n // allDigitSquare :: Int -> Int\n const allDigitSquare = base => {\n const bools = replicate(base, false);\n return untilSucc(\n allDigitsUsedAtBase(base, bools),\n ceil(sqrt(parseInt(\n '10' + '0123456789abcdef'.slice(2, base),\n base\n )))\n );\n };\n\n // allDigitsUsedAtBase :: Int -> [Bool] -> Int -> Bool\n const allDigitsUsedAtBase = (base, bools) => n => {\n // Fusion of representing the square of integer N at a given base\n // with checking whether all digits of that base contribute to N^2.\n // Sets the bool at a digit position to True when used.\n // True if all digit positions have been used.\n const ds = bools.slice(0);\n let x = n * n;\n while (x) {\n ds[x % base] = true;\n x = floor(x / base);\n }\n return ds.every(x => x)\n };\n\n // showBaseSquare :: Int -> String\n const showBaseSquare = b => {\n const q = allDigitSquare(b);\n return justifyRight(2, ' ', str(b)) + ' -> ' +\n justifyRight(8, ' ', showIntAtBase(b, digit, q, '')) +\n ' -> ' + showIntAtBase(b, digit, q * q, '');\n };\n\n // TEST -----------------------------------------------\n const main = () => {\n // 1-12 only - by 15 the squares are truncated by\n // JS integer limits.\n\n // Returning values through console.log \u2013\n // in separate events to avoid asynchronous disorder.\n print('Smallest perfect squares using all digits in bases 2-12:\\n')\n (id > 0 ? chars.substr(id, 1) : \" \") print('Base Root Square')\n\n print(showBaseSquare(2));\n print(showBaseSquare(3));\n print(showBaseSquare(4));\n print(showBaseSquare(5));\n print(showBaseSquare(6));\n print(showBaseSquare(7));\n print(showBaseSquare(8));\n print(showBaseSquare(9));\n print(showBaseSquare(10));\n print(showBaseSquare(11));\n print(showBaseSquare(12));\n };\n\n // GENERIC FUNCTIONS ----------------------------------\n \n const\n ceil = Math.ceil,\n floor = Math.floor,\n sqrt = Math.sqrt;\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = (a, b) => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // digit :: Int -> Char\n const digit = n =>\n // Digit character for given integer.\n '0123456789abcdef' [n];\n\n // enumFromTo :: (Int, Int) -> [Int]\n const enumFromTo = (m, n) =>\n Array.from({\n length: 1 + n - m\n }, (_, i) => m + i);\n\n // justifyRight :: Int -> Char -> String -> String\n const justifyRight = (n, cFiller, s) =>\n n > s.length ? (\n s.padStart(n, cFiller)\n ) : s;\n\n // print :: a -> IO ()\n const print = x => console.log(x)\n\n // quotRem :: Int -> Int -> (Int, Int)\n const quotRem = (m, n) =>\n Tuple(Math.floor(m / n), m % n);\n\n // replicate :: Int -> a -> [a]\n const replicate = (n, x) =>\n Array.from({\n length: n\n }, () => x);\n\n // showIntAtBase :: Int -> (Int -> Char) -> Int -> String -> String\n const showIntAtBase = (base, toChr, n, rs) => {\n const go = ([n, d], r) => {\n const r_ = toChr(d) + r;\n return 0 !== n ? (\n go(Array.from(quotRem(n, base)), r_)\n ) : r_;\n };\n return 1 >= base ? (\n 'error: showIntAtBase applied to unsupported base'\n ) : 0 > n ? (\n 'error: showIntAtBase applied to negative number'\n ) : go(Array.from(quotRem(n, base)), rs);\n };\n\n // Abbreviation for quick testing - any 2nd arg interpreted as indent size\n\n // sj :: a -> String\n function sj() {\n const args = Array.from(arguments);\n return JSON.stringify.apply(\n null,\n 1 < args.length && !isNaN(args[0]) ? [\n args[1], null, args[0]\n ] : [args[0], null, 2]\n );\n }\n\n // str :: a -> String\n const str = x => x.toString();\n\n // untilSucc :: (Int -> Bool) -> Int -> Int\n const untilSucc = (p, x) => {\n // The first in a chain of successive integers\n // for which p(x) returns true.\n let v = x;\n while (!p(v)) v = 1 + v;\n return v;\n };\n\n // MAIN ---\n return main();\n})();"} +{"title": "First perfect square in base n with n unique digits", "language": "Python 3.7", "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''' ('''32043\u00b2''').\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": "'''Perfect squares using every digit in a given base.'''\n\nfrom itertools import count, dropwhile, repeat\nfrom math import ceil, sqrt\nfrom time import time\n\n\n# allDigitSquare :: Int -> Int -> Int\ndef allDigitSquare(base, above):\n '''The lowest perfect square which\n requires all digits in the given base.\n '''\n bools = list(repeat(True, base))\n return next(\n dropwhile(\n missingDigitsAtBase(base, bools),\n count(\n max(\n above,\n ceil(sqrt(int(\n '10' + '0123456789abcdef'[2:base],\n base\n )))\n )\n )\n )\n )\n\n\n# missingDigitsAtBase :: Int -> [Bool] -> Int -> Bool\ndef missingDigitsAtBase(base, bools):\n '''Fusion of representing the square of integer N at a\n given base with checking whether all digits of\n that base contribute to N^2.\n Clears the bool at a digit position to False when used.\n True if any positions remain uncleared (unused).\n '''\n def go(x):\n xs = bools.copy()\n while x:\n xs[x % base] = False\n x //= base\n return any(xs)\n return lambda n: go(n * n)\n\n\n# digit :: Int -> Char\ndef digit(n):\n '''Digit character for given integer.'''\n return '0123456789abcdef'[n]\n\n\n# ------------------------- TEST -------------------------\n# main :: IO ()\ndef main():\n '''Smallest perfect squares using all digits in bases 2-16'''\n\n start = time()\n\n print(main.__doc__ + ':\\n\\nBase Root Square')\n q = 0\n for b in enumFromTo(2)(16):\n q = allDigitSquare(b, q)\n print(\n str(b).rjust(2, ' ') + ' -> ' +\n showIntAtBase(b)(digit)(q)('').rjust(8, ' ') +\n ' -> ' +\n showIntAtBase(b)(digit)(q * q)('')\n )\n\n print(\n '\\nc. ' + str(ceil(time() - start)) + ' seconds.'\n )\n\n\n# ----------------------- GENERIC ------------------------\n\n# enumFromTo :: (Int, Int) -> [Int]\ndef enumFromTo(m):\n '''Integer enumeration from m to n.'''\n return lambda n: list(range(m, 1 + n))\n\n\n# showIntAtBase :: Int -> (Int -> String) -> Int -> \n# String -> String\ndef showIntAtBase(base):\n '''String representation of an integer in a given base,\n using a supplied function for the string representation\n of digits.\n '''\n def wrap(toChr, n, rs):\n def go(nd, r):\n n, d = nd\n r_ = toChr(d) + r\n return go(divmod(n, base), r_) if 0 != n else r_\n return 'unsupported base' if 1 >= base else (\n 'negative number' if 0 > n else (\n go(divmod(n, base), rs))\n )\n return lambda toChr: lambda n: lambda rs: (\n wrap(toChr, n, rs)\n )\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()\n"} +{"title": "First power of 2 that has leading decimal digits of 12", "language": "C", "task": "(This task is taken from a \u00a0 ''Project Euler'' \u00a0 problem.)\n\n(All numbers herein are expressed in base ten.)\n\n\n'''27 \u00a0 = \u00a0 128''' \u00a0 and \u00a0 '''7''' \u00a0 is\nthe first power of \u00a0 '''2''' \u00a0 whose leading decimal digits are \u00a0 '''12'''.\n\nThe next power of \u00a0 '''2''' \u00a0 whose leading decimal digits\nare \u00a0 '''12''' \u00a0 is \u00a0 '''80''',\n'''280 \u00a0 = \u00a0 1208925819614629174706176'''.\n\n\nDefine \u00a0 \u00a0 ''' '' p''(''L,n'')''' \u00a0 \u00a0 to be the ''' ''n''th'''-smallest\nvalue of \u00a0 ''' ''j'' ''' \u00a0 such that the base ten representation\nof \u00a0 '''2''j''''' \u00a0 begins with the digits of \u00a0 ''' ''L'' '''.\n\n So ''p''(12, 1) = 7 and\n ''p''(12, 2) = 80\n\n\nYou are also given that:\n ''p''(123, 45) \u00a0 = \u00a0 12710\n\n\n;Task:\n::* \u00a0 find: \n:::::* \u00a0 ''' ''p''(12, 1) ''' \n:::::* \u00a0 ''' ''p''(12, 2) ''' \n:::::* \u00a0 ''' ''p''(123, 45) ''' \n:::::* \u00a0 ''' ''p''(123, 12345) ''' \n:::::* \u00a0 ''' ''p''(123, 678910) ''' \n::* \u00a0 display the results here, on this page.\n\n", "solution": "#include \n#include \n\nint p(int l, int n) {\n int test = 0;\n double logv = log(2.0) / log(10.0);\n int factor = 1;\n int loop = l;\n while (loop > 10) {\n factor *= 10;\n loop /= 10;\n }\n while (n > 0) {\n int val;\n\n test++;\n val = (int)(factor * pow(10.0, fmod(test * logv, 1)));\n if (val == l) {\n n--;\n }\n }\n return test;\n}\n\nvoid runTest(int l, int n) {\n printf(\"p(%d, %d) = %d\\n\", l, n, p(l, n));\n}\n\nint main() {\n runTest(12, 1);\n runTest(12, 2);\n runTest(123, 45);\n runTest(123, 12345);\n runTest(123, 678910);\n\n return 0;\n}"} +{"title": "First power of 2 that has leading decimal digits of 12", "language": "Python", "task": "(This task is taken from a \u00a0 ''Project Euler'' \u00a0 problem.)\n\n(All numbers herein are expressed in base ten.)\n\n\n'''27 \u00a0 = \u00a0 128''' \u00a0 and \u00a0 '''7''' \u00a0 is\nthe first power of \u00a0 '''2''' \u00a0 whose leading decimal digits are \u00a0 '''12'''.\n\nThe next power of \u00a0 '''2''' \u00a0 whose leading decimal digits\nare \u00a0 '''12''' \u00a0 is \u00a0 '''80''',\n'''280 \u00a0 = \u00a0 1208925819614629174706176'''.\n\n\nDefine \u00a0 \u00a0 ''' '' p''(''L,n'')''' \u00a0 \u00a0 to be the ''' ''n''th'''-smallest\nvalue of \u00a0 ''' ''j'' ''' \u00a0 such that the base ten representation\nof \u00a0 '''2''j''''' \u00a0 begins with the digits of \u00a0 ''' ''L'' '''.\n\n So ''p''(12, 1) = 7 and\n ''p''(12, 2) = 80\n\n\nYou are also given that:\n ''p''(123, 45) \u00a0 = \u00a0 12710\n\n\n;Task:\n::* \u00a0 find: \n:::::* \u00a0 ''' ''p''(12, 1) ''' \n:::::* \u00a0 ''' ''p''(12, 2) ''' \n:::::* \u00a0 ''' ''p''(123, 45) ''' \n:::::* \u00a0 ''' ''p''(123, 12345) ''' \n:::::* \u00a0 ''' ''p''(123, 678910) ''' \n::* \u00a0 display the results here, on this page.\n\n", "solution": "from math import log, modf, floor\n\ndef p(l, n, pwr=2):\n l = int(abs(l))\n digitcount = floor(log(l, 10))\n log10pwr = log(pwr, 10)\n raised, found = -1, 0\n while found < n:\n raised += 1\n firstdigits = floor(10**(modf(log10pwr * raised)[0] + digitcount))\n if firstdigits == l:\n found += 1\n return raised\n\n\nif __name__ == '__main__':\n for l, n in [(12, 1), (12, 2), (123, 45), (123, 12345), (123, 678910)]:\n print(f\"p({l}, {n}) =\", p(l, n))"} +{"title": "Fivenum", "language": "C", "task": "Many big data or scientific programs use boxplots to show distributions of data. \u00a0 In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. \u00a0 It can be useful to save large arrays as arrays with five numbers to save memory.\n\nFor example, the \u00a0 '''R''' \u00a0 programming language implements Tukey's five-number summary as the '''[https://stat.ethz.ch/R-manual/R-devel/library/stats/html/fivenum.html fivenum]''' function.\n\n\n;Task:\nGiven an array of numbers, compute the five-number summary.\n\n\n;Note: \nWhile these five numbers can be used to draw a boxplot, \u00a0 statistical packages will typically need extra data. \n\nMoreover, while there is a consensus about the \"box\" of the boxplot, \u00a0 there are variations among statistical packages for the whiskers.\n\n", "solution": "#include \n#include \n\ndouble median(double *x, int start, int end_inclusive) {\n int size = end_inclusive - start + 1;\n if (size <= 0) {\n printf(\"Array slice cannot be empty\\n\");\n exit(1);\n }\n int m = start + size / 2;\n if (size % 2) return x[m];\n return (x[m - 1] + x[m]) / 2.0;\n}\n\nint compare (const void *a, const void *b) {\n double aa = *(double*)a; \n double bb = *(double*)b;\n if (aa > bb) return 1;\n if (aa < bb) return -1;\n return 0;\n}\n\nint fivenum(double *x, double *result, int x_len) {\n int i, m, lower_end;\n for (i = 0; i < x_len; i++) {\n if (x[i] != x[i]) {\n printf(\"Unable to deal with arrays containing NaN\\n\\n\");\n return 1;\n }\n } \n qsort(x, x_len, sizeof(double), compare);\n result[0] = x[0];\n result[2] = median(x, 0, x_len - 1);\n result[4] = x[x_len - 1];\n m = x_len / 2;\n lower_end = (x_len % 2) ? m : m - 1;\n result[1] = median(x, 0, lower_end);\n result[3] = median(x, m, x_len - 1);\n return 0;\n}\n\nint show(double *result, int places) {\n int i;\n char f[7];\n sprintf(f, \"%%.%dlf\", places);\n printf(\"[\");\n for (i = 0; i < 5; i++) { \n printf(f, result[i]);\n if (i < 4) printf(\", \");\n }\n printf(\"]\\n\\n\");\n}\n\nint main() {\n double result[5];\n\n double x1[11] = {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0};\n if (!fivenum(x1, result, 11)) show(result, 1);\n\n double x2[6] = {36.0, 40.0, 7.0, 39.0, 41.0, 15.0};\n if (!fivenum(x2, result, 6)) show(result, 1);\n\n double x3[20] = {\n 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555,\n -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527,\n -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385,\n 0.75775634, 0.32566578\n };\n if (!fivenum(x3, result, 20)) show(result, 9);\n\n return 0;\n}"} +{"title": "Fivenum", "language": "JavaScript", "task": "Many big data or scientific programs use boxplots to show distributions of data. \u00a0 In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. \u00a0 It can be useful to save large arrays as arrays with five numbers to save memory.\n\nFor example, the \u00a0 '''R''' \u00a0 programming language implements Tukey's five-number summary as the '''[https://stat.ethz.ch/R-manual/R-devel/library/stats/html/fivenum.html fivenum]''' function.\n\n\n;Task:\nGiven an array of numbers, compute the five-number summary.\n\n\n;Note: \nWhile these five numbers can be used to draw a boxplot, \u00a0 statistical packages will typically need extra data. \n\nMoreover, while there is a consensus about the \"box\" of the boxplot, \u00a0 there are variations among statistical packages for the whiskers.\n\n", "solution": "\nfunction median(arr) {\n let mid = Math.floor(arr.length / 2);\n return (arr.length % 2 == 0) ? (arr[mid-1] + arr[mid]) / 2 : arr[mid];\n}\n\nArray.prototype.fiveNums = function() {\n this.sort(function(a, b) { return a - b} );\n let mid = Math.floor(this.length / 2),\n loQ = (this.length % 2 == 0) ? this.slice(0, mid) : this.slice(0, mid+1),\n hiQ = this.slice(mid);\n return [ this[0],\n median(loQ),\n median(this),\n median(hiQ),\n this[this.length-1] ];\n}\n\n// testing\nlet test = [15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43];\nconsole.log( test.fiveNums() );\n\ntest = [0, 0, 1, 2, 63, 61, 27, 13];\nconsole.log( test.fiveNums() );\n\ntest = [ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594,\n 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772,\n 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469,\n 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578];\nconsole.log( test.fiveNums() );\n"} +{"title": "Fivenum", "language": "Python", "task": "Many big data or scientific programs use boxplots to show distributions of data. \u00a0 In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. \u00a0 It can be useful to save large arrays as arrays with five numbers to save memory.\n\nFor example, the \u00a0 '''R''' \u00a0 programming language implements Tukey's five-number summary as the '''[https://stat.ethz.ch/R-manual/R-devel/library/stats/html/fivenum.html fivenum]''' function.\n\n\n;Task:\nGiven an array of numbers, compute the five-number summary.\n\n\n;Note: \nWhile these five numbers can be used to draw a boxplot, \u00a0 statistical packages will typically need extra data. \n\nMoreover, while there is a consensus about the \"box\" of the boxplot, \u00a0 there are variations among statistical packages for the whiskers.\n\n", "solution": "from __future__ import division\nimport math\nimport sys\n\ndef fivenum(array):\n n = len(array)\n if n == 0:\n print(\"you entered an empty array.\")\n sys.exit()\n x = sorted(array)\n \n n4 = math.floor((n+3.0)/2.0)/2.0\n d = [1, n4, (n+1)/2, n+1-n4, n]\n sum_array = []\n \n for e in range(5):\n floor = int(math.floor(d[e] - 1))\n ceil = int(math.ceil(d[e] - 1))\n sum_array.append(0.5 * (x[floor] + x[ceil]))\n \n return sum_array\n\nx = [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970,\n-0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163,\n1.04312009, -0.10305385, 0.75775634, 0.32566578]\n\ny = fivenum(x)\nprint(y)"} +{"title": "Fixed length records", "language": "Python", "task": "Fixed length read/write\n\nBefore terminals, computers commonly used [https://en.wikipedia.org/wiki/Punched_card_reader punch card readers] or paper tape input.\n\nA common format before these devices were superseded by terminal technology was based on the Hollerith code, [https://en.wikipedia.org/wiki/Hollerith_card Hollerith code].\n\nThese input devices handled 80 columns per card and had a limited character set, encoded by punching holes in one or more rows of the card for each column.\n\nThese devices assumed/demanded a fixed line width of 80 characters, newlines were not required (and could not even be encoded in some systems).\n\n;Task:\nWrite a program to read 80 column fixed length records (no newline terminators (but newline characters allowed in the data)) and then write out the reverse of each line as fixed length 80 column records. \n\nSamples here use printable characters, but that is not a given with fixed length data. Filenames used are sample.txt, infile.dat, outfile.dat.\n\n'''Note:''' There are no newlines, inputs and outputs are fixed at 80 columns, no more, no less, space padded. Fixed length data is 8 bit complete. NUL bytes of zero are allowed.\n\nThese fixed length formats are still in wide use on mainframes, with JCL and with COBOL (which commonly use [https://en.wikipedia.org/wiki/EBCDIC EBCDIC] encoding and not [https://en.wikipedia.org/wiki/ASCII ASCII]). Most of the large players in day to day financial transactions know all about fixed length records and the expression ''logical record length''.\n\n;Sample data:\nTo create the sample input file, use an editor that supports fixed length records or use a conversion utility. For instance, most GNU/Linux versions of '''dd''' support blocking and unblocking records with a conversion byte size.\n\nLine 1...1.........2.........3.........4.........5.........6.........7.........8\nLine 2\nLine 3\nLine 4\n\nLine 6\nLine 7\n Indented line 8............................................................\nLine 9 RT MARGIN\nprompt$ dd if=sample.txt of=infile.dat cbs=80 conv=block will create a fixed length record file of 80 bytes given newline delimited text input.\n\nprompt$ dd if=infile.dat cbs=80 conv=unblock will display a file with 80 byte logical record lengths to standard out as standard text with newlines.\n\n\n;Bonus round:\nForth systems often include BLOCK words. A block is 1024 bytes. Source code is stored as 16 lines of 64 characters each (again, no newline character or sequence to mark the end of a line).\n\nWrite a program to convert a block file to text (using newlines). Trailing spaces should be excluded from the output.\n\nAlso demonstrate how to convert from a normal text file to block form. All lines either truncated or padded to 64 characters with no newline terminators. The last block filled to be exactly 1024 characters by adding blanks if needed. Assume a full range of 8 bit byte values for each character.\n\nThe COBOL example uses forth.txt and forth.blk filenames.\n\n", "solution": "\ninfile = open('infile.dat', 'rb')\noutfile = open('outfile.dat', 'wb')\n\nwhile True:\n onerecord = infile.read(80)\n if len(onerecord) < 80:\n break\n onerecordreversed = bytes(reversed(onerecord))\n outfile.write(onerecordreversed)\n\ninfile.close()\noutfile.close()\n"} +{"title": "Flatten a list", "language": "C", "task": ";Task:\nWrite 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* \u00a0 [[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": "Flatten a list", "language": "JavaScript", "task": ";Task:\nWrite 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* \u00a0 [[Tree traversal]]\n\n", "solution": "(function () {\n 'use strict';\n\n // flatten :: Tree a -> [a]\n function flatten(t) {\n return (t instanceof Array ? concatMap(flatten, t) : t);\n }\n\n // concatMap :: (a -> [b]) -> [a] -> [b]\n function concatMap(f, xs) {\n return [].concat.apply([], xs.map(f));\n }\n\n return flatten(\n [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]\n );\n\n})();"} +{"title": "Flatten a list", "language": "Python", "task": ";Task:\nWrite 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* \u00a0 [[Tree traversal]]\n\n", "solution": ">>> def flatten(itr):\n>>> for x in itr:\n>>> try:\n>>> yield from flatten(x)\n>>> except:\n>>> yield x\n\n>>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]\n\n>>> list(flatten(lst))\n[1, 2, 3, 4, 5, 6, 7, 8]\n\n>>> tuple(flatten(lst))\n(1, 2, 3, 4, 5, 6, 7, 8)\n\n>>>for i in flatten(lst):\n>>> print(i)\n1\n2\n3\n4\n5\n6\n7\n8"} +{"title": "Flatten a list", "language": "Python 3.7", "task": ";Task:\nWrite 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* \u00a0 [[Tree traversal]]\n\n", "solution": "'''Flatten a nested list'''\n\nfrom itertools import (chain)\n\n\n# ----------------------- FLATTEN ------------------------\n\n# flatten :: NestedList a -> [a]\ndef flatten(x):\n '''A list of atomic values resulting from fully\n flattening an arbitrarily nested list.\n '''\n return concatMap(flatten)(x) if (\n isinstance(x, list)\n ) else [x]\n\n\n# ------------------------- TEST -------------------------\ndef main():\n '''Test: flatten an arbitrarily nested list.\n '''\n print(\n fTable(__doc__ + ':')(showList)(showList)(\n flatten\n )([\n [[[]]],\n [[1, 2, 3]],\n [[1], [[2]], [[[3, 4]]]],\n [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]\n ])\n )\n\n\n# ----------------------- GENERIC ------------------------\n\n# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n '''Right to left function composition.'''\n return lambda f: lambda x: g(f(x))\n\n\n# concatMap :: (a -> [b]) -> [a] -> [b]\ndef concatMap(f):\n '''A concatenated list over which a function has been mapped.\n The list monad can be derived by using a function f which\n wraps its output in a list,\n (using an empty list to represent computational failure).\n '''\n def go(xs):\n return chain.from_iterable(map(f, xs))\n return go\n\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) ->\n# (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function ->\n fx display function ->\n f -> value list -> tabular string.'''\n def go(xShow, fxShow, f, xs):\n w = max(map(compose(len)(xShow), xs))\n return s + '\\n' + '\\n'.join([\n xShow(x).rjust(w, ' ') + (' -> ') + fxShow(f(x))\n for x in xs\n ])\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\n# showList :: [a] -> String\ndef showList(xs):\n '''Stringification of a list.'''\n return '[' + ','.join(str(x) for x in xs) + ']'\n\n\nif __name__ == '__main__':\n main()"} +{"title": "Flipping bits game", "language": "C", "task": "[[Category:Games]]\n\n;The game:\nGiven an \u00a0 '''N\u00d7N''' \u00a0 square array of zeroes or ones in an initial configuration, \u00a0 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 \u00a0 (as one move).\n\nIn an inversion. \u00a0 any \u00a0'''1'''\u00a0 becomes \u00a0'''0''', \u00a0 and any \u00a0'''0'''\u00a0 becomes \u00a0'''1'''\u00a0 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. \u00a0 (One possible way to do this is to generate the start position by legal flips from a random target position. \u00a0 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 \u00a0 '''3\u00d73''' \u00a0 array of bits.\n\n", "solution": "\n#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": "Flipping bits game", "language": "JavaScript", "task": "[[Category:Games]]\n\n;The game:\nGiven an \u00a0 '''N\u00d7N''' \u00a0 square array of zeroes or ones in an initial configuration, \u00a0 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 \u00a0 (as one move).\n\nIn an inversion. \u00a0 any \u00a0'''1'''\u00a0 becomes \u00a0'''0''', \u00a0 and any \u00a0'''0'''\u00a0 becomes \u00a0'''1'''\u00a0 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. \u00a0 (One possible way to do this is to generate the start position by legal flips from a random target position. \u00a0 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 \u00a0 '''3\u00d73''' \u00a0 array of bits.\n\n", "solution": "function numOfRows(board) { return board.length; }\nfunction numOfCols(board) { return board[0].length; }\nfunction boardToString(board) {\n // First the top-header\n var header = ' ';\n for (var c = 0; c < numOfCols(board); c++)\n header += c + ' ';\n \n // Then the side-header + board\n var sideboard = [];\n for (var r = 0; r < numOfRows(board); r++) {\n sideboard.push(r + ' [' + board[r].join(' ') + ']');\n }\n \n return header + '\\n' + sideboard.join('\\n');\n}\nfunction flipRow(board, row) {\n for (var c = 0; c < numOfCols(board); c++) {\n board[row][c] = 1 - board[row][c];\n }\n}\nfunction flipCol(board, col) {\n for (var r = 0; r < numOfRows(board); r++) {\n board[r][col] = 1 - board[r][col];\n }\n}\n\nfunction playFlippingBitsGame(rows, cols) {\n rows = rows | 3;\n cols = cols | 3;\n var targetBoard = [];\n var manipulatedBoard = [];\n // Randomly generate two identical boards.\n for (var r = 0; r < rows; r++) {\n targetBoard.push([]);\n manipulatedBoard.push([]);\n for (var c = 0; c < cols; c++) {\n targetBoard[r].push(Math.floor(Math.random() * 2));\n manipulatedBoard[r].push(targetBoard[r][c]);\n }\n }\n // Naive-scramble one of the boards.\n while (boardToString(targetBoard) == boardToString(manipulatedBoard)) {\n var scrambles = rows * cols;\n while (scrambles-- > 0) {\n if (0 == Math.floor(Math.random() * 2)) {\n flipRow(manipulatedBoard, Math.floor(Math.random() * rows));\n }\n else {\n flipCol(manipulatedBoard, Math.floor(Math.random() * cols));\n }\n }\n }\n // Get the user to solve.\n alert(\n 'Try to match both boards.\\n' +\n 'Enter `r` or `c` to manipulate a row or col or enter `q` to quit.'\n );\n var input = '', letter, num, moves = 0;\n while (boardToString(targetBoard) != boardToString(manipulatedBoard) && input != 'q') {\n input = prompt(\n 'Target:\\n' + boardToString(targetBoard) +\n '\\n\\n\\n' +\n 'Board:\\n' + boardToString(manipulatedBoard)\n );\n try {\n letter = input.charAt(0);\n num = parseInt(input.slice(1));\n if (letter == 'q')\n\t\t\t\tbreak;\n if (isNaN(num)\n || (letter != 'r' && letter != 'c')\n || (letter == 'r' && num >= rows)\n || (letter == 'c' && num >= cols)\n ) {\n throw new Error('');\n }\n if (letter == 'r') {\n flipRow(manipulatedBoard, num);\n }\n else {\n flipCol(manipulatedBoard, num);\n }\n moves++;\n }\n catch(e) {\n alert('Uh-oh, there seems to have been an input error');\n }\n }\n if (input == 'q') {\n alert('~~ Thanks for playing ~~');\n }\n else {\n alert('Completed in ' + moves + ' moves.');\n }\n}"} +{"title": "Flipping bits game", "language": "Python", "task": "[[Category:Games]]\n\n;The game:\nGiven an \u00a0 '''N\u00d7N''' \u00a0 square array of zeroes or ones in an initial configuration, \u00a0 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 \u00a0 (as one move).\n\nIn an inversion. \u00a0 any \u00a0'''1'''\u00a0 becomes \u00a0'''0''', \u00a0 and any \u00a0'''0'''\u00a0 becomes \u00a0'''1'''\u00a0 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. \u00a0 (One possible way to do this is to generate the start position by legal flips from a random target position. \u00a0 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 \u00a0 '''3\u00d73''' \u00a0 array of bits.\n\n", "solution": "\"\"\"\nGiven a %i by %i sqare array of zeroes or ones in an initial\nconfiguration, and a target configuration of zeroes and ones\nThe task is to transform one to the other in as few moves as \npossible by inverting whole numbered rows or whole lettered \ncolumns at once.\nIn an inversion any 1 becomes 0 and any 0 becomes 1 for that\nwhole row or column.\n\n\"\"\"\n\nfrom random import randrange\nfrom copy import deepcopy\nfrom string import ascii_lowercase\n\n\ntry: # 2to3 fix\n input = raw_input\nexcept:\n pass\n\nN = 3 # N x N Square arrray\n\nboard = [[0]* N for i in range(N)]\n\ndef setbits(board, count=1):\n for i in range(count):\n board[randrange(N)][randrange(N)] ^= 1\n\ndef shuffle(board, count=1):\n for i in range(count):\n if randrange(0, 2):\n fliprow(randrange(N))\n else:\n flipcol(randrange(N))\n\n\ndef pr(board, comment=''):\n print(str(comment))\n print(' ' + ' '.join(ascii_lowercase[i] for i in range(N)))\n print(' ' + '\\n '.join(' '.join(['%2s' % j] + [str(i) for i in line])\n for j, line in enumerate(board, 1)))\n\ndef init(board):\n setbits(board, count=randrange(N)+1)\n target = deepcopy(board)\n while board == target:\n shuffle(board, count=2 * N)\n prompt = ' X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0], \n ascii_lowercase[N-1])\n return target, prompt\n\ndef fliprow(i):\n board[i-1][:] = [x ^ 1 for x in board[i-1] ]\n \ndef flipcol(i):\n for row in board:\n row[i] ^= 1\n\nif __name__ == '__main__':\n print(__doc__ % (N, N))\n target, prompt = init(board)\n pr(target, 'Target configuration is:')\n print('')\n turns = 0\n while board != target:\n turns += 1\n pr(board, '%i:' % turns)\n ans = input(prompt).strip()\n if (len(ans) == 1 \n and ans in ascii_lowercase and ascii_lowercase.index(ans) < N):\n flipcol(ascii_lowercase.index(ans))\n elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N:\n fliprow(int(ans))\n elif ans == 'T':\n pr(target, 'Target configuration is:')\n turns -= 1\n elif ans == 'X':\n break\n else:\n print(\" I don't understand %r... Try again. \"\n \"(X to exit or T to show target)\\n\" % ans[:9])\n turns -= 1\n else:\n print('\\nWell done!\\nBye.')"} +{"title": "Floyd's triangle", "language": "C", "task": "Floyd's triangle \u00a0 lists the natural numbers in a right triangle aligned to the left where \n* the first row is \u00a0 '''1''' \u00a0 \u00a0 (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 \u00a0 n \u00a0 lines of a Floyd triangle. (Use \u00a0 n=5 \u00a0 and \u00a0 n=14 \u00a0 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": "Floyd's triangle", "language": "JavaScript", "task": "Floyd's triangle \u00a0 lists the natural numbers in a right triangle aligned to the left where \n* the first row is \u00a0 '''1''' \u00a0 \u00a0 (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 \u00a0 n \u00a0 lines of a Floyd triangle. (Use \u00a0 n=5 \u00a0 and \u00a0 n=14 \u00a0 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": "(function () {\n 'use strict';\n\n // FLOYD's TRIANGLE -------------------------------------------------------\n\n // floyd :: Int -> [[Int]]\n function floyd(n) {\n return snd(mapAccumL(function (start, row) {\n return [start + row + 1, enumFromTo(start, start + row)];\n }, 1, enumFromTo(0, n - 1)));\n };\n\n // showFloyd :: [[Int]] -> String\n function showFloyd(xss) {\n var ws = map(compose([succ, length, show]), last(xss));\n return unlines(map(function (xs) {\n return concat(zipWith(function (w, x) {\n return justifyRight(w, ' ', show(x));\n }, ws, xs));\n }, xss));\n };\n\n\n // GENERIC FUNCTIONS ------------------------------------------------------\n\n // compose :: [(a -> a)] -> (a -> a)\n function compose(fs) {\n return function (x) {\n return fs.reduceRight(function (a, f) {\n return f(a);\n }, x);\n };\n };\n\n // concat :: [[a]] -> [a] | [String] -> String\n function concat(xs) {\n if (xs.length > 0) {\n var unit = typeof xs[0] === 'string' ? '' : [];\n return unit.concat.apply(unit, xs);\n } else return [];\n };\n\n // enumFromTo :: Int -> Int -> [Int]\n function enumFromTo(m, n) {\n return Array.from({\n length: Math.floor(n - m) + 1\n }, function (_, i) {\n return m + i;\n });\n };\n\n // justifyRight :: Int -> Char -> Text -> Text\n function justifyRight(n, cFiller, strText) {\n return n > strText.length ? (cFiller.repeat(n) + strText)\n .slice(-n) : strText;\n };\n\n // last :: [a] -> a\n function last(xs) {\n return xs.length ? xs.slice(-1)[0] : undefined;\n };\n\n // length :: [a] -> Int\n function length(xs) {\n return xs.length;\n };\n\n // map :: (a -> b) -> [a] -> [b]\n function map(f, xs) {\n return xs.map(f);\n };\n\n // 'The mapAccumL function behaves like a combination of map and foldl;\n // it applies a function to each element of a list, passing an accumulating\n // parameter from left to right, and returning a final value of this\n // accumulator together with the new list.' (See hoogle )\n\n // mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])\n function mapAccumL(f, acc, xs) {\n return xs.reduce(function (a, x) {\n var pair = f(a[0], x);\n\n return [pair[0], a[1].concat([pair[1]])];\n }, [acc, []]);\n };\n\n // show ::\n // (a -> String) f, Num n =>\n // a -> maybe f -> maybe n -> String\n var show = JSON.stringify;\n\n // snd :: (a, b) -> b\n function snd(tpl) {\n return Array.isArray(tpl) ? tpl[1] : undefined;\n };\n\n // succ :: Int -> Int\n function succ(x) {\n return x + 1;\n };\n\n // unlines :: [String] -> String\n function unlines(xs) {\n return xs.join('\\n');\n };\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n function zipWith(f, xs, ys) {\n var ny = ys.length;\n return (xs.length <= ny ? xs : xs.slice(0, ny))\n .map(function (x, i) {\n return f(x, ys[i]);\n });\n };\n\n // TEST ( n=5 and n=14 rows ) ---------------------------------------------\n\n return unlines(map(function (n) {\n return showFloyd(floyd(n)) + '\\n';\n }, [5, 14]));\n})();"} +{"title": "Floyd's triangle", "language": "Python", "task": "Floyd's triangle \u00a0 lists the natural numbers in a right triangle aligned to the left where \n* the first row is \u00a0 '''1''' \u00a0 \u00a0 (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 \u00a0 n \u00a0 lines of a Floyd triangle. (Use \u00a0 n=5 \u00a0 and \u00a0 n=14 \u00a0 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": ">>> def floyd(rowcount=5):\n\trows = [[1]]\n\twhile len(rows) < rowcount:\n\t\tn = rows[-1][-1] + 1\n\t\trows.append(list(range(n, n + len(rows[-1]) + 1)))\n\treturn rows\n\n>>> floyd()\n[[1], [2, 3], [4, 5, 6], [7, 8, 9, 10], [11, 12, 13, 14, 15]]\n>>> def pfloyd(rows=[[1], [2, 3], [4, 5, 6], [7, 8, 9, 10]]):\n\tcolspace = [len(str(n)) for n in rows[-1]]\n\tfor row in rows:\n\t\tprint( ' '.join('%*i' % space_n for space_n in zip(colspace, row)))\n\n\t\t\n>>> pfloyd()\n1\n2 3\n4 5 6\n7 8 9 10\n>>> pfloyd(floyd(5))\n 1\n 2 3\n 4 5 6\n 7 8 9 10\n11 12 13 14 15\n>>> pfloyd(floyd(14))\n 1\n 2 3\n 4 5 6\n 7 8 9 10\n11 12 13 14 15\n16 17 18 19 20 21\n22 23 24 25 26 27 28\n29 30 31 32 33 34 35 36\n37 38 39 40 41 42 43 44 45\n46 47 48 49 50 51 52 53 54 55\n56 57 58 59 60 61 62 63 64 65 66\n67 68 69 70 71 72 73 74 75 76 77 78\n79 80 81 82 83 84 85 86 87 88 89 90 91\n92 93 94 95 96 97 98 99 100 101 102 103 104 105\n>>> "} +{"title": "Floyd's triangle", "language": "Python 3", "task": "Floyd's triangle \u00a0 lists the natural numbers in a right triangle aligned to the left where \n* the first row is \u00a0 '''1''' \u00a0 \u00a0 (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 \u00a0 n \u00a0 lines of a Floyd triangle. (Use \u00a0 n=5 \u00a0 and \u00a0 n=14 \u00a0 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": "'''Floyd triangle in terms of iterate(f)(x)'''\n\nfrom itertools import islice\n\n\n# floyd :: Int -> [[Int]]\ndef floyd(n):\n '''n rows of a Floyd triangle.'''\n return take(n)(iterate(nextFloyd)([1]))\n\n\n# nextFloyd :: [Int] -> [Int]\ndef nextFloyd(xs):\n '''A Floyd triangle row derived from\n the preceding row.'''\n n = succ(len(xs))\n return [1] if n < 2 else (\n enumFromTo(succ(n * pred(n) // 2))(\n n * succ(n) // 2\n )\n )\n\n\n# showFloyd :: [[Int]] -> String\ndef showFloyd(xs):\n '''A stringification of Floyd triangle rows.'''\n return unlines(str(x) for x in xs)\n\n\n# main :: IO ()\ndef main():\n '''Test'''\n print(showFloyd(\n floyd(5)\n ))\n\n\n# GENERIC ABSTRACTIONS ------------------------------------\n\n# enumFromTo :: (Int, Int) -> [Int]\ndef enumFromTo(m):\n '''Integer enumeration from m to n.'''\n return lambda n: list(range(m, 1 + n))\n\n\n# iterate :: (a -> a) -> a -> Gen [a]\ndef iterate(f):\n '''An infinite list of repeated applications of f to x.'''\n def go(x):\n v = x\n while True:\n yield v\n v = f(v)\n return lambda x: go(x)\n\n\n# pred :: Enum a => a -> a\ndef pred(x):\n '''The predecessor of a value. For numeric types, (- 1).'''\n return x - 1 if isinstance(x, int) else (\n chr(ord(x) - 1)\n )\n\n\n# succ :: Enum a => a -> a\ndef succ(x):\n '''The successor of a value. For numeric types, (1 +).'''\n return 1 + x if isinstance(x, int) else (\n chr(1 + ord(x))\n )\n\n\n# take :: Int -> [a] -> [a]\n# take :: Int -> String -> String\ndef take(n):\n '''The prefix of xs of length n,\n or xs itself if n > length xs.'''\n return lambda xs: (\n xs[0:n]\n if isinstance(xs, list)\n else list(islice(xs, n))\n )\n\n\n# unlines :: [String] -> String\ndef unlines(xs):\n '''A single string derived by the intercalation\n of a list of strings with the newline character.'''\n return '\\n'.join(xs)\n\n\n# MAIN ----------------------------------------------------\nif __name__ == '__main__':\n main()"} +{"title": "Four bit adder", "language": "C", "task": ";Task:\n\"''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 \u00a0 ''xor'' \u00a0 gate and an \u00a0 ''and'' \u00a0 gate. \n\nThe \u00a0 ''xor'' \u00a0 gate can be made using two \u00a0 ''not''s, \u00a0 two \u00a0 ''and''s \u00a0 and one \u00a0 ''or''.\n\n'''Not''', \u00a0 '''or''' \u00a0 and \u00a0 '''and''', \u00a0 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 \u00a0 ''not'' \u00a0 does not \"invert\" all the other bits of the basic type \u00a0 (e.g. a byte) \u00a0 we are not interested in, \u00a0 you can use an extra \u00a0 ''nand'' \u00a0 (''and'' \u00a0 then \u00a0 ''not'') \u00a0 with the constant \u00a0 '''1''' \u00a0 on one input.\n\nInstead of optimizing and reducing the number of gates used for the final 4-bit adder, \u00a0 build it in the most straightforward way, \u00a0 ''connecting'' the other \"constructive blocks\", \u00a0 in turn made of \"simpler\" and \"smaller\" ones.\n\n{|\n|+Schematics of the \"constructive blocks\"\n!(Xor gate with ANDs, ORs and NOTs) \u00a0 \u00a0 \u00a0 \u00a0\n!\u00a0\u00a0 (A half adder) \u00a0 \u00a0 \u00a0 \u00a0\n!\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 (A full adder) \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0\n!\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 (A 4-bit adder) \u00a0 \u00a0 \u00a0 \u00a0\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": "Four bit adder", "language": "JavaScript", "task": ";Task:\n\"''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 \u00a0 ''xor'' \u00a0 gate and an \u00a0 ''and'' \u00a0 gate. \n\nThe \u00a0 ''xor'' \u00a0 gate can be made using two \u00a0 ''not''s, \u00a0 two \u00a0 ''and''s \u00a0 and one \u00a0 ''or''.\n\n'''Not''', \u00a0 '''or''' \u00a0 and \u00a0 '''and''', \u00a0 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 \u00a0 ''not'' \u00a0 does not \"invert\" all the other bits of the basic type \u00a0 (e.g. a byte) \u00a0 we are not interested in, \u00a0 you can use an extra \u00a0 ''nand'' \u00a0 (''and'' \u00a0 then \u00a0 ''not'') \u00a0 with the constant \u00a0 '''1''' \u00a0 on one input.\n\nInstead of optimizing and reducing the number of gates used for the final 4-bit adder, \u00a0 build it in the most straightforward way, \u00a0 ''connecting'' the other \"constructive blocks\", \u00a0 in turn made of \"simpler\" and \"smaller\" ones.\n\n{|\n|+Schematics of the \"constructive blocks\"\n!(Xor gate with ANDs, ORs and NOTs) \u00a0 \u00a0 \u00a0 \u00a0\n!\u00a0\u00a0 (A half adder) \u00a0 \u00a0 \u00a0 \u00a0\n!\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 (A full adder) \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0\n!\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 (A 4-bit adder) \u00a0 \u00a0 \u00a0 \u00a0\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": "\n// basic building blocks allowed by the rules are ~, &, and |, we'll fake these\n// in a way that makes what they do (at least when you use them) more obvious \n// than the other available options do.\n\nfunction not(a) {\n if (arePseudoBin(a))\n return a == 1 ? 0 : 1;\n}\n\nfunction and(a, b) {\n if (arePseudoBin(a, b))\n return a + b < 2 ? 0 : 1;\n}\n\nfunction nand(a, b) {\n if (arePseudoBin(a, b))\n return not(and(a, b));\n}\n\nfunction or(a, b) {\n if (arePseudoBin(a, b))\n return nand(nand(a,a), nand(b,b));\n}\n\nfunction xor(a, b) {\n if (arePseudoBin(a, b))\n return nand(nand(nand(a,b), a), nand(nand(a,b), b));\n}\n\nfunction halfAdder(a, b) {\n if (arePseudoBin(a, b))\n return { carry: and(a, b), sum: xor(a, b) };\n}\n\nfunction fullAdder(a, b, c) {\n if (arePseudoBin(a, b, c)) {\n var h0 = halfAdder(a, b), \n h1 = halfAdder(h0.sum, c);\n return {carry: or(h0.carry, h1.carry), sum: h1.sum };\n }\n}\n\nfunction fourBitAdder(a, b) {\n if (typeof a.length == 'undefined' || typeof b.length == 'undefined')\n throw new Error('bad values');\n // not sure if the rules allow this, but we need to pad the values \n // if they're too short and trim them if they're too long\n var inA = Array(4), \n inB = Array(4), \n out = Array(4), \n i = 4, \n pass;\n \n while (i--) {\n inA[i] = a[i] != 1 ? 0 : 1;\n inB[i] = b[i] != 1 ? 0 : 1;\n }\n\n // now we can start adding... I'd prefer to do this in a loop, \n // but that wouldn't be \"connecting the other 'constructive blocks', \n // in turn made of 'simpler' and 'smaller' ones\"\n \n pass = halfAdder(inA[3], inB[3]);\n out[3] = pass.sum;\n pass = fullAdder(inA[2], inB[2], pass.carry);\n out[2] = pass.sum;\n pass = fullAdder(inA[1], inB[1], pass.carry);\n out[1] = pass.sum;\n pass = fullAdder(inA[0], inB[0], pass.carry);\n out[0] = pass.sum;\n return out.join('');\n}\n"} +{"title": "Four bit adder", "language": "Python", "task": ";Task:\n\"''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 \u00a0 ''xor'' \u00a0 gate and an \u00a0 ''and'' \u00a0 gate. \n\nThe \u00a0 ''xor'' \u00a0 gate can be made using two \u00a0 ''not''s, \u00a0 two \u00a0 ''and''s \u00a0 and one \u00a0 ''or''.\n\n'''Not''', \u00a0 '''or''' \u00a0 and \u00a0 '''and''', \u00a0 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 \u00a0 ''not'' \u00a0 does not \"invert\" all the other bits of the basic type \u00a0 (e.g. a byte) \u00a0 we are not interested in, \u00a0 you can use an extra \u00a0 ''nand'' \u00a0 (''and'' \u00a0 then \u00a0 ''not'') \u00a0 with the constant \u00a0 '''1''' \u00a0 on one input.\n\nInstead of optimizing and reducing the number of gates used for the final 4-bit adder, \u00a0 build it in the most straightforward way, \u00a0 ''connecting'' the other \"constructive blocks\", \u00a0 in turn made of \"simpler\" and \"smaller\" ones.\n\n{|\n|+Schematics of the \"constructive blocks\"\n!(Xor gate with ANDs, ORs and NOTs) \u00a0 \u00a0 \u00a0 \u00a0\n!\u00a0\u00a0 (A half adder) \u00a0 \u00a0 \u00a0 \u00a0\n!\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 (A full adder) \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0\n!\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 (A 4-bit adder) \u00a0 \u00a0 \u00a0 \u00a0\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": "def xor(a, b): return (a and not b) or (b and not a)\n\ndef ha(a, b): return xor(a, b), a and b # sum, carry\n\ndef fa(a, b, ci):\n s0, c0 = ha(ci, a)\n s1, c1 = ha(s0, b)\n return s1, c0 or c1 # sum, carry\n\ndef fa4(a, b):\n width = 4\n ci = [None] * width\n co = [None] * width\n s = [None] * width\n for i in range(width):\n s[i], co[i] = fa(a[i], b[i], co[i-1] if i else 0)\n return s, co[-1]\n\ndef int2bus(n, width=4):\n return [int(c) for c in \"{0:0{1}b}\".format(n, width)[::-1]]\n\ndef bus2int(b):\n return sum(1 << i for i, bit in enumerate(b) if bit)\n\ndef test_fa4():\n width = 4\n tot = [None] * (width + 1)\n for a in range(2**width):\n for b in range(2**width):\n tot[:width], tot[width] = fa4(int2bus(a), int2bus(b))\n assert a + b == bus2int(tot), \"totals don't match: %i + %i != %s\" % (a, b, tot)\n\n\nif __name__ == '__main__':\n test_fa4()"} +{"title": "Four is magic", "language": "C", "task": ";Task:\nWrite a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the first word, followed by a comma.\n\nContinue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in ''that'' word. \n\nContinue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four.\n\nFor instance, suppose your are given the integer '''3'''. Convert '''3''' to '''Three''', add ''' is ''', then the cardinal character count of three, or '''five''', with a comma to separate if from the next phrase. Continue the sequence '''five is four,''' (five has four letters), and finally, '''four is magic.''' \n\n '''Three is five, five is four, four is magic.'''\n\nFor reference, here are outputs for 0 through 9.\n\n Zero is four, four is magic.\n One is three, three is five, five is four, four is magic.\n Two is three, three is five, five is four, four is magic.\n Three is five, five is four, four is magic.\n Four is magic.\n Five is four, four is magic.\n Six is three, three is five, five is four, four is magic.\n Seven is five, five is four, four is magic.\n Eight is five, five is four, four is magic.\n Nine is four, four is magic.\n\n\n;Some task guidelines:\n:* You may assume the input will only contain integer numbers.\n:* Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. ('''23''' is '''twenty three''' or '''twenty-three''' not '''twentythree'''.)\n:* Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.)\n:* Cardinal numbers should not include commas. ('''20140''' is '''twenty thousand one hundred forty''' not '''twenty thousand, one hundred forty'''.)\n:* When converted to a string, '''100''' should be '''one hundred''', not '''a hundred''' or '''hundred''', '''1000''' should be '''one thousand''', not '''a thousand''' or '''thousand'''.\n:* When converted to a string, there should be no '''and''' in the cardinal string. '''130''' should be '''one hundred thirty''' not '''one hundred and thirty'''.\n:* When counting characters, count ''all'' of the characters in the cardinal number including spaces and hyphens. '''One hundred fifty-one''' should be '''21''' not '''18'''.\n:* The output should follow the format \"N is K, K is M, M is ... four is magic.\" (unless the input is 4, in which case the output should simply be \"four is magic.\")\n:* The output can either be the return value from the function, or be displayed from within the function.\n:* You are encouraged, though not mandated to use proper sentence capitalization.\n:* You may optionally support negative numbers. '''-7''' is '''negative seven'''.\n:* Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration.\n\n\nYou can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public. \n\nIf you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.)\n\nFour is magic is a popular code-golf task. '''This is not code golf.''' Write legible, idiomatic and well formatted code.\n\n\n;Related tasks:\n:* \u00a0 [[Four is the number of_letters in the ...]]\n:* \u00a0 [[Look-and-say sequence]]\n:* \u00a0 [[Number names]]\n:* \u00a0 [[Self-describing numbers]]\n:* \u00a0 [[Summarize and say sequence]]\n:* \u00a0 [[Spelling of ordinal numbers]]\n:* \u00a0 [[De Bruijn sequences]]\n\n", "solution": "#include \n#include \n#include \n\ntypedef struct named_number_tag {\n const char* name;\n uint64_t number;\n} named_number;\n\nconst named_number named_numbers[] = {\n { \"hundred\", 100 },\n { \"thousand\", 1000 },\n { \"million\", 1000000 },\n { \"billion\", 1000000000 },\n { \"trillion\", 1000000000000 },\n { \"quadrillion\", 1000000000000000ULL },\n { \"quintillion\", 1000000000000000000ULL }\n};\n\nconst named_number* get_named_number(uint64_t n) {\n const size_t names_len = sizeof(named_numbers)/sizeof(named_number);\n for (size_t i = 0; i + 1 < names_len; ++i) {\n if (n < named_numbers[i + 1].number)\n return &named_numbers[i];\n }\n return &named_numbers[names_len - 1];\n}\n\nsize_t append_number_name(GString* str, uint64_t n) {\n static const char* small[] = {\n \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\",\n \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n };\n static const char* tens[] = {\n \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n };\n size_t len = str->len;\n if (n < 20) {\n g_string_append(str, small[n]);\n }\n else if (n < 100) {\n g_string_append(str, tens[n/10 - 2]);\n if (n % 10 != 0) {\n g_string_append_c(str, '-');\n g_string_append(str, small[n % 10]);\n }\n } else {\n const named_number* num = get_named_number(n);\n uint64_t p = num->number;\n append_number_name(str, n/p);\n g_string_append_c(str, ' ');\n g_string_append(str, num->name);\n if (n % p != 0) {\n g_string_append_c(str, ' ');\n append_number_name(str, n % p);\n }\n }\n return str->len - len;\n}\n\nGString* magic(uint64_t n) {\n GString* str = g_string_new(NULL);\n for (unsigned int i = 0; ; ++i) {\n size_t count = append_number_name(str, n);\n if (i == 0)\n str->str[0] = g_ascii_toupper(str->str[0]);\n if (n == 4) {\n g_string_append(str, \" is magic.\");\n break;\n }\n g_string_append(str, \" is \");\n append_number_name(str, count);\n g_string_append(str, \", \");\n n = count;\n }\n return str;\n}\n\nvoid test_magic(uint64_t n) {\n GString* str = magic(n);\n printf(\"%s\\n\", str->str);\n g_string_free(str, TRUE);\n}\n\nint main() {\n test_magic(5);\n test_magic(13);\n test_magic(78);\n test_magic(797);\n test_magic(2739);\n test_magic(4000);\n test_magic(7893);\n test_magic(93497412);\n test_magic(2673497412U);\n test_magic(10344658531277200972ULL);\n return 0;\n}"} +{"title": "Four is magic", "language": "JavaScript", "task": ";Task:\nWrite a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the first word, followed by a comma.\n\nContinue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in ''that'' word. \n\nContinue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four.\n\nFor instance, suppose your are given the integer '''3'''. Convert '''3''' to '''Three''', add ''' is ''', then the cardinal character count of three, or '''five''', with a comma to separate if from the next phrase. Continue the sequence '''five is four,''' (five has four letters), and finally, '''four is magic.''' \n\n '''Three is five, five is four, four is magic.'''\n\nFor reference, here are outputs for 0 through 9.\n\n Zero is four, four is magic.\n One is three, three is five, five is four, four is magic.\n Two is three, three is five, five is four, four is magic.\n Three is five, five is four, four is magic.\n Four is magic.\n Five is four, four is magic.\n Six is three, three is five, five is four, four is magic.\n Seven is five, five is four, four is magic.\n Eight is five, five is four, four is magic.\n Nine is four, four is magic.\n\n\n;Some task guidelines:\n:* You may assume the input will only contain integer numbers.\n:* Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. ('''23''' is '''twenty three''' or '''twenty-three''' not '''twentythree'''.)\n:* Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.)\n:* Cardinal numbers should not include commas. ('''20140''' is '''twenty thousand one hundred forty''' not '''twenty thousand, one hundred forty'''.)\n:* When converted to a string, '''100''' should be '''one hundred''', not '''a hundred''' or '''hundred''', '''1000''' should be '''one thousand''', not '''a thousand''' or '''thousand'''.\n:* When converted to a string, there should be no '''and''' in the cardinal string. '''130''' should be '''one hundred thirty''' not '''one hundred and thirty'''.\n:* When counting characters, count ''all'' of the characters in the cardinal number including spaces and hyphens. '''One hundred fifty-one''' should be '''21''' not '''18'''.\n:* The output should follow the format \"N is K, K is M, M is ... four is magic.\" (unless the input is 4, in which case the output should simply be \"four is magic.\")\n:* The output can either be the return value from the function, or be displayed from within the function.\n:* You are encouraged, though not mandated to use proper sentence capitalization.\n:* You may optionally support negative numbers. '''-7''' is '''negative seven'''.\n:* Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration.\n\n\nYou can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public. \n\nIf you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.)\n\nFour is magic is a popular code-golf task. '''This is not code golf.''' Write legible, idiomatic and well formatted code.\n\n\n;Related tasks:\n:* \u00a0 [[Four is the number of_letters in the ...]]\n:* \u00a0 [[Look-and-say sequence]]\n:* \u00a0 [[Number names]]\n:* \u00a0 [[Self-describing numbers]]\n:* \u00a0 [[Summarize and say sequence]]\n:* \u00a0 [[Spelling of ordinal numbers]]\n:* \u00a0 [[De Bruijn sequences]]\n\n", "solution": "const reverseOrderedNumberToTextMap = (function () {\n const rawNumberToTextMapping = { // Ported over from the Python solution.\n [1n]: \"one\",\n [2n]: \"two\",\n [3n]: \"three\",\n [4n]: \"four\",\n [5n]: \"five\",\n [6n]: \"six\",\n [7n]: \"seven\",\n [8n]: \"eight\",\n [9n]: \"nine\",\n [10n]: \"ten\",\n [11n]: \"eleven\",\n [12n]: \"twelve\",\n [13n]: \"thirteen\",\n [14n]: \"fourteen\",\n [15n]: \"fifteen\",\n [16n]: \"sixteen\",\n [17n]: \"seventeen\",\n [18n]: \"eighteen\",\n [19n]: \"nineteen\",\n [20n]: \"twenty\",\n [30n]: \"thirty\",\n [40n]: \"forty\",\n [50n]: \"fifty\",\n [60n]: \"sixty\",\n [70n]: \"seventy\",\n [80n]: \"eighty\",\n [90n]: \"ninety\",\n [100n]: \"hundred\",\n [1000n]: \"thousand\",\n [10n ** 6n]: \"million\",\n [10n ** 9n]: \"billion\",\n [10n ** 12n]: \"trillion\",\n [10n ** 15n]: \"quadrillion\",\n [10n ** 18n]: \"quintillion\",\n [10n ** 21n]: \"sextillion\",\n [10n ** 24n]: \"septillion\",\n [10n ** 27n]: \"octillion\",\n [10n ** 30n]: \"nonillion\",\n [10n ** 33n]: \"decillion\",\n [10n ** 36n]: \"undecillion\",\n [10n ** 39n]: \"duodecillion\",\n [10n ** 42n]: \"tredecillion\",\n [10n ** 45n]: \"quattuordecillion\",\n [10n ** 48n]: \"quinquadecillion\",\n [10n ** 51n]: \"sedecillion\",\n [10n ** 54n]: \"septendecillion\",\n [10n ** 57n]: \"octodecillion\",\n [10n ** 60n]: \"novendecillion\",\n [10n ** 63n]: \"vigintillion\",\n [10n ** 66n]: \"unvigintillion\",\n [10n ** 69n]: \"duovigintillion\",\n [10n ** 72n]: \"tresvigintillion\",\n [10n ** 75n]: \"quattuorvigintillion\",\n [10n ** 78n]: \"quinquavigintillion\",\n [10n ** 81n]: \"sesvigintillion\",\n [10n ** 84n]: \"septemvigintillion\",\n [10n ** 87n]: \"octovigintillion\",\n [10n ** 90n]: \"novemvigintillion\",\n [10n ** 93n]: \"trigintillion\",\n [10n ** 96n]: \"untrigintillion\",\n [10n ** 99n]: \"duotrigintillion\",\n [10n ** 102n]: \"trestrigintillion\",\n [10n ** 105n]: \"quattuortrigintillion\",\n [10n ** 108n]: \"quinquatrigintillion\",\n [10n ** 111n]: \"sestrigintillion\",\n [10n ** 114n]: \"septentrigintillion\",\n [10n ** 117n]: \"octotrigintillion\",\n [10n ** 120n]: \"noventrigintillion\",\n [10n ** 123n]: \"quadragintillion\",\n [10n ** 153n]: \"quinquagintillion\",\n [10n ** 183n]: \"sexagintillion\",\n [10n ** 213n]: \"septuagintillion\",\n [10n ** 243n]: \"octogintillion\",\n [10n ** 273n]: \"nonagintillion\",\n [10n ** 303n]: \"centillion\",\n [10n ** 306n]: \"uncentillion\",\n [10n ** 309n]: \"duocentillion\",\n [10n ** 312n]: \"trescentillion\",\n [10n ** 333n]: \"decicentillion\",\n [10n ** 336n]: \"undecicentillion\",\n [10n ** 363n]: \"viginticentillion\",\n [10n ** 366n]: \"unviginticentillion\",\n [10n ** 393n]: \"trigintacentillion\",\n [10n ** 423n]: \"quadragintacentillion\",\n [10n ** 453n]: \"quinquagintacentillion\",\n [10n ** 483n]: \"sexagintacentillion\",\n [10n ** 513n]: \"septuagintacentillion\",\n [10n ** 543n]: \"octogintacentillion\",\n [10n ** 573n]: \"nonagintacentillion\",\n [10n ** 603n]: \"ducentillion\",\n [10n ** 903n]: \"trecentillion\",\n [10n ** 1203n]: \"quadringentillion\",\n [10n ** 1503n]: \"quingentillion\",\n [10n ** 1803n]: \"sescentillion\",\n [10n ** 2103n]: \"septingentillion\",\n [10n ** 2403n]: \"octingentillion\",\n [10n ** 2703n]: \"nongentillion\",\n [10n ** 3003n]: \"millinillion\"\n };\n\n return new Map(Object.entries(rawNumberToTextMapping)\n .sort((a, b) => BigInt(a[0]) > BigInt(b[0]) ? -1 : 1)\n .map(numberAndText => [BigInt(numberAndText[0]), numberAndText[1]]));\n})();\n\n\nfunction getCardinalRepresentation(number)\n{\n if (number == 0n)\n {\n return \"zero\";\n }\n\n function* generateCardinalRepresentationTokens(number)\n {\n if (number <= 0n)\n {\n yield \"negative\";\n number *= -1n;\n }\n\n for (const [currentEntryNumber, currentEntryText] of reverseOrderedNumberToTextMap.entries())\n {\n if (number >= currentEntryNumber)\n {\n if (currentEntryNumber >= 100n)\n {\n yield* generateCardinalRepresentationTokens(number / currentEntryNumber);\n }\n\n yield currentEntryText;\n number -= currentEntryNumber;\n }\n }\n }\n\n\n return [...generateCardinalRepresentationTokens(number)].join(\" \");\n}\n\nfunction* generateFourIsMagicParts(number)\n{\n if (typeof number != \"bigint\")\n {\n number = BigInt(number);\n }\n\n if (number == 4n)\n {\n yield \"four is magic\";\n }\n else\n {\n const cardinalRepresentation = getCardinalRepresentation(number);\n yield `${cardinalRepresentation} is ${getCardinalRepresentation(BigInt(cardinalRepresentation.length))}`;\n yield* generateFourIsMagicParts(cardinalRepresentation.length);\n }\n\n}\n\nfunction capitalizeFirstLetter(str)\n{\n return str.replace(/^([a-z])/, chr => chr.toUpperCase());\n}\n\nfunction fourIsMagic(number)\n{\n return capitalizeFirstLetter(`${[...generateFourIsMagicParts(number)].join(\", \")}.`);\n}\n\n[\n 0,\n -150,\n 210,\n 10n ** 2703n + 1225n,\n 4,\n -4,\n 10n ** 3003n + 42n\n].map(fourIsMagic).join(\"\\n\\n\");"} +{"title": "Four is magic", "language": "Python", "task": ";Task:\nWrite a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the first word, followed by a comma.\n\nContinue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in ''that'' word. \n\nContinue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four.\n\nFor instance, suppose your are given the integer '''3'''. Convert '''3''' to '''Three''', add ''' is ''', then the cardinal character count of three, or '''five''', with a comma to separate if from the next phrase. Continue the sequence '''five is four,''' (five has four letters), and finally, '''four is magic.''' \n\n '''Three is five, five is four, four is magic.'''\n\nFor reference, here are outputs for 0 through 9.\n\n Zero is four, four is magic.\n One is three, three is five, five is four, four is magic.\n Two is three, three is five, five is four, four is magic.\n Three is five, five is four, four is magic.\n Four is magic.\n Five is four, four is magic.\n Six is three, three is five, five is four, four is magic.\n Seven is five, five is four, four is magic.\n Eight is five, five is four, four is magic.\n Nine is four, four is magic.\n\n\n;Some task guidelines:\n:* You may assume the input will only contain integer numbers.\n:* Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. ('''23''' is '''twenty three''' or '''twenty-three''' not '''twentythree'''.)\n:* Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.)\n:* Cardinal numbers should not include commas. ('''20140''' is '''twenty thousand one hundred forty''' not '''twenty thousand, one hundred forty'''.)\n:* When converted to a string, '''100''' should be '''one hundred''', not '''a hundred''' or '''hundred''', '''1000''' should be '''one thousand''', not '''a thousand''' or '''thousand'''.\n:* When converted to a string, there should be no '''and''' in the cardinal string. '''130''' should be '''one hundred thirty''' not '''one hundred and thirty'''.\n:* When counting characters, count ''all'' of the characters in the cardinal number including spaces and hyphens. '''One hundred fifty-one''' should be '''21''' not '''18'''.\n:* The output should follow the format \"N is K, K is M, M is ... four is magic.\" (unless the input is 4, in which case the output should simply be \"four is magic.\")\n:* The output can either be the return value from the function, or be displayed from within the function.\n:* You are encouraged, though not mandated to use proper sentence capitalization.\n:* You may optionally support negative numbers. '''-7''' is '''negative seven'''.\n:* Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration.\n\n\nYou can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public. \n\nIf you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.)\n\nFour is magic is a popular code-golf task. '''This is not code golf.''' Write legible, idiomatic and well formatted code.\n\n\n;Related tasks:\n:* \u00a0 [[Four is the number of_letters in the ...]]\n:* \u00a0 [[Look-and-say sequence]]\n:* \u00a0 [[Number names]]\n:* \u00a0 [[Self-describing numbers]]\n:* \u00a0 [[Summarize and say sequence]]\n:* \u00a0 [[Spelling of ordinal numbers]]\n:* \u00a0 [[De Bruijn sequences]]\n\n", "solution": "import random\nfrom collections import OrderedDict\n\nnumbers = { # taken from https://en.wikipedia.org/wiki/Names_of_large_numbers#cite_ref-a_14-3\n 1: 'one',\n 2: 'two',\n 3: 'three',\n 4: 'four',\n 5: 'five',\n 6: 'six',\n 7: 'seven',\n 8: 'eight',\n 9: 'nine',\n 10: 'ten',\n 11: 'eleven',\n 12: 'twelve',\n 13: 'thirteen',\n 14: 'fourteen',\n 15: 'fifteen',\n 16: 'sixteen',\n 17: 'seventeen',\n 18: 'eighteen',\n 19: 'nineteen',\n 20: 'twenty',\n 30: 'thirty',\n 40: 'forty',\n 50: 'fifty',\n 60: 'sixty',\n 70: 'seventy',\n 80: 'eighty',\n 90: 'ninety',\n 100: 'hundred',\n 1000: 'thousand',\n 10 ** 6: 'million',\n 10 ** 9: 'billion',\n 10 ** 12: 'trillion',\n 10 ** 15: 'quadrillion',\n 10 ** 18: 'quintillion',\n 10 ** 21: 'sextillion',\n 10 ** 24: 'septillion',\n 10 ** 27: 'octillion',\n 10 ** 30: 'nonillion',\n 10 ** 33: 'decillion',\n 10 ** 36: 'undecillion',\n 10 ** 39: 'duodecillion',\n 10 ** 42: 'tredecillion',\n 10 ** 45: 'quattuordecillion',\n 10 ** 48: 'quinquadecillion',\n 10 ** 51: 'sedecillion',\n 10 ** 54: 'septendecillion',\n 10 ** 57: 'octodecillion',\n 10 ** 60: 'novendecillion',\n 10 ** 63: 'vigintillion',\n 10 ** 66: 'unvigintillion',\n 10 ** 69: 'duovigintillion',\n 10 ** 72: 'tresvigintillion',\n 10 ** 75: 'quattuorvigintillion',\n 10 ** 78: 'quinquavigintillion',\n 10 ** 81: 'sesvigintillion',\n 10 ** 84: 'septemvigintillion',\n 10 ** 87: 'octovigintillion',\n 10 ** 90: 'novemvigintillion',\n 10 ** 93: 'trigintillion',\n 10 ** 96: 'untrigintillion',\n 10 ** 99: 'duotrigintillion',\n 10 ** 102: 'trestrigintillion',\n 10 ** 105: 'quattuortrigintillion',\n 10 ** 108: 'quinquatrigintillion',\n 10 ** 111: 'sestrigintillion',\n 10 ** 114: 'septentrigintillion',\n 10 ** 117: 'octotrigintillion',\n 10 ** 120: 'noventrigintillion',\n 10 ** 123: 'quadragintillion',\n 10 ** 153: 'quinquagintillion',\n 10 ** 183: 'sexagintillion',\n 10 ** 213: 'septuagintillion',\n 10 ** 243: 'octogintillion',\n 10 ** 273: 'nonagintillion',\n 10 ** 303: 'centillion',\n 10 ** 306: 'uncentillion',\n 10 ** 309: 'duocentillion',\n 10 ** 312: 'trescentillion',\n 10 ** 333: 'decicentillion',\n 10 ** 336: 'undecicentillion',\n 10 ** 363: 'viginticentillion',\n 10 ** 366: 'unviginticentillion',\n 10 ** 393: 'trigintacentillion',\n 10 ** 423: 'quadragintacentillion',\n 10 ** 453: 'quinquagintacentillion',\n 10 ** 483: 'sexagintacentillion',\n 10 ** 513: 'septuagintacentillion',\n 10 ** 543: 'octogintacentillion',\n 10 ** 573: 'nonagintacentillion',\n 10 ** 603: 'ducentillion',\n 10 ** 903: 'trecentillion',\n 10 ** 1203: 'quadringentillion',\n 10 ** 1503: 'quingentillion',\n 10 ** 1803: 'sescentillion',\n 10 ** 2103: 'septingentillion',\n 10 ** 2403: 'octingentillion',\n 10 ** 2703: 'nongentillion',\n 10 ** 3003: 'millinillion'\n}\nnumbers = OrderedDict(sorted(numbers.items(), key=lambda t: t[0], reverse=True))\n\n\ndef string_representation(i: int) -> str:\n \"\"\"\n Return the english string representation of an integer\n \"\"\"\n if i == 0:\n return 'zero'\n\n words = ['negative'] if i < 0 else []\n working_copy = abs(i)\n\n for key, value in numbers.items():\n if key <= working_copy:\n times = int(working_copy / key)\n\n if key >= 100:\n words.append(string_representation(times))\n\n words.append(value)\n working_copy -= times * key\n\n if working_copy == 0:\n break\n\n return ' '.join(words)\n\n\ndef next_phrase(i: int):\n \"\"\"\n Generate all the phrases\n \"\"\"\n while not i == 4: # Generate phrases until four is reached\n str_i = string_representation(i)\n len_i = len(str_i)\n\n yield str_i, 'is', string_representation(len_i)\n\n i = len_i\n\n # the last phrase\n yield string_representation(i), 'is', 'magic'\n\n\ndef magic(i: int) -> str:\n phrases = []\n\n for phrase in next_phrase(i):\n phrases.append(' '.join(phrase))\n\n return f'{\", \".join(phrases)}.'.capitalize()\n\n\nif __name__ == '__main__':\n\n for j in (random.randint(0, 10 ** 3) for i in range(5)):\n print(j, ':\\n', magic(j), '\\n')\n\n for j in (random.randint(-10 ** 24, 10 ** 24) for i in range(2)):\n print(j, ':\\n', magic(j), '\\n')"} +{"title": "Four is the number of letters in the ...", "language": "C", "task": "The \u00a0 \u00a0 '''Four is ...''' \u00a0 \u00a0 sequence is based on the counting of the number of\nletters in the words of the (never\u2500ending) sentence:\n Four is the number of letters in the first word of this sentence, two in the second,\n three in the third, six in the fourth, two in the fifth, seven in the sixth, \u00b7\u00b7\u00b7 \n\n\n;Definitions and directives:\n:* \u00a0 English is to be used in spelling numbers.\n:* \u00a0 '''Letters''' \u00a0 are defined as the upper\u2500 and lowercase letters in the Latin alphabet \u00a0 ('''A\u2500\u2500\u25baZ''' \u00a0 and \u00a0 '''a\u2500\u2500\u25baz''').\n:* \u00a0 Commas are not counted, \u00a0 nor are hyphens (dashes or minus signs).\n:* \u00a0 '''twenty\u2500three''' \u00a0 has eleven letters.\n:* \u00a0 '''twenty\u2500three''' \u00a0 is considered one word \u00a0 (which is hyphenated).\n:* \u00a0 no \u00a0 ''' ''and'' ''' \u00a0 words are to be used when spelling a (English) word for a number.\n:* \u00a0 The American version of numbers will be used here in this task \u00a0 (as opposed to the British version).\n '''2,000,000,000''' \u00a0 is two billion, \u00a0 ''not'' \u00a0 two milliard.\n\n\n;Task:\n:* \u00a0 Write a driver (invoking routine) and a function (subroutine/routine\u00b7\u00b7\u00b7) that returns the sequence (for any positive integer) of the number of letters in the first \u00a0 '''N''' \u00a0 words in the never\u2500ending sentence. \u00a0 For instance, the portion of the never\u2500ending sentence shown above (2nd sentence of this task's preamble), \u00a0 the sequence would be:\n '''4 2 3 6 2 7'''\n:* \u00a0 Only construct as much as is needed for the never\u2500ending sentence.\n:* \u00a0 Write a driver (invoking routine) to show the number of letters in the \u00a0 Nth \u00a0 word, \u00a0 ''as well as'' \u00a0 showing the \u00a0 Nth \u00a0 word itself.\n:* \u00a0 After each test case, show the total number of characters \u00a0 (including blanks, commas, and punctuation) \u00a0 of the sentence that was constructed.\n:* \u00a0 Show all output here.\n\n\n;Test cases:\n Display the first 201 numbers in the sequence \u00a0 (and the total number of characters in the sentence).\n Display the number of letters (and the word itself) of the 1,000th word.\n Display the number of letters (and the word itself) of the 10,000th word.\n Display the number of letters (and the word itself) of the 100,000th word.\n Display the number of letters (and the word itself) of the 1,000,000th word.\n Display the number of letters (and the word itself) of the 10,000,000th word (optional).\n\n\n;Related tasks:\n:* \u00a0 [[Four is magic]]\n:* \u00a0 [[Look-and-say sequence]]\n:* \u00a0 [[Number names]]\n:* \u00a0 [[Self-describing numbers]]\n:* \u00a0 [[Self-referential sequence]]\n:* \u00a0 [[Spelling of ordinal numbers]]\n\n\n;Also see:\n:* \u00a0 See the OEIS sequence A72425 \"Four is the number of letters...\".\n:* \u00a0 See the OEIS sequence A72424 \"Five's the number of letters...\"\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n\ntypedef uint64_t integer;\n\ntypedef struct number_names_tag {\n const char* cardinal;\n const char* ordinal;\n} number_names;\n\nconst number_names small[] = {\n { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\ntypedef struct named_number_tag {\n const char* cardinal;\n const char* ordinal;\n integer number;\n} named_number;\n\nconst named_number named_numbers[] = {\n { \"hundred\", \"hundredth\", 100 },\n { \"thousand\", \"thousandth\", 1000 },\n { \"million\", \"millionth\", 1000000 },\n { \"billion\", \"biliionth\", 1000000000 },\n { \"trillion\", \"trillionth\", 1000000000000 },\n { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_small_name(const number_names* n, bool ordinal) {\n return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst char* get_big_name(const named_number* n, bool ordinal) {\n return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst named_number* get_named_number(integer n) {\n const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]);\n for (size_t i = 0; i + 1 < names_len; ++i) {\n if (n < named_numbers[i + 1].number)\n return &named_numbers[i];\n }\n return &named_numbers[names_len - 1];\n}\n\ntypedef struct word_tag {\n size_t offset;\n size_t length;\n} word_t;\n\ntypedef struct word_list_tag {\n GArray* words;\n GString* str;\n} word_list;\n\nvoid word_list_create(word_list* words) {\n words->words = g_array_new(FALSE, FALSE, sizeof(word_t));\n words->str = g_string_new(NULL);\n}\n\nvoid word_list_destroy(word_list* words) {\n g_string_free(words->str, TRUE);\n g_array_free(words->words, TRUE);\n}\n\nvoid word_list_clear(word_list* words) {\n g_string_truncate(words->str, 0);\n g_array_set_size(words->words, 0);\n}\n\nvoid word_list_append(word_list* words, const char* str) {\n size_t offset = words->str->len;\n size_t len = strlen(str);\n g_string_append_len(words->str, str, len);\n word_t word;\n word.offset = offset;\n word.length = len;\n g_array_append_val(words->words, word);\n}\n\nword_t* word_list_get(word_list* words, size_t index) {\n return &g_array_index(words->words, word_t, index);\n}\n\nvoid word_list_extend(word_list* words, const char* str) {\n word_t* word = word_list_get(words, words->words->len - 1);\n size_t len = strlen(str);\n word->length += len;\n g_string_append_len(words->str, str, len);\n}\n\nsize_t append_number_name(word_list* words, integer n, bool ordinal) {\n size_t count = 0;\n if (n < 20) {\n word_list_append(words, get_small_name(&small[n], ordinal));\n count = 1;\n } else if (n < 100) {\n if (n % 10 == 0) {\n word_list_append(words, get_small_name(&tens[n/10 - 2], ordinal));\n } else {\n word_list_append(words, get_small_name(&tens[n/10 - 2], false));\n word_list_extend(words, \"-\");\n word_list_extend(words, get_small_name(&small[n % 10], ordinal));\n }\n count = 1;\n } else {\n const named_number* num = get_named_number(n);\n integer p = num->number;\n count += append_number_name(words, n/p, false);\n if (n % p == 0) {\n word_list_append(words, get_big_name(num, ordinal));\n ++count;\n } else {\n word_list_append(words, get_big_name(num, false));\n ++count;\n count += append_number_name(words, n % p, ordinal);\n }\n }\n return count;\n}\n\nsize_t count_letters(word_list* words, size_t index) {\n const word_t* word = word_list_get(words, index);\n size_t letters = 0;\n const char* s = words->str->str + word->offset;\n for (size_t i = 0, n = word->length; i < n; ++i) {\n if (isalpha((unsigned char)s[i]))\n ++letters;\n }\n return letters;\n}\n\nvoid sentence(word_list* result, size_t count) {\n static const char* words[] = {\n \"Four\", \"is\", \"the\", \"number\", \"of\", \"letters\", \"in\", \"the\",\n \"first\", \"word\", \"of\", \"this\", \"sentence,\"\n };\n word_list_clear(result);\n size_t n = sizeof(words)/sizeof(words[0]);\n for (size_t i = 0; i < n; ++i)\n word_list_append(result, words[i]);\n for (size_t i = 1; count > n; ++i) {\n n += append_number_name(result, count_letters(result, i), false);\n word_list_append(result, \"in\");\n word_list_append(result, \"the\");\n n += 2;\n n += append_number_name(result, i + 1, true);\n // Append a comma to the final word\n word_list_extend(result, \",\");\n }\n}\n\nsize_t sentence_length(const word_list* words) {\n size_t n = words->words->len;\n if (n == 0)\n return 0;\n return words->str->len + n - 1;\n}\n\nint main() {\n setlocale(LC_ALL, \"\");\n size_t n = 201;\n word_list result = { 0 };\n word_list_create(&result);\n sentence(&result, n);\n printf(\"Number of letters in first %'lu words in the sequence:\\n\", n);\n for (size_t i = 0; i < n; ++i) {\n if (i != 0)\n printf(\"%c\", i % 25 == 0 ? '\\n' : ' ');\n printf(\"%'2lu\", count_letters(&result, i));\n }\n printf(\"\\nSentence length: %'lu\\n\", sentence_length(&result));\n for (n = 1000; n <= 10000000; n *= 10) {\n sentence(&result, n);\n const word_t* word = word_list_get(&result, n - 1);\n const char* s = result.str->str + word->offset;\n printf(\"The %'luth word is '%.*s' and has %lu letters. \", n,\n (int)word->length, s, count_letters(&result, n - 1));\n printf(\"Sentence length: %'lu\\n\" , sentence_length(&result));\n }\n word_list_destroy(&result);\n return 0;\n}"} +{"title": "Four is the number of letters in the ...", "language": "Python", "task": "The \u00a0 \u00a0 '''Four is ...''' \u00a0 \u00a0 sequence is based on the counting of the number of\nletters in the words of the (never\u2500ending) sentence:\n Four is the number of letters in the first word of this sentence, two in the second,\n three in the third, six in the fourth, two in the fifth, seven in the sixth, \u00b7\u00b7\u00b7 \n\n\n;Definitions and directives:\n:* \u00a0 English is to be used in spelling numbers.\n:* \u00a0 '''Letters''' \u00a0 are defined as the upper\u2500 and lowercase letters in the Latin alphabet \u00a0 ('''A\u2500\u2500\u25baZ''' \u00a0 and \u00a0 '''a\u2500\u2500\u25baz''').\n:* \u00a0 Commas are not counted, \u00a0 nor are hyphens (dashes or minus signs).\n:* \u00a0 '''twenty\u2500three''' \u00a0 has eleven letters.\n:* \u00a0 '''twenty\u2500three''' \u00a0 is considered one word \u00a0 (which is hyphenated).\n:* \u00a0 no \u00a0 ''' ''and'' ''' \u00a0 words are to be used when spelling a (English) word for a number.\n:* \u00a0 The American version of numbers will be used here in this task \u00a0 (as opposed to the British version).\n '''2,000,000,000''' \u00a0 is two billion, \u00a0 ''not'' \u00a0 two milliard.\n\n\n;Task:\n:* \u00a0 Write a driver (invoking routine) and a function (subroutine/routine\u00b7\u00b7\u00b7) that returns the sequence (for any positive integer) of the number of letters in the first \u00a0 '''N''' \u00a0 words in the never\u2500ending sentence. \u00a0 For instance, the portion of the never\u2500ending sentence shown above (2nd sentence of this task's preamble), \u00a0 the sequence would be:\n '''4 2 3 6 2 7'''\n:* \u00a0 Only construct as much as is needed for the never\u2500ending sentence.\n:* \u00a0 Write a driver (invoking routine) to show the number of letters in the \u00a0 Nth \u00a0 word, \u00a0 ''as well as'' \u00a0 showing the \u00a0 Nth \u00a0 word itself.\n:* \u00a0 After each test case, show the total number of characters \u00a0 (including blanks, commas, and punctuation) \u00a0 of the sentence that was constructed.\n:* \u00a0 Show all output here.\n\n\n;Test cases:\n Display the first 201 numbers in the sequence \u00a0 (and the total number of characters in the sentence).\n Display the number of letters (and the word itself) of the 1,000th word.\n Display the number of letters (and the word itself) of the 10,000th word.\n Display the number of letters (and the word itself) of the 100,000th word.\n Display the number of letters (and the word itself) of the 1,000,000th word.\n Display the number of letters (and the word itself) of the 10,000,000th word (optional).\n\n\n;Related tasks:\n:* \u00a0 [[Four is magic]]\n:* \u00a0 [[Look-and-say sequence]]\n:* \u00a0 [[Number names]]\n:* \u00a0 [[Self-describing numbers]]\n:* \u00a0 [[Self-referential sequence]]\n:* \u00a0 [[Spelling of ordinal numbers]]\n\n\n;Also see:\n:* \u00a0 See the OEIS sequence A72425 \"Four is the number of letters...\".\n:* \u00a0 See the OEIS sequence A72424 \"Five's the number of letters...\"\n\n", "solution": "\n# Python implementation of Rosetta Code Task \n# http://rosettacode.org/wiki/Four_is_the_number_of_letters_in_the_...\n# Uses inflect\n# https://pypi.org/project/inflect/\n\nimport inflect\n\ndef count_letters(word):\n \"\"\"\n count letters ignore , or -, or space\n \"\"\"\n count = 0\n for letter in word:\n if letter != ',' and letter !='-' and letter !=' ':\n count += 1\n \n return count\n \ndef split_with_spaces(sentence):\n \"\"\"\n Takes string with partial sentence and returns\n list of words with spaces included.\n \n Leading space is attached to first word.\n Later spaces attached to prior word.\n \"\"\"\n sentence_list = []\n curr_word = \"\"\n for c in sentence:\n if c == \" \" and curr_word != \"\":\n # append space to end of non-empty words\n # assumed no more than 1 consecutive space.\n sentence_list.append(curr_word+\" \")\n curr_word = \"\"\n else:\n curr_word += c\n \n # add trailing word that does not end with a space \n \n if len(curr_word) > 0:\n sentence_list.append(curr_word)\n \n return sentence_list\n \ndef my_num_to_words(p, my_number):\n \"\"\"\n Front end to inflect's number_to_words\n \n Get's rid of ands and commas in large numbers.\n \"\"\"\n \n number_string_list = p.number_to_words(my_number, wantlist=True, andword='')\n \n number_string = number_string_list[0]\n \n for i in range(1,len(number_string_list)):\n number_string += \" \" + number_string_list[i]\n \n return number_string\n \ndef build_sentence(p, max_words):\n \"\"\"\n \n Builds at most max_words of the task following the pattern:\n \n Four is the number of letters in the first word of this sentence, two in the second,\n three in the third, six in the fourth, two in the fifth, seven in the sixth,\n \n \"\"\"\n \n # start with first part of sentence up first comma as a list\n \n sentence_list = split_with_spaces(\"Four is the number of letters in the first word of this sentence,\")\n \n num_words = 13\n \n # which word number we are doing next\n # two/second is first one in loop\n \n word_number = 2\n \n # loop until sentance is at least as long as needs be\n \n while num_words < max_words:\n # Build something like\n # ,two in the second\n \n # get second or whatever we are on\n \n ordinal_string = my_num_to_words(p, p.ordinal(word_number))\n \n # get two or whatever the length is of the word_number word\n \n word_number_string = my_num_to_words(p, count_letters(sentence_list[word_number - 1]))\n \n # sentence addition\n \n new_string = \" \"+word_number_string+\" in the \"+ordinal_string+\",\"\n\n new_list = split_with_spaces(new_string)\n \n sentence_list += new_list\n\n # add new word count\n \n num_words += len(new_list)\n \n # increment word number\n \n word_number += 1\n \n return sentence_list, num_words\n \ndef word_and_counts(word_num):\n \"\"\"\n \n Print's lines like this:\n \n Word 1000 is \"in\", with 2 letters. Length of sentence so far: 6279\n\n \"\"\"\n \n sentence_list, num_words = build_sentence(p, word_num)\n \n word_str = sentence_list[word_num - 1].strip(' ,')\n \n num_letters = len(word_str)\n \n num_characters = 0\n \n for word in sentence_list:\n num_characters += len(word)\n \n print('Word {0:8d} is \"{1}\", with {2} letters. Length of the sentence so far: {3} '.format(word_num,word_str,num_letters,num_characters))\n \n \np = inflect.engine()\n\nsentence_list, num_words = build_sentence(p, 201)\n\nprint(\" \")\nprint(\"The lengths of the first 201 words are:\")\nprint(\" \")\n\nprint('{0:3d}: '.format(1),end='')\n\ntotal_characters = 0\n\nfor word_index in range(201):\n\n word_length = count_letters(sentence_list[word_index])\n \n total_characters += len(sentence_list[word_index])\n \n print('{0:2d}'.format(word_length),end='')\n if (word_index+1) % 20 == 0:\n # newline every 20\n print(\" \")\n print('{0:3d}: '.format(word_index + 2),end='')\n else:\n print(\" \",end='')\n \nprint(\" \")\nprint(\" \")\nprint(\"Length of the sentence so far: \"+str(total_characters))\nprint(\" \")\n\n\"\"\"\n\nExpected output this part:\n\nWord 1000 is \"in\", with 2 letters. Length of the sentence so far: 6279\nWord 10000 is \"in\", with 2 letters. Length of the sentence so far: 64140\nWord 100000 is \"one\", with 3 letters. Length of the sentence so far: 659474\nWord 1000000 is \"the\", with 3 letters. Length of the sentence so far: 7113621\nWord 10000000 is \"thousand\", with 8 letters. Length of the sentence so far: 70995756\n\n\"\"\"\n\nword_and_counts(1000)\nword_and_counts(10000)\nword_and_counts(100000)\nword_and_counts(1000000)\nword_and_counts(10000000)\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": "Function prototype", "language": "JavaScript", "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": "\n// A prototype declaration for a function that does not require arguments\nfunction List() {}\n\nList.prototype.push = function() {\n return [].push.apply(this, arguments);\n};\n\nList.prototype.pop = function() {\n return [].pop.call(this);\n};\n\nvar l = new List();\nl.push(5);\nl.length; // 1\nl[0]; 5\nl.pop(); // 5\nl.length; // 0\n\n// A prototype declaration for a function that utilizes varargs\nfunction List() {\n this.push.apply(this, arguments);\n}\n\nList.prototype.push = function() {\n return [].push.apply(this, arguments);\n};\n\nList.prototype.pop = function() {\n return [].pop.call(this);\n};\n\nvar l = new List(5, 10, 15);\nl.length; // 3\nl[0]; 5\nl.pop(); // 15\nl.length; // 2\n\n"} +{"title": "Functional coverage tree", "language": "JavaScript", "task": "Functional coverage is a measure of how much a particular function of a system \nhas been verified as correct. It is used heavily in tracking the completeness \nof the verification of complex System on Chip (SoC) integrated circuits, where \nit can also be used to track how well the functional ''requirements'' of the \nsystem have been verified.\n\nThis task uses a sub-set of the calculations sometimes used in tracking \nfunctional coverage but uses a more familiar(?) scenario.\n\n;Task Description:\nThe head of the clean-up crews for \"The Men in a very dark shade of grey when \nviewed at night\" has been tasked with managing the cleansing of two properties\nafter an incident involving aliens.\n\nShe arranges the task hierarchically with a manager for the crews working on \neach house who return with a breakdown of how they will report on progress in \neach house.\n\nThe overall hierarchy of (sub)tasks is as follows, \ncleaning\n house1\n bedrooms\n bathrooms\n bathroom1\n bathroom2\n outside lavatory\n attic\n kitchen\n living rooms\n lounge\n dining room\n conservatory\n playroom\n basement\n garage\n garden\n house2\n upstairs\n bedrooms\n suite 1\n suite 2\n bedroom 3\n bedroom 4\n bathroom\n toilet\n attics\n groundfloor\n kitchen\n living rooms\n lounge\n dining room\n conservatory\n playroom\n wet room & toilet\n garage\n garden\n hot tub suite\n basement\n cellars\n wine cellar\n cinema\n\nThe head of cleanup knows that her managers will report fractional completion of leaf tasks (tasks with no child tasks of their own), and she knows that she will want to modify the weight of values of completion as she sees fit.\n\nSome time into the cleaning, and some coverage reports have come in and she thinks see needs to weight the big house2 60-40 with respect to coverage from house1 She prefers a tabular view of her data where missing weights are assumed to be 1.0 and missing coverage 0.0.\nNAME_HIERARCHY |WEIGHT |COVERAGE |\ncleaning | | |\n house1 |40 | |\n bedrooms | |0.25 |\n bathrooms | | |\n bathroom1 | |0.5 |\n bathroom2 | | |\n outside_lavatory | |1 |\n attic | |0.75 |\n kitchen | |0.1 |\n living_rooms | | |\n lounge | | |\n dining_room | | |\n conservatory | | |\n playroom | |1 |\n basement | | |\n garage | | |\n garden | |0.8 |\n house2 |60 | |\n upstairs | | |\n bedrooms | | |\n suite_1 | | |\n suite_2 | | |\n bedroom_3 | | |\n bedroom_4 | | |\n bathroom | | |\n toilet | | |\n attics | |0.6 |\n groundfloor | | |\n kitchen | | |\n living_rooms | | |\n lounge | | |\n dining_room | | |\n conservatory | | |\n playroom | | |\n wet_room_&_toilet | | |\n garage | | |\n garden | |0.9 |\n hot_tub_suite | |1 |\n basement | | |\n cellars | |1 |\n wine_cellar | |1 |\n cinema | |0.75 |\n\n;Calculation:\nThe coverage of a node in the tree is calculated as the weighted average of the coverage of its children evaluated bottom-upwards in the tree.\n\n'''The task is to''' calculate the overall coverage of the cleaning task and display the coverage at all levels of the hierarchy on this page, in a manner that visually shows the hierarchy, weights and coverage of all nodes.\n\n;Extra Credit:\nAfter calculating the coverage for all nodes, one can also calculate the additional/delta top level coverage that would occur if any (sub)task were to be fully covered from its current fractional coverage. This is done by multiplying the extra coverage that could be gained 1-coverage for any node, by the product of the `powers` of its parent nodes from the top down to the node.\nThe power of a direct child of any parent is given by the power of the parent multiplied by the weight of the child divided by the sum of the weights of all the direct children.\n\nThe pseudo code would be:\n\n method delta_calculation(this, power):\n sum_of_weights = sum(node.weight for node in children)\n this.delta = (1 - this.coverage) * power\n for node in self.children:\n node.delta_calculation(power * node.weight / sum_of_weights)\n return this.delta\n\nFollowed by a call to:\n\n top.delta_calculation(power=1)\n\n\n'''Note:''' to aid in getting the data into your program you might want to use an alternative, more functional description of the starting data given on the discussion page.\n\n", "solution": "(() => {\n 'use strict';\n\n // updatedCoverageOutline :: String -> String\n const updatedCoverageOutline = outlineText => {\n const\n delimiter = '|',\n indentedLines = indentLevelsFromLines(lines(outlineText)),\n columns = init(tokenizeWith(delimiter)(snd(indentedLines[0])));\n\n // SERIALISATION OF UPDATED PARSE TREE (TO NEW OUTLINE TEXT)\n return tabulation(delimiter)(\n columns.concat('SHARE OF RESIDUE\\n')\n ) + unlines(\n indentedLinesFromTree(\n showCoverage(delimiter))(' ')(\n\n // TWO TRAVERSAL COMPUTATIONS\n\n withResidueShares(1.0)(\n foldTree(weightedCoverage)(\n\n // PARSE TREE (FROM OUTLINE TEXT)\n fmapTree(compose(\n partialRecord, tokenizeWith(delimiter)\n ))(fst(\n forestFromLineIndents(tail(indentedLines))\n ))\n )\n ))\n );\n };\n\n // TEST -----------------------------------------------\n // main :: IO ()\n const main = () =>\n console.log(\n // strOutline is included as literal text\n // at the foot of this code listing.\n updatedCoverageOutline(strOutline)\n );\n\n // COVERAGE AND SHARES OF RESIDUE ---------------------\n\n // weightedCoverage :: Dict -> Forest Dict -> Tree Dict\n const weightedCoverage = x => xs => {\n const\n cws = map(compose(\n fanArrow(x => x.coverage)(x => x.weight),\n root\n ))(xs),\n totalWeight = cws.reduce((a, tpl) => a + snd(tpl), 0);\n return Node(\n insertDict('coverage')(\n cws.reduce((a, tpl) => {\n const [c, w] = Array.from(tpl);\n return a + (c * w);\n }, x.coverage) / (\n 0 < totalWeight ? totalWeight : 1\n )\n )(x)\n )(xs);\n };\n\n\n // withResidueShares :: Float -> Tree Dict -> Tree Dict\n const withResidueShares = shareOfTotal => tree => {\n const go = fraction => node => {\n const\n nodeRoot = node.root,\n forest = node.nest,\n weights = forest.map(x => x.root.weight),\n weightTotal = sum(weights);\n return Node(\n insertDict('share')(\n fraction * (1 - nodeRoot.coverage)\n )(nodeRoot)\n )(\n zipWith(go)(\n weights.map(w => fraction * (w / weightTotal))\n )(forest)\n );\n };\n return go(shareOfTotal)(tree);\n };\n\n\n // OUTLINE PARSED TO TREE -----------------------------\n\n // forestFromLineIndents :: [(Int, String)] -> [Tree String]\n const forestFromLineIndents = tuples => {\n const go = xs =>\n 0 < xs.length ? (() => {\n const [n, s] = Array.from(xs[0]);\n // Lines indented under this line,\n // tupled with all the rest.\n const [firstTreeLines, rest] = Array.from(\n span(x => n < x[0])(xs.slice(1))\n );\n // This first tree, and then the rest.\n return [Node(s)(go(firstTreeLines))]\n .concat(go(rest));\n })() : [];\n return go(tuples);\n };\n\n // indentLevelsFromLines :: [String] -> [(Int, String)]\n const indentLevelsFromLines = xs => {\n const\n indentTextPairs = xs.map(compose(\n firstArrow(length), span(isSpace)\n )),\n indentUnit = minimum(indentTextPairs.flatMap(pair => {\n const w = fst(pair);\n return 0 < w ? [w] : [];\n }));\n return indentTextPairs.map(\n firstArrow(flip(div)(indentUnit))\n );\n };\n\n // partialRecord :: [String] -> Dict\n const partialRecord = xs => {\n const [name, weightText, coverageText] = take(3)(\n xs.concat(['', '', ''])\n );\n return {\n name: name || '?',\n weight: parseFloat(weightText) || 1.0,\n coverage: parseFloat(coverageText) || 0.0,\n share: 0.0\n };\n };\n\n // tokenizeWith :: String -> String -> [String]\n const tokenizeWith = delimiter =>\n // A sequence of trimmed tokens obtained by\n // splitting s on the supplied delimiter.\n s => s.split(delimiter).map(x => x.trim());\n\n\n // TREE SERIALIZED TO OUTLINE -------------------------\n\n // indentedLinesFromTree :: (String -> a -> String) ->\n // String -> Tree a -> [String]\n const indentedLinesFromTree = showRoot =>\n strTab => tree => {\n const go = indent =>\n node => [showRoot(indent)(node.root)]\n .concat(node.nest.flatMap(go(strTab + indent)));\n return go('')(tree);\n };\n\n // showN :: Int -> Float -> String\n const showN = p =>\n n => justifyRight(7)(' ')(n.toFixed(p));\n\n // showCoverage :: String -> String -> Dict -> String\n const showCoverage = delimiter =>\n indent => x => tabulation(delimiter)(\n [indent + x.name, showN(0)(x.weight)]\n .concat([x.coverage, x.share].map(showN(4)))\n );\n\n // tabulation :: String -> [String] -> String\n const tabulation = delimiter =>\n // Up to 4 tokens drawn from the argument list,\n // as a single string with fixed left-justified\n // white-space widths, between delimiters.\n compose(\n intercalate(delimiter + ' '),\n zipWith(flip(justifyLeft)(' '))([31, 9, 9, 9])\n );\n\n\n // GENERIC AND REUSABLE FUNCTIONS ---------------------\n\n // Node :: a -> [Tree a] -> Tree a\n const Node = v => xs => ({\n type: 'Node',\n root: v, // any type of value (consistent across tree)\n nest: xs || []\n });\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = a => b => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (...fs) =>\n x => fs.reduceRight((a, f) => f(a), x);\n\n // concat :: [[a]] -> [a]\n // concat :: [String] -> String\n const concat = xs =>\n 0 < xs.length ? (() => {\n const unit = 'string' !== typeof xs[0] ? (\n []\n ) : '';\n return unit.concat.apply(unit, xs);\n })() : [];\n\n // div :: Int -> Int -> Int\n const div = x => y => Math.floor(x / y);\n\n // either :: (a -> c) -> (b -> c) -> Either a b -> c\n const either = fl => fr => e =>\n 'Either' === e.type ? (\n undefined !== e.Left ? (\n fl(e.Left)\n ) : fr(e.Right)\n ) : undefined;\n\n // Compose a function from a simple value to a tuple of\n // the separate outputs of two different functions\n\n // fanArrow (&&&) :: (a -> b) -> (a -> c) -> (a -> (b, c))\n const fanArrow = f => g => x => Tuple(f(x))(\n g(x)\n );\n\n // Lift a simple function to one which applies to a tuple,\n // transforming only the first item of the tuple\n\n // firstArrow :: (a -> b) -> ((a, c) -> (b, c))\n const firstArrow = f => xy => Tuple(f(xy[0]))(\n xy[1]\n );\n\n // flip :: (a -> b -> c) -> b -> a -> c\n const flip = f =>\n 1 < f.length ? (\n (a, b) => f(b, a)\n ) : (x => y => f(y)(x));\n\n // fmapTree :: (a -> b) -> Tree a -> Tree b\n const fmapTree = f => tree => {\n const go = node => Node(f(node.root))(\n node.nest.map(go)\n );\n return go(tree);\n };\n\n // foldTree :: (a -> [b] -> b) -> Tree a -> b\n const foldTree = f => tree => {\n const go = node => f(node.root)(\n node.nest.map(go)\n );\n return go(tree);\n };\n\n // foldl1 :: (a -> a -> a) -> [a] -> a\n const foldl1 = f => xs =>\n 1 < xs.length ? xs.slice(1)\n .reduce(uncurry(f), xs[0]) : xs[0];\n\n // fst :: (a, b) -> a\n const fst = tpl => tpl[0];\n\n // init :: [a] -> [a]\n const init = xs =>\n 0 < xs.length ? (\n xs.slice(0, -1)\n ) : undefined;\n\n // insertDict :: String -> a -> Dict -> Dict\n const insertDict = k => v => dct =>\n Object.assign({}, dct, {\n [k]: v\n });\n\n // intercalate :: [a] -> [[a]] -> [a]\n // intercalate :: String -> [String] -> String\n const intercalate = sep =>\n xs => xs.join(sep);\n\n // isSpace :: Char -> Bool\n const isSpace = c => /\\s/.test(c);\n\n // justifyLeft :: Int -> Char -> String -> String\n const justifyLeft = n => cFiller => s =>\n n > s.length ? (\n s.padEnd(n, cFiller)\n ) : s;\n\n // justifyRight :: Int -> Char -> String -> String\n const justifyRight = n => cFiller => s =>\n n > s.length ? (\n s.padStart(n, cFiller)\n ) : s;\n\n // length :: [a] -> Int\n const length = xs =>\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n // lines :: String -> [String]\n const lines = s => s.split(/[\\r\\n]/);\n\n // map :: (a -> b) -> [a] -> [b]\n const map = f => xs =>\n (Array.isArray(xs) ? (\n xs\n ) : xs.split('')).map(f);\n\n // minimum :: Ord a => [a] -> a\n const minimum = xs =>\n 0 < xs.length ? (\n foldl1(a => x => x < a ? x : a)(xs)\n ) : undefined;\n\n // root :: Tree a -> a\n const root = tree => tree.root;\n\n // showLog :: a -> IO ()\n const showLog = (...args) =>\n console.log(\n args\n .map(JSON.stringify)\n .join(' -> ')\n );\n\n // snd :: (a, b) -> b\n const snd = tpl => tpl[1];\n\n // span :: (a -> Bool) -> [a] -> ([a], [a])\n const span = p => xs => {\n const iLast = xs.length - 1;\n return splitAt(\n until(i => iLast < i || !p(xs[i]))(\n succ\n )(0)\n )(xs);\n };\n\n // splitAt :: Int -> [a] -> ([a], [a])\n const splitAt = n => xs =>\n Tuple(xs.slice(0, n))(\n xs.slice(n)\n );\n\n // succ :: Enum a => a -> a\n const succ = x =>\n 1 + x;\n\n // sum :: [Num] -> Num\n const sum = xs =>\n xs.reduce((a, x) => a + x, 0);\n\n // tail :: [a] -> [a]\n const tail = xs =>\n 0 < xs.length ? xs.slice(1) : [];\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n => xs =>\n 'GeneratorFunction' !== xs.constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // uncurry :: (a -> b -> c) -> ((a, b) -> c)\n const uncurry = f =>\n (x, y) => f(x)(y);\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // until :: (a -> Bool) -> (a -> a) -> a -> a\n const until = p => f => x => {\n let v = x;\n while (!p(v)) v = f(v);\n return v;\n };\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = f => xs => ys =>\n xs.slice(\n 0, Math.min(xs.length, ys.length)\n ).map((x, i) => f(x)(ys[i]));\n\n // SOURCE OUTLINE -----------------------------------------\n\n const strOutline = `NAME_HIERARCHY |WEIGHT |COVERAGE |\ncleaning | | |\n house1 |40 | |\n bedrooms | |0.25 |\n bathrooms | | |\n bathroom1 | |0.5 |\n bathroom2 | | |\n outside_lavatory | |1 |\n attic | |0.75 |\n kitchen | |0.1 |\n living_rooms | | |\n lounge | | |\n dining_room | | |\n conservatory | | |\n playroom | |1 |\n basement | | |\n garage | | |\n garden | |0.8 |\n house2 |60 | |\n upstairs | | |\n bedrooms | | |\n suite_1 | | |\n suite_2 | | |\n bedroom_3 | | |\n bedroom_4 | | |\n bathroom | | |\n toilet | | |\n attics | |0.6 |\n groundfloor | | |\n kitchen | | |\n living_rooms | | |\n lounge | | |\n dining_room | | |\n conservatory | | |\n playroom | | |\n wet_room_&_toilet | | |\n garage | | |\n garden | |0.9 |\n hot_tub_suite | |1 |\n basement | | |\n cellars | |1 |\n wine_cellar | |1 |\n cinema | |0.75 |`;\n\n // MAIN ---\n return main();\n})();"} +{"title": "Functional coverage tree", "language": "Python", "task": "Functional coverage is a measure of how much a particular function of a system \nhas been verified as correct. It is used heavily in tracking the completeness \nof the verification of complex System on Chip (SoC) integrated circuits, where \nit can also be used to track how well the functional ''requirements'' of the \nsystem have been verified.\n\nThis task uses a sub-set of the calculations sometimes used in tracking \nfunctional coverage but uses a more familiar(?) scenario.\n\n;Task Description:\nThe head of the clean-up crews for \"The Men in a very dark shade of grey when \nviewed at night\" has been tasked with managing the cleansing of two properties\nafter an incident involving aliens.\n\nShe arranges the task hierarchically with a manager for the crews working on \neach house who return with a breakdown of how they will report on progress in \neach house.\n\nThe overall hierarchy of (sub)tasks is as follows, \ncleaning\n house1\n bedrooms\n bathrooms\n bathroom1\n bathroom2\n outside lavatory\n attic\n kitchen\n living rooms\n lounge\n dining room\n conservatory\n playroom\n basement\n garage\n garden\n house2\n upstairs\n bedrooms\n suite 1\n suite 2\n bedroom 3\n bedroom 4\n bathroom\n toilet\n attics\n groundfloor\n kitchen\n living rooms\n lounge\n dining room\n conservatory\n playroom\n wet room & toilet\n garage\n garden\n hot tub suite\n basement\n cellars\n wine cellar\n cinema\n\nThe head of cleanup knows that her managers will report fractional completion of leaf tasks (tasks with no child tasks of their own), and she knows that she will want to modify the weight of values of completion as she sees fit.\n\nSome time into the cleaning, and some coverage reports have come in and she thinks see needs to weight the big house2 60-40 with respect to coverage from house1 She prefers a tabular view of her data where missing weights are assumed to be 1.0 and missing coverage 0.0.\nNAME_HIERARCHY |WEIGHT |COVERAGE |\ncleaning | | |\n house1 |40 | |\n bedrooms | |0.25 |\n bathrooms | | |\n bathroom1 | |0.5 |\n bathroom2 | | |\n outside_lavatory | |1 |\n attic | |0.75 |\n kitchen | |0.1 |\n living_rooms | | |\n lounge | | |\n dining_room | | |\n conservatory | | |\n playroom | |1 |\n basement | | |\n garage | | |\n garden | |0.8 |\n house2 |60 | |\n upstairs | | |\n bedrooms | | |\n suite_1 | | |\n suite_2 | | |\n bedroom_3 | | |\n bedroom_4 | | |\n bathroom | | |\n toilet | | |\n attics | |0.6 |\n groundfloor | | |\n kitchen | | |\n living_rooms | | |\n lounge | | |\n dining_room | | |\n conservatory | | |\n playroom | | |\n wet_room_&_toilet | | |\n garage | | |\n garden | |0.9 |\n hot_tub_suite | |1 |\n basement | | |\n cellars | |1 |\n wine_cellar | |1 |\n cinema | |0.75 |\n\n;Calculation:\nThe coverage of a node in the tree is calculated as the weighted average of the coverage of its children evaluated bottom-upwards in the tree.\n\n'''The task is to''' calculate the overall coverage of the cleaning task and display the coverage at all levels of the hierarchy on this page, in a manner that visually shows the hierarchy, weights and coverage of all nodes.\n\n;Extra Credit:\nAfter calculating the coverage for all nodes, one can also calculate the additional/delta top level coverage that would occur if any (sub)task were to be fully covered from its current fractional coverage. This is done by multiplying the extra coverage that could be gained 1-coverage for any node, by the product of the `powers` of its parent nodes from the top down to the node.\nThe power of a direct child of any parent is given by the power of the parent multiplied by the weight of the child divided by the sum of the weights of all the direct children.\n\nThe pseudo code would be:\n\n method delta_calculation(this, power):\n sum_of_weights = sum(node.weight for node in children)\n this.delta = (1 - this.coverage) * power\n for node in self.children:\n node.delta_calculation(power * node.weight / sum_of_weights)\n return this.delta\n\nFollowed by a call to:\n\n top.delta_calculation(power=1)\n\n\n'''Note:''' to aid in getting the data into your program you might want to use an alternative, more functional description of the starting data given on the discussion page.\n\n", "solution": "from itertools import zip_longest\n\n\nfc2 = '''\\\ncleaning,,\n house1,40,\n bedrooms,,.25\n bathrooms,,\n bathroom1,,.5\n bathroom2,,\n outside_lavatory,,1\n attic,,.75\n kitchen,,.1\n living_rooms,,\n lounge,,\n dining_room,,\n conservatory,,\n playroom,,1\n basement,,\n garage,,\n garden,,.8\n house2,60,\n upstairs,,\n bedrooms,,\n suite_1,,\n suite_2,,\n bedroom_3,,\n bedroom_4,,\n bathroom,,\n toilet,,\n attics,,.6\n groundfloor,,\n kitchen,,\n living_rooms,,\n lounge,,\n dining_room,,\n conservatory,,\n playroom,,\n wet_room_&_toilet,,\n garage,,\n garden,,.9\n hot_tub_suite,,1\n basement,,\n cellars,,1\n wine_cellar,,1\n cinema,,.75\n\n'''\n\nNAME, WT, COV = 0, 1, 2\n\ndef right_type(txt):\n try:\n return float(txt)\n except ValueError:\n return txt\n\ndef commas_to_list(the_list, lines, start_indent=0):\n '''\n Output format is a nest of lists and tuples\n lists are for coverage leaves without children items in the list are name, weight, coverage\n tuples are 2-tuples for nodes with children. The first element is a list representing the\n name, weight, coverage of the node (some to be calculated); the second element is a list of\n child elements which may be 2-tuples or lists as above.\n \n the_list is modified in-place\n lines must be a generator of successive lines of input like fc2\n '''\n for n, line in lines:\n indent = 0\n while line.startswith(' ' * (4 * indent)):\n indent += 1\n indent -= 1\n fields = [right_type(f) for f in line.strip().split(',')]\n if indent == start_indent:\n the_list.append(fields)\n elif indent > start_indent:\n lst = [fields]\n sub = commas_to_list(lst, lines, indent)\n the_list[-1] = (the_list[-1], lst)\n if sub not in (None, ['']) :\n the_list.append(sub)\n else:\n return fields if fields else None\n return None\n\n\ndef pptreefields(lst, indent=0, widths=['%-32s', '%-8g', '%-10g']):\n '''\n Pretty prints the format described from function commas_to_list as a table with \n names in the first column suitably indented and all columns having a fixed \n minimum column width.\n '''\n lhs = ' ' * (4 * indent)\n for item in lst:\n if type(item) != tuple:\n name, *rest = item\n print(widths[0] % (lhs + name), end='|')\n for width, item in zip_longest(widths[1:len(rest)], rest, fillvalue=widths[-1]):\n if type(item) == str:\n width = width[:-1] + 's'\n print(width % item, end='|')\n print()\n else:\n item, children = item\n name, *rest = item\n print(widths[0] % (lhs + name), end='|')\n for width, item in zip_longest(widths[1:len(rest)], rest, fillvalue=widths[-1]):\n if type(item) == str:\n width = width[:-1] + 's'\n print(width % item, end='|')\n print()\n pptreefields(children, indent+1)\n\n\ndef default_field(node_list):\n node_list[WT] = node_list[WT] if node_list[WT] else 1.0\n node_list[COV] = node_list[COV] if node_list[COV] else 0.0\n\ndef depth_first(tree, visitor=default_field):\n for item in tree:\n if type(item) == tuple:\n item, children = item\n depth_first(children, visitor)\n visitor(item)\n \n\ndef covercalc(tree):\n '''\n Depth first weighted average of coverage\n '''\n sum_covwt, sum_wt = 0, 0\n for item in tree:\n if type(item) == tuple:\n item, children = item\n item[COV] = covercalc(children)\n sum_wt += item[WT]\n sum_covwt += item[COV] * item[WT]\n cov = sum_covwt / sum_wt\n return cov\n\nif __name__ == '__main__': \n lstc = []\n commas_to_list(lstc, ((n, ln) for n, ln in enumerate(fc2.split('\\n'))))\n #pp(lstc, width=1, indent=4, compact=1)\n \n #print('\\n\\nEXPANDED DEFAULTS\\n')\n depth_first(lstc)\n #pptreefields(['NAME_HIERARCHY WEIGHT COVERAGE'.split()] + lstc)\n \n print('\\n\\nTOP COVERAGE = %f\\n' % covercalc(lstc))\n depth_first(lstc)\n pptreefields(['NAME_HIERARCHY WEIGHT COVERAGE'.split()] + lstc)"} +{"title": "Fusc sequence", "language": "C", "task": ";Definitions:\nThe \u00a0 '''fusc''' \u00a0 integer sequence is defined as:\n::* \u00a0 fusc(0) = 0\n::* \u00a0 fusc(1) = 1\n::* \u00a0 for '''n'''>1, \u00a0 the \u00a0 '''n'''th \u00a0 term is defined as:\n::::* \u00a0 if \u00a0 '''n''' \u00a0 is even; \u00a0 \u00a0 fusc(n) = fusc(n/2)\n::::* \u00a0 if \u00a0 '''n''' \u00a0 is \u00a0 odd; \u00a0 \u00a0 fusc(n) = fusc((n-1)/2) \u00a0 + \u00a0 fusc((n+1)/2)\n\n\nNote that MathWorld's definition starts with unity, not zero. \u00a0 This task will be using the OEIS' version \u00a0 (above).\n\n\n\n;An observation:\n:::::* \u00a0 fusc(A) = fusc(B)\n\nwhere \u00a0 '''A''' \u00a0 is some non-negative integer expressed in binary, \u00a0 and\nwhere \u00a0 '''B''' \u00a0 is the binary value of \u00a0 '''A''' \u00a0 reversed.\n\n\n\nFusc numbers are also known as:\n::* \u00a0 fusc function \u00a0 (named by Dijkstra, 1982)\n::* \u00a0 Stern's Diatomic series \u00a0 (although it starts with unity, not zero)\n::* \u00a0 Stern-Brocot sequence \u00a0 (although it starts with unity, not zero)\n\n\n\n;Task:\n::* \u00a0 show the first \u00a0 '''61''' \u00a0 fusc numbers (starting at zero) in a horizontal format.\n::* \u00a0 show the fusc number (and its index) whose length is greater than any previous fusc number length.\n::::* \u00a0 (the length is the number of decimal digits when the fusc number is expressed in base ten.)\n::* \u00a0 show all numbers with commas \u00a0 (if appropriate).\n::* \u00a0 show all output here.\n\n\n;Related task:\n::* \u00a0 RosettaCode Stern-Brocot sequence\n\n\n\n;Also see:\n::* \u00a0 the MathWorld entry: \u00a0 [http://mathworld.wolfram.com/SternsDiatomicSeries.html Stern's Diatomic Series].\n::* \u00a0 the OEIS entry: \u00a0 [http://oeis.org/A2487 A2487].\n\n", "solution": "\n#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": "Fusc sequence", "language": "Python", "task": ";Definitions:\nThe \u00a0 '''fusc''' \u00a0 integer sequence is defined as:\n::* \u00a0 fusc(0) = 0\n::* \u00a0 fusc(1) = 1\n::* \u00a0 for '''n'''>1, \u00a0 the \u00a0 '''n'''th \u00a0 term is defined as:\n::::* \u00a0 if \u00a0 '''n''' \u00a0 is even; \u00a0 \u00a0 fusc(n) = fusc(n/2)\n::::* \u00a0 if \u00a0 '''n''' \u00a0 is \u00a0 odd; \u00a0 \u00a0 fusc(n) = fusc((n-1)/2) \u00a0 + \u00a0 fusc((n+1)/2)\n\n\nNote that MathWorld's definition starts with unity, not zero. \u00a0 This task will be using the OEIS' version \u00a0 (above).\n\n\n\n;An observation:\n:::::* \u00a0 fusc(A) = fusc(B)\n\nwhere \u00a0 '''A''' \u00a0 is some non-negative integer expressed in binary, \u00a0 and\nwhere \u00a0 '''B''' \u00a0 is the binary value of \u00a0 '''A''' \u00a0 reversed.\n\n\n\nFusc numbers are also known as:\n::* \u00a0 fusc function \u00a0 (named by Dijkstra, 1982)\n::* \u00a0 Stern's Diatomic series \u00a0 (although it starts with unity, not zero)\n::* \u00a0 Stern-Brocot sequence \u00a0 (although it starts with unity, not zero)\n\n\n\n;Task:\n::* \u00a0 show the first \u00a0 '''61''' \u00a0 fusc numbers (starting at zero) in a horizontal format.\n::* \u00a0 show the fusc number (and its index) whose length is greater than any previous fusc number length.\n::::* \u00a0 (the length is the number of decimal digits when the fusc number is expressed in base ten.)\n::* \u00a0 show all numbers with commas \u00a0 (if appropriate).\n::* \u00a0 show all output here.\n\n\n;Related task:\n::* \u00a0 RosettaCode Stern-Brocot sequence\n\n\n\n;Also see:\n::* \u00a0 the MathWorld entry: \u00a0 [http://mathworld.wolfram.com/SternsDiatomicSeries.html Stern's Diatomic Series].\n::* \u00a0 the OEIS entry: \u00a0 [http://oeis.org/A2487 A2487].\n\n", "solution": "from collections import deque\nfrom itertools import islice, count\n\n\ndef fusc():\n q = deque([1])\n yield 0\n yield 1\n\n while True:\n x = q.popleft()\n q.append(x)\n yield x\n\n x += q[0]\n q.append(x)\n yield x\n\n\ndef longest_fusc():\n sofar = 0\n for i, f in zip(count(), fusc()):\n if f >= sofar:\n yield(i, f)\n sofar = 10 * sofar or 10\n\n\nprint('First 61:')\nprint(list(islice(fusc(), 61)))\n\nprint('\\nLength records:')\nfor i, f in islice(longest_fusc(), 6):\n print(f'fusc({i}) = {f}')\n"} +{"title": "Gapful numbers", "language": "C", "task": "Numbers \u00a0 (positive integers expressed in base ten) \u00a0 that are (evenly) divisible by the number formed by the\nfirst and last digit are known as \u00a0 '''gapful numbers'''.\n\n\n''Evenly divisible'' \u00a0 means divisible with \u00a0 no \u00a0 remainder.\n\n\nAll \u00a0 one\u2500 \u00a0 and two\u2500digit \u00a0 numbers have this property and are trivially excluded. \u00a0 Only\nnumbers \u00a0 \u2265 '''100''' \u00a0 will be considered for this Rosetta Code task.\n\n\n;Example:\n'''187''' \u00a0 is a \u00a0 '''gapful''' \u00a0 number because it is evenly divisible by the\nnumber \u00a0 '''17''' \u00a0 which is formed by the first and last decimal digits\nof \u00a0 '''187'''. \n\n\nAbout \u00a0 7.46% \u00a0 of positive integers are \u00a0 ''gapful''. \n\n\n;Task:\n:* \u00a0 Generate and show all sets of numbers (below) on one line (horizontally) with a title, \u00a0 here on this page\n:* \u00a0 Show the first \u00a0 '''30''' \u00a0 gapful numbers\n:* \u00a0 Show the first \u00a0 '''15''' \u00a0 gapful numbers \u00a0 \u2265 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0'''1,000,000'''\n:* \u00a0 Show the first \u00a0 '''10''' \u00a0 gapful numbers \u00a0 \u2265 \u00a0 '''1,000,000,000'''\n\n\n;Related tasks:\n:* \u00a0 [https://rosettacode.org/wiki/Harshad_or_Niven_series Harshad or Niven series].\n:* \u00a0 [https://rosettacode.org/wiki/Palindromic_gapful_numbers palindromic gapful numbers].\n:* \u00a0 [https://rosettacode.org/wiki/Largest_number_divisible_by_its_digits largest number divisible by its digits].\n\n\n;Also see:\n:* \u00a0 The OEIS entry: \u00a0 [https://oeis.org/A108343 A108343 gapful numbers].\n:* \u00a0 numbersaplenty [http://www.numbersaplenty.com/set/gapful_number/ gapful numbers]\n\n", "solution": "\n#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\nOutput : \nFirst 30 Gapful numbers >= 100 :\n\n 1 : 100\n 2 : 105\n 3 : 108\n 4 : 110\n 5 : 120\n 6 : 121\n 7 : 130\n 8 : 132\n 9 : 135\n 10 : 140\n 11 : 143\n 12 : 150\n 13 : 154\n 14 : 160\n 15 : 165\n 16 : 170\n 17 : 176\n 18 : 180\n 19 : 187\n 20 : 190\n 21 : 192\n 22 : 195\n 23 : 198\n 24 : 200\n 25 : 220\n 26 : 225\n 27 : 231\n 28 : 240\n 29 : 242\n 30 : 253\n\nFirst 15 Gapful numbers >= 1000000 :\n\n 1 : 1000000\n 2 : 1000005\n 3 : 1000008\n 4 : 1000010\n 5 : 1000016\n 6 : 1000020\n 7 : 1000021\n 8 : 1000030\n 9 : 1000032\n 10 : 1000034\n 11 : 1000035\n 12 : 1000040\n 13 : 1000050\n 14 : 1000060\n 15 : 1000065\n\nFirst 15 Gapful numbers >= 1000000000 :\n\n 1 : 1000000000\n 2 : 1000000001\n 3 : 1000000005\n 4 : 1000000008\n 5 : 1000000010\n 6 : 1000000016\n 7 : 1000000020\n 8 : 1000000027\n 9 : 1000000030\n 10 : 1000000032\n 11 : 1000000035\n 12 : 1000000039\n 13 : 1000000040\n 14 : 1000000050\n 15 : 1000000053\n\n"} +{"title": "Gapful numbers", "language": "Windows Script Host", "task": "Numbers \u00a0 (positive integers expressed in base ten) \u00a0 that are (evenly) divisible by the number formed by the\nfirst and last digit are known as \u00a0 '''gapful numbers'''.\n\n\n''Evenly divisible'' \u00a0 means divisible with \u00a0 no \u00a0 remainder.\n\n\nAll \u00a0 one\u2500 \u00a0 and two\u2500digit \u00a0 numbers have this property and are trivially excluded. \u00a0 Only\nnumbers \u00a0 \u2265 '''100''' \u00a0 will be considered for this Rosetta Code task.\n\n\n;Example:\n'''187''' \u00a0 is a \u00a0 '''gapful''' \u00a0 number because it is evenly divisible by the\nnumber \u00a0 '''17''' \u00a0 which is formed by the first and last decimal digits\nof \u00a0 '''187'''. \n\n\nAbout \u00a0 7.46% \u00a0 of positive integers are \u00a0 ''gapful''. \n\n\n;Task:\n:* \u00a0 Generate and show all sets of numbers (below) on one line (horizontally) with a title, \u00a0 here on this page\n:* \u00a0 Show the first \u00a0 '''30''' \u00a0 gapful numbers\n:* \u00a0 Show the first \u00a0 '''15''' \u00a0 gapful numbers \u00a0 \u2265 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0'''1,000,000'''\n:* \u00a0 Show the first \u00a0 '''10''' \u00a0 gapful numbers \u00a0 \u2265 \u00a0 '''1,000,000,000'''\n\n\n;Related tasks:\n:* \u00a0 [https://rosettacode.org/wiki/Harshad_or_Niven_series Harshad or Niven series].\n:* \u00a0 [https://rosettacode.org/wiki/Palindromic_gapful_numbers palindromic gapful numbers].\n:* \u00a0 [https://rosettacode.org/wiki/Largest_number_divisible_by_its_digits largest number divisible by its digits].\n\n\n;Also see:\n:* \u00a0 The OEIS entry: \u00a0 [https://oeis.org/A108343 A108343 gapful numbers].\n:* \u00a0 numbersaplenty [http://www.numbersaplenty.com/set/gapful_number/ gapful numbers]\n\n", "solution": "// Function to construct a new integer from the first and last digits of another\nfunction gapfulness_divisor (number) {\n\tvar digit_string = number.toString(10)\n\tvar digit_count = digit_string.length\n\tvar first_digit = digit_string.substring(0, 1)\n\tvar last_digit = digit_string.substring(digit_count - 1)\n\treturn parseInt(first_digit.concat(last_digit), 10)\n}\n\n// Divisibility test to determine gapfulness\nfunction is_gapful (number) {\n\treturn number % gapfulness_divisor(number) == 0\n}\n\n// Function to search for the least gapful number greater than a given integer\nfunction next_gapful (number) {\n\tdo {\n\t\t++number\n\t} while (!is_gapful(number))\n\treturn number\n}\n\n// Constructor for a list of gapful numbers starting from given lower bound\nfunction gapful_numbers (start, amount) {\n\tvar list = [], count = 0, number = start\n\tif (amount > 0 && is_gapful(start)) {\n\t\tlist.push(start)\n\t}\n\twhile (list.length < amount) {\n\t\tnumber = next_gapful(number)\n\t\tlist.push(number)\n\t}\n\treturn list\n}\n\n// Formatter for a comma-separated list of gapful numbers\nfunction single_line_gapfuls (start, amount) {\n\tvar list = gapful_numbers(start, amount)\n\treturn list.join(\", \")\n}\n\n// Windows console output wrapper\nfunction print(message) {\n\tWScript.StdOut.WriteLine(message)\n}\n\n// Main algorithm\n\nfunction print_gapfuls_with_header(start, amount) {\n\tprint(\"First \" + start + \" gapful numbers starting at \" + amount)\n\tprint(single_line_gapfuls(start, amount))\n}\n\nprint_gapfuls_with_header(100, 30)\nprint_gapfuls_with_header(1000000, 15)\nprint_gapfuls_with_header(1000000000, 10)"} +{"title": "Gapful numbers", "language": "Python", "task": "Numbers \u00a0 (positive integers expressed in base ten) \u00a0 that are (evenly) divisible by the number formed by the\nfirst and last digit are known as \u00a0 '''gapful numbers'''.\n\n\n''Evenly divisible'' \u00a0 means divisible with \u00a0 no \u00a0 remainder.\n\n\nAll \u00a0 one\u2500 \u00a0 and two\u2500digit \u00a0 numbers have this property and are trivially excluded. \u00a0 Only\nnumbers \u00a0 \u2265 '''100''' \u00a0 will be considered for this Rosetta Code task.\n\n\n;Example:\n'''187''' \u00a0 is a \u00a0 '''gapful''' \u00a0 number because it is evenly divisible by the\nnumber \u00a0 '''17''' \u00a0 which is formed by the first and last decimal digits\nof \u00a0 '''187'''. \n\n\nAbout \u00a0 7.46% \u00a0 of positive integers are \u00a0 ''gapful''. \n\n\n;Task:\n:* \u00a0 Generate and show all sets of numbers (below) on one line (horizontally) with a title, \u00a0 here on this page\n:* \u00a0 Show the first \u00a0 '''30''' \u00a0 gapful numbers\n:* \u00a0 Show the first \u00a0 '''15''' \u00a0 gapful numbers \u00a0 \u2265 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0'''1,000,000'''\n:* \u00a0 Show the first \u00a0 '''10''' \u00a0 gapful numbers \u00a0 \u2265 \u00a0 '''1,000,000,000'''\n\n\n;Related tasks:\n:* \u00a0 [https://rosettacode.org/wiki/Harshad_or_Niven_series Harshad or Niven series].\n:* \u00a0 [https://rosettacode.org/wiki/Palindromic_gapful_numbers palindromic gapful numbers].\n:* \u00a0 [https://rosettacode.org/wiki/Largest_number_divisible_by_its_digits largest number divisible by its digits].\n\n\n;Also see:\n:* \u00a0 The OEIS entry: \u00a0 [https://oeis.org/A108343 A108343 gapful numbers].\n:* \u00a0 numbersaplenty [http://www.numbersaplenty.com/set/gapful_number/ gapful numbers]\n\n", "solution": "from itertools import islice, count\nfor start, n in [(100, 30), (1_000_000, 15), (1_000_000_000, 10)]:\n print(f\"\\nFirst {n} gapful numbers from {start:_}\")\n print(list(islice(( x for x in count(start) \n if (x % (int(str(x)[0]) * 10 + (x % 10)) == 0) )\n , n)))"} +{"title": "Gauss-Jordan matrix inversion", "language": "C", "task": ";Task:\nInvert matrix \u00a0 '''A''' \u00a0 using Gauss-Jordan method.\n\n'''A''' \u00a0 being an \u00a0 '''n''' \u00d7 '''n''' \u00a0 matrix.\n\n", "solution": "/*----------------------------------------------------------------------\ngjinv - Invert a matrix, Gauss-Jordan algorithm\nA is destroyed. Returns 1 for a singular matrix.\n\n___Name_____Type______In/Out____Description_____________________________\n a[n*n] double* In An N by N matrix\n n int In Order of matrix\n b[n*n] double* Out Inverse of A\n----------------------------------------------------------------------*/\n#include \nint gjinv (double *a, int n, double *b)\n{\n\tint i, j, k, p;\n\tdouble f, g, tol;\n\tif (n < 1) return -1; /* Function Body */\n\tf = 0.; /* Frobenius norm of a */\n\tfor (i = 0; i < n; ++i) {\n\t\tfor (j = 0; j < n; ++j) {\n\t\t\tg = a[j+i*n];\n\t\t\tf += g * g;\n\t\t}\n\t}\n\tf = sqrt(f);\n\ttol = f * 2.2204460492503131e-016;\n\tfor (i = 0; i < n; ++i) { /* Set b to identity matrix. */\n\t\tfor (j = 0; j < n; ++j) {\n\t\t\tb[j+i*n] = (i == j) ? 1. : 0.;\n\t\t}\n\t}\n\tfor (k = 0; k < n; ++k) { /* Main loop */\n\t\tf = fabs(a[k+k*n]); /* Find pivot. */\n\t\tp = k;\n\t\tfor (i = k+1; i < n; ++i) {\n\t\t\tg = fabs(a[k+i*n]);\n\t\t\tif (g > f) {\n\t\t\t\tf = g;\n\t\t\t\tp = i;\n\t\t\t}\n\t\t}\n\t\tif (f < tol) return 1; /* Matrix is singular. */\n\t\tif (p != k) { /* Swap rows. */\n\t\t\tfor (j = k; j < n; ++j) {\n\t\t\t\tf = a[j+k*n];\n\t\t\t\ta[j+k*n] = a[j+p*n];\n\t\t\t\ta[j+p*n] = f;\n\t\t\t}\n\t\t\tfor (j = 0; j < n; ++j) {\n\t\t\t\tf = b[j+k*n];\n\t\t\t\tb[j+k*n] = b[j+p*n];\n\t\t\t\tb[j+p*n] = f;\n\t\t\t}\n\t\t}\n\t\tf = 1. / a[k+k*n]; /* Scale row so pivot is 1. */\n\t\tfor (j = k; j < n; ++j) a[j+k*n] *= f;\n\t\tfor (j = 0; j < n; ++j) b[j+k*n] *= f;\n\t\tfor (i = 0; i < n; ++i) { /* Subtract to get zeros. */\n\t\t\tif (i == k) continue;\n\t\t\tf = a[k+i*n];\n\t\t\tfor (j = k; j < n; ++j) a[j+i*n] -= a[j+k*n] * f;\n\t\t\tfor (j = 0; j < n; ++j) b[j+i*n] -= b[j+k*n] * f;\n\t\t}\n\t}\n\treturn 0;\n} /* end of gjinv */"} +{"title": "Gauss-Jordan matrix inversion", "language": "Python", "task": ";Task:\nInvert matrix \u00a0 '''A''' \u00a0 using Gauss-Jordan method.\n\n'''A''' \u00a0 being an \u00a0 '''n''' \u00d7 '''n''' \u00a0 matrix.\n\n", "solution": "\nimport numpy as np\nfrom numpy.linalg import inv\na = np.array([[1., 2., 3.], [4., 1., 6.],[ 7., 8., 9.]])\nainv = inv(a)\n\nprint(a)\nprint(ainv)\n"} +{"title": "Gaussian elimination", "language": "C", "task": ";Task:\nSolve \u00a0 '''Ax=b''' \u00a0 using Gaussian elimination then backwards substitution. \n\n'''A''' \u00a0 being an \u00a0 '''n''' by '''n''' \u00a0 matrix. \n\nAlso, \u00a0 '''x''' and '''b''' \u00a0 are \u00a0 '''n''' by '''1''' \u00a0 vectors. \n\nTo improve accuracy, please use partial pivoting and scaling.\n\n\n;See also:\n:* \u00a0 the Wikipedia entry: \u00a0 Gaussian elimination\n\n", "solution": "#include \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": "Gaussian elimination", "language": "JavaScript", "task": ";Task:\nSolve \u00a0 '''Ax=b''' \u00a0 using Gaussian elimination then backwards substitution. \n\n'''A''' \u00a0 being an \u00a0 '''n''' by '''n''' \u00a0 matrix. \n\nAlso, \u00a0 '''x''' and '''b''' \u00a0 are \u00a0 '''n''' by '''1''' \u00a0 vectors. \n\nTo improve accuracy, please use partial pivoting and scaling.\n\n\n;See also:\n:* \u00a0 the Wikipedia entry: \u00a0 Gaussian elimination\n\n", "solution": "// Lower Upper Solver\nfunction lusolve(A, b, update) {\n\tvar lu = ludcmp(A, update)\n\tif (lu === undefined) return // Singular Matrix!\n\treturn lubksb(lu, b, update)\n}\n\n// Lower Upper Decomposition\nfunction ludcmp(A, update) {\n\t// A is a matrix that we want to decompose into Lower and Upper matrices.\n\tvar d = true\n\tvar n = A.length\n\tvar idx = new Array(n) // Output vector with row permutations from partial pivoting\n\tvar vv = new Array(n) // Scaling information\n\n\tfor (var i=0; i max) max = temp\n\t\t}\n\t\tif (max == 0) return // Singular Matrix!\n\t\tvv[i] = 1 / max // Scaling\n\t}\n\t\n\tif (!update) { // make a copy of A \n\t\tvar Acpy = new Array(n)\n\t\tfor (var i=0; i= max) {\n\t\t\t\tmax = temp\n\t\t\t\tjmax = j\n\t\t\t}\n\t\t}\n\t\tif (i <= jmax) {\n\t\t\tfor (var j=0; j -1)\n\t\t\tfor (var j=ii; j=0; i--) {\n\t\tvar sum = b[i]\n\t\tfor (var j=i+1; j\n"} +{"title": "Gaussian elimination", "language": "Python", "task": ";Task:\nSolve \u00a0 '''Ax=b''' \u00a0 using Gaussian elimination then backwards substitution. \n\n'''A''' \u00a0 being an \u00a0 '''n''' by '''n''' \u00a0 matrix. \n\nAlso, \u00a0 '''x''' and '''b''' \u00a0 are \u00a0 '''n''' by '''1''' \u00a0 vectors. \n\nTo improve accuracy, please use partial pivoting and scaling.\n\n\n;See also:\n:* \u00a0 the Wikipedia entry: \u00a0 Gaussian elimination\n\n", "solution": "# The 'gauss' function takes two matrices, 'a' and 'b', with 'a' square, and it return the determinant of 'a' and a matrix 'x' such that a*x = b.\n# If 'b' is the identity, then 'x' is the inverse of 'a'.\n\nimport copy\nfrom fractions import Fraction\n\ndef gauss(a, b):\n a = copy.deepcopy(a)\n b = copy.deepcopy(b)\n n = len(a)\n p = len(b[0])\n det = 1\n for i in range(n - 1):\n k = i\n for j in range(i + 1, n):\n if abs(a[j][i]) > abs(a[k][i]):\n k = j\n if k != i:\n a[i], a[k] = a[k], a[i]\n b[i], b[k] = b[k], b[i]\n det = -det\n \n for j in range(i + 1, n):\n t = a[j][i]/a[i][i]\n for k in range(i + 1, n):\n a[j][k] -= t*a[i][k]\n for k in range(p):\n b[j][k] -= t*b[i][k]\n \n for i in range(n - 1, -1, -1):\n for j in range(i + 1, n):\n t = a[i][j]\n for k in range(p):\n b[i][k] -= t*b[j][k]\n t = 1/a[i][i]\n det *= a[i][i]\n for j in range(p):\n b[i][j] *= t\n return det, b\n\ndef zeromat(p, q):\n return [[0]*q for i in range(p)]\n\ndef matmul(a, b):\n n, p = len(a), len(a[0])\n p1, q = len(b), len(b[0])\n if p != p1:\n raise ValueError(\"Incompatible dimensions\")\n c = zeromat(n, q)\n for i in range(n):\n for j in range(q):\n c[i][j] = sum(a[i][k]*b[k][j] for k in range(p))\n return c\n\n\ndef mapmat(f, a):\n return [list(map(f, v)) for v in a]\n\ndef ratmat(a):\n return mapmat(Fraction, a)\n\n# As an example, compute the determinant and inverse of 3x3 magic square\n\na = [[2, 9, 4], [7, 5, 3], [6, 1, 8]]\nb = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]\ndet, c = gauss(a, b)\n\ndet\n-360.0\n\nc\n[[-0.10277777777777776, 0.18888888888888888, -0.019444444444444438],\n[0.10555555555555554, 0.02222222222222223, -0.061111111111111116],\n[0.0638888888888889, -0.14444444444444446, 0.14722222222222223]]\n\n# Check product\nmatmul(a, c)\n[[1.0, 0.0, 0.0], [5.551115123125783e-17, 1.0, 0.0],\n[1.1102230246251565e-16, -2.220446049250313e-16, 1.0]]\n\n# Same with fractions, so the result is exact\n\ndet, c = gauss(ratmat(a), ratmat(b))\n\ndet\nFraction(-360, 1)\n\nc\n[[Fraction(-37, 360), Fraction(17, 90), Fraction(-7, 360)],\n[Fraction(19, 180), Fraction(1, 45), Fraction(-11, 180)],\n[Fraction(23, 360), Fraction(-13, 90), Fraction(53, 360)]]\n\nmatmul(a, c)\n[[Fraction(1, 1), Fraction(0, 1), Fraction(0, 1)],\n[Fraction(0, 1), Fraction(1, 1), Fraction(0, 1)],\n[Fraction(0, 1), Fraction(0, 1), Fraction(1, 1)]]"} +{"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: \u2654\u2655\u2656\u2657\u2658 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": "Generate Chess960 starting position", "language": "JavaScript", "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: \u2654\u2655\u2656\u2657\u2658 or with the letters '''K'''ing '''Q'''ueen '''R'''ook '''B'''ishop k'''N'''ight.\n\n", "solution": "function ch960startPos() {\n var rank = new Array(8),\n // randomizer (our die)\n d = function(num) { return Math.floor(Math.random() * ++num) },\n emptySquares = function() {\n var arr = [];\n for (var i = 0; i < 8; i++) if (rank[i] == undefined) arr.push(i);\n return arr;\n };\n // place one bishop on any black square\n rank[d(2) * 2] = \"\u2657\";\n // place the other bishop on any white square\n rank[d(2) * 2 + 1] = \"\u2657\";\n // place the queen on any empty square\n rank[emptySquares()[d(5)]] = \"\u2655\";\n // place one knight on any empty square\n rank[emptySquares()[d(4)]] = \"\u2658\";\n // place the other knight on any empty square\n rank[emptySquares()[d(3)]] = \"\u2658\";\n // place the rooks and the king on the squares left, king in the middle\n for (var x = 1; x <= 3; x++) rank[emptySquares()[0]] = x==2 ? \"\u2654\" : \"\u2656\";\n return rank;\n}\n\n// testing (10 times)\nfor (var x = 1; x <= 10; x++) console.log(ch960startPos().join(\" | \"));"} +{"title": "Generate Chess960 starting position", "language": "Python", "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: \u2654\u2655\u2656\u2657\u2658 or with the letters '''K'''ing '''Q'''ueen '''R'''ook '''B'''ishop k'''N'''ight.\n\n", "solution": "from random import choice\n\ndef random960():\n start = ['R', 'K', 'R'] # Subsequent order unchanged by insertions.\n #\n for piece in ['Q', 'N', 'N']:\n start.insert(choice(range(len(start)+1)), piece)\n #\n bishpos = choice(range(len(start)+1))\n start.insert(bishpos, 'B')\n start.insert(choice(range(bishpos + 1, len(start) + 1, 2)), 'B')\n return start\n return ''.join(start).upper()\n\nprint(random960())"} +{"title": "Generate random chess position", "language": "C", "task": ";Task: \nGenerate a random chess position in FEN format. \n\nThe position does not have to be realistic or even balanced,\u00a0 but it must comply to the following rules:\n:* there is one and only one king of each color \u00a0(one black king and one white king);\n:* the kings must not be placed on adjacent squares;\n:* there can not be any pawn in the promotion square \u00a0(no white pawn in the eighth rank, and no black pawn in the first rank);\n:* including the kings, up to 32 pieces of either color can be placed. \n:* There is no requirement for material balance between sides. \n:* The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two. \n:* it is white's turn.\n:* It's assumed that both sides have lost castling rights and that there is no possibility for \u00a0 ''en passant'' \u00a0 (the FEN should thus end in w - - 0 1).\n\n\nNo requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\n#define TRUE 1\n#define FALSE 0\n\ntypedef int bool;\n\nchar grid[8][8];\n\nvoid placeKings() {\n int r1, r2, c1, c2;\n for (;;) {\n r1 = rand() % 8;\n c1 = rand() % 8;\n r2 = rand() % 8;\n c2 = rand() % 8;\n if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1) {\n grid[r1][c1] = 'K';\n grid[r2][c2] = 'k';\n return;\n }\n }\n}\n\nvoid placePieces(const char *pieces, bool isPawn) {\n int n, r, c;\n int numToPlace = rand() % strlen(pieces);\n for (n = 0; n < numToPlace; ++n) {\n do {\n r = rand() % 8;\n c = rand() % 8;\n }\n while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0)));\n grid[r][c] = pieces[n];\n }\n}\n\nvoid toFen() {\n char fen[80], ch;\n int r, c, countEmpty = 0, index = 0;\n for (r = 0; r < 8; ++r) {\n for (c = 0; c < 8; ++c) {\n ch = grid[r][c];\n printf(\"%2c \", ch == 0 ? '.' : ch);\n if (ch == 0) {\n countEmpty++;\n }\n else {\n if (countEmpty > 0) {\n fen[index++] = countEmpty + 48;\n countEmpty = 0; \n }\n fen[index++] = ch;\n }\n }\n if (countEmpty > 0) {\n fen[index++] = countEmpty + 48;\n countEmpty = 0;\n }\n fen[index++]= '/';\n printf(\"\\n\");\n }\n strcpy(fen + index, \" w - - 0 1\");\n printf(\"%s\\n\", fen);\n}\n\nchar *createFen() {\n placeKings();\n placePieces(\"PPPPPPPP\", TRUE);\n placePieces(\"pppppppp\", TRUE);\n placePieces(\"RNBQBNR\", FALSE);\n placePieces(\"rnbqbnr\", FALSE);\n toFen();\n}\n\nint main() {\n srand(time(NULL));\n createFen();\n return 0;\n}"} +{"title": "Generate random chess position", "language": "JavaScript", "task": ";Task: \nGenerate a random chess position in FEN format. \n\nThe position does not have to be realistic or even balanced,\u00a0 but it must comply to the following rules:\n:* there is one and only one king of each color \u00a0(one black king and one white king);\n:* the kings must not be placed on adjacent squares;\n:* there can not be any pawn in the promotion square \u00a0(no white pawn in the eighth rank, and no black pawn in the first rank);\n:* including the kings, up to 32 pieces of either color can be placed. \n:* There is no requirement for material balance between sides. \n:* The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two. \n:* it is white's turn.\n:* It's assumed that both sides have lost castling rights and that there is no possibility for \u00a0 ''en passant'' \u00a0 (the FEN should thus end in w - - 0 1).\n\n\nNo requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.\n\n", "solution": "\nArray.prototype.shuffle = function() {\n for (let i = this.length - 1; i > 0; i--) {\n let j = Math.floor(Math.random() * (i + 1));\n [this[i], this[j]] = [this[j], this[i]];\n }\n}\n\nfunction randomFEN() {\n\n let board = [];\n for (let x = 0; x < 8; x++) board.push('. . . . . . . .'.split(' '));\n\n function getRandPos() {\n return [Math.floor(Math.random() * 8), Math.floor(Math.random() * 8)];\n }\n\n function isOccupied(pos) {\n return board[pos[0]][pos[1]] != '.';\n }\n\n function isAdjacent(pos1, pos2) {\n if (pos1[0] == pos2[0] || pos1[0] == pos2[0]-1 || pos1[0] == pos2[0]+1)\n if (pos1[1] == pos2[1] || pos1[1] == pos2[1]-1 || pos1[1] == pos2[1]+1)\n return true;\n return false;\n }\n\n // place kings\n let wk, bk;\n do { wk = getRandPos(); bk = getRandPos(); }\n while (isAdjacent(wk, bk));\n board[wk[0]][wk[1]] = 'K';\n board[bk[0]][bk[1]] = 'k';\n\n // get peaces\n let peaces = [];\n let names = 'PRNBQ';\n function pick() {\n for (x = 1; x < Math.floor(Math.random() * 32); x++)\n peaces.push(names[Math.floor(Math.random() * names.length)]);\n }\n pick();\n names = names.toLowerCase();\n pick();\n peaces.shuffle();\n\n // place peaces\n while (peaces.length > 0) {\n let p = peaces.shift(), pos;\n // paws: cannot be placed in bottom or top row\n if (p == 'p' || p == 'P')\n do { pos = getRandPos() }\n while (isOccupied(pos) || pos[0] == 0 || pos[0] == 7);\n // everything else\n else do { pos = getRandPos(); } while (isOccupied(pos));\n board[pos[0]][pos[1]] = p;\n }\n\n // write FEN\n let fen = [];\n for (x = 0; x < board.length; x++) {\n let str ='', buf = 0;\n for (let y = 0; y < board[x].length; y++)\n if (board[x][y] == '.') buf++;\n else {\n if (buf > 0) { str += buf; buf = 0; }\n str += board[x][y];\n }\n if (buf > 0) str += buf;\n fen.push(str);\n }\n fen = fen.join('/') + ' w - - 0 1';\n console.table(board); // for demonstrating purpose\n return fen;\n}\n\n// example\nconsole.log(randomFEN());\n"} +{"title": "Generate random chess position", "language": "Python", "task": ";Task: \nGenerate a random chess position in FEN format. \n\nThe position does not have to be realistic or even balanced,\u00a0 but it must comply to the following rules:\n:* there is one and only one king of each color \u00a0(one black king and one white king);\n:* the kings must not be placed on adjacent squares;\n:* there can not be any pawn in the promotion square \u00a0(no white pawn in the eighth rank, and no black pawn in the first rank);\n:* including the kings, up to 32 pieces of either color can be placed. \n:* There is no requirement for material balance between sides. \n:* The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two. \n:* it is white's turn.\n:* It's assumed that both sides have lost castling rights and that there is no possibility for \u00a0 ''en passant'' \u00a0 (the FEN should thus end in w - - 0 1).\n\n\nNo requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.\n\n", "solution": "\nimport random\n\nboard = [[\" \" for x in range(8)] for y in range(8)]\npiece_list = [\"R\", \"N\", \"B\", \"Q\", \"P\"]\n\n\ndef place_kings(brd):\n\twhile True:\n\t\trank_white, file_white, rank_black, file_black = random.randint(0,7), random.randint(0,7), random.randint(0,7), random.randint(0,7)\n\t\tdiff_list = [abs(rank_white - rank_black), abs(file_white - file_black)]\n\t\tif sum(diff_list) > 2 or set(diff_list) == set([0, 2]):\n\t\t\tbrd[rank_white][file_white], brd[rank_black][file_black] = \"K\", \"k\"\n\t\t\tbreak\n\ndef populate_board(brd, wp, bp):\n\tfor x in range(2):\n\t\tif x == 0:\n\t\t\tpiece_amount = wp\n\t\t\tpieces = piece_list\n\t\telse:\n\t\t\tpiece_amount = bp\n\t\t\tpieces = [s.lower() for s in piece_list]\n\t\twhile piece_amount != 0:\n\t\t\tpiece_rank, piece_file = random.randint(0, 7), random.randint(0, 7)\n\t\t\tpiece = random.choice(pieces)\n\t\t\tif brd[piece_rank][piece_file] == \" \" and pawn_on_promotion_square(piece, piece_rank) == False:\n\t\t\t\tbrd[piece_rank][piece_file] = piece\n\t\t\t\tpiece_amount -= 1\n\ndef fen_from_board(brd):\n\tfen = \"\"\n\tfor x in brd:\n\t\tn = 0\n\t\tfor y in x:\n\t\t\tif y == \" \":\n\t\t\t\tn += 1\n\t\t\telse:\n\t\t\t\tif n != 0:\n\t\t\t\t\tfen += str(n)\n\t\t\t\tfen += y\n\t\t\t\tn = 0\n\t\tif n != 0:\n\t\t\tfen += str(n)\n\t\tfen += \"/\" if fen.count(\"/\") < 7 else \"\"\n\tfen += \" w - - 0 1\\n\"\n\treturn fen\n\ndef pawn_on_promotion_square(pc, pr):\n\tif pc == \"P\" and pr == 0:\n\t\treturn True\n\telif pc == \"p\" and pr == 7:\n\t\treturn True\n\treturn False\n\n\ndef start():\n\tpiece_amount_white, piece_amount_black = random.randint(0, 15), random.randint(0, 15)\n\tplace_kings(board)\n\tpopulate_board(board, piece_amount_white, piece_amount_black)\n\tprint(fen_from_board(board))\n\tfor x in board:\n\t\tprint(x)\n\n#entry point\nstart()\n"} +{"title": "Generator/Exponential", "language": "C", "task": "[[Category:Non parametric generators]]\n[[Category:Stateful transactions]]\n\nA 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 \u201cnaturally\u201d. \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:::* \u00a0 Squares.\n:::* \u00a0 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": "Generator/Exponential", "language": "Firefox 3.6 using JavaScript 1.7 ", "task": "[[Category:Non parametric generators]]\n[[Category:Stateful transactions]]\n\nA 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 \u201cnaturally\u201d. \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:::* \u00a0 Squares.\n:::* \u00a0 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": "(() => {\n 'use strict';\n\n // main :: IO()\n const main = () => {\n\n // powers :: Gen [Int]\n const powers = n =>\n fmapGen(\n x => Math.pow(x, n),\n enumFrom(0)\n );\n\n // xs :: [Int]\n const xs = take(10, drop(20,\n differenceGen(\n powers(2),\n powers(3)\n )\n ));\n\n console.log(xs);\n // -> [529,576,625,676,784,841,900,961,1024,1089]\n };\n\n\n // GENERIC FUNCTIONS ----------------------------------\n\n // Just :: a -> Maybe a\n const Just = x => ({\n type: 'Maybe',\n Nothing: false,\n Just: x\n });\n\n // Nothing :: Maybe a\n const Nothing = () => ({\n type: 'Maybe',\n Nothing: true,\n });\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = (a, b) => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // differenceGen :: Gen [a] -> Gen [a] -> Gen [a]\n function* differenceGen(ga, gb) {\n // All values of generator stream a except any\n // already seen in generator stream b.\n const\n stream = zipGen(ga, gb),\n sb = new Set([]);\n let xy = take(1, stream);\n while (0 < xy.length) {\n const [x, y] = Array.from(xy[0]);\n sb.add(y);\n if (!sb.has(x)) yield x;\n xy = take(1, stream);\n }\n };\n\n // drop :: Int -> [a] -> [a]\n // drop :: Int -> Generator [a] -> Generator [a]\n // drop :: Int -> String -> String\n const drop = (n, xs) =>\n Infinity > length(xs) ? (\n xs.slice(n)\n ) : (take(n, xs), xs);\n\n // enumFrom :: Enum a => a -> [a]\n function* enumFrom(x) {\n let v = x;\n while (true) {\n yield v;\n v = 1 + v;\n }\n }\n\n // fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]\n function* fmapGen(f, gen) {\n let v = take(1, gen);\n while (0 < v.length) {\n yield(f(v[0]))\n v = take(1, gen)\n }\n }\n\n // fst :: (a, b) -> a\n const fst = tpl => tpl[0];\n\n // Returns Infinity over objects without finite length.\n // This enables zip and zipWith to choose the shorter\n // argument when one is non-finite, like cycle, repeat etc\n\n // length :: [a] -> Int\n const length = xs =>\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n // snd :: (a, b) -> b\n const snd = tpl => tpl[1];\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = (n, xs) =>\n 'GeneratorFunction' !== xs.constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // uncons :: [a] -> Maybe (a, [a])\n const uncons = xs => {\n const lng = length(xs);\n return (0 < lng) ? (\n lng < Infinity ? (\n Just(Tuple(xs[0], xs.slice(1))) // Finite list\n ) : (() => {\n const nxt = take(1, xs);\n return 0 < nxt.length ? (\n Just(Tuple(nxt[0], xs))\n ) : Nothing();\n })() // Lazy generator\n ) : Nothing();\n };\n\n // zipGen :: Gen [a] -> Gen [b] -> Gen [(a, b)]\n const zipGen = (ga, gb) => {\n function* go(ma, mb) {\n let\n a = ma,\n b = mb;\n while (!a.Nothing && !b.Nothing) {\n let\n ta = a.Just,\n tb = b.Just\n yield(Tuple(fst(ta), fst(tb)));\n a = uncons(snd(ta));\n b = uncons(snd(tb));\n }\n }\n return go(uncons(ga), uncons(gb));\n };\n\n // MAIN ---\n return main();\n})();"} +{"title": "Generator/Exponential", "language": "Python", "task": "[[Category:Non parametric generators]]\n[[Category:Stateful transactions]]\n\nA 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 \u201cnaturally\u201d. \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:::* \u00a0 Squares.\n:::* \u00a0 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": "In Python, any function that contains a yield statement becomes a generator. The standard libraries itertools module provides the following functions used in the solution: [http://docs.python.org/library/itertools.html#itertools.count count], that will count up from zero; and [http://docs.python.org/library/itertools.html#itertools.islice islice], which will take a slice from an iterator/generator.\n\n"} +{"title": "Generator/Exponential", "language": "Python 2.6+ and 3.x", "task": "[[Category:Non parametric generators]]\n[[Category:Stateful transactions]]\n\nA 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 \u201cnaturally\u201d. \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:::* \u00a0 Squares.\n:::* \u00a0 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": "from itertools import islice, count\n\ndef powers(m):\n for n in count():\n yield n ** m\n \ndef filtered(s1, s2):\n v, f = next(s1), next(s2)\n while True:\n if v > f:\n f = next(s2)\n continue\n elif v < f:\n yield v\n v = next(s1)\n\nsquares, cubes = powers(2), powers(3)\nf = filtered(squares, cubes)\nprint(list(islice(f, 20, 30)))"} +{"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": "\n#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": "Get system command output", "language": "Python", "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": ">>> import subprocess\n>>> returned_text = subprocess.check_output(\"dir\", shell=True, universal_newlines=True)\n>>> type(returned_text)\n\n>>> print(returned_text)\n Volume in drive C is Windows\n Volume Serial Number is 44X7-73CE\n\n Directory of C:\\Python33\n\n04/07/2013 06:40 .\n04/07/2013 06:40 ..\n27/05/2013 07:10 DLLs\n27/05/2013 07:10 Doc\n27/05/2013 07:10 include\n27/05/2013 07:10 Lib\n27/05/2013 07:10 libs\n16/05/2013 00:15 33,326 LICENSE.txt\n15/05/2013 22:49 214,554 NEWS.txt\n16/05/2013 00:03 26,624 python.exe\n16/05/2013 00:03 27,136 pythonw.exe\n15/05/2013 22:49 6,701 README.txt\n27/05/2013 07:10 tcl\n27/05/2013 07:10 Tools\n16/05/2013 00:02 43,008 w9xpopen.exe\n 6 File(s) 351,349 bytes\n 9 Dir(s) 46,326,947,840 bytes free\n\n>>> # Ref: https://docs.python.org/3/library/subprocess.html"} +{"title": "Giuga numbers", "language": "Python", "task": ";Definition\nA '''Giuga number''' is a composite number '''n''' which is such that each of its distinct prime factors\n'''f''' divide (n/f - 1) exactly.\n\nAll known Giuga numbers are even though it is not known for certain that there are no odd examples. \n\n;Example\n30 is a Giuga number because its distinct prime factors are 2, 3 and 5 and:\n* 30/2 - 1 = 14 is divisible by 2\n* 30/3 - 1 = 9 is divisible by 3\n* 30/5 - 1 = 5 is divisible by 5\n\n;Task\nDetermine and show here the first four Giuga numbers.\n\n;Stretch\nDetermine the fifth Giuga number and any more you have the patience for.\n\n;References\n\n* Wikipedia: Giuga number\n* OEIS:A007850 - Giuga numbers\n\n", "solution": "#!/usr/bin/python\n\nfrom math import sqrt\n\ndef isGiuga(m):\n n = m\n f = 2\n l = sqrt(n)\n while True:\n if n % f == 0:\n if ((m / f) - 1) % f != 0:\n return False\n n /= f\n if f > n:\n return True\n else:\n f += 1\n if f > l:\n return False\n\n\nif __name__ == '__main__':\n n = 3\n c = 0\n print(\"The first 4 Giuga numbers are: \")\n while c < 4:\n if isGiuga(n):\n c += 1\n print(n)\n n += 1"} +{"title": "Globally replace text in several files", "language": "C", "task": ";Task:\nReplace 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 \u00a0 \"'''Goodbye London!'''\" \u00a0 with \u00a0 \"'''Hello New York!'''\" \u00a0 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": "Globally replace text in several files", "language": "Python", "task": ";Task:\nReplace 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 \u00a0 \"'''Goodbye London!'''\" \u00a0 with \u00a0 \"'''Hello New York!'''\" \u00a0 for a list of files.\n\n", "solution": "import fileinput\n\nfor line in fileinput.input(inplace=True):\n print(line.replace('Goodbye London!', 'Hello New York!'), end='')\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": "Graph colouring", "language": "Python", "task": "A Graph is a collection of nodes\n(or vertices), connected by edges (or not).\nNodes directly connected by edges are called neighbours.\n\nIn our representation of graphs, nodes are numbered and edges are represented\nby the two node numbers connected by the edge separated by a dash.\nEdges define the nodes being connected. Only unconnected nodes ''need'' a separate\ndescription.\n\nFor example,\n0-1 1-2 2-0 3\nDescribes the following graph. Note that node 3 has no neighbours\n\n\n;Example graph:\n\n+---+\n| 3 |\n+---+\n\n +-------------------+\n | |\n+---+ +---+ +---+\n| 0 | --- | 1 | --- | 2 |\n+---+ +---+ +---+\n\n\nA useful internal datastructure for a graph and for later graph algorithms is\nas a mapping between each node and the set/list of its neighbours.\n\nIn the above example:\n0 maps-to 1 and 2\n1 maps to 2 and 0\n2 maps-to 1 and 0\n3 maps-to \n\n;Graph colouring task:\nColour the vertices of a given graph so that no edge is between verticies of\nthe same colour.\n\n* Integers may be used to denote different colours.\n* Algorithm should do better than just assigning each vertex a separate colour. The idea is to minimise the number of colours used, although no algorithm short of exhaustive search for the minimum is known at present, (and exhaustive search is '''not''' a requirement).\n* Show for each edge, the colours assigned on each vertex.\n* Show the total number of nodes, edges, and colours used for each graph.\n\n;Use the following graphs:\n;Ex1:\n\n 0-1 1-2 2-0 3\n\n\n+---+\n| 3 |\n+---+\n\n +-------------------+\n | |\n+---+ +---+ +---+\n| 0 | --- | 1 | --- | 2 |\n+---+ +---+ +---+\n\n;Ex2:\nThe wp articles left-side graph\n\n 1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7\n\n\n\n +----------------------------------+\n | |\n | +---+ |\n | +-----------------| 3 | ------+----+\n | | +---+ | |\n | | | | |\n | | | | |\n | | | | |\n | +---+ +---+ +---+ +---+ |\n | | 8 | --- | 1 | --- | 6 | --- | 4 | |\n | +---+ +---+ +---+ +---+ |\n | | | | |\n | | | | |\n | | | | |\n | | +---+ +---+ +---+ |\n +----+------ | 7 | --- | 2 | --- | 5 | -+\n | +---+ +---+ +---+\n | |\n +-------------------+\n\n;Ex3:\nThe wp articles right-side graph which is the same graph as Ex2, but with\ndifferent node orderings and namings.\n\n 1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6\n\n\n\n +----------------------------------+\n | |\n | +---+ |\n | +-----------------| 5 | ------+----+\n | | +---+ | |\n | | | | |\n | | | | |\n | | | | |\n | +---+ +---+ +---+ +---+ |\n | | 8 | --- | 1 | --- | 4 | --- | 7 | |\n | +---+ +---+ +---+ +---+ |\n | | | | |\n | | | | |\n | | | | |\n | | +---+ +---+ +---+ |\n +----+------ | 6 | --- | 3 | --- | 2 | -+\n | +---+ +---+ +---+\n | |\n +-------------------+\n\n;Ex4:\nThis is the same graph, node naming, and edge order as Ex2 except some of the edges x-y are flipped to y-x.\nThis might alter the node order used in the greedy algorithm leading to differing numbers of colours.\n\n 1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7\n\n\n\n +-------------------------------------------------+\n | |\n | |\n +-------------------+---------+ |\n | | | |\n+---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+\n| 4 | --- | 5 | --- | 2 | --- | 7 | --- | 1 | --- | 6 | --- | 3 | --- | 8 |\n+---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+\n | | | | | |\n +---------+-----------------------------+---------+ | |\n | | | |\n | | | |\n +-----------------------------+-------------------+ |\n | |\n | |\n +-----------------------------+\n\n\n;References:\n* Greedy coloring Wikipedia.\n* [https://www.slideshare.net/PriyankJain26/graph-coloring-48222920 Graph Coloring : Greedy Algorithm & Welsh Powell Algorithm] by Priyank Jain.\n\n\n", "solution": "import re\nfrom collections import defaultdict\nfrom itertools import count\n\n\nconnection_re = r\"\"\"\n (?: (?P\\d+) - (?P\\d+) | (?P\\d+) (?!\\s*-))\n \"\"\"\n\nclass Graph:\n\n def __init__(self, name, connections):\n self.name = name\n self.connections = connections\n g = self.graph = defaultdict(list) # maps vertex to direct connections\n\n matches = re.finditer(connection_re, connections,\n re.MULTILINE | re.VERBOSE)\n for match in matches:\n n1, n2, n = match.groups()\n if n:\n g[n] += []\n else:\n g[n1].append(n2) # Each the neighbour of the other\n g[n2].append(n1)\n\n def greedy_colour(self, order=None):\n \"Greedy colourisation algo.\"\n if order is None:\n order = self.graph # Choose something\n colour = self.colour = {}\n neighbours = self.graph\n for node in order:\n used_neighbour_colours = (colour[nbr] for nbr in neighbours[node]\n if nbr in colour)\n colour[node] = first_avail_int(used_neighbour_colours)\n self.pp_colours()\n return colour\n\n def pp_colours(self):\n print(f\"\\n{self.name}\")\n c = self.colour\n e = canonical_edges = set()\n for n1, neighbours in sorted(self.graph.items()):\n if neighbours:\n for n2 in neighbours:\n edge = tuple(sorted([n1, n2]))\n if edge not in canonical_edges:\n print(f\" {n1}-{n2}: Colour: {c[n1]}, {c[n2]}\")\n canonical_edges.add(edge)\n else:\n print(f\" {n1}: Colour: {c[n1]}\")\n lc = len(set(c.values()))\n print(f\" #Nodes: {len(c)}\\n #Edges: {len(e)}\\n #Colours: {lc}\")\n\n\ndef first_avail_int(data):\n \"return lowest int 0... not in data\"\n d = set(data)\n for i in count():\n if i not in d:\n return i\n\n\nif __name__ == '__main__':\n for name, connections in [\n ('Ex1', \"0-1 1-2 2-0 3\"),\n ('Ex2', \"1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7\"),\n ('Ex3', \"1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6\"),\n ('Ex4', \"1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7\"),\n ]:\n g = Graph(name, connections)\n g.greedy_colour()"} +{"title": "Gray code", "language": "C", "task": "Create functions to encode a number to and decode a number from Gray code. \n\nDisplay the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).\n\nThere are many possible Gray codes. The following encodes what is called \"binary reflected Gray code.\"\n\nEncoding (MSB is bit 0, b is binary, g is Gray code):\n\nif b[i-1] = 1\n g[i] = not b[i]\nelse\n g[i] = b[i]\n\nOr:\n\ng = b xor (b logically right shifted 1 time)\n\nDecoding (MSB is bit 0, b is binary, g is Gray code):\n\nb[0] = g[0]\n\nfor other bits:\nb[i] = g[i] xor b[i-1]\n\n;Reference\n* [http://www.wisc-online.com/Objects/ViewObject.aspx?ID=IAU8307 Converting Between Gray and Binary Codes]. It includes step-by-step animations.\n\n", "solution": "#include \n\n/* Simple bool formatter, only good on range 0..31 */\nvoid fmtbool(int n, char *buf) {\n char *b = buf + 5;\n *b=0;\n do {\n\t*--b = '0' + (n & 1);\n\tn >>= 1;\n } while (b != buf);\n}\n\nint main(int argc, char **argv) {\n int i,g,b;\n char bi[6],bg[6],bb[6];\n\n for (i=0 ; i<32 ; i++) {\n\tg = gray_encode(i);\n\tb = gray_decode(g);\n\tfmtbool(i,bi); fmtbool(g,bg); fmtbool(b,bb);\n\tprintf(\"%2d : %5s => %5s => %5s : %2d\\n\", i, bi, bg, bb, b);\n }\n return 0;\n}"} +{"title": "Gray code", "language": "Python", "task": "Create functions to encode a number to and decode a number from Gray code. \n\nDisplay the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).\n\nThere are many possible Gray codes. The following encodes what is called \"binary reflected Gray code.\"\n\nEncoding (MSB is bit 0, b is binary, g is Gray code):\n\nif b[i-1] = 1\n g[i] = not b[i]\nelse\n g[i] = b[i]\n\nOr:\n\ng = b xor (b logically right shifted 1 time)\n\nDecoding (MSB is bit 0, b is binary, g is Gray code):\n\nb[0] = g[0]\n\nfor other bits:\nb[i] = g[i] xor b[i-1]\n\n;Reference\n* [http://www.wisc-online.com/Objects/ViewObject.aspx?ID=IAU8307 Converting Between Gray and Binary Codes]. It includes step-by-step animations.\n\n", "solution": "def gray_encode(n):\n return n ^ n >> 1\n\ndef gray_decode(n):\n m = n >> 1\n while m:\n n ^= m\n m >>= 1\n return n\n\n\nif __name__ == '__main__':\n print(\"DEC, BIN => GRAY => DEC\")\n for i in range(32):\n gray = gray_encode(i)\n dec = gray_decode(gray)\n print(f\" {i:>2d}, {i:>05b} => {gray:>05b} => {dec:>2d}\")"} +{"title": "Greatest subsequential sum", "language": "C", "task": "[[Category:Arithmetic operations]]\n\n;Task:\nGiven 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 \u00a0 '''0'''; \u00a0 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": "Greatest subsequential sum", "language": "JavaScript", "task": "[[Category:Arithmetic operations]]\n\n;Task:\nGiven 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 \u00a0 '''0'''; \u00a0 thus if all elements are negative, the result must be the empty sequence.\n\n", "solution": "(() => {\n\n // maxSubseq :: [Int] -> (Int, [Int])\n const maxSubseq = xs =>\n snd(xs.reduce((tpl, x) => {\n const [m1, m2] = Array.from(fst(tpl)),\n high = max(\n Tuple(0, []),\n Tuple(m1 + x, m2.concat(x))\n );\n return Tuple(high, max(snd(tpl), high));\n }, Tuple(Tuple(0, []), Tuple(0, []))));\n\n\n // TEST -----------------------------------------------\n // main :: IO ()\n const main = () => {\n const mx = maxSubseq([-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]);\n showLog(snd(mx), fst(mx))\n }\n // [3,5,6,-2,-1,4] -> 15\n\n\n // GENERIC FUNCTIONS ----------------------------------\n\n // fst :: (a, b) -> a\n const fst = tpl => tpl[0];\n\n // gt :: Ord a => a -> a -> Bool\n const gt = (x, y) =>\n 'Tuple' === x.type ? (\n x[0] > y[0]\n ) : (x > y);\n\n // max :: Ord a => a -> a -> a\n const max = (a, b) => gt(b, a) ? b : a;\n\n // showLog :: a -> IO ()\n const showLog = (...args) =>\n console.log(\n args\n .map(JSON.stringify)\n .join(' -> ')\n );\n\n // snd :: (a, b) -> b\n const snd = tpl => tpl[1];\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = (a, b) => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // MAIN ---\n return main();\n})();"} +{"title": "Greatest subsequential sum", "language": "Python", "task": "[[Category:Arithmetic operations]]\n\n;Task:\nGiven 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 \u00a0 '''0'''; \u00a0 thus if all elements are negative, the result must be the empty sequence.\n\n", "solution": "f = maxsumit\nassert f([]) == []\nassert f([-1]) == []\nassert f([0]) == []\nassert f([1]) == [1]\nassert f([1, 0]) == [1]\nassert f([0, 1]) == [0, 1] \nassert f([0, 1, 0]) == [0, 1] \nassert f([2]) == [2]\nassert f([2, -1]) == [2]\nassert f([-1, 2]) == [2]\nassert f([-1, 2, -1]) == [2]\nassert f([2, -1, 3]) == [2, -1, 3]\nassert f([2, -1, 3, -1]) == [2, -1, 3] \nassert f([-1, 2, -1, 3]) == [2, -1, 3]\nassert f([-1, 2, -1, 3, -1]) == [2, -1, 3]\nassert f([-1, 1, 2, -5, -6]) == [1,2]"} +{"title": "Greatest subsequential sum", "language": "Python 3.7", "task": "[[Category:Arithmetic operations]]\n\n;Task:\nGiven 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 \u00a0 '''0'''; \u00a0 thus if all elements are negative, the result must be the empty sequence.\n\n", "solution": "'''Greatest subsequential sum'''\n\nfrom functools import (reduce)\n\n\n# maxSubseq :: [Int] -> [Int] -> (Int, [Int])\ndef maxSubseq(xs):\n '''Subsequence of xs with the maximum sum'''\n def go(ab, x):\n (m1, m2) = ab[0]\n hi = max((0, []), (m1 + x, m2 + [x]))\n return (hi, max(ab[1], hi))\n return reduce(go, xs, ((0, []), (0, [])))[1]\n\n\n# TEST -----------------------------------------------------------\nprint(\n maxSubseq(\n [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]\n )\n)"} +{"title": "Greedy algorithm for Egyptian fractions", "language": "C", "task": "An \u00a0 Egyptian fraction \u00a0 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 \u00a0 '''1''' \u00a0 (unity) \u00a0 and a denominator that is a positive integer, \u00a0 and all the denominators are distinct \u00a0 (i.e., no repetitions). \n\nFibonacci's \u00a0 Greedy algorithm for Egyptian fractions \u00a0 expands the fraction \u00a0 \\tfrac{x}{y} \u00a0 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 \u00a0 \\lceil x \\rceil \u00a0 is the \u00a0 ''ceiling'' \u00a0 function).\n\n\n\nFor this task, \u00a0 Proper and improper fractions \u00a0 must be able to be expressed.\n\n\nProper \u00a0fractions \u00a0 are of the form \u00a0 \\tfrac{a}{b} \u00a0 where \u00a0 a \u00a0 and \u00a0 b \u00a0 are positive integers, such that \u00a0 a < b, \u00a0 \u00a0 and \n\nimproper fractions are of the form \u00a0 \\tfrac{a}{b} \u00a0 where \u00a0 a \u00a0 and \u00a0 b \u00a0 are positive integers, such that \u00a0 ''a'' \u2265 ''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* \u00a0 show the Egyptian fractions for: \\tfrac{43}{48} and \\tfrac{5}{121} and \\tfrac{2014}{59} \n* \u00a0 for all proper fractions, \u00a0 \\tfrac{a}{b} \u00a0 where \u00a0 a \u00a0 and \u00a0 b \u00a0 are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:\n::* \u00a0 the largest number of terms,\n::* \u00a0 the largest denominator.\n* \u00a0 for all one-, two-, and three-digit integers, \u00a0 find and show (as above). \u00a0 \u00a0 {extra credit}\n\n\n;Also see:\n* \u00a0 Wolfram MathWorld\u2122 entry: [http://mathworld.wolfram.com/EgyptianFraction.html 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": "Greedy algorithm for Egyptian fractions", "language": "Python", "task": "An \u00a0 Egyptian fraction \u00a0 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 \u00a0 '''1''' \u00a0 (unity) \u00a0 and a denominator that is a positive integer, \u00a0 and all the denominators are distinct \u00a0 (i.e., no repetitions). \n\nFibonacci's \u00a0 Greedy algorithm for Egyptian fractions \u00a0 expands the fraction \u00a0 \\tfrac{x}{y} \u00a0 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 \u00a0 \\lceil x \\rceil \u00a0 is the \u00a0 ''ceiling'' \u00a0 function).\n\n\n\nFor this task, \u00a0 Proper and improper fractions \u00a0 must be able to be expressed.\n\n\nProper \u00a0fractions \u00a0 are of the form \u00a0 \\tfrac{a}{b} \u00a0 where \u00a0 a \u00a0 and \u00a0 b \u00a0 are positive integers, such that \u00a0 a < b, \u00a0 \u00a0 and \n\nimproper fractions are of the form \u00a0 \\tfrac{a}{b} \u00a0 where \u00a0 a \u00a0 and \u00a0 b \u00a0 are positive integers, such that \u00a0 ''a'' \u2265 ''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* \u00a0 show the Egyptian fractions for: \\tfrac{43}{48} and \\tfrac{5}{121} and \\tfrac{2014}{59} \n* \u00a0 for all proper fractions, \u00a0 \\tfrac{a}{b} \u00a0 where \u00a0 a \u00a0 and \u00a0 b \u00a0 are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:\n::* \u00a0 the largest number of terms,\n::* \u00a0 the largest denominator.\n* \u00a0 for all one-, two-, and three-digit integers, \u00a0 find and show (as above). \u00a0 \u00a0 {extra credit}\n\n\n;Also see:\n* \u00a0 Wolfram MathWorld\u2122 entry: [http://mathworld.wolfram.com/EgyptianFraction.html Egyptian fraction]\n\n", "solution": "from fractions import Fraction\nfrom math import ceil\n\nclass Fr(Fraction):\n def __repr__(self):\n return '%s/%s' % (self.numerator, self.denominator)\n\ndef ef(fr):\n ans = []\n if fr >= 1:\n if fr.denominator == 1:\n return [[int(fr)], Fr(0, 1)]\n intfr = int(fr)\n ans, fr = [[intfr]], fr - intfr\n x, y = fr.numerator, fr.denominator\n while x != 1:\n ans.append(Fr(1, ceil(1/fr)))\n fr = Fr(-y % x, y* ceil(1/fr))\n x, y = fr.numerator, fr.denominator\n ans.append(fr)\n return ans\n\nif __name__ == '__main__':\n for fr in [Fr(43, 48), Fr(5, 121), Fr(2014, 59)]:\n print('%r \u2500\u25ba %s' % (fr, ' '.join(str(x) for x in ef(fr))))\n lenmax = denommax = (0, None) \n for fr in set(Fr(a, b) for a in range(1,100) for b in range(1, 100)):\n e = ef(fr)\n #assert sum((f[0] if type(f) is list else f) for f in e) == fr, 'Whoops!'\n elen, edenom = len(e), e[-1].denominator\n if elen > lenmax[0]:\n lenmax = (elen, fr, e)\n if edenom > denommax[0]:\n denommax = (edenom, fr, e)\n print('Term max is %r with %i terms' % (lenmax[1], lenmax[0]))\n dstr = str(denommax[0])\n print('Denominator max is %r with %i digits %s...%s' %\n (denommax[1], len(dstr), dstr[:5], dstr[-5:]))"} +{"title": "Greyscale bars/Display", "language": "C", "task": "The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. \n\nFor the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars)\n\nFor the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars).\n\nHalfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.\n\n", "solution": "#include \n/* do some greyscale plotting */\nvoid gsplot (cairo_t *cr,int x,int y,double s) {\n cairo_set_source_rgb (cr,s,s,s);\n cairo_move_to (cr,x+0.5,y);\n cairo_rel_line_to (cr,0,1);\n cairo_stroke (cr);\n}\n/* make a shaded widget */\ngboolean expose_event (GtkWidget *widget,GdkEventExpose *event,gpointer data) {\n int r,c,x=0;\n cairo_t *cr;\n cr = gdk_cairo_create (widget->window);\n cairo_scale (cr,5,50);\n cairo_set_line_width (cr,1);\n for (r=0;r<4;r++) {\n c = (r&1)*64-(r%2);\n do gsplot (cr,x++%64,r,c/(1<<(3-r))/(8*(1<\n"} +{"title": "Greyscale bars/Display", "language": "Python", "task": "The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. \n\nFor the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars)\n\nFor the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars).\n\nHalfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.\n\n", "solution": "#!/usr/bin/env python\n#four gray scaled stripes 8:16:32:64 in Python 2.7.1\n\nfrom livewires import *\n\nhoriz=640; vert=480; pruh=vert/4; dpp=255.0\nbegin_graphics(width=horiz,height=vert,title=\"Gray stripes\",background=Colour.black)\n\ndef ty_pruhy(each):\n\thiy=each[0]*pruh; loy=hiy-pruh\n\tkrok=horiz/each[1]; piecol=255.0/(each[1]-1)\n\tfor x in xrange(0,each[1]):\n\t\tbarva=Colour(piecol*x/dpp,piecol*x/dpp,piecol*x/dpp ); set_colour(barva)\n\t\tif each[2]:\n\t\t\tbox(x*krok,hiy,x*krok+krok,loy,filled=1)\n\t\telse:\n\t\t\tbox(horiz-x*krok,hiy,horiz-((x+1)*krok),loy,filled=1)\n\n# main\nsource=[[4,8,True],[3,16,False],[2,32,True],[1,64,False]]\nfor each in source:\n\tty_pruhy(each)\n\nwhile keys_pressed() != [' ']: # press spacebar to close window\n\tpass\n"} +{"title": "Hailstone sequence", "language": "C", "task": "The Hailstone sequence of numbers can be generated from a starting positive integer, \u00a0 n \u00a0 by:\n* \u00a0 If \u00a0 n \u00a0 is \u00a0 \u00a0 '''1''' \u00a0 \u00a0 then the sequence ends.\n* \u00a0 If \u00a0 n \u00a0 is \u00a0 '''even''' then the next \u00a0 n \u00a0 of the sequence \u00a0 = n/2 \n* \u00a0 If \u00a0 n \u00a0 is \u00a0 '''odd''' \u00a0 then the next \u00a0 n \u00a0 of the sequence \u00a0 = (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 \u00a0 (or possibly in 1939), \u00a0 and is also known as (the):\n:::* \u00a0 hailstone sequence, \u00a0 hailstone numbers\n:::* \u00a0 3x + 2 mapping, \u00a0 3n + 1 problem\n:::* \u00a0 Collatz sequence\n:::* \u00a0 Hasse's algorithm\n:::* \u00a0 Kakutani's problem\n:::* \u00a0 Syracuse algorithm, \u00a0 Syracuse problem\n:::* \u00a0 Thwaites conjecture \n:::* \u00a0 Ulam's problem\n\n\nThe hailstone sequence is also known as \u00a0 ''hailstone numbers'' \u00a0 (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. \u00a0 (But don't show the actual sequence!)\n\n\n;See also:\n* \u00a0 [http://xkcd.com/710 xkcd] (humourous).\n* \u00a0 [https://terrytao.files.wordpress.com/2020/02/collatz.pdf The Notorious Collatz conjecture] Terence Tao, UCLA (Presentation, pdf).\n* \u00a0 [https://www.youtube.com/watch?v=094y1Z2wpJg 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": "Hailstone sequence", "language": "JavaScript", "task": "The Hailstone sequence of numbers can be generated from a starting positive integer, \u00a0 n \u00a0 by:\n* \u00a0 If \u00a0 n \u00a0 is \u00a0 \u00a0 '''1''' \u00a0 \u00a0 then the sequence ends.\n* \u00a0 If \u00a0 n \u00a0 is \u00a0 '''even''' then the next \u00a0 n \u00a0 of the sequence \u00a0 = n/2 \n* \u00a0 If \u00a0 n \u00a0 is \u00a0 '''odd''' \u00a0 then the next \u00a0 n \u00a0 of the sequence \u00a0 = (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 \u00a0 (or possibly in 1939), \u00a0 and is also known as (the):\n:::* \u00a0 hailstone sequence, \u00a0 hailstone numbers\n:::* \u00a0 3x + 2 mapping, \u00a0 3n + 1 problem\n:::* \u00a0 Collatz sequence\n:::* \u00a0 Hasse's algorithm\n:::* \u00a0 Kakutani's problem\n:::* \u00a0 Syracuse algorithm, \u00a0 Syracuse problem\n:::* \u00a0 Thwaites conjecture \n:::* \u00a0 Ulam's problem\n\n\nThe hailstone sequence is also known as \u00a0 ''hailstone numbers'' \u00a0 (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. \u00a0 (But don't show the actual sequence!)\n\n\n;See also:\n* \u00a0 [http://xkcd.com/710 xkcd] (humourous).\n* \u00a0 [https://terrytao.files.wordpress.com/2020/02/collatz.pdf The Notorious Collatz conjecture] Terence Tao, UCLA (Presentation, pdf).\n* \u00a0 [https://www.youtube.com/watch?v=094y1Z2wpJg The Simplest Math Problem No One Can Solve] Veritasium (video, sponsored).\n\n", "solution": "function hailstone (n) {\n var seq = [n];\n while (n > 1) {\n n = n % 2 ? 3 * n + 1 : n / 2;\n seq.push(n);\n }\n return seq;\n}\n\n// task 2: verify the sequence for n = 27\nvar h = hailstone(27), hLen = h.length;\nprint(\"sequence 27 is (\" + h.slice(0, 4).join(\", \") + \" ... \"\n + h.slice(hLen - 4, hLen).join(\", \") + \"). length: \" + hLen);\n\n// task 3: find the longest sequence for n < 100000\nfor (var n, max = 0, i = 100000; --i;) {\n var seq = hailstone(i), sLen = seq.length;\n if (sLen > max) {\n n = i;\n max = sLen;\n }\n}\nprint(\"longest sequence: \" + max + \" numbers for starting point \" + n);"} +{"title": "Hailstone sequence", "language": "Python", "task": "The Hailstone sequence of numbers can be generated from a starting positive integer, \u00a0 n \u00a0 by:\n* \u00a0 If \u00a0 n \u00a0 is \u00a0 \u00a0 '''1''' \u00a0 \u00a0 then the sequence ends.\n* \u00a0 If \u00a0 n \u00a0 is \u00a0 '''even''' then the next \u00a0 n \u00a0 of the sequence \u00a0 = n/2 \n* \u00a0 If \u00a0 n \u00a0 is \u00a0 '''odd''' \u00a0 then the next \u00a0 n \u00a0 of the sequence \u00a0 = (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 \u00a0 (or possibly in 1939), \u00a0 and is also known as (the):\n:::* \u00a0 hailstone sequence, \u00a0 hailstone numbers\n:::* \u00a0 3x + 2 mapping, \u00a0 3n + 1 problem\n:::* \u00a0 Collatz sequence\n:::* \u00a0 Hasse's algorithm\n:::* \u00a0 Kakutani's problem\n:::* \u00a0 Syracuse algorithm, \u00a0 Syracuse problem\n:::* \u00a0 Thwaites conjecture \n:::* \u00a0 Ulam's problem\n\n\nThe hailstone sequence is also known as \u00a0 ''hailstone numbers'' \u00a0 (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. \u00a0 (But don't show the actual sequence!)\n\n\n;See also:\n* \u00a0 [http://xkcd.com/710 xkcd] (humourous).\n* \u00a0 [https://terrytao.files.wordpress.com/2020/02/collatz.pdf The Notorious Collatz conjecture] Terence Tao, UCLA (Presentation, pdf).\n* \u00a0 [https://www.youtube.com/watch?v=094y1Z2wpJg The Simplest Math Problem No One Can Solve] Veritasium (video, sponsored).\n\n", "solution": "def hailstone(n):\n seq = [n]\n while n > 1:\n n = 3 * n + 1 if n & 1 else n // 2\n seq.append(n)\n return seq\n\n\nif __name__ == '__main__':\n h = hailstone(27)\n assert (len(h) == 112\n and h[:4] == [27, 82, 41, 124]\n and h[-4:] == [8, 4, 2, 1])\n max_length, n = max((len(hailstone(i)), i) for i in range(1, 100_000))\n print(f\"Maximum length {max_length} was found for hailstone({n}) \"\n f\"for numbers <100,000\")"} +{"title": "Harmonic series", "language": "Python", "task": "In mathematics, the '''n-th''' harmonic number is the sum of the reciprocals of the first '''n''' natural numbers: \n\n\n'''H''n'' = 1 + 1/2 + 1/3 + ... + 1/n'''\n\nThe series of harmonic numbers thus obtained is often loosely referred to as the harmonic series. \n\nHarmonic numbers are closely related to the Euler\u2013Mascheroni constant.\n\nThe harmonic series is divergent, albeit quite slowly, and grows toward infinity.\n\n\n;Task\n* Write a function (routine, procedure, whatever it may be called in your language) to generate harmonic numbers.\n* Use that procedure to show the values of the first 20 harmonic numbers.\n* Find and show the position in the series of the first value greater than the integers 1 through 5\n\n\n;Stretch\n* Find and show the position in the series of the first value greater than the integers 6 through 10\n\n\n;Related\n* [[Egyptian fractions]]\n\n\n", "solution": "from fractions import Fraction\n\ndef harmonic_series():\n n, h = Fraction(1), Fraction(1)\n while True:\n yield h\n h += 1 / (n + 1)\n n += 1\n\nif __name__ == '__main__':\n from itertools import islice\n for n, d in (h.as_integer_ratio() for h in islice(harmonic_series(), 20)):\n print(n, '/', d)"} +{"title": "Harshad or Niven series", "language": "C", "task": "The [http://mathworld.wolfram.com/HarshadNumber.html Harshad] or Niven numbers are positive integers \u2265 1 that are divisible by the sum of their digits. \n\nFor example, \u00a0 '''42''' \u00a0 is a Harshad number as \u00a0 '''42''' \u00a0 is divisible by \u00a0 ('''4''' + '''2''') \u00a0 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::* \u00a0 list the first '''20''' members of the sequence, \u00a0 and\n::* \u00a0 list the first Harshad number greater than '''1000'''.\n\n\nShow your output here.\n\n\n;Related task\n:* \u00a0 [https://rosettacode.org/wiki/Increasing_gaps_between_consecutive_Niven_numbers Increasing gaps between consecutive Niven numbers]\n\n\n;See also\n* \u00a0 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": "Harshad or Niven series", "language": "JavaScript", "task": "The [http://mathworld.wolfram.com/HarshadNumber.html Harshad] or Niven numbers are positive integers \u2265 1 that are divisible by the sum of their digits. \n\nFor example, \u00a0 '''42''' \u00a0 is a Harshad number as \u00a0 '''42''' \u00a0 is divisible by \u00a0 ('''4''' + '''2''') \u00a0 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::* \u00a0 list the first '''20''' members of the sequence, \u00a0 and\n::* \u00a0 list the first Harshad number greater than '''1000'''.\n\n\nShow your output here.\n\n\n;Related task\n:* \u00a0 [https://rosettacode.org/wiki/Increasing_gaps_between_consecutive_Niven_numbers Increasing gaps between consecutive Niven numbers]\n\n\n;See also\n* \u00a0 OEIS: A005349\n\n", "solution": "function isHarshad(n) {\n var s = 0;\n var n_str = new String(n);\n for (var i = 0; i < n_str.length; ++i) {\n s += parseInt(n_str.charAt(i));\n }\n return n % s === 0;\n}\n\nvar count = 0;\nvar harshads = [];\n\nfor (var n = 1; count < 20; ++n) {\n if (isHarshad(n)) {\n count++;\n harshads.push(n);\n }\n}\n\nconsole.log(harshads.join(\" \"));\n\nvar h = 1000;\nwhile (!isHarshad(++h));\nconsole.log(h);\n"} +{"title": "Harshad or Niven series", "language": "Python", "task": "The [http://mathworld.wolfram.com/HarshadNumber.html Harshad] or Niven numbers are positive integers \u2265 1 that are divisible by the sum of their digits. \n\nFor example, \u00a0 '''42''' \u00a0 is a Harshad number as \u00a0 '''42''' \u00a0 is divisible by \u00a0 ('''4''' + '''2''') \u00a0 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::* \u00a0 list the first '''20''' members of the sequence, \u00a0 and\n::* \u00a0 list the first Harshad number greater than '''1000'''.\n\n\nShow your output here.\n\n\n;Related task\n:* \u00a0 [https://rosettacode.org/wiki/Increasing_gaps_between_consecutive_Niven_numbers Increasing gaps between consecutive Niven numbers]\n\n\n;See also\n* \u00a0 OEIS: A005349\n\n", "solution": ">>> import itertools\n>>> def harshad():\n\tfor n in itertools.count(1):\n\t\tif n % sum(int(ch) for ch in str(n)) == 0:\n\t\t\tyield n\n\n\t\t\n>>> list(itertools.islice(harshad(), 0, 20))\n[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42]\n>>> for n in harshad():\n\tif n > 1000:\n\t\tprint(n)\n\t\tbreak\n\n\t\n1002\n>>> "} +{"title": "Harshad or Niven series", "language": "Python 3.7", "task": "The [http://mathworld.wolfram.com/HarshadNumber.html Harshad] or Niven numbers are positive integers \u2265 1 that are divisible by the sum of their digits. \n\nFor example, \u00a0 '''42''' \u00a0 is a Harshad number as \u00a0 '''42''' \u00a0 is divisible by \u00a0 ('''4''' + '''2''') \u00a0 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::* \u00a0 list the first '''20''' members of the sequence, \u00a0 and\n::* \u00a0 list the first Harshad number greater than '''1000'''.\n\n\nShow your output here.\n\n\n;Related task\n:* \u00a0 [https://rosettacode.org/wiki/Increasing_gaps_between_consecutive_Niven_numbers Increasing gaps between consecutive Niven numbers]\n\n\n;See also\n* \u00a0 OEIS: A005349\n\n", "solution": "'''Harshad or Niven series'''\n\nfrom itertools import count, dropwhile, islice\n\n\n# harshads :: () -> [Int]\ndef harshads():\n '''Harshad series'''\n return (\n x for x in count(1)\n if 0 == x % digitSum(x)\n )\n\n\n# digitSum :: Int -> Int\ndef digitSum(n):\n '''Sum of the decimal digits of n.'''\n def go(x):\n return None if 0 == x else divmod(x, 10)\n return sum(unfoldl(go)(n))\n\n\n# ------------------------- TEST -------------------------\n# main :: IO ()\ndef main():\n '''First 20, and first above 1000.'''\n\n def firstTwenty(xs):\n return take(20)(xs)\n\n def firstAbove1000(xs):\n return take(1)(\n dropwhile(lambda x: 1000 >= x, xs)\n )\n\n print(\n fTable(__doc__ + ':\\n')(\n lambda x: x.__name__\n )(showList)(lambda f: f(harshads()))([\n firstTwenty,\n firstAbove1000\n ])\n )\n\n\n# ----------------------- GENERIC ------------------------\n\n# take :: Int -> [a] -> [a]\n# take :: Int -> String -> String\ndef take(n):\n '''The prefix of xs of length n,\n or xs itself if n > length xs.\n '''\n return lambda xs: (\n xs[0:n]\n if isinstance(xs, (list, tuple))\n else list(islice(xs, n))\n )\n\n\n# unfoldl :: (b -> Maybe (b, a)) -> b -> [a]\ndef unfoldl(f):\n '''A lazy (generator) list unfolded from a seed value\n by repeated application of f until no residue remains.\n Dual to fold/reduce.\n f returns either None or just (residue, value).\n For a strict output list, wrap the result with list()\n '''\n def go(v):\n residueValue = f(v)\n while residueValue:\n yield residueValue[1]\n residueValue = f(residueValue[0])\n return go\n\n\n# ----------------------- DISPLAY ------------------------\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function ->\n fx display function -> f -> xs -> tabular string.\n '''\n def gox(xShow):\n def gofx(fxShow):\n def gof(f):\n def goxs(xs):\n ys = [xShow(x) for x in xs]\n w = max(map(len, ys))\n\n def arrowed(x, y):\n return y.rjust(w, ' ') + ' -> ' + (\n fxShow(f(x))\n )\n return s + '\\n' + '\\n'.join(\n map(arrowed, xs, ys)\n )\n return goxs\n return gof\n return gofx\n return gox\n\n\n# showList :: [a] -> String\ndef showList(xs):\n '''Stringification of a list.'''\n return '[' + ','.join(repr(x) for x in xs) + ']'\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} +{"title": "Hash join", "language": "JavaScript", "task": "An hash join algorithm.\n\n\nImplement the \"hash join\" algorithm, and demonstrate that it passes the test-case listed below.\n\nYou should represent the tables as data structures that feel natural in your programming language.\n\n\nThe \"hash join\" algorithm consists of two steps:\n\n# '''Hash phase:''' Create a multimap from one of the two tables, mapping from each join column value to all the rows that contain it.\n#* The multimap must support hash-based lookup which scales better than a simple linear search, because that's the whole point of this algorithm.\n#* Ideally we should create the multimap for the ''smaller'' table, thus minimizing its creation time and memory size.\n# '''Join phase:''' Scan the other table, and find matching rows by looking in the multimap created before.\n\n\nIn pseudo-code, the algorithm could be expressed as follows:\n\n '''let''' ''A'' = the first input table (or ideally, the larger one)\n '''let''' ''B'' = the second input table (or ideally, the smaller one)\n '''let''' ''jA'' = the join column ID of table ''A''\n '''let''' ''jB'' = the join column ID of table ''B''\n '''let''' ''MB'' = a multimap for mapping from single values to multiple rows of table ''B'' (starts out empty)\n '''let''' ''C'' = the output table (starts out empty)\n \n '''for each''' row ''b'' '''in''' table ''B''''':'''\n '''place''' ''b'' '''in''' multimap ''MB'' under key ''b''(''jB'')\n \n '''for each''' row ''a'' '''in''' table ''A''''':'''\n '''for each''' row ''b'' '''in''' multimap ''MB'' under key ''a''(''jA'')''':'''\n '''let''' ''c'' = the concatenation of row ''a'' and row ''b''\n '''place''' row ''c'' in table ''C''\n\n\n{| class=\"wikitable\"\n|-\n! Input\n! Output\n|-\n|\n\n{| style=\"border:none; border-collapse:collapse;\"\n|-\n| style=\"border:none\" | ''A'' = \n| style=\"border:none\" |\n\n{| class=\"wikitable\"\n|-\n! Age !! Name\n|-\n| 27 || Jonah\n|-\n| 18 || Alan\n|-\n| 28 || Glory\n|-\n| 18 || Popeye\n|-\n| 28 || Alan\n|}\n\n| style=\"border:none; padding-left:1.5em;\" rowspan=\"2\" |\n| style=\"border:none\" | ''B'' = \n| style=\"border:none\" |\n\n{| class=\"wikitable\"\n|-\n! Character !! Nemesis\n|-\n| Jonah || Whales\n|-\n| Jonah || Spiders\n|-\n| Alan || Ghosts\n|-\n| Alan || Zombies\n|-\n| Glory || Buffy\n|}\n\n|-\n| style=\"border:none\" | ''jA'' =\n| style=\"border:none\" | Name (i.e. column 1)\n\n| style=\"border:none\" | ''jB'' =\n| style=\"border:none\" | Character (i.e. column 0)\n|}\n\n|\n\n{| class=\"wikitable\" style=\"margin-left:1em\"\n|-\n! A.Age !! A.Name !! B.Character !! B.Nemesis\n|-\n| 27 || Jonah || Jonah || Whales\n|-\n| 27 || Jonah || Jonah || Spiders\n|-\n| 18 || Alan || Alan || Ghosts\n|-\n| 18 || Alan || Alan || Zombies\n|-\n| 28 || Glory || Glory || Buffy\n|-\n| 28 || Alan || Alan || Ghosts\n|-\n| 28 || Alan || Alan || Zombies\n|}\n\n|}\n\nThe order of the rows in the output table is not significant.\nIf you're using numerically indexed arrays to represent table rows (rather than referring to columns by name), you could represent the output rows in the form [[27, \"Jonah\"], [\"Jonah\", \"Whales\"]].\n\n\n", "solution": "(() => {\n 'use strict';\n\n // hashJoin :: [Dict] -> [Dict] -> String -> [Dict]\n let hashJoin = (tblA, tblB, strJoin) => {\n\n let [jA, jB] = strJoin.split('='),\n M = tblB.reduce((a, x) => {\n let id = x[jB];\n return (\n a[id] ? a[id].push(x) : a[id] = [x],\n a\n );\n }, {});\n\n return tblA.reduce((a, x) => {\n let match = M[x[jA]];\n return match ? (\n a.concat(match.map(row => dictConcat(x, row)))\n ) : a;\n }, []);\n },\n\n // dictConcat :: Dict -> Dict -> Dict\n dictConcat = (dctA, dctB) => {\n let ok = Object.keys;\n return ok(dctB).reduce(\n (a, k) => (a['B_' + k] = dctB[k]) && a,\n ok(dctA).reduce(\n (a, k) => (a['A_' + k] = dctA[k]) && a, {}\n )\n );\n };\n\n\n // TEST\n let lstA = [\n { age: 27, name: 'Jonah' },\n { age: 18, name: 'Alan' },\n { age: 28, name: 'Glory' },\n { age: 18, name: 'Popeye' },\n { age: 28, name: 'Alan' }\n ],\n lstB = [\n { character: 'Jonah', nemesis: 'Whales' },\n { character: 'Jonah', nemesis: 'Spiders' },\n { character: 'Alan', nemesis: 'Ghosts' },\n { character:'Alan', nemesis: 'Zombies' },\n { character: 'Glory', nemesis: 'Buffy' },\n { character: 'Bob', nemesis: 'foo' }\n ];\n\n return hashJoin(lstA, lstB, 'name=character');\n \n})();\n"} +{"title": "Hash join", "language": "Python", "task": "An hash join algorithm.\n\n\nImplement the \"hash join\" algorithm, and demonstrate that it passes the test-case listed below.\n\nYou should represent the tables as data structures that feel natural in your programming language.\n\n\nThe \"hash join\" algorithm consists of two steps:\n\n# '''Hash phase:''' Create a multimap from one of the two tables, mapping from each join column value to all the rows that contain it.\n#* The multimap must support hash-based lookup which scales better than a simple linear search, because that's the whole point of this algorithm.\n#* Ideally we should create the multimap for the ''smaller'' table, thus minimizing its creation time and memory size.\n# '''Join phase:''' Scan the other table, and find matching rows by looking in the multimap created before.\n\n\nIn pseudo-code, the algorithm could be expressed as follows:\n\n '''let''' ''A'' = the first input table (or ideally, the larger one)\n '''let''' ''B'' = the second input table (or ideally, the smaller one)\n '''let''' ''jA'' = the join column ID of table ''A''\n '''let''' ''jB'' = the join column ID of table ''B''\n '''let''' ''MB'' = a multimap for mapping from single values to multiple rows of table ''B'' (starts out empty)\n '''let''' ''C'' = the output table (starts out empty)\n \n '''for each''' row ''b'' '''in''' table ''B''''':'''\n '''place''' ''b'' '''in''' multimap ''MB'' under key ''b''(''jB'')\n \n '''for each''' row ''a'' '''in''' table ''A''''':'''\n '''for each''' row ''b'' '''in''' multimap ''MB'' under key ''a''(''jA'')''':'''\n '''let''' ''c'' = the concatenation of row ''a'' and row ''b''\n '''place''' row ''c'' in table ''C''\n\n\n{| class=\"wikitable\"\n|-\n! Input\n! Output\n|-\n|\n\n{| style=\"border:none; border-collapse:collapse;\"\n|-\n| style=\"border:none\" | ''A'' = \n| style=\"border:none\" |\n\n{| class=\"wikitable\"\n|-\n! Age !! Name\n|-\n| 27 || Jonah\n|-\n| 18 || Alan\n|-\n| 28 || Glory\n|-\n| 18 || Popeye\n|-\n| 28 || Alan\n|}\n\n| style=\"border:none; padding-left:1.5em;\" rowspan=\"2\" |\n| style=\"border:none\" | ''B'' = \n| style=\"border:none\" |\n\n{| class=\"wikitable\"\n|-\n! Character !! Nemesis\n|-\n| Jonah || Whales\n|-\n| Jonah || Spiders\n|-\n| Alan || Ghosts\n|-\n| Alan || Zombies\n|-\n| Glory || Buffy\n|}\n\n|-\n| style=\"border:none\" | ''jA'' =\n| style=\"border:none\" | Name (i.e. column 1)\n\n| style=\"border:none\" | ''jB'' =\n| style=\"border:none\" | Character (i.e. column 0)\n|}\n\n|\n\n{| class=\"wikitable\" style=\"margin-left:1em\"\n|-\n! A.Age !! A.Name !! B.Character !! B.Nemesis\n|-\n| 27 || Jonah || Jonah || Whales\n|-\n| 27 || Jonah || Jonah || Spiders\n|-\n| 18 || Alan || Alan || Ghosts\n|-\n| 18 || Alan || Alan || Zombies\n|-\n| 28 || Glory || Glory || Buffy\n|-\n| 28 || Alan || Alan || Ghosts\n|-\n| 28 || Alan || Alan || Zombies\n|}\n\n|}\n\nThe order of the rows in the output table is not significant.\nIf you're using numerically indexed arrays to represent table rows (rather than referring to columns by name), you could represent the output rows in the form [[27, \"Jonah\"], [\"Jonah\", \"Whales\"]].\n\n\n", "solution": "from collections import defaultdict\n\ndef hashJoin(table1, index1, table2, index2):\n h = defaultdict(list)\n # hash phase\n for s in table1:\n h[s[index1]].append(s)\n # join phase\n return [(s, r) for r in table2 for s in h[r[index2]]]\n\ntable1 = [(27, \"Jonah\"),\n (18, \"Alan\"),\n (28, \"Glory\"),\n (18, \"Popeye\"),\n (28, \"Alan\")]\ntable2 = [(\"Jonah\", \"Whales\"),\n (\"Jonah\", \"Spiders\"),\n (\"Alan\", \"Ghosts\"),\n (\"Alan\", \"Zombies\"),\n (\"Glory\", \"Buffy\")]\n\nfor row in hashJoin(table1, 1, table2, 0):\n print(row)"} +{"title": "Haversine formula", "language": "C", "task": "The '''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) \u00a0 in Nashville, TN, USA, \u00a0 which is: \n '''N''' 36\u00b07.2', '''W''' 86\u00b040.2' (36.12, -86.67) -and-\n* Los Angeles International Airport (LAX) \u00a0in Los Angeles, CA, USA, \u00a0 which is:\n '''N''' 33\u00b056.4', '''W''' 118\u00b024.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' \u2248 1.0621333 km and .001\" \u2248 .00177 km,\n practical precision required is certainly no greater than about\n .0000001\u2014\u2014i.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\n[http://math.wikia.com/wiki/Ellipsoidal_quadratic_mean_radius ellipsoidal quadratic mean radius]\nis wrong (the averaging over azimuth is biased). When applying these\nexamples in real applications, it is better to use the\n[https://en.wikipedia.org/wiki/Earth_radius#Mean_radius mean 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": "Haversine formula", "language": "JavaScript", "task": "The '''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) \u00a0 in Nashville, TN, USA, \u00a0 which is: \n '''N''' 36\u00b07.2', '''W''' 86\u00b040.2' (36.12, -86.67) -and-\n* Los Angeles International Airport (LAX) \u00a0in Los Angeles, CA, USA, \u00a0 which is:\n '''N''' 33\u00b056.4', '''W''' 118\u00b024.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' \u2248 1.0621333 km and .001\" \u2248 .00177 km,\n practical precision required is certainly no greater than about\n .0000001\u2014\u2014i.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\n[http://math.wikia.com/wiki/Ellipsoidal_quadratic_mean_radius ellipsoidal quadratic mean radius]\nis wrong (the averaging over azimuth is biased). When applying these\nexamples in real applications, it is better to use the\n[https://en.wikipedia.org/wiki/Earth_radius#Mean_radius mean 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": "function haversine() {\n var radians = Array.prototype.map.call(arguments, function(deg) { return deg/180.0 * Math.PI; });\n var lat1 = radians[0], lon1 = radians[1], lat2 = radians[2], lon2 = radians[3];\n var R = 6372.8; // km\n var dLat = lat2 - lat1;\n var dLon = lon2 - lon1;\n var a = Math.sin(dLat / 2) * Math.sin(dLat /2) + Math.sin(dLon / 2) * Math.sin(dLon /2) * Math.cos(lat1) * Math.cos(lat2);\n var c = 2 * Math.asin(Math.sqrt(a));\n return R * c;\n}\nconsole.log(haversine(36.12, -86.67, 33.94, -118.40));"} +{"title": "Haversine formula", "language": "Python", "task": "The '''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) \u00a0 in Nashville, TN, USA, \u00a0 which is: \n '''N''' 36\u00b07.2', '''W''' 86\u00b040.2' (36.12, -86.67) -and-\n* Los Angeles International Airport (LAX) \u00a0in Los Angeles, CA, USA, \u00a0 which is:\n '''N''' 33\u00b056.4', '''W''' 118\u00b024.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' \u2248 1.0621333 km and .001\" \u2248 .00177 km,\n practical precision required is certainly no greater than about\n .0000001\u2014\u2014i.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\n[http://math.wikia.com/wiki/Ellipsoidal_quadratic_mean_radius ellipsoidal quadratic mean radius]\nis wrong (the averaging over azimuth is biased). When applying these\nexamples in real applications, it is better to use the\n[https://en.wikipedia.org/wiki/Earth_radius#Mean_radius mean 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": "from math import radians, sin, cos, sqrt, asin\n\n\ndef haversine(lat1, lon1, lat2, lon2):\n R = 6372.8 # Earth radius in kilometers\n\n dLat = radians(lat2 - lat1)\n dLon = radians(lon2 - lon1)\n lat1 = radians(lat1)\n lat2 = radians(lat2)\n\n a = sin(dLat / 2)**2 + cos(lat1) * cos(lat2) * sin(dLon / 2)**2\n c = 2 * asin(sqrt(a))\n\n return R * c\n\n>>> haversine(36.12, -86.67, 33.94, -118.40)\n2887.2599506071106\n>>> "} +{"title": "Hello world/Line printer", "language": "C", "task": "[[Category:Hardware]] \n[[Category:Printer]]\n\n;Task:\nCause a line printer attached to the computer to print a line containing the message: \u00a0 Hello World! \n\n\n;Note:\nA line printer is not the same as standard output. \n\nA \u00a0 line printer \u00a0 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": "Hello world/Line printer", "language": "Node.js", "task": "[[Category:Hardware]] \n[[Category:Printer]]\n\n;Task:\nCause a line printer attached to the computer to print a line containing the message: \u00a0 Hello World! \n\n\n;Note:\nA line printer is not the same as standard output. \n\nA \u00a0 line printer \u00a0 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": "// This example runs on Node.js\nvar fs = require('fs');\n// Assuming lp is at /dev/lp0\nvar lp = fs.openSync('/dev/lp0', 'w');\nfs.writeSync(lp, 'Hello, world!\\n');\nfs.close(lp);"} +{"title": "Hello world/Line printer", "language": "Chromium", "task": "[[Category:Hardware]] \n[[Category:Printer]]\n\n;Task:\nCause a line printer attached to the computer to print a line containing the message: \u00a0 Hello World! \n\n\n;Note:\nA line printer is not the same as standard output. \n\nA \u00a0 line printer \u00a0 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": "\ndocument.write(\"Hello World!\");\nprint(); //Opens a dialog.\n"} +{"title": "Hello world/Line printer", "language": "Python", "task": "[[Category:Hardware]] \n[[Category:Printer]]\n\n;Task:\nCause a line printer attached to the computer to print a line containing the message: \u00a0 Hello World! \n\n\n;Note:\nA line printer is not the same as standard output. \n\nA \u00a0 line printer \u00a0 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": "lp = open(\"/dev/lp0\",\"w\")\nlp.write(\"Hello World!\\n\")\nlp.close()"} +{"title": "Hello world/Newbie", "language": "C", "task": ";Task:\nGuide a new user of a language through the steps necessary \nto install the programming language and selection of a text editor if needed, \nto run the languages' example in the [[Hello world/Text]] task.\n* Assume the language-newbie is a programmer in another language.\n* Assume the language-newbie is competent in installing software for the platform.\n* Assume the language-newbie can use one simple text editor for the OS/platform, (but that may not necessarily be a particular one if the installation needs a particular editor).\n* Refer to, (and link to), already existing documentation as much as possible (but provide a summary here).\n* Remember to state where to view the output.\n* If particular IDE's or editors are required that are not standard, then point to/explain their installation too.\n\n\n;Note:\n* If it is more natural for a language to give output via a GUI or to a file etc, then use that method of output rather than as text to a terminal/command-line, but remember to give instructions on how to view the output generated.\n* You may use sub-headings if giving instructions for multiple platforms.\n\n", "solution": "===Using gcc===\n\n====Debian Based Systems====\nInstall gcc\n $ sudo apt-get install gcc\n\n====Red Hat Based Systems====\nInstall gcc\n $ su\n # yum install gcc\n\n====All Distributions====\nAfter you have installed gcc using instructions above. \nCreate helloworld.c. \nThis uses HERE document and bash, the standard shell.\n $ cat > helloworld.c <\n int main( int argc, char *argv[] ) {\n puts( \"Hello World!\" );\n return 0;\n }\n HERE\nCompile it using gcc.\n $ gcc -o helloworld helloworld.c\nRun it\n $ ./helloworld\n\n"} +{"title": "Here document", "language": "JavaScript", "task": "A \u00a0 ''here document'' \u00a0 (or \"heredoc\") \u00a0 is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. \n\nDepending on the language being used, a \u00a0 ''here document'' \u00a0 is constructed using a command followed by \"<<\" (or some other symbol) followed by a token string. \n\nThe text block will then start on the next line, and will be followed by the chosen token at the beginning of the following line, which is used to mark the end of the text block.\n\n\n;Task:\nDemonstrate the use of \u00a0 ''here documents'' \u00a0 within the language.\n\n;Related task:\n* \u00a0 [[Documentation]]\n\n", "solution": "const myVar = 123;\nconst tempLit = `Here is some\nmulti-line string. And here is\nthe value of \"myVar\": ${myVar}\nThat's all.`;\nconsole.log(tempLit)\n"} +{"title": "Here document", "language": "Python", "task": "A \u00a0 ''here document'' \u00a0 (or \"heredoc\") \u00a0 is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. \n\nDepending on the language being used, a \u00a0 ''here document'' \u00a0 is constructed using a command followed by \"<<\" (or some other symbol) followed by a token string. \n\nThe text block will then start on the next line, and will be followed by the chosen token at the beginning of the following line, which is used to mark the end of the text block.\n\n\n;Task:\nDemonstrate the use of \u00a0 ''here documents'' \u00a0 within the language.\n\n;Related task:\n* \u00a0 [[Documentation]]\n\n", "solution": "print(\"\"\"\\\nUsage: thingy [OPTIONS]\n -h Display this usage message\n -H hostname Hostname to connect to\n\"\"\")"} +{"title": "Heronian triangles", "language": "C", "task": "Hero's formula for the area of a triangle given the length of its three sides \u00a0 ''a'', \u00a0 ''b'', \u00a0 and \u00a0 ''c'' \u00a0 is given by:\n\n:::: A = \\sqrt{s(s-a)(s-b)(s-c)},\n\nwhere \u00a0 ''s'' \u00a0 is half the perimeter of the triangle; that is,\n\n:::: s=\\frac{a+b+c}{2}.\n\n'''[http://www.had2know.com/academics/heronian-triangles-generator-calculator.html Heronian triangles]'''\nare triangles whose sides ''and area'' are all integers.\n: An example is the triangle with sides \u00a0 '''3, 4, 5''' \u00a0 whose area is \u00a0 '''6''' \u00a0 (and whose perimeter is \u00a0 '''12'''). \n\n\nNote that any triangle whose sides are all an integer multiple of \u00a0 '''3, 4, 5'''; \u00a0 such as \u00a0 '''6, 8, 10,''' \u00a0 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 \u00a0 '''1''' \u00a0 (unity). \n\nThis will exclude, for example, triangle \u00a0 '''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": "\n#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": "Heronian triangles", "language": "JavaScript", "task": "Hero's formula for the area of a triangle given the length of its three sides \u00a0 ''a'', \u00a0 ''b'', \u00a0 and \u00a0 ''c'' \u00a0 is given by:\n\n:::: A = \\sqrt{s(s-a)(s-b)(s-c)},\n\nwhere \u00a0 ''s'' \u00a0 is half the perimeter of the triangle; that is,\n\n:::: s=\\frac{a+b+c}{2}.\n\n'''[http://www.had2know.com/academics/heronian-triangles-generator-calculator.html Heronian triangles]'''\nare triangles whose sides ''and area'' are all integers.\n: An example is the triangle with sides \u00a0 '''3, 4, 5''' \u00a0 whose area is \u00a0 '''6''' \u00a0 (and whose perimeter is \u00a0 '''12'''). \n\n\nNote that any triangle whose sides are all an integer multiple of \u00a0 '''3, 4, 5'''; \u00a0 such as \u00a0 '''6, 8, 10,''' \u00a0 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 \u00a0 '''1''' \u00a0 (unity). \n\nThis will exclude, for example, triangle \u00a0 '''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": "\nwindow.onload = function(){\t\n var list = [];\n var j = 0;\t\n for(var c = 1; c <= 200; c++)\n for(var b = 1; b <= c; b++)\n for(var a = 1; a <= b; a++)\n\t if(gcd(gcd(a, b), c) == 1 && isHeron(heronArea(a, b, c)))\t\t\t\t\t\t\t\n\t\t list[j++] = new Array(a, b, c, a + b + c, heronArea(a, b, c));\n sort(list);\t\n document.write(\"Primitive Heronian triangles with sides up to 200: \" + list.length + \"First ten when ordered by increasing area, then perimeter:SidesPerimeterArea\");\n for(var i = 0; i < 10; i++)\n\tdocument.write(\"\" + list[i][0] + \" x \" + list[i][1] + \" x \" + list[i][2] + \"\" + list[i][3] + \"\" + list[i][4] + \"\");\n document.write(\"Area = 210SidesPerimeterArea\");\n for(var i = 0; i < list.length; i++)\n\tif(list[i][4] == 210)\n\t document.write(\"\" + list[i][0] + \" x \" + list[i][1] + \" x \" + list[i][2] + \"\" + list[i][3] + \"\" + list[i][4] + \"\"); \t\t\n function heronArea(a, b, c){\n\tvar s = (a + b + c)/ 2;\n\treturn Math.sqrt(s *(s -a)*(s - b)*(s - c));\t\t\n }\t\n function isHeron(h){\n return h % 1 == 0 && h > 0;\n }\t\n function gcd(a, b){\n\tvar leftover = 1, dividend = a > b ? a : b, divisor = a > b ? b : a;\t\t\n\twhile(leftover != 0){\n\t leftover = dividend % divisor;\n\t if(leftover > 0){\n\t\tdividend = divisor;\n\t\tdivisor = leftover;\n\t }\n\t}\t\t\n\treturn divisor;\n }\t\n function sort(list){\n\tvar swapped = true;\n\tvar temp = [];\n\twhile(swapped){\n\t swapped = false;\n\t for(var i = 1; i < list.length; i++){\n\t\tif(list[i][4] < list[i - 1][4] || list[i][4] == list[i - 1][4] && list[i][3] < list[i - 1][3]){\n\t\t temp = list[i];\n\t\t list[i] = list[i - 1];\n\t\t list[i - 1] = temp;\n\t\t swapped = true;\n\t\t}\t\t\t\t\n\t }\t\t\t\n\t}\n }\n}\n"} +{"title": "Heronian triangles", "language": "Python", "task": "Hero's formula for the area of a triangle given the length of its three sides \u00a0 ''a'', \u00a0 ''b'', \u00a0 and \u00a0 ''c'' \u00a0 is given by:\n\n:::: A = \\sqrt{s(s-a)(s-b)(s-c)},\n\nwhere \u00a0 ''s'' \u00a0 is half the perimeter of the triangle; that is,\n\n:::: s=\\frac{a+b+c}{2}.\n\n'''[http://www.had2know.com/academics/heronian-triangles-generator-calculator.html Heronian triangles]'''\nare triangles whose sides ''and area'' are all integers.\n: An example is the triangle with sides \u00a0 '''3, 4, 5''' \u00a0 whose area is \u00a0 '''6''' \u00a0 (and whose perimeter is \u00a0 '''12'''). \n\n\nNote that any triangle whose sides are all an integer multiple of \u00a0 '''3, 4, 5'''; \u00a0 such as \u00a0 '''6, 8, 10,''' \u00a0 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 \u00a0 '''1''' \u00a0 (unity). \n\nThis will exclude, for example, triangle \u00a0 '''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": "from __future__ import division, print_function\nfrom math import gcd, sqrt\n\n\ndef hero(a, b, c):\n s = (a + b + c) / 2\n a2 = s * (s - a) * (s - b) * (s - c)\n return sqrt(a2) if a2 > 0 else 0\n\n\ndef is_heronian(a, b, c):\n a = hero(a, b, c)\n return a > 0 and a.is_integer()\n\n\ndef gcd3(x, y, z):\n return gcd(gcd(x, y), z)\n\n\nif __name__ == '__main__':\n MAXSIDE = 200\n\n N = 1 + MAXSIDE\n h = [(x, y, z)\n for x in range(1, N)\n for y in range(x, N)\n for z in range(y, N) if (x + y > z) and\n 1 == gcd3(x, y, z) and\n is_heronian(x, y, z)]\n\n # By increasing area, perimeter, then sides\n h.sort(key=lambda x: (hero(*x), sum(x), x[::-1]))\n\n print(\n 'Primitive Heronian triangles with sides up to %i:' % MAXSIDE, len(h)\n )\n print('\\nFirst ten when ordered by increasing area, then perimeter,',\n 'then maximum sides:')\n print('\\n'.join(' %14r perim: %3i area: %i'\n % (sides, sum(sides), hero(*sides)) for sides in h[:10]))\n print('\\nAll with area 210 subject to the previous ordering:')\n print('\\n'.join(' %14r perim: %3i area: %i'\n % (sides, sum(sides), hero(*sides)) for sides in h\n if hero(*sides) == 210))\n"} +{"title": "Hex words", "language": "Python", "task": ";Definition\nFor the purposes of this task a '''hex word''' means a word which (in lower case form) consists entirely of the letters '''a, b, c, d, e''' and '''f'''.\n\n;Task\nUsing [http://wiki.puzzlers.org/pub/wordlists/unixdict.txt unixdict.txt], find all hex words with '''4''' letters or more.\n\nConvert each such word to its decimal equivalent and compute its base 10 digital root.\n\nDisplay all three in increasing order of digital root and show the total count of such words.\n\nKeeping only words which contain at least '''4''' distinct letters, display the same statistics but in decreasing order of decimal equivalent together with their total count.\n\n", "solution": "def digroot(n):\n while n > 9:\n n = sum([int(d) for d in str(n)])\n return n\n\nwith open('unixdict.txt') as f:\n lines = [w.strip() for w in f.readlines()]\n words = [w for w in lines if len(w) >= 4 and all(c in 'abcdef' for c in w)]\n results = [[w, int(w, 16)] for w in words]\n for a in results:\n a.append(digroot(a[1]))\n \n print(f\"Hex words in unixdict.txt:\\nRoot Word Base 10\\n\", \"-\"*22)\n for a in sorted(results, key=lambda x:x[2]):\n print(f\"{a[2]} {a[0]:6}{a[1]:10}\")\n \n print(\"Total count of these words:\", len(results))\n print(\"\\nHex words with > 3 distinct letters:\\nRoot Word Base 10\\n\", \"-\"*22)\n results = [a for a in results if len(set(str(a[0]))) > 3]\n for a in sorted(results, key=lambda x:x[2]):\n print(f\"{a[2]} {a[0]:6}{a[1]:10}\")\n \n print(\"Total count of those words:\", len(results))\n"} +{"title": "Hickerson series of almost integers", "language": "C", "task": "The following function, \u00a0 due to D. Hickerson, \u00a0 is said to generate \"Almost integers\" by the \n[http://mathworld.wolfram.com/AlmostInteger.html \"Almost Integer\" page of Wolfram MathWorld], \u00a0 (December 31 2013). \u00a0 (See formula numbered \u00a0 '''51'''.)\n\n\nThe function is: \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 h(n) = {\\operatorname{n}!\\over2(\\ln{2})^{n+1}}\n\n\nIt is said to produce \"almost integers\" for \u00a0 '''n''' \u00a0 between \u00a0 '''1''' \u00a0 and \u00a0 '''17'''. \nThe purpose of the task is to verify this assertion.\n\nAssume that an \"almost integer\" has '''either a nine or a zero as its first digit after the decimal point''' of its decimal string representation\n\n\n;Task:\nCalculate all values of the function checking and stating which are \"almost integers\".\n\nNote: Use extended/arbitrary precision numbers in your calculation if necessary to ensure you have adequate precision of results as for example:\n h(18) = 3385534663256845326.39...\n\n", "solution": "#include \n#include \n\nvoid h(int n)\n{\n\tMPFR_DECL_INIT(a, 200);\n\tMPFR_DECL_INIT(b, 200);\n\n\tmpfr_fac_ui(a, n, MPFR_RNDD);\t\t// a = n!\n\n\tmpfr_set_ui(b, 2, MPFR_RNDD);\t\t// b = 2\n\tmpfr_log(b, b, MPFR_RNDD);\t\t// b = log(b)\n\tmpfr_pow_ui(b, b, n + 1, MPFR_RNDD);\t// b = b^(n+1)\n\n\tmpfr_div(a, a, b, MPFR_RNDD);\t\t// a = a / b\n\tmpfr_div_ui(a, a, 2, MPFR_RNDD);\t// a = a / 2\n\n\tmpfr_frac(b, a, MPFR_RNDD);\t\t// b = a - [a]\n\tmpfr_printf(\"%2d: %23.4Rf %c\\n\", n, a,\n\t\tmpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N');\n}\n\nint main(void)\n{\n\tint n;\n\tfor (n = 1; n <= 17; n++) h(n);\n\n\treturn 0;\n}"} +{"title": "Hickerson series of almost integers", "language": "Python", "task": "The following function, \u00a0 due to D. Hickerson, \u00a0 is said to generate \"Almost integers\" by the \n[http://mathworld.wolfram.com/AlmostInteger.html \"Almost Integer\" page of Wolfram MathWorld], \u00a0 (December 31 2013). \u00a0 (See formula numbered \u00a0 '''51'''.)\n\n\nThe function is: \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 h(n) = {\\operatorname{n}!\\over2(\\ln{2})^{n+1}}\n\n\nIt is said to produce \"almost integers\" for \u00a0 '''n''' \u00a0 between \u00a0 '''1''' \u00a0 and \u00a0 '''17'''. \nThe purpose of the task is to verify this assertion.\n\nAssume that an \"almost integer\" has '''either a nine or a zero as its first digit after the decimal point''' of its decimal string representation\n\n\n;Task:\nCalculate all values of the function checking and stating which are \"almost integers\".\n\nNote: Use extended/arbitrary precision numbers in your calculation if necessary to ensure you have adequate precision of results as for example:\n h(18) = 3385534663256845326.39...\n\n", "solution": "from decimal import Decimal\nimport math\n\ndef h(n):\n 'Simple, reduced precision calculation'\n return math.factorial(n) / (2 * math.log(2) ** (n + 1))\n \ndef h2(n):\n 'Extended precision Hickerson function'\n return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1))\n\nfor n in range(18):\n x = h2(n)\n norm = str(x.normalize())\n almostinteger = (' Nearly integer' \n if 'E' not in norm and ('.0' in norm or '.9' in norm) \n else ' NOT nearly integer!')\n print('n:%2i h:%s%s' % (n, norm, almostinteger))"} +{"title": "History variables", "language": "Python", "task": "''Storing the history of objects in a program is a common task. \nMaintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging.''\n\n''History variables are variables in a programming language which store not only their current value, but also the values they have contained in the past. Some existing languages do provide support for history variables. However these languages typically have many limits and restrictions on use of history variables.\n'' \n\n[http://www.bod.com/index.php?id=3435&objk_id=148050 \"History Variables: \nThe Semantics, Formal Correctness, and Implementation of History Variables \nin an Imperative Programming Language\" by Mallon and Takaoka]\n\nConcept also discussed on [http://lambda-the-ultimate.org/node/3111 LtU] and [http://www.patents.com/us-7111283.html Patents.com].\n\n;Task: \nDemonstrate History variable support: \n* enable history variable support (if needed) \n* define a history variable\n* assign three values\n* non-destructively display the history\n* recall the three values. \n\nFor extra points, if the language of choice does not support history variables, \ndemonstrate how this might be implemented.\n\n", "solution": "import sys\n\nHIST = {}\n\ndef trace(frame, event, arg):\n for name,val in frame.f_locals.items():\n if name not in HIST:\n HIST[name] = []\n else:\n if HIST[name][-1] is val:\n continue\n HIST[name].append(val)\n return trace\n\ndef undo(name):\n HIST[name].pop(-1)\n return HIST[name][-1]\n\ndef main():\n a = 10\n a = 20\n\n for i in range(5):\n c = i\n\n print \"c:\", c, \"-> undo x3 ->\",\n c = undo('c')\n c = undo('c')\n c = undo('c')\n print c\n print 'HIST:', HIST\n\nsys.settrace(trace)\nmain()"} +{"title": "Hofstadter-Conway $10,000 sequence", "language": "C", "task": "The definition of the sequence is colloquially described as:\n* \u00a0 Starting with the list [1,1],\n* \u00a0 Take the last number in the list so far: 1, I'll call it x.\n* \u00a0 Count forward x places from the beginning of the list to find the first number to add (1)\n* \u00a0 Count backward x places from the end of the list to find the second number to add (1)\n* \u00a0 Add the two indexed numbers from the list and the result becomes the next number in the list (1+1)\n* \u00a0 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* \u00a0 a(n)/n \u00a0 tends to \u00a0 0.5 \u00a0 as \u00a0 n \u00a0 grows towards infinity.\n* \u00a0 a(n)/n \u00a0 where \u00a0 n \u00a0 is a power of \u00a0 2 \u00a0 is \u00a0 0.5\n* \u00a0 For \u00a0 n>4 \u00a0 the maximal value of \u00a0 a(n)/n \u00a0 between successive powers of 2 decreases.\n\na(n) / n \u00a0 for \u00a0 n \u00a0 in \u00a0 1..256 \n\n\nThe sequence is so named because John Conway [http://www.nytimes.com/1988/08/30/science/intellectual-duel-brash-challenge-swift-response.html offered a prize] of $10,000 to the first person who could\nfind the first position, \u00a0 p \u00a0 in the sequence where \n \u2502a(n)/n\u2502 < 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 [https://en.wikipedia.org/wiki/Colin_Lingwood_Mallows Dr. Colin L. Mallows] who proved the properties of the sequence and allowed him to find the value of \u00a0 n \u00a0 (which is much smaller than the 3,173,375,556 quoted in the NYT article).\n\n\n;Task:\n# \u00a0 Create a routine to generate members of the Hofstadter-Conway $10,000 sequence.\n# \u00a0 Use it to show the maxima of \u00a0 a(n)/n \u00a0 between successive powers of two up to \u00a0 2**20\n# \u00a0 As a stretch goal: \u00a0 compute the value of \u00a0 n \u00a0 that would have won the prize and confirm it is true for \u00a0 n \u00a0 up to 2**20\n\n\n\n;Also see:\n* \u00a0 [http://www.jstor.org/stable/2324028 Conways Challenge Sequence], Mallows' own account.\n* \u00a0 [http://mathworld.wolfram.com/Hofstadter-Conway10000-DollarSequence.html 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-Conway $10,000 sequence", "language": "JavaScript", "task": "The definition of the sequence is colloquially described as:\n* \u00a0 Starting with the list [1,1],\n* \u00a0 Take the last number in the list so far: 1, I'll call it x.\n* \u00a0 Count forward x places from the beginning of the list to find the first number to add (1)\n* \u00a0 Count backward x places from the end of the list to find the second number to add (1)\n* \u00a0 Add the two indexed numbers from the list and the result becomes the next number in the list (1+1)\n* \u00a0 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* \u00a0 a(n)/n \u00a0 tends to \u00a0 0.5 \u00a0 as \u00a0 n \u00a0 grows towards infinity.\n* \u00a0 a(n)/n \u00a0 where \u00a0 n \u00a0 is a power of \u00a0 2 \u00a0 is \u00a0 0.5\n* \u00a0 For \u00a0 n>4 \u00a0 the maximal value of \u00a0 a(n)/n \u00a0 between successive powers of 2 decreases.\n\na(n) / n \u00a0 for \u00a0 n \u00a0 in \u00a0 1..256 \n\n\nThe sequence is so named because John Conway [http://www.nytimes.com/1988/08/30/science/intellectual-duel-brash-challenge-swift-response.html offered a prize] of $10,000 to the first person who could\nfind the first position, \u00a0 p \u00a0 in the sequence where \n \u2502a(n)/n\u2502 < 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 [https://en.wikipedia.org/wiki/Colin_Lingwood_Mallows Dr. Colin L. Mallows] who proved the properties of the sequence and allowed him to find the value of \u00a0 n \u00a0 (which is much smaller than the 3,173,375,556 quoted in the NYT article).\n\n\n;Task:\n# \u00a0 Create a routine to generate members of the Hofstadter-Conway $10,000 sequence.\n# \u00a0 Use it to show the maxima of \u00a0 a(n)/n \u00a0 between successive powers of two up to \u00a0 2**20\n# \u00a0 As a stretch goal: \u00a0 compute the value of \u00a0 n \u00a0 that would have won the prize and confirm it is true for \u00a0 n \u00a0 up to 2**20\n\n\n\n;Also see:\n* \u00a0 [http://www.jstor.org/stable/2324028 Conways Challenge Sequence], Mallows' own account.\n* \u00a0 [http://mathworld.wolfram.com/Hofstadter-Conway10000-DollarSequence.html Mathworld Article].\n\n", "solution": "var hofst_10k = function(n) {\n\tvar memo = [1, 1];\n\n\tvar a = function(n) {\n\t\tvar result = memo[n-1];\n\t\tif (typeof result !== 'number') {\n\t\t\tresult = a(a(n-1))+a(n-a(n-1));\t\n\t\t\tmemo[n-1] = result;\n\t\t}\t\n\t\treturn result;\n\t}\n\treturn a;\n}();\n\nvar maxima_between_twos = function(exp) {\n\tvar current_max = 0;\n\tfor(var i = Math.pow(2,exp)+1; i < Math.pow(2,exp+1); i += 1) {\n\t\tcurrent_max = Math.max(current_max, hofst_10k(i)/i);\n\t}\n\treturn current_max;\n}\n\nfor(var i = 1; i <= 20; i += 1) {\n\tconsole.log(\"Maxima between 2^\"+i+\"-2^\"+(i+1)+\" is: \"+maxima_between_twos(i)+\"\\n\");\n}"} +{"title": "Hofstadter-Conway $10,000 sequence", "language": "Python", "task": "The definition of the sequence is colloquially described as:\n* \u00a0 Starting with the list [1,1],\n* \u00a0 Take the last number in the list so far: 1, I'll call it x.\n* \u00a0 Count forward x places from the beginning of the list to find the first number to add (1)\n* \u00a0 Count backward x places from the end of the list to find the second number to add (1)\n* \u00a0 Add the two indexed numbers from the list and the result becomes the next number in the list (1+1)\n* \u00a0 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* \u00a0 a(n)/n \u00a0 tends to \u00a0 0.5 \u00a0 as \u00a0 n \u00a0 grows towards infinity.\n* \u00a0 a(n)/n \u00a0 where \u00a0 n \u00a0 is a power of \u00a0 2 \u00a0 is \u00a0 0.5\n* \u00a0 For \u00a0 n>4 \u00a0 the maximal value of \u00a0 a(n)/n \u00a0 between successive powers of 2 decreases.\n\na(n) / n \u00a0 for \u00a0 n \u00a0 in \u00a0 1..256 \n\n\nThe sequence is so named because John Conway [http://www.nytimes.com/1988/08/30/science/intellectual-duel-brash-challenge-swift-response.html offered a prize] of $10,000 to the first person who could\nfind the first position, \u00a0 p \u00a0 in the sequence where \n \u2502a(n)/n\u2502 < 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 [https://en.wikipedia.org/wiki/Colin_Lingwood_Mallows Dr. Colin L. Mallows] who proved the properties of the sequence and allowed him to find the value of \u00a0 n \u00a0 (which is much smaller than the 3,173,375,556 quoted in the NYT article).\n\n\n;Task:\n# \u00a0 Create a routine to generate members of the Hofstadter-Conway $10,000 sequence.\n# \u00a0 Use it to show the maxima of \u00a0 a(n)/n \u00a0 between successive powers of two up to \u00a0 2**20\n# \u00a0 As a stretch goal: \u00a0 compute the value of \u00a0 n \u00a0 that would have won the prize and confirm it is true for \u00a0 n \u00a0 up to 2**20\n\n\n\n;Also see:\n* \u00a0 [http://www.jstor.org/stable/2324028 Conways Challenge Sequence], Mallows' own account.\n* \u00a0 [http://mathworld.wolfram.com/Hofstadter-Conway10000-DollarSequence.html Mathworld Article].\n\n", "solution": "from __future__ import division\n\ndef maxandmallows(nmaxpower2):\n nmax = 2**nmaxpower2\n mx = (0.5, 2)\n mxpow2 = []\n mallows = None\n\n # Hofstadter-Conway sequence starts at hc[1],\n # hc[0] is not part of the series.\n hc = [None, 1, 1]\n\n for n in range(2, nmax + 1):\n ratio = hc[n] / n\n if ratio > mx[0]:\n mx = (ratio, n)\n if ratio >= 0.55:\n mallows = n\n if ratio == 0.5:\n print(\"In the region %7i < n <= %7i: max a(n)/n = %6.4f at n = %i\" %\n\t\t (n//2, n, mx[0], mx[1]))\n mxpow2.append(mx[0])\n mx = (ratio, n)\n hc.append(hc[hc[n]] + hc[-hc[n]])\n\n return hc, mallows if mxpow2 and mxpow2[-1] < 0.55 and n > 4 else None\n\nif __name__ == '__main__':\n hc, mallows = maxandmallows(20)\n if mallows:\n print(\"\\nYou too might have won $1000 with the mallows number of %i\" % mallows)\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 [http://oeis.org/A005228 A005228] and [http://oeis.org/A030124 A030124].\n* [http://mathworld.wolfram.com/HofstadterFigure-FigureSequence.html 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 Figure-Figure sequences", "language": "JavaScript", "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 [http://oeis.org/A005228 A005228] and [http://oeis.org/A030124 A030124].\n* [http://mathworld.wolfram.com/HofstadterFigure-FigureSequence.html Wolfram MathWorld]\n* Wikipedia: Hofstadter Figure-Figure sequences.\n\n", "solution": "var R = [null, 1];\nvar S = [null, 2];\n\nvar extend_sequences = function (n) {\n\tvar current = Math.max(R[R.length-1],S[S.length-1]);\n\tvar i;\n\twhile (R.length <= n || S.length <= n) {\n\t\ti = Math.min(R.length, S.length) - 1;\n\t\tcurrent += 1;\n\t\tif (current === R[i] + S[i]) {\n\t\t\tR.push(current);\n\t\t} else {\n\t\t\tS.push(current);\n\t\t}\n\t}\n}\n\nvar ffr = function(n) {\n\textend_sequences(n);\n\treturn R[n];\n};\n\nvar ffs = function(n) {\n\textend_sequences(n);\n\treturn S[n];\n};\n\nfor (var i = 1; i <=10; i += 1) {\n console.log('R('+ i +') = ' + ffr(i));\n}\n\nvar int_array = [];\n\nfor (var i = 1; i <= 40; i += 1) {\n\tint_array.push(ffr(i));\n}\nfor (var i = 1; i <= 960; i += 1) {\n\tint_array.push(ffs(i));\n}\n\nint_array.sort(function(a,b){return a-b;});\n\nfor (var i = 1; i <= 1000; i += 1) {\n\tif (int_array[i-1] !== i) { \n\t\tthrow \"Something's wrong!\" \n\t} else { console.log(\"1000 integer check ok.\"); }\n}"} +{"title": "Hofstadter Figure-Figure sequences", "language": "Python", "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 [http://oeis.org/A005228 A005228] and [http://oeis.org/A030124 A030124].\n* [http://mathworld.wolfram.com/HofstadterFigure-FigureSequence.html Wolfram MathWorld]\n* Wikipedia: Hofstadter Figure-Figure sequences.\n\n", "solution": "def ffr(n):\n if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n try:\n return ffr.r[n]\n except IndexError:\n r, s = ffr.r, ffs.s\n ffr_n_1 = ffr(n-1)\n lastr = r[-1]\n # extend s up to, and one past, last r \n s += list(range(s[-1] + 1, lastr))\n if s[-1] < lastr: s += [lastr + 1]\n # access s[n-1] temporarily extending s if necessary\n len_s = len(s)\n ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]\n ans = ffr_n_1 + ffs_n_1\n r.append(ans)\n return ans\nffr.r = [None, 1]\n\ndef ffs(n):\n if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n try:\n return ffs.s[n]\n except IndexError:\n r, s = ffr.r, ffs.s\n for i in range(len(r), n+2):\n ffr(i)\n if len(s) > n:\n return s[n]\n raise Exception(\"Whoops!\")\nffs.s = [None, 2]\n\nif __name__ == '__main__':\n first10 = [ffr(i) for i in range(1,11)]\n assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], \"ffr() value error(s)\"\n print(\"ffr(n) for n = [1..10] is\", first10)\n #\n bin = [None] + [0]*1000\n for i in range(40, 0, -1):\n bin[ffr(i)] += 1\n for i in range(960, 0, -1):\n bin[ffs(i)] += 1\n if all(b == 1 for b in bin[1:1000]):\n print(\"All Integers 1..1000 found OK\")\n else:\n print(\"All Integers 1..1000 NOT found only once: ERROR\")"} +{"title": "Hofstadter Q sequence", "language": "C", "task": ":: \\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: \u00a0 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 \u00a0 ''safely'' \u00a0 handles being initially asked for an '''n'''th term where \u00a0 '''n''' \u00a0 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": "Hofstadter Q sequence", "language": "JavaScript", "task": ":: \\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: \u00a0 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 \u00a0 ''safely'' \u00a0 handles being initially asked for an '''n'''th term where \u00a0 '''n''' \u00a0 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": "var hofstadterQ = function() {\n var memo = [1,1,1];\n var Q = function (n) {\n var result = memo[n];\n if (typeof result !== 'number') {\n result = Q(n - Q(n-1)) + Q(n - Q(n-2));\n memo[n] = result;\n }\n return result;\n };\n return Q;\n}();\n\nfor (var i = 1; i <=10; i += 1) {\n console.log('Q('+ i +') = ' + hofstadterQ(i));\n}\n\nconsole.log('Q(1000) = ' + hofstadterQ(1000));\n"} +{"title": "Hofstadter Q sequence", "language": "Python", "task": ":: \\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: \u00a0 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 \u00a0 ''safely'' \u00a0 handles being initially asked for an '''n'''th term where \u00a0 '''n''' \u00a0 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": "from sys import getrecursionlimit\n\ndef q1(n):\n if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n try:\n return q.seq[n]\n except IndexError:\n len_q, rlimit = len(q.seq), getrecursionlimit()\n if (n - len_q) > (rlimit // 5):\n for i in range(len_q, n, rlimit // 5):\n q(i)\n ans = q(n - q(n - 1)) + q(n - q(n - 2))\n q.seq.append(ans)\n return ans\n\nif __name__ == '__main__':\n tmp = q1(100000)\n print(\"Q(i+1) < Q(i) for i [1..100000] is true %i times.\" %\n sum(k1 < k0 for k0, k1 in zip(q.seq[1:], q.seq[2:])))"} +{"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": "\n\n/* 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": "Honeycombs", "language": "Python", "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": "[[Honeycombs/Python|Rambling python3 code with tkinter]]\n\n"} +{"title": "Horner's rule for polynomial evaluation", "language": "C", "task": "A fast scheme for evaluating a polynomial such as:\n: -19+7x-4x^2+6x^3\\,\nwhen\n: x=3\\;.\nis to arrange the computation as follows:\n: ((((0) x + 6) x + (-4)) x + 7) x + (-19)\\;\nAnd compute the result from the innermost brackets outwards as in this pseudocode:\n coefficients ''':=''' [-19, 7, -4, 6] ''# list coefficients of all x^0..x^n in order''\n x ''':=''' 3\n accumulator ''':=''' 0\n '''for''' i '''in''' ''length''(coefficients) '''downto''' 1 '''do'''\n ''# Assumes 1-based indexing for arrays''\n accumulator ''':=''' ( accumulator * x ) + coefficients[i]\n '''done'''\n ''# accumulator now has the answer''\n\n'''Task Description'''\n:Create a routine that takes a list of coefficients of a polynomial in order of increasing powers of x; together with a value of x to compute its value at, and return the value of the polynomial at that value using [http://www.physics.utah.edu/~detar/lessons/c++/array/node1.html Horner's rule].\n\nCf. [[Formal power series]]\n\n", "solution": "#include \n\ndouble horner(double *coeffs, int s, double x)\n{\n int i;\n double res = 0.0;\n \n for(i=s-1; i >= 0; i--)\n {\n res = res * x + coeffs[i];\n }\n return res;\n}\n\n\nint main()\n{\n double coeffs[] = { -19.0, 7.0, -4.0, 6.0 };\n \n printf(\"%5.1f\\n\", horner(coeffs, sizeof(coeffs)/sizeof(double), 3.0));\n return 0;\n}"} +{"title": "Horner's rule for polynomial evaluation", "language": "JavaScript 1.8", "task": "A fast scheme for evaluating a polynomial such as:\n: -19+7x-4x^2+6x^3\\,\nwhen\n: x=3\\;.\nis to arrange the computation as follows:\n: ((((0) x + 6) x + (-4)) x + 7) x + (-19)\\;\nAnd compute the result from the innermost brackets outwards as in this pseudocode:\n coefficients ''':=''' [-19, 7, -4, 6] ''# list coefficients of all x^0..x^n in order''\n x ''':=''' 3\n accumulator ''':=''' 0\n '''for''' i '''in''' ''length''(coefficients) '''downto''' 1 '''do'''\n ''# Assumes 1-based indexing for arrays''\n accumulator ''':=''' ( accumulator * x ) + coefficients[i]\n '''done'''\n ''# accumulator now has the answer''\n\n'''Task Description'''\n:Create a routine that takes a list of coefficients of a polynomial in order of increasing powers of x; together with a value of x to compute its value at, and return the value of the polynomial at that value using [http://www.physics.utah.edu/~detar/lessons/c++/array/node1.html Horner's rule].\n\nCf. [[Formal power series]]\n\n", "solution": "function horner(coeffs, x) {\n return coeffs.reduceRight( function(acc, coeff) { return(acc * x + coeff) }, 0);\n}\nconsole.log(horner([-19,7,-4,6],3)); // ==> 128\n"} +{"title": "Horner's rule for polynomial evaluation", "language": "Python", "task": "A fast scheme for evaluating a polynomial such as:\n: -19+7x-4x^2+6x^3\\,\nwhen\n: x=3\\;.\nis to arrange the computation as follows:\n: ((((0) x + 6) x + (-4)) x + 7) x + (-19)\\;\nAnd compute the result from the innermost brackets outwards as in this pseudocode:\n coefficients ''':=''' [-19, 7, -4, 6] ''# list coefficients of all x^0..x^n in order''\n x ''':=''' 3\n accumulator ''':=''' 0\n '''for''' i '''in''' ''length''(coefficients) '''downto''' 1 '''do'''\n ''# Assumes 1-based indexing for arrays''\n accumulator ''':=''' ( accumulator * x ) + coefficients[i]\n '''done'''\n ''# accumulator now has the answer''\n\n'''Task Description'''\n:Create a routine that takes a list of coefficients of a polynomial in order of increasing powers of x; together with a value of x to compute its value at, and return the value of the polynomial at that value using [http://www.physics.utah.edu/~detar/lessons/c++/array/node1.html Horner's rule].\n\nCf. [[Formal power series]]\n\n", "solution": ">>> try: from functools import reduce\nexcept: pass\n\n>>> def horner(coeffs, x):\n\treturn reduce(lambda acc, c: acc * x + c, reversed(coeffs), 0)\n\n>>> horner( (-19, 7, -4, 6), 3)\n128"} +{"title": "ISBN13 check digit", "language": "C", "task": ";Task:\nValidate the check digit of an ISBN-13 code:\n::* \u00a0 Multiply every other digit by \u00a0'''3'''.\n::* \u00a0 Add these numbers and the other digits.\n::* \u00a0 Take the remainder of this number after division by \u00a0'''10'''.\n::* \u00a0 If it is \u00a0'''0''', \u00a0 the ISBN-13 check digit is correct.\n\n\nYou might use the following codes for testing:\n::::* \u00a0 978-0596528126 \u00a0 \u00a0 \u00a0 (good)\n::::* \u00a0 978-0596528120 \u00a0 \u00a0 \u00a0 \u00a0 (bad)\n::::* \u00a0 978-1788399081 \u00a0 \u00a0 \u00a0 (good)\n::::* \u00a0 978-1788399083 \u00a0 \u00a0 \u00a0 \u00a0 (bad)\n\n\nShow output here, on this page\n\n\n;See also:\n:* \u00a0 for details: \u00a0 [https://isbn-information.com/the-13-digit-isbn.html 13-digit ISBN method of validation]. \u00a0 \u00a0 \u00a0 (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": "ISBN13 check digit", "language": "Python", "task": ";Task:\nValidate the check digit of an ISBN-13 code:\n::* \u00a0 Multiply every other digit by \u00a0'''3'''.\n::* \u00a0 Add these numbers and the other digits.\n::* \u00a0 Take the remainder of this number after division by \u00a0'''10'''.\n::* \u00a0 If it is \u00a0'''0''', \u00a0 the ISBN-13 check digit is correct.\n\n\nYou might use the following codes for testing:\n::::* \u00a0 978-0596528126 \u00a0 \u00a0 \u00a0 (good)\n::::* \u00a0 978-0596528120 \u00a0 \u00a0 \u00a0 \u00a0 (bad)\n::::* \u00a0 978-1788399081 \u00a0 \u00a0 \u00a0 (good)\n::::* \u00a0 978-1788399083 \u00a0 \u00a0 \u00a0 \u00a0 (bad)\n\n\nShow output here, on this page\n\n\n;See also:\n:* \u00a0 for details: \u00a0 [https://isbn-information.com/the-13-digit-isbn.html 13-digit ISBN method of validation]. \u00a0 \u00a0 \u00a0 (installs cookies.)\n\n", "solution": "def is_isbn13(n):\n n = n.replace('-','').replace(' ', '')\n if len(n) != 13:\n return False\n product = (sum(int(ch) for ch in n[::2]) \n + sum(int(ch) * 3 for ch in n[1::2]))\n return product % 10 == 0\n\nif __name__ == '__main__':\n tests = '''\n978-1734314502\n978-1734314509\n978-1788399081\n978-1788399083'''.strip().split()\n for t in tests:\n print(f\"ISBN13 {t} validates {is_isbn13(t)}\")"} +{"title": "I before E except after C", "language": "C", "task": "The phrase \u00a0 \u00a0 \"I before E, except after C\" \u00a0 \u00a0 is a \nwidely known mnemonic which is supposed to help when spelling English words.\n\n\n;Task:\nUsing the word list from \u00a0 [http://wiki.puzzlers.org/pub/wordlists/unixdict.txt http://wiki.puzzlers.org/pub/wordlists/unixdict.txt], \ncheck if the two sub-clauses of the phrase are plausible individually:\n:::# \u00a0 ''\"I before E when not preceded by C\"''\n:::# \u00a0 ''\"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 [http://ucrel.lancs.ac.uk/bncfreq/lists/1_2_all_freq.txt 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* [http://news.bbc.co.uk/1/hi/education/8110573.stm Schools to rethink 'i before e'] - BBC news, 20 June 2009\n* [http://www.youtube.com/watch?v=duqlZXiIZqA I Before E Except After C] - QI Series 8 Ep 14, (humorous)\n* [http://ucrel.lancs.ac.uk/bncfreq/ Companion website] for the book: \"Word Frequencies in Written and Spoken English: based on the British National Corpus\".\n\n", "solution": "\n%{\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": "I before E except after C", "language": "Python", "task": "The phrase \u00a0 \u00a0 \"I before E, except after C\" \u00a0 \u00a0 is a \nwidely known mnemonic which is supposed to help when spelling English words.\n\n\n;Task:\nUsing the word list from \u00a0 [http://wiki.puzzlers.org/pub/wordlists/unixdict.txt http://wiki.puzzlers.org/pub/wordlists/unixdict.txt], \ncheck if the two sub-clauses of the phrase are plausible individually:\n:::# \u00a0 ''\"I before E when not preceded by C\"''\n:::# \u00a0 ''\"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 [http://ucrel.lancs.ac.uk/bncfreq/lists/1_2_all_freq.txt 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* [http://news.bbc.co.uk/1/hi/education/8110573.stm Schools to rethink 'i before e'] - BBC news, 20 June 2009\n* [http://www.youtube.com/watch?v=duqlZXiIZqA I Before E Except After C] - QI Series 8 Ep 14, (humorous)\n* [http://ucrel.lancs.ac.uk/bncfreq/ Companion website] for the book: \"Word Frequencies in Written and Spoken English: based on the British National Corpus\".\n\n", "solution": "import urllib.request\nimport re\n\nPLAUSIBILITY_RATIO = 2\n\ndef plausibility_check(comment, x, y):\n print('\\n Checking plausibility of: %s' % comment)\n if x > PLAUSIBILITY_RATIO * y:\n print(' PLAUSIBLE. As we have counts of %i vs %i, a ratio of %4.1f times'\n % (x, y, x / y))\n else:\n if x > y:\n print(' IMPLAUSIBLE. As although we have counts of %i vs %i, a ratio of %4.1f times does not make it plausible'\n % (x, y, x / y))\n else:\n print(' IMPLAUSIBLE, probably contra-indicated. As we have counts of %i vs %i, a ratio of %4.1f times'\n % (x, y, x / y))\n return x > PLAUSIBILITY_RATIO * y\n\ndef simple_stats(url='http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'):\n words = urllib.request.urlopen(url).read().decode().lower().split()\n cie = len({word for word in words if 'cie' in word})\n cei = len({word for word in words if 'cei' in word})\n not_c_ie = len({word for word in words if re.search(r'(^ie|[^c]ie)', word)})\n not_c_ei = len({word for word in words if re.search(r'(^ei|[^c]ei)', word)})\n return cei, cie, not_c_ie, not_c_ei\n\ndef print_result(cei, cie, not_c_ie, not_c_ei):\n if ( plausibility_check('I before E when not preceded by C', not_c_ie, not_c_ei)\n & plausibility_check('E before I when preceded by C', cei, cie) ):\n print('\\nOVERALL IT IS PLAUSIBLE!')\n else:\n print('\\nOVERALL IT IS IMPLAUSIBLE!')\n print('(To be plausible, one count must exceed another by %i times)' % PLAUSIBILITY_RATIO)\n\nprint('Checking plausibility of \"I before E except after C\":')\nprint_result(*simple_stats())"} +{"title": "Identity matrix", "language": "C", "task": "[[Category:Matrices]]\n\n;Task:\nBuild an \u00a0 identity matrix \u00a0 of a size known at run-time. \n\n\nAn ''identity matrix'' is a square matrix of size '''''n'' \u00d7 ''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* \u00a0 [[Spiral matrix]]\n* \u00a0 [[Zig-zag matrix]] \n* \u00a0 [[Ulam_spiral_(for_primes)]]\n\n", "solution": "\n#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": "Identity matrix", "language": "JavaScript", "task": "[[Category:Matrices]]\n\n;Task:\nBuild an \u00a0 identity matrix \u00a0 of a size known at run-time. \n\n\nAn ''identity matrix'' is a square matrix of size '''''n'' \u00d7 ''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* \u00a0 [[Spiral matrix]]\n* \u00a0 [[Zig-zag matrix]] \n* \u00a0 [[Ulam_spiral_(for_primes)]]\n\n", "solution": "(() => {\n\n // identityMatrix :: Int -> [[Int]]\n const identityMatrix = n =>\n Array.from({\n length: n\n }, (_, i) => Array.from({\n length: n\n }, (_, j) => i !== j ? 0 : 1));\n\n\n // ----------------------- TEST ------------------------\n return identityMatrix(5)\n .map(JSON.stringify)\n .join('\\n');\n})();"} +{"title": "Identity matrix", "language": "Python", "task": "[[Category:Matrices]]\n\n;Task:\nBuild an \u00a0 identity matrix \u00a0 of a size known at run-time. \n\n\nAn ''identity matrix'' is a square matrix of size '''''n'' \u00d7 ''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* \u00a0 [[Spiral matrix]]\n* \u00a0 [[Zig-zag matrix]] \n* \u00a0 [[Ulam_spiral_(for_primes)]]\n\n", "solution": "def identity(size):\n matrix = [[0]*size for i in range(size)]\n #matrix = [[0] * size] * size #Has a flaw. See http://stackoverflow.com/questions/240178/unexpected-feature-in-a-python-list-of-lists\n\n for i in range(size):\n matrix[i][i] = 1\n \n for rows in matrix:\n for elements in rows:\n print elements,\n print \"\""} +{"title": "Identity matrix", "language": "Python 3.7", "task": "[[Category:Matrices]]\n\n;Task:\nBuild an \u00a0 identity matrix \u00a0 of a size known at run-time. \n\n\nAn ''identity matrix'' is a square matrix of size '''''n'' \u00d7 ''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* \u00a0 [[Spiral matrix]]\n* \u00a0 [[Zig-zag matrix]] \n* \u00a0 [[Ulam_spiral_(for_primes)]]\n\n", "solution": "'''Identity matrices by maps and equivalent list comprehensions'''\n\nimport operator\n\n\n# idMatrix :: Int -> [[Int]]\ndef idMatrix(n):\n '''Identity matrix of order n,\n expressed as a nested map.\n '''\n eq = curry(operator.eq)\n xs = range(0, n)\n return list(map(\n lambda x: list(map(\n compose(int)(eq(x)),\n xs\n )),\n xs\n ))\n\n\n# idMatrix3 :: Int -> [[Int]]\ndef idMatrix2(n):\n '''Identity matrix of order n,\n expressed as a nested comprehension.\n '''\n xs = range(0, n)\n return ([int(x == y) for x in xs] for y in xs)\n\n\n# TEST ----------------------------------------------------\ndef main():\n '''\n Identity matrix of dimension five,\n by two different routes.\n '''\n for f in [idMatrix, idMatrix2]:\n print(\n '\\n' + f.__name__ + ':',\n '\\n\\n' + '\\n'.join(map(str, f(5))),\n )\n\n\n# GENERIC -------------------------------------------------\n\n# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n '''Right to left function composition.'''\n return lambda f: lambda x: g(f(x))\n\n\n# curry :: ((a, b) -> c) -> a -> b -> c\ndef curry(f):\n '''A curried function derived\n from an uncurried function.'''\n return lambda a: lambda b: f(a, b)\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} +{"title": "Idiomatically determine all the characters that can be used for symbols", "language": "Python", "task": "Idiomatically determine all the characters that can be used for ''symbols''.\nThe word ''symbols'' is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer programmer can choose to ''name'', but not being restricted to this list. ''Identifiers'' might be another name for ''symbols''.\n\nThe method should find the characters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other).\n\n;Task requirements\n\nDisplay the set of all the characters that can be used for symbols which can be used (allowed) by the computer program. \nYou may want to mention what hardware architecture is being used, and if applicable, the operating system.\n\nNote that most languages have additional restrictions on what characters can't be used for the first character of a variable or statement label, for instance. These type of restrictions needn't be addressed here (but can be mentioned).\n\n;See also\n* Idiomatically determine all the lowercase and uppercase letters.\n\n", "solution": "See [[Idiomatically_determine_all_the_lowercase_and_uppercase_letters#Python|String class isidentifier]].\n\n"} +{"title": "Idiomatically determine all the lowercase and uppercase letters", "language": "C", "task": "right\n\nIdiomatically determine all the lowercase and uppercase letters \u00a0 (of the Latin [English] alphabet) \u00a0 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::::::* \u00a0 lowercase letters \n::::::* \u00a0 uppercase letters\n\nthat can be used (allowed) by the computer program,\n\nwhere \u00a0 ''letter'' \u00a0 is a member of the Latin (English) alphabet: \u00a0 \u00a0 '''a''' \u2500\u2500\u25ba '''z''' \u00a0 \u00a0 and \u00a0 \u00a0 '''A''' \u2500\u2500\u25ba '''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": "Idiomatically determine all the lowercase and uppercase letters", "language": "Python", "task": "right\n\nIdiomatically determine all the lowercase and uppercase letters \u00a0 (of the Latin [English] alphabet) \u00a0 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::::::* \u00a0 lowercase letters \n::::::* \u00a0 uppercase letters\n\nthat can be used (allowed) by the computer program,\n\nwhere \u00a0 ''letter'' \u00a0 is a member of the Latin (English) alphabet: \u00a0 \u00a0 '''a''' \u2500\u2500\u25ba '''z''' \u00a0 \u00a0 and \u00a0 \u00a0 '''A''' \u2500\u2500\u25ba '''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": "classes = (str.isupper, str.islower, str.isalnum, str.isalpha, str.isdecimal,\n str.isdigit, str.isidentifier, str.isnumeric, str.isprintable,\n str.isspace, str.istitle)\n\nfor stringclass in classes:\n chars = ''.join(chr(i) for i in range(0x10FFFF+1) if stringclass(chr(i)))\n print('\\nString class %s has %i characters the first of which are:\\n %r'\n % (stringclass.__name__, len(chars), chars[:100]))"} +{"title": "Imaginary base numbers", "language": "C", "task": "Imaginary base numbers are a non-standard positional numeral system which uses an imaginary number as its radix. The most common is quater-imaginary with radix 2i. \n\n''The quater-imaginary numeral system was first proposed by [https://en.wikipedia.org/wiki/Donald_Knuth Donald Knuth] in 1955 as a submission for a high school science talent search. [http://www.fact-index.com/q/qu/quater_imaginary_base.html [Ref.]]''\n\nOther imaginary bases are possible too but are not as widely discussed and aren't specifically named.\n\n'''Task:''' Write a set of procedures (functions, subroutines, however they are referred to in your language) to convert base 10 numbers to an imaginary base and back. \n\nAt a minimum, support quater-imaginary (base 2i).\n\nFor extra kudos, support positive or negative bases 2i through 6i (or higher).\n\nAs a stretch goal, support converting non-integer numbers ( E.G. 227.65625+10.859375i ) to an imaginary base.\n\nSee [https://en.wikipedia.org/wiki/Quater-imaginary_base Wikipedia: Quater-imaginary_base] for more details. \n\nFor reference, here are some some decimal and complex numbers converted to quater-imaginary.\n\n\n\n\n\nBase 10\nBase 2i\n\n\n1\n\u00a01\n\n\n2\n\u00a02\n\n\n3\n\u00a03\n\n\n4\n\u00a010300\n\n\n5\n\u00a010301\n\n\n6\n\u00a010302\n\n\n7\n\u00a010303\n\n\n8\n\u00a010200\n\n\n9\n\u00a010201\n\n\n10\n\u00a010202\n\n\n11\n\u00a010203\n\n\n12\n\u00a010100\n\n\n13\n\u00a010101\n\n\n14\n\u00a010102\n\n\n15\n\u00a010103\n\n\n16\n\u00a010000\n\n\n\n\n\n\nBase 10\nBase 2i\n\n\n\u22121\n\u00a0103\n\n\n\u22122\n\u00a0102\n\n\n\u22123\n\u00a0101\n\n\n\u22124\n\u00a0100\n\n\n\u22125\n\u00a0203\n\n\n\u22126\n\u00a0202\n\n\n\u22127\n\u00a0201\n\n\n\u22128\n\u00a0200\n\n\n\u22129\n\u00a0303\n\n\n\u221210\n\u00a0302\n\n\n\u221211\n\u00a0301\n\n\n\u221212\n\u00a0300\n\n\n\u221213\n\u00a01030003\n\n\n\u221214\n\u00a01030002\n\n\n\u221215\n\u00a01030001\n\n\n\u221216\n\u00a01030000\n\n\n\n\n\n\nBase 10\nBase 2i\n\n\n1i\n10.2\n\n\n2i\n10.0\n\n\n3i\n20.2\n\n\n4i\n20.0\n\n\n5i\n30.2\n\n\n6i\n30.0\n\n\n7i\n103000.2\n\n\n8i\n103000.0\n\n\n9i\n103010.2\n\n\n10i\n103010.0\n\n\n11i\n103020.2\n\n\n12i\n103020.0\n\n\n13i\n103030.2\n\n\n14i\n103030.0\n\n\n15i\n102000.2\n\n\n16i\n102000.0\n\n\n\n\n\n\nBase 10\nBase 2i\n\n\n\u22121i\n0.2\n\n\n\u22122i\n1030.0\n\n\n\u22123i\n1030.2\n\n\n\u22124i\n1020.0\n\n\n\u22125i\n1020.2\n\n\n\u22126i\n1010.0\n\n\n\u22127i\n1010.2\n\n\n\u22128i\n1000.0\n\n\n\u22129i\n1000.2\n\n\n\u221210i\n2030.0\n\n\n\u221211i\n2030.2\n\n\n\u221212i\n2020.0\n\n\n\u221213i\n2020.2\n\n\n\u221214i\n2010.0\n\n\n\u221215i\n2010.2\n\n\n\u221216i\n2000.0\n\n\n\n\n\n", "solution": "#include \n#include \n#include \n\nint find(char *s, char c) {\n for (char *i = s; *i != 0; i++) {\n if (*i == c) {\n return i - s;\n }\n }\n return -1;\n}\n\nvoid reverse(char *b, char *e) {\n for (e--; b < e; b++, e--) {\n char t = *b;\n *b = *e;\n *e = t;\n }\n}\n\n//////////////////////////////////////////////////////\n\nstruct Complex {\n double rel, img;\n};\n\nvoid printComplex(struct Complex c) {\n printf(\"(%3.0f + %3.0fi)\", c.rel, c.img);\n}\n\nstruct Complex makeComplex(double rel, double img) {\n struct Complex c = { rel, img };\n return c;\n}\n\nstruct Complex addComplex(struct Complex a, struct Complex b) {\n struct Complex c = { a.rel + b.rel, a.img + b.img };\n return c;\n}\n\nstruct Complex mulComplex(struct Complex a, struct Complex b) {\n struct Complex c = { a.rel * b.rel - a.img * b.img, a.rel * b.img - a.img * b.rel };\n return c;\n}\n\nstruct Complex mulComplexD(struct Complex a, double b) {\n struct Complex c = { a.rel * b, a.img * b };\n return c;\n}\n\nstruct Complex negComplex(struct Complex a) {\n return mulComplexD(a, -1.0);\n}\n\nstruct Complex divComplex(struct Complex a, struct Complex b) {\n double re = a.rel * b.rel + a.img * b.img;\n double im = a.img * b.rel - a.rel * b.img;\n double d = b.rel * b.rel + b.img * b.img;\n struct Complex c = { re / d, im / d };\n return c;\n}\n\nstruct Complex inv(struct Complex c) {\n double d = c.rel * c.rel + c.img * c.img;\n struct Complex i = { c.rel / d, -c.img / d };\n return i;\n}\n\nconst struct Complex TWO_I = { 0.0, 2.0 };\nconst struct Complex INV_TWO_I = { 0.0, -0.5 };\n\n//////////////////////////////////////////////////////\n\nstruct QuaterImaginary {\n char *b2i;\n int valid;\n};\n\nstruct QuaterImaginary makeQuaterImaginary(char *s) {\n struct QuaterImaginary qi = { s, 0 }; // assume invalid until tested\n size_t i, valid = 1, cnt = 0;\n\n if (*s != 0) {\n for (i = 0; s[i] != 0; i++) {\n if (s[i] < '0' || '3' < s[i]) {\n if (s[i] == '.') {\n cnt++;\n } else {\n valid = 0;\n break;\n }\n }\n }\n if (valid && cnt > 1) {\n valid = 0;\n }\n }\n\n qi.valid = valid;\n return qi;\n}\n\nvoid printQuaterImaginary(struct QuaterImaginary qi) {\n if (qi.valid) {\n printf(\"%8s\", qi.b2i);\n } else {\n printf(\" ERROR \");\n }\n}\n\n//////////////////////////////////////////////////////\n\nstruct Complex qi2c(struct QuaterImaginary qi) {\n size_t len = strlen(qi.b2i);\n int pointPos = find(qi.b2i, '.');\n size_t posLen = (pointPos > 0) ? pointPos : len;\n struct Complex sum = makeComplex(0.0, 0.0);\n struct Complex prod = makeComplex(1.0, 0.0);\n size_t j;\n\n for (j = 0; j < posLen; j++) {\n double k = qi.b2i[posLen - 1 - j] - '0';\n if (k > 0.0) {\n sum = addComplex(sum, mulComplexD(prod, k));\n }\n prod = mulComplex(prod, TWO_I);\n }\n if (pointPos != -1) {\n prod = INV_TWO_I;\n for (j = posLen + 1; j < len; j++) {\n double k = qi.b2i[j] - '0';\n if (k > 0.0) {\n sum = addComplex(sum, mulComplexD(prod, k));\n }\n prod = mulComplex(prod, INV_TWO_I);\n }\n }\n return sum;\n}\n\n// only works properly if the real and imaginary parts are integral\nstruct QuaterImaginary c2qi(struct Complex c, char *out) {\n char *p = out;\n int re, im, fi;\n\n *p = 0;\n if (c.rel == 0.0 && c.img == 0.0) {\n return makeQuaterImaginary(\"0\");\n }\n\n re = (int)c.rel;\n im = (int)c.img;\n fi = -1;\n while (re != 0) {\n int rem = re % -4;\n re /= -4;\n if (rem < 0) {\n rem += 4;\n re++;\n }\n *p++ = rem + '0';\n *p++ = '0';\n *p = 0;\n }\n if (im != 0) {\n size_t index = 1;\n struct Complex fc = divComplex((struct Complex) { 0.0, c.img }, (struct Complex) { 0.0, 2.0 });\n double f = fc.rel;\n im = (int)ceil(f);\n f = -4.0 * (f - im);\n while (im != 0) {\n int rem = im % -4;\n im /= -4;\n if (rem < 0) {\n rem += 4;\n im++;\n }\n if (index < (p - out)) {\n out[index] = rem + '0';\n } else {\n *p++ = '0';\n *p++ = rem + '0';\n *p = 0;\n }\n index += 2;\n }\n fi = (int)f;\n }\n\n reverse(out, p);\n if (fi != -1) {\n *p++ = '.';\n *p++ = fi + '0';\n *p = 0;\n }\n while (out[0] == '0' && out[1] != '.') {\n size_t i;\n for (i = 0; out[i] != 0; i++) {\n out[i] = out[i + 1];\n }\n }\n if (*out == '.') {\n reverse(out, p);\n *p++ = '0';\n *p = 0;\n reverse(out, p);\n }\n return makeQuaterImaginary(out);\n}\n\n//////////////////////////////////////////////////////\n\nint main() {\n char buffer[16];\n int i;\n\n for (i = 1; i <= 16; i++) {\n struct Complex c1 = { i, 0.0 };\n struct QuaterImaginary qi = c2qi(c1, buffer);\n struct Complex c2 = qi2c(qi);\n printComplex(c1);\n printf(\" -> \");\n printQuaterImaginary(qi);\n printf(\" -> \");\n printComplex(c2);\n\n printf(\" \");\n\n c1 = negComplex(c1);\n qi = c2qi(c1, buffer);\n c2 = qi2c(qi);\n printComplex(c1);\n printf(\" -> \");\n printQuaterImaginary(qi);\n printf(\" -> \");\n printComplex(c2);\n\n printf(\"\\n\");\n }\n\n printf(\"\\n\");\n\n for (i = 1; i <= 16; i++) {\n struct Complex c1 = { 0.0, i };\n struct QuaterImaginary qi = c2qi(c1, buffer);\n struct Complex c2 = qi2c(qi);\n printComplex(c1);\n printf(\" -> \");\n printQuaterImaginary(qi);\n printf(\" -> \");\n printComplex(c2);\n\n printf(\" \");\n\n c1 = negComplex(c1);\n qi = c2qi(c1, buffer);\n c2 = qi2c(qi);\n printComplex(c1);\n printf(\" -> \");\n printQuaterImaginary(qi);\n printf(\" -> \");\n printComplex(c2);\n\n printf(\"\\n\");\n }\n\n return 0;\n}"} +{"title": "Imaginary base numbers", "language": "Python", "task": "Imaginary base numbers are a non-standard positional numeral system which uses an imaginary number as its radix. The most common is quater-imaginary with radix 2i. \n\n''The quater-imaginary numeral system was first proposed by [https://en.wikipedia.org/wiki/Donald_Knuth Donald Knuth] in 1955 as a submission for a high school science talent search. [http://www.fact-index.com/q/qu/quater_imaginary_base.html [Ref.]]''\n\nOther imaginary bases are possible too but are not as widely discussed and aren't specifically named.\n\n'''Task:''' Write a set of procedures (functions, subroutines, however they are referred to in your language) to convert base 10 numbers to an imaginary base and back. \n\nAt a minimum, support quater-imaginary (base 2i).\n\nFor extra kudos, support positive or negative bases 2i through 6i (or higher).\n\nAs a stretch goal, support converting non-integer numbers ( E.G. 227.65625+10.859375i ) to an imaginary base.\n\nSee [https://en.wikipedia.org/wiki/Quater-imaginary_base Wikipedia: Quater-imaginary_base] for more details. \n\nFor reference, here are some some decimal and complex numbers converted to quater-imaginary.\n\n\n\n\n\nBase 10\nBase 2i\n\n\n1\n\u00a01\n\n\n2\n\u00a02\n\n\n3\n\u00a03\n\n\n4\n\u00a010300\n\n\n5\n\u00a010301\n\n\n6\n\u00a010302\n\n\n7\n\u00a010303\n\n\n8\n\u00a010200\n\n\n9\n\u00a010201\n\n\n10\n\u00a010202\n\n\n11\n\u00a010203\n\n\n12\n\u00a010100\n\n\n13\n\u00a010101\n\n\n14\n\u00a010102\n\n\n15\n\u00a010103\n\n\n16\n\u00a010000\n\n\n\n\n\n\nBase 10\nBase 2i\n\n\n\u22121\n\u00a0103\n\n\n\u22122\n\u00a0102\n\n\n\u22123\n\u00a0101\n\n\n\u22124\n\u00a0100\n\n\n\u22125\n\u00a0203\n\n\n\u22126\n\u00a0202\n\n\n\u22127\n\u00a0201\n\n\n\u22128\n\u00a0200\n\n\n\u22129\n\u00a0303\n\n\n\u221210\n\u00a0302\n\n\n\u221211\n\u00a0301\n\n\n\u221212\n\u00a0300\n\n\n\u221213\n\u00a01030003\n\n\n\u221214\n\u00a01030002\n\n\n\u221215\n\u00a01030001\n\n\n\u221216\n\u00a01030000\n\n\n\n\n\n\nBase 10\nBase 2i\n\n\n1i\n10.2\n\n\n2i\n10.0\n\n\n3i\n20.2\n\n\n4i\n20.0\n\n\n5i\n30.2\n\n\n6i\n30.0\n\n\n7i\n103000.2\n\n\n8i\n103000.0\n\n\n9i\n103010.2\n\n\n10i\n103010.0\n\n\n11i\n103020.2\n\n\n12i\n103020.0\n\n\n13i\n103030.2\n\n\n14i\n103030.0\n\n\n15i\n102000.2\n\n\n16i\n102000.0\n\n\n\n\n\n\nBase 10\nBase 2i\n\n\n\u22121i\n0.2\n\n\n\u22122i\n1030.0\n\n\n\u22123i\n1030.2\n\n\n\u22124i\n1020.0\n\n\n\u22125i\n1020.2\n\n\n\u22126i\n1010.0\n\n\n\u22127i\n1010.2\n\n\n\u22128i\n1000.0\n\n\n\u22129i\n1000.2\n\n\n\u221210i\n2030.0\n\n\n\u221211i\n2030.2\n\n\n\u221212i\n2020.0\n\n\n\u221213i\n2020.2\n\n\n\u221214i\n2010.0\n\n\n\u221215i\n2010.2\n\n\n\u221216i\n2000.0\n\n\n\n\n\n", "solution": "import math\nimport re\n\ndef inv(c):\n denom = c.real * c.real + c.imag * c.imag\n return complex(c.real / denom, -c.imag / denom)\n\nclass QuaterImaginary:\n twoI = complex(0, 2)\n invTwoI = inv(twoI)\n\n def __init__(self, str):\n if not re.match(\"^[0123.]+$\", str) or str.count('.') > 1:\n raise Exception('Invalid base 2i number')\n self.b2i = str\n\n def toComplex(self):\n pointPos = self.b2i.find('.')\n posLen = len(self.b2i) if (pointPos < 0) else pointPos\n sum = complex(0, 0)\n prod = complex(1, 0)\n for j in xrange(0, posLen):\n k = int(self.b2i[posLen - 1 - j])\n if k > 0:\n sum += prod * k\n prod *= QuaterImaginary.twoI\n if pointPos != -1:\n prod = QuaterImaginary.invTwoI\n for j in xrange(posLen + 1, len(self.b2i)):\n k = int(self.b2i[j])\n if k > 0:\n sum += prod * k\n prod *= QuaterImaginary.invTwoI\n return sum\n\n def __str__(self):\n return str(self.b2i)\n\ndef toQuaterImaginary(c):\n if c.real == 0.0 and c.imag == 0.0:\n return QuaterImaginary(\"0\")\n\n re = int(c.real)\n im = int(c.imag)\n fi = -1\n ss = \"\"\n while re != 0:\n re, rem = divmod(re, -4)\n if rem < 0:\n rem += 4\n re += 1\n ss += str(rem) + '0'\n if im != 0:\n f = c.imag / 2\n im = int(math.ceil(f))\n f = -4 * (f - im)\n index = 1\n while im != 0:\n im, rem = divmod(im, -4)\n if rem < 0:\n rem += 4\n im += 1\n if index < len(ss):\n ss[index] = str(rem)\n else:\n ss += '0' + str(rem)\n index = index + 2\n fi = int(f)\n ss = ss[::-1]\n if fi != -1:\n ss += '.' + str(fi)\n ss = ss.lstrip('0')\n if ss[0] == '.':\n ss = '0' + ss\n return QuaterImaginary(ss)\n\nfor i in xrange(1,17):\n c1 = complex(i, 0)\n qi = toQuaterImaginary(c1)\n c2 = qi.toComplex()\n print \"{0:8} -> {1:>8} -> {2:8} \".format(c1, qi, c2),\n\n c1 = -c1\n qi = toQuaterImaginary(c1)\n c2 = qi.toComplex()\n print \"{0:8} -> {1:>8} -> {2:8}\".format(c1, qi, c2)\nprint\n\nfor i in xrange(1,17):\n c1 = complex(0, i)\n qi = toQuaterImaginary(c1)\n c2 = qi.toComplex()\n print \"{0:8} -> {1:>8} -> {2:8} \".format(c1, qi, c2),\n\n c1 = -c1\n qi = toQuaterImaginary(c1)\n c2 = qi.toComplex()\n print \"{0:8} -> {1:>8} -> {2:8}\".format(c1, qi, c2)\n\nprint \"done\"\n"} +{"title": "Include a file", "language": "C", "task": ";Task:\nDemonstrate 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": "Include a file", "language": "JavaScript", "task": ";Task:\nDemonstrate 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": "var s = document.createElement('script');\ns.type = 'application/javascript';\n\n// path to the desired file\ns.src = 'http://code.jquery.com/jquery-1.6.2.js';\ndocument.body.appendChild(s);"} +{"title": "Increasing gaps between consecutive Niven numbers", "language": "C", "task": "Note: \u00a0 '''Niven''' \u00a0 numbers are also called \u00a0 '''Harshad''' \u00a0 numbers.\n:::: \u00a0 They are also called\u00a0 \u00a0 '''multidigital''' \u00a0 numbers.\n\n\n'''Niven''' numbers are positive integers which are evenly divisible by the sum of its\ndigits \u00a0 (expressed in base ten).\n\n''Evenly divisible'' \u00a0 means \u00a0 ''divisible with no remainder''.\n\n\n;Task:\n:* \u00a0 find the gap (difference) of a Niven number from the previous Niven number\n:* \u00a0 if the gap is \u00a0 ''larger'' \u00a0 than the (highest) previous gap, \u00a0 then:\n:::* \u00a0 show the index (occurrence) of the gap \u00a0 \u00a0 (the 1st gap is \u00a0 '''1''')\n:::* \u00a0 show the index of the Niven number that starts the gap \u00a0 \u00a0 (1st Niven number is \u00a0 '''1''', \u00a0 33rd Niven number is \u00a0 '''100''')\n:::* \u00a0 show the Niven number that starts the gap\n:::* \u00a0 show all numbers with comma separators where appropriate \u00a0 (optional)\n:::* \u00a0 I.E.: \u00a0 the gap size of \u00a0 '''60''' \u00a0 starts at the \u00a0 33,494th \u00a0 Niven number which is Niven number \u00a0 '''297,864'''\n:* \u00a0 show all increasing gaps up to the \u00a0 ten millionth \u00a0 ('''10,000,000th''') \u00a0 Niven number\n:* \u00a0 (optional) \u00a0 show all gaps up to whatever limit is feasible/practical/realistic/reasonable/sensible/viable on your computer\n:* \u00a0 show all output here, on this page\n\n\n;Related task:\n:* \u00a0 [https://rosettacode.org/wiki/Harshad_or_Niven_series Harshad or Niven series].\n\n\n;Also see:\n:* \u00a0 [https://cs.uwaterloo.ca/journals/JIS/VOL6/Doyon/doyon.html Journal of Integer Sequences, Vol. 6 (2004), Article 03.2.5, Large and Small Gaps Between Consecutive Niven Numbers].\n:* \u00a0 [https://cs.uwaterloo.ca/journals/JIS/VOL6/Doyon/doyon.pdf (PDF) version of the (above) article by Doyon].\n\n", "solution": "#include \n#include \n#include \n#include \n\n// Returns the sum of the digits of n given the\n// sum of the digits of n - 1\nuint64_t digit_sum(uint64_t n, uint64_t sum) {\n ++sum;\n while (n > 0 && n % 10 == 0) {\n sum -= 9;\n n /= 10;\n }\n return sum;\n}\n\ninline bool divisible(uint64_t n, uint64_t d) {\n if ((d & 1) == 0 && (n & 1) == 1)\n return false;\n return n % d == 0;\n}\n\nint main() {\n setlocale(LC_ALL, \"\");\n\n uint64_t previous = 1, gap = 0, sum = 0;\n int niven_index = 0, gap_index = 1;\n\n printf(\"Gap index Gap Niven index Niven number\\n\");\n for (uint64_t niven = 1; gap_index <= 32; ++niven) {\n sum = digit_sum(niven, sum);\n if (divisible(niven, sum)) {\n if (niven > previous + gap) {\n gap = niven - previous;\n printf(\"%'9d %'4llu %'14d %'15llu\\n\", gap_index++,\n gap, niven_index, previous);\n }\n previous = niven;\n ++niven_index;\n }\n }\n return 0;\n}"} +{"title": "Increasing gaps between consecutive Niven numbers", "language": "Python", "task": "Note: \u00a0 '''Niven''' \u00a0 numbers are also called \u00a0 '''Harshad''' \u00a0 numbers.\n:::: \u00a0 They are also called\u00a0 \u00a0 '''multidigital''' \u00a0 numbers.\n\n\n'''Niven''' numbers are positive integers which are evenly divisible by the sum of its\ndigits \u00a0 (expressed in base ten).\n\n''Evenly divisible'' \u00a0 means \u00a0 ''divisible with no remainder''.\n\n\n;Task:\n:* \u00a0 find the gap (difference) of a Niven number from the previous Niven number\n:* \u00a0 if the gap is \u00a0 ''larger'' \u00a0 than the (highest) previous gap, \u00a0 then:\n:::* \u00a0 show the index (occurrence) of the gap \u00a0 \u00a0 (the 1st gap is \u00a0 '''1''')\n:::* \u00a0 show the index of the Niven number that starts the gap \u00a0 \u00a0 (1st Niven number is \u00a0 '''1''', \u00a0 33rd Niven number is \u00a0 '''100''')\n:::* \u00a0 show the Niven number that starts the gap\n:::* \u00a0 show all numbers with comma separators where appropriate \u00a0 (optional)\n:::* \u00a0 I.E.: \u00a0 the gap size of \u00a0 '''60''' \u00a0 starts at the \u00a0 33,494th \u00a0 Niven number which is Niven number \u00a0 '''297,864'''\n:* \u00a0 show all increasing gaps up to the \u00a0 ten millionth \u00a0 ('''10,000,000th''') \u00a0 Niven number\n:* \u00a0 (optional) \u00a0 show all gaps up to whatever limit is feasible/practical/realistic/reasonable/sensible/viable on your computer\n:* \u00a0 show all output here, on this page\n\n\n;Related task:\n:* \u00a0 [https://rosettacode.org/wiki/Harshad_or_Niven_series Harshad or Niven series].\n\n\n;Also see:\n:* \u00a0 [https://cs.uwaterloo.ca/journals/JIS/VOL6/Doyon/doyon.html Journal of Integer Sequences, Vol. 6 (2004), Article 03.2.5, Large and Small Gaps Between Consecutive Niven Numbers].\n:* \u00a0 [https://cs.uwaterloo.ca/journals/JIS/VOL6/Doyon/doyon.pdf (PDF) version of the (above) article by Doyon].\n\n", "solution": "\n\"\"\"\n\nPython implementation of\n\nhttp://rosettacode.org/wiki/Increasing_gaps_between_consecutive_Niven_numbers\n\n\"\"\"\n\n# based on C example\n\n# Returns the sum of the digits of n given the\n# sum of the digits of n - 1\ndef digit_sum(n, sum):\n sum += 1\n while n > 0 and n % 10 == 0:\n sum -= 9\n n /= 10\n \n return sum\n \nprevious = 1\ngap = 0\nsum = 0\nniven_index = 0\ngap_index = 1\n \nprint(\"Gap index Gap Niven index Niven number\")\n\nniven = 1\n\nwhile gap_index <= 22:\n sum = digit_sum(niven, sum)\n if niven % sum == 0:\n if niven > previous + gap:\n gap = niven - previous;\n print('{0:9d} {1:4d} {2:13d} {3:11d}'.format(gap_index, gap, niven_index, previous))\n gap_index += 1\n previous = niven\n niven_index += 1\n niven += 1\n"} +{"title": "Index finite lists of positive integers", "language": "Python", "task": "It is known that the set of finite lists of positive integers is \u00a0 countable. \n\nThis means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers. \n\n\n;Task:\nImplement such a mapping:\n:* \u00a0 write a function \u00a0 \u00a0 ''rank'' \u00a0 \u00a0 which assigns an integer to any finite, arbitrarily long list of arbitrary large positive integers.\n:* \u00a0 write a function \u00a0 ''unrank'' \u00a0 which is the \u00a0 ''rank'' \u00a0 inverse function.\n\n\nDemonstrate your solution by:\n:* \u00a0 picking a random-length list of random positive integers\n:* \u00a0 turn it into an integer, \u00a0 and \n:* \u00a0 get the list back.\n\n\nThere are many ways to do this. \u00a0 Feel free to choose any one you like.\n\n\n;Extra credit:\nMake the \u00a0 ''rank'' \u00a0 function as a \u00a0 bijection \u00a0 and show \u00a0 ''unrank(n)'' \u00a0 for \u00a0 '''n''' \u00a0 varying from \u00a0 '''0''' \u00a0 to \u00a0 '''10'''.\n\n", "solution": "def rank(x): return int('a'.join(map(str, [1] + x)), 11)\n\ndef unrank(n):\n\ts = ''\n\twhile n: s,n = \"0123456789a\"[n%11] + s, n//11\n\treturn map(int, s.split('a'))[1:]\n\nl = [1, 2, 3, 10, 100, 987654321]\nprint l\nn = rank(l)\nprint n\nl = unrank(n)\nprint l"} +{"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; \u00a0 usually \u00a0 '''8'''-bit, \u00a0 '''16'''-bit, \u00a0 '''32'''-bit, \u00a0 or \u00a0 '''64'''-bit.\nThe integers supported by such a type can be \u00a0 ''signed'' \u00a0 or \u00a0 ''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:* \u00a0 When the integer overflow does trigger an exception show how the exception is caught.\n:* \u00a0 When the integer overflow produces some value, \u00a0 print it.\n:* \u00a0 It should be explicitly noted when an integer overflow is not recognized, \u00a0 the program continues with wrong results.\n:* \u00a0 This should be done for signed and unsigned integers of various sizes supported by the computer programming language.\n:* \u00a0 When a language has no fixed size integer type, \u00a0 or when no integer overflow can occur for other reasons, \u00a0 this should be noted.\n:* \u00a0 It is okay to mention, \u00a0 when a language supports unlimited precision integers, \u00a0 but this task is NOT the place to demonstrate the \u00a0 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 overflow", "language": "Python", "task": "Some languages support one or more integer types of the underlying processor.\n\nThis integer types have fixed size; \u00a0 usually \u00a0 '''8'''-bit, \u00a0 '''16'''-bit, \u00a0 '''32'''-bit, \u00a0 or \u00a0 '''64'''-bit.\nThe integers supported by such a type can be \u00a0 ''signed'' \u00a0 or \u00a0 ''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:* \u00a0 When the integer overflow does trigger an exception show how the exception is caught.\n:* \u00a0 When the integer overflow produces some value, \u00a0 print it.\n:* \u00a0 It should be explicitly noted when an integer overflow is not recognized, \u00a0 the program continues with wrong results.\n:* \u00a0 This should be done for signed and unsigned integers of various sizes supported by the computer programming language.\n:* \u00a0 When a language has no fixed size integer type, \u00a0 or when no integer overflow can occur for other reasons, \u00a0 this should be noted.\n:* \u00a0 It is okay to mention, \u00a0 when a language supports unlimited precision integers, \u00a0 but this task is NOT the place to demonstrate the \u00a0 capabilities of unlimited precision integers.\n\n", "solution": "Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (Intel)] on win32\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> for calc in ''' -(-2147483647-1)\n 2000000000 + 2000000000\n -2147483647 - 2147483647\n 46341 * 46341\n (-2147483647-1) / -1'''.split('\\n'):\n\tans = eval(calc)\n\tprint('Expression: %r evaluates to %s of type %s'\n\t % (calc.strip(), ans, type(ans)))\n\n\t\nExpression: '-(-2147483647-1)' evaluates to 2147483648 of type \nExpression: '2000000000 + 2000000000' evaluates to 4000000000 of type \nExpression: '-2147483647 - 2147483647' evaluates to -4294967294 of type \nExpression: '46341 * 46341' evaluates to 2147488281 of type \nExpression: '(-2147483647-1) / -1' evaluates to 2147483648.0 of type \n>>> "} +{"title": "Integer sequence", "language": "C", "task": ";Task:\nCreate a program that, when run, would display all integers from \u00a0 '''1''' \u00a0 to \u00a0 ''' \u221e ''' \u00a0 (or any relevant implementation limit), \u00a0 in sequence \u00a0 (i.e. \u00a0 1, 2, 3, 4, etc) \u00a0 if given enough time.\n\n\nAn example may not be able to reach arbitrarily-large numbers based on implementations limits. \u00a0 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. \u00a0 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\u2014or 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": "Integer sequence", "language": "JavaScript", "task": ";Task:\nCreate a program that, when run, would display all integers from \u00a0 '''1''' \u00a0 to \u00a0 ''' \u221e ''' \u00a0 (or any relevant implementation limit), \u00a0 in sequence \u00a0 (i.e. \u00a0 1, 2, 3, 4, etc) \u00a0 if given enough time.\n\n\nAn example may not be able to reach arbitrarily-large numbers based on implementations limits. \u00a0 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. \u00a0 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\u2014or lack thereof.\n\n", "solution": "var i = 0n;\n\nwhile (true)\n document.write(++i + ' ');"} +{"title": "Integer sequence", "language": "Python", "task": ";Task:\nCreate a program that, when run, would display all integers from \u00a0 '''1''' \u00a0 to \u00a0 ''' \u221e ''' \u00a0 (or any relevant implementation limit), \u00a0 in sequence \u00a0 (i.e. \u00a0 1, 2, 3, 4, etc) \u00a0 if given enough time.\n\n\nAn example may not be able to reach arbitrarily-large numbers based on implementations limits. \u00a0 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. \u00a0 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\u2014or lack thereof.\n\n", "solution": "from itertools import count\n\nfor i in count(): \n print(i)"} +{"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": "Intersecting number wheels", "language": "JavaScript", "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": "(() => {\n 'use strict';\n\n // main :: IO ()\n const main = () => {\n\n // clockWorkTick :: Dict -> (Dict, Char)\n const clockWorkTick = wheelMap => {\n // The new configuration of the wheels, tupled with\n // a digit found by recursive descent from a single\n // click of the first wheel.\n const click = wheels => wheelName => {\n const\n wheel = wheels[wheelName] || ['?'],\n v = wheel[0];\n return bool(click)(Tuple)(isDigit(v) || '?' === v)(\n insertDict(wheelName)(\n leftRotate(wheel)\n )(wheels)\n )(v);\n };\n return click(wheelMap)('A');\n };\n\n // leftRotate ::[a] -> [a]\n const leftRotate = xs =>\n // The head of the list appended\n // to the tail of of the list.\n 0 < xs.length ? (\n xs.slice(1).concat(xs[0])\n ) : [];\n\n\n // TEST -------------------------------------------\n // State of each wheel-set after 20 clicks,\n // paired with the resulting series of characters.\n\n const tuple = uncurry(Tuple);\n const wheelLists = [\n [tuple('A', '123')],\n [tuple('A', '1B2'), tuple('B', '34')],\n [tuple('A', '1DD'), tuple('D', '678')],\n [tuple('A', '1BC'), tuple('B', '34'), tuple('C', '5B')]\n ];\n\n console.log([\n 'Series and state of each wheel-set after 20 clicks:\\n',\n unlines(\n map(tuples => showWheels(\n mapAccumL(\n compose(constant, clockWorkTick)\n )(dictFromList(tuples))(replicate(20)(''))\n ))(wheelLists)\n ),\n '\\nInitial state of each wheel-set:\\n',\n map(map(compose(\n JSON.stringify,\n dictFromList,\n x => [Array.from(x)]\n )))(wheelLists).join('\\n')\n ].join('\\n'));\n };\n\n // DISPLAY FORMATTING ---------------------------------\n\n // showWheels :: (Dict, [Char]) -> String\n const showWheels = tpl =>\n JSON.stringify(\n Array.from(secondArrow(concat)(tpl))\n );\n\n // GENERIC FUNCTIONS ----------------------------------\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = a => b => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // bool :: a -> a -> Bool -> a\n const bool = f => t => p =>\n p ? t : f;\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (...fs) =>\n x => fs.reduceRight((a, f) => f(a), x);\n\n // concat :: [[a]] -> [a]\n // concat :: [String] -> String\n const concat = xs =>\n 0 < xs.length ? (() => {\n const unit = 'string' !== typeof xs[0] ? (\n []\n ) : '';\n return unit.concat.apply(unit, xs);\n })() : [];\n\n // constant :: a -> b -> a\n const constant = k => _ => k;\n\n // dictFromList :: [(k, v)] -> Dict\n const dictFromList = kvs =>\n Object.fromEntries(kvs);\n\n // secondArrow :: (a -> b) -> ((c, a) -> (c, b))\n const secondArrow = f => xy =>\n // A function over a simple value lifted\n // to a function over a tuple.\n // f (a, b) -> (a, f(b))\n Tuple(xy[0])(\n f(xy[1])\n );\n\n // insertDict :: String -> a -> Dict -> Dict\n const insertDict = k => v => dct =>\n Object.assign({}, dct, {\n [k]: v\n });\n\n // isDigit :: Char -> Bool\n const isDigit = c => {\n const n = c.codePointAt(0);\n return 48 <= n && 57 >= n;\n };\n\n // map :: (a -> b) -> [a] -> [b]\n const map = f => xs =>\n (Array.isArray(xs) ? (\n xs\n ) : xs.split('')).map(f);\n\n // Map-accumulation is a combination of map and a catamorphism;\n // it applies a function to each element of a list, passing an\n // accumulating parameter from left to right, and returning a final\n // value of this accumulator together with the new list.\n\n // mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])\n const mapAccumL = f => acc => xs =>\n xs.reduce((a, x) => {\n const pair = f(a[0])(x);\n return Tuple(pair[0])(a[1].concat(pair[1]));\n }, Tuple(acc)([]));\n\n // replicate :: Int -> a -> [a]\n const replicate = n => x =>\n Array.from({\n length: n\n }, () => x);\n\n // uncurry :: (a -> b -> c) -> ((a, b) -> c)\n const uncurry = f =>\n (x, y) => f(x)(y);\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // MAIN ---\n return main();\n})();"} +{"title": "Intersecting number wheels", "language": "Python", "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": "from itertools import islice\n\nclass INW():\n \"\"\"\n Intersecting Number Wheels\n represented as a dict mapping\n name to tuple of values.\n \"\"\"\n\n def __init__(self, **wheels):\n self._wheels = wheels\n self.isect = {name: self._wstate(name, wheel) \n for name, wheel in wheels.items()}\n \n def _wstate(self, name, wheel):\n \"Wheel state holder\"\n assert all(val in self._wheels for val in wheel if type(val) == str), \\\n f\"ERROR: Interconnected wheel not found in {name}: {wheel}\"\n pos = 0\n ln = len(wheel)\n while True:\n nxt, pos = wheel[pos % ln], pos + 1\n yield next(self.isect[nxt]) if type(nxt) == str else nxt\n \n def __iter__(self):\n base_wheel_name = next(self.isect.__iter__())\n yield from self.isect[base_wheel_name]\n \n def __repr__(self):\n return f\"{self.__class__.__name__}({self._wheels})\"\n \n def __str__(self):\n txt = \"Intersecting Number Wheel group:\"\n for name, wheel in self._wheels.items():\n txt += f\"\\n {name+':':4}\" + ' '.join(str(v) for v in wheel)\n return txt\n\ndef first(iter, n):\n \"Pretty print first few terms\"\n return ' '.join(f\"{nxt}\" for nxt in islice(iter, n))\n\nif __name__ == '__main__':\n for group in[\n {'A': (1, 2, 3)},\n {'A': (1, 'B', 2),\n 'B': (3, 4)},\n {'A': (1, 'D', 'D'),\n 'D': (6, 7, 8)},\n {'A': (1, 'B', 'C'),\n 'B': (3, 4),\n 'C': (5, 'B')}, # 135143145...\n ]:\n w = INW(**group)\n print(f\"{w}\\n Generates:\\n {first(w, 20)} ...\\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": "\nmain()\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": "Isqrt (integer square root) of X", "language": "C", "task": "Sometimes a function is needed to find the integer square root of \u00a0 '''X''', \u00a0 where \u00a0 '''X''' \u00a0 can be a\nreal non\u2500negative number.\n\nOften \u00a0 '''X''' \u00a0 is actually a non\u2500negative integer.\n\nFor the purposes of this task, \u00a0 '''X''' \u00a0 can be an integer or a real number, \u00a0 but if it\nsimplifies things in your computer programming language, \u00a0 assume it's an integer.\n\n\nOne of the most common uses of \u00a0 '''Isqrt''' \u00a0 is in the division of an integer by all factors \u00a0 (or\nprimes) \u00a0 up to the \u00a0 \n\u221a\u00a0X\u00a0 \u00a0 of that\ninteger, \u00a0 either to find the factors of that integer, \u00a0 or to determine primality.\n\n\nAn alternative method for finding the \u00a0 '''Isqrt''' \u00a0 of a number is to\ncalculate: \u00a0 \u00a0 \u00a0 floor( sqrt(X) ) \n::* \u00a0 where \u00a0 '''sqrt''' \u00a0\u00a0 is the \u00a0 square root \u00a0 function for non\u2500negative real numbers, \u00a0 and\n::* \u00a0 where \u00a0 '''floor''' \u00a0 is the \u00a0 floor \u00a0 function for real numbers.\n\n\nIf the hardware supports the computation of (real) square roots, \u00a0 the above method might be a faster method for\nsmall numbers that don't have very many significant (decimal) digits.\n\nHowever, floating point arithmetic is limited in the number of \u00a0 (binary or decimal) \u00a0 digits that it can support.\n\n\n;Pseudo\u2500code using quadratic residue:\nFor this task, the integer square root of a non\u2500negative number will be computed using a version\nof \u00a0 ''quadratic residue'', \u00a0 which has the advantage that no \u00a0 ''floating point'' \u00a0 calculations are\nused, \u00a0 only integer arithmetic. \n\nFurthermore, the two divisions can be performed by bit shifting, \u00a0 and the one multiplication can also be be performed by bit shifting or additions.\n\nThe disadvantage is the limitation of the size of the largest integer that a particular computer programming language can support.\n\n\nPseudo\u2500code of a procedure for finding the integer square root of \u00a0 '''X''' \u00a0 \u00a0 \u00a0 (all variables are integers):\n q \u25c4\u2500\u2500 1 /*initialize Q to unity. */\n /*find a power of 4 that's greater than X.*/\n perform while q <= x /*perform while Q <= X. */\n q \u25c4\u2500\u2500 q * 4 /*multiply Q by four. */\n end /*perform*/\n /*Q is now greater than X.*/\n z \u25c4\u2500\u2500 x /*set Z to the value of X.*/\n r \u25c4\u2500\u2500 0 /*initialize R to zero. */\n perform while q > 1 /*perform while Q > unity. */\n q \u25c4\u2500\u2500 q \u00f7 4 /*integer divide by four. */\n t \u25c4\u2500\u2500 z - r - q /*compute value of T. */\n r \u25c4\u2500\u2500 r \u00f7 2 /*integer divide by two. */\n if t >= 0 then do \n z \u25c4\u2500\u2500 t /*set Z to value of T. */\n r \u25c4\u2500\u2500 r + q /*compute new value of R. */\n end\n end /*perform*/\n /*R is now the Isqrt(X). */\n \n /* Sidenote: Also, Z is now the remainder after square root (i.e. */\n /* R^2 + Z = X, so if Z = 0 then X is a perfect square). */\n\nAnother version for the (above) \u00a0 1st \u00a0 '''perform''' \u00a0 is:\n perform until q > X /*perform until Q > X. */\n q \u25c4\u2500\u2500 q * 4 /*multiply Q by four. */\n end /*perform*/\n\n\nInteger square roots of some values:\n Isqrt( 0) is 0 Isqrt(60) is 7 Isqrt( 99) is 9\n Isqrt( 1) is 1 Isqrt(61) is 7 Isqrt(100) is 10\n Isqrt( 2) is 1 Isqrt(62) is 7 Isqrt(102) is 10\n Isqrt( 3) is 1 Isqrt(63) is 7\n Isqrt( 4) is 2 Isqrt(64) is 8 Isqet(120) is 10\n Isqrt( 5) is 2 Isqrt(65) is 8 Isqrt(121) is 11\n Isqrt( 6) is 2 Isqrt(66) is 8 Isqrt(122) is 11\n Isqrt( 7) is 2 Isqrt(67) is 8\n Isqrt( 8) is 2 Isqrt(68) is 8 Isqrt(143) is 11\n Isqrt( 9) is 3 Isqrt(69) is 8 Isqrt(144) is 12\n Isqrt(10) is 3 Isqrt(70) is 8 Isqrt(145) is 12\n\n\n;Task:\nCompute and show all output here \u00a0 (on this page) \u00a0 for:\n::* \u00a0 the Isqrt of the \u00a0 \u00a0 integers \u00a0 \u00a0 from \u00a0 \u00a0 '''0''' \u2500\u2500\u2500\u25ba '''65''' \u00a0\u00a0 (inclusive), shown in a horizontal format.\n::* \u00a0 the Isqrt of the \u00a0 odd powers\u00a0 from \u00a0 '''71''' \u2500\u2500\u2500\u25ba '''773''' \u00a0 (inclusive), shown in a \u00a0 vertical \u00a0 format.\n::* \u00a0 use commas in the displaying of larger numbers.\n\n\nYou can show more numbers for the 2nd requirement if the displays fits on one screen on Rosetta Code.\nIf your computer programming language only supports smaller integers, \u00a0 show what you can.\n\n\n;Related tasks:\n:* \u00a0 sequence of non-squares\n:* \u00a0 integer roots\n:* \u00a0 square root by hand\n\n", "solution": "#include \n#include \n\nint64_t isqrt(int64_t x) {\n int64_t q = 1, r = 0;\n while (q <= x) {\n q <<= 2;\n }\n while (q > 1) {\n int64_t t;\n q >>= 2;\n t = x - r - q;\n r >>= 1;\n if (t >= 0) {\n x = t;\n r += q;\n }\n }\n return r;\n}\n\nint main() {\n int64_t p;\n int n;\n\n printf(\"Integer square root for numbers 0 to 65:\\n\");\n for (n = 0; n <= 65; n++) {\n printf(\"%lld \", isqrt(n));\n }\n printf(\"\\n\\n\");\n\n printf(\"Integer square roots of odd powers of 7 from 1 to 21:\\n\");\n printf(\" n | 7 ^ n | isqrt(7 ^ n)\\n\");\n p = 7;\n for (n = 1; n <= 21; n += 2, p *= 49) {\n printf(\"%2d | %18lld | %12lld\\n\", n, p, isqrt(p));\n }\n}"} +{"title": "Isqrt (integer square root) of X", "language": "Python 2.7", "task": "Sometimes a function is needed to find the integer square root of \u00a0 '''X''', \u00a0 where \u00a0 '''X''' \u00a0 can be a\nreal non\u2500negative number.\n\nOften \u00a0 '''X''' \u00a0 is actually a non\u2500negative integer.\n\nFor the purposes of this task, \u00a0 '''X''' \u00a0 can be an integer or a real number, \u00a0 but if it\nsimplifies things in your computer programming language, \u00a0 assume it's an integer.\n\n\nOne of the most common uses of \u00a0 '''Isqrt''' \u00a0 is in the division of an integer by all factors \u00a0 (or\nprimes) \u00a0 up to the \u00a0 \n\u221a\u00a0X\u00a0 \u00a0 of that\ninteger, \u00a0 either to find the factors of that integer, \u00a0 or to determine primality.\n\n\nAn alternative method for finding the \u00a0 '''Isqrt''' \u00a0 of a number is to\ncalculate: \u00a0 \u00a0 \u00a0 floor( sqrt(X) ) \n::* \u00a0 where \u00a0 '''sqrt''' \u00a0\u00a0 is the \u00a0 square root \u00a0 function for non\u2500negative real numbers, \u00a0 and\n::* \u00a0 where \u00a0 '''floor''' \u00a0 is the \u00a0 floor \u00a0 function for real numbers.\n\n\nIf the hardware supports the computation of (real) square roots, \u00a0 the above method might be a faster method for\nsmall numbers that don't have very many significant (decimal) digits.\n\nHowever, floating point arithmetic is limited in the number of \u00a0 (binary or decimal) \u00a0 digits that it can support.\n\n\n;Pseudo\u2500code using quadratic residue:\nFor this task, the integer square root of a non\u2500negative number will be computed using a version\nof \u00a0 ''quadratic residue'', \u00a0 which has the advantage that no \u00a0 ''floating point'' \u00a0 calculations are\nused, \u00a0 only integer arithmetic. \n\nFurthermore, the two divisions can be performed by bit shifting, \u00a0 and the one multiplication can also be be performed by bit shifting or additions.\n\nThe disadvantage is the limitation of the size of the largest integer that a particular computer programming language can support.\n\n\nPseudo\u2500code of a procedure for finding the integer square root of \u00a0 '''X''' \u00a0 \u00a0 \u00a0 (all variables are integers):\n q \u25c4\u2500\u2500 1 /*initialize Q to unity. */\n /*find a power of 4 that's greater than X.*/\n perform while q <= x /*perform while Q <= X. */\n q \u25c4\u2500\u2500 q * 4 /*multiply Q by four. */\n end /*perform*/\n /*Q is now greater than X.*/\n z \u25c4\u2500\u2500 x /*set Z to the value of X.*/\n r \u25c4\u2500\u2500 0 /*initialize R to zero. */\n perform while q > 1 /*perform while Q > unity. */\n q \u25c4\u2500\u2500 q \u00f7 4 /*integer divide by four. */\n t \u25c4\u2500\u2500 z - r - q /*compute value of T. */\n r \u25c4\u2500\u2500 r \u00f7 2 /*integer divide by two. */\n if t >= 0 then do \n z \u25c4\u2500\u2500 t /*set Z to value of T. */\n r \u25c4\u2500\u2500 r + q /*compute new value of R. */\n end\n end /*perform*/\n /*R is now the Isqrt(X). */\n \n /* Sidenote: Also, Z is now the remainder after square root (i.e. */\n /* R^2 + Z = X, so if Z = 0 then X is a perfect square). */\n\nAnother version for the (above) \u00a0 1st \u00a0 '''perform''' \u00a0 is:\n perform until q > X /*perform until Q > X. */\n q \u25c4\u2500\u2500 q * 4 /*multiply Q by four. */\n end /*perform*/\n\n\nInteger square roots of some values:\n Isqrt( 0) is 0 Isqrt(60) is 7 Isqrt( 99) is 9\n Isqrt( 1) is 1 Isqrt(61) is 7 Isqrt(100) is 10\n Isqrt( 2) is 1 Isqrt(62) is 7 Isqrt(102) is 10\n Isqrt( 3) is 1 Isqrt(63) is 7\n Isqrt( 4) is 2 Isqrt(64) is 8 Isqet(120) is 10\n Isqrt( 5) is 2 Isqrt(65) is 8 Isqrt(121) is 11\n Isqrt( 6) is 2 Isqrt(66) is 8 Isqrt(122) is 11\n Isqrt( 7) is 2 Isqrt(67) is 8\n Isqrt( 8) is 2 Isqrt(68) is 8 Isqrt(143) is 11\n Isqrt( 9) is 3 Isqrt(69) is 8 Isqrt(144) is 12\n Isqrt(10) is 3 Isqrt(70) is 8 Isqrt(145) is 12\n\n\n;Task:\nCompute and show all output here \u00a0 (on this page) \u00a0 for:\n::* \u00a0 the Isqrt of the \u00a0 \u00a0 integers \u00a0 \u00a0 from \u00a0 \u00a0 '''0''' \u2500\u2500\u2500\u25ba '''65''' \u00a0\u00a0 (inclusive), shown in a horizontal format.\n::* \u00a0 the Isqrt of the \u00a0 odd powers\u00a0 from \u00a0 '''71''' \u2500\u2500\u2500\u25ba '''773''' \u00a0 (inclusive), shown in a \u00a0 vertical \u00a0 format.\n::* \u00a0 use commas in the displaying of larger numbers.\n\n\nYou can show more numbers for the 2nd requirement if the displays fits on one screen on Rosetta Code.\nIf your computer programming language only supports smaller integers, \u00a0 show what you can.\n\n\n;Related tasks:\n:* \u00a0 sequence of non-squares\n:* \u00a0 integer roots\n:* \u00a0 square root by hand\n\n", "solution": "def isqrt ( x ):\n q = 1\n while q <= x : \n q *= 4\n z,r = x,0\n while q > 1 :\n q /= 4\n t,r = z-r-q,r/2\n if t >= 0 :\n z,r = t,r+q\n return r \n\nprint ' '.join( '%d'%isqrt( n ) for n in xrange( 66 ))\nprint '\\n'.join( '{0:114,} = isqrt( 7^{1:3} )'.format( isqrt( 7**n ),n ) for n in range( 1,204,2 ))"} +{"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 [https://projecteuler.net/problem=92 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": "Iterated digits squaring", "language": "Python", "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 [https://projecteuler.net/problem=92 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": "from math import ceil, log10, factorial\n\ndef next_step(x):\n result = 0\n while x > 0:\n result += (x % 10) ** 2\n x /= 10\n return result\n\ndef check(number):\n candidate = 0\n for n in number:\n candidate = candidate * 10 + n\n\n while candidate != 89 and candidate != 1:\n candidate = next_step(candidate)\n\n if candidate == 89:\n digits_count = [0] * 10\n for d in number:\n digits_count[d] += 1\n\n result = factorial(len(number))\n for c in digits_count:\n result /= factorial(c)\n return result\n\n return 0\n\ndef main():\n limit = 100000000\n cache_size = int(ceil(log10(limit)))\n assert 10 ** cache_size == limit\n\n number = [0] * cache_size\n result = 0\n i = cache_size - 1\n\n while True:\n if i == 0 and number[i] == 9:\n break\n if i == cache_size - 1 and number[i] < 9:\n number[i] += 1\n result += check(number)\n elif number[i] == 9:\n i -= 1\n else:\n number[i] += 1\n for j in xrange(i + 1, cache_size):\n number[j] = number[i]\n i = cache_size - 1\n result += check(number)\n\n print result\n\nmain()"} +{"title": "JSON", "language": "YAJL 2", "task": "Load a JSON string into a data structure. \nAlso, create a new data structure and serialize it into JSON.\n\nUse objects and arrays (as appropriate for your language) \nand make sure your JSON is valid (https://jsonformatter.org).\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nstatic void print_callback (void *ctx, const char *str, size_t len)\n{\n FILE *f = (FILE *) ctx;\n fwrite (str, 1, len, f);\n}\n\nstatic void check_status (yajl_gen_status status)\n{\n if (status != yajl_gen_status_ok)\n {\n fprintf (stderr, \"yajl_gen_status was %d\\n\", (int) status);\n exit (EXIT_FAILURE);\n }\n}\n\nstatic void serialize_value (yajl_gen gen, yajl_val val, int parse_numbers)\n{\n size_t i;\n\n switch (val->type)\n {\n case yajl_t_string:\n check_status (yajl_gen_string (gen,\n (const unsigned char *) val->u.string,\n strlen (val->u.string)));\n break;\n case yajl_t_number:\n if (parse_numbers && YAJL_IS_INTEGER (val))\n check_status (yajl_gen_integer (gen, YAJL_GET_INTEGER (val)));\n else if (parse_numbers && YAJL_IS_DOUBLE (val))\n check_status (yajl_gen_double (gen, YAJL_GET_DOUBLE (val)));\n else\n check_status (yajl_gen_number (gen, YAJL_GET_NUMBER (val),\n strlen (YAJL_GET_NUMBER (val))));\n break;\n case yajl_t_object:\n check_status (yajl_gen_map_open (gen));\n for (i = 0 ; i < val->u.object.len ; i++)\n {\n check_status (yajl_gen_string (gen,\n (const unsigned char *) val->u.object.keys[i],\n strlen (val->u.object.keys[i])));\n serialize_value (gen, val->u.object.values[i], parse_numbers);\n }\n check_status (yajl_gen_map_close (gen));\n break;\n case yajl_t_array:\n check_status (yajl_gen_array_open (gen));\n for (i = 0 ; i < val->u.array.len ; i++)\n serialize_value (gen, val->u.array.values[i], parse_numbers);\n check_status (yajl_gen_array_close (gen));\n break;\n case yajl_t_true:\n check_status (yajl_gen_bool (gen, 1));\n break;\n case yajl_t_false:\n check_status (yajl_gen_bool (gen, 0));\n break;\n case yajl_t_null:\n check_status (yajl_gen_null (gen));\n break;\n default:\n fprintf (stderr, \"unexpectedly got type %d\\n\", (int) val->type);\n exit (EXIT_FAILURE);\n }\n}\n\nstatic void print_tree (FILE *f, yajl_val tree, int parse_numbers)\n{\n yajl_gen gen;\n\n gen = yajl_gen_alloc (NULL);\n if (! gen)\n {\n fprintf (stderr, \"yajl_gen_alloc failed\\n\");\n exit (EXIT_FAILURE);\n }\n\n if (0 == yajl_gen_config (gen, yajl_gen_beautify, 1) ||\n 0 == yajl_gen_config (gen, yajl_gen_validate_utf8, 1) ||\n 0 == yajl_gen_config (gen, yajl_gen_print_callback, print_callback, f))\n {\n fprintf (stderr, \"yajl_gen_config failed\\n\");\n exit (EXIT_FAILURE);\n }\n\n serialize_value (gen, tree, parse_numbers);\n yajl_gen_free (gen);\n}\n\nint main (int argc, char **argv)\n{\n char err_buf[200];\n const char *json =\n \"{\\\"pi\\\": 3.14, \\\"large number\\\": 123456789123456789123456789, \"\n \"\\\"an array\\\": [-1, true, false, null, \\\"foo\\\"]}\";\n yajl_val tree;\n\n tree = yajl_tree_parse (json, err_buf, sizeof (err_buf));\n if (! tree)\n {\n fprintf (stderr, \"parsing failed because: %s\\n\", err_buf);\n return EXIT_FAILURE;\n }\n\n printf (\"Treating numbers as strings...\\n\");\n print_tree (stdout, tree, 0);\n printf (\"Parsing numbers to long long or double...\\n\");\n print_tree (stdout, tree, 1);\n\n yajl_tree_free (tree);\n\n return EXIT_SUCCESS;\n}"} +{"title": "JSON", "language": "JavaScript", "task": "Load a JSON string into a data structure. \nAlso, create a new data structure and serialize it into JSON.\n\nUse objects and arrays (as appropriate for your language) \nand make sure your JSON is valid (https://jsonformatter.org).\n\n", "solution": "var data = JSON.parse('{ \"foo\": 1, \"bar\": [10, \"apples\"] }');\n\nvar sample = { \"blue\": [1,2], \"ocean\": \"water\" };\nvar json_string = JSON.stringify(sample);"} +{"title": "JSON", "language": "Python 2.6+", "task": "Load a JSON string into a data structure. \nAlso, create a new data structure and serialize it into JSON.\n\nUse objects and arrays (as appropriate for your language) \nand make sure your JSON is valid (https://jsonformatter.org).\n\n", "solution": ">>> import json\n>>> data = json.loads('{ \"foo\": 1, \"bar\": [10, \"apples\"] }')\n>>> sample = { \"blue\": [1,2], \"ocean\": \"water\" }\n>>> json_string = json.dumps(sample)\n>>> json_string\n'{\"blue\": [1, 2], \"ocean\": \"water\"}'\n>>> sample\n{'blue': [1, 2], 'ocean': 'water'}\n>>> data\n{'foo': 1, 'bar': [10, 'apples']}"} +{"title": "Jacobi symbol", "language": "C", "task": "The '''[https://en.wikipedia.org/wiki/Jacobi_symbol 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) \u2261 \u00a0 1 \u00a0 \u00a0 if a is a square (mod p)\n* (a | p) \u2261 -1 \u00a0 \u00a0 if a is not a square (mod p)\n* (a | p) \u2261 \u00a0 0 \u00a0 \u00a0 if a \u2261 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* [https://en.wikipedia.org/wiki/Jacobi_symbol 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": "Jacobi symbol", "language": "Python", "task": "The '''[https://en.wikipedia.org/wiki/Jacobi_symbol 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) \u2261 \u00a0 1 \u00a0 \u00a0 if a is a square (mod p)\n* (a | p) \u2261 -1 \u00a0 \u00a0 if a is not a square (mod p)\n* (a | p) \u2261 \u00a0 0 \u00a0 \u00a0 if a \u2261 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* [https://en.wikipedia.org/wiki/Jacobi_symbol Wikipedia article on Jacobi symbol].\n\n", "solution": "def jacobi(a, n):\n if n <= 0:\n raise ValueError(\"'n' must be a positive integer.\")\n if n % 2 == 0:\n raise ValueError(\"'n' must be odd.\")\n a %= n\n result = 1\n while a != 0:\n while a % 2 == 0:\n a /= 2\n n_mod_8 = n % 8\n if n_mod_8 in (3, 5):\n result = -result\n a, n = n, a\n if a % 4 == 3 and n % 4 == 3:\n result = -result\n a %= n\n if n == 1:\n return result\n else:\n return 0"} +{"title": "Jacobsthal numbers", "language": "C", "task": "'''Jacobsthal numbers''' are an integer sequence related to Fibonacci numbers. Similar to Fibonacci, where each term is the sum of the previous two terms, each term is the sum of the previous, plus twice the one before that. Traditionally the sequence starts with the given terms 0, 1.\n\n \n J0 = 0\n J1 = 1\n Jn = Jn-1 + 2 \u00d7 Jn-2\n\n\nTerms may be calculated directly using one of several possible formulas:\n \n Jn = ( 2n - (-1)n ) / 3\n \n\n\n'''Jacobsthal-Lucas numbers''' are very similar. They have the same recurrence relationship, the only difference is an initial starting value '''J0 = 2''' rather than '''J0 = 0'''.\n\nTerms may be calculated directly using one of several possible formulas:\n \n JLn = 2n + (-1)n\n\n\n'''Jacobsthal oblong numbers''' is the sequence obtained from multiplying each '''Jacobsthal number''' '''Jn''' by its direct successor '''Jn+1'''.\n\n\n'''Jacobsthal primes''' are '''Jacobsthal numbers''' that are prime.\n\n\n\n;Task\n* Find and display the first 30 '''Jacobsthal numbers'''\n* Find and display the first 30 '''Jacobsthal-Lucas numbers'''\n* Find and display the first 20 '''Jacobsthal oblong numbers'''\n* Find and display at least the first 10 '''Jacobsthal primes'''\n\n\n\n;See also\n;* Wikipedia: Jacobsthal number\n;* [https://www.numbersaplenty.com/set/Jacobsthal_number Numbers Aplenty - Jacobsthal number]\n;* OEIS:A001045 - Jacobsthal sequence (or Jacobsthal numbers)\n;* OEIS:A014551 - Jacobsthal-Lucas numbers.\n;* OEIS:A084175 - Jacobsthal oblong numbers\n;* OEIS:A049883 - Primes in the Jacobsthal sequence\n;* Related task: Fibonacci sequence\n;* Related task: Leonardo numbers\n\n\n\n\n", "solution": "#include \n#include \n\nvoid jacobsthal(mpz_t r, unsigned long n) {\n mpz_t s;\n mpz_init(s);\n mpz_set_ui(r, 1);\n mpz_mul_2exp(r, r, n);\n mpz_set_ui(s, 1);\n if (n % 2) mpz_neg(s, s);\n mpz_sub(r, r, s);\n mpz_div_ui(r, r, 3);\n}\n\nvoid jacobsthal_lucas(mpz_t r, unsigned long n) {\n mpz_t a;\n mpz_init(a);\n mpz_set_ui(r, 1);\n mpz_mul_2exp(r, r, n);\n mpz_set_ui(a, 1);\n if (n % 2) mpz_neg(a, a);\n mpz_add(r, r, a);\n}\n\nint main() {\n int i, count;\n mpz_t jac[30], j;\n printf(\"First 30 Jacobsthal numbers:\\n\");\n for (i = 0; i < 30; ++i) {\n mpz_init(jac[i]);\n jacobsthal(jac[i], i);\n gmp_printf(\"%9Zd \", jac[i]);\n if (!((i+1)%5)) printf(\"\\n\");\n }\n\n printf(\"\\nFirst 30 Jacobsthal-Lucas numbers:\\n\");\n mpz_init(j);\n for (i = 0; i < 30; ++i) {\n jacobsthal_lucas(j, i);\n gmp_printf(\"%9Zd \", j);\n if (!((i+1)%5)) printf(\"\\n\");\n }\n\n printf(\"\\nFirst 20 Jacobsthal oblong numbers:\\n\");\n for (i = 0; i < 20; ++i) {\n mpz_mul(j, jac[i], jac[i+1]);\n gmp_printf(\"%11Zd \", j);\n if (!((i+1)%5)) printf(\"\\n\");\n }\n\n printf(\"\\nFirst 20 Jacobsthal primes:\\n\");\n for (i = 0, count = 0; count < 20; ++i) {\n jacobsthal(j, i);\n if (mpz_probab_prime_p(j, 15) > 0) {\n gmp_printf(\"%Zd\\n\", j);\n ++count;\n }\n }\n\n return 0;\n}"} +{"title": "Jacobsthal numbers", "language": "Python", "task": "'''Jacobsthal numbers''' are an integer sequence related to Fibonacci numbers. Similar to Fibonacci, where each term is the sum of the previous two terms, each term is the sum of the previous, plus twice the one before that. Traditionally the sequence starts with the given terms 0, 1.\n\n \n J0 = 0\n J1 = 1\n Jn = Jn-1 + 2 \u00d7 Jn-2\n\n\nTerms may be calculated directly using one of several possible formulas:\n \n Jn = ( 2n - (-1)n ) / 3\n \n\n\n'''Jacobsthal-Lucas numbers''' are very similar. They have the same recurrence relationship, the only difference is an initial starting value '''J0 = 2''' rather than '''J0 = 0'''.\n\nTerms may be calculated directly using one of several possible formulas:\n \n JLn = 2n + (-1)n\n\n\n'''Jacobsthal oblong numbers''' is the sequence obtained from multiplying each '''Jacobsthal number''' '''Jn''' by its direct successor '''Jn+1'''.\n\n\n'''Jacobsthal primes''' are '''Jacobsthal numbers''' that are prime.\n\n\n\n;Task\n* Find and display the first 30 '''Jacobsthal numbers'''\n* Find and display the first 30 '''Jacobsthal-Lucas numbers'''\n* Find and display the first 20 '''Jacobsthal oblong numbers'''\n* Find and display at least the first 10 '''Jacobsthal primes'''\n\n\n\n;See also\n;* Wikipedia: Jacobsthal number\n;* [https://www.numbersaplenty.com/set/Jacobsthal_number Numbers Aplenty - Jacobsthal number]\n;* OEIS:A001045 - Jacobsthal sequence (or Jacobsthal numbers)\n;* OEIS:A014551 - Jacobsthal-Lucas numbers.\n;* OEIS:A084175 - Jacobsthal oblong numbers\n;* OEIS:A049883 - Primes in the Jacobsthal sequence\n;* Related task: Fibonacci sequence\n;* Related task: Leonardo numbers\n\n\n\n\n", "solution": "#!/usr/bin/python\nfrom math import floor, pow\n\ndef isPrime(n):\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n return False \n return True\n\ndef odd(n):\n return n and 1 != 0\n \ndef jacobsthal(n):\n return floor((pow(2,n)+odd(n))/3)\n\ndef jacobsthal_lucas(n):\n return int(pow(2,n)+pow(-1,n))\n\ndef jacobsthal_oblong(n):\n return jacobsthal(n)*jacobsthal(n+1)\n\n\nif __name__ == '__main__':\n print(\"First 30 Jacobsthal numbers:\")\n for j in range(0, 30):\n print(jacobsthal(j), end=\" \")\n\n print(\"\\n\\nFirst 30 Jacobsthal-Lucas numbers: \")\n for j in range(0, 30):\n print(jacobsthal_lucas(j), end = '\\t')\n\n print(\"\\n\\nFirst 20 Jacobsthal oblong numbers: \")\n for j in range(0, 20):\n print(jacobsthal_oblong(j), end=\" \")\n\n print(\"\\n\\nFirst 10 Jacobsthal primes: \")\n for j in range(3, 33):\n if isPrime(jacobsthal(j)):\n print(jacobsthal(j))"} +{"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 \u00a0 '''0''' \u00a0 equates to no similarities and \u00a0 '''1''' \u00a0 is an exact match.\n\n\n;;Definition\n\nThe Jaro similarity \u00a0 d_j \u00a0 of two given strings \u00a0 s_1 \u00a0 and \u00a0 s_2 \u00a0 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 \u00a0 is the number of ''matching characters'';\n* t \u00a0 is half the number of ''transpositions''.\n\n\nTwo characters from \u00a0 s_1 \u00a0 and \u00a0 s_2 \u00a0 respectively, are considered ''matching'' only if they are the same and not farther apart than \u00a0 \\left\\lfloor\\frac{\\max(|s_1|,|s_2|)}{2}\\right\\rfloor-1 characters.\n\nEach character of \u00a0 s_1 \u00a0 is compared with all its matching characters in \u00a0 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 \u00a0 s_1 \u00a0 ''DWAYNE'' \u00a0 and \u00a0 s_2 \u00a0 ''DUANE'' \u00a0 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\u2013Winkler 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": "Jaro similarity", "language": "Python 3", "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 \u00a0 '''0''' \u00a0 equates to no similarities and \u00a0 '''1''' \u00a0 is an exact match.\n\n\n;;Definition\n\nThe Jaro similarity \u00a0 d_j \u00a0 of two given strings \u00a0 s_1 \u00a0 and \u00a0 s_2 \u00a0 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 \u00a0 is the number of ''matching characters'';\n* t \u00a0 is half the number of ''transpositions''.\n\n\nTwo characters from \u00a0 s_1 \u00a0 and \u00a0 s_2 \u00a0 respectively, are considered ''matching'' only if they are the same and not farther apart than \u00a0 \\left\\lfloor\\frac{\\max(|s_1|,|s_2|)}{2}\\right\\rfloor-1 characters.\n\nEach character of \u00a0 s_1 \u00a0 is compared with all its matching characters in \u00a0 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 \u00a0 s_1 \u00a0 ''DWAYNE'' \u00a0 and \u00a0 s_2 \u00a0 ''DUANE'' \u00a0 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\u2013Winkler distance on Wikipedia.\n\n", "solution": "'''Jaro distance'''\n\nfrom __future__ import division\n\n\ndef jaro(s, t):\n '''Jaro distance between two strings.'''\n s_len = len(s)\n t_len = len(t)\n\n if s_len == 0 and t_len == 0:\n return 1\n\n match_distance = (max(s_len, t_len) // 2) - 1\n\n s_matches = [False] * s_len\n t_matches = [False] * t_len\n\n matches = 0\n transpositions = 0\n\n for i in range(s_len):\n start = max(0, i - match_distance)\n end = min(i + match_distance + 1, t_len)\n\n for j in range(start, end):\n if t_matches[j]:\n continue\n if s[i] != t[j]:\n continue\n s_matches[i] = True\n t_matches[j] = True\n matches += 1\n break\n\n if matches == 0:\n return 0\n\n k = 0\n for i in range(s_len):\n if not s_matches[i]:\n continue\n while not t_matches[k]:\n k += 1\n if s[i] != t[k]:\n transpositions += 1\n k += 1\n\n return ((matches / s_len) +\n (matches / t_len) +\n ((matches - transpositions / 2) / matches)) / 3\n\n\ndef main():\n '''Tests'''\n\n for s, t in [('MARTHA', 'MARHTA'),\n ('DIXON', 'DICKSONX'),\n ('JELLYFISH', 'SMELLYFISH')]:\n print(\"jaro(%r, %r) = %.10f\" % (s, t, jaro(s, t)))\n\n\nif __name__ == '__main__':\n main()"} +{"title": "Jewels and stones", "language": "C", "task": ";Task:\n\nCreate a function which takes two string parameters: 'stones' and 'jewels' and returns an integer.\n\nBoth strings can contain any number of upper or lower case letters. However, in the case of 'jewels', all letters must be distinct.\n\nThe function should count (and return) how many 'stones' are 'jewels' or, in other words, how many letters in 'stones' are also letters in 'jewels'.\n\n\nNote that:\n:# Only letters in the [https://en.wikipedia.org/wiki/ISO_basic_Latin_alphabet ISO basic Latin alphabet] i.e. 'A to Z' or 'a to z' need be considered. \n:# A lower case letter is considered to be different from its upper case equivalent for this purpose, i.e., 'a' != 'A'.\n:# The parameters do not need to have exactly the same names.\n:# Validating the arguments is unnecessary. \n\nSo, for example, if passed \"aAAbbbb\" for 'stones' and \"aA\" for 'jewels', the function should return 3.\n\nThis task was inspired by [https://leetcode.com/problems/jewels-and-stones/description/ this problem].\n\n\n\n", "solution": "#include \n#include \n\nint count_jewels(const char *s, const char *j) {\n int count = 0;\n for ( ; *s; ++s) if (strchr(j, *s)) ++count;\n return count;\n}\n\nint main() {\n printf(\"%d\\n\", count_jewels(\"aAAbbbb\", \"aA\"));\n printf(\"%d\\n\", count_jewels(\"ZZ\", \"z\"));\n return 0;\n}"} +{"title": "Jewels and stones", "language": "Python", "task": ";Task:\n\nCreate a function which takes two string parameters: 'stones' and 'jewels' and returns an integer.\n\nBoth strings can contain any number of upper or lower case letters. However, in the case of 'jewels', all letters must be distinct.\n\nThe function should count (and return) how many 'stones' are 'jewels' or, in other words, how many letters in 'stones' are also letters in 'jewels'.\n\n\nNote that:\n:# Only letters in the [https://en.wikipedia.org/wiki/ISO_basic_Latin_alphabet ISO basic Latin alphabet] i.e. 'A to Z' or 'a to z' need be considered. \n:# A lower case letter is considered to be different from its upper case equivalent for this purpose, i.e., 'a' != 'A'.\n:# The parameters do not need to have exactly the same names.\n:# Validating the arguments is unnecessary. \n\nSo, for example, if passed \"aAAbbbb\" for 'stones' and \"aA\" for 'jewels', the function should return 3.\n\nThis task was inspired by [https://leetcode.com/problems/jewels-and-stones/description/ this problem].\n\n\n\n", "solution": "def countJewels(s, j):\n return sum(x in j for x in s)\n\nprint countJewels(\"aAAbbbb\", \"aA\")\nprint countJewels(\"ZZ\", \"z\")"} +{"title": "Juggler sequence", "language": "Python", "task": "Background of the \u00a0 '''juggler sequence''':\n\nJuggler sequences were publicized by an American mathematician and author \u00a0 [https://en.wikipedia.org/wiki/Clifford_A._Pickover Clifford A. Pickover]. \u00a0 The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences, \u00a0 much like balls in the hands of a juggler.\n\n\n;Description\nA [https://en.wikipedia.org/wiki/Juggler_sequence juggler sequence] is an integer sequence that starts with a positive integer a[0], with each subsequent term in the sequence being defined by the recurrence relation: \n\n a[k + 1] = floor(a[k] ^ 0.5) if a[k] is even ''' ''or'' ''' \n a[k + 1] = floor(a[k] ^ 1.5) if a[k] is odd \n\nIf a juggler sequence reaches 1, then all subsequent terms are equal to 1. This is known to be the case for initial terms up to 1,000,000 but it is not known whether all juggler sequences after that will eventually reach 1.\n\n\n;Task:\nCompute and show here the following statistics for juggler sequences with an initial term of a[n] where n is between '''20''' and '''39''' inclusive:\n\n* l[n] - the number of terms needed to reach 1.\n* h[n] - the maximum value reached in that sequence.\n* i[n] - the index of the term (starting from 0) at which the maximum is (first) reached.\n\nIf your language supports ''big integers'' with an integer square root function, also compute and show here the same statistics for as many as you reasonably can of the following values for n:\n\n113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909, 2264915, 5812827\n\nThose with fast languages and fast machines may also like to try their luck at n = 7110201.\n\nHowever, as h[n] for most of these numbers is thousands or millions of digits long, show instead of h[n]:\n\n* d[n] - the number of digits in h[n]\n\nThe results can be (partially) verified against the table [https://web.archive.org/web/20091027053243/http://www.geocities.com/hjsmithh/Juggler/JuggWhat.html here].\n \n\n;Related tasks:\n* \u00a0 [[Hailstone sequence]]\n* \u00a0 [[Yellowstone sequence]]\n* \u00a0 [[Isqrt_(integer_square_root)_of_X]]\n\n\n;See also:\n* [[oeis:A007320]] Number of steps needed for Juggler sequence started at n to reach 1 \t\t\n* [[oeis:A094716]] Largest value in the Juggler sequence started at n\n\n", "solution": "from math import isqrt\n\ndef juggler(k, countdig=True, maxiters=1000):\n m, maxj, maxjpos = k, k, 0\n for i in range(1, maxiters):\n m = isqrt(m) if m % 2 == 0 else isqrt(m * m * m)\n if m >= maxj:\n maxj, maxjpos = m, i\n if m == 1:\n print(f\"{k: 9}{i: 6,}{maxjpos: 6}{len(str(maxj)) if countdig else maxj: 20,}{' digits' if countdig else ''}\")\n return i\n\n print(\"ERROR: Juggler series starting with $k did not converge in $maxiters iterations\")\n\n\nprint(\" n l(n) i(n) h(n) or d(n)\\n-------------------------------------------\")\nfor k in range(20, 40):\n juggler(k, False)\n\nfor k in [113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909]:\n juggler(k)\n"} +{"title": "Julia set", "language": "C", "task": "right\n\n;Task\nGenerate and draw a Julia set. \n\n\n;Related tasks\n* \u00a0 Mandelbrot Set\n\n", "solution": "\n#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": "Julia set", "language": "JavaScript", "task": "right\n\n;Task\nGenerate and draw a Julia set. \n\n\n;Related tasks\n* \u00a0 Mandelbrot Set\n\n", "solution": "\nvar maxIterations = 450, minX = -.5, maxX = .5, \n minY = -.5, maxY = .5, wid, hei, ctx,\n jsX = 0.285, jsY = 0.01;\n\nfunction remap( x, t1, t2, s1, s2 ) {\n var f = ( x - t1 ) / ( t2 - t1 ),\n g = f * ( s2 - s1 ) + s1;\n return g;\n}\nfunction getColor( c ) {\n var r, g, b, p = c / 32,\n l = ~~( p * 6 ), o = p * 6 - l, \n q = 1 - o;\n\n switch( l % 6 ) {\n case 0: r = 1; g = o; b = 0; break;\n case 1: r = q; g = 1; b = 0; break;\n case 2: r = 0; g = 1; b = o; break;\n case 3: r = 0; g = q; b = 1; break;\n case 4: r = o; g = 0; b = 1; break;\n case 5: r = 1; g = 0; b = q; break;\n }\n var c = \"#\" + ( \"00\" + ( ~~( r * 255 ) ).toString( 16 ) ).slice( -2 ) + \n ( \"00\" + ( ~~( g * 255 ) ).toString( 16 ) ).slice( -2 ) + \n ( \"00\" + ( ~~( b * 255 ) ).toString( 16 ) ).slice( -2 );\n return (c);\n}\nfunction drawFractal() {\n var a, as, za, b, bs, zb, cnt, clr\n for( var j = 0; j < hei; j++ ) {\n for( var i = 0; i < wid; i++ ) {\n a = remap( i, 0, wid, minX, maxX )\n b = remap( j, 0, hei, minY, maxY )\n cnt = 0;\n while( ++cnt < maxIterations ) {\n za = a * a; zb = b * b;\n if( za + zb > 4 ) break;\n as = za - zb; bs = 2 * a * b;\n a = as + jsX; b = bs + jsY;\n }\n if( cnt < maxIterations ) {\n ctx.fillStyle = getColor( cnt );\n }\n ctx.fillRect( i, j, 1, 1 );\n }\n }\n}\nfunction init() {\n var canvas = document.createElement( \"canvas\" );\n wid = hei = 800;\n canvas.width = wid; canvas.height = hei;\n ctx = canvas.getContext( \"2d\" );\n ctx.fillStyle = \"black\"; ctx.fillRect( 0, 0, wid, hei );\n document.body.appendChild( canvas );\n drawFractal();\n}\n"} +{"title": "Julia set", "language": "Python", "task": "right\n\n;Task\nGenerate and draw a Julia set. \n\n\n;Related tasks\n* \u00a0 Mandelbrot Set\n\n", "solution": "\"\"\"\nSolution from:\nhttps://codereview.stackexchange.com/questions/210271/generating-julia-set\n\"\"\"\nfrom functools import partial\nfrom numbers import Complex\nfrom typing import Callable\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef douady_hubbard_polynomial(z: Complex,\n c: Complex) -> Complex:\n \"\"\"\n Monic and centered quadratic complex polynomial\n https://en.wikipedia.org/wiki/Complex_quadratic_polynomial#Map\n \"\"\"\n return z ** 2 + c\n\n\ndef julia_set(mapping: Callable[[Complex], Complex],\n *,\n min_coordinate: Complex,\n max_coordinate: Complex,\n width: int,\n height: int,\n iterations_count: int = 256,\n threshold: float = 2.) -> np.ndarray:\n \"\"\"\n As described in https://en.wikipedia.org/wiki/Julia_set\n :param mapping: function defining Julia set\n :param min_coordinate: bottom-left complex plane coordinate\n :param max_coordinate: upper-right complex plane coordinate\n :param height: pixels in vertical axis\n :param width: pixels in horizontal axis\n :param iterations_count: number of iterations\n :param threshold: if the magnitude of z becomes greater\n than the threshold we assume that it will diverge to infinity\n :return: 2D pixels array of intensities\n \"\"\"\n im, re = np.ogrid[min_coordinate.imag: max_coordinate.imag: height * 1j,\n min_coordinate.real: max_coordinate.real: width * 1j]\n z = (re + 1j * im).flatten()\n\n live, = np.indices(z.shape) # indexes of pixels that have not escaped\n iterations = np.empty_like(z, dtype=int)\n\n for i in range(iterations_count):\n z_live = z[live] = mapping(z[live])\n escaped = abs(z_live) > threshold\n iterations[live[escaped]] = i\n live = live[~escaped]\n if live.size == 0:\n break\n else:\n iterations[live] = iterations_count\n\n return iterations.reshape((height, width))\n\n\nif __name__ == '__main__':\n mapping = partial(douady_hubbard_polynomial,\n c=-0.7 + 0.27015j) # type: Callable[[Complex], Complex]\n\n image = julia_set(mapping,\n min_coordinate=-1.5 - 1j,\n max_coordinate=1.5 + 1j,\n width=800,\n height=600)\n plt.axis('off')\n plt.imshow(image,\n cmap='nipy_spectral_r',\n origin='lower')\n plt.show()\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": "\n 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": "Jump anywhere", "language": "Python", "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": "\n# Example 2: Restarting a loop:\nfrom goto import goto, label\nlabel .start\nfor i in range(1, 4):\n print i\n if i == 2:\n try:\n output = message\n except NameError:\n print \"Oops - forgot to define 'message'! Start again.\"\n message = \"Hello world\"\n goto .start\nprint output, \"\\n\"\n"} +{"title": "K-d tree", "language": "C", "task": "[[Category:Data Structures]]\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''\u2006\u226b\u20062''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": "\n\n#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": "K-d tree", "language": "Python", "task": "[[Category:Data Structures]]\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''\u2006\u226b\u20062''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": "from random import seed, random\nfrom time import time\nfrom operator import itemgetter\nfrom collections import namedtuple\nfrom math import sqrt\nfrom copy import deepcopy\n\n\ndef sqd(p1, p2):\n return sum((c1 - c2) ** 2 for c1, c2 in zip(p1, p2))\n\n\nclass KdNode(object):\n __slots__ = (\"dom_elt\", \"split\", \"left\", \"right\")\n\n def __init__(self, dom_elt, split, left, right):\n self.dom_elt = dom_elt\n self.split = split\n self.left = left\n self.right = right\n\n\nclass Orthotope(object):\n __slots__ = (\"min\", \"max\")\n\n def __init__(self, mi, ma):\n self.min, self.max = mi, ma\n\n\nclass KdTree(object):\n __slots__ = (\"n\", \"bounds\")\n\n def __init__(self, pts, bounds):\n def nk2(split, exset):\n if not exset:\n return None\n exset.sort(key=itemgetter(split))\n m = len(exset) // 2\n d = exset[m]\n while m + 1 < len(exset) and exset[m + 1][split] == d[split]:\n m += 1\n d = exset[m]\n\n\n s2 = (split + 1) % len(d) # cycle coordinates\n return KdNode(d, split, nk2(s2, exset[:m]),\n nk2(s2, exset[m + 1:]))\n self.n = nk2(0, pts)\n self.bounds = bounds\n\nT3 = namedtuple(\"T3\", \"nearest dist_sqd nodes_visited\")\n\n\ndef find_nearest(k, t, p):\n def nn(kd, target, hr, max_dist_sqd):\n if kd is None:\n return T3([0.0] * k, float(\"inf\"), 0)\n\n nodes_visited = 1\n s = kd.split\n pivot = kd.dom_elt\n left_hr = deepcopy(hr)\n right_hr = deepcopy(hr)\n left_hr.max[s] = pivot[s]\n right_hr.min[s] = pivot[s]\n\n if target[s] <= pivot[s]:\n nearer_kd, nearer_hr = kd.left, left_hr\n further_kd, further_hr = kd.right, right_hr\n else:\n nearer_kd, nearer_hr = kd.right, right_hr\n further_kd, further_hr = kd.left, left_hr\n\n n1 = nn(nearer_kd, target, nearer_hr, max_dist_sqd)\n nearest = n1.nearest\n dist_sqd = n1.dist_sqd\n nodes_visited += n1.nodes_visited\n\n if dist_sqd < max_dist_sqd:\n max_dist_sqd = dist_sqd\n d = (pivot[s] - target[s]) ** 2\n if d > max_dist_sqd:\n return T3(nearest, dist_sqd, nodes_visited)\n d = sqd(pivot, target)\n if d < dist_sqd:\n nearest = pivot\n dist_sqd = d\n max_dist_sqd = dist_sqd\n\n n2 = nn(further_kd, target, further_hr, max_dist_sqd)\n nodes_visited += n2.nodes_visited\n if n2.dist_sqd < dist_sqd:\n nearest = n2.nearest\n dist_sqd = n2.dist_sqd\n\n return T3(nearest, dist_sqd, nodes_visited)\n\n return nn(t.n, p, t.bounds, float(\"inf\"))\n\n\ndef show_nearest(k, heading, kd, p):\n print(heading + \":\")\n print(\"Point: \", p)\n n = find_nearest(k, kd, p)\n print(\"Nearest neighbor:\", n.nearest)\n print(\"Distance: \", sqrt(n.dist_sqd))\n print(\"Nodes visited: \", n.nodes_visited, \"\\n\")\n\n\ndef random_point(k):\n return [random() for _ in range(k)]\n\n\ndef random_points(k, n):\n return [random_point(k) for _ in range(n)]\n\nif __name__ == \"__main__\":\n seed(1)\n P = lambda *coords: list(coords)\n kd1 = KdTree([P(2, 3), P(5, 4), P(9, 6), P(4, 7), P(8, 1), P(7, 2)],\n Orthotope(P(0, 0), P(10, 10)))\n show_nearest(2, \"Wikipedia example data\", kd1, P(9, 2))\n\n N = 400000\n t0 = time()\n kd2 = KdTree(random_points(3, N), Orthotope(P(0, 0, 0), P(1, 1, 1)))\n t1 = time()\n text = lambda *parts: \"\".join(map(str, parts))\n show_nearest(2, text(\"k-d tree with \", N,\n \" random 3D points (generation time: \",\n t1-t0, \"s)\"),\n kd2, random_point(3))"} +{"title": "Kaprekar numbers", "language": "C", "task": "A positive integer is a Kaprekar number if:\n* It is \u00a0 '''1''' \u00a0 \u00a0 (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* [http://www.cs.uwaterloo.ca/journals/JIS/VOL3/iann2a.html The Kaprekar Numbers] by Douglas E. Iannucci (2000). [http://pictor.math.uqam.ca/~plouffe/OEIS/jis/The%20Kaprekar%20Numbers.pdf PDF version]\n\n\n;Related task:\n* \u00a0 [[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": "Kaprekar numbers", "language": "JavaScript", "task": "A positive integer is a Kaprekar number if:\n* It is \u00a0 '''1''' \u00a0 \u00a0 (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* [http://www.cs.uwaterloo.ca/journals/JIS/VOL3/iann2a.html The Kaprekar Numbers] by Douglas E. Iannucci (2000). [http://pictor.math.uqam.ca/~plouffe/OEIS/jis/The%20Kaprekar%20Numbers.pdf PDF version]\n\n\n;Related task:\n* \u00a0 [[Casting out nines]]\n\n", "solution": "function isKaprekar( n, bs ) {\n\tif ( n < 1 ) return false\n\tif ( n == 1 ) return true\n\tbs = bs || 10\n\tvar s = (n * n).toString(bs)\n\tfor (var i=1, e=s.length; i\n'''or this numeric version'''\nfunction isKaprekar( n, bs ) {\n\tif ( n < 1 ) return false\n\tif ( n == 1 ) return true\n\tbs = bs || 10\n\tfor (var a=n*n, b=0, s=1; a; s*=bs) {\n\t\tb += a%bs*s\n\t\ta = Math.floor(a/bs)\n\t\tif (b && a + b == n) return true\n\t}\n\treturn false\n}\n'''with'''\nfunction kaprekar( s, e, bs, pbs ) {\n\tbs = bs || 10; pbs = pbs || 10\n\tconst toString = n => n.toString(pbs).toUpperCase()\n\tdocument.write('start:',toString(s), ' end:',toString(e), ' base:',bs, ' printBase:',pbs, '' )\n\tfor (var k=0, n=s; n<=e; n+=1) if (isKaprekar(n, bs)) k+=1, document.write(toString(n), ' ') \n\tdocument.write('found ', k, ' numbers')\n}\n\nkaprekar( 1, 99 )\nkaprekar( 1, 255, 16)\nkaprekar( 1, 255, 16, 16)\nkaprekar( 1, 288, 17, 17)\n"} +{"title": "Kaprekar numbers", "language": "Python", "task": "A positive integer is a Kaprekar number if:\n* It is \u00a0 '''1''' \u00a0 \u00a0 (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* [http://www.cs.uwaterloo.ca/journals/JIS/VOL3/iann2a.html The Kaprekar Numbers] by Douglas E. Iannucci (2000). [http://pictor.math.uqam.ca/~plouffe/OEIS/jis/The%20Kaprekar%20Numbers.pdf PDF version]\n\n\n;Related task:\n* \u00a0 [[Casting out nines]]\n\n", "solution": "\nBase = 10\nN = 6\nPaddy_cnt = 1\nfor n in range(N):\n for V in CastOut(Base,Start=Base**n,End=Base**(n+1)):\n for B in range(n+1,n*2+2):\n x,y = divmod(V*V,Base**B)\n if V == x+y and 0\nProduces:\n\n1: 1\n2: 9\n3: 45\n4: 55\n5: 99\n6: 297\n7: 703\n8: 999\n9: 2223\n10: 2728\n11: 4879\n12: 4950\n13: 5050\n14: 5292\n15: 7272\n16: 7777\n17: 9999\n18: 17344\n19: 22222\n20: 38962\n21: 77778\n22: 82656\n23: 95121\n24: 99999\n25: 142857\n26: 148149\n27: 181819\n28: 187110\n29: 208495\n30: 318682\n31: 329967\n32: 351352\n33: 356643\n34: 390313\n35: 461539\n36: 466830\n37: 499500\n38: 500500\n39: 533170\n40: 538461\n41: 609687\n42: 627615\n43: 643357\n44: 648648\n45: 670033\n46: 681318\n47: 791505\n48: 812890\n49: 818181\n50: 851851\n51: 857143\n52: 961038\n53: 994708\n54: 999999\n\nOther bases may be used e.g.:\n\nBase = 16\nN = 4\nPaddy_cnt = 1\nfor V in CastOut(Base,Start=1,End=Base**N):\n for B in range(1,N*2-1):\n x,y = divmod(V*V,Base**B)\n if V == x+y and 0\nProduces:\n\n1: 1\n2: 6\n3: a\n4: f\n5: 33\n6: 55\n7: 5b\n8: 78\n9: 88\n10: ab\n11: cd\n12: ff\n13: 15f\n14: 334\n15: 38e\n16: 492\n17: 4ed\n18: 7e0\n19: 820\n20: b13\n21: b6e\n22: c72\n23: ccc\n24: ea1\n25: fa5\n26: fff\n27: 191a\n28: 2a2b\n29: 3c3c\n30: 4444\n31: 5556\n32: 6667\n33: 7f80\n34: 8080\n35: 9999\n36: aaaa\n37: bbbc\n38: c3c4\n39: d5d5\n40: e6e6\n41: ffff\n\n"} +{"title": "Kernighans large earthquake problem", "language": "C", "task": "Brian Kernighan, in a [https://www.youtube.com/watch?v=Sg4U4r_AgJU lecture] at the University of Nottingham, described a [https://youtu.be/Sg4U4r_AgJU?t=50s 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": "Kernighans large earthquake problem", "language": "JavaScript", "task": "Brian Kernighan, in a [https://www.youtube.com/watch?v=Sg4U4r_AgJU lecture] at the University of Nottingham, described a [https://youtu.be/Sg4U4r_AgJU?t=50s 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": "\nconst fs = require(\"fs\");\nconst readline = require(\"readline\");\n\nconst args = process.argv.slice(2);\nif (!args.length) {\n console.error(\"must supply file name\");\n process.exit(1);\n}\n\nconst fname = args[0];\n\nconst readInterface = readline.createInterface({\n input: fs.createReadStream(fname),\n console: false,\n});\n\nreadInterface.on(\"line\", (line) => {\n const fields = line.split(/\\s+/);\n if (+fields[fields.length - 1] > 6) {\n console.log(line);\n }\n});\n"} +{"title": "Kernighans large earthquake problem", "language": "Python", "task": "Brian Kernighan, in a [https://www.youtube.com/watch?v=Sg4U4r_AgJU lecture] at the University of Nottingham, described a [https://youtu.be/Sg4U4r_AgJU?t=50s 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": "from os.path import expanduser\nfrom functools import (reduce)\nfrom itertools import (chain)\n\n\n# largeQuakes :: Int -> [String] -> [(String, String, String)]\ndef largeQuakes(n):\n def quake(threshold):\n def go(x):\n ws = x.split()\n return [tuple(ws)] if threshold < float(ws[2]) else []\n return lambda x: go(x)\n return concatMap(quake(n))\n\n\n# main :: IO ()\ndef main():\n print (\n largeQuakes(6)(\n open(expanduser('~/data.txt')).read().splitlines()\n )\n )\n\n\n# GENERIC ABSTRACTION -------------------------------------\n\n# concatMap :: (a -> [b]) -> [a] -> [b]\ndef concatMap(f):\n return lambda xs: list(\n chain.from_iterable(\n map(f, xs)\n )\n )\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} +{"title": "Keyboard input/Obtain a Y or N response", "language": "C", "task": "[[Category:Simple]]\n \n\n;Task:\nObtain a valid \u00a0 '''Y''' \u00a0 or \u00a0 '''N''' \u00a0 response from the [[input device::keyboard]]. \n\nThe keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing \u00a0 '''Y''' \u00a0 or \u00a0 '''N''' \u00a0 key-press from being evaluated. \n\nThe response should be obtained as soon as \u00a0 '''Y''' \u00a0 or \u00a0 '''N''' \u00a0 are pressed, and there should be no need to press an \u00a0 enter \u00a0 key.\n\n", "solution": "\n#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": "Keyboard input/Obtain a Y or N response", "language": "JavaScript", "task": "[[Category:Simple]]\n \n\n;Task:\nObtain a valid \u00a0 '''Y''' \u00a0 or \u00a0 '''N''' \u00a0 response from the [[input device::keyboard]]. \n\nThe keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing \u00a0 '''Y''' \u00a0 or \u00a0 '''N''' \u00a0 key-press from being evaluated. \n\nThe response should be obtained as soon as \u00a0 '''Y''' \u00a0 or \u00a0 '''N''' \u00a0 are pressed, and there should be no need to press an \u00a0 enter \u00a0 key.\n\n", "solution": "const readline = require('readline');\nreadline.emitKeypressEvents(process.stdin);\nprocess.stdin.setRawMode(true);\n\nvar wait_key = async function() {\n return await new Promise(function(resolve,reject) {\n var key_listen = function(str,key) {\n process.stdin.removeListener('keypress', key_listen);\n resolve(str);\n }\n process.stdin.on('keypress', key_listen);\n });\n}\n\nvar done = function() {\n process.exit();\n}\n\nvar go = async function() {\n do {\n console.log('Press any key...');\n var key = await wait_key();\n console.log(\"Key pressed is\",key);\n await new Promise(function(resolve) { setTimeout(resolve,1000); });\n } while(key != 'y');\n done();\n}\n\ngo();\n"} +{"title": "Keyboard input/Obtain a Y or N response", "language": "Python", "task": "[[Category:Simple]]\n \n\n;Task:\nObtain a valid \u00a0 '''Y''' \u00a0 or \u00a0 '''N''' \u00a0 response from the [[input device::keyboard]]. \n\nThe keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing \u00a0 '''Y''' \u00a0 or \u00a0 '''N''' \u00a0 key-press from being evaluated. \n\nThe response should be obtained as soon as \u00a0 '''Y''' \u00a0 or \u00a0 '''N''' \u00a0 are pressed, and there should be no need to press an \u00a0 enter \u00a0 key.\n\n", "solution": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom curses import wrapper\n#\n#\ndef main(stdscr):\n # const\n #y = ord(\"y\")\n #n = ord(\"n\")\n while True:\n # keyboard input interceptor|listener\n #window.nodelay(yes)\n # - If yes is 1, getch() will be non-blocking.\n # return char code\n #kb_Inpt = stdscr.getch()\n # return string\n kb_Inpt = stdscr.getkey()\n #if kb_Inpt == (y or n):\n if kb_Inpt.lower() == ('y' or 'n'):\n break\n return None\n #\n return None\n#\n#*** unit test ***#\nif __name__ == \"__main__\":\n #\n wrapper(main)"} +{"title": "Knight's tour", "language": "C", "task": "right\n\n;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 [http://en.wikipedia.org/wiki/Algebraic_chess_notation 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": "Knight's tour", "language": "Python", "task": "right\n\n;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 [http://en.wikipedia.org/wiki/Algebraic_chess_notation 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": "import copy\n\nboardsize=6\n_kmoves = ((2,1), (1,2), (-1,2), (-2,1), (-2,-1), (-1,-2), (1,-2), (2,-1)) \n\n\ndef chess2index(chess, boardsize=boardsize):\n 'Convert Algebraic chess notation to internal index format'\n chess = chess.strip().lower()\n x = ord(chess[0]) - ord('a')\n y = boardsize - int(chess[1:])\n return (x, y)\n \ndef boardstring(board, boardsize=boardsize):\n r = range(boardsize)\n lines = ''\n for y in r:\n lines += '\\n' + ','.join('%2i' % board[(x,y)] if board[(x,y)] else ' '\n for x in r)\n return lines\n \ndef knightmoves(board, P, boardsize=boardsize):\n Px, Py = P\n kmoves = set((Px+x, Py+y) for x,y in _kmoves)\n kmoves = set( (x,y)\n for x,y in kmoves\n if 0 <= x < boardsize\n and 0 <= y < boardsize\n and not board[(x,y)] )\n return kmoves\n\ndef accessibility(board, P, boardsize=boardsize):\n access = []\n brd = copy.deepcopy(board)\n for pos in knightmoves(board, P, boardsize=boardsize):\n brd[pos] = -1\n access.append( (len(knightmoves(brd, pos, boardsize=boardsize)), pos) )\n brd[pos] = 0\n return access\n \ndef knights_tour(start, boardsize=boardsize, _debug=False):\n board = {(x,y):0 for x in range(boardsize) for y in range(boardsize)}\n move = 1\n P = chess2index(start, boardsize)\n board[P] = move\n move += 1\n if _debug:\n print(boardstring(board, boardsize=boardsize))\n while move <= len(board):\n P = min(accessibility(board, P, boardsize))[1]\n board[P] = move\n move += 1\n if _debug:\n print(boardstring(board, boardsize=boardsize))\n input('\\n%2i next: ' % move)\n return board\n\nif __name__ == '__main__':\n while 1:\n boardsize = int(input('\\nboardsize: '))\n if boardsize < 5:\n continue\n start = input('Start position: ')\n board = knights_tour(start, boardsize)\n print(boardstring(board, boardsize=boardsize))"} +{"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 \u00a0 2nd step \u00a0 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": "Knuth's algorithm S", "language": "Python 3.x", "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 \u00a0 2nd step \u00a0 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": "from random import randrange\n\ndef s_of_n_creator(n):\n sample, i = [], 0\n def s_of_n(item):\n nonlocal i\n\n i += 1\n if i <= n:\n # Keep first n items\n sample.append(item)\n elif randrange(i) < n:\n # Keep item\n sample[randrange(n)] = item\n return sample\n return s_of_n\n\nif __name__ == '__main__':\n bin = [0]* 10\n items = range(10)\n print(\"Single run samples for n = 3:\")\n s_of_n = s_of_n_creator(3)\n for item in items:\n sample = s_of_n(item)\n print(\" Item: %i -> sample: %s\" % (item, sample))\n #\n for trial in range(100000):\n s_of_n = s_of_n_creator(3)\n for item in items:\n sample = s_of_n(item)\n for s in sample:\n bin[s] += 1\n print(\"\\nTest item frequencies for 100000 runs:\\n \",\n '\\n '.join(\"%i:%i\" % x for x in enumerate(bin)))"} +{"title": "Koch curve", "language": "C", "task": "Draw a Koch curve. See details: [https://en.wikipedia.org/wiki/Koch_snowflake Koch curve]\n\n", "solution": "\n#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": "Koch curve", "language": "JavaScript", "task": "Draw a Koch curve. See details: [https://en.wikipedia.org/wiki/Koch_snowflake Koch curve]\n\n", "solution": "(() => {\n 'use strict';\n\n // kochSnowflake :: Int -> (Float, Float) -> (Float, Float)\n // -> [(Float, Float)]\n const kochSnowflake = n => a => b => {\n // List of points on a Koch snowflake of order n, derived\n // from an equilateral triangle with base a b.\n const points = [a, equilateralApex(a)(b), b];\n return concat(\n zipWith(kochCurve(n))(points)(\n points.slice(1).concat([points[0]])\n )\n );\n };\n\n\n // koch :: Int -> (Float, Float) -> (Float, Float)\n // -> [(Float, Float)]\n const kochCurve = n => ab => xy => {\n // A Koch curve of order N, starting at the point\n // (a, b), and ending at the point (x, y).\n const go = n => ([ab, xy]) =>\n 0 !== n ? (() => {\n const [mp, mq] = midThirdOfLine(ab)(xy);\n const points = [\n ab,\n mp,\n equilateralApex(mp)(mq),\n mq,\n xy\n ];\n return zip(points)(points.slice(1))\n .flatMap(go(n - 1))\n })() : [xy];\n return [ab].concat(go(n)([ab, xy]));\n };\n\n\n // equilateralApex :: (Float, Float) -> (Float, Float) -> (Float, Float)\n const equilateralApex = p => q =>\n rotatedPoint(Math.PI / 3)(p)(q);\n\n\n // rotatedPoint :: Float -> (Float, Float) ->\n // (Float, Float) -> (Float, Float)\n const rotatedPoint = theta => ([ox, oy]) => ([a, b]) => {\n // The point ab rotated theta radians\n // around the origin xy.\n const [dx, dy] = rotatedVector(theta)(\n [a - ox, oy - b]\n );\n return [ox + dx, oy - dy];\n };\n\n\n // rotatedVector :: Float -> (Float, Float) -> (Float, Float)\n const rotatedVector = theta => ([x, y]) =>\n // The vector xy rotated by theta radians.\n [\n x * Math.cos(theta) - y * Math.sin(theta),\n x * Math.sin(theta) + y * Math.cos(theta)\n ];\n\n\n // midThirdOfLine :: (Float, Float) -> (Float, Float)\n // -> ((Float, Float), (Float, Float))\n const midThirdOfLine = ab => xy => {\n // Second of three equal segments of\n // the line between ab and xy.\n const\n vector = zipWith(dx => x => (dx - x) / 3)(xy)(ab),\n f = zipWith(add)(vector),\n p = f(ab);\n return [p, f(p)];\n };\n\n\n // TEST -----------------------------------------------\n // main :: IO ()\n const main = () =>\n // SVG showing a Koch snowflake of order 4.\n console.log(\n svgFromPoints(1024)(\n kochSnowflake(5)(\n [200, 600]\n )([800, 600])\n )\n );\n\n // SVG ----------------------------------------------\n\n // svgFromPoints :: Int -> [(Int, Int)] -> String\n const svgFromPoints = w => ps => [\n '`,\n `',\n ''\n ].join('\\n');\n\n\n // GENERIC --------------------------------------------\n\n // add :: Num -> Num -> Num\n const add = a => b => a + b;\n\n // concat :: [[a]] -> [a]\n const concat = xs => [].concat.apply([], xs);\n\n // zip :: [a] -> [b] -> [(a, b)]\n const zip = xs => ys =>\n xs.slice(\n 0, Math.min(xs.length, ys.length)\n ).map((x, i) => [x, ys[i]]);\n\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = f => xs => ys =>\n xs.slice(\n 0, Math.min(xs.length, ys.length)\n ).map((x, i) => f(x)(ys[i]));\n\n // MAIN ---\n return main();\n})();"} +{"title": "Koch curve", "language": "Python", "task": "Draw a Koch curve. See details: [https://en.wikipedia.org/wiki/Koch_snowflake Koch curve]\n\n", "solution": "'''Koch curve'''\n\nfrom math import cos, pi, sin\nfrom operator import add, sub\nfrom itertools import chain\n\n\n# kochSnowflake :: Int -> (Float, Float) -> (Float, Float) -> [(Float, Float)]\ndef kochSnowflake(n, a, b):\n '''List of points on a Koch snowflake of order n, derived\n from an equilateral triangle with base a b.\n '''\n points = [a, equilateralApex(a, b), b]\n return chain.from_iterable(map(\n kochCurve(n),\n points,\n points[1:] + [points[0]]\n ))\n\n\n# kochCurve :: Int -> (Float, Float) -> (Float, Float)\n# -> [(Float, Float)]\ndef kochCurve(n):\n '''List of points on a Koch curve of order n,\n starting at point ab, and ending at point xy.\n '''\n def koch(n):\n def goTuple(abxy):\n ab, xy = abxy\n if 0 == n:\n return [xy]\n else:\n mp, mq = midThirdOfLine(ab, xy)\n points = [\n ab,\n mp,\n equilateralApex(mp, mq),\n mq,\n xy\n ]\n return list(\n chain.from_iterable(map(\n koch(n - 1),\n zip(points, points[1:])\n ))\n )\n return goTuple\n\n def go(ab, xy):\n return [ab] + koch(n)((ab, xy))\n return go\n\n\n# equilateralApex :: (Float, Float) -> (Float, Float) -> (Float, Float)\ndef equilateralApex(p, q):\n '''Apex of triangle with base p q.\n '''\n return rotatedPoint(pi / 3)(p, q)\n\n\n# rotatedPoint :: Float -> (Float, Float) ->\n# (Float, Float) -> (Float, Float)\ndef rotatedPoint(theta):\n '''The point ab rotated theta radians\n around the origin xy.\n '''\n def go(xy, ab):\n ox, oy = xy\n a, b = ab\n dx, dy = rotatedVector(theta, (a - ox, oy - b))\n return ox + dx, oy - dy\n return go\n\n\n# rotatedVector :: Float -> (Float, Float) -> (Float, Float)\ndef rotatedVector(theta, xy):\n '''The vector xy rotated by theta radians.\n '''\n x, y = xy\n return (\n x * cos(theta) - y * sin(theta),\n x * sin(theta) + y * cos(theta)\n )\n\n\n# midThirdOfLine :: (Float, Float) -> (Float, Float)\n# -> ((Float, Float), (Float, Float))\ndef midThirdOfLine(ab, xy):\n '''Second of three equal segments of\n the line between ab and xy.\n '''\n vector = [x / 3 for x in map(sub, xy, ab)]\n\n def f(p):\n return tuple(map(add, vector, p))\n p = f(ab)\n return (p, f(p))\n\n\n# -------------------------- TEST --------------------------\n# main :: IO ()\ndef main():\n '''SVG for Koch snowflake of order 4.\n '''\n print(\n svgFromPoints(1024)(\n kochSnowflake(\n 4, (200, 600), (800, 600)\n )\n )\n )\n\n\n# -------------------------- SVG ---------------------------\n\n# svgFromPoints :: Int -> [(Float, Float)] -> SVG String\ndef svgFromPoints(w):\n '''Width of square canvas -> Point list -> SVG string.\n '''\n def go(xys):\n xs = ' '.join(map(\n lambda xy: str(round(xy[0], 2)) + ' ' + str(round(xy[1], 2)),\n xys\n ))\n return '\\n'.join([\n '',\n f'',\n ''\n ])\n return go\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} +{"title": "Kolakoski sequence", "language": "C", "task": "The natural numbers, (excluding zero); with the property that:\n: ''if you form a new sequence from the counts of runs of the same number in the first sequence, this new sequence is the same as the first sequence''.\n\n;Example:\nThis is ''not'' a Kolakoski sequence:\n1,1,2,2,2,1,2,2,1,2,...\nIts sequence of run counts, (sometimes called a run length encoding, (RLE); but a true RLE also gives the character that each run encodes), is calculated like this:\n\n: Starting from the leftmost number of the sequence we have 2 ones, followed by 3 twos, then 1 ones, 2 twos, 1 one, ...\n\nThe above gives the RLE of:\n2, 3, 1, 2, 1, ...\n\nThe original sequence is different from its RLE in this case. '''It would be the same for a true Kolakoski sequence'''.\n\n;Creating a Kolakoski sequence:\n\nLets start with the two numbers (1, 2) that we will cycle through; i.e. they will be used in this order: 1,2,1,2,1,2,....\n\n# We start the sequence s with the first item from the cycle c: 1\n# An index, k, into the, (expanding), sequence will step, or index through each item of the sequence s from the first, at its own rate. \nWe will arrange that the k'th item of s states how many ''times'' the ''last'' item of sshould appear at the end of s.\n\nWe started s with 1 and therefore s[k] states that it should appear only the 1 time.\n\nIncrement k\nGet the next item from c and append it to the end of sequence s. s will then become: 1, 2\nk was moved to the second item in the list and s[k] states that it should appear two times, so append another of the last item to the sequence s: 1, 2,2\nIncrement k\nAppend the next item from the cycle to the list: 1, 2,2, 1\nk is now at the third item in the list that states that the last item should appear twice so add another copy of the last item to the sequence s: 1, 2,2, 1,1\nincrement k\n\n...\n\n'''Note''' that the RLE of 1, 2, 2, 1, 1, ... begins 1, 2, 2 which is the beginning of the original sequence. The generation algorithm ensures that this will always be the case.\n\n;Task:\n# Create a routine/proceedure/function/... that given an initial ordered list/array/tuple etc of the natural numbers (1, 2), returns the next number from the list when accessed in a cycle.\n# Create another routine that when given the initial ordered list (1, 2) and the minimum length of the sequence to generate; uses the first routine and the algorithm above, to generate at least the requested first members of the kolakoski sequence.\n# Create a routine that when given a sequence, creates the run length encoding of that sequence (as defined above) and returns the result of checking if sequence starts with the exact members of its RLE. (But ''note'', due to sampling, do not compare the last member of the RLE).\n# Show, on this page, (compactly), the first 20 members of the sequence generated from (1, 2)\n# Check the sequence againt its RLE.\n# Show, on this page, the first 20 members of the sequence generated from (2, 1)\n# Check the sequence againt its RLE.\n# Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 1, 2)\n# Check the sequence againt its RLE.\n# Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 2, 1)\n# Check the sequence againt its RLE.\n(There are rules on generating Kolakoski sequences from this method that are broken by the last example)\n\n", "solution": "#include \n#include \n\n#define TRUE 1\n#define FALSE 0\n\ntypedef int bool;\n\nint next_in_cycle(int *c, int len, int index) {\n return c[index % len];\n}\n\nvoid kolakoski(int *c, int *s, int clen, int slen) {\n int i = 0, j, k = 0;\n while (TRUE) {\n s[i] = next_in_cycle(c, clen, k);\n if (s[k] > 1) {\n for (j = 1; j < s[k]; ++j) {\n if (++i == slen) return;\n s[i] = s[i - 1];\n }\n }\n if (++i == slen) return;\n k++;\n }\n}\n\nbool possible_kolakoski(int *s, int len) {\n int i, j = 0, prev = s[0], count = 1;\n int *rle = calloc(len, sizeof(int));\n bool result = TRUE;\n for (i = 1; i < len; ++i) {\n if (s[i] == prev) {\n count++;\n }\n else {\n rle[j++] = count;\n count = 1;\n prev = s[i];\n }\n }\n /* no point adding final 'count' to rle as we're not going to compare it anyway */\n for (i = 0; i < j; i++) {\n if (rle[i] != s[i]) {\n result = FALSE;\n break;\n }\n }\n free(rle);\n return result;\n}\n\nvoid print_array(int *a, int len) {\n int i;\n printf(\"[\");\n for (i = 0; i < len; ++i) {\n printf(\"%d\", a[i]);\n if (i < len - 1) printf(\", \");\n }\n printf(\"]\");\n}\n\nint main() {\n int i, clen, slen, *s;\n int c0[2] = {1, 2};\n int c1[2] = {2, 1};\n int c2[4] = {1, 3, 1, 2};\n int c3[4] = {1, 3, 2, 1};\n int *cs[4] = {c0, c1, c2, c3};\n bool p;\n int clens[4] = {2, 2, 4, 4};\n int slens[4] = {20, 20, 30, 30};\n for (i = 0; i < 4; ++i) {\n clen = clens[i];\n slen = slens[i];\n s = calloc(slen, sizeof(int));\n kolakoski(cs[i], s, clen, slen);\n printf(\"First %d members of the sequence generated by \", slen);\n print_array(cs[i], clen);\n printf(\":\\n\");\n print_array(s, slen);\n printf(\"\\n\");\n p = possible_kolakoski(s, slen);\n printf(\"Possible Kolakoski sequence? %s\\n\\n\", p ? \"True\" : \"False\");\n free(s); \n }\n return 0;\n}"} +{"title": "Kolakoski sequence", "language": "Python", "task": "The natural numbers, (excluding zero); with the property that:\n: ''if you form a new sequence from the counts of runs of the same number in the first sequence, this new sequence is the same as the first sequence''.\n\n;Example:\nThis is ''not'' a Kolakoski sequence:\n1,1,2,2,2,1,2,2,1,2,...\nIts sequence of run counts, (sometimes called a run length encoding, (RLE); but a true RLE also gives the character that each run encodes), is calculated like this:\n\n: Starting from the leftmost number of the sequence we have 2 ones, followed by 3 twos, then 1 ones, 2 twos, 1 one, ...\n\nThe above gives the RLE of:\n2, 3, 1, 2, 1, ...\n\nThe original sequence is different from its RLE in this case. '''It would be the same for a true Kolakoski sequence'''.\n\n;Creating a Kolakoski sequence:\n\nLets start with the two numbers (1, 2) that we will cycle through; i.e. they will be used in this order: 1,2,1,2,1,2,....\n\n# We start the sequence s with the first item from the cycle c: 1\n# An index, k, into the, (expanding), sequence will step, or index through each item of the sequence s from the first, at its own rate. \nWe will arrange that the k'th item of s states how many ''times'' the ''last'' item of sshould appear at the end of s.\n\nWe started s with 1 and therefore s[k] states that it should appear only the 1 time.\n\nIncrement k\nGet the next item from c and append it to the end of sequence s. s will then become: 1, 2\nk was moved to the second item in the list and s[k] states that it should appear two times, so append another of the last item to the sequence s: 1, 2,2\nIncrement k\nAppend the next item from the cycle to the list: 1, 2,2, 1\nk is now at the third item in the list that states that the last item should appear twice so add another copy of the last item to the sequence s: 1, 2,2, 1,1\nincrement k\n\n...\n\n'''Note''' that the RLE of 1, 2, 2, 1, 1, ... begins 1, 2, 2 which is the beginning of the original sequence. The generation algorithm ensures that this will always be the case.\n\n;Task:\n# Create a routine/proceedure/function/... that given an initial ordered list/array/tuple etc of the natural numbers (1, 2), returns the next number from the list when accessed in a cycle.\n# Create another routine that when given the initial ordered list (1, 2) and the minimum length of the sequence to generate; uses the first routine and the algorithm above, to generate at least the requested first members of the kolakoski sequence.\n# Create a routine that when given a sequence, creates the run length encoding of that sequence (as defined above) and returns the result of checking if sequence starts with the exact members of its RLE. (But ''note'', due to sampling, do not compare the last member of the RLE).\n# Show, on this page, (compactly), the first 20 members of the sequence generated from (1, 2)\n# Check the sequence againt its RLE.\n# Show, on this page, the first 20 members of the sequence generated from (2, 1)\n# Check the sequence againt its RLE.\n# Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 1, 2)\n# Check the sequence againt its RLE.\n# Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 2, 1)\n# Check the sequence againt its RLE.\n(There are rules on generating Kolakoski sequences from this method that are broken by the last example)\n\n", "solution": "import itertools\n\ndef cycler(start_items):\n\treturn itertools.cycle(start_items).__next__\n\ndef _kolakoski_gen(start_items):\n s, k = [], 0\n c = cycler(start_items)\n while True:\n c_next = c()\n s.append(c_next)\n sk = s[k]\n yield sk\n if sk > 1:\n s += [c_next] * (sk - 1)\n k += 1\n\ndef kolakoski(start_items=(1, 2), length=20):\n return list(itertools.islice(_kolakoski_gen(start_items), length))\n\ndef _run_len_encoding(truncated_series):\n return [len(list(group)) for grouper, group in itertools.groupby(truncated_series)][:-1]\n\ndef is_series_eq_its_rle(series):\n rle = _run_len_encoding(series)\n return (series[:len(rle)] == rle) if rle else not series\n\nif __name__ == '__main__':\n for start_items, length in [((1, 2), 20), ((2, 1), 20), \n ((1, 3, 1, 2), 30), ((1, 3, 2, 1), 30)]:\n print(f'\\n## {length} members of the series generated from {start_items} is:')\n s = kolakoski(start_items, length)\n print(f' {s}')\n ans = 'YES' if is_series_eq_its_rle(s) else 'NO'\n print(f' Does it look like a Kolakoski sequence: {ans}')"} +{"title": "Kosaraju", "language": "Python", "task": "[[Category:Algorithm]]\n\nKosaraju's algorithm (also known as the Kosaraju\u2013Sharir algorithm) is a linear time algorithm to find the strongly connected components of a directed graph. Aho, Hopcroft and Ullman credit it to an unpublished paper from 1978 by S. Rao Kosaraju. The same algorithm was independently discovered by Micha Sharir and published by him in 1981. It makes use of the fact that the transpose graph (the same graph with the direction of every edge reversed) has exactly the same strongly connected components as the original graph.\n\nFor this task consider the directed graph with these connections:\n 0 -> 1\n 1 -> 2\n 2 -> 0\n 3 -> 1, 3 -> 2, 3 -> 4\n 4 -> 3, 4 -> 5\n 5 -> 2, 5 -> 6\n 6 -> 5\n 7 -> 4, 7 -> 6, 7 -> 7\n\nAnd report the kosaraju strongly connected component for each node.\n\n;References:\n* The article on Wikipedia.\n\n", "solution": "def kosaraju(g):\n class nonlocal: pass\n\n # 1. For each vertex u of the graph, mark u as unvisited. Let l be empty.\n size = len(g)\n\n vis = [False]*size # vertexes that have been visited\n l = [0]*size\n nonlocal.x = size\n t = [[]]*size # transpose graph\n\n def visit(u):\n if not vis[u]:\n vis[u] = True\n for v in g[u]:\n visit(v)\n t[v] = t[v] + [u]\n nonlocal.x = nonlocal.x - 1\n l[nonlocal.x] = u\n\n # 2. For each vertex u of the graph do visit(u)\n for u in range(len(g)):\n visit(u)\n c = [0]*size\n\n def assign(u, root):\n if vis[u]:\n vis[u] = False\n c[u] = root\n for v in t[u]:\n assign(v, root)\n\n # 3: For each element u of l in order, do assign(u, u)\n for u in l:\n assign(u, u)\n\n return c\n\ng = [[1], [2], [0], [1,2,4], [3,5], [2,6], [5], [4,6,7]]\nprint kosaraju(g)"} +{"title": "Lah numbers", "language": "C", "task": "Lah numbers, sometimes referred to as ''Stirling numbers of the third kind'', are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials.\n\nUnsigned Lah numbers count the number of ways a set of '''n''' elements can be partitioned into '''k''' non-empty linearly ordered subsets.\n\nLah numbers are closely related to Stirling numbers of the first & second kinds, and may be derived from them.\n\nLah numbers obey the identities and relations:\n L(n, 0), L(0, k) = 0 # for n, k > 0\n L(n, n) = 1\n L(n, 1) = n!\n L(n, k) = ( n! * (n - 1)! ) / ( k! * (k - 1)! ) / (n - k)! # For unsigned Lah numbers\n ''or''\n L(n, k) = (-1)**n * ( n! * (n - 1)! ) / ( k! * (k - 1)! ) / (n - k)! # For signed Lah numbers\n\n;Task:\n:* Write a routine (function, procedure, whatever) to find '''unsigned Lah numbers'''. There are several methods to generate unsigned Lah numbers. 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 unsigned Lah numbers, '''L(n, k)''', up to '''L(12, 12)'''. it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where L(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 '''L(n, k)''' where '''n == 100'''.\n\n\n;See also:\n\n:* '''Wikipedia - Lah number'''\n:* '''OEIS:A105278 - Unsigned Lah numbers'''\n:* '''OEIS:A008297 - Signed Lah numbers'''\n\n\n;Related Tasks:\n\n:* '''Stirling numbers of the first kind'''\n:* '''Stirling numbers of the second kind'''\n:* '''Bell numbers'''\n\n\n", "solution": "#include \n#include \n\nuint64_t factorial(uint64_t n) {\n uint64_t res = 1;\n if (n == 0) return res;\n while (n > 0) res *= n--;\n return res;\n}\n\nuint64_t lah(uint64_t n, uint64_t k) {\n if (k == 1) return factorial(n);\n if (k == n) return 1;\n if (k > n) return 0;\n if (k < 1 || n < 1) return 0;\n return (factorial(n) * factorial(n - 1)) / (factorial(k) * factorial(k - 1)) / factorial(n - k);\n}\n\nint main() {\n int row, i;\n\n printf(\"Unsigned Lah numbers: L(n, k):\\n\");\n printf(\"n/k \");\n for (i = 0; i < 13; i++) {\n printf(\"%10d \", i);\n }\n printf(\"\\n\");\n for (row = 0; row < 13; row++) {\n printf(\"%-3d\", row);\n for (i = 0; i < row + 1; i++) {\n uint64_t l = lah(row, i);\n printf(\"%11lld\", l);\n }\n printf(\"\\n\");\n }\n\n return 0;\n}"} +{"title": "Lah numbers", "language": "Python", "task": "Lah numbers, sometimes referred to as ''Stirling numbers of the third kind'', are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials.\n\nUnsigned Lah numbers count the number of ways a set of '''n''' elements can be partitioned into '''k''' non-empty linearly ordered subsets.\n\nLah numbers are closely related to Stirling numbers of the first & second kinds, and may be derived from them.\n\nLah numbers obey the identities and relations:\n L(n, 0), L(0, k) = 0 # for n, k > 0\n L(n, n) = 1\n L(n, 1) = n!\n L(n, k) = ( n! * (n - 1)! ) / ( k! * (k - 1)! ) / (n - k)! # For unsigned Lah numbers\n ''or''\n L(n, k) = (-1)**n * ( n! * (n - 1)! ) / ( k! * (k - 1)! ) / (n - k)! # For signed Lah numbers\n\n;Task:\n:* Write a routine (function, procedure, whatever) to find '''unsigned Lah numbers'''. There are several methods to generate unsigned Lah numbers. 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 unsigned Lah numbers, '''L(n, k)''', up to '''L(12, 12)'''. it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where L(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 '''L(n, k)''' where '''n == 100'''.\n\n\n;See also:\n\n:* '''Wikipedia - Lah number'''\n:* '''OEIS:A105278 - Unsigned Lah numbers'''\n:* '''OEIS:A008297 - Signed Lah numbers'''\n\n\n;Related Tasks:\n\n:* '''Stirling numbers of the first kind'''\n:* '''Stirling numbers of the second kind'''\n:* '''Bell numbers'''\n\n\n", "solution": "from math import (comb,\n factorial)\n\n\ndef lah(n, k):\n if k == 1:\n return factorial(n)\n if k == n:\n return 1\n if k > n:\n return 0\n if k < 1 or n < 1:\n return 0\n return comb(n, k) * factorial(n - 1) // factorial(k - 1)\n\n\ndef main():\n print(\"Unsigned Lah numbers: L(n, k):\")\n print(\"n/k \", end='\\t')\n for i in range(13):\n print(\"%11d\" % i, end='\\t')\n print()\n for row in range(13):\n print(\"%-4d\" % row, end='\\t')\n for i in range(row + 1):\n l = lah(row, i)\n print(\"%11d\" % l, end='\\t')\n print()\n print(\"\\nMaximum value from the L(100, *) row:\")\n max_val = max(lah(100, a) for a in range(100))\n print(max_val)\n\n\nif __name__ == '__main__':\n main()"} +{"title": "Largest int from concatenated ints", "language": "C", "task": ";Task: \nGiven 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 \u00a0 and \u00a0 show your program output here.\n\n:::::* \u00a0 {1, 34, 3, 98, 9, 76, 45, 4}\n:::::* \u00a0 {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* \u00a0 [http://www.quora.com/Algorithms/What-is-the-most-efficient-way-to-arrange-the-given-numbers-to-form-the-biggest-number Algorithms: What is the most efficient way to arrange the given numbers to form the biggest number?]\n* \u00a0 [http://stackoverflow.com/questions/14532105/constructing-the-largest-number-possible-by-rearranging-a-list/14539943#14539943 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 int from concatenated ints", "language": "JavaScript", "task": ";Task: \nGiven 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 \u00a0 and \u00a0 show your program output here.\n\n:::::* \u00a0 {1, 34, 3, 98, 9, 76, 45, 4}\n:::::* \u00a0 {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* \u00a0 [http://www.quora.com/Algorithms/What-is-the-most-efficient-way-to-arrange-the-given-numbers-to-form-the-biggest-number Algorithms: What is the most efficient way to arrange the given numbers to form the biggest number?]\n* \u00a0 [http://stackoverflow.com/questions/14532105/constructing-the-largest-number-possible-by-rearranging-a-list/14539943#14539943 Constructing the largest number possible by rearranging a list]\n\n", "solution": " (function () {\n 'use strict';\n\n // maxCombine :: [Int] -> Int\n function maxCombine(xs) {\n return parseInt(\n xs.sort(\n function (x, y) {\n var a = x.toString(),\n b = y.toString(),\n ab = parseInt(a + b),\n ba = parseInt(b + a);\n\n return ab > ba ? -1 : (ab < ba ? 1 : 0);\n }\n )\n .join(''), 10\n );\n }\n\n return [\n [1, 34, 3, 98, 9, 76, 45, 4],\n [54, 546, 548, 60]\n ].map(maxCombine);\n\n })();\n"} +{"title": "Largest int from concatenated ints", "language": "Python", "task": ";Task: \nGiven 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 \u00a0 and \u00a0 show your program output here.\n\n:::::* \u00a0 {1, 34, 3, 98, 9, 76, 45, 4}\n:::::* \u00a0 {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* \u00a0 [http://www.quora.com/Algorithms/What-is-the-most-efficient-way-to-arrange-the-given-numbers-to-form-the-biggest-number Algorithms: What is the most efficient way to arrange the given numbers to form the biggest number?]\n* \u00a0 [http://stackoverflow.com/questions/14532105/constructing-the-largest-number-possible-by-rearranging-a-list/14539943#14539943 Constructing the largest number possible by rearranging a list]\n\n", "solution": "try:\n cmp # Python 2 OK or NameError in Python 3\n def maxnum(x):\n return ''.join(sorted((str(n) for n in x),\n cmp=lambda x,y:cmp(y+x, x+y)))\nexcept NameError:\n # Python 3\n from functools import cmp_to_key\n def cmp(x, y):\n return -1 if x\n"} +{"title": "Largest number divisible by its digits", "language": "C", "task": ";Task:\nFind the largest base 10 integer whose digits are all different, \u00a0 and \u00a0 is evenly divisible by each of its individual digits.\n\n\nThese numbers are also known as \u00a0 '''Lynch-Bell numbers''', \u00a0 numbers \u00a0 '''n''' \u00a0 such that the\n(base ten) digits are all different (and do not include zero) \u00a0 and \u00a0 '''n''' \u00a0 is divisible by each of its individual digits. \n\n\n;Example:\n'''135''' \u00a0 is evenly divisible by \u00a0 '''1''', \u00a0 '''3''', \u00a0 and \u00a0 '''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:* \u00a0 [https://rosettacode.org/wiki/Gapful_numbers gapful numbers].\n:* \u00a0 [https://rosettacode.org/wiki/Palindromic_gapful_numbers palindromic gapful numbers]. \n\n\n;Also see:\n:* \u00a0 The OEIS sequence: \u00a0 [http://oeis.org/A115569 A115569: Lynch-Bell numbers]. \n\n", "solution": "#include\n#include\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef char bool;\n\ntypedef unsigned long long uint64;\n\nbool div_by_all(uint64 num, char digits[], int len) {\n int i, d;\n for (i = 0; i < len; ++i) {\n d = digits[i];\n d = (d <= '9') ? d - '0' : d - 'W';\n if (num % d != 0) return FALSE;\n }\n return TRUE;\n}\n\nint main() {\n uint64 i, magic = 15 * 14 * 13 * 12 * 11;\n uint64 high = 0xfedcba987654321 / magic * magic;\n int j, len;\n char c, *p, s[17], sd[16], found[16];\n\n for (i = high; i >= magic; i -= magic) {\n if (i % 16 == 0) continue; // can't end in '0'\n snprintf(s, 17, \"%llx\", i); // always generates lower case a-f\n if (strchr(s, '0') - s >= 0) continue; // can't contain '0'\n for (j = 0; j < 16; ++j) found[j] = FALSE;\n len = 0;\n for (p = s; *p; ++p) {\n if (*p <= '9') {\n c = *p - '0';\n } else {\n c = *p - 87;\n }\n if (!found[c]) {\n found[c] = TRUE;\n sd[len++] = *p;\n }\n }\n if (len != p - s) {\n continue; // digits must be unique\n }\n if (div_by_all(i, sd, len)) {\n printf(\"Largest hex number is %llx\\n\", i);\n break;\n }\n }\n return 0;\n}"} +{"title": "Largest number divisible by its digits", "language": "Python", "task": ";Task:\nFind the largest base 10 integer whose digits are all different, \u00a0 and \u00a0 is evenly divisible by each of its individual digits.\n\n\nThese numbers are also known as \u00a0 '''Lynch-Bell numbers''', \u00a0 numbers \u00a0 '''n''' \u00a0 such that the\n(base ten) digits are all different (and do not include zero) \u00a0 and \u00a0 '''n''' \u00a0 is divisible by each of its individual digits. \n\n\n;Example:\n'''135''' \u00a0 is evenly divisible by \u00a0 '''1''', \u00a0 '''3''', \u00a0 and \u00a0 '''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:* \u00a0 [https://rosettacode.org/wiki/Gapful_numbers gapful numbers].\n:* \u00a0 [https://rosettacode.org/wiki/Palindromic_gapful_numbers palindromic gapful numbers]. \n\n\n;Also see:\n:* \u00a0 The OEIS sequence: \u00a0 [http://oeis.org/A115569 A115569: Lynch-Bell numbers]. \n\n", "solution": "===base 10===\nUsing the insights presented in the preamble to the Raku (base 10) example:\n"} +{"title": "Largest number divisible by its digits", "language": "Python 3.7", "task": ";Task:\nFind the largest base 10 integer whose digits are all different, \u00a0 and \u00a0 is evenly divisible by each of its individual digits.\n\n\nThese numbers are also known as \u00a0 '''Lynch-Bell numbers''', \u00a0 numbers \u00a0 '''n''' \u00a0 such that the\n(base ten) digits are all different (and do not include zero) \u00a0 and \u00a0 '''n''' \u00a0 is divisible by each of its individual digits. \n\n\n;Example:\n'''135''' \u00a0 is evenly divisible by \u00a0 '''1''', \u00a0 '''3''', \u00a0 and \u00a0 '''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:* \u00a0 [https://rosettacode.org/wiki/Gapful_numbers gapful numbers].\n:* \u00a0 [https://rosettacode.org/wiki/Palindromic_gapful_numbers palindromic gapful numbers]. \n\n\n;Also see:\n:* \u00a0 The OEIS sequence: \u00a0 [http://oeis.org/A115569 A115569: Lynch-Bell numbers]. \n\n", "solution": "'''Largest number divisible by its digits'''\n\nfrom itertools import (chain, permutations)\nfrom functools import (reduce)\nfrom math import (gcd)\n\n\n# main :: IO ()\ndef main():\n '''Tests'''\n\n # (Division by zero is not an option, so 0 and 5 are omitted)\n digits = [1, 2, 3, 4, 6, 7, 8, 9]\n\n # Least common multiple of the digits above\n lcmDigits = reduce(lcm, digits)\n\n # Any 7 items drawn from the digits above,\n # including any two of [1, 4, 7]\n sevenDigits = ((delete)(digits)(x) for x in [1, 4, 7])\n\n print(\n max(\n (\n intFromDigits(x) for x\n in concatMap(permutations)(sevenDigits)\n ),\n key=lambda n: n if 0 == n % lcmDigits else 0\n )\n )\n\n\n# intFromDigits :: [Int] -> Int\ndef intFromDigits(xs):\n '''An integer derived from an\n ordered list of digits.\n '''\n return reduce(lambda a, x: a * 10 + x, xs, 0)\n\n\n# ----------------------- GENERIC ------------------------\n\n# concatMap :: (a -> [b]) -> [a] -> [b]\ndef concatMap(f):\n '''A concatenated list over which a function has been\n mapped. The list monad can be derived by using a\n function f which wraps its output in a list,\n (using an empty list to represent computational failure).\n '''\n def go(xs):\n return chain.from_iterable(map(f, xs))\n return go\n\n\n# delete :: Eq a => [a] -> a -> [a]\ndef delete(xs):\n '''xs with the first instance of\n x removed.\n '''\n def go(x):\n ys = xs.copy()\n ys.remove(x)\n return ys\n return go\n\n\n# lcm :: Int -> Int -> Int\ndef lcm(x, y):\n '''The smallest positive integer divisible\n without remainder by both x and y.\n '''\n return 0 if (0 == x or 0 == y) else abs(\n y * (x // gcd(x, y))\n )\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} +{"title": "Last Friday of each month", "language": "C", "task": "[[Category:Date and time]]\n\n;Task:\nWrite 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 Friday of each month", "language": "Nodejs", "task": "[[Category:Date and time]]\n\n;Task:\nWrite 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": "var last_friday_of_month, print_last_fridays_of_month;\n\nlast_friday_of_month = function(year, month) {\n var i, last_day;\n i = 0;\n while (true) {\n last_day = new Date(year, month, i);\n if (last_day.getDay() === 5) {\n return last_day.toDateString();\n }\n i -= 1;\n }\n};\n\nprint_last_fridays_of_month = function(year) {\n var month, results;\n results = [];\n for (month = 1; month <= 12; ++month) {\n results.push(console.log(last_friday_of_month(year, month)));\n }\n return results;\n};\n\n(function() {\n var year;\n year = parseInt(process.argv[2]);\n return print_last_fridays_of_month(year);\n})();"} +{"title": "Last Friday of each month", "language": "Python", "task": "[[Category:Date and time]]\n\n;Task:\nWrite 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": "import calendar\n\ndef last_fridays(year):\n for month in range(1, 13):\n last_friday = max(week[calendar.FRIDAY]\n for week in calendar.monthcalendar(year, month))\n print('{:4d}-{:02d}-{:02d}'.format(year, month, last_friday))"} +{"title": "Last letter-first letter", "language": "C", "task": "A certain children's game involves starting with a word in a particular category. \u00a0 Each participant in turn says a word, but that word must begin with the final letter of the previous word. \u00a0 Once a word has been given, it cannot be repeated. \u00a0 If an opponent cannot give a word in the category, they fall out of the game. \n\n\nFor example, with \u00a0 \"animals\" \u00a0 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 \u00a0 (extracted from \u00a0 Wikipedia's list of Pokemon) \u00a0 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 \u00a0 646 \u00a0 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": "Last letter-first letter", "language": "Node.js", "task": "A certain children's game involves starting with a word in a particular category. \u00a0 Each participant in turn says a word, but that word must begin with the final letter of the previous word. \u00a0 Once a word has been given, it cannot be repeated. \u00a0 If an opponent cannot give a word in the category, they fall out of the game. \n\n\nFor example, with \u00a0 \"animals\" \u00a0 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 \u00a0 (extracted from \u00a0 Wikipedia's list of Pokemon) \u00a0 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 \u00a0 646 \u00a0 names.\n\n", "solution": "/**\n * Find the letter the word ends on\n * @param {string} word\n * @returns {string}\n */\nconst endsWith = word => word[word.length - 1];\n\n/**\n * Remove the used elements from the candidate elements\n * @param {Array} words Candidate words\n * @param {Array} used Used words\n * @returns {*}\n */\nconst getCandidates = (words, used) => words.filter(e => !used.includes(e));\n\n/**\n * Build a map of letters to words that start with that letter\n * @param {Array} words\n * @returns {Map>}\n */\nconst buildLookup = words => {\n const lookup = new Map();\n words.forEach(e => {\n const start = e[0];\n lookup.set(start, [...(lookup.get(start) || []), e]);\n });\n return lookup;\n};\n\n\n/**\n * Main function\n * @param {Array} names\n */\nconst findPaths = names => {\n const t0 = process.hrtime();\n console.log('Checking:', names.length, 'names');\n const lookup = buildLookup(names);\n\n let maxNum = 0;\n let maxPaths = [];\n\n const parseResult = arr => {\n if (typeof arr[0] === 'object') {\n arr.forEach(el => parseResult(el))\n } else {\n if (arr.length > maxNum) {\n maxNum = arr.length;\n maxPaths = [arr];\n }\n if (arr.length === maxNum) {\n maxPaths.push(arr)\n }\n }\n };\n\n const searchWords = (word, res) => {\n const cs = getCandidates(lookup.get(endsWith(word)) || [], res);\n return cs.length ? cs.map(e => searchWords(e, [...res, e])) : res;\n };\n\n names.forEach(word => {\n const res = searchWords(word, [word]);\n parseResult(res);\n });\n\n const t1 = process.hrtime(t0);\n console.info('Execution time (hr): %ds %dms', t1[0], t1[1] / 1000000);\n console.log('Max Path:', maxNum);\n console.log('Matching Paths:', maxPaths.length);\n console.log('Example Path:', maxPaths[0]);\n\n};\n\nconst pokimon = [\"audino\", \"bagon\", \"baltoy\", \"banette\",\n \"bidoof\", \"braviary\", \"bronzor\", \"carracosta\", \"charmeleon\",\n \"cresselia\", \"croagunk\", \"darmanitan\", \"deino\", \"emboar\",\n \"emolga\", \"exeggcute\", \"gabite\", \"girafarig\", \"gulpin\",\n \"haxorus\", \"heatmor\", \"heatran\", \"ivysaur\", \"jellicent\",\n \"jumpluff\", \"kangaskhan\", \"kricketune\", \"landorus\", \"ledyba\",\n \"loudred\", \"lumineon\", \"lunatone\", \"machamp\", \"magnezone\",\n \"mamoswine\", \"nosepass\", \"petilil\", \"pidgeotto\", \"pikachu\",\n \"pinsir\", \"poliwrath\", \"poochyena\", \"porygon2\", \"porygonz\",\n \"registeel\", \"relicanth\", \"remoraid\", \"rufflet\", \"sableye\",\n \"scolipede\", \"scrafty\", \"seaking\", \"sealeo\", \"silcoon\",\n \"simisear\", \"snivy\", \"snorlax\", \"spoink\", \"starly\", \"tirtouga\",\n \"trapinch\", \"treecko\", \"tyrogue\", \"vigoroth\", \"vulpix\",\n \"wailord\", \"wartortle\", \"whismur\", \"wingull\", \"yamask\"];\n\nfindPaths(pokimon);\n"} +{"title": "Last letter-first letter", "language": "Python", "task": "A certain children's game involves starting with a word in a particular category. \u00a0 Each participant in turn says a word, but that word must begin with the final letter of the previous word. \u00a0 Once a word has been given, it cannot be repeated. \u00a0 If an opponent cannot give a word in the category, they fall out of the game. \n\n\nFor example, with \u00a0 \"animals\" \u00a0 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 \u00a0 (extracted from \u00a0 Wikipedia's list of Pokemon) \u00a0 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 \u00a0 646 \u00a0 names.\n\n", "solution": "import psyco\n\nnsolutions = 0\n\ndef search(sequences, ord_minc, curr_word, current_path,\n current_path_len, longest_path):\n global nsolutions\n\n current_path[current_path_len] = curr_word\n current_path_len += 1\n\n if current_path_len == len(longest_path):\n nsolutions += 1\n elif current_path_len > len(longest_path):\n nsolutions = 1\n longest_path[:] = current_path[:current_path_len]\n\n # recursive search\n last_char_index = ord(curr_word[-1]) - ord_minc\n if last_char_index >= 0 and last_char_index < len(sequences):\n for pair in sequences[last_char_index]:\n if not pair[1]:\n pair[1] = True\n search(sequences, ord_minc, pair[0], current_path,\n current_path_len, longest_path)\n pair[1] = False\n\n\ndef find_longest_chain(words):\n ord_minc = ord(min(word[0] for word in words))\n ord_maxc = ord(max(word[0] for word in words))\n sequences = [[] for _ in xrange(ord_maxc - ord_minc + 1)]\n for word in words:\n sequences[ord(word[0]) - ord_minc].append([word, False])\n\n current_path = [None] * len(words)\n longest_path = []\n\n # try each item as possible start\n for seq in sequences:\n for pair in seq:\n pair[1] = True\n search(sequences, ord_minc, pair[0],\n current_path, 0, longest_path)\n pair[1] = False\n\n return longest_path\n\n\ndef main():\n global nsolutions\n\n pokemon = \"\"\"audino bagon baltoy banette bidoof braviary\nbronzor carracosta charmeleon cresselia croagunk darmanitan deino\nemboar emolga exeggcute gabite girafarig gulpin haxorus heatmor\nheatran ivysaur jellicent jumpluff kangaskhan kricketune landorus\nledyba loudred lumineon lunatone machamp magnezone mamoswine nosepass\npetilil pidgeotto pikachu pinsir poliwrath poochyena porygon2\nporygonz registeel relicanth remoraid rufflet sableye scolipede\nscrafty seaking sealeo silcoon simisear snivy snorlax spoink starly\ntirtouga trapinch treecko tyrogue vigoroth vulpix wailord wartortle\nwhismur wingull yamask\"\"\".lower().split()\n\n # remove duplicates\n pokemon = sorted(set(pokemon))\n\n sol = find_longest_chain(pokemon)\n print \"Maximum path length:\", len(sol)\n print \"Paths of that length:\", nsolutions\n print \"Example path of that length:\"\n for i in xrange(0, len(sol), 7):\n print \" \", \" \".join(sol[i : i+7])\n\npsyco.full()\nmain()"} +{"title": "Latin Squares in reduced form", "language": "Python", "task": "A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin Squares of order n. The objective of this task is to construct the set of all Latin Squares of a given order and to provide a means which given suitable values for g any element within the set may be obtained.\n\nFor a reduced Latin Square the first row is always 1 to n. The second row is all [[Permutations/Derangements]] of 1 to n starting with 2. The third row is all [[Permutations/Derangements]] of 1 to n starting with 3 which do not clash (do not have the same item in any column) with row 2. The fourth row is all [[Permutations/Derangements]] of 1 to n starting with 4 which do not clash with rows 2 or 3. Likewise continuing to the nth row.\n\nDemonstrate by:\n* displaying the four reduced Latin Squares of order 4.\n* for n = 1 to 6 (or more) produce the set of reduced Latin Squares; produce a table which shows the size of the set of reduced Latin Squares and compares this value times n! times (n-1)! with the values in OEIS A002860.\n\n", "solution": "def dList(n, start):\n start -= 1 # use 0 basing\n a = range(n)\n a[start] = a[0]\n a[0] = start\n a[1:] = sorted(a[1:])\n first = a[1]\n # rescursive closure permutes a[1:]\n r = []\n def recurse(last):\n if (last == first):\n # bottom of recursion. you get here once for each permutation.\n # test if permutation is deranged.\n # yes, save a copy with 1 based indexing\n for j,v in enumerate(a[1:]):\n if j + 1 == v:\n return # no, ignore it\n b = [x + 1 for x in a]\n r.append(b)\n return\n for i in xrange(last, 0, -1):\n a[i], a[last] = a[last], a[i]\n recurse(last - 1)\n a[i], a[last] = a[last], a[i]\n recurse(n - 1)\n return r\n\ndef printSquare(latin,n):\n for row in latin:\n print row\n print\n\ndef reducedLatinSquares(n,echo):\n if n <= 0:\n if echo:\n print []\n return 0\n elif n == 1:\n if echo:\n print [1]\n return 1\n\n rlatin = [None] * n\n for i in xrange(n):\n rlatin[i] = [None] * n\n # first row\n for j in xrange(0, n):\n rlatin[0][j] = j + 1\n\n class OuterScope:\n count = 0\n def recurse(i):\n rows = dList(n, i)\n\n for r in xrange(len(rows)):\n rlatin[i - 1] = rows[r]\n justContinue = False\n k = 0\n while not justContinue and k < i - 1:\n for j in xrange(1, n):\n if rlatin[k][j] == rlatin[i - 1][j]:\n if r < len(rows) - 1:\n justContinue = True\n break\n if i > 2:\n return\n k += 1\n if not justContinue:\n if i < n:\n recurse(i + 1)\n else:\n OuterScope.count += 1\n if echo:\n printSquare(rlatin, n)\n\n # remaining rows\n recurse(2)\n return OuterScope.count\n\ndef factorial(n):\n if n == 0:\n return 1\n prod = 1\n for i in xrange(2, n + 1):\n prod *= i\n return prod\n\nprint \"The four reduced latin squares of order 4 are:\\n\"\nreducedLatinSquares(4,True)\n\nprint \"The size of the set of reduced latin squares for the following orders\"\nprint \"and hence the total number of latin squares of these orders are:\\n\"\nfor n in xrange(1, 7):\n size = reducedLatinSquares(n, False)\n f = factorial(n - 1)\n f *= f * n * size\n print \"Order %d: Size %-4d x %d! x %d! => Total %d\" % (n, size, n, n - 1, f)"} +{"title": "Law of cosines - triples", "language": "C", "task": "The [https://en.wikipedia.org/wiki/Law_of_cosines Law of cosines] states that for an angle \u03b3, (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(\u03b3) = C2 \n\n;Specific angles:\nFor an angle of of \u00a0 '''90\u00ba''' \u00a0 this becomes the more familiar \"Pythagoras equation\":\n A2 + B2 = C2 \n\nFor an angle of \u00a0 '''60\u00ba''' \u00a0 this becomes the less familiar equation:\n A2 + B2 - AB = C2 \n\nAnd finally for an angle of \u00a0 '''120\u00ba''' \u00a0 this becomes the equation:\n A2 + B2 + AB = C2 \n\n\n;Task:\n* \u00a0 Find all integer solutions (in order) to the three specific cases, distinguishing between each angle being considered.\n* \u00a0 Restrain all sides to the integers \u00a0 '''1..13''' \u00a0 inclusive.\n* \u00a0 Show how many results there are for each of the three angles mentioned above.\n* \u00a0 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 60\u00b0 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* [https://youtu.be/p-0SOWbzUYI?t=12m11s 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": "Law of cosines - triples", "language": "JavaScript", "task": "The [https://en.wikipedia.org/wiki/Law_of_cosines Law of cosines] states that for an angle \u03b3, (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(\u03b3) = C2 \n\n;Specific angles:\nFor an angle of of \u00a0 '''90\u00ba''' \u00a0 this becomes the more familiar \"Pythagoras equation\":\n A2 + B2 = C2 \n\nFor an angle of \u00a0 '''60\u00ba''' \u00a0 this becomes the less familiar equation:\n A2 + B2 - AB = C2 \n\nAnd finally for an angle of \u00a0 '''120\u00ba''' \u00a0 this becomes the equation:\n A2 + B2 + AB = C2 \n\n\n;Task:\n* \u00a0 Find all integer solutions (in order) to the three specific cases, distinguishing between each angle being considered.\n* \u00a0 Restrain all sides to the integers \u00a0 '''1..13''' \u00a0 inclusive.\n* \u00a0 Show how many results there are for each of the three angles mentioned above.\n* \u00a0 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 60\u00b0 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* [https://youtu.be/p-0SOWbzUYI?t=12m11s Visualising Pythagoras: ultimate proofs and crazy contortions] Mathlogger Video\n\n", "solution": "(() => {\n 'use strict';\n\n // main :: IO ()\n const main = () => {\n\n const\n f90 = dct => x2 => dct[x2],\n f60 = dct => (x2, ab) => dct[x2 - ab],\n f120 = dct => (x2, ab) => dct[x2 + ab],\n f60unequal = dct => (x2, ab, a, b) =>\n (a !== b) ? (\n dct[x2 - ab]\n ) : undefined;\n\n\n // triangles :: Dict -> (Int -> Int -> Int -> Int -> Maybe Int)\n // -> [String]\n const triangles = (f, n) => {\n const\n xs = enumFromTo(1, n),\n fr = f(xs.reduce((a, x) => (a[x * x] = x, a), {})),\n gc = xs.reduce((a, _) => a, {}),\n setSoln = new Set();\n return (\n xs.forEach(\n a => {\n const a2 = a * a;\n enumFromTo(1, 1 + a).forEach(\n b => {\n const\n suma2b2 = a2 + b * b,\n c = fr(suma2b2, a * b, a, b);\n if (undefined !== c) {\n setSoln.add([a, b, c].sort())\n };\n }\n );\n }\n ),\n Array.from(setSoln.keys())\n );\n };\n\n const\n result = 'Triangles of maximum side 13:\\n\\n' +\n unlines(\n zipWith(\n (s, f) => {\n const ks = triangles(f, 13);\n return ks.length.toString() + ' solutions for ' + s +\n ' degrees:\\n' + unlines(ks) + '\\n';\n },\n ['120', '90', '60'],\n [f120, f90, f60]\n )\n ) + '\\nUneven triangles of maximum side 10000. Total:\\n' +\n triangles(f60unequal, 10000).length\n\n return (\n //console.log(result),\n result\n );\n };\n\n\n // GENERIC FUNCTIONS ----------------------------\n\n // concatMap :: (a -> [b]) -> [a] -> [b]\n const concatMap = (f, xs) =>\n xs.reduce((a, x) => a.concat(f(x)), []);\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = (m, n) =>\n m <= n ? iterateUntil(\n x => n <= x,\n x => 1 + x,\n m\n ) : [];\n\n // iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a]\n const iterateUntil = (p, f, x) => {\n const vs = [x];\n let h = x;\n while (!p(h))(h = f(h), vs.push(h));\n return vs;\n };\n\n // Returns Infinity over objects without finite length\n // this enables zip and zipWith to choose the shorter\n // argument when one non-finite like cycle, repeat etc\n\n // length :: [a] -> Int\n const length = xs => xs.length || Infinity;\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = (n, xs) =>\n xs.constructor.constructor.name !== 'GeneratorFunction' ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // Use of `take` and `length` here allows zipping with non-finite lists\n // i.e. generators like cycle, repeat, iterate.\n\n // Use of `take` and `length` here allows zipping with non-finite lists\n // i.e. generators like cycle, repeat, iterate.\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = (f, xs, ys) => {\n const\n lng = Math.min(length(xs), length(ys)),\n as = take(lng, xs),\n bs = take(lng, ys);\n return Array.from({\n length: lng\n }, (_, i) => f(as[i], bs[i], i));\n };\n\n // MAIN ---\n return main();\n})();"} +{"title": "Law of cosines - triples", "language": "Python", "task": "The [https://en.wikipedia.org/wiki/Law_of_cosines Law of cosines] states that for an angle \u03b3, (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(\u03b3) = C2 \n\n;Specific angles:\nFor an angle of of \u00a0 '''90\u00ba''' \u00a0 this becomes the more familiar \"Pythagoras equation\":\n A2 + B2 = C2 \n\nFor an angle of \u00a0 '''60\u00ba''' \u00a0 this becomes the less familiar equation:\n A2 + B2 - AB = C2 \n\nAnd finally for an angle of \u00a0 '''120\u00ba''' \u00a0 this becomes the equation:\n A2 + B2 + AB = C2 \n\n\n;Task:\n* \u00a0 Find all integer solutions (in order) to the three specific cases, distinguishing between each angle being considered.\n* \u00a0 Restrain all sides to the integers \u00a0 '''1..13''' \u00a0 inclusive.\n* \u00a0 Show how many results there are for each of the three angles mentioned above.\n* \u00a0 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 60\u00b0 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* [https://youtu.be/p-0SOWbzUYI?t=12m11s Visualising Pythagoras: ultimate proofs and crazy contortions] Mathlogger Video\n\n", "solution": "N = 13\n\ndef method1(N=N):\n squares = [x**2 for x in range(0, N+1)]\n sqrset = set(squares)\n tri90, tri60, tri120 = (set() for _ in range(3))\n for a in range(1, N+1):\n a2 = squares[a]\n for b in range(1, a + 1):\n b2 = squares[b]\n c2 = a2 + b2\n if c2 in sqrset:\n tri90.add(tuple(sorted((a, b, int(c2**0.5)))))\n ab = a * b\n c2 -= ab\n if c2 in sqrset:\n tri60.add(tuple(sorted((a, b, int(c2**0.5)))))\n c2 += 2 * ab\n if c2 in sqrset:\n tri120.add(tuple(sorted((a, b, int(c2**0.5)))))\n return sorted(tri90), sorted(tri60), sorted(tri120)\n#%%\nif __name__ == '__main__':\n print(f'Integer triangular triples for sides 1..{N}:')\n for angle, triples in zip([90, 60, 120], method1(N)):\n print(f' {angle:3}\u00b0 has {len(triples)} solutions:\\n {triples}')\n _, t60, _ = method1(10_000)\n notsame = sum(1 for a, b, c in t60 if a != b or b != c)\n print('Extra credit:', notsame)"} +{"title": "Least common multiple", "language": "C", "task": ";Task:\nCompute the \u00a0 least common multiple \u00a0 (LCM) \u00a0 of two integers.\n\nGiven \u00a0 ''m'' \u00a0 and \u00a0 ''n'', \u00a0 the least common multiple is the smallest positive integer that has both \u00a0 ''m'' \u00a0 and \u00a0 ''n'' \u00a0 as factors. \n\n\n;Example:\nThe least common multiple of \u00a0 '''12''' \u00a0 and \u00a0 '''18''' \u00a0 is \u00a0 '''36''', \u00a0 \u00a0 \u00a0 because:\n:* \u00a0 '''12''' \u00a0 is a factor \u00a0 \u00a0 ('''12''' \u00d7 '''3''' = '''36'''), \u00a0 \u00a0 and \n:* \u00a0 '''18''' \u00a0 is a factor \u00a0 \u00a0 ('''18''' \u00d7 '''2''' = '''36'''), \u00a0 \u00a0 and \n:* \u00a0 there is no positive integer less than \u00a0 '''36''' \u00a0 that has both factors. \n\n\nAs a special case, \u00a0 if either \u00a0 ''m'' \u00a0 or \u00a0 ''n'' \u00a0 is zero, \u00a0 then the least common multiple is zero.\n\n\nOne way to calculate the least common multiple is to iterate all the multiples of \u00a0 ''m'', \u00a0 until you find one that is also a multiple of \u00a0 ''n''.\n\nIf you already have \u00a0 ''gcd'' \u00a0 for [[greatest common divisor]], \u00a0 then this formula calculates \u00a0 ''lcm''.\n\n\n:::: \\operatorname{lcm}(m, n) = \\frac{|m \\times n|}{\\operatorname{gcd}(m, n)}\n\n\nOne can also find \u00a0 ''lcm'' \u00a0 by merging the [[prime decomposition]]s of both \u00a0 ''m'' \u00a0 and \u00a0 ''n''.\n\n\n;Related task\n:* \u00a0 [https://rosettacode.org/wiki/Greatest_common_divisor greatest common divisor].\n\n\n;See also:\n* \u00a0 MathWorld entry: \u00a0 [http://mathworld.wolfram.com/LeastCommonMultiple.html Least Common Multiple].\n* \u00a0 Wikipedia entry: \u00a0 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": "Least common multiple", "language": "JavaScript", "task": ";Task:\nCompute the \u00a0 least common multiple \u00a0 (LCM) \u00a0 of two integers.\n\nGiven \u00a0 ''m'' \u00a0 and \u00a0 ''n'', \u00a0 the least common multiple is the smallest positive integer that has both \u00a0 ''m'' \u00a0 and \u00a0 ''n'' \u00a0 as factors. \n\n\n;Example:\nThe least common multiple of \u00a0 '''12''' \u00a0 and \u00a0 '''18''' \u00a0 is \u00a0 '''36''', \u00a0 \u00a0 \u00a0 because:\n:* \u00a0 '''12''' \u00a0 is a factor \u00a0 \u00a0 ('''12''' \u00d7 '''3''' = '''36'''), \u00a0 \u00a0 and \n:* \u00a0 '''18''' \u00a0 is a factor \u00a0 \u00a0 ('''18''' \u00d7 '''2''' = '''36'''), \u00a0 \u00a0 and \n:* \u00a0 there is no positive integer less than \u00a0 '''36''' \u00a0 that has both factors. \n\n\nAs a special case, \u00a0 if either \u00a0 ''m'' \u00a0 or \u00a0 ''n'' \u00a0 is zero, \u00a0 then the least common multiple is zero.\n\n\nOne way to calculate the least common multiple is to iterate all the multiples of \u00a0 ''m'', \u00a0 until you find one that is also a multiple of \u00a0 ''n''.\n\nIf you already have \u00a0 ''gcd'' \u00a0 for [[greatest common divisor]], \u00a0 then this formula calculates \u00a0 ''lcm''.\n\n\n:::: \\operatorname{lcm}(m, n) = \\frac{|m \\times n|}{\\operatorname{gcd}(m, n)}\n\n\nOne can also find \u00a0 ''lcm'' \u00a0 by merging the [[prime decomposition]]s of both \u00a0 ''m'' \u00a0 and \u00a0 ''n''.\n\n\n;Related task\n:* \u00a0 [https://rosettacode.org/wiki/Greatest_common_divisor greatest common divisor].\n\n\n;See also:\n* \u00a0 MathWorld entry: \u00a0 [http://mathworld.wolfram.com/LeastCommonMultiple.html Least Common Multiple].\n* \u00a0 Wikipedia entry: \u00a0 Least common multiple.\n\n", "solution": "(() => {\n 'use strict';\n\n // gcd :: Integral a => a -> a -> a\n let gcd = (x, y) => {\n let _gcd = (a, b) => (b === 0 ? a : _gcd(b, a % b)),\n abs = Math.abs;\n return _gcd(abs(x), abs(y));\n }\n\n // lcm :: Integral a => a -> a -> a\n let lcm = (x, y) =>\n x === 0 || y === 0 ? 0 : Math.abs(Math.floor(x / gcd(x, y)) * y);\n\n // TEST\n return lcm(12, 18);\n\n})();"} +{"title": "Least common multiple", "language": "Python", "task": ";Task:\nCompute the \u00a0 least common multiple \u00a0 (LCM) \u00a0 of two integers.\n\nGiven \u00a0 ''m'' \u00a0 and \u00a0 ''n'', \u00a0 the least common multiple is the smallest positive integer that has both \u00a0 ''m'' \u00a0 and \u00a0 ''n'' \u00a0 as factors. \n\n\n;Example:\nThe least common multiple of \u00a0 '''12''' \u00a0 and \u00a0 '''18''' \u00a0 is \u00a0 '''36''', \u00a0 \u00a0 \u00a0 because:\n:* \u00a0 '''12''' \u00a0 is a factor \u00a0 \u00a0 ('''12''' \u00d7 '''3''' = '''36'''), \u00a0 \u00a0 and \n:* \u00a0 '''18''' \u00a0 is a factor \u00a0 \u00a0 ('''18''' \u00d7 '''2''' = '''36'''), \u00a0 \u00a0 and \n:* \u00a0 there is no positive integer less than \u00a0 '''36''' \u00a0 that has both factors. \n\n\nAs a special case, \u00a0 if either \u00a0 ''m'' \u00a0 or \u00a0 ''n'' \u00a0 is zero, \u00a0 then the least common multiple is zero.\n\n\nOne way to calculate the least common multiple is to iterate all the multiples of \u00a0 ''m'', \u00a0 until you find one that is also a multiple of \u00a0 ''n''.\n\nIf you already have \u00a0 ''gcd'' \u00a0 for [[greatest common divisor]], \u00a0 then this formula calculates \u00a0 ''lcm''.\n\n\n:::: \\operatorname{lcm}(m, n) = \\frac{|m \\times n|}{\\operatorname{gcd}(m, n)}\n\n\nOne can also find \u00a0 ''lcm'' \u00a0 by merging the [[prime decomposition]]s of both \u00a0 ''m'' \u00a0 and \u00a0 ''n''.\n\n\n;Related task\n:* \u00a0 [https://rosettacode.org/wiki/Greatest_common_divisor greatest common divisor].\n\n\n;See also:\n* \u00a0 MathWorld entry: \u00a0 [http://mathworld.wolfram.com/LeastCommonMultiple.html Least Common Multiple].\n* \u00a0 Wikipedia entry: \u00a0 Least common multiple.\n\n", "solution": "'''Least common multiple'''\n\nfrom inspect import signature\n\n\n# lcm :: Int -> Int -> Int\ndef lcm(x):\n '''The smallest positive integer divisible\n without remainder by both x and y.\n '''\n return lambda y: 0 if 0 in (x, y) else abs(\n y * (x // gcd_(x)(y))\n )\n\n\n# gcd_ :: Int -> Int -> Int\ndef gcd_(x):\n '''The greatest common divisor in terms of\n the divisibility preordering.\n '''\n def go(a, b):\n return go(b, a % b) if 0 != b else a\n return lambda y: go(abs(x), abs(y))\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Tests'''\n\n print(\n fTable(\n __doc__ + 's of 60 and [12..20]:'\n )(repr)(repr)(\n lcm(60)\n )(enumFromTo(12)(20))\n )\n\n pairs = [(0, 2), (2, 0), (-6, 14), (12, 18)]\n print(\n fTable(\n '\\n\\n' + __doc__ + 's of ' + repr(pairs) + ':'\n )(repr)(repr)(\n uncurry(lcm)\n )(pairs)\n )\n\n\n# GENERIC -------------------------------------------------\n\n# enumFromTo :: (Int, Int) -> [Int]\ndef enumFromTo(m):\n '''Integer enumeration from m to n.'''\n return lambda n: list(range(m, 1 + n))\n\n\n# uncurry :: (a -> b -> c) -> ((a, b) -> c)\ndef uncurry(f):\n '''A function over a tuple, derived from\n a vanilla or curried function.\n '''\n if 1 < len(signature(f).parameters):\n return lambda xy: f(*xy)\n else:\n return lambda xy: f(xy[0])(xy[1])\n\n\n# unlines :: [String] -> String\ndef unlines(xs):\n '''A single string derived by the intercalation\n of a list of strings with the newline character.\n '''\n return '\\n'.join(xs)\n\n\n# FORMATTING ----------------------------------------------\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\n '''\n def go(xShow, fxShow, f, xs):\n ys = [xShow(x) for x in xs]\n w = max(map(len, ys))\n return s + '\\n' + '\\n'.join(map(\n lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n xs, ys\n ))\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} +{"title": "Left factorials", "language": "C", "task": "[[Category:Mathematics]]\n\n\n'''Left factorials''', \u00a0 !n, \u00a0 may refer to either \u00a0 ''subfactorials'' \u00a0 or to \u00a0 ''factorial sums''; \nthe same notation can be confusingly seen being used for the two different definitions.\n\nSometimes, \u00a0 ''subfactorials'' \u00a0 (also known as ''derangements'') \u00a0 may use any of the notations: \n:::::::* \u00a0 !''n''` \n:::::::* \u00a0 !''n'' \n:::::::* \u00a0 ''n''\u00a1 \n\n\n(It may not be visually obvious, but the last example uses an upside-down exclamation mark.)\n\n\nThis Rosetta Code task will be using this formula \u00a0 (''factorial sums'') \u00a0 for \u00a0 '''left factorial''':\n\n::::: \u00a0 !n = \\sum_{k=0}^{n-1} k! \n\n:::: where\n\n::::: \u00a0 !0 = 0\n\n\n\n;Task\nDisplay the left factorials for:\n* \u00a0 zero through ten \u00a0 \u00a0 (inclusive)\n* \u00a0 20 \u00a0 through \u00a0 110 \u00a0 (inclusive) \u00a0 by tens\n\n\nDisplay the length (in decimal digits) of the left factorials for:\n* \u00a0 1,000 \u00a0 through \u00a0 10,000 \u00a0 (inclusive), by thousands.\n\n\n;Also see:\n* \u00a0 The OEIS entry: [http://oeis.org/A003422 A003422 left factorials]\n* \u00a0 The MathWorld entry: [http://mathworld.wolfram.com/LeftFactorial.html left factorial]\n* \u00a0 The MathWorld entry: [http://mathworld.wolfram.com/FactorialSums.html factorial sums]\n* \u00a0 The MathWorld entry: [http://mathworld.wolfram.com/Subfactorial.html subfactorial]\n\n\n;Related task:\n* \u00a0 [http://rosettacode.org/wiki/Permutations/Derangements permutations/derangements (subfactorials)]\n\n", "solution": "\n#include \n#include \n#include \n#include \n\nvoid mpz_left_fac_ui(mpz_t rop, unsigned long op)\n{\n mpz_t t1;\n mpz_init_set_ui(t1, 1);\n mpz_set_ui(rop, 0);\n\n size_t i;\n for (i = 1; i <= op; ++i) {\n mpz_add(rop, rop, t1);\n mpz_mul_ui(t1, t1, i);\n }\n\n mpz_clear(t1);\n}\n\nsize_t mpz_digitcount(mpz_t op)\n{\n /* mpz_sizeinbase can not be trusted to give accurate base 10 length */\n char *t = mpz_get_str(NULL, 10, op);\n size_t ret = strlen(t);\n free(t);\n return ret;\n}\n\nint main(void)\n{\n mpz_t t;\n mpz_init(t);\n size_t i;\n\n for (i = 0; i <= 110; ++i) {\n if (i <= 10 || i % 10 == 0) {\n mpz_left_fac_ui(t, i);\n gmp_printf(\"!%u = %Zd\\n\", i, t);\n }\n }\n\n for (i = 1000; i <= 10000; i += 1000) {\n mpz_left_fac_ui(t, i);\n printf(\"!%u has %u digits\\n\", i, mpz_digitcount(t));\n }\n\n mpz_clear(t);\n return 0;\n}\n"} +{"title": "Left factorials", "language": "Python", "task": "[[Category:Mathematics]]\n\n\n'''Left factorials''', \u00a0 !n, \u00a0 may refer to either \u00a0 ''subfactorials'' \u00a0 or to \u00a0 ''factorial sums''; \nthe same notation can be confusingly seen being used for the two different definitions.\n\nSometimes, \u00a0 ''subfactorials'' \u00a0 (also known as ''derangements'') \u00a0 may use any of the notations: \n:::::::* \u00a0 !''n''` \n:::::::* \u00a0 !''n'' \n:::::::* \u00a0 ''n''\u00a1 \n\n\n(It may not be visually obvious, but the last example uses an upside-down exclamation mark.)\n\n\nThis Rosetta Code task will be using this formula \u00a0 (''factorial sums'') \u00a0 for \u00a0 '''left factorial''':\n\n::::: \u00a0 !n = \\sum_{k=0}^{n-1} k! \n\n:::: where\n\n::::: \u00a0 !0 = 0\n\n\n\n;Task\nDisplay the left factorials for:\n* \u00a0 zero through ten \u00a0 \u00a0 (inclusive)\n* \u00a0 20 \u00a0 through \u00a0 110 \u00a0 (inclusive) \u00a0 by tens\n\n\nDisplay the length (in decimal digits) of the left factorials for:\n* \u00a0 1,000 \u00a0 through \u00a0 10,000 \u00a0 (inclusive), by thousands.\n\n\n;Also see:\n* \u00a0 The OEIS entry: [http://oeis.org/A003422 A003422 left factorials]\n* \u00a0 The MathWorld entry: [http://mathworld.wolfram.com/LeftFactorial.html left factorial]\n* \u00a0 The MathWorld entry: [http://mathworld.wolfram.com/FactorialSums.html factorial sums]\n* \u00a0 The MathWorld entry: [http://mathworld.wolfram.com/Subfactorial.html subfactorial]\n\n\n;Related task:\n* \u00a0 [http://rosettacode.org/wiki/Permutations/Derangements permutations/derangements (subfactorials)]\n\n", "solution": "from itertools import islice\n\ndef lfact():\n yield 0\n fact, summ, n = 1, 0, 1 \n while 1:\n fact, summ, n = fact*n, summ + fact, n + 1\n yield summ\n\nprint('first 11:\\n %r' % [lf for i, lf in zip(range(11), lfact())])\nprint('20 through 110 (inclusive) by tens:')\nfor lf in islice(lfact(), 20, 111, 10):\n print(lf)\nprint('Digits in 1,000 through 10,000 (inclusive) by thousands:\\n %r' \n % [len(str(lf)) for lf in islice(lfact(), 1000, 10001, 1000)] )"} +{"title": "Levenshtein distance", "language": "C", "task": "In information theory and computer science, the '''Levenshtein distance''' is a edit distance). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character. \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::# \u00a0 '''k'''itten \u00a0 '''s'''itten \u00a0 (substitution of 'k' with 's')\n::# \u00a0 sitt'''e'''n \u00a0 sitt'''i'''n \u00a0 (substitution of 'e' with 'i')\n::# \u00a0 sittin \u00a0 sittin'''g''' \u00a0 (insert 'g' at the end).\n\n\n''The Levenshtein distance between \u00a0 \"'''rosettacode'''\", \u00a0 \"'''raisethysword'''\" \u00a0 is \u00a0 '''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 \u00a0 \"kitten\" \u00a0 and \u00a0 \"sitting\". \n\n\n;Related task:\n* \u00a0 [[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", "language": "JavaScript", "task": "In information theory and computer science, the '''Levenshtein distance''' is a edit distance). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character. \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::# \u00a0 '''k'''itten \u00a0 '''s'''itten \u00a0 (substitution of 'k' with 's')\n::# \u00a0 sitt'''e'''n \u00a0 sitt'''i'''n \u00a0 (substitution of 'e' with 'i')\n::# \u00a0 sittin \u00a0 sittin'''g''' \u00a0 (insert 'g' at the end).\n\n\n''The Levenshtein distance between \u00a0 \"'''rosettacode'''\", \u00a0 \"'''raisethysword'''\" \u00a0 is \u00a0 '''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 \u00a0 \"kitten\" \u00a0 and \u00a0 \"sitting\". \n\n\n;Related task:\n* \u00a0 [[Longest common subsequence]]\n\n\n\n", "solution": "(() => {\n 'use strict';\n\n // levenshtein :: String -> String -> Int\n const levenshtein = sa => sb => {\n const cs = chars(sa);\n const go = (ns, c) => {\n const calc = z => tpl => {\n const [c1, x, y] = Array.from(tpl);\n return minimum([\n succ(y),\n succ(z),\n x + (c !== c1 ? 1 : 0)\n ]);\n };\n const [n, ns1] = [ns[0], ns.slice(1)];\n return scanl(calc)(succ(n))(\n zip3(cs)(ns)(ns1)\n );\n };\n return last(\n chars(sb).reduce(\n go,\n enumFromTo(0)(cs.length)\n )\n );\n };\n\n // ----------------------- TEST ------------------------\n const main = () => [\n [\"kitten\", \"sitting\"],\n [\"sitting\", \"kitten\"],\n [\"rosettacode\", \"raisethysword\"],\n [\"raisethysword\", \"rosettacode\"]\n ].map(uncurry(levenshtein));\n\n\n // ----------------- GENERIC FUNCTIONS -----------------\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = a =>\n b => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n\n // TupleN :: a -> b ... -> (a, b ... )\n function TupleN() {\n const\n args = Array.from(arguments),\n n = args.length;\n return 2 < n ? Object.assign(\n args.reduce((a, x, i) => Object.assign(a, {\n [i]: x\n }), {\n type: 'Tuple' + n.toString(),\n length: n\n })\n ) : args.reduce((f, x) => f(x), Tuple);\n };\n\n\n // chars :: String -> [Char]\n const chars = s =>\n s.split('');\n\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = m =>\n n => Array.from({\n length: 1 + n - m\n }, (_, i) => m + i);\n\n\n // last :: [a] -> a\n const last = xs => (\n // The last item of a list.\n ys => 0 < ys.length ? (\n ys.slice(-1)[0]\n ) : undefined\n )(xs);\n\n\n // minimum :: Ord a => [a] -> a\n const minimum = xs => (\n // The least value of xs.\n ys => 0 < ys.length ? (\n ys.slice(1)\n .reduce((a, y) => y < a ? y : a, ys[0])\n ) : undefined\n )(xs);\n\n\n // length :: [a] -> Int\n const length = xs =>\n // Returns Infinity over objects without finite\n // length. This enables zip and zipWith to choose\n // the shorter argument when one is non-finite,\n // like cycle, repeat etc\n 'GeneratorFunction' !== xs.constructor.constructor.name ? (\n xs.length\n ) : Infinity;\n\n\n // scanl :: (b -> a -> b) -> b -> [a] -> [b]\n const scanl = f => startValue => xs =>\n xs.reduce((a, x) => {\n const v = f(a[0])(x);\n return Tuple(v)(a[1].concat(v));\n }, Tuple(startValue)([startValue]))[1];\n\n\n // succ :: Enum a => a -> a\n const succ = x =>\n 1 + x;\n\n\n // uncurry :: (a -> b -> c) -> ((a, b) -> c)\n const uncurry = f =>\n // A function over a pair, derived\n // from a curried function.\n function () {\n const\n args = arguments,\n xy = Boolean(args.length % 2) ? (\n args[0]\n ) : args;\n return f(xy[0])(xy[1]);\n };\n\n\n // zip3 :: [a] -> [b] -> [c] -> [(a, b, c)]\n const zip3 = xs =>\n ys => zs => xs\n .slice(0, Math.min(...[xs, ys, zs].map(length)))\n .map((x, i) => TupleN(x, ys[i], zs[i]));\n\n // MAIN ---\n return JSON.stringify(main())\n})();"} +{"title": "Levenshtein distance", "language": "Python", "task": "In information theory and computer science, the '''Levenshtein distance''' is a edit distance). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character. \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::# \u00a0 '''k'''itten \u00a0 '''s'''itten \u00a0 (substitution of 'k' with 's')\n::# \u00a0 sitt'''e'''n \u00a0 sitt'''i'''n \u00a0 (substitution of 'e' with 'i')\n::# \u00a0 sittin \u00a0 sittin'''g''' \u00a0 (insert 'g' at the end).\n\n\n''The Levenshtein distance between \u00a0 \"'''rosettacode'''\", \u00a0 \"'''raisethysword'''\" \u00a0 is \u00a0 '''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 \u00a0 \"kitten\" \u00a0 and \u00a0 \"sitting\". \n\n\n;Related task:\n* \u00a0 [[Longest common subsequence]]\n\n\n\n", "solution": "def levenshteinDistance(str1, str2):\n m = len(str1)\n n = len(str2)\n d = [[i] for i in range(1, m + 1)] # d matrix rows\n d.insert(0, list(range(0, n + 1))) # d matrix columns\n for j in range(1, n + 1):\n for i in range(1, m + 1):\n if str1[i - 1] == str2[j - 1]: # Python (string) is 0-based\n substitutionCost = 0\n else:\n substitutionCost = 1\n d[i].insert(j, min(d[i - 1][j] + 1,\n d[i][j - 1] + 1,\n d[i - 1][j - 1] + substitutionCost))\n return d[-1][-1]\n\nprint(levenshteinDistance(\"kitten\",\"sitting\"))\nprint(levenshteinDistance(\"rosettacode\",\"raisethysword\"))"} +{"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": "Levenshtein distance/Alignment", "language": "Python", "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": "from difflib import ndiff\n\ndef levenshtein(str1, str2):\n result = \"\"\n pos, removed = 0, 0\n for x in ndiff(str1, str2):\n if pos 0:\n removed -=1\n else:\n result += \"-\"\n print(result)\n\nlevenshtein(\"place\",\"palace\")\nlevenshtein(\"rosettacode\",\"raisethysword\")"} +{"title": "List rooted trees", "language": "C", "task": "You came back from grocery shopping. \u00a0 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. \u00a0 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 [https://oeis.org/A000081 OEIS A81].\n\n\n;Task: \nWrite a program that, when given ''n'', enumerates all ways of nesting ''n'' bags. \u00a0 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. \u00a0 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": "List rooted trees", "language": "Python", "task": "You came back from grocery shopping. \u00a0 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. \u00a0 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 [https://oeis.org/A000081 OEIS A81].\n\n\n;Task: \nWrite a program that, when given ''n'', enumerates all ways of nesting ''n'' bags. \u00a0 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. \u00a0 There should be 9 ways.\n\n", "solution": "def bags(n,cache={}):\n\tif not n: return [(0, \"\")]\n\n\tupto = sum([bags(x) for x in range(n-1, 0, -1)], [])\n\treturn [(c+1, '('+s+')') for c,s in bagchain((0, \"\"), n-1, upto)]\n\ndef bagchain(x, n, bb, start=0):\n\tif not n: return [x]\n\n\tout = []\n\tfor i in range(start, len(bb)):\n\t\tc,s = bb[i]\n\t\tif c <= n: out += bagchain((x[0] + c, x[1] + s), n-c, bb, i)\n\treturn out\n\n# Maybe this lessens eye strain. Maybe not.\ndef replace_brackets(s):\n\tdepth,out = 0,[]\n\tfor c in s:\n\t\tif c == '(':\n\t\t\tout.append(\"([{\"[depth%3])\n\t\t\tdepth += 1\n\t\telse:\n\t\t\tdepth -= 1\n\t\t\tout.append(\")]}\"[depth%3])\n\treturn \"\".join(out)\n\nfor x in bags(5): print(replace_brackets(x[1]))"} +{"title": "Long literals, with continuations", "language": "Python", "task": "This task is about writing a computer program that has long literals \u00a0 (character\nliterals that may require specifying the words/tokens on more than one (source)\nline, \u00a0 either with continuations or some other method, such as abutments or\nconcatenations \u00a0 (or some other mechanisms).\n\n\nThe literal is to be in the form of a \"list\", \u00a0 a literal that contains many\nwords (tokens) separated by a blank (space), \u00a0 in this case \u00a0 (so as to have a\ncommon list), \u00a0 the (English) names of the chemical elements of the periodic table.\n\n\nThe list is to be in (ascending) order of the (chemical) element's atomic number:\n\n ''hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium aluminum silicon ...''\n\n... up to the last known (named) chemical element \u00a0 (at this time).\n\n\nDo not include any of the \u00a0 \"unnamed\" \u00a0 chemical element names such as:\n\n ''ununennium unquadnilium triunhexium penthextrium penthexpentium septhexunium octenntrium ennennbium''\n\n\nTo make computer programming languages comparable, \u00a0 the statement widths should be\nrestricted to less than \u00a0 '''81''' \u00a0 bytes (characters), \u00a0 or less\nif a computer programming language has more restrictive limitations or standards.\n\nAlso mention what column the programming statements can start in if \u00a0 ''not'' \u00a0\nin column one.\n\n\nThe list \u00a0 ''may'' \u00a0 have leading/embedded/trailing blanks during the\ndeclaration \u00a0 (the actual program statements), \u00a0 this is allow the list to be\nmore readable. \u00a0 The \"final\" list shouldn't have any leading/trailing or superfluous\nblanks \u00a0 (when stored in the program's \"memory\").\n\nThis list should be written with the idea in mind that the\nprogram \u00a0 ''will'' \u00a0 be updated, \u00a0 most likely someone other than the\noriginal author, \u00a0 as there will be newer (discovered) elements of the periodic\ntable being added \u00a0 (possibly in the near future). \u00a0 These future updates\nshould be one of the primary concerns in writing these programs and it should be \"easy\"\nfor someone else to add chemical elements to the list \u00a0 (within the computer\nprogram).\n\nAttention should be paid so as to not exceed the \u00a0 ''clause length'' \u00a0 of\ncontinued or specified statements, \u00a0 if there is such a restriction. \u00a0 If the\nlimit is greater than (say) 4,000 bytes or so, \u00a0 it needn't be mentioned here.\n\n\n;Task:\n:* \u00a0 Write a computer program (by whatever name) to contain a list of the known elements.\n:* \u00a0 The program should eventually contain a long literal of words \u00a0 (the elements).\n:* \u00a0 The literal should show how one could create a long list of blank-delineated words.\n:* \u00a0 The \"final\" (stored) list should only have a single blank between elements.\n:* \u00a0 Try to use the most idiomatic approach(es) in creating the final list.\n:* \u00a0 Use continuation if possible, and/or show alternatives \u00a0 (possibly using concatenation).\n:* \u00a0 Use a program comment to explain what the continuation character is if it isn't obvious.\n:* \u00a0 The program should contain a variable that has the date of the last update/revision.\n:* \u00a0 The program, when run, should display with verbiage:\n:::* \u00a0 The last update/revision date \u00a0 (and should be unambiguous).\n:::* \u00a0 The number of chemical elements in the list.\n:::* \u00a0 The name of the highest (last) element name.\n\n\nShow all output here, on this page.\n\n\n\n", "solution": "\"\"\"Long string literal. Requires Python 3.6+ for f-strings.\"\"\"\n\nrevision = \"October 13th 2020\"\n\n# String literal continuation. Notice the trailing space at the end of each\n# line but the last, and the lack of commas. There is exactly one \"blank\"\n# between each item in the list.\nelements = (\n \"hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine \"\n \"neon sodium magnesium aluminum silicon phosphorous sulfur chlorine argon \"\n \"potassium calcium scandium titanium vanadium chromium manganese iron \"\n \"cobalt nickel copper zinc gallium germanium arsenic selenium bromine \"\n \"krypton rubidium strontium yttrium zirconium niobium molybdenum \"\n \"technetium ruthenium rhodium palladium silver cadmium indium tin \"\n \"antimony tellurium iodine xenon cesium barium lanthanum cerium \"\n \"praseodymium neodymium promethium samarium europium gadolinium terbium \"\n \"dysprosium holmium erbium thulium ytterbium lutetium hafnium tantalum \"\n \"tungsten rhenium osmium iridium platinum gold mercury thallium lead \"\n \"bismuth polonium astatine radon francium radium actinium thorium \"\n \"protactinium uranium neptunium plutonium americium curium berkelium \"\n \"californium einsteinium fermium mendelevium nobelium lawrencium \"\n \"rutherfordium dubnium seaborgium bohrium hassium meitnerium darmstadtium \"\n \"roentgenium copernicium nihonium flerovium moscovium livermorium \"\n \"tennessine oganesson\"\n)\n\n\ndef report():\n \"\"\"Write a summary report to stdout.\"\"\"\n items = elements.split()\n\n print(f\"Last revision date: {revision}\")\n print(f\"Number of elements: {len(items)}\")\n print(f\"Last element : {items[-1]}\")\n\n\nif __name__ == \"__main__\":\n report()\n"} +{"title": "Long year", "language": "C", "task": "Most years have 52 weeks, some have 53, according to [https://en.wikipedia.org/wiki/ISO_week_date#Weeks_per_year 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": "Long year", "language": "JavaScript", "task": "Most years have 52 weeks, some have 53, according to [https://en.wikipedia.org/wiki/ISO_week_date#Weeks_per_year 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": "const isLongYear = (year) => {\n const jan1 = new Date(year, 0, 1);\n const dec31 = new Date(year, 11, 31);\n return (4 == jan1.getDay() || 4 == dec31.getDay())\n}\n\nfor (let y = 1995; y <= 2045; y++) {\n if (isLongYear(y)) {\n console.log(y)\n }\n}"} +{"title": "Long year", "language": "Python 3.7", "task": "Most years have 52 weeks, some have 53, according to [https://en.wikipedia.org/wiki/ISO_week_date#Weeks_per_year 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": "'''Long Year ?'''\n\nfrom datetime import date\n\n\n# longYear :: Year Int -> Bool\ndef longYear(y):\n '''True if the ISO year y has 53 weeks.'''\n return 52 < date(y, 12, 28).isocalendar()[1]\n\n\n# --------------------------TEST---------------------------\n# main :: IO ()\ndef main():\n '''Longer (53 week) years in the range 2000-2100'''\n for year in [\n x for x in range(2000, 1 + 2100)\n if longYear(x)\n ]:\n print(year)\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} +{"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 [http://en.wikipedia.org/wiki/Longest_common_subsequence_problem '''Longest Common Subsequence'''] ('''LCS''') is a subsequence of maximum length common to two or more strings.\n\nLet ''A'' \u2261 ''A''[0]\u2026 ''A''[m - 1] and ''B'' \u2261 ''B''[0]\u2026 ''B''[n - 1], m < n be strings drawn from an alphabet \u03a3 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 \u2264 i < m and 0 \u2264 j < n.\n\nThe set of matches '''M''' defines a relation over matches: '''M'''[i, j] \u21d4 (i, j) \u2208 '''M'''.\n\nDefine a ''non-strict'' [https://en.wikipedia.org/wiki/Product_order product-order] (\u2264) over ordered pairs, such that (i1, j1) \u2264 (i2, j2) \u21d4 i1 \u2264 i2 and j1 \u2264 j2. We define (\u2265) similarly.\n\nWe say ordered pairs p1 and p2 are ''comparable'' if either p1 \u2264 p2 or p1 \u2265 p2 holds. If i1 < i2 and j2 < j1 (or i2 < i1 and j1 < j2) then neither p1 \u2264 p2 nor p1 \u2265 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) \u21d4 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 \u03a3 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\u2013281]\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 common subsequence", "language": "JavaScript", "task": "'''Introduction'''\n\nDefine a ''subsequence'' to be any output string obtained by deleting zero or more symbols from an input string.\n\nThe [http://en.wikipedia.org/wiki/Longest_common_subsequence_problem '''Longest Common Subsequence'''] ('''LCS''') is a subsequence of maximum length common to two or more strings.\n\nLet ''A'' \u2261 ''A''[0]\u2026 ''A''[m - 1] and ''B'' \u2261 ''B''[0]\u2026 ''B''[n - 1], m < n be strings drawn from an alphabet \u03a3 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 \u2264 i < m and 0 \u2264 j < n.\n\nThe set of matches '''M''' defines a relation over matches: '''M'''[i, j] \u21d4 (i, j) \u2208 '''M'''.\n\nDefine a ''non-strict'' [https://en.wikipedia.org/wiki/Product_order product-order] (\u2264) over ordered pairs, such that (i1, j1) \u2264 (i2, j2) \u21d4 i1 \u2264 i2 and j1 \u2264 j2. We define (\u2265) similarly.\n\nWe say ordered pairs p1 and p2 are ''comparable'' if either p1 \u2264 p2 or p1 \u2265 p2 holds. If i1 < i2 and j2 < j1 (or i2 < i1 and j1 < j2) then neither p1 \u2264 p2 nor p1 \u2265 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) \u21d4 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 \u03a3 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\u2013281]\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": "function lcs_greedy(x,y){\n var p1, i, idx,\n symbols = {},\n r = 0,\n p = 0,\n l = 0,\n m = x.length,\n n = y.length,\n s = new Buffer((m < n) ? n : m);\n\n p1 = popsym(0);\n\n for (i = 0; i < m; i++) {\n p = (r === p) ? p1 : popsym(i);\n p1 = popsym(i + 1);\n if (p > p1) {\n i += 1;\n idx = p1;\n } else {\n idx = p;\n }\n\n if (idx === n) {\n p = popsym(i);\n } else {\n r = idx;\n s[l] = x.charCodeAt(i);\n l += 1;\n }\n }\n return s.toString('utf8', 0, l);\n\t\n function popsym(index) {\n var s = x[index],\n pos = symbols[s] + 1;\n\n pos = y.indexOf(s, ((pos > r) ? pos : r));\n if (pos === -1) { pos = n; }\n symbols[s] = pos;\n return pos;\n }\n}"} +{"title": "Longest common subsequence", "language": "Python", "task": "'''Introduction'''\n\nDefine a ''subsequence'' to be any output string obtained by deleting zero or more symbols from an input string.\n\nThe [http://en.wikipedia.org/wiki/Longest_common_subsequence_problem '''Longest Common Subsequence'''] ('''LCS''') is a subsequence of maximum length common to two or more strings.\n\nLet ''A'' \u2261 ''A''[0]\u2026 ''A''[m - 1] and ''B'' \u2261 ''B''[0]\u2026 ''B''[n - 1], m < n be strings drawn from an alphabet \u03a3 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 \u2264 i < m and 0 \u2264 j < n.\n\nThe set of matches '''M''' defines a relation over matches: '''M'''[i, j] \u21d4 (i, j) \u2208 '''M'''.\n\nDefine a ''non-strict'' [https://en.wikipedia.org/wiki/Product_order product-order] (\u2264) over ordered pairs, such that (i1, j1) \u2264 (i2, j2) \u21d4 i1 \u2264 i2 and j1 \u2264 j2. We define (\u2265) similarly.\n\nWe say ordered pairs p1 and p2 are ''comparable'' if either p1 \u2264 p2 or p1 \u2265 p2 holds. If i1 < i2 and j2 < j1 (or i2 < i1 and j1 < j2) then neither p1 \u2264 p2 nor p1 \u2265 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) \u21d4 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 \u03a3 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\u2013281]\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": "def lcs(a, b):\n # generate matrix of length of longest common subsequence for substrings of both words\n lengths = [[0] * (len(b)+1) for _ in range(len(a)+1)]\n for i, x in enumerate(a):\n for j, y in enumerate(b):\n if x == y:\n lengths[i+1][j+1] = lengths[i][j] + 1\n else:\n lengths[i+1][j+1] = max(lengths[i+1][j], lengths[i][j+1])\n\n # read a substring from the matrix\n result = ''\n j = len(b)\n for i in range(1, len(a)+1):\n if lengths[i][j] != lengths[i-1][j]:\n result += a[i-1]\n\n return result"} +{"title": "Longest common substring", "language": "C", "task": ";Task:\nWrite a function that returns the longest common substring of two strings. \n\nUse it within a program that demonstrates sample output from the function, which will consist of the longest common substring between \"thisisatest\" and \"testing123testing\". \n\nNote that substrings are consecutive characters within a string. \u00a0 This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them. \n\nHence, the [[longest common subsequence]] between \"thisisatest\" and \"testing123testing\" is \"tsitest\", whereas the longest common sub''string'' is just \"test\".\n\n\n\n\n;References:\n*[http://en.wikipedia.org/wiki/Generalized_suffix_tree Generalize Suffix Tree]\n*[[Ukkonen\u2019s Suffix Tree Construction]]\n\n", "solution": "#include \n\nvoid lcs(const char * const sa, const char * const sb, char ** const beg, char ** const end) {\n size_t apos, bpos;\n ptrdiff_t len;\n\n *beg = 0;\n *end = 0;\n len = 0;\n\n for (apos = 0; sa[apos] != 0; ++apos) {\n for (bpos = 0; sb[bpos] != 0; ++bpos) {\n if (sa[apos] == sb[bpos]) {\n len = 1;\n while (sa[apos + len] != 0 && sb[bpos + len] != 0 && sa[apos + len] == sb[bpos + len]) {\n len++;\n }\n }\n\n if (len > *end - *beg) {\n *beg = sa + apos;\n *end = *beg + len;\n len = 0;\n }\n }\n }\n}\n\nint main() {\n char *s1 = \"thisisatest\";\n char *s2 = \"testing123testing\";\n char *beg, *end, *it;\n\n lcs(s1, s2, &beg, &end);\n\n for (it = beg; it != end; it++) {\n putchar(*it);\n }\n printf(\"\\n\");\n\n return 0;\n}"} +{"title": "Longest common substring", "language": "JavaScript", "task": ";Task:\nWrite a function that returns the longest common substring of two strings. \n\nUse it within a program that demonstrates sample output from the function, which will consist of the longest common substring between \"thisisatest\" and \"testing123testing\". \n\nNote that substrings are consecutive characters within a string. \u00a0 This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them. \n\nHence, the [[longest common subsequence]] between \"thisisatest\" and \"testing123testing\" is \"tsitest\", whereas the longest common sub''string'' is just \"test\".\n\n\n\n\n;References:\n*[http://en.wikipedia.org/wiki/Generalized_suffix_tree Generalize Suffix Tree]\n*[[Ukkonen\u2019s Suffix Tree Construction]]\n\n", "solution": "(() => {\n 'use strict';\n\n // longestCommon :: String -> String -> String\n const longestCommon = (s1, s2) => maximumBy(\n comparing(length),\n intersect(...apList(\n [s => map(\n concat,\n concatMap(tails, compose(tail, inits)(s))\n )],\n [s1, s2]\n ))\n );\n\n // main :: IO ()\n const main = () =>\n console.log(\n longestCommon(\n \"testing123testing\",\n \"thisisatest\"\n )\n );\n\n // GENERIC FUNCTIONS ----------------------------\n\n // Each member of a list of functions applied to each\n // of a list of arguments, deriving a list of new values.\n\n // apList (<*>) :: [(a -> b)] -> [a] -> [b]\n const apList = (fs, xs) => //\n fs.reduce((a, f) => a.concat(\n xs.reduce((a, x) => a.concat([f(x)]), [])\n ), []);\n\n // comparing :: (a -> b) -> (a -> a -> Ordering)\n const comparing = f =>\n (x, y) => {\n const\n a = f(x),\n b = f(y);\n return a < b ? -1 : (a > b ? 1 : 0);\n };\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (f, g) => x => f(g(x));\n\n // concat :: [[a]] -> [a]\n // concat :: [String] -> String\n const concat = xs =>\n 0 < xs.length ? (() => {\n const unit = 'string' !== typeof xs[0] ? (\n []\n ) : '';\n return unit.concat.apply(unit, xs);\n })() : [];\n\n // concatMap :: (a -> [b]) -> [a] -> [b]\n const concatMap = (f, xs) =>\n xs.reduce((a, x) => a.concat(f(x)), []);\n\n // inits([1, 2, 3]) -> [[], [1], [1, 2], [1, 2, 3]\n // inits('abc') -> [\"\", \"a\", \"ab\", \"abc\"]\n\n // inits :: [a] -> [[a]]\n // inits :: String -> [String]\n const inits = xs => [\n []\n ]\n .concat(('string' === typeof xs ? xs.split('') : xs)\n .map((_, i, lst) => lst.slice(0, i + 1)));\n\n // intersect :: (Eq a) => [a] -> [a] -> [a]\n const intersect = (xs, ys) =>\n xs.filter(x => -1 !== ys.indexOf(x));\n\n // Returns Infinity over objects without finite length.\n // This enables zip and zipWith to choose the shorter\n // argument when one is non-finite, like cycle, repeat etc\n\n // length :: [a] -> Int\n const length = xs =>\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) => xs.map(f);\n\n // maximumBy :: (a -> a -> Ordering) -> [a] -> a\n const maximumBy = (f, xs) =>\n 0 < xs.length ? (\n xs.slice(1)\n .reduce((a, x) => 0 < f(x, a) ? x : a, xs[0])\n ) : undefined;\n\n // tail :: [a] -> [a]\n const tail = xs => 0 < xs.length ? xs.slice(1) : [];\n\n // tails :: [a] -> [[a]]\n const tails = xs => {\n const\n es = ('string' === typeof xs) ? (\n xs.split('')\n ) : xs;\n return es.map((_, i) => es.slice(i))\n .concat([\n []\n ]);\n };\n\n // MAIN ---\n return main();\n})();"} +{"title": "Longest common substring", "language": "Python", "task": ";Task:\nWrite a function that returns the longest common substring of two strings. \n\nUse it within a program that demonstrates sample output from the function, which will consist of the longest common substring between \"thisisatest\" and \"testing123testing\". \n\nNote that substrings are consecutive characters within a string. \u00a0 This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them. \n\nHence, the [[longest common subsequence]] between \"thisisatest\" and \"testing123testing\" is \"tsitest\", whereas the longest common sub''string'' is just \"test\".\n\n\n\n\n;References:\n*[http://en.wikipedia.org/wiki/Generalized_suffix_tree Generalize Suffix Tree]\n*[[Ukkonen\u2019s Suffix Tree Construction]]\n\n", "solution": "s1 = \"thisisatest\"\ns2 = \"testing123testing\"\nlen1, len2 = len(s1), len(s2)\nir, jr = 0, -1\nfor i1 in range(len1):\n i2 = s2.find(s1[i1])\n while i2 >= 0:\n j1, j2 = i1, i2\n while j1 < len1 and j2 < len2 and s2[j2] == s1[j1]:\n if j1-i1 >= jr-ir:\n ir, jr = i1, j1\n j1 += 1; j2 += 1\n i2 = s2.find(s1[i1], i2+1)\nprint (s1[ir:jr+1])"} +{"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# [http://www.youtube.com/watch?v=4fQJGoeW5VE 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": "Longest increasing subsequence", "language": "JavaScript", "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# [http://www.youtube.com/watch?v=4fQJGoeW5VE Dynamic Programming #1: Longest Increasing Subsequence] on YouTube\n# An efficient solution can be based on Patience sorting.\n\n", "solution": "function getLis(input) {\n if (input.length === 0) {\n return [];\n }\n\n var lisLenPerIndex = [];\n let max = { index: 0, length: 1 };\n\n for (var i = 0; i < input.length; i++) {\n lisLenPerIndex[i] = 1;\n for (var j = i - 1; j >= 0; j--) {\n if (input[i] > input[j] && lisLenPerIndex[j] >= lisLenPerIndex[i]) {\n var length = lisLenPerIndex[i] = lisLenPerIndex[j] + 1;\n if (length > max.length) {\n max = { index: i, length };\n }\n }\n }\n }\n\n var lis = [input[max.index]];\n for (var i = max.index; i >= 0 && max.length !== 0; i--) {\n if (input[max.index] > input[i] && lisLenPerIndex[i] === max.length - 1) {\n lis.unshift(input[i]);\n max.length--;\n }\n }\n\n return lis;\n}\n\nconsole.log(getLongestIncreasingSubsequence([0, 7, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]));\nconsole.log(getLongestIncreasingSubsequence([3, 2, 6, 4, 5, 1]));\n"} +{"title": "Longest increasing subsequence", "language": "Python", "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# [http://www.youtube.com/watch?v=4fQJGoeW5VE Dynamic Programming #1: Longest Increasing Subsequence] on YouTube\n# An efficient solution can be based on Patience sorting.\n\n", "solution": "def longest_increasing_subsequence(X):\n \"\"\"Returns the Longest Increasing Subsequence in the Given List/Array\"\"\"\n N = len(X)\n P = [0] * N\n M = [0] * (N+1)\n L = 0\n for i in range(N):\n lo = 1\n hi = L\n while lo <= hi:\n mid = (lo+hi)//2\n if (X[M[mid]] < X[i]):\n lo = mid+1\n else:\n hi = mid-1\n \n newL = lo\n P[i] = M[newL-1]\n M[newL] = i\n \n if (newL > L):\n L = newL\n \n S = []\n k = M[L]\n for i in range(L-1, -1, -1):\n S.append(X[k])\n k = P[k]\n return S[::-1]\n\nif __name__ == '__main__':\n for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:\n print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))"} +{"title": "Lucky and even lucky numbers", "language": "C", "task": "Note that in the following explanation list indices are assumed to start at ''one''.\n\n;Definition of lucky numbers\n''Lucky numbers'' are positive integers that are formed by:\n\n# Form a list of all the positive odd integers > 01, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39 ...\n# Return the first number from the list (which is '''1''').\n# (Loop begins here)\n#* Note then return the second number from the list (which is '''3''').\n#* Discard every third, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 19, 21, 25, 27, 31, 33, 37, 39, 43, 45, 49, 51, 55, 57 ...\n# (Expanding the loop a few more times...)\n#* Note then return the third number from the list (which is '''7''').\n#* Discard every 7th, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 21, 25, 27, 31, 33, 37, 43, 45, 49, 51, 55, 57, 63, 67 ...\n#* Note then return the 4th number from the list (which is '''9''').\n#* Discard every 9th, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, 43, 45, 49, 51, 55, 63, 67, 69, 73 ...\n#* Take the 5th, i.e. '''13'''. Remove every 13th.\n#* Take the 6th, i.e. '''15'''. Remove every 15th.\n#* Take the 7th, i.e. '''21'''. Remove every 21th.\n#* Take the 8th, i.e. '''25'''. Remove every 25th.\n# (Rule for the loop)\n#* Note the nth, which is m.\n#* Remove every mth.\n#* Increment n.\n\n;Definition of even lucky numbers\nThis follows the same rules as the definition of lucky numbers above ''except for the very first step'':\n# Form a list of all the positive '''even''' integers > 02, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40 ...\n# Return the first number from the list (which is '''2''').\n# (Loop begins here)\n#* Note then return the second number from the list (which is '''4''').\n#* Discard every 4th, (as noted), number from the list to form the new list2, 4, 6, 10, 12, 14, 18, 20, 22, 26, 28, 30, 34, 36, 38, 42, 44, 46, 50, 52 ...\n# (Expanding the loop a few more times...)\n#* Note then return the third number from the list (which is '''6''').\n#* Discard every 6th, (as noted), number from the list to form the new list2, 4, 6, 10, 12, 18, 20, 22, 26, 28, 34, 36, 38, 42, 44, 50, 52, 54, 58, 60 ...\n#* Take the 4th, i.e. '''10'''. Remove every 10th.\n#* Take the 5th, i.e. '''12'''. Remove every 12th.\n# (Rule for the loop)\n#* Note the nth, which is m.\n#* Remove every mth.\n#* Increment n.\n\n;Task requirements\n* Write one or two subroutines (functions) to generate ''lucky numbers'' and ''even lucky numbers'' \n* Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors:\n** missing arguments\n** too many arguments\n** number (or numbers) aren't legal\n** misspelled argument ('''lucky''' or '''evenLucky''')\n* The command line handling should:\n** support mixed case handling of the (non-numeric) arguments\n** support printing a particular number\n** support printing a range of numbers by their index\n** support printing a range of numbers by their values\n* The resulting list of numbers should be printed on a single line.\n\nThe program should support the arguments:\n\n what is displayed (on a single line)\n argument(s) (optional verbiage is encouraged)\n \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n \u2551 j \u2551 Jth lucky number \u2551\n \u2551 j , lucky \u2551 Jth lucky number \u2551\n \u2551 j , evenLucky \u2551 Jth even lucky number \u2551\n \u2551 \u2551 \u2551\n \u2551 j k \u2551 Jth through Kth (inclusive) lucky numbers \u2551\n \u2551 j k lucky \u2551 Jth through Kth (inclusive) lucky numbers \u2551\n \u2551 j k evenLucky \u2551 Jth through Kth (inclusive) even lucky numbers \u2551\n \u2551 \u2551 \u2551\n \u2551 j -k \u2551 all lucky numbers in the range j \u2500\u2500\u25ba |k| \u2551\n \u2551 j -k lucky \u2551 all lucky numbers in the range j \u2500\u2500\u25ba |k| \u2551\n \u2551 j -k evenLucky \u2551 all even lucky numbers in the range j \u2500\u2500\u25ba |k| \u2551\n \u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d\n where |k| is the absolute value of k\n\nDemonstrate the program by:\n* showing the first twenty ''lucky'' numbers\n* showing the first twenty ''even lucky'' numbers\n* showing all ''lucky'' numbers between 6,000 and 6,100 (inclusive)\n* showing all ''even lucky'' numbers in the same range as above\n* showing the 10,000th ''lucky'' number (extra credit)\n* showing the 10,000th ''even lucky'' number (extra credit)\n\n;See also:\n* This task is related to the [[Sieve of Eratosthenes]] task.\n* OEIS Wiki [http://oeis.org/wiki/Lucky_numbers Lucky numbers].\n* Sequence [https://oeis.org/A000959 A000959 lucky numbers] on The On-Line Encyclopedia of Integer Sequences.\n* Sequence [https://oeis.org/A045954 A045954 even lucky numbers or ELN] on The On-Line Encyclopedia of Integer Sequences.\n* Entry [http://mathworld.wolfram.com/LuckyNumber.html lucky numbers] on The Eric Weisstein's World of Mathematics.\n", "solution": "#include \n#include \n#include \n\n#define LUCKY_SIZE 60000\nint luckyOdd[LUCKY_SIZE];\nint luckyEven[LUCKY_SIZE];\n\nvoid compactLucky(int luckyArray[]) {\n int i, j, k;\n\n for (i = 0; i < LUCKY_SIZE; i++) {\n if (luckyArray[i] == 0) {\n j = i;\n break;\n }\n }\n\n for (j = i + 1; j < LUCKY_SIZE; j++) {\n if (luckyArray[j] > 0) {\n luckyArray[i++] = luckyArray[j];\n }\n }\n\n for (; i < LUCKY_SIZE; i++) {\n luckyArray[i] = 0;\n }\n}\n\nvoid initialize() {\n int i, j;\n\n // unfiltered\n for (i = 0; i < LUCKY_SIZE; i++) {\n luckyEven[i] = 2 * i + 2;\n luckyOdd[i] = 2 * i + 1;\n }\n\n // odd filter\n for (i = 1; i < LUCKY_SIZE; i++) {\n if (luckyOdd[i] > 0) {\n for (j = luckyOdd[i] - 1; j < LUCKY_SIZE; j += luckyOdd[i]) {\n luckyOdd[j] = 0;\n }\n compactLucky(luckyOdd);\n }\n }\n\n // even filter\n for (i = 1; i < LUCKY_SIZE; i++) {\n if (luckyEven[i] > 0) {\n for (j = luckyEven[i] - 1; j < LUCKY_SIZE; j += luckyEven[i]) {\n luckyEven[j] = 0;\n }\n compactLucky(luckyEven);\n }\n }\n}\n\nvoid printBetween(size_t j, size_t k, bool even) {\n int i;\n\n if (even) {\n if (luckyEven[j] == 0 || luckyEven[k] == 0) {\n fprintf(stderr, \"At least one argument is too large\\n\");\n exit(EXIT_FAILURE);\n }\n printf(\"Lucky even numbers between %d and %d are:\", j, k);\n for (i = 0; luckyEven[i] != 0; i++) {\n if (luckyEven[i] > k) {\n break;\n }\n if (luckyEven[i] > j) {\n printf(\" %d\", luckyEven[i]);\n }\n }\n } else {\n if (luckyOdd[j] == 0 || luckyOdd[k] == 0) {\n fprintf(stderr, \"At least one argument is too large\\n\");\n exit(EXIT_FAILURE);\n }\n printf(\"Lucky numbers between %d and %d are:\", j, k);\n for (i = 0; luckyOdd[i] != 0; i++) {\n if (luckyOdd[i] > k) {\n break;\n }\n if (luckyOdd[i] > j) {\n printf(\" %d\", luckyOdd[i]);\n }\n }\n }\n printf(\"\\n\");\n}\n\nvoid printRange(size_t j, size_t k, bool even) {\n int i;\n\n if (even) {\n if (luckyEven[k] == 0) {\n fprintf(stderr, \"The argument is too large\\n\");\n exit(EXIT_FAILURE);\n }\n printf(\"Lucky even numbers %d to %d are:\", j, k);\n for (i = j - 1; i < k; i++) {\n printf(\" %d\", luckyEven[i]);\n }\n } else {\n if (luckyOdd[k] == 0) {\n fprintf(stderr, \"The argument is too large\\n\");\n exit(EXIT_FAILURE);\n }\n printf(\"Lucky numbers %d to %d are:\", j, k);\n for (i = j - 1; i < k; i++) {\n printf(\" %d\", luckyOdd[i]);\n }\n }\n printf(\"\\n\");\n}\n\nvoid printSingle(size_t j, bool even) {\n if (even) {\n if (luckyEven[j] == 0) {\n fprintf(stderr, \"The argument is too large\\n\");\n exit(EXIT_FAILURE);\n }\n printf(\"Lucky even number %d=%d\\n\", j, luckyEven[j - 1]);\n } else {\n if (luckyOdd[j] == 0) {\n fprintf(stderr, \"The argument is too large\\n\");\n exit(EXIT_FAILURE);\n }\n printf(\"Lucky number %d=%d\\n\", j, luckyOdd[j - 1]);\n }\n}\n\nvoid help() {\n printf(\"./lucky j [k] [--lucky|--evenLucky]\\n\");\n printf(\"\\n\");\n printf(\" argument(s) | what is displayed\\n\");\n printf(\"==============================================\\n\");\n printf(\"-j=m | mth lucky number\\n\");\n printf(\"-j=m --lucky | mth lucky number\\n\");\n printf(\"-j=m --evenLucky | mth even lucky number\\n\");\n printf(\"-j=m -k=n | mth through nth (inclusive) lucky numbers\\n\");\n printf(\"-j=m -k=n --lucky | mth through nth (inclusive) lucky numbers\\n\");\n printf(\"-j=m -k=n --evenLucky | mth through nth (inclusive) even lucky numbers\\n\");\n printf(\"-j=m -k=-n | all lucky numbers in the range [m, n]\\n\");\n printf(\"-j=m -k=-n --lucky | all lucky numbers in the range [m, n]\\n\");\n printf(\"-j=m -k=-n --evenLucky | all even lucky numbers in the range [m, n]\\n\");\n}\n\nvoid process(int argc, char *argv[]) {\n bool evenLucky = false;\n int j = 0;\n int k = 0;\n\n bool good = false;\n int i;\n\n for (i = 1; i < argc; ++i) {\n if ('-' == argv[i][0]) {\n if ('-' == argv[i][1]) {\n // long args\n if (0 == strcmp(\"--lucky\", argv[i])) {\n evenLucky = false;\n } else if (0 == strcmp(\"--evenLucky\", argv[i])) {\n evenLucky = true;\n } else {\n fprintf(stderr, \"Unknown long argument: [%s]\\n\", argv[i]);\n exit(EXIT_FAILURE);\n }\n } else {\n // short args\n if ('j' == argv[i][1] && '=' == argv[i][2] && argv[i][3] != 0) {\n good = true;\n j = atoi(&argv[i][3]);\n } else if ('k' == argv[i][1] && '=' == argv[i][2]) {\n k = atoi(&argv[i][3]);\n } else {\n fprintf(stderr, \"Unknown short argument: [%s]\\n\", argv[i]);\n exit(EXIT_FAILURE);\n }\n }\n } else {\n fprintf(stderr, \"Unknown argument: [%s]\\n\", argv[i]);\n exit(EXIT_FAILURE);\n }\n }\n\n if (!good) {\n help();\n exit(EXIT_FAILURE);\n }\n\n if (k > 0) {\n printRange(j, k, evenLucky);\n } else if (k < 0) {\n printBetween(j, -k, evenLucky);\n } else {\n printSingle(j, evenLucky);\n }\n}\n\nvoid test() {\n printRange(1, 20, false);\n printRange(1, 20, true);\n\n printBetween(6000, 6100, false);\n printBetween(6000, 6100, true);\n\n printSingle(10000, false);\n printSingle(10000, true);\n}\n\nint main(int argc, char *argv[]) {\n initialize();\n\n //test();\n\n if (argc < 2) {\n help();\n return 1;\n }\n process(argc, argv);\n\n return 0;\n}"} +{"title": "Lucky and even lucky numbers", "language": "JavaScript", "task": "Note that in the following explanation list indices are assumed to start at ''one''.\n\n;Definition of lucky numbers\n''Lucky numbers'' are positive integers that are formed by:\n\n# Form a list of all the positive odd integers > 01, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39 ...\n# Return the first number from the list (which is '''1''').\n# (Loop begins here)\n#* Note then return the second number from the list (which is '''3''').\n#* Discard every third, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 19, 21, 25, 27, 31, 33, 37, 39, 43, 45, 49, 51, 55, 57 ...\n# (Expanding the loop a few more times...)\n#* Note then return the third number from the list (which is '''7''').\n#* Discard every 7th, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 21, 25, 27, 31, 33, 37, 43, 45, 49, 51, 55, 57, 63, 67 ...\n#* Note then return the 4th number from the list (which is '''9''').\n#* Discard every 9th, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, 43, 45, 49, 51, 55, 63, 67, 69, 73 ...\n#* Take the 5th, i.e. '''13'''. Remove every 13th.\n#* Take the 6th, i.e. '''15'''. Remove every 15th.\n#* Take the 7th, i.e. '''21'''. Remove every 21th.\n#* Take the 8th, i.e. '''25'''. Remove every 25th.\n# (Rule for the loop)\n#* Note the nth, which is m.\n#* Remove every mth.\n#* Increment n.\n\n;Definition of even lucky numbers\nThis follows the same rules as the definition of lucky numbers above ''except for the very first step'':\n# Form a list of all the positive '''even''' integers > 02, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40 ...\n# Return the first number from the list (which is '''2''').\n# (Loop begins here)\n#* Note then return the second number from the list (which is '''4''').\n#* Discard every 4th, (as noted), number from the list to form the new list2, 4, 6, 10, 12, 14, 18, 20, 22, 26, 28, 30, 34, 36, 38, 42, 44, 46, 50, 52 ...\n# (Expanding the loop a few more times...)\n#* Note then return the third number from the list (which is '''6''').\n#* Discard every 6th, (as noted), number from the list to form the new list2, 4, 6, 10, 12, 18, 20, 22, 26, 28, 34, 36, 38, 42, 44, 50, 52, 54, 58, 60 ...\n#* Take the 4th, i.e. '''10'''. Remove every 10th.\n#* Take the 5th, i.e. '''12'''. Remove every 12th.\n# (Rule for the loop)\n#* Note the nth, which is m.\n#* Remove every mth.\n#* Increment n.\n\n;Task requirements\n* Write one or two subroutines (functions) to generate ''lucky numbers'' and ''even lucky numbers'' \n* Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors:\n** missing arguments\n** too many arguments\n** number (or numbers) aren't legal\n** misspelled argument ('''lucky''' or '''evenLucky''')\n* The command line handling should:\n** support mixed case handling of the (non-numeric) arguments\n** support printing a particular number\n** support printing a range of numbers by their index\n** support printing a range of numbers by their values\n* The resulting list of numbers should be printed on a single line.\n\nThe program should support the arguments:\n\n what is displayed (on a single line)\n argument(s) (optional verbiage is encouraged)\n \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n \u2551 j \u2551 Jth lucky number \u2551\n \u2551 j , lucky \u2551 Jth lucky number \u2551\n \u2551 j , evenLucky \u2551 Jth even lucky number \u2551\n \u2551 \u2551 \u2551\n \u2551 j k \u2551 Jth through Kth (inclusive) lucky numbers \u2551\n \u2551 j k lucky \u2551 Jth through Kth (inclusive) lucky numbers \u2551\n \u2551 j k evenLucky \u2551 Jth through Kth (inclusive) even lucky numbers \u2551\n \u2551 \u2551 \u2551\n \u2551 j -k \u2551 all lucky numbers in the range j \u2500\u2500\u25ba |k| \u2551\n \u2551 j -k lucky \u2551 all lucky numbers in the range j \u2500\u2500\u25ba |k| \u2551\n \u2551 j -k evenLucky \u2551 all even lucky numbers in the range j \u2500\u2500\u25ba |k| \u2551\n \u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d\n where |k| is the absolute value of k\n\nDemonstrate the program by:\n* showing the first twenty ''lucky'' numbers\n* showing the first twenty ''even lucky'' numbers\n* showing all ''lucky'' numbers between 6,000 and 6,100 (inclusive)\n* showing all ''even lucky'' numbers in the same range as above\n* showing the 10,000th ''lucky'' number (extra credit)\n* showing the 10,000th ''even lucky'' number (extra credit)\n\n;See also:\n* This task is related to the [[Sieve of Eratosthenes]] task.\n* OEIS Wiki [http://oeis.org/wiki/Lucky_numbers Lucky numbers].\n* Sequence [https://oeis.org/A000959 A000959 lucky numbers] on The On-Line Encyclopedia of Integer Sequences.\n* Sequence [https://oeis.org/A045954 A045954 even lucky numbers or ELN] on The On-Line Encyclopedia of Integer Sequences.\n* Entry [http://mathworld.wolfram.com/LuckyNumber.html lucky numbers] on The Eric Weisstein's World of Mathematics.\n", "solution": "\nfunction luckyNumbers(opts={}) {\n /**************************************************************************\\\n | OPTIONS |\n |**************************************************************************|\n | even ...... boolean ............. return even/uneven numbers |\n | (default: false) |\n | |\n | nth ....... number ............... return nth number |\n | |\n | through ... number ............... return numbers from #1 to number |\n | OR array[from, to] ... return numbers on index |\n | from array[from] to array[to] |\n | |\n | range ..... array[from, to] ...... return numbers between from and to |\n \\**************************************************************************/\n\n opts.even = opts.even || false;\n if (typeof opts.through == 'number') opts.through = [0, opts.through];\n let out = [],\n x = opts.even ? 2 : 1,\n max = opts.range ? opts.range[1] * 3\n : opts.through ? opts.through[1] * 12\n : opts.nth ? opts.nth * 15\n : 2000;\n\n for (x; x <= max; x = x+2) out.push(x); // fill\n for (x = 1; x < Math.floor(out.length / 2); x++) { // sieve\n let i = out.length;\n while (i--)\n (i+1) % out[x] == 0 && out.splice(i, 1);\n }\n\n if (opts.nth) return out[opts.nth-1];\n if (opts.through) return out.slice(opts.through[0], opts.through[1]);\n if (opts.range) return out.filter(function(val) {\n return val >= opts.range[0] && val <= opts.range[1];\n });\n return out;\n}\n\n/* TESTING */\n// blank\nconsole.log( luckyNumbers() );\n// showing the first twenty lucky numbers\nconsole.log( luckyNumbers({through: 20}) );\n// showing the first twenty even lucky numbers\nconsole.log( luckyNumbers({even: true, through: 20}) );\n// showing all lucky numbers between 6,000 and 6,100 (inclusive)\nconsole.log( luckyNumbers({range: [6000, 6100]}) );\n// showing all even lucky numbers in the same range as above\nconsole.log( luckyNumbers({even: true, range: [6000, 6100]}) );\n// showing the 10,000th lucky number (extra credit)\nconsole.log( luckyNumbers({nth: 10000}) );\n// showing the 10,000th even lucky number (extra credit)\nconsole.log( luckyNumbers({even: true, nth: 10000}) );\n"} +{"title": "Lucky and even lucky numbers", "language": "Python", "task": "Note that in the following explanation list indices are assumed to start at ''one''.\n\n;Definition of lucky numbers\n''Lucky numbers'' are positive integers that are formed by:\n\n# Form a list of all the positive odd integers > 01, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39 ...\n# Return the first number from the list (which is '''1''').\n# (Loop begins here)\n#* Note then return the second number from the list (which is '''3''').\n#* Discard every third, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 19, 21, 25, 27, 31, 33, 37, 39, 43, 45, 49, 51, 55, 57 ...\n# (Expanding the loop a few more times...)\n#* Note then return the third number from the list (which is '''7''').\n#* Discard every 7th, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 21, 25, 27, 31, 33, 37, 43, 45, 49, 51, 55, 57, 63, 67 ...\n#* Note then return the 4th number from the list (which is '''9''').\n#* Discard every 9th, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, 43, 45, 49, 51, 55, 63, 67, 69, 73 ...\n#* Take the 5th, i.e. '''13'''. Remove every 13th.\n#* Take the 6th, i.e. '''15'''. Remove every 15th.\n#* Take the 7th, i.e. '''21'''. Remove every 21th.\n#* Take the 8th, i.e. '''25'''. Remove every 25th.\n# (Rule for the loop)\n#* Note the nth, which is m.\n#* Remove every mth.\n#* Increment n.\n\n;Definition of even lucky numbers\nThis follows the same rules as the definition of lucky numbers above ''except for the very first step'':\n# Form a list of all the positive '''even''' integers > 02, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40 ...\n# Return the first number from the list (which is '''2''').\n# (Loop begins here)\n#* Note then return the second number from the list (which is '''4''').\n#* Discard every 4th, (as noted), number from the list to form the new list2, 4, 6, 10, 12, 14, 18, 20, 22, 26, 28, 30, 34, 36, 38, 42, 44, 46, 50, 52 ...\n# (Expanding the loop a few more times...)\n#* Note then return the third number from the list (which is '''6''').\n#* Discard every 6th, (as noted), number from the list to form the new list2, 4, 6, 10, 12, 18, 20, 22, 26, 28, 34, 36, 38, 42, 44, 50, 52, 54, 58, 60 ...\n#* Take the 4th, i.e. '''10'''. Remove every 10th.\n#* Take the 5th, i.e. '''12'''. Remove every 12th.\n# (Rule for the loop)\n#* Note the nth, which is m.\n#* Remove every mth.\n#* Increment n.\n\n;Task requirements\n* Write one or two subroutines (functions) to generate ''lucky numbers'' and ''even lucky numbers'' \n* Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors:\n** missing arguments\n** too many arguments\n** number (or numbers) aren't legal\n** misspelled argument ('''lucky''' or '''evenLucky''')\n* The command line handling should:\n** support mixed case handling of the (non-numeric) arguments\n** support printing a particular number\n** support printing a range of numbers by their index\n** support printing a range of numbers by their values\n* The resulting list of numbers should be printed on a single line.\n\nThe program should support the arguments:\n\n what is displayed (on a single line)\n argument(s) (optional verbiage is encouraged)\n \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n \u2551 j \u2551 Jth lucky number \u2551\n \u2551 j , lucky \u2551 Jth lucky number \u2551\n \u2551 j , evenLucky \u2551 Jth even lucky number \u2551\n \u2551 \u2551 \u2551\n \u2551 j k \u2551 Jth through Kth (inclusive) lucky numbers \u2551\n \u2551 j k lucky \u2551 Jth through Kth (inclusive) lucky numbers \u2551\n \u2551 j k evenLucky \u2551 Jth through Kth (inclusive) even lucky numbers \u2551\n \u2551 \u2551 \u2551\n \u2551 j -k \u2551 all lucky numbers in the range j \u2500\u2500\u25ba |k| \u2551\n \u2551 j -k lucky \u2551 all lucky numbers in the range j \u2500\u2500\u25ba |k| \u2551\n \u2551 j -k evenLucky \u2551 all even lucky numbers in the range j \u2500\u2500\u25ba |k| \u2551\n \u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d\n where |k| is the absolute value of k\n\nDemonstrate the program by:\n* showing the first twenty ''lucky'' numbers\n* showing the first twenty ''even lucky'' numbers\n* showing all ''lucky'' numbers between 6,000 and 6,100 (inclusive)\n* showing all ''even lucky'' numbers in the same range as above\n* showing the 10,000th ''lucky'' number (extra credit)\n* showing the 10,000th ''even lucky'' number (extra credit)\n\n;See also:\n* This task is related to the [[Sieve of Eratosthenes]] task.\n* OEIS Wiki [http://oeis.org/wiki/Lucky_numbers Lucky numbers].\n* Sequence [https://oeis.org/A000959 A000959 lucky numbers] on The On-Line Encyclopedia of Integer Sequences.\n* Sequence [https://oeis.org/A045954 A045954 even lucky numbers or ELN] on The On-Line Encyclopedia of Integer Sequences.\n* Entry [http://mathworld.wolfram.com/LuckyNumber.html lucky numbers] on The Eric Weisstein's World of Mathematics.\n", "solution": "from itertools import islice\nimport sys, re\n\nclass ArgumentError(Exception):\n pass\ndef arghandler(argstring):\n match_obj = re.match( r\"\"\"(?mx)\n (?:\n (?P\n (?: ^ (?P \\d+ ) (?: | \\s , \\s lucky ) \\s* $ )\n |(?: ^ (?P \\d+ ) (?: | \\s , \\s evenLucky ) \\s* $ )\n )\n |(?P\n (?: ^ (?P \\d+ \\s \\d+ ) (?: | \\s lucky ) \\s* $ )\n |(?: ^ (?P \\d+ \\s \\d+ ) (?: | \\s evenLucky ) \\s* $ )\n )\n |(?P\n (?: ^ (?P \\d+ \\s -\\d+ ) (?: | \\s lucky ) \\s* $ )\n |(?: ^ (?P \\d+ \\s -\\d+ ) (?: | \\s evenLucky ) \\s* $ )\n )\n )\"\"\", argstring)\n \n if match_obj:\n # Retrieve group(s) by name\n SINGLEL = match_obj.group('SINGLEL')\n SINGLEE = match_obj.group('SINGLEE')\n KTHL = match_obj.group('KTHL')\n KTHE = match_obj.group('KTHE')\n RANGEL = match_obj.group('RANGEL')\n RANGEE = match_obj.group('RANGEE')\n if SINGLEL: \n j = int(SINGLEL)\n assert 0 < j < 10001, \"Argument out of range\"\n print(\"Single %i'th lucky number:\" % j, end=' ')\n print( list(islice(lgen(), j-1, j))[0] )\n elif SINGLEE: \n j = int(SINGLEE)\n assert 0 < j < 10001, \"Argument out of range\"\n print(\"Single %i'th even lucky number:\" % j, end=' ')\n print( list(islice(lgen(even=True), j-1, j))[0] )\n elif KTHL: \n j, k = [int(num) for num in KTHL.split()]\n assert 0 < j < 10001, \"first argument out of range\"\n assert 0 < k < 10001 and k > j, \"second argument out of range\"\n print(\"List of %i ... %i lucky numbers:\" % (j, k), end=' ')\n for n, luck in enumerate(lgen(), 1):\n if n > k: break\n if n >=j: print(luck, end = ', ')\n print('')\n elif KTHE: \n j, k = [int(num) for num in KTHE.split()]\n assert 0 < j < 10001, \"first argument out of range\"\n assert 0 < k < 10001 and k > j, \"second argument out of range\"\n print(\"List of %i ... %i even lucky numbers:\" % (j, k), end=' ')\n for n, luck in enumerate(lgen(even=True), 1):\n if n > k: break\n if n >=j: print(luck, end = ', ')\n print('')\n elif RANGEL: \n j, k = [int(num) for num in RANGEL.split()]\n assert 0 < j < 10001, \"first argument out of range\"\n assert 0 < -k < 10001 and -k > j, \"second argument out of range\"\n k = -k\n print(\"List of lucky numbers in the range %i ... %i :\" % (j, k), end=' ')\n for n in lgen():\n if n > k: break\n if n >=j: print(n, end = ', ')\n print('')\n elif RANGEE: \n j, k = [int(num) for num in RANGEE.split()]\n assert 0 < j < 10001, \"first argument out of range\"\n assert 0 < -k < 10001 and -k > j, \"second argument out of range\"\n k = -k\n print(\"List of even lucky numbers in the range %i ... %i :\" % (j, k), end=' ')\n for n in lgen(even=True):\n if n > k: break\n if n >=j: print(n, end = ', ')\n print('')\n else:\n raise ArgumentError('''\n \n Error Parsing Arguments!\n \n Expected Arguments of the form (where j and k are integers):\n \n j # Jth lucky number\n j , lucky # Jth lucky number\n j , evenLucky # Jth even lucky number\n #\n j k # Jth through Kth (inclusive) lucky numbers\n j k lucky # Jth through Kth (inclusive) lucky numbers\n j k evenLucky # Jth through Kth (inclusive) even lucky numbers\n #\n j -k # all lucky numbers in the range j --? |k|\n j -k lucky # all lucky numbers in the range j --? |k|\n j -k evenLucky # all even lucky numbers in the range j --? |k|\n ''')\n\nif __name__ == '__main__':\n arghandler(' '.join(sys.argv[1:]))"} +{"title": "Lychrel numbers", "language": "Python", "task": "::# \u00a0 Take an integer n, greater than zero.\n::# \u00a0 Form the next n of its series by reversing the digits of the current n and adding the result to the current n.\n::# \u00a0 Stop when n becomes palindromic - i.e. the digits of n in reverse order == n.\n\n\nThe above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly.\n\n\n;Example:\nIf n0 = 12 we get\n\n 12\n 12 + 21 = 33, a palindrome!\n\n\nAnd if n0 = 55 we get\n\n 55\n 55 + 55 = 110\n 110 + 011 = 121, a palindrome!\n\n\nNotice that the check for a palindrome happens \u00a0 ''after'' \u00a0 an addition.\n\n\nSome starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome. \n\nThese numbers that do not end in a palindrome are called '''Lychrel numbers'''.\n\nFor the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations.\n\n\n;Seed and related Lychrel numbers:\nAny integer produced in the sequence of a Lychrel number is also a Lychrel number.\n\nIn general, any sequence from one Lychrel number ''might'' converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin:\n\n 196\n 196 + 691 = 887\n 887 + 788 = 1675\n 1675 + 5761 = 7436\n 7436 + 6347 = 13783\n 13783 + 38731 = 52514\n 52514 + 41525 = 94039\n ...\n\n\n 689\n 689 + 986 = 1675\n 1675 + 5761 = 7436\n ...\n\nSo we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196. \n\nBecause of this we can further split the Lychrel numbers into true '''Seed''' Lychrel number candidates, and '''Related''' numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number.\n\n\n;Task:\n* \u00a0 Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500).\n* \u00a0 Print the number of seed Lychrels found; the actual seed Lychrels; and just the ''number'' of relateds found.\n* \u00a0 Print any seed Lychrel or related number that is itself a palindrome.\n\n\nShow all output here.\n\n\n;References:\n* \u00a0 [https://www.youtube.com/watch?v=bN8PE3eljdA What's special about 196?] Numberphile video.\n* \u00a0 [http://oeis.org/A023108 A023108] Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed).\n* \u00a0 [http://mathoverflow.net/questions/117104/status-of-the-196-conjecture/117277#117277 Status of the 196 conjecture?] Mathoverflow.\n\n", "solution": "from __future__ import print_function\n\ndef add_reverse(num, max_iter=1000):\n i, nums = 0, {num}\n while True:\n i, num = i+1, num + reverse_int(num)\n nums.add(num)\n if reverse_int(num) == num or i >= max_iter:\n break\n return nums\n \n#@functools.lru_cache(maxsize=2**20)\ndef reverse_int(num):\n return int(str(num)[::-1])\n\ndef split_roots_from_relateds(roots_and_relateds):\n roots = roots_and_relateds[::]\n i = 1\n while i < len(roots):\n this = roots[i]\n if any(this.intersection(prev) for prev in roots[:i]):\n del roots[i]\n else:\n i += 1\n root = [min(each_set) for each_set in roots]\n related = [min(each_set) for each_set in roots_and_relateds]\n related = [n for n in related if n not in root]\n return root, related\n\ndef find_lychrel(maxn, max_reversions):\n 'Lychrel number generator'\n series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)]\n roots_and_relateds = [s for s in series if len(s) > max_reversions]\n return split_roots_from_relateds(roots_and_relateds)\n\n\nif __name__ == '__main__':\n maxn, reversion_limit = 10000, 500\n print(\"Calculations using n = 1..%i and limiting each search to 2*%i reverse-digits-and-adds\"\n % (maxn, reversion_limit))\n lychrel, l_related = find_lychrel(maxn, reversion_limit)\n print(' Number of Lychrel numbers:', len(lychrel))\n print(' Lychrel numbers:', ', '.join(str(n) for n in lychrel))\n print(' Number of Lychrel related:', len(l_related))\n #print(' Lychrel related:', ', '.join(str(n) for n in l_related))\n pals = [x for x in lychrel + l_related if x == reverse_int(x)]\n print(' Number of Lychrel palindromes:', len(pals))\n print(' Lychrel palindromes:', ', '.join(str(n) for n in pals))"} +{"title": "MAC vendor lookup", "language": "C", "task": "[[Category:Network Tools]]\n\nEvery connected device around the world comes with a unique Media Access Control address, or a \u00a0 [https://en.wikipedia.org/wiki/MAC_address 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\". \u00a0 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": "\n#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": "MAC vendor lookup", "language": "Python", "task": "[[Category:Network Tools]]\n\nEvery connected device around the world comes with a unique Media Access Control address, or a \u00a0 [https://en.wikipedia.org/wiki/MAC_address 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\". \u00a0 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": "import requests\n\nfor addr in ['88:53:2E:67:07:BE', 'FC:FB:FB:01:FA:21',\n 'D4:F4:6F:C9:EF:8D', '23:45:67']:\n vendor = requests.get('http://api.macvendors.com/' + addr).text\n print(addr, vendor)"} +{"title": "MD4", "language": "C", "task": "Find the MD4 message digest of a string of [[octet]]s. \nUse the ASCII encoded string \u201cRosetta Code\u201d (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 *\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": "MD4", "language": "JavaScript", "task": "Find the MD4 message digest of a string of [[octet]]s. \nUse the ASCII encoded string \u201cRosetta Code\u201d (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": "const md4func = () => {\n\n const hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */\n const b64pad = \"\"; /* base-64 pad character. \"=\" for strict RFC compliance */\n const chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */\n\n const tab = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n const hex_tab = hexcase ? \"0123456789ABCDEF\" : \"0123456789abcdef\";\n\n /**\n * Add integers, wrapping at 2^32. This uses 16-bit operations internally\n * to work around bugs in some JS interpreters.\n */\n const safe_add = (x, y) => {\n const lsw = (x & 0xFFFF) + (y & 0xFFFF);\n const msw = (x >> 16) + (y >> 16) + (lsw >> 16);\n return (msw << 16) | (lsw & 0xFFFF);\n };\n\n /**\n * Bitwise rotate a 32-bit number to the left.\n */\n const rol = (num, cnt) => (num << cnt) | (num >>> (32 - cnt));\n\n /**\n * Convert a string to an array of little-endian words\n * If chrsz is ASCII, characters >255 have their hi-byte silently ignored.\n */\n const str2binl = str => {\n const bin = Array();\n const mask = (1 << chrsz) - 1;\n for (let i = 0; i < str.length * chrsz; i += chrsz)\n bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (i % 32);\n return bin;\n };\n\n /**\n * Convert an array of little-endian words to a string\n */\n const binl2str = bin => {\n let str = \"\";\n const mask = (1 << chrsz) - 1;\n for (let i = 0; i < bin.length * 32; i += chrsz)\n str += String.fromCharCode((bin[i >> 5] >>> (i % 32)) & mask);\n return str;\n };\n\n /**\n * Convert an array of little-endian words to a hex string.\n */\n const binl2hex = binarray => {\n let str = \"\";\n for (let i = 0; i < binarray.length * 4; i++) {\n str += hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8 + 4)) & 0xF) +\n hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8)) & 0xF);\n }\n return str;\n };\n\n /**\n * Convert an array of little-endian words to a base-64 string\n */\n const binl2b64 = binarray => {\n let str = \"\";\n for (let i = 0; i < binarray.length * 4; i += 3) {\n const triplet = (((binarray[i >> 2] >> 8 * (i % 4)) & 0xFF) << 16)\n | (((binarray[i + 1 >> 2] >> 8 * ((i + 1) % 4)) & 0xFF) << 8)\n | ((binarray[i + 2 >> 2] >> 8 * ((i + 2) % 4)) & 0xFF);\n for (let j = 0; j < 4; j++) {\n if (i * 8 + j * 6 > binarray.length * 32) str += b64pad;\n else str += tab.charAt((triplet >> 6 * (3 - j)) & 0x3F);\n }\n }\n return str;\n };\n\n\n /**\n * Calculate the MD4 of an array of little-endian words, and a bit length\n */\n const core_md4 = (x, len) => {\n\n x[len >> 5] |= 0x80 << (len % 32);\n x[(((len + 64) >>> 9) << 4) + 14] = len;\n let a = 1732584193;\n let b = -271733879;\n let c = -1732584194;\n let d = 271733878;\n\n for (let i = 0; i < x.length; i += 16) {\n\n const olda = a;\n const oldb = b;\n const oldc = c;\n const oldd = d;\n\n a = md4_ff(a, b, c, d, x[i], 3);\n d = md4_ff(d, a, b, c, x[i + 1], 7);\n c = md4_ff(c, d, a, b, x[i + 2], 11);\n b = md4_ff(b, c, d, a, x[i + 3], 19);\n a = md4_ff(a, b, c, d, x[i + 4], 3);\n d = md4_ff(d, a, b, c, x[i + 5], 7);\n c = md4_ff(c, d, a, b, x[i + 6], 11);\n b = md4_ff(b, c, d, a, x[i + 7], 19);\n a = md4_ff(a, b, c, d, x[i + 8], 3);\n d = md4_ff(d, a, b, c, x[i + 9], 7);\n c = md4_ff(c, d, a, b, x[i + 10], 11);\n b = md4_ff(b, c, d, a, x[i + 11], 19);\n a = md4_ff(a, b, c, d, x[i + 12], 3);\n d = md4_ff(d, a, b, c, x[i + 13], 7);\n c = md4_ff(c, d, a, b, x[i + 14], 11);\n b = md4_ff(b, c, d, a, x[i + 15], 19);\n\n a = md4_gg(a, b, c, d, x[i], 3);\n d = md4_gg(d, a, b, c, x[i + 4], 5);\n c = md4_gg(c, d, a, b, x[i + 8], 9);\n b = md4_gg(b, c, d, a, x[i + 12], 13);\n a = md4_gg(a, b, c, d, x[i + 1], 3);\n d = md4_gg(d, a, b, c, x[i + 5], 5);\n c = md4_gg(c, d, a, b, x[i + 9], 9);\n b = md4_gg(b, c, d, a, x[i + 13], 13);\n a = md4_gg(a, b, c, d, x[i + 2], 3);\n d = md4_gg(d, a, b, c, x[i + 6], 5);\n c = md4_gg(c, d, a, b, x[i + 10], 9);\n b = md4_gg(b, c, d, a, x[i + 14], 13);\n a = md4_gg(a, b, c, d, x[i + 3], 3);\n d = md4_gg(d, a, b, c, x[i + 7], 5);\n c = md4_gg(c, d, a, b, x[i + 11], 9);\n b = md4_gg(b, c, d, a, x[i + 15], 13);\n\n a = md4_hh(a, b, c, d, x[i], 3);\n d = md4_hh(d, a, b, c, x[i + 8], 9);\n c = md4_hh(c, d, a, b, x[i + 4], 11);\n b = md4_hh(b, c, d, a, x[i + 12], 15);\n a = md4_hh(a, b, c, d, x[i + 2], 3);\n d = md4_hh(d, a, b, c, x[i + 10], 9);\n c = md4_hh(c, d, a, b, x[i + 6], 11);\n b = md4_hh(b, c, d, a, x[i + 14], 15);\n a = md4_hh(a, b, c, d, x[i + 1], 3);\n d = md4_hh(d, a, b, c, x[i + 9], 9);\n c = md4_hh(c, d, a, b, x[i + 5], 11);\n b = md4_hh(b, c, d, a, x[i + 13], 15);\n a = md4_hh(a, b, c, d, x[i + 3], 3);\n d = md4_hh(d, a, b, c, x[i + 11], 9);\n c = md4_hh(c, d, a, b, x[i + 7], 11);\n b = md4_hh(b, c, d, a, x[i + 15], 15);\n\n a = safe_add(a, olda);\n b = safe_add(b, oldb);\n c = safe_add(c, oldc);\n d = safe_add(d, oldd);\n }\n\n return Array(a, b, c, d);\n\n };\n\n /**\n * These functions implement the basic operation for each round of the\n * algorithm.\n */\n const md4_cmn = (q, a, b, x, s, t) => safe_add(\n rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b);\n\n const md4_ff = (a, b, c, d, x, s) => md4_cmn(\n (b & c) | ((~b) & d), a, 0, x, s, 0);\n\n const md4_gg = (a, b, c, d, x, s) => md4_cmn(\n (b & c) | (b & d) | (c & d), a, 0, x, s, 1518500249);\n\n const md4_hh = (a, b, c, d, x, s) => md4_cmn(\n b ^ c ^ d, a, 0, x, s, 1859775393);\n\n /**\n * Calculate the HMAC-MD4, of a key and some data\n */\n const core_hmac_md4 = (key, data) => {\n\n let bkey = str2binl(key);\n if (bkey.length > 16) {\n bkey = core_md4(bkey, key.length * chrsz)\n }\n\n const ipad = Array(16);\n const opad = Array(16);\n\n for (let i = 0; i < 16; i++) {\n ipad[i] = bkey[i] ^ 0x36363636;\n opad[i] = bkey[i] ^ 0x5C5C5C5C;\n }\n const hash = core_md4(\n ipad.concat(str2binl(data)), 512 + data.length * chrsz);\n\n return core_md4(opad.concat(hash), 512 + 128);\n };\n\n /**\n * These are the functions you'll usually want to call\n */\n return {\n hex_md4: s => binl2hex(core_md4(str2binl(s), s.length * chrsz)),\n b64_md4: s => binl2b64(core_md4(str2binl(s), s.length * chrsz)),\n str_md4: s => binl2str(core_md4(str2binl(s), s.length * chrsz)),\n hex_hmac_md4: (key, data) => binl2hex(core_hmac_md4(key, data)),\n b64_hmac_md4: (key, data) => binl2b64(core_hmac_md4(key, data)),\n str_hmac_md4: (key, data) => binl2str(core_hmac_md4(key, data)),\n };\n\n};\n\nconst md4 = md4func();\nconsole.log(md4.hex_md4('Rosetta Code'));"} +{"title": "MD4", "language": "Python", "task": "Find the MD4 message digest of a string of [[octet]]s. \nUse the ASCII encoded string \u201cRosetta Code\u201d (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": "import hashlib\nprint hashlib.new(\"md4\",raw_input().encode('utf-16le')).hexdigest().upper()"} +{"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": "Machine code", "language": "CPython 3.x", "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": "import ctypes\nimport os\nfrom ctypes import c_ubyte, c_int\n\ncode = bytes([0x8b, 0x44, 0x24, 0x04, 0x03, 0x44, 0x24, 0x08, 0xc3])\n\ncode_size = len(code)\n# copy code into an executable buffer\nif (os.name == 'posix'):\n import mmap\n executable_map = mmap.mmap(-1, code_size, mmap.MAP_PRIVATE | mmap.MAP_ANON, mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC)\n # we must keep a reference to executable_map until the call, to avoid freeing the mapped memory\n executable_map.write(code)\n # the mmap object won't tell us the actual address of the mapping, but we can fish it out by allocating\n # some ctypes object over its buffer, then asking the address of that\n func_address = ctypes.addressof(c_ubyte.from_buffer(executable_map))\nelif (os.name == 'nt'):\n # the mmap module doesn't support protection flags on Windows, so execute VirtualAlloc instead\n code_buffer = ctypes.create_string_buffer(code)\n PAGE_EXECUTE_READWRITE = 0x40 # Windows constants that would usually come from header files\n MEM_COMMIT = 0x1000\n executable_buffer_address = ctypes.windll.kernel32.VirtualAlloc(0, code_size, MEM_COMMIT, PAGE_EXECUTE_READWRITE)\n if (executable_buffer_address == 0):\n print('Warning: Failed to enable code execution, call will likely cause a protection fault.')\n func_address = ctypes.addressof(code_buffer)\n else:\n ctypes.memmove(executable_buffer_address, code_buffer, code_size)\n func_address = executable_buffer_address\nelse:\n # for other platforms, we just hope DEP isn't enabled\n code_buffer = ctypes.create_string_buffer(code)\n func_address = ctypes.addressof(code_buffer)\n\nprototype = ctypes.CFUNCTYPE(c_int, c_ubyte, c_ubyte) # build a function prototype from return type and argument types\nfunc = prototype(func_address) # build an actual function from the prototype by specifying the address\nres = func(7,12)\nprint(res)\n"} +{"title": "Mad Libs", "language": "C", "task": "Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. \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": "\n#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": "Mad Libs", "language": "Python", "task": "Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. \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": "import re\n\n# Optional Python 2.x compatibility\n#try: input = raw_input\n#except: pass\n\ntemplate = ''' went for a walk in the park. \nfound a . decided to take it home.'''\n\ndef madlibs(template):\n print('The story template is:\\n' + template)\n fields = sorted(set( re.findall('<[^>]+>', template) ))\n values = input('\\nInput a comma-separated list of words to replace the following items'\n '\\n %s: ' % ','.join(fields)).split(',')\n story = template\n for f,v in zip(fields, values):\n story = story.replace(f, v)\n print('\\nThe story becomes:\\n\\n' + story)\n\nmadlibs(template)"} +{"title": "Magic 8-ball", "language": "C", "task": ";Task:\nCreate Magic 8-Ball. \n\n\nSee details at: \u00a0 [https://en.wikipedia.org/wiki/Magic_8-Ball Magic 8-Ball].\n\n\n\n", "solution": "#include \n#include \n#include \n\nint main() {\n char *question = NULL;\n size_t len = 0;\n ssize_t read;\n const char* answers[20] = {\n \"It is certain\", \"It is decidedly so\", \"Without a doubt\",\n \"Yes, definitely\", \"You may rely on it\", \"As I see it, yes\",\n \"Most likely\", \"Outlook good\", \"Signs point to yes\", \"Yes\",\n \"Reply hazy, try again\", \"Ask again later\",\n \"Better not tell you now\", \"Cannot predict now\",\n \"Concentrate and ask again\", \"Don't bet on it\",\n \"My reply is no\", \"My sources say no\", \"Outlook not so good\",\n \"Very doubtful\"\n };\n srand(time(NULL));\n printf(\"Please enter your question or a blank line to quit.\\n\");\n while (1) {\n printf(\"\\n? : \");\n read = getline(&question, &len, stdin);\n if (read < 2) break;\n printf(\"\\n%s\\n\", answers[rand() % 20]);\n }\n if (question) free(question);\n return 0;\n}"} +{"title": "Magic 8-ball", "language": "JavaScript", "task": ";Task:\nCreate Magic 8-Ball. \n\n\nSee details at: \u00a0 [https://en.wikipedia.org/wiki/Magic_8-Ball Magic 8-Ball].\n\n\n\n", "solution": "\n//console\nvar answers = [ \"It is certain\", \"It is decidedly so\", \"Without a doubt\",\n \"Yes, definitely\", \"You may rely on it\", \"As I see it, yes\",\n \"Most likely\", \"Outlook good\", \"Signs point to yes\", \"Yes\",\n \"Reply hazy, try again\", \"Ask again later\",\n \"Better not tell you now\", \"Cannot predict now\",\n \"Concentrate and ask again\", \"Don't bet on it\",\n \"My reply is no\", \"My sources say no\", \"Outlook not so good\",\n \"Very doubtful\"])\n\nconsole.log(\"ASK ANY QUESTION TO THE MAGIC 8-BALL AND YOU SHALL RECEIVE AN ANSWER!\")\n\nfor(;;){\n var answer = prompt(\"question:\")\n console.log(answer)\nconsole.log(answers[Math.floor(Math.random()*answers.length)]);\n}\n"} +{"title": "Magic 8-ball", "language": "Python", "task": ";Task:\nCreate Magic 8-Ball. \n\n\nSee details at: \u00a0 [https://en.wikipedia.org/wiki/Magic_8-Ball Magic 8-Ball].\n\n\n\n", "solution": "import random\n\ns = ('It is certain', 'It is decidedly so', 'Without a doubt', 'Yes, definitely',\n 'You may rely on it', 'As I see it, yes', 'Most likely', 'Outlook good',\n 'Signs point to yes', 'Yes', 'Reply hazy, try again', 'Ask again later',\n 'Better not tell you now', 'Cannot predict now', 'Concentrate and ask again',\n \"Don't bet on it\", 'My reply is no', 'My sources say no', 'Outlook not so good',\n 'Very doubtful')\n\nq_and_a = {}\n\nwhile True:\n question = input('Ask your question:')\n if len(question) == 0: break\n \n if question in q_and_a:\n print('Your question has already been answered')\n else:\n answer = random.choice(s)\n q_and_a[question] = answer\n print(answer)"} +{"title": "Magic constant", "language": "Python", "task": "A magic square is a square grid containing consecutive integers from 1 to N\u00b2, arranged so that every row, column and diagonal adds up to the same number. That number is a constant. There is no way to create a valid N x N magic square that does not sum to the associated constant. \n\n;EG\n\nA 3 x 3 magic square ''always'' sums to 15. \n\n \u250c\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2510\n \u2502 2 \u2502 7 \u2502 6 \u2502\n \u251c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2524\n \u2502 9 \u2502 5 \u2502 1 \u2502\n \u251c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2524\n \u2502 4 \u2502 3 \u2502 8 \u2502\n \u2514\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2518\n\nA 4 x 4 magic square ''always'' sums to 34.\n\nTraditionally, the sequence leaves off terms for n = 0 and n = 1 as the magic squares of order 0 and 1 are trivial; and a term for n = 2 because it is impossible to form a magic square of order 2.\n\n\n;Task\n\n* Starting at order 3, show the first 20 magic constants.\n* Show the 1000th magic constant. (Order 1003)\n* Find and show the order of the smallest N x N magic square whose constant is greater than 10\u00b9 through 10\u00b9\u2070.\n\n\n;Stretch\n\n* Find and show the order of the smallest N x N magic square whose constant is greater than 10\u00b9\u00b9 through 10\u00b2\u2070.\n\n\n;See also\n\n* Wikipedia: Magic constant\n* OEIS: A006003 (Similar sequence, though it includes terms for 0, 1 & 2.)\n* [[Magic squares of odd order]]\n* [[Magic squares of singly even order]]\n* [[Magic squares of doubly even order]]\n\n\n\n", "solution": "#!/usr/bin/python\n\ndef a(n):\n n += 2\n return n*(n**2 + 1)/2\n \ndef inv_a(x):\n k = 0\n while k*(k**2+1)/2+2 < x:\n k+=1\n return k\n\n \nif __name__ == '__main__':\n print(\"The first 20 magic constants are:\");\n for n in range(1, 20):\n print(int(a(n)), end = \" \");\n print(\"\\nThe 1,000th magic constant is:\",int(a(1000)));\n \n for e in range(1, 20):\n print(f'10^{e}: {inv_a(10**e)}');"} +{"title": "Magic squares of doubly even order", "language": "C", "task": "A magic square is an \u00a0 '''N\u00d7N''' \u00a0square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, \u00a0 ''and'' \u00a0 both diagonals are equal to the same sum \u00a0 (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 \u00a0 (e.g. \u00a0 \u00a0 '''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 \u00a0 '''8 \u00d7 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* [http://www.1728.org/magicsq2.htm Doubly Even Magic Squares (1728.org)]\n\n", "solution": "\n#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 doubly even order", "language": "JavaScript", "task": "A magic square is an \u00a0 '''N\u00d7N''' \u00a0square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, \u00a0 ''and'' \u00a0 both diagonals are equal to the same sum \u00a0 (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 \u00a0 (e.g. \u00a0 \u00a0 '''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 \u00a0 '''8 \u00d7 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* [http://www.1728.org/magicsq2.htm Doubly Even Magic Squares (1728.org)]\n\n", "solution": "(() => {\n 'use strict';\n\n // doublyEvenMagicSquare :: Int -> [[Int]]\n const doublyEvenMagicSquare = n =>\n 0 === n % 4 ? (() => {\n const\n sqr = n * n,\n power = Math.log2(sqr),\n scale = replicate(n / 4);\n return chunksOf(n)(\n map((x, i) => x ? 1 + i : sqr - i)(\n isInt(power) ? truthSeries(power) : (\n compose(\n flatten,\n scale,\n map(scale),\n chunksOf(4)\n )(truthSeries(4))\n )\n )\n );\n })() : undefined;\n\n // truthSeries :: Int -> [Bool]\n const truthSeries = n =>\n 0 >= n ? (\n [true]\n ) : (() => {\n const xs = truthSeries(n - 1);\n return xs.concat(xs.map(x => !x));\n })();\n\n\n\n // TEST -----------------------------------------------\n const main = () =>\n // Magic squares of orders 4, 8 and 12, with\n // checks of row, column and diagonal sums.\n intercalate('\\n\\n')(\n map(n => {\n const\n lines = doublyEvenMagicSquare(n),\n sums = map(sum)(\n lines.concat(\n transpose(lines)\n .concat(diagonals(lines))\n )\n ),\n total = sums[0];\n return unlines([\n \"Order: \" + str(n),\n \"Summing to: \" + str(total),\n \"Row, column and diagonal sums checked: \" +\n str(all(eq(total))(sums)) + '\\n',\n unlines(map(compose(\n intercalate(' '),\n map(compose(justifyRight(3)(' '), str))\n ))(lines))\n ]);\n })([4, 8, 12])\n );\n\n\n // GENERIC FUNCTIONS ----------------------------------\n\n // all :: (a -> Bool) -> [a] -> Bool\n const all = p =>\n // True if p(x) holds for every x in xs.\n xs => xs.every(p);\n\n // chunksOf :: Int -> [a] -> [[a]]\n const chunksOf = n => xs =>\n enumFromThenTo(0)(n)(\n xs.length - 1\n ).reduce(\n (a, i) => a.concat([xs.slice(i, (n + i))]),\n []\n );\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (...fs) =>\n x => fs.reduceRight((a, f) => f(a), x);\n\n // diagonals :: [[a]] -> [[a], [a]]\n const diagonals = rows =>\n // Two diagonal sequences,\n // from top left and bottom left\n // respectively, of a given matrix.\n map(flip(zipWith(index))(\n enumFromTo(0)(pred(\n 0 < rows.length ? (\n rows[0].length\n ) : 0\n ))\n ))([rows, reverse(rows)]);\n\n // enumFromThenTo :: Int -> Int -> Int -> [Int]\n const enumFromThenTo = x1 => x2 => y => {\n const d = x2 - x1;\n return Array.from({\n length: Math.floor(y - x2) / d + 2\n }, (_, i) => x1 + (d * i));\n };\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = m => n =>\n Array.from({\n length: 1 + n - m\n }, (_, i) => m + i);\n\n // eq (==) :: Eq a => a -> a -> Bool\n const eq = a => b => a === b;\n\n // flatten :: NestedList a -> [a]\n const flatten = nest => nest.flat(Infinity);\n\n // flip :: (a -> b -> c) -> b -> a -> c\n const flip = f =>\n x => y => f(y)(x);\n\n // index (!!) :: [a] -> Int -> a\n const index = xs => i => xs[i];\n\n // intercalate :: String -> [String] -> String\n const intercalate = s =>\n xs => xs.join(s);\n\n // isInt :: Int -> Bool\n const isInt = x => x === Math.floor(x);\n\n // justifyRight :: Int -> Char -> String -> String\n const justifyRight = n => cFiller => s =>\n n > s.length ? (\n s.padStart(n, cFiller)\n ) : s;\n\n // map :: (a -> b) -> [a] -> [b]\n const map = f => xs =>\n (Array.isArray(xs) ? (\n xs\n ) : xs.split('')).map(f);\n\n // pred :: Enum a => a -> a\n const pred = x => x - 1;\n\n // replicate :: Int -> a -> [a]\n const replicate = n => x =>\n Array.from({\n length: n\n }, () => x);\n\n // reverse :: [a] -> [a]\n const reverse = xs =>\n 'string' !== typeof xs ? (\n xs.slice(0).reverse()\n ) : xs.split('').reverse().join('');\n\n // show :: a -> String\n const show = x => JSON.stringify(x);\n\n // str :: a -> String\n const str = x => x.toString();\n\n // sum :: [Num] -> Num\n const sum = xs => xs.reduce((a, x) => a + x, 0);\n\n // transpose :: [[a]] -> [[a]]\n const transpose = xs =>\n xs[0].map((_, iCol) => xs.map((row) => row[iCol]));\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = f => xs => ys =>\n xs.slice(\n 0, Math.min(xs.length, ys.length)\n ).map((x, i) => f(x)(ys[i]));\n\n // MAIN ------------------------------------------------\n return main();\n})();"} +{"title": "Magic squares of doubly even order", "language": "Python", "task": "A magic square is an \u00a0 '''N\u00d7N''' \u00a0square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, \u00a0 ''and'' \u00a0 both diagonals are equal to the same sum \u00a0 (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 \u00a0 (e.g. \u00a0 \u00a0 '''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 \u00a0 '''8 \u00d7 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* [http://www.1728.org/magicsq2.htm Doubly Even Magic Squares (1728.org)]\n\n", "solution": "\ndef MagicSquareDoublyEven(order):\n sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ]\n n1 = order/4\n for r in range(n1):\n r1 = sq[r][n1:-n1]\n r2 = sq[order -r - 1][n1:-n1]\n r1.reverse()\n r2.reverse()\n sq[r][n1:-n1] = r2\n sq[order -r - 1][n1:-n1] = r1\n for r in range(n1, order-n1):\n r1 = sq[r][:n1]\n r2 = sq[order -r - 1][order-n1:]\n r1.reverse()\n r2.reverse()\n sq[r][:n1] = r2\n sq[order -r - 1][order-n1:] = r1\n return sq\n\ndef printsq(s):\n n = len(s)\n bl = len(str(n**2))+1\n for i in range(n):\n print ''.join( [ (\"%\"+str(bl)+\"s\")%(str(x)) for x in s[i]] )\n print \"\\nMagic constant = %d\"%sum(s[0])\n\nprintsq(MagicSquareDoublyEven(8))\n"} +{"title": "Magic squares of odd order", "language": "C", "task": "A magic square is an \u00a0 '''NxN''' \u00a0 square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, \u00a0 ''and'' \u00a0 both long (main) diagonals are equal to the same sum (which is called the \u00a0 ''magic number'' \u00a0 or \u00a0 ''magic constant''). \n\nThe numbers are usually (but not always) the first \u00a0 '''N'''2 \u00a0 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 \u00a0 '''N''', \u00a0 generate a magic square with the integers \u00a0 ''' 1''' \u2500\u2500\u25ba '''N''', \u00a0 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 \u00a0 '''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\u2122 entry: [http://mathworld.wolfram.com/MagicSquare.html Magic_square] \n* [http://www.1728.org/magicsq1.htm 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 odd order", "language": "JavaScript", "task": "A magic square is an \u00a0 '''NxN''' \u00a0 square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, \u00a0 ''and'' \u00a0 both long (main) diagonals are equal to the same sum (which is called the \u00a0 ''magic number'' \u00a0 or \u00a0 ''magic constant''). \n\nThe numbers are usually (but not always) the first \u00a0 '''N'''2 \u00a0 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 \u00a0 '''N''', \u00a0 generate a magic square with the integers \u00a0 ''' 1''' \u2500\u2500\u25ba '''N''', \u00a0 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 \u00a0 '''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\u2122 entry: [http://mathworld.wolfram.com/MagicSquare.html Magic_square] \n* [http://www.1728.org/magicsq1.htm Odd Magic Squares (1728.org)]\n\n", "solution": "(() => {\n\n // magicSquare :: Int -> [[Int]]\n const magicSquare = n =>\n n % 2 !== 0 ? (\n compose([transpose, cycled, transpose, cycled, enumSquare])(n)\n ) : [];\n\n // Size of square -> rows containing integers [1..]\n // enumSquare :: Int -> [[Int]]\n const enumSquare = n =>\n chunksOf(n, enumFromTo(1, n * n));\n\n // Table of integers -> Table with rows rotated by descending deltas\n // cycled :: [[Int]] -> [[Int]]\n const cycled = rows => {\n const d = Math.floor(rows.length / 2);\n return zipWith(listCycle, enumFromTo(d, -d), rows)\n };\n\n // Number of positions to shift to right -> List -> Wrap-cycled list\n // listCycle :: Int -> [a] -> [a]\n const listCycle = (n, xs) => {\n const d = -(n % xs.length);\n return (d !== 0 ? xs.slice(d)\n .concat(xs.slice(0, d)) : xs);\n };\n\n // GENERIC FUNCTIONS ------------------------------------------------------\n\n // chunksOf :: Int -> [a] -> [[a]]\n const chunksOf = (n, xs) =>\n xs.reduce((a, _, i, xs) =>\n i % n ? a : a.concat([xs.slice(i, i + n)]), []);\n\n // compose :: [(a -> a)] -> (a -> a)\n const compose = fs => x => fs.reduceRight((a, f) => f(a), x);\n\n // enumFromTo :: Int -> Int -> Maybe Int -> [Int]\n const enumFromTo = (m, n, step) => {\n const d = (step || 1) * (n >= m ? 1 : -1);\n return Array.from({\n length: Math.floor((n - m) / d) + 1\n }, (_, i) => m + (i * d));\n };\n\n // intercalate :: String -> [a] -> String\n const intercalate = (s, xs) => xs.join(s);\n\n // min :: Ord a => a -> a -> a\n const min = (a, b) => b < a ? b : a;\n\n // show :: a -> String\n const show = JSON.stringify;\n\n // transpose :: [[a]] -> [[a]]\n const transpose = xs =>\n xs[0].map((_, iCol) => xs.map(row => row[iCol]));\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = (f, xs, ys) =>\n Array.from({\n length: min(xs.length, ys.length)\n }, (_, i) => f(xs[i], ys[i]));\n\n // TEST -------------------------------------------------------------------\n return intercalate('\\n\\n', [3, 5, 7]\n .map(magicSquare)\n .map(xs => unlines(xs.map(show))));\n})();"} +{"title": "Magic squares of odd order", "language": "Python", "task": "A magic square is an \u00a0 '''NxN''' \u00a0 square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, \u00a0 ''and'' \u00a0 both long (main) diagonals are equal to the same sum (which is called the \u00a0 ''magic number'' \u00a0 or \u00a0 ''magic constant''). \n\nThe numbers are usually (but not always) the first \u00a0 '''N'''2 \u00a0 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 \u00a0 '''N''', \u00a0 generate a magic square with the integers \u00a0 ''' 1''' \u2500\u2500\u25ba '''N''', \u00a0 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 \u00a0 '''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\u2122 entry: [http://mathworld.wolfram.com/MagicSquare.html Magic_square] \n* [http://www.1728.org/magicsq1.htm Odd Magic Squares (1728.org)]\n\n", "solution": ">>> def magic(n):\n for row in range(1, n + 1):\n print(' '.join('%*i' % (len(str(n**2)), cell) for cell in\n (n * ((row + col - 1 + n // 2) % n) +\n ((row + 2 * col - 2) % n) + 1\n for col in range(1, n + 1))))\n print('\\nAll sum to magic number %i' % ((n * n + 1) * n // 2))\n\n \n>>> for n in (5, 3, 7):\n\tprint('\\nOrder %i\\n=======' % n)\n\tmagic(n)\n\n\t\n\nOrder 5\n=======\n17 24 1 8 15\n23 5 7 14 16\n 4 6 13 20 22\n10 12 19 21 3\n11 18 25 2 9\n\nAll sum to magic number 65\n\nOrder 3\n=======\n8 1 6\n3 5 7\n4 9 2\n\nAll sum to magic number 15\n\nOrder 7\n=======\n30 39 48 1 10 19 28\n38 47 7 9 18 27 29\n46 6 8 17 26 35 37\n 5 14 16 25 34 36 45\n13 15 24 33 42 44 4\n21 23 32 41 43 3 12\n22 31 40 49 2 11 20\n\nAll sum to magic number 175\n>>> "} +{"title": "Magic squares of odd order", "language": "Python 3.7", "task": "A magic square is an \u00a0 '''NxN''' \u00a0 square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, \u00a0 ''and'' \u00a0 both long (main) diagonals are equal to the same sum (which is called the \u00a0 ''magic number'' \u00a0 or \u00a0 ''magic constant''). \n\nThe numbers are usually (but not always) the first \u00a0 '''N'''2 \u00a0 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 \u00a0 '''N''', \u00a0 generate a magic square with the integers \u00a0 ''' 1''' \u2500\u2500\u25ba '''N''', \u00a0 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 \u00a0 '''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\u2122 entry: [http://mathworld.wolfram.com/MagicSquare.html Magic_square] \n* [http://www.1728.org/magicsq1.htm Odd Magic Squares (1728.org)]\n\n", "solution": "'''Magic squares of odd order N'''\n\nfrom itertools import cycle, islice, repeat\nfrom functools import reduce\n\n\n# magicSquare :: Int -> [[Int]]\ndef magicSquare(n):\n '''Magic square of odd order n.'''\n return applyN(2)(\n compose(transposed)(cycled)\n )(plainSquare(n)) if 1 == n % 2 else []\n\n\n# plainSquare :: Int -> [[Int]]\ndef plainSquare(n):\n '''The sequence of integers from 1 to N^2,\n subdivided into N sub-lists of equal length,\n forming N rows, each of N integers.\n '''\n return chunksOf(n)(\n enumFromTo(1)(n ** 2)\n )\n\n\n# cycled :: [[Int]] -> [[Int]]\ndef cycled(rows):\n '''A table in which the rows are\n rotated by descending deltas.\n '''\n n = len(rows)\n d = n // 2\n return list(map(\n lambda d, xs: take(n)(\n drop(n - d)(cycle(xs))\n ),\n enumFromThenTo(d)(d - 1)(-d),\n rows\n ))\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Magic squares of order 3, 5, 7'''\n print(\n fTable(__doc__ + ':')(lambda x: '\\n' + repr(x))(\n showSquare\n )(magicSquare)([3, 5, 7])\n )\n\n\n# GENERIC -------------------------------------------------\n\n# applyN :: Int -> (a -> a) -> a -> a\ndef applyN(n):\n '''n applications of f.\n (Church numeral n).\n '''\n def go(f):\n return lambda x: reduce(\n lambda a, g: g(a), repeat(f, n), x\n )\n return lambda f: go(f)\n\n\n# chunksOf :: Int -> [a] -> [[a]]\ndef chunksOf(n):\n '''A series of lists of length n,\n subdividing the contents of xs.\n Where the length of xs is not evenly divible,\n the final list will be shorter than n.'''\n return lambda xs: reduce(\n lambda a, i: a + [xs[i:n + i]],\n range(0, len(xs), n), []\n ) if 0 < n else []\n\n\n# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n '''Right to left function composition.'''\n return lambda f: lambda x: g(f(x))\n\n\n# drop :: Int -> [a] -> [a]\n# drop :: Int -> String -> String\ndef drop(n):\n '''The sublist of xs beginning at\n (zero-based) index n.'''\n def go(xs):\n if isinstance(xs, (list, tuple, str)):\n return xs[n:]\n else:\n take(n)(xs)\n return xs\n return lambda xs: go(xs)\n\n\n# enumFromThenTo :: Int -> Int -> Int -> [Int]\ndef enumFromThenTo(m):\n '''Integer values enumerated from m to n\n with a step defined by nxt-m.\n '''\n def go(nxt, n):\n d = nxt - m\n return range(m, n - 1 if d < 0 else 1 + n, d)\n return lambda nxt: lambda n: list(go(nxt, n))\n\n\n# enumFromTo :: (Int, Int) -> [Int]\ndef enumFromTo(m):\n '''Integer enumeration from m to n.'''\n return lambda n: list(range(m, 1 + n))\n\n\n# take :: Int -> [a] -> [a]\n# take :: Int -> String -> String\ndef take(n):\n '''The prefix of xs of length n,\n or xs itself if n > length xs.\n '''\n return lambda xs: (\n xs[0:n]\n if isinstance(xs, (list, tuple))\n else list(islice(xs, n))\n )\n\n\n# transposed :: Matrix a -> Matrix a\ndef transposed(m):\n '''The rows and columns of the argument transposed.\n (The matrix containers and rows can be lists or tuples).\n '''\n if m:\n inner = type(m[0])\n z = zip(*m)\n return (type(m))(\n map(inner, z) if tuple != inner else z\n )\n else:\n return m\n\n\n# DISPLAY -------------------------------------------------\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\n '''\n def go(xShow, fxShow, f, xs):\n ys = [xShow(x) for x in xs]\n w = max(map(len, ys))\n return s + '\\n' + '\\n'.join(map(\n lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n xs, ys\n ))\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\n# indented :: Int -> String -> String\ndef indented(n):\n '''String indented by n multiples\n of four spaces\n '''\n return lambda s: (n * 4 * ' ') + s\n\n\n# showSquare :: [[Int]] -> String\ndef showSquare(rows):\n '''Lines representing rows of lists.'''\n w = 1 + len(str(reduce(max, map(max, rows), 0)))\n return '\\n' + '\\n'.join(\n map(\n lambda row: indented(1)(''.join(\n map(lambda x: str(x).rjust(w, ' '), row)\n )),\n rows\n )\n )\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} +{"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* [http://www.1728.org/magicsq3.htm Singly Even Magic Squares (1728.org)]\n\n", "solution": "\n #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": "Magic squares of singly even order", "language": "Python", "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* [http://www.1728.org/magicsq3.htm Singly Even Magic Squares (1728.org)]\n\n", "solution": "\nimport math\nfrom sys import stdout\n\nLOG_10 = 2.302585092994\n\n\n# build odd magic square\ndef build_oms(s):\n if s % 2 == 0:\n s += 1\n q = [[0 for j in range(s)] for i in range(s)]\n p = 1\n i = s // 2\n j = 0\n while p <= (s * s):\n q[i][j] = p\n ti = i + 1\n if ti >= s: ti = 0\n tj = j - 1\n if tj < 0: tj = s - 1\n if q[ti][tj] != 0:\n ti = i\n tj = j + 1\n i = ti\n j = tj\n p = p + 1\n\n return q, s\n\n\n# build singly even magic square\ndef build_sems(s):\n if s % 2 == 1:\n s += 1\n while s % 4 == 0:\n s += 2\n\n q = [[0 for j in range(s)] for i in range(s)]\n z = s // 2\n b = z * z\n c = 2 * b\n d = 3 * b\n o = build_oms(z)\n\n for j in range(0, z):\n for i in range(0, z):\n a = o[0][i][j]\n q[i][j] = a\n q[i + z][j + z] = a + b\n q[i + z][j] = a + c\n q[i][j + z] = a + d\n\n lc = z // 2\n rc = lc\n for j in range(0, z):\n for i in range(0, s):\n if i < lc or i > s - rc or (i == lc and j == lc):\n if not (i == 0 and j == lc):\n t = q[i][j]\n q[i][j] = q[i][j + z]\n q[i][j + z] = t\n\n return q, s\n\n\ndef format_sqr(s, l):\n for i in range(0, l - len(s)):\n s = \"0\" + s\n return s + \" \"\n\n\ndef display(q):\n s = q[1]\n print(\" - {0} x {1}\\n\".format(s, s))\n k = 1 + math.floor(math.log(s * s) / LOG_10)\n for j in range(0, s):\n for i in range(0, s):\n stdout.write(format_sqr(\"{0}\".format(q[0][i][j]), k))\n print()\n print(\"Magic sum: {0}\\n\".format(s * ((s * s) + 1) // 2))\n\n\nstdout.write(\"Singly Even Magic Square\")\ndisplay(build_sems(6))\n"} +{"title": "Map range", "language": "C", "task": "Given two ranges: \n:::* \u00a0 [a_1,a_2] \u00a0 and \n:::* \u00a0 [b_1,b_2]; \n:::* \u00a0 then a value \u00a0 s \u00a0 in range \u00a0 [a_1,a_2]\n:::* \u00a0 is linearly mapped to a value \u00a0 t \u00a0 in range \u00a0 [b_1,b_2]\n \u00a0 where: \n\n\n:::* \u00a0 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 \u00a0 [0, 10] \u00a0 to the range \u00a0 [-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": "Map range", "language": "JavaScript", "task": "Given two ranges: \n:::* \u00a0 [a_1,a_2] \u00a0 and \n:::* \u00a0 [b_1,b_2]; \n:::* \u00a0 then a value \u00a0 s \u00a0 in range \u00a0 [a_1,a_2]\n:::* \u00a0 is linearly mapped to a value \u00a0 t \u00a0 in range \u00a0 [b_1,b_2]\n \u00a0 where: \n\n\n:::* \u00a0 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 \u00a0 [0, 10] \u00a0 to the range \u00a0 [-1, 0]. \n\n\n;Extra credit:\nShow additional idiomatic ways of performing the mapping, using tools available to the language.\n\n", "solution": "// Javascript doesn't have built-in support for ranges\n// Insted we use arrays of two elements to represent ranges\nvar mapRange = function(from, to, s) {\n return to[0] + (s - from[0]) * (to[1] - to[0]) / (from[1] - from[0]);\n};\n\nvar range = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\nfor (var i = 0; i < range.length; i++) {\n range[i] = mapRange([0, 10], [-1, 0], range[i]);\n}\n\nconsole.log(range);"} +{"title": "Map range", "language": "Python", "task": "Given two ranges: \n:::* \u00a0 [a_1,a_2] \u00a0 and \n:::* \u00a0 [b_1,b_2]; \n:::* \u00a0 then a value \u00a0 s \u00a0 in range \u00a0 [a_1,a_2]\n:::* \u00a0 is linearly mapped to a value \u00a0 t \u00a0 in range \u00a0 [b_1,b_2]\n \u00a0 where: \n\n\n:::* \u00a0 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 \u00a0 [0, 10] \u00a0 to the range \u00a0 [-1, 0]. \n\n\n;Extra credit:\nShow additional idiomatic ways of performing the mapping, using tools available to the language.\n\n", "solution": ">>> def maprange( a, b, s):\n\t(a1, a2), (b1, b2) = a, b\n\treturn b1 + ((s - a1) * (b2 - b1) / (a2 - a1))\n\n>>> for s in range(11):\n\tprint(\"%2g maps to %g\" % (s, maprange( (0, 10), (-1, 0), s)))\n\n\t\n 0 maps to -1\n 1 maps to -0.9\n 2 maps to -0.8\n 3 maps to -0.7\n 4 maps to -0.6\n 5 maps to -0.5\n 6 maps to -0.4\n 7 maps to -0.3\n 8 maps to -0.2\n 9 maps to -0.1\n10 maps to 0"} +{"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/**\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": "Matrix digital rain", "language": "Microsoft Visual Studio 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*\n* Digital ASCII rain - multithreaded.\n* 2012 (C) by Author, 2020 GPL licensed for RossetaCode\n*\n*******************************************************************************/\n\n#include /* assertions */\n#include /* console operations */\n#include /* l10n and i18n */\n#include /* operations on strings and memory blocks */\n#include /* Microsoft Windows API for threads etc. */\n#include /* standard i/o library */\n#include /* standard library with rand() function */\n#include /* time(NULL) used as srand(time(NULL)) */\n#include /* just the Microsoft Windows main header for C */\n\n\n/*\n * Global variables, shared by fibers.\n */\n\nBOOL loop = TRUE; \nHANDLE hStdOut; \nCONSOLE_SCREEN_BUFFER_INFO csbi; \n\nLPVOID mainFiber = NULL;\n\nstruct WorkingFiber\n{\n int column;\n DWORD callAfter;\n unsigned seed;\n LPVOID fiber;\n} *workingFibersTable = NULL;\n\n/* \n * A function to generate random numbers from the range (a, b). \n * NOTE: POSIX rand () is not thread safe, \n * but we use secure rand() from MS runtime libraries.\n */\n\nint rnd(int a, int b)\n{\n return a + rand() % (b + 1 - a);\n}\n\nBOOL randomShow(void)\n{\n return rnd(0, 99) < 65;\n}\n\nint randomDelay(void)\n{\n return rnd(0,150) + rnd(0,150) + rnd(0,150);\n}\n\nBOOL randomRegenerate(void)\n{\n return rnd(0,99) < 2;\n}\n\n\nVOID CALLBACK one_column(void *arg)\n{\n struct WorkingFiber *ptr;\n BOOL show; \n int k;\n char c;\n WORD a;\n int delay;\n PCHAR_INFO buffer;\n COORD bufferSize, bufferCoord, newCharPosition;\n SMALL_RECT s, d;\n DWORD result;\n\n ptr = (struct WorkingFiber*)arg;\n k = ptr->column;\n ptr->callAfter = 0;\n srand(ptr->seed);\n assert(csbi.dwSize.X != 0 && csbi.dwSize.Y != 0);\n assert(0 <= k && k <= csbi.dwSize.X);\n\n show = randomShow();\n delay = randomDelay();\n\n bufferSize.X = 1;\n bufferSize.Y = csbi.dwSize.Y - 1;\n bufferCoord.X = 0;\n bufferCoord.Y = 0;\n\n buffer = (PCHAR_INFO)malloc(bufferSize.Y * sizeof(CHAR_INFO));\n assert( buffer != NULL );\n\n s.Left = k;\n s.Top = 0;\n s.Bottom = bufferSize.Y - 2;\n s.Right = k;\n\n d.Left = s.Left;\n d.Top = s.Top + 1;\n d.Right = s.Right;\n d.Bottom = s.Bottom + 1;\n\n newCharPosition.X = k;\n newCharPosition.Y = 0;\n \n while(loop)\n {\n ReadConsoleOutput ( hStdOut, buffer, bufferSize, bufferCoord, &s);\n WriteConsoleOutput( hStdOut, buffer, bufferSize, bufferCoord, &d); \n\n if(show)\n {\n c = (rnd(1,100) <= 15) ? ' ' : rnd( 'a', 'z' );\n a = FOREGROUND_GREEN | ((rnd(1,100) > 1) ? 0 : FOREGROUND_INTENSITY);\n }\n else\n {\n c = ' ';\n a = FOREGROUND_GREEN;\n }\n\n WriteConsoleOutputCharacter( hStdOut, &c, 1, newCharPosition, &result );\n WriteConsoleOutputAttribute( hStdOut, &a, 1, newCharPosition, &result );\n\n if(randomRegenerate()) show = randomShow();\n if(randomRegenerate()) delay = randomDelay();\n\n ptr->callAfter = GetTickCount() + delay;\n SwitchToFiber(mainFiber);\n }\n\n free(buffer);\n}\n\n\nint main(int argc, char* argv[])\n{\n int j;\n\n srand((unsigned int)time(NULL));\n\n hStdOut = GetStdHandle( STD_OUTPUT_HANDLE );\n SetConsoleTitle(\"MATRIX - FIBERS\");\n\n if(argc == 1)\n {\n COORD coord;\n CONSOLE_CURSOR_INFO cci;\n\n cci.bVisible = FALSE;\n cci.dwSize = 0;\n SetConsoleDisplayMode(hStdOut,CONSOLE_FULLSCREEN_MODE,&coord);\n SetConsoleCursorInfo(hStdOut,&cci);\n }\n\n GetConsoleScreenBufferInfo( hStdOut, &csbi );\n //SetConsoleTextAttribute(hStdOut,FOREGROUND_GREEN);\n\n mainFiber = ConvertThreadToFiber(NULL);\n assert( mainFiber != NULL );\n\n workingFibersTable = (struct WorkingFiber*)\n calloc(csbi.dwSize.X, sizeof(struct WorkingFiber));\n assert( workingFibersTable != NULL );\n\n for(j = 0; j < csbi.dwSize.X; j++)\n {\n workingFibersTable[j].column = j;\n workingFibersTable[j].callAfter = 0;\n workingFibersTable[j].seed = rand();\n workingFibersTable[j].fiber = CreateFiber( 0, one_column, &workingFibersTable[j] );\n }\n\n loop = TRUE;\n while(!_kbhit())\n {\n DWORD t = GetTickCount();\n for(j = 0; j < csbi.dwSize.X; j++)\n if(workingFibersTable[j].callAfter < t)\n SwitchToFiber( workingFibersTable[j].fiber );\n Sleep(1);\n }\n\n loop = FALSE;\n for(j = 0; j < csbi.dwSize.X; j++)\n {\n SwitchToFiber( workingFibersTable[j].fiber );\n DeleteFiber(workingFibersTable[j].fiber);\n }\n\n free(workingFibersTable);\n\n return 0;\n}"} +{"title": "Matrix digital rain", "language": "Python", "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": "\nimport curses\nimport random\nimport time\n\n\"\"\"\n\nBased on C ncurses version\n\nhttp://rosettacode.org/wiki/Matrix_Digital_Rain#NCURSES_version\n\n\"\"\"\n\n\"\"\"\nTime between row updates in seconds\nControls the speed of the digital rain effect.\n\"\"\"\n\nROW_DELAY=.0001\n\ndef get_rand_in_range(min, max):\n return random.randrange(min,max+1)\n\ntry:\n # Characters to randomly appear in the rain sequence.\n chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n \n total_chars = len(chars)\n \n stdscr = curses.initscr()\n curses.noecho()\n curses.curs_set(False)\n \n curses.start_color()\n curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)\n stdscr.attron(curses.color_pair(1))\n \n max_x = curses.COLS - 1\n max_y = curses.LINES - 1\n \n \n # Create arrays of columns based on screen width.\n \n # Array containing the current row of each column.\n \n columns_row = []\n \n # Array containing the active status of each column.\n # A column draws characters on a row when active.\n \n columns_active = []\n \n for i in range(max_x+1):\n columns_row.append(-1)\n columns_active.append(0)\n \n while(True):\n for i in range(max_x):\n if columns_row[i] == -1:\n # If a column is at the top row, pick a\n # random starting row and active status.\n columns_row[i] = get_rand_in_range(0, max_y)\n columns_active[i] = get_rand_in_range(0, 1)\n \n # Loop through columns and draw characters on rows\n \n for i in range(max_x):\n if columns_active[i] == 1:\n # Draw a random character at this column's current row.\n char_index = get_rand_in_range(0, total_chars-1)\n #mvprintw(columns_row[i], i, \"%c\", chars[char_index]) \n stdscr.addstr(columns_row[i], i, chars[char_index])\n else:\n # Draw an empty character if the column is inactive.\n #mvprintw(columns_row[i], i, \" \");\n stdscr.addstr(columns_row[i], i, \" \");\n \n \n columns_row[i]+=1\n \n # When a column reaches the bottom row, reset to top.\n if columns_row[i] >= max_y:\n columns_row[i] = -1\n \n # Randomly alternate the column's active status.\n if get_rand_in_range(0, 1000) == 0:\n if columns_active[i] == 0: \n columns_active[i] = 1\n else:\n columns_active[i] = 0\n \n time.sleep(ROW_DELAY)\n stdscr.refresh()\n \nexcept KeyboardInterrupt as err:\n curses.endwin() \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 [http://projecteuler.net/problem=18 Euler Problem #18].\n\n", "solution": "\n#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": "Maximum triangle path sum", "language": "Python", "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 [http://projecteuler.net/problem=18 Euler Problem #18].\n\n", "solution": "def solve(tri):\n while len(tri) > 1:\n t0 = tri.pop()\n t1 = tri.pop()\n tri.append([max(t0[i], t0[i+1]) + t for i,t in enumerate(t1)])\n return tri[0][0]\n\n\ndata = \"\"\" 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\nprint solve([map(int, row.split()) for row in data.splitlines()])"} +{"title": "Mayan calendar", "language": "Python 3.6", "task": "The ancient Maya people had two somewhat distinct calendar systems.\n\nIn somewhat simplified terms, one is a cyclical calendar known as '''The Calendar Round''',\nthat meshes several sacred and civil cycles; the other is an offset calendar\nknown as '''The Long Count''', similar in many ways to the Gregorian calendar.\n\n'''The Calendar Round'''\n\n'''The Calendar Round''' has several intermeshing sacred and civil cycles that uniquely identify a specific date in an approximately 52 year cycle.\n\n'''The Tzolk\u2019in'''\n\nThe sacred cycle in the Mayan calendar round was called the '''Tzolk\u2019in'''. The '''Tzolk'in''' has a cycle of 20 day names:\n\n Imix\u2019\n Ik\u2019\n Ak\u2019bal\n K\u2019an\n Chikchan\n Kimi\n Manik\u2019\n Lamat\n Muluk\n Ok\n Chuwen\n Eb\n Ben\n Hix\n Men\n K\u2019ib\u2019\n Kaban\n Etz\u2019nab\u2019\n Kawak\n Ajaw\n\nIntermeshed with the named days, the '''Tzolk\u2019in''' has a cycle of 13 numbered days; 1\nthrough 13. Every day has both a number and a name that repeat in a 260 day cycle.\n\nFor example:\n\n 1 Imix\u2019\n 2 Ik\u2019\n 3 Ak\u2019bal\n ...\n 11 Chuwen\n 12 Eb\n 13 Ben\n 1 Hix\n 2 Men\n 3 K\u2019ib\u2019\n ... and so on.\n\n'''The Haab\u2019'''\n\nThe Mayan civil calendar is called the '''Haab\u2019'''. This calendar has 365 days per\nyear, and is sometimes called the \u2018vague year.\u2019 It is substantially the same as\nour year, but does not make leap year adjustments, so over long periods of time,\ngets out of synchronization with the seasons. It consists of 18 months with 20 days each, \nand the end of the year, a special month of only 5 days, giving a total of 365. \nThe 5 days of the month of '''Wayeb\u2019''' (the last month), are usually considered to be \na time of bad luck.\n\nEach month in the '''Haab\u2019''' has a name. The Mayan names for the civil months are:\n\n Pop\n Wo\u2019\n Sip\n Sotz\u2019\n Sek\n Xul\n Yaxk\u2019in\n Mol\n Ch\u2019en\n Yax\n Sak\u2019\n Keh\n Mak\n K\u2019ank\u2019in\n Muwan\n Pax\n K\u2019ayab\n Kumk\u2019u\n Wayeb\u2019 (Short, \"unlucky\" month)\n\nThe months function very much like ours do. That is, for any given month we\ncount through all the days of that month, and then move on to the next month.\n\nNormally, the day '''1 Pop''' is considered the first day of the civil year, just as '''1 January''' \nis the first day of our year. In 2019, '''1 Pop''' falls on '''April 2nd'''. But,\nbecause of the leap year in 2020, '''1 Pop''' falls on '''April 1st''' in the years 2020-2023.\n\nThe only really unusual aspect of the '''Haab\u2019''' calendar is that, although there are\n20 (or 5) days in each month, the last day of the month is not called\nthe 20th (5th). Instead, the last day of the month is referred to as the\n\u2018seating,\u2019 or \u2018putting in place,\u2019 of the next month. (Much like how in our\nculture, December 24th is Christmas Eve and December 31st is 'New-Years Eve'.) In\nthe language of the ancient Maya, the word for seating was '''chum''', So you might\nhave:\n\n ...\n 18 Pop (18th day of the first month)\n 19 Pop (19th day of the first month)\n Chum Wo\u2019 (20th day of the first month)\n 1 Wo\u2019 (1st day of the second month)\n ... and so on.\n\nDates for any particular day are a combination of the '''Tzolk\u2019in''' sacred date,\nand '''Haab\u2019''' civil date. When put together we get the '''\u201cCalendar Round.\u201d'''\n\n'''Calendar Round''' dates always have two numbers and two names, and they are\nalways written in the same order:\n\n (1) the day number in the '''Tzolk\u2019in'''\n (2) the day name in the '''Tzolk\u2019in'''\n (3) the day of the month in the '''Haab\u2019'''\n (4) the month name in the '''Haab\u2019'''\n\nA calendar round is a repeating cycle with a period of just short of 52\nGregorian calendar years. To be precise: it is 52 x 365 days. (No leap days)\n\n'''Lords of the Night'''\n\nA third cycle of nine days honored the nine '''Lords of the Night'''; nine deities\nthat were associated with each day in turn. The names of the nine deities are\nlost; they are now commonly referred to as '''G1''' through '''G9'''. The Lord of the Night\nmay or may not be included in a Mayan date, if it is, it is typically\njust the appropriate '''G(''x'')''' at the end.\n\n'''The Long Count'''\n\nMayans had a separate independent way of measuring time that did not run in\ncycles. (At least, not on normal human scales.) Instead, much like our yearly\ncalendar, each day just gets a little further from the starting point. For the\nancient Maya, the starting point was the \u2018creation date\u2019 of the current world.\nThis date corresponds to our date of August 11, 3114 B.C. Dates are calculated\nby measuring how many days have transpired since this starting date; This is\ncalled '''\u201cThe Long Count.\u201d''' Rather than just an absolute count of days, the long\ncount is broken up into unit blocks, much like our calendar has months, years,\ndecades and centuries.\n\n The basic unit is a '''k\u2019in''' - one day.\n A 20 day month is a '''winal'''.\n 18 '''winal''' (360 days) is a '''tun''' - sometimes referred to as a short year.\n 20 short years ('''tun''') is a '''k\u2019atun'''\n 20 '''k\u2019atun''' is a '''bak\u2019tun'''\n\nThere are longer units too:\n\n '''Piktun''' == 20 '''Bak\u2019tun''' (8,000 short years)\n '''Kalabtun''' == 20 '''Piktun''' (160,000 short years)\n '''Kinchiltun''' == 20 '''Kalabtun''' (3,200,000 short years)\n\nFor the most part, the Maya only used the blocks of time up to the '''bak\u2019tun'''. One\n'''bak\u2019tun''' is around 394 years, much more than a human life span, so that was all\nthey usually needed to describe dates in this era, or this world. It is worth\nnoting, the two calendars working together allow much more accurate and reliable\nnotation for dates than is available in many other calendar systems; mostly due\nto the pragmatic choice to make the calendar simply track days, rather than\ntrying to make it align with seasons and/or try to conflate it with the notion\nof time.\n\n'''Mayan Date correlations'''\n\nThere is some controversy over finding a correlation point between the Gregorian\nand Mayan calendars. The Gregorian calendar is full of jumps and skips to keep\nthe calendar aligned with the seasons so is much more difficult to work with.\nThe most commonly used correlation\nfactor is The '''GMT: 584283'''. Julian 584283 is a day count corresponding '''Mon, Aug 11, 3114 BCE''' \nin the Gregorian calendar, and the final day in the last Mayan long count\ncycle: 13.0.0.0.0 which is referred to as \"the day of creation\" in the Mayan\ncalendar. There is nothing in known Mayan writing or history that suggests that\na long count \"cycle\" resets ''every'' 13 '''bak\u2019tun'''. Judging by their other practices,\nit would make much more sense for it to reset at 20, if at all.\n\nThe reason there was much interest at all, outside historical scholars, in\nthe Mayan calendar is that the long count recently (relatively speaking) rolled over to 13.0.0.0.0 (the same as the historic day of creation Long Count date) on Fri,\nDec 21, 2012 (using the most common GMT correlation factor), prompting conspiracy\ntheorists to predict a cataclysmic \"end-of-the-world\" scenario.\n\n'''Excerpts taken from, and recommended reading:'''\n\n*''From the website of the Foundation for the Advancement of Meso-America Studies, Inc.'' Pitts, Mark. The complete Writing in Maya Glyphs Book 2 \u2013 Maya Numbers and the Maya Calendar. 2009. Accessed 2019-01-19. http://www.famsi.org/research/pitts/MayaGlyphsBook2.pdf\n\n*wikipedia: Maya calendar\n\n*wikipedia: Mesoamerican Long Count calendar\n\n\n'''The Task:'''\n\nWrite a reusable routine that takes a Gregorian date and returns the equivalent date in Mayan in the Calendar Round and the Long Count. At a minimum, use the GMT correlation. ''If desired, support other correlations.''\n\nUsing the GMT correlation, the following Gregorian and Mayan dates are equivalent: \n\n '''Dec 21, 2012''' (Gregorian)\n '''4 Ajaw 3 K\u2019ank\u2019in G9''' (Calendar round)\n '''13.0.0.0.0''' (Long count)\n\nSupport looking up dates for at least 50 years before and after the Mayan Long Count '''13 bak\u2019tun''' rollover: ''Dec 21, 2012''. ''(Will require taking into account Gregorian leap days.)''\n\nShow the output here, on this page, for ''at least'' the following dates:\n\n''(Note that these are in ISO-8601 format: YYYY-MM-DD. There is no requirement to use ISO-8601 format in your program, but if you differ, make a note of the expected format.)''\n\n 2004-06-19\n 2012-12-18\n 2012-12-21\n 2019-01-19\n 2019-03-27\n 2020-02-29\n 2020-03-01\n", "solution": "\nimport datetime\n\n\ndef g2m(date, gtm_correlation=True):\n \"\"\"\n Translates Gregorian date into Mayan date, see\n https://rosettacode.org/wiki/Mayan_calendar\n\n Input arguments:\n\n date: string date in ISO-8601 format: YYYY-MM-DD\n gtm_correlation: GTM correlation to apply if True, Astronomical correlation otherwise (optional, True by default)\n\n Output arguments:\n\n long_date: Mayan date in Long Count system as string\n round_date: Mayan date in Calendar Round system as string\n \"\"\"\n\n # define some parameters and names\n\n correlation = 584283 if gtm_correlation else 584285\n\n long_count_days = [144000, 7200, 360, 20, 1]\n\n tzolkin_months = ['Imix\u2019', 'Ik\u2019', 'Ak\u2019bal', 'K\u2019an', 'Chikchan', 'Kimi', 'Manik\u2019', 'Lamat', 'Muluk', 'Ok', 'Chuwen',\n 'Eb', 'Ben', 'Hix', 'Men', 'K\u2019ib\u2019', 'Kaban', 'Etz\u2019nab\u2019', 'Kawak', 'Ajaw'] # tzolk'in\n\n haad_months = ['Pop', 'Wo\u2019', 'Sip', 'Sotz\u2019', 'Sek', 'Xul', 'Yaxk\u2019in', 'Mol', 'Ch\u2019en', 'Yax', 'Sak\u2019', 'Keh', 'Mak',\n 'K\u2019ank\u2019in', 'Muwan', 'Pax', 'K\u2019ayab', 'Kumk\u2019u', 'Wayeb\u2019'] # haab'\n\n gregorian_days = datetime.datetime.strptime(date, '%Y-%m-%d').toordinal()\n julian_days = gregorian_days + 1721425\n\n # 1. calculate long count date\n\n long_date = list()\n remainder = julian_days - correlation\n\n for days in long_count_days:\n\n result, remainder = divmod(remainder, days)\n long_date.append(int(result))\n\n long_date = '.'.join(['{:02d}'.format(d) for d in long_date])\n\n # 2. calculate round calendar date\n\n tzolkin_month = (julian_days + 16) % 20\n tzolkin_day = ((julian_days + 5) % 13) + 1\n\n haab_month = int(((julian_days + 65) % 365) / 20)\n haab_day = ((julian_days + 65) % 365) % 20\n haab_day = haab_day if haab_day else 'Chum'\n\n lord_number = (julian_days - correlation) % 9\n lord_number = lord_number if lord_number else 9\n\n round_date = f'{tzolkin_day} {tzolkin_months[tzolkin_month]} {haab_day} {haad_months[haab_month]} G{lord_number}'\n\n return long_date, round_date\n\nif __name__ == '__main__':\n\n dates = ['2004-06-19', '2012-12-18', '2012-12-21', '2019-01-19', '2019-03-27', '2020-02-29', '2020-03-01']\n\n for date in dates:\n\n long, round = g2m(date)\n print(date, long, round)\n"} +{"title": "McNuggets problem", "language": "C", "task": "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": "McNuggets problem", "language": "JavaScript", "task": "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": "(() => {\n 'use strict';\n\n // main :: IO ()\n const main = () => {\n const\n size = n => enumFromTo(0)(\n quot(100, n)\n ),\n nuggets = new Set(\n size(6).flatMap(\n x => size(9).flatMap(\n y => size(20).flatMap(\n z => {\n const v = sum([6 * x, 9 * y, 20 * z]);\n return 101 > v ? (\n [v]\n ) : [];\n }\n ),\n )\n )\n ),\n xs = dropWhile(\n x => nuggets.has(x),\n enumFromThenTo(100, 99, 1)\n );\n\n return 0 < xs.length ? (\n xs[0]\n ) : 'No unreachable quantities found in this range';\n };\n\n\n // GENERIC FUNCTIONS ----------------------------------\n\n // dropWhile :: (a -> Bool) -> [a] -> [a]\n const dropWhile = (p, xs) => {\n const lng = xs.length;\n return 0 < lng ? xs.slice(\n until(\n i => i === lng || !p(xs[i]),\n i => 1 + i,\n 0\n )\n ) : [];\n };\n\n // enumFromThenTo :: Int -> Int -> Int -> [Int]\n const enumFromThenTo = (x1, x2, y) => {\n const d = x2 - x1;\n return Array.from({\n length: Math.floor(y - x2) / d + 2\n }, (_, i) => x1 + (d * i));\n };\n\n // ft :: Int -> Int -> [Int]\n const enumFromTo = m => n =>\n Array.from({\n length: 1 + n - m\n }, (_, i) => m + i);\n\n // quot :: Int -> Int -> Int\n const quot = (n, m) => Math.floor(n / m);\n\n // sum :: [Num] -> Num\n const sum = xs => xs.reduce((a, x) => a + x, 0);\n\n // until :: (a -> Bool) -> (a -> a) -> a -> a\n const until = (p, f, x) => {\n let v = x;\n while (!p(v)) v = f(v);\n return v;\n };\n\n // MAIN ---\n return console.log(\n main()\n );\n})();"} +{"title": "McNuggets problem", "language": "Python", "task": "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": "\n#Wherein I observe that Set Comprehension is not intrinsically dysfunctional. Nigel Galloway: October 28th., 2018\nn = {n for x in range(0,101,20) for y in range(x,101,9) for n in range(y,101,6)}\ng = {n for n in range(101)}\nprint(max(g.difference(n)))\n"} +{"title": "Meissel\u2013Mertens constant", "language": "Python", "task": ";Task:\nCalculate Meissel\u2013Mertens constant up to a precision your language can handle.\n\n\n;Motivation:\nAnalogous to Euler's constant, which is important in determining the sum of reciprocal natural numbers, Meissel-Mertens' constant is important in calculating the sum of reciprocal primes.\n\n\n;Example:\nWe consider the finite sum of reciprocal natural numbers:\n\n''1 + 1/2 + 1/3 + 1/4 + 1/5 ... 1/n''\n\nthis sum can be well approximated with:\n\n''log(n) + E'' \n\nwhere ''E'' denotes Euler's constant: 0.57721...\n \n''log(n)'' denotes the natural logarithm of ''n''.\n\n\nNow consider the finite sum of reciprocal primes:\n\n''1/2 + 1/3 + 1/5 + 1/7 + 1/11 ... 1/p''\n\nthis sum can be well approximated with:\n\n''log( log(p) ) + M''\n\nwhere ''M'' denotes Meissel-Mertens constant: 0.26149...\n\n\n;See:\n:* \u00a0 Details in the Wikipedia article: \u00a0[https://en.wikipedia.org/wiki/Meissel%E2%80%93Mertens_constant Meissel\u2013Mertens constant]\n\n", "solution": "#!/usr/bin/python\n\nfrom math import log\n\ndef isPrime(n):\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n return False \n return True\n\n\nif __name__ == '__main__':\n Euler = 0.57721566490153286\n m = 0\n for x in range(2, 10_000_000):\n if isPrime(x):\n m += log(1-(1/x)) + (1/x)\n\n print(\"MM =\", Euler + m)"} +{"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": "Memory layout of a data structure", "language": "Python", "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": "from ctypes import Structure, c_int\n\nrs232_9pin = \"_0 CD RD TD DTR SG DSR RTS CTS RI\".split()\nrs232_25pin = ( \"_0 PG TD RD RTS CTS DSR SG CD pos neg\"\n \"_11 SCD SCS STD TC SRD RC\"\n \"_18 SRS DTR SQD RI DRS XTC\" ).split()\n\nclass RS232_9pin(Structure):\n _fields_ = [(__, c_int, 1) for __ in rs232_9pin]\n\n\t\nclass RS232_25pin(Structure):\n _fields_ = [(__, c_int, 1) for __ in rs232_25pin]"} +{"title": "Metallic ratios", "language": "Python", "task": "Many people have heard of the '''Golden ratio''', phi ('''\u03c6'''). Phi is just one of a series\nof related ratios that are referred to as the \"'''Metallic ratios'''\".\n\nThe '''Golden ratio''' was discovered and named by ancient civilizations as it was\nthought to be the most pure and beautiful (like Gold). The '''Silver ratio''' was was\nalso known to the early Greeks, though was not named so until later as a nod to\nthe '''Golden ratio''' to which it is closely related. The series has been extended to\nencompass all of the related ratios and was given the general name '''Metallic ratios''' (or ''Metallic means'').\n''Somewhat incongruously as the original Golden ratio referred to the adjective \"golden\" rather than the metal \"gold\".''\n\n'''Metallic ratios''' are the real roots of the general form equation:\n\n x2 - bx - 1 = 0 \n\nwhere the integer '''b''' determines which specific one it is.\n\nUsing the quadratic equation:\n\n ( -b \u00b1 \u221a(b2 - 4ac) ) / 2a = x \n\nSubstitute in (from the top equation) '''1''' for '''a''', '''-1''' for '''c''', and recognising that -b is negated we get:\n\n ( b \u00b1 \u221a(b2 + 4) ) ) / 2 = x \n\nWe only want the real root:\n\n ( b + \u221a(b2 + 4) ) ) / 2 = x \n\nWhen we set '''b''' to '''1''', we get an irrational number: the '''Golden ratio'''.\n\n ( 1 + \u221a(12 + 4) ) / 2 = (1 + \u221a5) / 2 = ~1.618033989... \n\nWith '''b''' set to '''2''', we get a different irrational number: the '''Silver ratio'''.\n\n ( 2 + \u221a(22 + 4) ) / 2 = (2 + \u221a8) / 2 = ~2.414213562... \n\nWhen the ratio '''b''' is '''3''', it is commonly referred to as the '''Bronze''' ratio, '''4''' and '''5'''\nare sometimes called the '''Copper''' and '''Nickel''' ratios, though they aren't as\nstandard. After that there isn't really any attempt at standardized names. They\nare given names here on this page, but consider the names fanciful rather than\ncanonical.\n\nNote that technically, '''b''' can be '''0''' for a \"smaller\" ratio than the '''Golden ratio'''.\nWe will refer to it here as the '''Platinum ratio''', though it is kind-of a\ndegenerate case.\n\n'''Metallic ratios''' where '''b''' > '''0''' are also defined by the irrational continued fractions:\n\n [b;b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b...] \n\n\nSo, The first ten '''Metallic ratios''' are:\n\n:::::: {| class=\"wikitable\" style=\"text-align: center;\"\n|+ Metallic ratios\n!Name!!'''b'''!!Equation!!Value!!Continued fraction!!OEIS link\n|-\n|Platinum||0||(0 + \u221a4) / 2|| 1||-||-\n|-\n|Golden||1||(1 + \u221a5) / 2|| 1.618033988749895...||[1;1,1,1,1,1,1,1,1,1,1...]||[[OEIS:A001622]]\n|-\n|Silver||2||(2 + \u221a8) / 2|| 2.414213562373095...||[2;2,2,2,2,2,2,2,2,2,2...]||[[OEIS:A014176]]\n|-\n|Bronze||3||(3 + \u221a13) / 2|| 3.302775637731995...||[3;3,3,3,3,3,3,3,3,3,3...]||[[OEIS:A098316]]\n|-\n|Copper||4||(4 + \u221a20) / 2|| 4.23606797749979...||[4;4,4,4,4,4,4,4,4,4,4...]||[[OEIS:A098317]]\n|-\n|Nickel||5||(5 + \u221a29) / 2|| 5.192582403567252...||[5;5,5,5,5,5,5,5,5,5,5...]||[[OEIS:A098318]]\n|-\n|Aluminum||6||(6 + \u221a40) / 2|| 6.16227766016838...||[6;6,6,6,6,6,6,6,6,6,6...]||[[OEIS:A176398]]\n|-\n|Iron||7||(7 + \u221a53) / 2|| 7.140054944640259...||[7;7,7,7,7,7,7,7,7,7,7...]||[[OEIS:A176439]]\n|-\n|Tin||8||(8 + \u221a68) / 2|| 8.123105625617661...||[8;8,8,8,8,8,8,8,8,8,8...]||[[OEIS:A176458]]\n|-\n|Lead||9||(9 + \u221a85) / 2|| 9.109772228646444...||[9;9,9,9,9,9,9,9,9,9,9...]||[[OEIS:A176522]]\n|}\n\n\n\n\nThere are other ways to find the '''Metallic ratios'''; one, (the focus of this task)\nis through '''successive approximations of Lucas sequences'''.\n\nA traditional '''Lucas sequence''' is of the form:\n\n x''n'' = P * x''n-1'' - Q * x''n-2''\n\nand starts with the first 2 values '''0, 1'''. \n\nFor our purposes in this task, to find the metallic ratios we'll use the form:\n\n x''n'' = b * x''n-1'' + x''n-2''\n\n( '''P''' is set to '''b''' and '''Q''' is set to '''-1'''. ) To avoid \"divide by zero\" issues we'll start the sequence with the first two terms '''1, 1'''. The initial starting value has very little effect on the final ratio or convergence rate. ''Perhaps it would be more accurate to call it a Lucas-like sequence.'' \n\nAt any rate, when '''b = 1''' we get:\n\n x''n'' = x''n-1'' + x''n-2''\n\n 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144...\n\nmore commonly known as the Fibonacci sequence.\n\nWhen '''b = 2''':\n\n x''n'' = 2 * x''n-1'' + x''n-2''\n\n 1, 1, 3, 7, 17, 41, 99, 239, 577, 1393...\n\n\nAnd so on.\n\n\nTo find the ratio by successive approximations, divide the ('''n+1''')th term by the\n'''n'''th. As '''n''' grows larger, the ratio will approach the '''b''' metallic ratio.\n\nFor '''b = 1''' (Fibonacci sequence):\n\n 1/1 = 1\n 2/1 = 2\n 3/2 = 1.5\n 5/3 = 1.666667\n 8/5 = 1.6\n 13/8 = 1.625\n 21/13 = 1.615385\n 34/21 = 1.619048\n 55/34 = 1.617647\n 89/55 = 1.618182\n etc.\n\nIt converges, but pretty slowly. In fact, the '''Golden ratio''' has the slowest\npossible convergence for any irrational number.\n\n\n;Task\n\nFor each of the first '''10 Metallic ratios'''; '''b''' = '''0''' through '''9''':\n\n* Generate the corresponding \"Lucas\" sequence.\n* Show here, on this page, at least the first '''15''' elements of the \"Lucas\" sequence.\n* Using successive approximations, calculate the value of the ratio accurate to '''32''' decimal places.\n* Show the '''value''' of the '''approximation''' at the required accuracy.\n* Show the '''value''' of '''n''' when the approximation reaches the required accuracy (How many iterations did it take?).\n\nOptional, stretch goal - Show the '''value''' and number of iterations '''n''', to approximate the '''Golden ratio''' to '''256''' decimal places.\n\nYou may assume that the approximation has been reached when the next iteration does not cause the value (to the desired places) to change.\n\n;See also\n* Wikipedia: Metallic mean\n* Wikipedia: Lucas sequence\n\n", "solution": "from itertools import count, islice\nfrom _pydecimal import getcontext, Decimal\n\ndef metallic_ratio(b):\n m, n = 1, 1\n while True:\n yield m, n\n m, n = m*b + n, m\n\ndef stable(b, prec):\n def to_decimal(b):\n for m,n in metallic_ratio(b):\n yield Decimal(m)/Decimal(n)\n\n getcontext().prec = prec\n last = 0\n for i,x in zip(count(), to_decimal(b)):\n if x == last:\n print(f'after {i} iterations:\\n\\t{x}')\n break\n last = x\n\nfor b in range(4):\n coefs = [n for _,n in islice(metallic_ratio(b), 15)]\n print(f'\\nb = {b}: {coefs}')\n stable(b, 32)\n\nprint(f'\\nb = 1 with 256 digits:')\nstable(1, 256)"} +{"title": "Metaprogramming", "language": "C", "task": "Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. \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": "\n#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": "Metaprogramming", "language": "Python", "task": "Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. \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": "\nMetaprogramming is frowned on in Python and considered un-pythonic. The only widely known example of metaprogramming in Python was an implementation of a goto (and comefrom) keyword done as an [http://entrian.com/goto/ April-fools joke].\n\nAnother more recent library that shows it can be done in Python is [https://github.com/lihaoyi/macropy MacroPy].\n\n"} +{"title": "Metaprogramming", "language": "https://github.com/lihaoyi/macropy MacroPy", "task": "Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. \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": "\nfrom macropy.core.macros import *\nfrom macropy.core.quotes import macros, q, ast, u\n\nmacros = Macros()\n\n@macros.expr\ndef expand(tree, **kw):\n addition = 10\n return q[lambda x: x * ast[tree] + u[addition]]\n"} +{"title": "Metronome", "language": "C", "task": "right\n\nThe task is to implement a \u00a0 [https://en.wikipedia.org/wiki/Metronomemetronome 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": "Metronome", "language": "Python", "task": "right\n\nThe task is to implement a \u00a0 [https://en.wikipedia.org/wiki/Metronomemetronome 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": "\n#lang Python\nimport time\n\ndef main(bpm = 72, bpb = 4):\n sleep = 60.0 / bpm\n counter = 0\n while True:\n counter += 1\n if counter % bpb:\n print 'tick'\n else:\n print 'TICK'\n time.sleep(sleep)\n \n\n\nmain()\n\n"} +{"title": "Mian-Chowla sequence", "language": "C", "task": "The Mian\u2013Chowla sequence is an integer sequence defined recursively.\n\n\nMian\u2013Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B\u2082 sequences.\n\n\nThe sequence starts with:\n\n::a1 = 1\n\nthen for n > 1, an is the smallest positive integer such that every pairwise sum\n\n::ai + aj \n\nis distinct, for all i and j less than or equal to n.\n\n;The Task:\n\n:* Find and display, here, on this page the first 30 terms of the Mian\u2013Chowla sequence.\n:* Find and display, here, on this page the 91st through 100th terms of the Mian\u2013Chowla sequence.\n\n\nDemonstrating working through the first few terms longhand:\n\n::a1 = 1\n\n::1 + 1 = 2\n\nSpeculatively try a2 = 2\n\n::1 + 1 = 2\n::1 + 2 = 3\n::2 + 2 = 4\n\nThere are no repeated sums so '''2''' is the next number in the sequence.\n\nSpeculatively try a3 = 3\n\n::1 + 1 = 2\n::1 + 2 = 3 \n::1 + 3 = 4\n::2 + 2 = 4\n::2 + 3 = 5\n::3 + 3 = 6\n\nSum of '''4''' is repeated so '''3''' is rejected.\n\nSpeculatively try a3 = 4\n\n::1 + 1 = 2\n::1 + 2 = 3\n::1 + 4 = 5\n::2 + 2 = 4\n::2 + 4 = 6\n::4 + 4 = 8\n\nThere are no repeated sums so '''4''' is the next number in the sequence.\n\nAnd so on...\n\n;See also:\n\n:* OEIS:A005282 Mian-Chowla sequence\n\n", "solution": "#include \n#include \n#include \n \n#define n 100\n#define nn ((n * (n + 1)) >> 1)\n\nbool Contains(int lst[], int item, int size) {\n\tfor (int i = size - 1; i >= 0; i--)\n \t\tif (item == lst[i]) return true;\n\treturn false;\n}\n \nint * MianChowla()\n{\n\tstatic int mc[n]; mc[0] = 1;\n\tint sums[nn];\tsums[0] = 2;\n\tint sum, le, ss = 1;\n\tfor (int i = 1; i < n; i++) {\n\t\tle = ss;\n\t\tfor (int j = mc[i - 1] + 1; ; j++) {\n\t\t\tmc[i] = j;\n\t\t\tfor (int k = 0; k <= i; k++) {\n\t\t\t\tsum = mc[k] + j;\n\t\t\t\tif (Contains(sums, sum, ss)) {\n\t\t\t\t\tss = le; goto nxtJ;\n\t\t\t\t}\n\t\t\t\tsums[ss++] = sum;\n\t\t\t}\n\t\t\tbreak;\n\t\tnxtJ:;\n\t\t}\n\t}\n\treturn mc;\n}\n \nint main() {\n\tclock_t st = clock(); int * mc; mc = MianChowla();\n double et = ((double)(clock() - st)) / CLOCKS_PER_SEC;\n\tprintf(\"The first 30 terms of the Mian-Chowla sequence are:\\n\");\n\tfor (int i = 0; i < 30; i++) printf(\"%d \", mc[i]);\n\tprintf(\"\\n\\nTerms 91 to 100 of the Mian-Chowla sequence are:\\n\");\n\tfor (int i = 90; i < 100; i++) printf(\"%d \", mc[i]); \n\tprintf(\"\\n\\nComputation time was %f seconds.\", et);\n}"} +{"title": "Mian-Chowla sequence", "language": "JavaScript", "task": "The Mian\u2013Chowla sequence is an integer sequence defined recursively.\n\n\nMian\u2013Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B\u2082 sequences.\n\n\nThe sequence starts with:\n\n::a1 = 1\n\nthen for n > 1, an is the smallest positive integer such that every pairwise sum\n\n::ai + aj \n\nis distinct, for all i and j less than or equal to n.\n\n;The Task:\n\n:* Find and display, here, on this page the first 30 terms of the Mian\u2013Chowla sequence.\n:* Find and display, here, on this page the 91st through 100th terms of the Mian\u2013Chowla sequence.\n\n\nDemonstrating working through the first few terms longhand:\n\n::a1 = 1\n\n::1 + 1 = 2\n\nSpeculatively try a2 = 2\n\n::1 + 1 = 2\n::1 + 2 = 3\n::2 + 2 = 4\n\nThere are no repeated sums so '''2''' is the next number in the sequence.\n\nSpeculatively try a3 = 3\n\n::1 + 1 = 2\n::1 + 2 = 3 \n::1 + 3 = 4\n::2 + 2 = 4\n::2 + 3 = 5\n::3 + 3 = 6\n\nSum of '''4''' is repeated so '''3''' is rejected.\n\nSpeculatively try a3 = 4\n\n::1 + 1 = 2\n::1 + 2 = 3\n::1 + 4 = 5\n::2 + 2 = 4\n::2 + 4 = 6\n::4 + 4 = 8\n\nThere are no repeated sums so '''4''' is the next number in the sequence.\n\nAnd so on...\n\n;See also:\n\n:* OEIS:A005282 Mian-Chowla sequence\n\n", "solution": "(() => {\n 'use strict';\n\n // main :: IO ()\n const main = () => {\n const genMianChowla = mianChowlas();\n console.log([\n 'Mian-Chowla terms 1-30:',\n take(30)(\n genMianChowla\n ),\n\n '\\nMian-Chowla terms 91-100:',\n (\n drop(60)(genMianChowla),\n take(10)(\n genMianChowla\n )\n )\n ].join('\\n') + '\\n');\n };\n\n // mianChowlas :: Gen [Int]\n function* mianChowlas() {\n let\n mcs = [1],\n sumSet = new Set([2]),\n x = 1;\n while (true) {\n yield x;\n [sumSet, mcs, x] = nextMC(sumSet, mcs, x);\n }\n }\n\n // nextMC :: Set Int -> [Int] -> Int -> (Set Int, [Int], Int)\n const nextMC = (setSums, mcs, n) => {\n // Set of sums -> Series up to n -> Next term in series\n const valid = x => {\n for (const m of mcs) {\n if (setSums.has(x + m)) return false;\n }\n return true;\n };\n const x = until(valid)(x => 1 + x)(n);\n return [\n sumList(mcs)(x)\n .reduce(\n (a, n) => (a.add(n), a),\n setSums\n ),\n mcs.concat(x),\n x\n ];\n };\n\n // sumList :: [Int] -> Int -> [Int]\n const sumList = xs =>\n // Series so far -> additional term -> new sums\n n => [2 * n].concat(xs.map(x => n + x));\n\n\n // ---------------- GENERIC FUNCTIONS ----------------\n\n // drop :: Int -> [a] -> [a]\n // drop :: Int -> Generator [a] -> Generator [a]\n // drop :: Int -> String -> String\n const drop = n =>\n xs => Infinity > length(xs) ? (\n xs.slice(n)\n ) : (take(n)(xs), xs);\n\n\n // length :: [a] -> Int\n const length = xs =>\n // Returns Infinity over objects without finite\n // length. This enables zip and zipWith to choose\n // the shorter argument when one is non-finite,\n // like cycle, repeat etc\n 'GeneratorFunction' !== xs.constructor\n .constructor.name ? (\n xs.length\n ) : Infinity;\n\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n =>\n // The first n elements of a list,\n // string of characters, or stream.\n xs => 'GeneratorFunction' !== xs\n .constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n\n // until :: (a -> Bool) -> (a -> a) -> a -> a\n const until = p =>\n f => x => {\n let v = x;\n while (!p(v)) v = f(v);\n return v;\n };\n\n // MAIN ---\n return main();\n})();"} +{"title": "Mian-Chowla sequence", "language": "Python", "task": "The Mian\u2013Chowla sequence is an integer sequence defined recursively.\n\n\nMian\u2013Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B\u2082 sequences.\n\n\nThe sequence starts with:\n\n::a1 = 1\n\nthen for n > 1, an is the smallest positive integer such that every pairwise sum\n\n::ai + aj \n\nis distinct, for all i and j less than or equal to n.\n\n;The Task:\n\n:* Find and display, here, on this page the first 30 terms of the Mian\u2013Chowla sequence.\n:* Find and display, here, on this page the 91st through 100th terms of the Mian\u2013Chowla sequence.\n\n\nDemonstrating working through the first few terms longhand:\n\n::a1 = 1\n\n::1 + 1 = 2\n\nSpeculatively try a2 = 2\n\n::1 + 1 = 2\n::1 + 2 = 3\n::2 + 2 = 4\n\nThere are no repeated sums so '''2''' is the next number in the sequence.\n\nSpeculatively try a3 = 3\n\n::1 + 1 = 2\n::1 + 2 = 3 \n::1 + 3 = 4\n::2 + 2 = 4\n::2 + 3 = 5\n::3 + 3 = 6\n\nSum of '''4''' is repeated so '''3''' is rejected.\n\nSpeculatively try a3 = 4\n\n::1 + 1 = 2\n::1 + 2 = 3\n::1 + 4 = 5\n::2 + 2 = 4\n::2 + 4 = 6\n::4 + 4 = 8\n\nThere are no repeated sums so '''4''' is the next number in the sequence.\n\nAnd so on...\n\n;See also:\n\n:* OEIS:A005282 Mian-Chowla sequence\n\n", "solution": "from itertools import count, islice, chain\nimport time\n\ndef mian_chowla():\n mc = [1]\n yield mc[-1]\n psums = set([2])\n newsums = set([])\n for trial in count(2):\n for n in chain(mc, [trial]):\n sum = n + trial\n if sum in psums:\n newsums.clear()\n break\n newsums.add(sum)\n else:\n psums |= newsums\n newsums.clear()\n mc.append(trial)\n yield trial\n\ndef pretty(p, t, s, f):\n print(p, t, \" \".join(str(n) for n in (islice(mian_chowla(), s, f))))\n\nif __name__ == '__main__':\n st = time.time()\n ts = \"of the Mian-Chowla sequence are:\\n\"\n pretty(\"The first 30 terms\", ts, 0, 30)\n pretty(\"\\nTerms 91 to 100\", ts, 90, 100)\n print(\"\\nComputation time was\", (time.time()-st) * 1000, \"ms\")"} +{"title": "Middle three digits", "language": "C", "task": ";Task:\nWrite 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": "\n#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": "Middle three digits", "language": "JavaScript", "task": ";Task:\nWrite 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": "(() => {\n 'use strict';\n\n // mid3digits :: Int -> Either String String\n const mid3digits = n => {\n const\n m = abs(n),\n s = m.toString();\n return 100 > m ? (\n Left('Less than 3 digits')\n ) : even(length(s)) ? (\n Left('Even digit count')\n ) : Right(take(3, drop(quot(length(s) - 3, 2), s)));\n };\n\n // TEST -----------------------------------------------\n const main = () => {\n const\n xs = [\n 123, 12345, 1234567, 987654321, 10001, -10001, -123,\n -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0\n ],\n w = maximum(map(x => x.toString().length, xs));\n return (\n unlines(map(\n n => justifyRight(w, ' ', n.toString()) + ' -> ' +\n either(\n s => '(' + s + ')',\n id,\n mid3digits(n)\n ),\n xs\n ))\n );\n };\n\n // GENERIC FUNCTIONS ----------------------------------\n\n // Left :: a -> Either a b\n const Left = x => ({\n type: 'Either',\n Left: x\n });\n\n // Right :: b -> Either a b\n const Right = x => ({\n type: 'Either',\n Right: x\n });\n\n // abs :: Num -> Num\n const abs = Math.abs;\n\n // drop :: Int -> [a] -> [a]\n // drop :: Int -> Generator [a] -> Generator [a]\n // drop :: Int -> String -> String\n const drop = (n, xs) =>\n Infinity > length(xs) ? (\n xs.slice(n)\n ) : (take(n, xs), xs);\n\n // either :: (a -> c) -> (b -> c) -> Either a b -> c\n const either = (fl, fr, e) =>\n 'Either' === e.type ? (\n undefined !== e.Left ? (\n fl(e.Left)\n ) : fr(e.Right)\n ) : undefined;\n\n // even :: Int -> Bool\n const even = n => 0 === n % 2;\n\n // foldl1 :: (a -> a -> a) -> [a] -> a\n const foldl1 = (f, xs) =>\n 1 < xs.length ? xs.slice(1)\n .reduce(f, xs[0]) : xs[0];\n\n // id :: a -> a\n const id = x => x;\n\n // justifyRight :: Int -> Char -> String -> String\n const justifyRight = (n, cFiller, s) =>\n n > s.length ? (\n s.padStart(n, cFiller)\n ) : s;\n\n // Returns Infinity over objects without finite length.\n // This enables zip and zipWith to choose the shorter\n // argument when one is non-finite, like cycle, repeat etc\n\n // length :: [a] -> Int\n const length = xs =>\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n // maximum :: Ord a => [a] -> a\n const maximum = xs =>\n 0 < xs.length ? (\n foldl1((a, x) => x > a ? x : a, xs)\n ) : undefined;\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) => xs.map(f);\n\n // quot :: Int -> Int -> Int\n const quot = (n, m) => Math.floor(n / m);\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = (n, xs) =>\n 'GeneratorFunction' !== xs.constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // MAIN ---\n return main();\n})();"} +{"title": "Middle three digits", "language": "Python", "task": ";Task:\nWrite 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": "'''Middle 3 digits'''\n\n\n# mid3digits :: Int -> Either String String\ndef mid3digits(n):\n '''Either the middle three digits,\n or an explanatory string.'''\n m = abs(n)\n s = str(m)\n return Left('Less than 3 digits') if (100 > m) else (\n Left('Even digit count') if even(len(s)) else Right(\n s[(len(s) - 3) // 2:][0:3]\n )\n )\n\n\n# TEST ----------------------------------------------------\ndef main():\n '''Test'''\n\n def bracketed(x):\n return '(' + str(x) + ')'\n\n print(\n tabulated('Middle three digits, where defined:\\n')(str)(\n either(bracketed)(str)\n )(mid3digits)([\n 123, 12345, 1234567, 987654321, 10001, -10001, -123,\n -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0\n ])\n )\n\n\n# GENERIC -------------------------------------------------\n\n# Left :: a -> Either a b\ndef Left(x):\n '''Constructor for an empty Either (option type) value\n with an associated string.'''\n return {'type': 'Either', 'Right': None, 'Left': x}\n\n\n# Right :: b -> Either a b\ndef Right(x):\n '''Constructor for a populated Either (option type) value'''\n return {'type': 'Either', 'Left': None, 'Right': x}\n\n\n# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n '''Function composition.'''\n return lambda f: lambda x: g(f(x))\n\n\n# either :: (a -> c) -> (b -> c) -> Either a b -> c\ndef either(fl):\n '''The application of fl to e if e is a Left value,\n or the application of fr to e if e is a Right value.'''\n return lambda fr: lambda e: fl(e['Left']) if (\n None is e['Right']\n ) else fr(e['Right'])\n\n\n# even :: Int -> Bool\ndef even(x):\n '''Is x even ?'''\n return 0 == x % 2\n\n\n# tabulated :: String -> (b -> String) -> (a -> b) -> [a] -> String\ndef tabulated(s):\n '''Heading -> x display function -> fx display function ->\n f -> value list -> tabular string.'''\n def go(xShow, fxShow, f, xs):\n w = max(map(compose(len)(str), xs))\n return s + '\\n' + '\\n'.join(\n xShow(x).rjust(w, ' ') + ' -> ' + fxShow(f(x)) for x in xs\n )\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\nif __name__ == '__main__':\n main()"} +{"title": "Mind boggling card trick", "language": "C", "task": "Matt Parker of the \"Stand Up Maths channel\" has a \u00a0 [https://www.youtube.com/watch?v=aNpGxZ_1KXU YouTube video] \u00a0 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 \u00a0 (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 \u00a0 ''top card'' \u00a0 and hold it in your hand. \n### if the card is \u00a0 black, \u00a0 then add the \u00a0 ''next'' \u00a0 card (unseen) to the \"black\" pile. \n### If the card is \u00a0 \u00a0 red,\u00a0 \u00a0 then add the \u00a0 ''next'' \u00a0 card (unseen) to the \u00a0 \"red\"\u00a0 pile.\n## Add the \u00a0 ''top card'' \u00a0 that you're holding to the '''discard''' pile. \u00a0 (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 \u00a0 (call it '''X''') \u00a0 that will be used to swap cards from the \"red\" and \"black\" piles.\n# Randomly choose \u00a0 '''X''' \u00a0 cards from the \u00a0 \"red\"\u00a0 pile (unseen), let's call this the \u00a0 \"red\"\u00a0 bunch. \n# Randomly choose \u00a0 '''X''' \u00a0 cards from the \"black\" pile (unseen), let's call this the \"black\" bunch.\n# Put the \u00a0 \u00a0 \"red\"\u00a0 \u00a0 bunch into the \u00a0 \"black\" pile.\n# Put the \u00a0 \"black\" \u00a0 bunch into the \u00a0 \u00a0 \"red\"\u00a0 pile.\n# (The above two steps complete the swap of \u00a0 '''X''' \u00a0 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"} +{"title": "Mind boggling card trick", "language": "Python", "task": "Matt Parker of the \"Stand Up Maths channel\" has a \u00a0 [https://www.youtube.com/watch?v=aNpGxZ_1KXU YouTube video] \u00a0 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 \u00a0 (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 \u00a0 ''top card'' \u00a0 and hold it in your hand. \n### if the card is \u00a0 black, \u00a0 then add the \u00a0 ''next'' \u00a0 card (unseen) to the \"black\" pile. \n### If the card is \u00a0 \u00a0 red,\u00a0 \u00a0 then add the \u00a0 ''next'' \u00a0 card (unseen) to the \u00a0 \"red\"\u00a0 pile.\n## Add the \u00a0 ''top card'' \u00a0 that you're holding to the '''discard''' pile. \u00a0 (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 \u00a0 (call it '''X''') \u00a0 that will be used to swap cards from the \"red\" and \"black\" piles.\n# Randomly choose \u00a0 '''X''' \u00a0 cards from the \u00a0 \"red\"\u00a0 pile (unseen), let's call this the \u00a0 \"red\"\u00a0 bunch. \n# Randomly choose \u00a0 '''X''' \u00a0 cards from the \"black\" pile (unseen), let's call this the \"black\" bunch.\n# Put the \u00a0 \u00a0 \"red\"\u00a0 \u00a0 bunch into the \u00a0 \"black\" pile.\n# Put the \u00a0 \"black\" \u00a0 bunch into the \u00a0 \u00a0 \"red\"\u00a0 pile.\n# (The above two steps complete the swap of \u00a0 '''X''' \u00a0 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": "import random\n\n## 1. Cards\nn = 52\nBlack, Red = 'Black', 'Red'\nblacks = [Black] * (n // 2) \nreds = [Red] * (n // 2)\npack = blacks + reds\n# Give the pack a good shuffle.\nrandom.shuffle(pack)\n\n## 2. Deal from the randomised pack into three stacks\nblack_stack, red_stack, discard = [], [], []\nwhile pack:\n top = pack.pop()\n if top == Black:\n black_stack.append(pack.pop())\n else:\n red_stack.append(pack.pop())\n discard.append(top)\nprint('(Discards:', ' '.join(d[0] for d in discard), ')\\n')\n\n## 3. Swap the same, random, number of cards between the two stacks.\n# We can't swap more than the number of cards in a stack.\nmax_swaps = min(len(black_stack), len(red_stack))\n# Randomly choose the number of cards to swap.\nswap_count = random.randint(0, max_swaps)\nprint('Swapping', swap_count)\n# Randomly choose that number of cards out of each stack to swap.\ndef random_partition(stack, count):\n \"Partition the stack into 'count' randomly selected members and the rest\"\n sample = random.sample(stack, count)\n rest = stack[::]\n for card in sample:\n rest.remove(card)\n return rest, sample\n\nblack_stack, black_swap = random_partition(black_stack, swap_count)\nred_stack, red_swap = random_partition(red_stack, swap_count)\n\n# Perform the swap.\nblack_stack += red_swap\nred_stack += black_swap\n\n## 4. Order from randomness?\nif black_stack.count(Black) == red_stack.count(Red):\n print('Yeha! The mathematicians assertion is correct.')\nelse:\n print('Whoops - The mathematicians (or my card manipulations) are flakey')"} +{"title": "Minimal steps down to 1", "language": "Python", "task": "Given:\n* A starting, positive integer (greater than one), N.\n* A selection of possible integer perfect divisors, D.\n* And a selection of possible subtractors, S.\nThe goal is find the minimum number of steps necessary to reduce N down to one.\n\nAt any step, the number may be:\n* Divided by any member of D if it is perfectly divided by D, (remainder zero).\n* OR have one of S subtracted from it, if N is greater than the member of S.\n\n\nThere may be many ways to reduce the initial N down to 1. Your program needs to:\n* Find the ''minimum'' number of ''steps'' to reach 1.\n* Show '''one''' way of getting fron N to 1 in those minimum steps.\n\n;Examples:\nNo divisors, D. a single subtractor of 1.\n:Obviousely N will take N-1 subtractions of 1 to reach 1\n\nSingle divisor of 2; single subtractor of 1:\n:N = 7 Takes 4 steps N -1=> 6, /2=> 3, -1=> 2, /2=> 1\n:N = 23 Takes 7 steps N -1=>22, /2=>11, -1=>10, /2=> 5, -1=> 4, /2=> 2, /2=> 1\n\nDivisors 2 and 3; subtractor 1:\n:N = 11 Takes 4 steps N -1=>10, -1=> 9, /3=> 3, /3=> 1\n\n;Task:\nUsing the possible divisors D, of 2 and 3; together with a possible subtractor S, of 1:\n\n:1. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.\n:2. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.\n\nUsing the possible divisors D, of 2 and 3; together with a possible subtractor S, of 2:\n\n:3. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.\n:4. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.\n\n\n;Optional stretch goal:\n:2a, and 4a: As in 2 and 4 above, but for N in the range 1 to 20_000\n\n\n;Reference:\n* [https://www.youtube.com/watch?v=f2xi3c1S95M Learn Dynamic Programming (Memoization & Tabulation)] Video of similar task.\n\n", "solution": "\nfrom functools import lru_cache\n\n\n#%%\n\nDIVS = {2, 3}\nSUBS = {1}\n\nclass Minrec():\n \"Recursive, memoised minimised steps to 1\"\n\n def __init__(self, divs=DIVS, subs=SUBS):\n self.divs, self.subs = divs, subs\n\n @lru_cache(maxsize=None)\n def _minrec(self, n):\n \"Recursive, memoised\"\n if n == 1:\n return 0, ['=1']\n possibles = {}\n for d in self.divs:\n if n % d == 0:\n possibles[f'/{d}=>{n // d:2}'] = self._minrec(n // d)\n for s in self.subs:\n if n > s:\n possibles[f'-{s}=>{n - s:2}'] = self._minrec(n - s)\n thiskind, (count, otherkinds) = min(possibles.items(), key=lambda x: x[1])\n ret = 1 + count, [thiskind] + otherkinds\n return ret\n\n def __call__(self, n):\n \"Recursive, memoised\"\n ans = self._minrec(n)[1][:-1]\n return len(ans), ans\n\n\nif __name__ == '__main__':\n for DIVS, SUBS in [({2, 3}, {1}), ({2, 3}, {2})]:\n minrec = Minrec(DIVS, SUBS)\n print('\\nMINIMUM STEPS TO 1: Recursive algorithm')\n print(' Possible divisors: ', DIVS)\n print(' Possible decrements:', SUBS)\n for n in range(1, 11):\n steps, how = minrec(n)\n print(f' minrec({n:2}) in {steps:2} by: ', ', '.join(how))\n\n upto = 2000\n print(f'\\n Those numbers up to {upto} that take the maximum, \"minimal steps down to 1\":')\n stepn = sorted((minrec(n)[0], n) for n in range(upto, 0, -1))\n mx = stepn[-1][0]\n ans = [x[1] for x in stepn if x[0] == mx]\n print(' Taking', mx, f'steps is/are the {len(ans)} numbers:',\n ', '.join(str(n) for n in sorted(ans)))\n #print(minrec._minrec.cache_info())\n print()"} +{"title": "Minimum multiple of m where digital sum equals m", "language": "C", "task": "Generate the sequence '''a(n)''' when each element is the minimum integer multiple '''m''' such that the digit sum of '''n''' times '''m''' is equal to '''n'''.\n\n\n;Task\n\n* Find the first 40 elements of the sequence.\n\n\n\n;Stretch\n\n* Find the next 30 elements of the sequence.\n\n\n;See also\n\n;* OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n\n\n\n\n\n", "solution": "#include \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 multiple of m where digital sum equals m", "language": "Python", "task": "Generate the sequence '''a(n)''' when each element is the minimum integer multiple '''m''' such that the digit sum of '''n''' times '''m''' is equal to '''n'''.\n\n\n;Task\n\n* Find the first 40 elements of the sequence.\n\n\n\n;Stretch\n\n* Find the next 30 elements of the sequence.\n\n\n;See also\n\n;* OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n\n\n\n\n\n", "solution": "'''A131382'''\n\nfrom itertools import count, islice\n\n\n# a131382 :: [Int]\ndef a131382():\n '''An infinite series of the terms of A131382'''\n return (\n elemIndex(x)(\n productDigitSums(x)\n ) for x in count(1)\n )\n\n\n# productDigitSums :: Int -> [Int]\ndef productDigitSums(n):\n '''The sum of the decimal digits of n'''\n return (digitSum(n * x) for x in count(0))\n\n\n# ------------------------- TEST -------------------------\n# main :: IO ()\ndef main():\n '''First 40 terms of A131382'''\n\n print(\n table(10)([\n str(x) for x in islice(\n a131382(),\n 40\n )\n ])\n )\n\n\n# ----------------------- GENERIC ------------------------\n\n# chunksOf :: Int -> [a] -> [[a]]\ndef chunksOf(n):\n '''A series of lists of length n, subdividing the\n contents of xs. Where the length of xs is not evenly\n divisible, the final list will be shorter than n.\n '''\n def go(xs):\n return (\n xs[i:n + i] for i in range(0, len(xs), n)\n ) if 0 < n else None\n return go\n\n\n# digitSum :: Int -> Int\ndef digitSum(n):\n '''The sum of the digital digits of n.\n '''\n return sum(int(x) for x in list(str(n)))\n\n\n# elemIndex :: a -> [a] -> (None | Int)\ndef elemIndex(x):\n '''Just the first index of x in xs,\n or None if no elements match.\n '''\n def go(xs):\n try:\n return next(\n i for i, v in enumerate(xs) if x == v\n )\n except StopIteration:\n return None\n return go\n\n\n# table :: Int -> [String] -> String\ndef table(n):\n '''A list of strings formatted as\n right-justified rows of n columns.\n '''\n def go(xs):\n w = len(xs[-1])\n return '\\n'.join(\n ' '.join(row) for row in chunksOf(n)([\n s.rjust(w, ' ') for s in xs\n ])\n )\n return go\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} +{"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''' \u00d7 '''multiplier'''\n 1 1 ( 1 \u00d7 1 )\n 2 10 ( 2 \u00d7 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:* [https://math.stackexchange.com/questions/388165/how-to-find-the-smallest-number-with-just-0-and-1-which-is-divided-by-a-give 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": "Minimum positive multiple in base 10 using only 0 and 1", "language": "Python", "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''' \u00d7 '''multiplier'''\n 1 1 ( 1 \u00d7 1 )\n 2 10 ( 2 \u00d7 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:* [https://math.stackexchange.com/questions/388165/how-to-find-the-smallest-number-with-just-0-and-1-which-is-divided-by-a-give How to find Minimum Positive Multiple in base 10 using only 0 and 1]\n\n", "solution": "def getA004290(n):\n if n < 2:\n return 1\n arr = [[0 for _ in range(n)] for _ in range(n)]\n arr[0][0] = 1\n arr[0][1] = 1\n m = 0\n while True:\n m += 1\n if arr[m - 1][-10 ** m % n] == 1:\n break\n arr[m][0] = 1\n for k in range(1, n):\n arr[m][k] = max([arr[m - 1][k], arr[m - 1][k - 10 ** m % n]])\n r = 10 ** m\n k = -r % n\n for j in range((m - 1), 0, -1):\n if arr[j - 1][k] == 0:\n r = r + 10 ** j\n k = (k - 10 ** j) % n \n if k == 1:\n r += 1\n return r\n \nfor n in [i for i in range(1, 11)] + \\\n [i for i in range(95, 106)] + \\\n [297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878]:\n result = getA004290(n)\n print(f\"A004290({n}) = {result} = {n} * {result // n})\")\n"} +{"title": "Minkowski question-mark function", "language": "Python", "task": "The '''Minkowski question-mark function''' converts the continued fraction representation {{math|[a0; a1, a2, a3, ...]}} of a number into a binary decimal representation in which the integer part {{math|a0}} is unchanged and the {{math|a1, a2, ...}} become alternating runs of binary zeroes and ones of those lengths. The decimal point takes the place of the first zero. \n\nThus, {{math|?}}(31/7) = 71/16 because 31/7 has the continued fraction representation {{math|[4;2,3]}} giving the binary expansion {{math|4 + 0.01112}}.\n\nAmong its interesting properties is that it maps roots of quadratic equations, which have repeating continued fractions, to rational numbers, which have repeating binary digits.\n\nThe question-mark function is continuous and monotonically increasing, so it has an inverse.\n\n* Produce a function for {{math|?(x)}}. \u00a0 Be careful: rational numbers have two possible continued fraction representations:\n:::* \u00a0 {{math|[a0;a1,... an\u22121,an]}} \u00a0 \u00a0 and \n:::* \u00a0 {{math|[a0;a1,... an\u22121,an\u22121,1]}} \n* Choose one of the above that will give a binary expansion ending with a \u00a0 '''1'''.\n* Produce the inverse function {{math|?-1(x)}}\n* Verify that {{math|?(\u03c6)}} = 5/3, where {{math|\u03c6}} is the Greek golden ratio.\n* Verify that {{math|?-1(-5/9)}} = (\u221a13 - 7)/6\n* Verify that the two functions are inverses of each other by showing that {{math|?-1(?(x))}}={{math|x}} and {{math|?(?-1(y))}}={{math|y}} for {{math|x, y}} of your choice \n\n\nDon't worry about precision error in the last few digits. \n\n\n;See also:\n* Wikipedia entry: Minkowski's question-mark function\n\n\n", "solution": "import math\n\nMAXITER = 151\n\n\ndef minkowski(x):\n if x > 1 or x < 0:\n return math.floor(x) + minkowski(x - math.floor(x))\n\n p = int(x)\n q = 1\n r = p + 1\n s = 1\n d = 1.0\n y = float(p)\n\n while True:\n d /= 2\n if y + d == y:\n break\n\n m = p + r\n if m < 0 or p < 0:\n break\n\n n = q + s\n if n < 0:\n break\n\n if x < m / n:\n r = m\n s = n\n else:\n y += d\n p = m\n q = n\n\n return y + d\n\n\ndef minkowski_inv(x):\n if x > 1 or x < 0:\n return math.floor(x) + minkowski_inv(x - math.floor(x))\n\n if x == 1 or x == 0:\n return x\n\n cont_frac = [0]\n current = 0\n count = 1\n i = 0\n\n while True:\n x *= 2\n\n if current == 0:\n if x < 1:\n count += 1\n else:\n cont_frac.append(0)\n cont_frac[i] = count\n\n i += 1\n count = 1\n current = 1\n x -= 1\n else:\n if x > 1:\n count += 1\n x -= 1\n else:\n cont_frac.append(0)\n cont_frac[i] = count\n\n i += 1\n count = 1\n current = 0\n\n if x == math.floor(x):\n cont_frac[i] = count\n break\n\n if i == MAXITER:\n break\n\n ret = 1.0 / cont_frac[i]\n for j in range(i - 1, -1, -1):\n ret = cont_frac[j] + 1.0 / ret\n\n return 1.0 / ret\n\n\nif __name__ == \"__main__\":\n print(\n \"{:19.16f} {:19.16f}\".format(\n minkowski(0.5 * (1 + math.sqrt(5))),\n 5.0 / 3.0,\n )\n )\n\n print(\n \"{:19.16f} {:19.16f}\".format(\n minkowski_inv(-5.0 / 9.0),\n (math.sqrt(13) - 7) / 6,\n )\n )\n\n print(\n \"{:19.16f} {:19.16f}\".format(\n minkowski(minkowski_inv(0.718281828)),\n minkowski_inv(minkowski(0.1213141516171819)),\n )\n )\n"} +{"title": "Modified random distribution", "language": "Python", "task": "Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x)\ntaking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following algorithm for generating random numbers to the probability given by function modifier:\nwhile True:\n random1 = rgen()\n random2 = rgen()\n if random2 < modifier(random1):\n answer = random1\n break\n endif\nendwhile\n\n;Task:\n* Create a modifier function that generates a 'V' shaped probability of number generation using something like, for example:\n modifier(x) = 2*(0.5 - x) if x < 0.5 else 2*(x - 0.5) \n* Create a generator of random numbers with probabilities modified by the above function.\n* Generate >= 10,000 random numbers subject to the probability modification.\n* Output a textual histogram with from 11 to 21 bins showing the distribution of the random numbers generated.\n\n\nShow your output here, on this page.\n\n", "solution": "import random\nfrom typing import List, Callable, Optional\n\n\ndef modifier(x: float) -> float:\n \"\"\"\n V-shaped, modifier(x) goes from 1 at 0 to 0 at 0.5 then back to 1 at 1.0 .\n\n Parameters\n ----------\n x : float\n Number, 0.0 .. 1.0 .\n\n Returns\n -------\n float\n Target probability for generating x; between 0 and 1.\n\n \"\"\"\n return 2*(.5 - x) if x < 0.5 else 2*(x - .5)\n\n\ndef modified_random_distribution(modifier: Callable[[float], float],\n n: int) -> List[float]:\n \"\"\"\n Generate n random numbers between 0 and 1 subject to modifier.\n\n Parameters\n ----------\n modifier : Callable[[float], float]\n Target random number gen. 0 <= modifier(x) < 1.0 for 0 <= x < 1.0 .\n n : int\n number of random numbers generated.\n\n Returns\n -------\n List[float]\n n random numbers generated with given probability.\n\n \"\"\"\n d: List[float] = []\n while len(d) < n:\n r1 = prob = random.random()\n if random.random() < modifier(prob):\n d.append(r1)\n return d\n\n\nif __name__ == '__main__':\n from collections import Counter\n\n data = modified_random_distribution(modifier, 50_000)\n bins = 15\n counts = Counter(d // (1 / bins) for d in data)\n #\n mx = max(counts.values())\n print(\" BIN, COUNTS, DELTA: HISTOGRAM\\n\")\n last: Optional[float] = None\n for b, count in sorted(counts.items()):\n delta = 'N/A' if last is None else str(count - last)\n print(f\" {b / bins:5.2f}, {count:4}, {delta:>4}: \"\n f\"{'#' * int(40 * count / mx)}\")\n last = count"} +{"title": "Modular arithmetic", "language": "C", "task": "'''equivalence relation called ''congruence''. \n\nFor any positive integer p called the ''congruence modulus'', \ntwo numbers a and b are said to be ''congruent modulo p'' whenever there exists an integer k such that:\n:a = b + k\\,p\n\nThe corresponding set of multiplicative inverse for this task.\n\nAddition and multiplication on this ring have the same algebraic structure as in usual arithmetic, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.\n\nThe purpose of this task is to show, if your programming language allows it, \nhow to redefine operators so that they can be used transparently on modular integers. \nYou can do it either by using a dedicated library, or by implementing your own class.\n\nYou will use the following function for demonstration:\n:f(x) = x^{100} + x + 1\nYou will use 13 as the congruence modulus and you will compute f(10).\n\nIt is important that the function f is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers. \nIn other words, the function is an algebraic expression that could be used with any ring, not just integers.\n\n", "solution": "#include \n\nstruct ModularArithmetic {\n int value;\n int modulus;\n};\n\nstruct ModularArithmetic make(const int value, const int modulus) {\n struct ModularArithmetic r = { value % modulus, modulus };\n return r;\n}\n\nstruct ModularArithmetic add(const struct ModularArithmetic a, const struct ModularArithmetic b) {\n return make(a.value + b.value, a.modulus);\n}\n\nstruct ModularArithmetic addi(const struct ModularArithmetic a, const int v) {\n return make(a.value + v, a.modulus);\n}\n\nstruct ModularArithmetic mul(const struct ModularArithmetic a, const struct ModularArithmetic b) {\n return make(a.value * b.value, a.modulus);\n}\n\nstruct ModularArithmetic pow(const struct ModularArithmetic b, int pow) {\n struct ModularArithmetic r = make(1, b.modulus);\n while (pow-- > 0) {\n r = mul(r, b);\n }\n return r;\n}\n\nvoid print(const struct ModularArithmetic v) {\n printf(\"ModularArithmetic(%d, %d)\", v.value, v.modulus);\n}\n\nstruct ModularArithmetic f(const struct ModularArithmetic x) {\n return addi(add(pow(x, 100), x), 1);\n}\n\nint main() {\n struct ModularArithmetic input = make(10, 13);\n struct ModularArithmetic output = f(input);\n\n printf(\"f(\");\n print(input);\n printf(\") = \");\n print(output);\n printf(\"\\n\");\n\n return 0;\n}"} +{"title": "Modular arithmetic", "language": "Python 3.x", "task": "'''equivalence relation called ''congruence''. \n\nFor any positive integer p called the ''congruence modulus'', \ntwo numbers a and b are said to be ''congruent modulo p'' whenever there exists an integer k such that:\n:a = b + k\\,p\n\nThe corresponding set of multiplicative inverse for this task.\n\nAddition and multiplication on this ring have the same algebraic structure as in usual arithmetic, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.\n\nThe purpose of this task is to show, if your programming language allows it, \nhow to redefine operators so that they can be used transparently on modular integers. \nYou can do it either by using a dedicated library, or by implementing your own class.\n\nYou will use the following function for demonstration:\n:f(x) = x^{100} + x + 1\nYou will use 13 as the congruence modulus and you will compute f(10).\n\nIt is important that the function f is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers. \nIn other words, the function is an algebraic expression that could be used with any ring, not just integers.\n\n", "solution": "import operator\nimport functools\n\n@functools.total_ordering\nclass Mod:\n __slots__ = ['val','mod']\n\n def __init__(self, val, mod):\n if not isinstance(val, int):\n raise ValueError('Value must be integer')\n if not isinstance(mod, int) or mod<=0:\n raise ValueError('Modulo must be positive integer')\n self.val = val % mod\n self.mod = mod\n\n def __repr__(self):\n return 'Mod({}, {})'.format(self.val, self.mod)\n\n def __int__(self):\n return self.val\n\n def __eq__(self, other):\n if isinstance(other, Mod):\n if self.mod == other.mod:\n return self.val==other.val\n else:\n return NotImplemented\n elif isinstance(other, int):\n return self.val == other\n else:\n return NotImplemented\n\n def __lt__(self, other):\n if isinstance(other, Mod):\n if self.mod == other.mod:\n return self.val\n"} +{"title": "Modular exponentiation", "language": "C", "task": "Find the last \u00a0 '''40''' \u00a0 decimal digits of \u00a0 a^b, \u00a0 where\n\n::* \u00a0 a = 2988348162058574136915891421498819466320163312926952423791023078876139\n::* \u00a0 b = 2351399303373464486466122544523690094744975233415544072992656881240319\n\n\nA computer is too slow to find the entire value of \u00a0 a^b. \n\nInstead, the program must use a fast algorithm for modular exponentiation: \u00a0 a^b \\mod m.\n\nThe algorithm must work for any integers \u00a0 a, b, m, \u00a0 \u00a0 where \u00a0 b \\ge 0 \u00a0 and \u00a0 m > 0.\n\n", "solution": "#include \n\nint main()\n{\n\tmpz_t a, b, m, r;\n\n\tmpz_init_set_str(a,\t\"2988348162058574136915891421498819466320\"\n\t\t\t\t\"163312926952423791023078876139\", 0);\n\tmpz_init_set_str(b,\t\"2351399303373464486466122544523690094744\"\n\t\t\t\t\"975233415544072992656881240319\", 0);\n\tmpz_init(m);\n\tmpz_ui_pow_ui(m, 10, 40);\n\n\tmpz_init(r);\n\tmpz_powm(r, a, b, m);\n\n\tgmp_printf(\"%Zd\\n\", r); /* ...16808958343740453059 */\n\n\tmpz_clear(a);\n\tmpz_clear(b);\n\tmpz_clear(m);\n\tmpz_clear(r);\n\n\treturn 0;\n}"} +{"title": "Modular exponentiation", "language": "Python", "task": "Find the last \u00a0 '''40''' \u00a0 decimal digits of \u00a0 a^b, \u00a0 where\n\n::* \u00a0 a = 2988348162058574136915891421498819466320163312926952423791023078876139\n::* \u00a0 b = 2351399303373464486466122544523690094744975233415544072992656881240319\n\n\nA computer is too slow to find the entire value of \u00a0 a^b. \n\nInstead, the program must use a fast algorithm for modular exponentiation: \u00a0 a^b \\mod m.\n\nThe algorithm must work for any integers \u00a0 a, b, m, \u00a0 \u00a0 where \u00a0 b \\ge 0 \u00a0 and \u00a0 m > 0.\n\n", "solution": "a = 2988348162058574136915891421498819466320163312926952423791023078876139\nb = 2351399303373464486466122544523690094744975233415544072992656881240319\nm = 10 ** 40\nprint(pow(a, b, m))"} +{"title": "Modular inverse", "language": "C", "task": "From [http://en.wikipedia.org/wiki/Modular_multiplicative_inverse Wikipedia]:\n\nIn modulo \u00a0 ''m'' \u00a0 is an integer \u00a0 ''x'' \u00a0 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 \u00a0 if and only if \u00a0 ''a'' \u00a0 and \u00a0 ''m'' \u00a0 are coprime, \u00a0 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, \u00a0 compute the modular inverse of \u00a0 42 modulo 2017.\n\n", "solution": "#include \n\nint mul_inv(int a, int b)\n{\n int t, nt, r, nr, q, tmp;\n if (b < 0) b = -b;\n if (a < 0) a = b - (-a % b);\n t = 0; nt = 1; r = b; nr = a % b;\n while (nr != 0) {\n q = r/nr;\n tmp = nt; nt = t - q*nt; t = tmp;\n tmp = nr; nr = r - q*nr; r = tmp;\n }\n if (r > 1) return -1; /* No inverse */\n if (t < 0) t += b;\n return t;\n}\nint main(void) {\n printf(\"%d\\n\", mul_inv(42, 2017));\n printf(\"%d\\n\", mul_inv(40, 1));\n printf(\"%d\\n\", mul_inv(52, -217)); /* Pari semantics for negative modulus */\n printf(\"%d\\n\", mul_inv(-486, 217));\n printf(\"%d\\n\", mul_inv(40, 2018));\n return 0;\n}"} +{"title": "Modular inverse", "language": "JavaScript", "task": "From [http://en.wikipedia.org/wiki/Modular_multiplicative_inverse Wikipedia]:\n\nIn modulo \u00a0 ''m'' \u00a0 is an integer \u00a0 ''x'' \u00a0 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 \u00a0 if and only if \u00a0 ''a'' \u00a0 and \u00a0 ''m'' \u00a0 are coprime, \u00a0 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, \u00a0 compute the modular inverse of \u00a0 42 modulo 2017.\n\n", "solution": "var modInverse = function(a, b) {\n a %= b;\n for (var x = 1; x < b; x++) {\n if ((a*x)%b == 1) {\n return x;\n }\n }\n}"} +{"title": "Modular inverse", "language": "Python", "task": "From [http://en.wikipedia.org/wiki/Modular_multiplicative_inverse Wikipedia]:\n\nIn modulo \u00a0 ''m'' \u00a0 is an integer \u00a0 ''x'' \u00a0 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 \u00a0 if and only if \u00a0 ''a'' \u00a0 and \u00a0 ''m'' \u00a0 are coprime, \u00a0 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, \u00a0 compute the modular inverse of \u00a0 42 modulo 2017.\n\n", "solution": "from functools import (reduce)\nfrom itertools import (chain)\n\n\n# modInv :: Int -> Int -> Maybe Int\ndef modInv(a):\n return lambda m: (\n lambda ig=gcdExt(a)(m): (\n lambda i=ig[0]: (\n Just(i + m if 0 > i else i) if 1 == ig[2] else (\n Nothing()\n )\n )\n )()\n )()\n\n\n# gcdExt :: Int -> Int -> (Int, Int, Int)\ndef gcdExt(x):\n def go(a, b):\n if 0 == b:\n return (1, 0, a)\n else:\n (q, r) = divmod(a, b)\n (s, t, g) = go(b, r)\n return (t, s - q * t, g)\n return lambda y: go(x, y)\n\n\n# TEST ---------------------------------------------------\n\n# Numbers between 2010 and 2015 which do yield modular inverses for 42:\n\n# main :: IO ()\ndef main():\n print (\n mapMaybe(\n lambda y: bindMay(modInv(42)(y))(\n lambda mInv: Just((y, mInv))\n )\n )(\n enumFromTo(2010)(2025)\n )\n )\n\n# -> [(2011, 814), (2015, 48), (2017, 1969), (2021, 1203)]\n\n\n# GENERIC ABSTRACTIONS ------------------------------------\n\n\n# enumFromTo :: Int -> Int -> [Int]\ndef enumFromTo(m):\n return lambda n: list(range(m, 1 + n))\n\n\n# bindMay (>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b\ndef bindMay(m):\n return lambda mf: (\n m if m.get('Nothing') else mf(m.get('Just'))\n )\n\n\n# Just :: a -> Maybe a\ndef Just(x):\n return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n# mapMaybe :: (a -> Maybe b) -> [a] -> [b]\ndef mapMaybe(mf):\n return lambda xs: reduce(\n lambda a, x: maybe(a)(lambda j: a + [j])(mf(x)),\n xs,\n []\n )\n\n\n# maybe :: b -> (a -> b) -> Maybe a -> b\ndef maybe(v):\n return lambda f: lambda m: v if m.get('Nothing') else (\n f(m.get('Just'))\n )\n\n\n# Nothing :: Maybe a\ndef Nothing():\n return {'type': 'Maybe', 'Nothing': True}\n\n\n# MAIN ---\nmain()"} +{"title": "Monads/List monad", "language": "C", "task": "[[Category:Monads]]\n\nA 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 \u2013 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/List monad", "language": "Python", "task": "[[Category:Monads]]\n\nA 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 \u2013 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": "\"\"\"A List Monad. Requires Python >= 3.7 for type hints.\"\"\"\nfrom __future__ import annotations\nfrom itertools import chain\n\nfrom typing import Any\nfrom typing import Callable\nfrom typing import Iterable\nfrom typing import List\nfrom typing import TypeVar\n\n\nT = TypeVar(\"T\")\n\n\nclass MList(List[T]):\n @classmethod\n def unit(cls, value: Iterable[T]) -> MList[T]:\n return cls(value)\n\n def bind(self, func: Callable[[T], MList[Any]]) -> MList[Any]:\n return MList(chain.from_iterable(map(func, self)))\n\n def __rshift__(self, func: Callable[[T], MList[Any]]) -> MList[Any]:\n return self.bind(func)\n\n\nif __name__ == \"__main__\":\n # Chained int and string functions\n print(\n MList([1, 99, 4])\n .bind(lambda val: MList([val + 1]))\n .bind(lambda val: MList([f\"${val}.00\"]))\n )\n\n # Same, but using `>>` as the bind operator.\n print(\n MList([1, 99, 4])\n >> (lambda val: MList([val + 1]))\n >> (lambda val: MList([f\"${val}.00\"]))\n )\n\n # Cartesian product of [1..5] and [6..10]\n print(\n MList(range(1, 6)).bind(\n lambda x: MList(range(6, 11)).bind(lambda y: MList([(x, y)]))\n )\n )\n\n # Pythagorean triples with elements between 1 and 25\n print(\n MList(range(1, 26)).bind(\n lambda x: MList(range(x + 1, 26)).bind(\n lambda y: MList(range(y + 1, 26)).bind(\n lambda z: MList([(x, y, z)])\n if x * x + y * y == z * z\n else MList([])\n )\n )\n )\n )\n"} +{"title": "Monads/Maybe monad", "language": "C", "task": "[[Category:Monads]]\nDemonstrate 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": "\n#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": "Monads/Maybe monad", "language": "JavaScript", "task": "[[Category:Monads]]\nDemonstrate 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": "(function () {\n 'use strict';\n\n // START WITH SOME SIMPLE (UNSAFE) PARTIAL FUNCTIONS:\n\n // Returns Infinity if n === 0\n function reciprocal(n) {\n return 1 / n;\n }\n\n // Returns NaN if n < 0\n function root(n) {\n return Math.sqrt(n);\n }\n\n // Returns -Infinity if n === 0\n // Returns NaN if n < 0\n function log(n) {\n return Math.log(n);\n }\n\n\n // NOW DERIVE SAFE VERSIONS OF THESE SIMPLE FUNCTIONS:\n // These versions use a validity test, and return a wrapped value\n // with a boolean .isValid property as well as a .value property\n\n function safeVersion(f, fnSafetyCheck) {\n return function (v) {\n return maybe(fnSafetyCheck(v) ? f(v) : undefined);\n }\n }\n\n var safe_reciprocal = safeVersion(reciprocal, function (n) {\n return n !== 0;\n });\n\n var safe_root = safeVersion(root, function (n) {\n return n >= 0;\n });\n\n\n var safe_log = safeVersion(log, function (n) {\n return n > 0;\n });\n\n\n // THE DERIVATION OF THE SAFE VERSIONS USED THE 'UNIT' OR 'RETURN' \n // FUNCTION OF THE MAYBE MONAD\n\n // Named maybe() here, the unit function of the Maybe monad wraps a raw value \n // in a datatype with two elements: .isValid (Bool) and .value (Number)\n\n // a -> Ma\n function maybe(n) {\n return {\n isValid: (typeof n !== 'undefined'),\n value: n\n };\n }\n\n // THE PROBLEM FOR FUNCTION NESTING (COMPOSITION) OF THE SAFE FUNCTIONS\n // IS THAT THEIR INPUT AND OUTPUT TYPES ARE DIFFERENT\n\n // Our safe versions of the functions take simple numeric arguments, but return\n // wrapped results. If we feed a wrapped result as an input to another safe function,\n // it will choke on the unexpected type. The solution is to write a higher order\n // function (sometimes called 'bind' or 'chain') which handles composition, taking a \n // a safe function and a wrapped value as arguments,\n\n // The 'bind' function of the Maybe monad:\n // 1. Applies a 'safe' function directly to the raw unwrapped value, and\n // 2. returns the wrapped result.\n\n // Ma -> (a -> Mb) -> Mb\n function bind(maybeN, mf) {\n return (maybeN.isValid ? mf(maybeN.value) : maybeN);\n }\n\n // Using the bind function, we can nest applications of safe_ functions,\n // without their choking on unexpectedly wrapped values returned from\n // other functions of the same kind.\n var rootOneOverFour = bind(\n bind(maybe(4), safe_reciprocal), safe_root\n ).value;\n\n // -> 0.5\n\n\n // We can compose a chain of safe functions (of any length) with a simple foldr/reduceRight\n // which starts by 'lifting' the numeric argument into a Maybe wrapping,\n // and then nests function applications (working from right to left)\n function safeCompose(lstFunctions, value) {\n return lstFunctions\n .reduceRight(function (a, f) {\n return bind(a, f);\n }, maybe(value));\n }\n\n // TEST INPUT VALUES WITH A SAFELY COMPOSED VERSION OF LOG(SQRT(1/X))\n\n var safe_log_root_reciprocal = function (n) {\n return safeCompose([safe_log, safe_root, safe_reciprocal], n).value;\n }\n\n return [-2, -1, -0.5, 0, 1 / Math.E, 1, 2, Math.E, 3, 4, 5].map(\n safe_log_root_reciprocal\n );\n\n})();"} +{"title": "Monads/Maybe monad", "language": "Python", "task": "[[Category:Monads]]\nDemonstrate 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": "\"\"\"A Maybe Monad. Requires Python >= 3.7 for type hints.\"\"\"\nfrom __future__ import annotations\n\nfrom typing import Any\nfrom typing import Callable\nfrom typing import Generic\nfrom typing import Optional\nfrom typing import TypeVar\nfrom typing import Union\n\n\nT = TypeVar(\"T\")\n\n\nclass Maybe(Generic[T]):\n def __init__(self, value: Union[Optional[T], Maybe[T]] = None):\n if isinstance(value, Maybe):\n self.value: Optional[T] = value.value\n else:\n self.value = value\n\n def __rshift__(self, func: Callable[[Optional[T]], Maybe[Any]]):\n return self.bind(func)\n\n def bind(self, func: Callable[[Optional[T]], Maybe[Any]]) -> Maybe[Any]:\n return func(self.value)\n\n def __str__(self):\n return f\"{self.__class__.__name__}({self.value!r})\"\n\n\ndef plus_one(value: Optional[int]) -> Maybe[int]:\n if value is not None:\n return Maybe[int](value + 1)\n return Maybe[int](None)\n\n\ndef currency(value: Optional[int]) -> Maybe[str]:\n if value is not None:\n return Maybe[str](f\"${value}.00\")\n return Maybe[str](None)\n\n\nif __name__ == \"__main__\":\n test_cases = [1, 99, None, 4]\n\n for case in test_cases:\n m_int = Maybe[int](case)\n result = m_int >> plus_one >> currency\n # or..\n # result = m_int.bind(plus_one).bind(currency)\n print(f\"{str(case):<4} -> {result}\")\n"} +{"title": "Monads/Writer monad", "language": "JavaScript", "task": "[[Category:Monads]]\n\nThe Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application.\n\nDemonstrate in your programming language the following:\n\n# Construct a Writer monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that monad (or just use what the language already provides)\n# Write three simple functions: root, addOne, and half\n# Derive Writer monad versions of each of these functions\n# Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio \u03c6, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.)\n\n", "solution": "(function () {\n 'use strict';\n\n // START WITH THREE SIMPLE FUNCTIONS\n\n // Square root of a number more than 0\n function root(x) {\n return Math.sqrt(x);\n }\n\n // Add 1\n function addOne(x) {\n return x + 1;\n }\n\n // Divide by 2\n function half(x) {\n return x / 2;\n }\n\n\n // DERIVE LOGGING VERSIONS OF EACH FUNCTION\n\n function loggingVersion(f, strLog) {\n return function (v) {\n return {\n value: f(v),\n log: strLog\n };\n }\n }\n\n var log_root = loggingVersion(root, \"obtained square root\"),\n\n log_addOne = loggingVersion(addOne, \"added 1\"),\n\n log_half = loggingVersion(half, \"divided by 2\");\n\n\n // UNIT/RETURN and BIND for the the WRITER MONAD\n\n // The Unit / Return function for the Writer monad:\n // 'Lifts' a raw value into the wrapped form\n // a -> Writer a\n function writerUnit(a) {\n return {\n value: a,\n log: \"Initial value: \" + JSON.stringify(a)\n };\n }\n\n // The Bind function for the Writer monad:\n // applies a logging version of a function\n // to the contents of a wrapped value\n // and return a wrapped result (with extended log)\n\n // Writer a -> (a -> Writer b) -> Writer b\n function writerBind(w, f) {\n var writerB = f(w.value),\n v = writerB.value;\n\n return {\n value: v,\n log: w.log + '\\n' + writerB.log + ' -> ' + JSON.stringify(v)\n };\n }\n\n // USING UNIT AND BIND TO COMPOSE LOGGING FUNCTIONS\n\n // We can compose a chain of Writer functions (of any length) with a simple foldr/reduceRight\n // which starts by 'lifting' the initial value into a Writer wrapping,\n // and then nests function applications (working from right to left)\n function logCompose(lstFunctions, value) {\n return lstFunctions.reduceRight(\n writerBind,\n writerUnit(value)\n );\n }\n\n var half_of_addOne_of_root = function (v) {\n return logCompose(\n [log_half, log_addOne, log_root], v\n );\n };\n\n return half_of_addOne_of_root(5);\n})();"} +{"title": "Monads/Writer monad", "language": "Python", "task": "[[Category:Monads]]\n\nThe Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application.\n\nDemonstrate in your programming language the following:\n\n# Construct a Writer monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that monad (or just use what the language already provides)\n# Write three simple functions: root, addOne, and half\n# Derive Writer monad versions of each of these functions\n# Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio \u03c6, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.)\n\n", "solution": "\"\"\"A Writer Monad. Requires Python >= 3.7 for type hints.\"\"\"\nfrom __future__ import annotations\n\nimport functools\nimport math\nimport os\n\nfrom typing import Any\nfrom typing import Callable\nfrom typing import Generic\nfrom typing import List\nfrom typing import TypeVar\nfrom typing import Union\n\n\nT = TypeVar(\"T\")\n\n\nclass Writer(Generic[T]):\n def __init__(self, value: Union[T, Writer[T]], *msgs: str):\n if isinstance(value, Writer):\n self.value: T = value.value\n self.msgs: List[str] = value.msgs + list(msgs)\n else:\n self.value = value\n self.msgs = list(f\"{msg}: {self.value}\" for msg in msgs)\n\n def bind(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:\n writer = func(self.value)\n return Writer(writer, *self.msgs)\n\n def __rshift__(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:\n return self.bind(func)\n\n def __str__(self):\n return f\"{self.value}\\n{os.linesep.join(reversed(self.msgs))}\"\n\n def __repr__(self):\n return f\"Writer({self.value}, \\\"{', '.join(reversed(self.msgs))}\\\")\"\n\n\ndef lift(func: Callable, msg: str) -> Callable[[Any], Writer[Any]]:\n \"\"\"Return a writer monad version of the simple function `func`.\"\"\"\n\n @functools.wraps(func)\n def wrapped(value):\n return Writer(func(value), msg)\n\n return wrapped\n\n\nif __name__ == \"__main__\":\n square_root = lift(math.sqrt, \"square root\")\n add_one = lift(lambda x: x + 1, \"add one\")\n half = lift(lambda x: x / 2, \"div two\")\n\n print(Writer(5, \"initial\") >> square_root >> add_one >> half)\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 \u00a0 '''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:* \u00a0 Encode and decode the following three strings of characters using the symbol table of the lowercase characters \u00a0 '''a'''-to-'''z''' \u00a0 as above. \n:* \u00a0 Show the strings and their encoding here.\n:* \u00a0 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"} +{"title": "Move-to-front algorithm", "language": "JavaScript", "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 \u00a0 '''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:* \u00a0 Encode and decode the following three strings of characters using the symbol table of the lowercase characters \u00a0 '''a'''-to-'''z''' \u00a0 as above. \n:* \u00a0 Show the strings and their encoding here.\n:* \u00a0 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": "var encodeMTF = function (word) {\n var init = {wordAsNumbers: [], charList: 'abcdefghijklmnopqrstuvwxyz'.split('')};\n\n return word.split('').reduce(function (acc, char) {\n var charNum = acc.charList.indexOf(char); //get index of char\n acc.wordAsNumbers.push(charNum); //add original index to acc\n acc.charList.unshift(acc.charList.splice(charNum, 1)[0]); //put at beginning of list\n return acc;\n }, init).wordAsNumbers; //return number list\n};\n\nvar decodeMTF = function (numList) {\n var init = {word: '', charList: 'abcdefghijklmnopqrstuvwxyz'.split('')};\n\n return numList.reduce(function (acc, num) {\n acc.word += acc.charList[num];\n acc.charList.unshift(acc.charList.splice(num, 1)[0]); //put at beginning of list\n return acc;\n }, init).word;\n};\n\n//test our algorithms\nvar words = ['broood', 'bananaaa', 'hiphophiphop'];\nvar encoded = words.map(encodeMTF);\nvar decoded = encoded.map(decodeMTF);\n\n//print results\nconsole.log(\"from encoded:\");\nconsole.log(encoded);\nconsole.log(\"from decoded:\");\nconsole.log(decoded);"} +{"title": "Move-to-front algorithm", "language": "Python", "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 \u00a0 '''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:* \u00a0 Encode and decode the following three strings of characters using the symbol table of the lowercase characters \u00a0 '''a'''-to-'''z''' \u00a0 as above. \n:* \u00a0 Show the strings and their encoding here.\n:* \u00a0 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": "from __future__ import print_function\nfrom string import ascii_lowercase\n\nSYMBOLTABLE = list(ascii_lowercase)\n\ndef move2front_encode(strng, symboltable):\n sequence, pad = [], symboltable[::]\n for char in strng:\n indx = pad.index(char)\n sequence.append(indx)\n pad = [pad.pop(indx)] + pad\n return sequence\n\ndef move2front_decode(sequence, symboltable):\n chars, pad = [], symboltable[::]\n for indx in sequence:\n char = pad[indx]\n chars.append(char)\n pad = [pad.pop(indx)] + pad\n return ''.join(chars)\n\nif __name__ == '__main__':\n for s in ['broood', 'bananaaa', 'hiphophiphop']:\n encode = move2front_encode(s, SYMBOLTABLE)\n print('%14r encodes to %r' % (s, encode), end=', ')\n decode = move2front_decode(encode, SYMBOLTABLE)\n print('which decodes back to %r' % decode)\n assert s == decode, 'Whoops!'"} +{"title": "Multi-dimensional array", "language": "C", "task": "For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. \n\nIt is enough to:\n# State the number and extent of each index to the array.\n# Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value.\n# Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position.\n\n\n;Task:\n* State if the language supports multi-dimensional arrays in its syntax and usual implementation.\n* State whether the language uses [https://en.wikipedia.org/wiki/Row-major_order row-major or column major order] for multi-dimensional array storage, or any other relevant kind of storage.\n* Show how to create a four dimensional array in your language and set, access, set to another value; and access the new value of an integer-indexed item of the array. The idiomatic method for the language is preferred.\n:* The array should allow a range of five, four, three and two (or two three four five if convenient), in each of the indices, in order. (For example, ''if'' indexing starts at zero for the first index then a range of 0..4 inclusive would suffice).\n* State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated.\n* If the language has exceptional native multi-dimensional array support such as optional bounds checking, reshaping, or being able to state both the lower and upper bounds of index ranges, then this is the task to mention them.\n\n\nShow all output here, (but you may judiciously use ellipses to shorten repetitive output text).\n\n", "solution": "\n\n#include\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": "Multi-dimensional array", "language": "Python", "task": "For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. \n\nIt is enough to:\n# State the number and extent of each index to the array.\n# Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value.\n# Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position.\n\n\n;Task:\n* State if the language supports multi-dimensional arrays in its syntax and usual implementation.\n* State whether the language uses [https://en.wikipedia.org/wiki/Row-major_order row-major or column major order] for multi-dimensional array storage, or any other relevant kind of storage.\n* Show how to create a four dimensional array in your language and set, access, set to another value; and access the new value of an integer-indexed item of the array. The idiomatic method for the language is preferred.\n:* The array should allow a range of five, four, three and two (or two three four five if convenient), in each of the indices, in order. (For example, ''if'' indexing starts at zero for the first index then a range of 0..4 inclusive would suffice).\n* State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated.\n* If the language has exceptional native multi-dimensional array support such as optional bounds checking, reshaping, or being able to state both the lower and upper bounds of index ranges, then this is the task to mention them.\n\n\nShow all output here, (but you may judiciously use ellipses to shorten repetitive output text).\n\n", "solution": ">>> from numpy import *\n>>> \n>>> mdarray = zeros((2, 3, 4, 5), dtype=int8, order='F')\n\n>>> mdarray\narray([[[[0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0]],\n\n [[0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0]],\n\n [[0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0]]],\n\n\n [[[0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0]],\n\n [[0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0]],\n\n [[0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0]]]], dtype=int8)\n>>> mdarray[0, 1, 2, 3]\n0\n>>> mdarray[0, 1, 2, 3] = 123\n>>> mdarray[0, 1, 2, 3]\n123\n>>> mdarray[0, 1, 2, 3] = 666\n>>> mdarray[0, 1, 2, 3]\n-102\n>>> mdarray[0, 1, 2, 3] = 255\n>>> mdarray[0, 1, 2, 3]\n-1\n>>> mdarray[0, 1, 2, 3] = -128\n>>> mdarray[0, 1, 2, 3]\n-128\n>>> mdarray\narray([[[[ 0, 0, 0, 0, 0],\n [ 0, 0, 0, 0, 0],\n [ 0, 0, 0, 0, 0],\n [ 0, 0, 0, 0, 0]],\n\n [[ 0, 0, 0, 0, 0],\n [ 0, 0, 0, 0, 0],\n [ 0, 0, 0, -128, 0],\n [ 0, 0, 0, 0, 0]],\n\n [[ 0, 0, 0, 0, 0],\n [ 0, 0, 0, 0, 0],\n [ 0, 0, 0, 0, 0],\n [ 0, 0, 0, 0, 0]]],\n\n\n [[[ 0, 0, 0, 0, 0],\n [ 0, 0, 0, 0, 0],\n [ 0, 0, 0, 0, 0],\n [ 0, 0, 0, 0, 0]],\n\n [[ 0, 0, 0, 0, 0],\n [ 0, 0, 0, 0, 0],\n [ 0, 0, 0, 0, 0],\n [ 0, 0, 0, 0, 0]],\n\n [[ 0, 0, 0, 0, 0],\n [ 0, 0, 0, 0, 0],\n [ 0, 0, 0, 0, 0],\n [ 0, 0, 0, 0, 0]]]], dtype=int8)\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\n[http://mathworld.wolfram.com/Multifactorial.html Multifactorials] 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 [http://mathworld.wolfram.com/Multifactorial.html Wolfram mathworld definition].\n\n", "solution": "\n/* 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": "Multifactorial", "language": "JavaScript", "task": "The factorial of a number, written as n!, is defined as n! = n(n-1)(n-2)...(2)(1).\n\n[http://mathworld.wolfram.com/Multifactorial.html Multifactorials] 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 [http://mathworld.wolfram.com/Multifactorial.html Wolfram mathworld definition].\n\n", "solution": "\nfunction test (n, deg) {\n\tfor (var i = 1; i <= deg; i ++) {\n\t\tvar results = '';\n\t\tfor (var j = 1; j <= n; j ++) {\n\t\t\tresults += multifact(j, i) + ' ';\n\t\t}\n\t\tconsole.log('Degree ' + i + ': ' + results);\n\t}\n}\n"} +{"title": "Multifactorial", "language": "Python", "task": "The factorial of a number, written as n!, is defined as n! = n(n-1)(n-2)...(2)(1).\n\n[http://mathworld.wolfram.com/Multifactorial.html Multifactorials] 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 [http://mathworld.wolfram.com/Multifactorial.html Wolfram mathworld definition].\n\n", "solution": ">>> from functools import reduce\n>>> from operator import mul\n>>> def mfac(n, m): return reduce(mul, range(n, 0, -m))\n\n>>> for m in range(1, 11): print(\"%2i: %r\" % (m, [mfac(n, m) for n in range(1, 11)]))\n\n 1: [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]\n 2: [1, 2, 3, 8, 15, 48, 105, 384, 945, 3840]\n 3: [1, 2, 3, 4, 10, 18, 28, 80, 162, 280]\n 4: [1, 2, 3, 4, 5, 12, 21, 32, 45, 120]\n 5: [1, 2, 3, 4, 5, 6, 14, 24, 36, 50]\n 6: [1, 2, 3, 4, 5, 6, 7, 16, 27, 40]\n 7: [1, 2, 3, 4, 5, 6, 7, 8, 18, 30]\n 8: [1, 2, 3, 4, 5, 6, 7, 8, 9, 20]\n 9: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n10: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\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": "Multiple distinct objects", "language": "JavaScript", "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": "(n => {\n\n let nObjects = n => Array.from({\n length: n + 1\n }, (_, i) => {\n // optionally indexed object constructor\n return {\n index: i\n };\n });\n\n return nObjects(6);\n\n})(6);"} +{"title": "Multiple distinct objects", "language": "Python", "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()] * n # here Foo() can be any expression that returns a new object"} +{"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 \u201ca!===b=!=c\u201d and the separators \u201c==\u201d, \u201c!=\u201d and \u201c=\u201d.\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": "Multisplit", "language": "JavaScript", "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 \u201ca!===b=!=c\u201d and the separators \u201c==\u201d, \u201c!=\u201d and \u201c=\u201d.\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": "(() => {\n\n /// Delimiter list -> String -> list of parts, delimiters, offsets\n\n // multiSplit :: [String] -> String ->\n // [{part::String, delim::String, offset::Int}]\n const multiSplit = (ds, s) => {\n const\n dcs = map(chars, ds),\n xs = chars(s),\n dct = foldl(\n (a, c, i, s) => {\n const\n inDelim = a.offset > i,\n mb = inDelim ? (\n nothing('')\n ) : find(d => isPrefixOf(d, drop(i, xs)), dcs);\n return mb.nothing ? {\n tokens: a.tokens.concat(inDelim ? (\n []\n ) : [c]),\n parts: a.parts,\n offset: a.offset\n } : {\n tokens: [],\n parts: append(a.parts, [{\n part: intercalate('', a.tokens),\n delim: intercalate('', mb.just),\n offset: i\n }]),\n offset: i + length(mb.just)\n };\n }, {\n tokens: [],\n parts: [],\n offset: 0\n }, xs\n );\n return append(dct.parts, [{\n part: intercalate('', dct.tokens),\n delim: \"\",\n offset: length(s)\n }]);\n };\n\n // GENERIC FUNCTIONS -----------------------------------------------------\n\n // append (++) :: [a] -> [a] -> [a]\n const append = (xs, ys) => xs.concat(ys);\n\n // chars :: String -> [Char]\n const chars = s => s.split('');\n\n // drop :: Int -> [a] -> [a]\n // drop :: Int -> String -> String\n const drop = (n, xs) => xs.slice(n);\n\n // find :: (a -> Bool) -> [a] -> Maybe a\n const find = (p, xs) => {\n for (var i = 0, lng = xs.length; i < lng; i++) {\n var x = xs[i];\n if (p(x)) return just(x);\n }\n return nothing('Not found');\n };\n\n // foldl :: (a -> b -> a) -> a -> [b] -> a\n const foldl = (f, a, xs) => xs.reduce(f, a);\n\n // intercalate :: String -> [String] -> String\n const intercalate = (s, xs) => xs.join(s);\n\n // isPrefixOf takes two lists or strings and returns\n // true iff the first is a prefix of the second.\n // isPrefixOf :: [a] -> [a] -> Bool\n // isPrefixOf :: String -> String -> Bool\n const isPrefixOf = (xs, ys) => {\n const pfx = (xs, ys) => xs.length ? (\n ys.length ? xs[0] === ys[0] && pfx(\n xs.slice(1), ys.slice(1)\n ) : false\n ) : true;\n return typeof xs !== 'string' ? pfx(xs, ys) : ys.startsWith(xs);\n };\n\n // just :: a -> Just a\n const just = x => ({\n nothing: false,\n just: x\n });\n\n // length :: [a] -> Int\n const length = xs => xs.length;\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) => xs.map(f);\n\n // nothing :: () -> Nothing\n const nothing = (optionalMsg) => ({\n nothing: true,\n msg: optionalMsg\n });\n\n // show :: Int -> a -> Indented String\n // show :: a -> String\n const show = (...x) =>\n JSON.stringify.apply(\n null, x.length > 1 ? [x[1], null, x[0]] : x\n );\n\n // TEST ------------------------------------------------------------------\n const\n strTest = 'a!===b=!=c',\n delims = ['==', '!=', '='];\n\n return show(2,\n multiSplit(delims, strTest)\n );\n})();"} +{"title": "Multisplit", "language": "Python", "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 \u201ca!===b=!=c\u201d and the separators \u201c==\u201d, \u201c!=\u201d and \u201c=\u201d.\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": "def min_pos(List):\n\treturn List.index(min(List))\n\ndef find_all(S, Sub, Start = 0, End = -1, IsOverlapped = 0):\n\tRes = []\n\tif End == -1:\n\t\tEnd = len(S)\n\tif IsOverlapped:\n\t\tDeltaPos = 1\n\telse:\n\t\tDeltaPos = len(Sub)\n\tPos = Start\n\twhile True:\n\t\tPos = S.find(Sub, Pos, End)\n\t\tif Pos == -1:\n\t\t\tbreak\n\t\tRes.append(Pos)\n\t\tPos += DeltaPos\n\treturn Res\n\ndef multisplit(S, SepList):\n\tSepPosListList = []\n\tSLen = len(S)\n\tSepNumList = []\n\tListCount = 0\n\tfor i, Sep in enumerate(SepList):\n\t\tSepPosList = find_all(S, Sep, 0, SLen, IsOverlapped = 1)\n\t\tif SepPosList != []:\n\t\t\tSepNumList.append(i)\n\t\t\tSepPosListList.append(SepPosList)\n\t\t\tListCount += 1\n\tif ListCount == 0:\n\t\treturn [S]\n\tMinPosList = []\n\tfor i in range(ListCount):\n\t\tMinPosList.append(SepPosListList[i][0])\n\tSepEnd = 0\n\tMinPosPos = min_pos(MinPosList)\n\tRes = []\n\twhile True:\n\t\tRes.append( S[SepEnd : MinPosList[MinPosPos]] )\n\t\tRes.append([SepNumList[MinPosPos], MinPosList[MinPosPos]])\n\t\tSepEnd = MinPosList[MinPosPos] + len(SepList[SepNumList[MinPosPos]])\n\t\twhile True:\n\t\t\tMinPosPos = min_pos(MinPosList)\n\t\t\tif MinPosList[MinPosPos] < SepEnd:\n\t\t\t\tdel SepPosListList[MinPosPos][0]\n\t\t\t\tif len(SepPosListList[MinPosPos]) == 0:\n\t\t\t\t\tdel SepPosListList[MinPosPos]\n\t\t\t\t\tdel MinPosList[MinPosPos]\n\t\t\t\t\tdel SepNumList[MinPosPos]\n\t\t\t\t\tListCount -= 1\n\t\t\t\t\tif ListCount == 0:\n\t\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tMinPosList[MinPosPos] = SepPosListList[MinPosPos][0]\n\t\t\telse:\n\t\t\t\tbreak\n\t\tif ListCount == 0:\n\t\t\tbreak\n\tRes.append(S[SepEnd:])\n\treturn Res\n\n\nS = \"a!===b=!=c\"\nmultisplit(S, [\"==\", \"!=\", \"=\"]) # output: ['a', [1, 1], '', [0, 3], 'b', [2, 6], '', [1, 7], 'c']\nmultisplit(S, [\"=\", \"!=\", \"==\"]) # output: ['a', [1, 1], '', [0, 3], '', [0, 4], 'b', [0, 6], '', [1, 7], 'c']"} +{"title": "Multisplit", "language": "Python 3.7", "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 \u201ca!===b=!=c\u201d and the separators \u201c==\u201d, \u201c!=\u201d and \u201c=\u201d.\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": "'''Multisplit'''\n\n\nfrom functools import reduce\n\n\n# multiSplit :: [String] -> String -> [(String, String, Int)]\ndef multiSplit(separators):\n '''List of triples:\n [(token, separator, start index of separator].\n '''\n def go(s):\n def f(tokensPartsOffset, ic):\n tokens, parts, offset = tokensPartsOffset\n i, c = ic\n inDelim = offset > i\n return maybe(\n (\n tokens if inDelim\n else c + tokens, parts, offset\n )\n )(\n lambda x: (\n '',\n [(tokens, x, i)] + parts,\n i + len(x)\n )\n )(\n None if inDelim else find(\n s[i:].startswith\n )(separators)\n )\n ts, ps, _ = reduce(f, enumerate(s), ('', [], 0))\n return list(reversed(ps)) + [(ts, '', len(s))]\n return go\n\n\n# ------------------------- TEST -------------------------\n# main :: IO ()\ndef main():\n '''String split on three successive separators.'''\n print(\n multiSplit(['==', '!=', '='])(\n 'a!===b=!=c'\n )\n )\n\n\n# ------------------ GENERIC FUNCTIONS -------------------\n\n# find :: (a -> Bool) -> [a] -> (a | None)\ndef find(p):\n '''Just the first element in the list that matches p,\n or None if no elements match.\n '''\n def go(xs):\n try:\n return next(x for x in xs if p(x))\n except StopIteration:\n return None\n return go\n\n\n# maybe :: b -> (a -> b) -> (a | None) -> b\ndef maybe(v):\n '''Either the default value v, if m is None,\n or the application of f to x.\n '''\n return lambda f: lambda m: v if (\n None is m\n ) else f(m)\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} +{"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: '''M\u00fcnchhausen'''.) \n\nFor instance: \u00a0 3435 = 33 + 44 + 33 + 55 \n\n\n;Task\nFind all Munchausen numbers between \u00a0 '''1''' \u00a0 and \u00a0 '''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": "Munchausen numbers", "language": "JavaScript", "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: '''M\u00fcnchhausen'''.) \n\nFor instance: \u00a0 3435 = 33 + 44 + 33 + 55 \n\n\n;Task\nFind all Munchausen numbers between \u00a0 '''1''' \u00a0 and \u00a0 '''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": "for (let i of [...Array(5000).keys()]\n\t.filter(n => n == n.toString().split('')\n\t.reduce((a, b) => a+Math.pow(parseInt(b),parseInt(b)), 0)))\n console.log(i);"} +{"title": "Munchausen numbers", "language": "Python", "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: '''M\u00fcnchhausen'''.) \n\nFor instance: \u00a0 3435 = 33 + 44 + 33 + 55 \n\n\n;Task\nFind all Munchausen numbers between \u00a0 '''1''' \u00a0 and \u00a0 '''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": "for i in range(5000):\n if i == sum(int(x) ** int(x) for x in str(i)):\n print(i)"} +{"title": "Musical scale", "language": "C", "task": "[[Category:Temporal media]]\n\n;Task:\nOutput 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 Solf\u00e8ge.\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": "\n#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": "Musical scale", "language": "Python", "task": "[[Category:Temporal media]]\n\n;Task:\nOutput 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 Solf\u00e8ge.\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": ">>> import winsound\n>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:\n\twinsound.Beep(int(note+.5), 500)\t\n>>> "} +{"title": "Mutex", "language": "POSIX", "task": "[[Category:Encyclopedia]]\n\nA '''mutex''' (''abbreviated'' '''Mut'''ually '''Ex'''clusive access) is a synchronization object, a variant of [[semaphore]] with ''k''=1. \nA mutex is said to be seized by a [[task]] decreasing ''k''. \nIt is released when the task restores ''k''. Mutexes are typically used to protect a shared resource from concurrent access. \nA [[task]] seizes (or acquires) the mutex, then accesses the resource, and after that releases the mutex.\n\nA mutex is a low-level synchronization primitive exposed to deadlocking. A deadlock can occur with just two tasks and two mutexes (if each task attempts to acquire both mutexes, but in the opposite order). \nEntering the deadlock is usually aggravated by a [[race condition]] state, which leads to sporadic hangups, which are very difficult to track down. \n\n=Variants of mutexes=\n\n==Global and local mutexes==\nUsually the [[OS]] provides various implementations of mutexes corresponding to the variants of [[task]]s available in the OS. For example, system-wide mutexes can be used by [[process]]es. Local mutexes can be used only by [[threads]] etc. This distinction is maintained because, depending on the hardware, seizing a global mutex might be a thousand times slower than seizing a local one.\n\n==Reentrant mutex==\nA reentrant mutex can be seized by the same [[task]] multiple times. Each seizing of the mutex is matched by releasing it, in order to allow another task to seize it.\n\n==Read write mutex==\nA read write mutex can be seized at two levels for ''read'' and for ''write''. The mutex can be seized for ''read'' by any number of tasks. Only one task may seize it for '''write''. Read write mutexes are usually used to protect resources which can be accessed in mutable and immutable ways. Immutable (read) access is granted concurrently for many tasks because they do not change the resource state. Read write mutexes can be reentrant, global or local. Further, promotion operations may be provided. That's when a [[task]] that has seized the mutex for ''write'' releases it while keeping seized for ''read''. Note that the reverse operation is potentially deadlocking and requires some additional access policy control.\n\n=Deadlock prevention=\nThere exists a simple technique of deadlock prevention when mutexes are seized in some fixed order. This is discussed in depth in the [[Dining philosophers]] problem.\n\n=Sample implementations / APIs=\n", "solution": "#include \n\npthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;"} +{"title": "Mutex", "language": "Python", "task": "[[Category:Encyclopedia]]\n\nA '''mutex''' (''abbreviated'' '''Mut'''ually '''Ex'''clusive access) is a synchronization object, a variant of [[semaphore]] with ''k''=1. \nA mutex is said to be seized by a [[task]] decreasing ''k''. \nIt is released when the task restores ''k''. Mutexes are typically used to protect a shared resource from concurrent access. \nA [[task]] seizes (or acquires) the mutex, then accesses the resource, and after that releases the mutex.\n\nA mutex is a low-level synchronization primitive exposed to deadlocking. A deadlock can occur with just two tasks and two mutexes (if each task attempts to acquire both mutexes, but in the opposite order). \nEntering the deadlock is usually aggravated by a [[race condition]] state, which leads to sporadic hangups, which are very difficult to track down. \n\n=Variants of mutexes=\n\n==Global and local mutexes==\nUsually the [[OS]] provides various implementations of mutexes corresponding to the variants of [[task]]s available in the OS. For example, system-wide mutexes can be used by [[process]]es. Local mutexes can be used only by [[threads]] etc. This distinction is maintained because, depending on the hardware, seizing a global mutex might be a thousand times slower than seizing a local one.\n\n==Reentrant mutex==\nA reentrant mutex can be seized by the same [[task]] multiple times. Each seizing of the mutex is matched by releasing it, in order to allow another task to seize it.\n\n==Read write mutex==\nA read write mutex can be seized at two levels for ''read'' and for ''write''. The mutex can be seized for ''read'' by any number of tasks. Only one task may seize it for '''write''. Read write mutexes are usually used to protect resources which can be accessed in mutable and immutable ways. Immutable (read) access is granted concurrently for many tasks because they do not change the resource state. Read write mutexes can be reentrant, global or local. Further, promotion operations may be provided. That's when a [[task]] that has seized the mutex for ''write'' releases it while keeping seized for ''read''. Note that the reverse operation is potentially deadlocking and requires some additional access policy control.\n\n=Deadlock prevention=\nThere exists a simple technique of deadlock prevention when mutexes are seized in some fixed order. This is discussed in depth in the [[Dining philosophers]] problem.\n\n=Sample implementations / APIs=\n", "solution": "import threading\nfrom time import sleep\n\n# res: max number of resources. If changed to 1, it functions\n# identically to a mutex/lock object\nres = 2\nsema = threading.Semaphore(res)\n\nclass res_thread(threading.Thread):\n def run(self):\n global res\n n = self.getName()\n for i in range(1, 4):\n # acquire a resource if available and work hard\n # for 2 seconds. if all res are occupied, block\n # and wait\n sema.acquire()\n res = res - 1\n print n, \"+ res count\", res\n sleep(2)\n\n # after done with resource, return it to pool and flag so\n res = res + 1\n print n, \"- res count\", res\n sema.release()\n\n# create 4 threads, each acquire resorce and work\nfor i in range(1, 5):\n t = res_thread()\n t.start()"} +{"title": "Narcissist", "language": "C", "task": "Quoting from the [http://esolangs.org/wiki/Narcissist 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": "Narcissist", "language": "SpiderMonkey 1.7.0", "task": "Quoting from the [http://esolangs.org/wiki/Narcissist 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": "var code='var q=String.fromCharCode(39);print(\"var code=\" + q + code + q + \"; eval(code)\" == readline())'; eval(code)"} +{"title": "Narcissist", "language": "JScript", "task": "Quoting from the [http://esolangs.org/wiki/Narcissist 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": "var oFSO = new ActiveXObject(\"Scripting.FileSystemObject\");\nfunction readfile(fname) {\n\tvar h = oFSO.OpenTextFile(fname, 1, false);\n\tvar result = h.ReadAll();\n\th.Close();\n\treturn result;\n}\n\nif (0 === WScript.Arguments.UnNamed.Count) {\n\tWScript.Echo(WScript.ScriptName,\"filename\");\n\tWScript.Quit();\n}\n\n// first read self \nvar self = readfile(WScript.ScriptFullName);\n// read whatever file is given on commmand line\nvar whatever = readfile(WScript.Arguments.UnNamed(0));\n\n// compare and contrast\nWScript.Echo(self === whatever ? \"Accept\" : \"Reject\");\n"} +{"title": "Narcissist", "language": "Python 2", "task": "Quoting from the [http://esolangs.org/wiki/Narcissist 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": "\nimport sys\nwith open(sys.argv[0]) as quine:\n code = raw_input(\"Enter source code: \")\n if code == quine.read():\n print(\"Accept\")\n else:\n print(\"Reject\")\n"} +{"title": "Narcissist", "language": "Python 3", "task": "Quoting from the [http://esolangs.org/wiki/Narcissist 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": "\n_='_=%r;print (_%%_==input())';print (_%_==input())\n"} +{"title": "Narcissistic decimal number", "language": "C", "task": "A \u00a0 [http://mathworld.wolfram.com/NarcissisticNumber.html Narcissistic decimal number] \u00a0 is a non-negative integer, \u00a0 n, \u00a0 that is equal to the sum of the \u00a0 m-th \u00a0 powers of each of the digits in the decimal representation of \u00a0 n, \u00a0 where \u00a0 m \u00a0 is the number of digits in the decimal representation of \u00a0 n.\n\n\nNarcissistic (decimal) numbers are sometimes called \u00a0 '''Armstrong''' \u00a0 numbers, named after Michael F. Armstrong. \nThey are also known as \u00a0 '''Plus Perfect''' \u00a0 numbers.\n\n\n;An example:\n::::* \u00a0 if \u00a0 n \u00a0 is \u00a0 '''153''' \n::::* \u00a0 then \u00a0 m, \u00a0 (the number of decimal digits) \u00a0 is \u00a0 '''3''' \n::::* \u00a0 we have \u00a0 13 + 53 + 33 \u00a0 = \u00a0 1 + 125 + 27 \u00a0 = \u00a0 '''153''' \n::::* \u00a0 and so \u00a0 '''153''' \u00a0 is a narcissistic decimal number\n\n\n;Task:\nGenerate and show here the first \u00a0 '''25''' \u00a0 narcissistic decimal numbers.\n\n\n\nNote: \u00a0 0^1 = 0, \u00a0 the first in the series. \n\n\n;See also:\n* \u00a0 the \u00a0OEIS entry: \u00a0 \u00a0 [http://oeis.org/A005188 Armstrong (or Plus Perfect, or narcissistic) numbers].\n* \u00a0 MathWorld entry: \u00a0 [http://mathworld.wolfram.com/NarcissisticNumber.html Narcissistic Number].\n* \u00a0 Wikipedia entry: \u00a0 \u00a0 [https://en.wikipedia.org/wiki/Narcissistic_number 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": "Narcissistic decimal number", "language": "JavaScript", "task": "A \u00a0 [http://mathworld.wolfram.com/NarcissisticNumber.html Narcissistic decimal number] \u00a0 is a non-negative integer, \u00a0 n, \u00a0 that is equal to the sum of the \u00a0 m-th \u00a0 powers of each of the digits in the decimal representation of \u00a0 n, \u00a0 where \u00a0 m \u00a0 is the number of digits in the decimal representation of \u00a0 n.\n\n\nNarcissistic (decimal) numbers are sometimes called \u00a0 '''Armstrong''' \u00a0 numbers, named after Michael F. Armstrong. \nThey are also known as \u00a0 '''Plus Perfect''' \u00a0 numbers.\n\n\n;An example:\n::::* \u00a0 if \u00a0 n \u00a0 is \u00a0 '''153''' \n::::* \u00a0 then \u00a0 m, \u00a0 (the number of decimal digits) \u00a0 is \u00a0 '''3''' \n::::* \u00a0 we have \u00a0 13 + 53 + 33 \u00a0 = \u00a0 1 + 125 + 27 \u00a0 = \u00a0 '''153''' \n::::* \u00a0 and so \u00a0 '''153''' \u00a0 is a narcissistic decimal number\n\n\n;Task:\nGenerate and show here the first \u00a0 '''25''' \u00a0 narcissistic decimal numbers.\n\n\n\nNote: \u00a0 0^1 = 0, \u00a0 the first in the series. \n\n\n;See also:\n* \u00a0 the \u00a0OEIS entry: \u00a0 \u00a0 [http://oeis.org/A005188 Armstrong (or Plus Perfect, or narcissistic) numbers].\n* \u00a0 MathWorld entry: \u00a0 [http://mathworld.wolfram.com/NarcissisticNumber.html Narcissistic Number].\n* \u00a0 Wikipedia entry: \u00a0 \u00a0 [https://en.wikipedia.org/wiki/Narcissistic_number Narcissistic number].\n\n", "solution": "function isNarc(x) {\n var str = x.toString(),\n i,\n sum = 0,\n l = str.length;\n if (x < 0) {\n return false;\n } else {\n for (i = 0; i < l; i++) {\n sum += Math.pow(str.charAt(i), l);\n }\n }\n return sum == x;\n}\nfunction main(){\n var n = []; \n for (var x = 0, count = 0; count < 25; x++){\n if (isNarc(x)){\n n.push(x);\n count++;\n }\n }\n return n.join(' '); \n}"} +{"title": "Narcissistic decimal number", "language": "Python", "task": "A \u00a0 [http://mathworld.wolfram.com/NarcissisticNumber.html Narcissistic decimal number] \u00a0 is a non-negative integer, \u00a0 n, \u00a0 that is equal to the sum of the \u00a0 m-th \u00a0 powers of each of the digits in the decimal representation of \u00a0 n, \u00a0 where \u00a0 m \u00a0 is the number of digits in the decimal representation of \u00a0 n.\n\n\nNarcissistic (decimal) numbers are sometimes called \u00a0 '''Armstrong''' \u00a0 numbers, named after Michael F. Armstrong. \nThey are also known as \u00a0 '''Plus Perfect''' \u00a0 numbers.\n\n\n;An example:\n::::* \u00a0 if \u00a0 n \u00a0 is \u00a0 '''153''' \n::::* \u00a0 then \u00a0 m, \u00a0 (the number of decimal digits) \u00a0 is \u00a0 '''3''' \n::::* \u00a0 we have \u00a0 13 + 53 + 33 \u00a0 = \u00a0 1 + 125 + 27 \u00a0 = \u00a0 '''153''' \n::::* \u00a0 and so \u00a0 '''153''' \u00a0 is a narcissistic decimal number\n\n\n;Task:\nGenerate and show here the first \u00a0 '''25''' \u00a0 narcissistic decimal numbers.\n\n\n\nNote: \u00a0 0^1 = 0, \u00a0 the first in the series. \n\n\n;See also:\n* \u00a0 the \u00a0OEIS entry: \u00a0 \u00a0 [http://oeis.org/A005188 Armstrong (or Plus Perfect, or narcissistic) numbers].\n* \u00a0 MathWorld entry: \u00a0 [http://mathworld.wolfram.com/NarcissisticNumber.html Narcissistic Number].\n* \u00a0 Wikipedia entry: \u00a0 \u00a0 [https://en.wikipedia.org/wiki/Narcissistic_number Narcissistic number].\n\n", "solution": "from __future__ import print_function\nfrom itertools import count, islice\n\ndef narcissists():\n for digits in count(0):\n digitpowers = [i**digits for i in range(10)]\n for n in range(int(10**(digits-1)), 10**digits):\n div, digitpsum = n, 0\n while div:\n div, mod = divmod(div, 10)\n digitpsum += digitpowers[mod]\n if n == digitpsum:\n yield n\n\nfor i, n in enumerate(islice(narcissists(), 25), 1):\n print(n, end=' ')\n if i % 5 == 0: print() \nprint()"} +{"title": "Nautical bell", "language": "C", "task": "right\n[[Category: Date and time]]\n\n;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": "\n#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": "Nautical bell", "language": "Python", "task": "right\n[[Category: Date and time]]\n\n;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": "import time, calendar, sched, winsound\n\nduration = 750 # Bell duration in ms\nfreq = 1280 # Bell frequency in hertz\nbellchar = \"\\u2407\"\nwatches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',')\n\ndef gap(n=1):\n time.sleep(n * duration / 1000)\noff = gap\n \ndef on(n=1):\n winsound.Beep(freq, n * duration)\n \ndef bong():\n on(); off(0.5)\n\ndef bongs(m):\n for i in range(m):\n print(bellchar, end=' ')\n bong()\n if i % 2:\n print(' ', end='')\n off(0.5)\n print('')\n \nscheds = sched.scheduler(time.time, time.sleep)\n\ndef ships_bell(now=None):\n def adjust_to_half_hour(atime):\n atime[4] = (atime[4] // 30) * 30\n atime[5] = 0\n return atime\n\n debug = now is not None\n rightnow = time.gmtime()\n if not debug:\n now = adjust_to_half_hour( list(rightnow) )\n then = now[::]\n then[4] += 30\n hr, mn = now[3:5]\n watch, b = divmod(int(2 * hr + mn // 30 - 1), 8)\n b += 1\n bells = '%i bell%s' % (b, 's' if b > 1 else ' ')\n if debug:\n print(\"%02i:%02i, %-20s %s\" % (now[3], now[4], watches[watch] + ' watch', bells), end=' ')\n else:\n print(\"%02i:%02i, %-20s %s\" % (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ')\n bongs(b)\n if not debug:\n scheds.enterabs(calendar.timegm(then), 0, ships_bell)\n #print(time.struct_time(then))\n scheds.run()\n\ndef dbg_tester():\n for h in range(24):\n for m in (0, 30):\n if (h,m) == (24,30): break\n ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] )\n \n \nif __name__ == '__main__':\n ships_bell()"} +{"title": "Negative base numbers", "language": "C", "task": "Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).[http://mathworld.wolfram.com/Negabinary.html Negabinary on Wolfram Mathworld][https://en.wikipedia.org/wiki/Negative_base Negative base] on Wikipedia\n\n\n;Task:\n\n*Encode the decimal number 10 as negabinary (expect 11110)\n*Encode the decimal number 146 as negaternary (expect 21102)\n*Encode the decimal number 15 as negadecimal (expect 195)\n*In each of the above cases, convert the encoded number back to decimal.\n\n\n;extra credit:\n\n* supply an integer, that when encoded to base \u00a0 -62 \u00a0 (or something \"higher\"), \u00a0 expresses the name of the language being used \u00a0 (with correct capitalization). \u00a0 If the computer language has non-alphanumeric characters, \u00a0 try to encode them into the negatory numerals, \u00a0 or use other characters instead.\n\n", "solution": "#include \n\nconst char DIGITS[] = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\nconst int DIGITS_LEN = 64;\n\nvoid encodeNegativeBase(long n, long base, char *out) {\n char *ptr = out;\n\n if (base > -1 || base < -62) {\n /* Bounds check*/\n out = \"\";\n return;\n }\n if (n == 0) {\n /* Trivial case */\n out = \"0\";\n return;\n }\n\n /* Convert the number into a string (in reverse) */\n while (n != 0) {\n long rem = n % base;\n n = n / base;\n if (rem < 0) {\n n++;\n rem = rem - base;\n }\n *ptr = DIGITS[rem];\n ptr++;\n }\n *ptr = 0;\n\n /* Reverse the current string to get the final result */\n ptr--;\n while (out < ptr) {\n char t = *out;\n *out = *ptr;\n *ptr = t;\n out++;\n ptr--;\n }\n return;\n}\n\nlong decodeNegativeBase(const char* ns, long base) {\n long value, bb;\n int i;\n const char *ptr;\n\n if (base < -62 || base > -1) {\n /* Bounds check */\n return 0;\n }\n if (ns[0] == 0 || (ns[0] == '0' && ns[1] == 0)) {\n /* Trivial case */\n return 0;\n }\n\n /* Find the end of the string */\n ptr = ns;\n while (*ptr != 0) {\n ptr++;\n }\n\n /* Convert */\n value = 0;\n bb = 1;\n ptr--;\n while (ptr >= ns) {\n for (i = 0; i < DIGITS_LEN; i++) {\n if (*ptr == DIGITS[i]) {\n value = value + i * bb;\n bb = bb * base;\n break;\n }\n }\n ptr--;\n }\n\n return value;\n}\n\nvoid driver(long n, long b) {\n char buf[64];\n long value;\n\n encodeNegativeBase(n, b, buf);\n printf(\"%12d encoded in base %3d = %12s\\n\", n, b, buf);\n\n value = decodeNegativeBase(buf, b);\n printf(\"%12s decoded in base %3d = %12d\\n\", buf, b, value);\n\n printf(\"\\n\");\n}\n\nint main() {\n driver(10, -2);\n driver(146, -3);\n driver(15, -10);\n driver(12, -62);\n\n return 0;\n}"} +{"title": "Negative base numbers", "language": "Python", "task": "Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).[http://mathworld.wolfram.com/Negabinary.html Negabinary on Wolfram Mathworld][https://en.wikipedia.org/wiki/Negative_base Negative base] on Wikipedia\n\n\n;Task:\n\n*Encode the decimal number 10 as negabinary (expect 11110)\n*Encode the decimal number 146 as negaternary (expect 21102)\n*Encode the decimal number 15 as negadecimal (expect 195)\n*In each of the above cases, convert the encoded number back to decimal.\n\n\n;extra credit:\n\n* supply an integer, that when encoded to base \u00a0 -62 \u00a0 (or something \"higher\"), \u00a0 expresses the name of the language being used \u00a0 (with correct capitalization). \u00a0 If the computer language has non-alphanumeric characters, \u00a0 try to encode them into the negatory numerals, \u00a0 or use other characters instead.\n\n", "solution": "#!/bin/python\nfrom __future__ import print_function\n\ndef EncodeNegBase(n, b): #Converts from decimal\n\tif n == 0:\n\t\treturn \"0\"\n\tout = []\n\twhile n != 0:\n\t\tn, rem = divmod(n, b)\n\t\tif rem < 0:\n\t\t\tn += 1\n\t\t\trem -= b\n\t\tout.append(rem)\n\treturn \"\".join(map(str, out[::-1]))\n\ndef DecodeNegBase(nstr, b): #Converts to decimal\n\tif nstr == \"0\":\n\t\treturn 0\n\t\n\ttotal = 0\n\tfor i, ch in enumerate(nstr[::-1]):\n\t\ttotal += int(ch) * b**i\n\treturn total\n\nif __name__==\"__main__\":\n\t\n\tprint (\"Encode 10 as negabinary (expect 11110)\")\n\tresult = EncodeNegBase(10, -2)\n\tprint (result)\n\tif DecodeNegBase(result, -2) == 10: print (\"Converted back to decimal\")\n\telse: print (\"Error converting back to decimal\")\n\n\tprint (\"Encode 146 as negaternary (expect 21102)\")\n\tresult = EncodeNegBase(146, -3)\n\tprint (result)\n\tif DecodeNegBase(result, -3) == 146: print (\"Converted back to decimal\")\n\telse: print (\"Error converting back to decimal\")\n\n\tprint (\"Encode 15 as negadecimal (expect 195)\")\n\tresult = EncodeNegBase(15, -10)\n\tprint (result)\n\tif DecodeNegBase(result, -10) == 15: print (\"Converted back to decimal\")\n\telse: print (\"Error converting back to decimal\")"} +{"title": "Nested function", "language": "C", "task": "[[Category:Scope]][[Category:Functions and subroutines]]\n\nIn 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": "\n#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": "Nested function", "language": "JavaScript", "task": "[[Category:Scope]][[Category:Functions and subroutines]]\n\nIn 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": "function makeList(separator) {\n var counter = 1;\n\n function makeItem(item) {\n return counter++ + separator + item + \"\\n\";\n }\n\n return makeItem(\"first\") + makeItem(\"second\") + makeItem(\"third\");\n}\n\nconsole.log(makeList(\". \"));"} +{"title": "Nested function", "language": "Python 3+", "task": "[[Category:Scope]][[Category:Functions and subroutines]]\n\nIn 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": "def makeList(separator):\n counter = 1\n\n def makeItem(item):\n nonlocal counter\n result = str(counter) + separator + item + \"\\n\"\n counter += 1\n return result\n\n return makeItem(\"first\") + makeItem(\"second\") + makeItem(\"third\")\n\nprint(makeList(\". \"))"} +{"title": "Nested templated data", "language": "Python", "task": "A template for data is an arbitrarily nested tree of integer indices.\n \nData payloads are given as a separate mapping, array or other simpler, flat,\nassociation of indices to individual items of data, and are strings.\nThe idea is to create a data structure with the templates' nesting, and the \npayload corresponding to each index appearing at the position of each index.\n\nAnswers using simple string replacement or regexp are to be avoided. The idea is \nto use the native, or usual implementation of lists/tuples etc of the language\nand to hierarchically traverse the template to generate the output.\n\n;Task Detail:\nGiven the following input template t and list of payloads p:\n# Square brackets are used here to denote nesting but may be changed for other,\n# clear, visual representations of nested data appropriate to ones programming \n# language.\nt = [\n [[1, 2],\n [3, 4, 1], \n 5]]\n\np = 'Payload#0' ... 'Payload#6'\n\nThe correct output should have the following structure, (although spacing and \nlinefeeds may differ, the nesting and order should follow):\n[[['Payload#1', 'Payload#2'],\n ['Payload#3', 'Payload#4', 'Payload#1'],\n 'Payload#5']]\n\n1. Generate the output for the above template, t.\n\n;Optional Extended tasks:\n2. Show which payloads remain unused.\n3. Give some indication/handling of indices without a payload.\n\n''Show output on this page.''\n\n", "solution": "from pprint import pprint as pp\n\nclass Template():\n def __init__(self, structure):\n self.structure = structure\n self.used_payloads, self.missed_payloads = [], []\n \n def inject_payload(self, id2data):\n \n def _inject_payload(substruct, i2d, used, missed):\n used.extend(i2d[x] for x in substruct if type(x) is not tuple and x in i2d)\n missed.extend(f'??#{x}' \n for x in substruct if type(x) is not tuple and x not in i2d)\n return tuple(_inject_payload(x, i2d, used, missed) \n if type(x) is tuple \n else i2d.get(x, f'??#{x}') \n for x in substruct)\n \n ans = _inject_payload(self.structure, id2data, \n self.used_payloads, self.missed_payloads)\n self.unused_payloads = sorted(set(id2data.values()) \n - set(self.used_payloads))\n self.missed_payloads = sorted(set(self.missed_payloads))\n return ans\n\nif __name__ == '__main__':\n index2data = {p: f'Payload#{p}' for p in range(7)}\n print(\"##PAYLOADS:\\n \", end='')\n print('\\n '.join(list(index2data.values())))\n for structure in [\n (((1, 2),\n (3, 4, 1),\n 5),),\n \n (((1, 2),\n (10, 4, 1),\n 5),)]:\n print(\"\\n\\n# TEMPLATE:\")\n pp(structure, width=13)\n print(\"\\n TEMPLATE WITH PAYLOADS:\")\n t = Template(structure)\n out = t.inject_payload(index2data)\n pp(out)\n print(\"\\n UNUSED PAYLOADS:\\n \", end='')\n unused = t.unused_payloads\n print('\\n '.join(unused) if unused else '-')\n print(\" MISSING PAYLOADS:\\n \", end='')\n missed = t.missed_payloads\n print('\\n '.join(missed) if missed else '-')"} +{"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* \u00a0 Numbers will not be padded to the left with zeroes.\n* \u00a0 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* \u00a0 If there is no next highest integer return zero.\n\n\n:*1 \u00a0 Alternatively phrased as: \u00a0 \"Find the smallest integer larger than the (positive or zero) integer \u00a0 '''N''' \n:: which can be obtained by reordering the (base ten) digits of \u00a0 '''N'''\".\n\n\n;Algorithm 1:\n# \u00a0 Generate all the permutations of the digits and sort into numeric order.\n# \u00a0 Find the number in the list.\n# \u00a0 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# \u00a0 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# \u00a0 Exchange that digit with the digit on the right that is ''both'' more than it, and closest to it.\n# \u00a0 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), \u00a0 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:* \u00a0 0\n:* \u00a0 9\n:* \u00a0 12\n:* \u00a0 21\n:* \u00a0 12453\n:* \u00a0 738440\n:* \u00a0 45072010\n:* \u00a0 95322020\n\n\n;Optional stretch goal:\n:* \u00a0 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": "Next highest int from digits", "language": "JavaScript", "task": "Given a zero or positive integer, the task is to generate the next largest\ninteger using only the given digits*1.\n\n* \u00a0 Numbers will not be padded to the left with zeroes.\n* \u00a0 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* \u00a0 If there is no next highest integer return zero.\n\n\n:*1 \u00a0 Alternatively phrased as: \u00a0 \"Find the smallest integer larger than the (positive or zero) integer \u00a0 '''N''' \n:: which can be obtained by reordering the (base ten) digits of \u00a0 '''N'''\".\n\n\n;Algorithm 1:\n# \u00a0 Generate all the permutations of the digits and sort into numeric order.\n# \u00a0 Find the number in the list.\n# \u00a0 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# \u00a0 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# \u00a0 Exchange that digit with the digit on the right that is ''both'' more than it, and closest to it.\n# \u00a0 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), \u00a0 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:* \u00a0 0\n:* \u00a0 9\n:* \u00a0 12\n:* \u00a0 21\n:* \u00a0 12453\n:* \u00a0 738440\n:* \u00a0 45072010\n:* \u00a0 95322020\n\n\n;Optional stretch goal:\n:* \u00a0 9589776899767587796600\n\n", "solution": "const compose = (...fn) => (...x) => fn.reduce((a, b) => c => a(b(c)))(...x);\nconst toString = x => x + '';\nconst reverse = x => Array.from(x).reduce((p, c) => [c, ...p], []);\nconst minBiggerThanN = (arr, n) => arr.filter(e => e > n).sort()[0];\nconst remEl = (arr, e) => {\n const r = arr.indexOf(e);\n return arr.filter((e,i) => i !== r);\n}\n\nconst nextHighest = itr => {\n const seen = [];\n let result = 0;\n for (const [i,v] of itr.entries()) {\n const n = +v;\n if (Math.max(n, ...seen) !== n) {\n const right = itr.slice(i + 1);\n const swap = minBiggerThanN(seen, n);\n const rem = remEl(seen, swap);\n const rest = [n, ...rem].sort();\n result = [...reverse(right), swap, ...rest].join('');\n break;\n } else {\n seen.push(n);\n }\n }\n return result;\n};\n\nconst check = compose(nextHighest, reverse, toString);\n\nconst test = v => {\n console.log(v, '=>', check(v));\n}\n\ntest(0);\ntest(9);\ntest(12);\ntest(21);\ntest(12453);\ntest(738440);\ntest(45072010);\ntest(95322020);\ntest('9589776899767587796600');\n"} +{"title": "Next highest int from digits", "language": "Python", "task": "Given a zero or positive integer, the task is to generate the next largest\ninteger using only the given digits*1.\n\n* \u00a0 Numbers will not be padded to the left with zeroes.\n* \u00a0 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* \u00a0 If there is no next highest integer return zero.\n\n\n:*1 \u00a0 Alternatively phrased as: \u00a0 \"Find the smallest integer larger than the (positive or zero) integer \u00a0 '''N''' \n:: which can be obtained by reordering the (base ten) digits of \u00a0 '''N'''\".\n\n\n;Algorithm 1:\n# \u00a0 Generate all the permutations of the digits and sort into numeric order.\n# \u00a0 Find the number in the list.\n# \u00a0 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# \u00a0 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# \u00a0 Exchange that digit with the digit on the right that is ''both'' more than it, and closest to it.\n# \u00a0 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), \u00a0 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:* \u00a0 0\n:* \u00a0 9\n:* \u00a0 12\n:* \u00a0 21\n:* \u00a0 12453\n:* \u00a0 738440\n:* \u00a0 45072010\n:* \u00a0 95322020\n\n\n;Optional stretch goal:\n:* \u00a0 9589776899767587796600\n\n", "solution": "def closest_more_than(n, lst):\n \"(index of) closest int from lst, to n that is also > n\"\n large = max(lst) + 1\n return lst.index(min(lst, key=lambda x: (large if x <= n else x)))\n\ndef nexthigh(n):\n \"Return nxt highest number from n's digits using scan & re-order\"\n assert n == int(abs(n)), \"n >= 0\"\n this = list(int(digit) for digit in str(int(n)))[::-1]\n mx = this[0]\n for i, digit in enumerate(this[1:], 1):\n if digit < mx:\n mx_index = closest_more_than(digit, this[:i + 1])\n this[mx_index], this[i] = this[i], this[mx_index]\n this[:i] = sorted(this[:i], reverse=True)\n return int(''.join(str(d) for d in this[::-1]))\n elif digit > mx:\n mx, mx_index = digit, i\n return 0\n\n\nif __name__ == '__main__':\n for x in [0, 9, 12, 21, 12453, 738440, 45072010, 95322020,\n 9589776899767587796600]:\n print(f\"{x:>12_d} -> {nexthigh(x):>12_d}\")"} +{"title": "Nim game", "language": "C", "task": "Nim is a simple game where the second player\u2500if they know the trick\u2500will always win.\n\n\nThe game has only 3 rules:\n::* \u00a0 start with \u00a0 '''12''' \u00a0 tokens\n::* \u00a0 each player takes \u00a0 '''1, \u00a02, \u00a0or \u00a03''' \u00a0 tokens in turn\n::* \u00a0the player who takes the last token wins.\n\n\nTo win every time, \u00a0 the second player simply takes 4 minus the number the first player took. \u00a0 So if the first player takes 1, \u00a0 the second takes 3; if the first player takes 2, \u00a0 the second should take 2; and if the first player takes 3, \u00a0 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": "\n#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": "Nim game", "language": "Python", "task": "Nim is a simple game where the second player\u2500if they know the trick\u2500will always win.\n\n\nThe game has only 3 rules:\n::* \u00a0 start with \u00a0 '''12''' \u00a0 tokens\n::* \u00a0 each player takes \u00a0 '''1, \u00a02, \u00a0or \u00a03''' \u00a0 tokens in turn\n::* \u00a0the player who takes the last token wins.\n\n\nTo win every time, \u00a0 the second player simply takes 4 minus the number the first player took. \u00a0 So if the first player takes 1, \u00a0 the second takes 3; if the first player takes 2, \u00a0 the second should take 2; and if the first player takes 3, \u00a0 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": "\nprint(\"Py Nim\\n\")\n\ndef getTokens(curTokens):\n\tglobal tokens\n\t\n\tprint(\"How many tokens would you like to take? \", end='')\n\ttake = int(input())\n\t\n\tif (take < 1 or take > 3):\n\t\tprint(\"Number must be between 1 and 3.\\n\")\n\t\tgetTokens(curTokens)\n\t\treturn\n\t\n\ttokens = curTokens - take\n\tprint(f'You take {take} tokens.')\n\tprint(f'{tokens} tokens remaining.\\n')\n\ndef compTurn(curTokens):\n\tglobal tokens\n\t\n\ttake = curTokens % 4\n\ttokens = curTokens - take\n\tprint (f'Computer takes {take} tokens.')\n\tprint (f'{tokens} tokens remaining.\\n')\n\t\n\ntokens = 12\nwhile (tokens > 0):\n\tgetTokens(tokens)\n\tcompTurn(tokens)\n\nprint(\"Computer wins!\")\n"} +{"title": "Non-transitive dice", "language": "Python", "task": "Let our dice select numbers on their faces with equal probability, i.e. fair dice.\nDice may have more or less than six faces. (The possibility of there being a \n3D physical shape that has that many \"faces\" that allow them to be fair dice,\nis ignored for this task - a die with 3 or 33 defined sides is defined by the \nnumber of faces and the numbers on each face).\n\nThrowing dice will randomly select a face on each die with equal probability.\nTo show which die of dice thrown multiple times is more likely to win over the \nothers:\n# calculate all possible combinations of different faces from each die\n# Count how many times each die wins a combination\n# Each ''combination'' is equally likely so the die with more winning face combinations is statistically more likely to win against the other dice.\n\n\n'''If two dice X and Y are thrown against each other then X likely to: win, lose, or break-even against Y can be shown as: X > Y, X < Y, or X = Y respectively.\n'''\n;Example 1:\nIf X is the three sided die with 1, 3, 6 on its faces and Y has 2, 3, 4 on its\nfaces then the equal possibility outcomes from throwing both, and the winners \nis:\n \n X Y Winner\n = = ======\n 1 2 Y\n 1 3 Y\n 1 4 Y\n 3 2 X\n 3 3 -\n 3 4 Y\n 6 2 X\n 6 3 X\n 6 4 X\n \n TOTAL WINS: X=4, Y=4\n\nBoth die will have the same statistical probability of winning, i.e.their comparison can be written as X = Y\n\n;Transitivity:\nIn mathematics transitivity are rules like: \n if a op b and b op c then a op c\nIf, for example, the op, (for operator), is the familiar less than, <, and it's applied to integers\nwe get the familiar if a < b and b < c then a < c\n\n;Non-transitive dice\nThese are an ordered list of dice where the '>' operation between successive \ndice pairs applies but a comparison between the first and last of the list\nyields the opposite result, '<'.\n''(Similarly '<' successive list comparisons with a final '>' between first and last is also non-transitive).''\n\n\nThree dice S, T, U with appropriate face values could satisfy\n\n S < T, T < U and yet S > U\n\nTo be non-transitive.\n\n;Notes:\n\n* The order of numbers on the faces of a die is not relevant. For example, three faced die described with face numbers of 1, 2, 3 or 2, 1, 3 or any other permutation are equivalent. For the purposes of the task '''show only the permutation in lowest-first sorted order i.e. 1, 2, 3''' (and remove any of its perms).\n* A die can have more than one instance of the same number on its faces, e.g. 2, 3, 3, 4\n* '''Rotations''': Any rotation of non-transitive dice from an answer is also an answer. You may ''optionally'' compute and show only one of each such rotation sets, ideally the first when sorted in a natural way. If this option is used then prominently state in the output that rotations of results are also solutions.\n\n\n;Task:\n;====\nFind all the ordered lists of ''three'' non-transitive dice S, T, U of the form \nS < T, T < U and yet S > U; where the dice are selected from all ''four-faced die''\n, (unique w.r.t the notes), possible by having selections from the integers \n''one to four'' on any dies face.\n\nSolution can be found by generating all possble individual die then testing all\npossible permutations, (permutations are ordered), of three dice for \nnon-transitivity.\n\n;Optional stretch goal:\nFind lists of '''four''' non-transitive dice selected from the same possible dice from the non-stretch goal.\n\n\nShow the results here, on this page.\n\n;References:\n* [https://youtu.be/zzKGnuvX6IQ The Most Powerful Dice] - Numberphile Video.\n* [https://en.wikipedia.org/wiki/Nontransitive_dice Nontransitive dice] - Wikipedia.\n\n", "solution": "from itertools import combinations_with_replacement as cmbr\nfrom time import time\n \ndef dice_gen(n, faces, m):\n dice = list(cmbr(faces, n))\n \n succ = [set(j for j, b in enumerate(dice)\n if sum((x>y) - (x 0)\n for a in dice]\n \n def loops(seq):\n s = succ[seq[-1]]\n\n if len(seq) == m:\n if seq[0] in s: yield seq\n return\n\n for d in (x for x in s if x > seq[0] and not x in seq):\n yield from loops(seq + (d,))\n \n yield from (tuple(''.join(dice[s]) for s in x)\n for i, v in enumerate(succ)\n for x in loops((i,)))\n \nt = time()\nfor n, faces, loop_len in [(4, '1234', 3), (4, '1234', 4), (6, '123456', 3), (6, '1234567', 3)]:\n for i, x in enumerate(dice_gen(n, faces, loop_len)): pass\n \n print(f'{n}-sided, markings {faces}, loop length {loop_len}:')\n print(f'\\t{i + 1}*{loop_len} solutions, e.g. {\" > \".join(x)} > [loop]')\n t, t0 = time(), t\n print(f'\\ttime: {t - t0:.4f} seconds\\n')"} +{"title": "Nonoblock", "language": "C", "task": "Nonoblock is a chip off the old 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# \u00a0 '''5''' \u00a0 cells \u00a0 and \u00a0 '''[2, 1]''' \u00a0 blocks\n# \u00a0 '''5''' \u00a0 cells \u00a0 and \u00a0 '''[]''' \u00a0 blocks \u00a0 (no blocks)\n# \u00a0 '''10''' \u00a0 cells \u00a0 and \u00a0 '''[8]''' \u00a0 blocks\n# \u00a0 '''15''' \u00a0 cells \u00a0 and \u00a0 '''[2, 3, 2, 3]''' \u00a0 blocks\n# \u00a0 '''5''' \u00a0 cells \u00a0 and \u00a0 '''[2, 3]''' \u00a0 blocks \u00a0 (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 [http://paddy3118.blogspot.co.uk/2014/03/nonogram-puzzle-solver-part-1.html 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": "Nonoblock", "language": "JavaScript", "task": "Nonoblock is a chip off the old 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# \u00a0 '''5''' \u00a0 cells \u00a0 and \u00a0 '''[2, 1]''' \u00a0 blocks\n# \u00a0 '''5''' \u00a0 cells \u00a0 and \u00a0 '''[]''' \u00a0 blocks \u00a0 (no blocks)\n# \u00a0 '''10''' \u00a0 cells \u00a0 and \u00a0 '''[8]''' \u00a0 blocks\n# \u00a0 '''15''' \u00a0 cells \u00a0 and \u00a0 '''[2, 3, 2, 3]''' \u00a0 blocks\n# \u00a0 '''5''' \u00a0 cells \u00a0 and \u00a0 '''[2, 3]''' \u00a0 blocks \u00a0 (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 [http://paddy3118.blogspot.co.uk/2014/03/nonogram-puzzle-solver-part-1.html Nonogram puzzle solver (part 1)] Inspired this task and donated its [[Nonoblock#Python]] solution.\n\n", "solution": "const compose = (...fn) => (...x) => fn.reduce((a, b) => c => a(b(c)))(...x);\nconst inv = b => !b;\nconst arrJoin = str => arr => arr.join(str);\nconst mkArr = (l, f) => Array(l).fill(f);\nconst sumArr = arr => arr.reduce((a, b) => a + b, 0);\nconst sumsTo = val => arr => sumArr(arr) === val;\nconst zipper = arr => (p, c, i) => arr[i] ? [...p, c, arr[i]] : [...p, c];\nconst zip = (a, b) => a.reduce(zipper(b), []);\nconst zipArr = arr => a => zip(a, arr);\nconst hasInner = v => arr => arr.slice(1, -1).indexOf(v) >= 0;\nconst choose = (even, odd) => n => n % 2 === 0 ? even : odd;\nconst toBin = f => arr => arr.reduce(\n (p, c, i) => [...p, ...mkArr(c, f(i))], []);\n\n\nconst looper = (arr, max, acc = [[...arr]], idx = 0) => {\n if (idx !== arr.length) {\n const b = looper([...arr], max, acc, idx + 1)[0];\n if (b[idx] !== max) {\n b[idx] = b[idx] + 1;\n acc.push(looper([...b], max, acc, idx)[0]);\n }\n }\n return [arr, acc];\n};\n\nconst gapPerms = (grpSize, numGaps, minVal = 0) => {\n const maxVal = numGaps - grpSize * minVal + minVal;\n return maxVal <= 0\n ? (grpSize === 2 ? [[0]] : [])\n : looper(mkArr(grpSize, minVal), maxVal)[1];\n}\n\nconst test = (cells, ...blocks) => {\n const grpSize = blocks.length + 1;\n const numGaps = cells - sumArr(blocks);\n\n // Filter functions\n const sumsToTrg = sumsTo(numGaps);\n const noInnerZero = compose(inv, hasInner(0));\n\n // Output formatting\n const combine = zipArr([...blocks]);\n const choices = toBin(choose(0, 1));\n const output = compose(console.log, arrJoin(''), choices, combine);\n\n console.log(`\\n${cells} cells. Blocks: ${blocks}`);\n gapPerms(grpSize, numGaps)\n .filter(noInnerZero)\n .filter(sumsToTrg)\n .map(output);\n};\n\ntest(5, 2, 1);\ntest(5);\ntest(5, 5);\ntest(5, 1, 1, 1);\ntest(10, 8);\ntest(15, 2, 3, 2, 3);\ntest(10, 4, 3);\ntest(5, 2, 3);\n"} +{"title": "Nonoblock", "language": "Python", "task": "Nonoblock is a chip off the old 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# \u00a0 '''5''' \u00a0 cells \u00a0 and \u00a0 '''[2, 1]''' \u00a0 blocks\n# \u00a0 '''5''' \u00a0 cells \u00a0 and \u00a0 '''[]''' \u00a0 blocks \u00a0 (no blocks)\n# \u00a0 '''10''' \u00a0 cells \u00a0 and \u00a0 '''[8]''' \u00a0 blocks\n# \u00a0 '''15''' \u00a0 cells \u00a0 and \u00a0 '''[2, 3, 2, 3]''' \u00a0 blocks\n# \u00a0 '''5''' \u00a0 cells \u00a0 and \u00a0 '''[2, 3]''' \u00a0 blocks \u00a0 (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 [http://paddy3118.blogspot.co.uk/2014/03/nonogram-puzzle-solver-part-1.html Nonogram puzzle solver (part 1)] Inspired this task and donated its [[Nonoblock#Python]] solution.\n\n", "solution": "def nonoblocks(blocks, cells):\n if not blocks or blocks[0] == 0:\n yield [(0, 0)]\n else:\n assert sum(blocks) + len(blocks)-1 <= cells, \\\n 'Those blocks will not fit in those cells'\n blength, brest = blocks[0], blocks[1:] # Deal with the first block of length\n minspace4rest = sum(1+b for b in brest) # The other blocks need space\n # Slide the start position from left to max RH index allowing for other blocks.\n for bpos in range(0, cells - minspace4rest - blength + 1):\n if not brest:\n # No other blocks to the right so just yield this one.\n yield [(bpos, blength)]\n else:\n # More blocks to the right so create a *sub-problem* of placing\n # the brest blocks in the cells one space to the right of the RHS of \n # this block.\n offset = bpos + blength +1\n nonoargs = (brest, cells - offset) # Pre-compute arguments to nonoargs\n # recursive call to nonoblocks yields multiple sub-positions\n for subpos in nonoblocks(*nonoargs):\n # Remove the offset from sub block positions\n rest = [(offset + bp, bl) for bp, bl in subpos]\n # Yield this block plus sub blocks positions\n vec = [(bpos, blength)] + rest\n yield vec\n\ndef pblock(vec, cells):\n 'Prettyprints each run of blocks with a different letter A.. for each block of filled cells'\n vector = ['_'] * cells\n for ch, (bp, bl) in enumerate(vec, ord('A')):\n for i in range(bp, bp + bl):\n vector[i] = chr(ch) if vector[i] == '_' else'?'\n return '|' + '|'.join(vector) + '|'\n\n\nif __name__ == '__main__':\n for blocks, cells in (\n ([2, 1], 5),\n ([], 5),\n ([8], 10),\n ([2, 3, 2, 3], 15),\n # ([4, 3], 10),\n # ([2, 1], 5),\n # ([3, 1], 10),\n ([2, 3], 5),\n ):\n print('\\nConfiguration:\\n %s # %i cells and %r blocks' % (pblock([], cells), cells, blocks)) \n print(' Possibilities:')\n for i, vector in enumerate(nonoblocks(blocks, cells)):\n print(' ', pblock(vector, cells))\n print(' A total of %i Possible configurations.' % (i+1))"} +{"title": "Nonogram solver", "language": "Python", "task": "A nonogram is a puzzle that provides \nnumeric clues used to fill in a grid of cells, \nestablishing for each cell whether it is filled or not. \nThe puzzle solution is typically a picture of some kind.\n\nEach row and column of a rectangular grid is annotated with the lengths \nof its distinct runs of occupied cells. \nUsing only these lengths you should find one valid configuration \nof empty and occupied cells, or show a failure message.\n\n;Example\nProblem: Solution:\n\n. . . . . . . . 3 . # # # . . . . 3\n. . . . . . . . 2 1 # # . # . . . . 2 1\n. . . . . . . . 3 2 . # # # . . # # 3 2\n. . . . . . . . 2 2 . . # # . . # # 2 2\n. . . . . . . . 6 . . # # # # # # 6\n. . . . . . . . 1 5 # . # # # # # . 1 5\n. . . . . . . . 6 # # # # # # . . 6\n. . . . . . . . 1 . . . . # . . . 1\n. . . . . . . . 2 . . . # # . . . 2\n1 3 1 7 5 3 4 3 1 3 1 7 5 3 4 3\n2 1 5 1 2 1 5 1 \nThe problem above could be represented by two lists of lists:\nx = [[3], [2,1], [3,2], [2,2], [6], [1,5], [6], [1], [2]]\ny = [[1,2], [3,1], [1,5], [7,1], [5], [3], [4], [3]]\nA more compact representation of the same problem uses strings, \nwhere the letters represent the numbers, A=1, B=2, etc:\nx = \"C BA CB BB F AE F A B\"\ny = \"AB CA AE GA E C D C\"\n\n;Task\nFor this task, try to solve the 4 problems below, read from a \u201cnonogram_problems.txt\u201d file that has this content \n(the blank lines are separators):\nC BA CB BB F AE F A B\nAB CA AE GA E C D C\n\nF CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\nD D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\n\nCA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\nBC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC\n\nE BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\nE CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\n\n'''Extra credit''': generate nonograms with unique solutions, of desired height and width.\n\nThis task is the problem n.98 of the \"[https://sites.google.com/site/prologsite/prolog-problems 99 Prolog Problems]\" by Werner Hett (also thanks to Paul Singleton for the idea and the examples).\n\n; Related tasks\n* [[Nonoblock]].\n\n;See also\n* Arc Consistency Algorithm\n* http://www.haskell.org/haskellwiki/99_questions/Solutions/98 (Haskell)\n* http://twanvl.nl/blog/haskell/Nonograms (Haskell)\n* http://picolisp.com/5000/!wiki?99p98 (PicoLisp)\n\n", "solution": "from itertools import izip\n\ndef gen_row(w, s):\n \"\"\"Create all patterns of a row or col that match given runs.\"\"\"\n def gen_seg(o, sp):\n if not o:\n return [[2] * sp]\n return [[2] * x + o[0] + tail\n for x in xrange(1, sp - len(o) + 2)\n for tail in gen_seg(o[1:], sp - x)]\n\n return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))]\n\n\ndef deduce(hr, vr):\n \"\"\"Fix inevitable value of cells, and propagate.\"\"\"\n def allowable(row):\n return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row)\n\n def fits(a, b):\n return all(x & y for x, y in izip(a, b))\n\n def fix_col(n):\n \"\"\"See if any value in a given column is fixed;\n if so, mark its corresponding row for future fixup.\"\"\"\n c = [x[n] for x in can_do]\n cols[n] = [x for x in cols[n] if fits(x, c)]\n for i, x in enumerate(allowable(cols[n])):\n if x != can_do[i][n]:\n mod_rows.add(i)\n can_do[i][n] &= x\n\n def fix_row(n):\n \"\"\"Ditto, for rows.\"\"\"\n c = can_do[n]\n rows[n] = [x for x in rows[n] if fits(x, c)]\n for i, x in enumerate(allowable(rows[n])):\n if x != can_do[n][i]:\n mod_cols.add(i)\n can_do[n][i] &= x\n\n def show_gram(m):\n # If there's 'x', something is wrong.\n # If there's '?', needs more work.\n for x in m:\n print \" \".join(\"x#.?\"[i] for i in x)\n print\n\n w, h = len(vr), len(hr)\n rows = [gen_row(w, x) for x in hr]\n cols = [gen_row(h, x) for x in vr]\n can_do = map(allowable, rows)\n\n # Initially mark all columns for update.\n mod_rows, mod_cols = set(), set(xrange(w))\n\n while mod_cols:\n for i in mod_cols:\n fix_col(i)\n mod_cols = set()\n for i in mod_rows:\n fix_row(i)\n mod_rows = set()\n\n if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)):\n print \"Solution would be unique\" # but could be incorrect!\n else:\n print \"Solution may not be unique, doing exhaustive search:\"\n\n # We actually do exhaustive search anyway. Unique solution takes\n # no time in this phase anyway, but just in case there's no\n # solution (could happen?).\n out = [0] * h\n\n def try_all(n = 0):\n if n >= h:\n for j in xrange(w):\n if [x[j] for x in out] not in cols[j]:\n return 0\n show_gram(out)\n return 1\n sol = 0\n for x in rows[n]:\n out[n] = x\n sol += try_all(n + 1)\n return sol\n\n n = try_all()\n if not n:\n print \"No solution.\"\n elif n == 1:\n print \"Unique solution.\"\n else:\n print n, \"solutions.\"\n print\n\n\ndef solve(p, show_runs=True):\n s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()]\n for l in p.splitlines()]\n if show_runs:\n print \"Horizontal runs:\", s[0]\n print \"Vertical runs:\", s[1]\n deduce(s[0], s[1])\n\n\ndef main():\n # Read problems from file.\n fn = \"nonogram_problems.txt\"\n for p in (x for x in open(fn).read().split(\"\\n\\n\") if x):\n solve(p)\n\n print \"Extra example not solvable by deduction alone:\"\n solve(\"B B A A\\nB B A A\")\n\n print \"Extra example where there is no solution:\"\n solve(\"B A A\\nA A A\")\n\nmain()"} +{"title": "Numbers which are the cube roots of the product of their proper divisors", "language": "C", "task": ";Example\nConsider the number 24. Its proper divisors are: 1, 2, 3, 4, 6, 8 and 12. Their product is 13,824 and the cube root of this is 24. So 24 satisfies the definition in the task title.\n\n;Task\nCompute and show here the first '''50''' positive integers which are the cube roots of the product of their proper divisors.\n\nAlso show the '''500th''' and '''5,000th''' such numbers.\n\n;Stretch\nCompute and show the '''50,000th''' such number.\n\n;Reference\n* OEIS:A111398 - Numbers which are the cube roots of the product of their proper divisors.\n\n;Note\nOEIS considers 1 to be the first number in this sequence even though, strictly speaking, it has no proper divisors. Please therefore do likewise.\n\n", "solution": "#include \n#include \n\nint divisorCount(int n) {\n int i, j, count = 0, k = !(n%2) ? 1 : 2;\n for (i = 1; i*i <= n; i += k) {\n if (!(n%i)) {\n ++count;\n j = n/i;\n if (j != i) ++count;\n }\n }\n return count;\n}\n\nint main() {\n int i, numbers50[50], count = 0, n = 1, dc;\n printf(\"First 50 numbers which are the cube roots of the products of their proper divisors:\\n\");\n setlocale(LC_NUMERIC, \"\");\n while (1) {\n dc = divisorCount(n);\n if (n == 1|| dc == 8) {\n ++count;\n if (count <= 50) {\n numbers50[count-1] = n;\n if (count == 50) {\n for (i = 0; i < 50; ++i) {\n printf(\"%3d \", numbers50[i]);\n if (!((i+1) % 10)) printf(\"\\n\");\n }\n }\n } else if (count == 500) {\n printf(\"\\n500th : %'d\\n\", n);\n } else if (count == 5000) {\n printf(\"5,000th : %'d\\n\", n);\n } else if (count == 50000) {\n printf(\"50,000th: %'d\\n\", n);\n break;\n }\n }\n ++n;\n }\n return 0;\n}"} +{"title": "Numbers which are the cube roots of the product of their proper divisors", "language": "Python", "task": ";Example\nConsider the number 24. Its proper divisors are: 1, 2, 3, 4, 6, 8 and 12. Their product is 13,824 and the cube root of this is 24. So 24 satisfies the definition in the task title.\n\n;Task\nCompute and show here the first '''50''' positive integers which are the cube roots of the product of their proper divisors.\n\nAlso show the '''500th''' and '''5,000th''' such numbers.\n\n;Stretch\nCompute and show the '''50,000th''' such number.\n\n;Reference\n* OEIS:A111398 - Numbers which are the cube roots of the product of their proper divisors.\n\n;Note\nOEIS considers 1 to be the first number in this sequence even though, strictly speaking, it has no proper divisors. Please therefore do likewise.\n\n", "solution": "''' Rosetta code rosettacode.org/wiki/Numbers_which_are_the_cube_roots_of_the_product_of_their_proper_divisors '''\n\nfrom functools import reduce\nfrom sympy import divisors\n\n\nFOUND = 0\nfor num in range(1, 1_000_000):\n divprod = reduce(lambda x, y: x * y, divisors(num)[:-1])if num > 1 else 1\n if num * num * num == divprod:\n FOUND += 1\n if FOUND <= 50:\n print(f'{num:5}', end='\\n' if FOUND % 10 == 0 else '')\n if FOUND == 500:\n print(f'\\nFive hundreth: {num:,}')\n if FOUND == 5000:\n print(f'\\nFive thousandth: {num:,}')\n if FOUND == 50000:\n print(f'\\nFifty thousandth: {num:,}')\n break\n"} +{"title": "Numbers with equal rises and falls", "language": "C", "task": "When a number is written in base 10, \u00a0 adjacent digits may \"rise\" or \"fall\" as the number is read \u00a0 (usually from left to right).\n\n\n;Definition:\nGiven the decimal digits of the number are written as a series \u00a0 d:\n:* \u00a0 A \u00a0 ''rise'' \u00a0 is an index \u00a0 i \u00a0 such that \u00a0 d(i) \u00a0<\u00a0 d(i+1)\n:* \u00a0 A \u00a0 ''fall''\u00a0 \u00a0 is an index \u00a0 i \u00a0 such that \u00a0 d(i) \u00a0>\u00a0 d(i+1)\n\n\n;Examples:\n:* \u00a0 The number \u00a0 '''726,169''' \u00a0 has \u00a0 '''3''' \u00a0 rises and \u00a0 '''2''' \u00a0 falls, \u00a0 so it isn't in the sequence.\n:* \u00a0 The number \u00a0 \u00a0 '''83,548''' \u00a0 has \u00a0 '''2''' \u00a0 rises and \u00a0 '''2''' \u00a0 falls, \u00a0 so it \u00a0 is \u00a0 in the sequence.\n\n\n;Task:\n:* \u00a0 Print the first \u00a0 '''200''' \u00a0 numbers in the sequence \n:* \u00a0 Show that the \u00a0 '''10 millionth''' \u00a0 (10,000,000th) \u00a0 number in the sequence is \u00a0 '''41,909,002'''\n\n\n;See also:\n* \u00a0 OEIS Sequence \u00a0A296712 \u00a0 describes numbers whose digit sequence in base 10 have equal \"rises\" and \"falls\".\n\n\n;Related tasks:\n* \u00a0 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": "Numbers with equal rises and falls", "language": "Python", "task": "When a number is written in base 10, \u00a0 adjacent digits may \"rise\" or \"fall\" as the number is read \u00a0 (usually from left to right).\n\n\n;Definition:\nGiven the decimal digits of the number are written as a series \u00a0 d:\n:* \u00a0 A \u00a0 ''rise'' \u00a0 is an index \u00a0 i \u00a0 such that \u00a0 d(i) \u00a0<\u00a0 d(i+1)\n:* \u00a0 A \u00a0 ''fall''\u00a0 \u00a0 is an index \u00a0 i \u00a0 such that \u00a0 d(i) \u00a0>\u00a0 d(i+1)\n\n\n;Examples:\n:* \u00a0 The number \u00a0 '''726,169''' \u00a0 has \u00a0 '''3''' \u00a0 rises and \u00a0 '''2''' \u00a0 falls, \u00a0 so it isn't in the sequence.\n:* \u00a0 The number \u00a0 \u00a0 '''83,548''' \u00a0 has \u00a0 '''2''' \u00a0 rises and \u00a0 '''2''' \u00a0 falls, \u00a0 so it \u00a0 is \u00a0 in the sequence.\n\n\n;Task:\n:* \u00a0 Print the first \u00a0 '''200''' \u00a0 numbers in the sequence \n:* \u00a0 Show that the \u00a0 '''10 millionth''' \u00a0 (10,000,000th) \u00a0 number in the sequence is \u00a0 '''41,909,002'''\n\n\n;See also:\n* \u00a0 OEIS Sequence \u00a0A296712 \u00a0 describes numbers whose digit sequence in base 10 have equal \"rises\" and \"falls\".\n\n\n;Related tasks:\n* \u00a0 Esthetic numbers\n\n", "solution": "import itertools\n\ndef riseEqFall(num):\n \"\"\"Check whether a number belongs to sequence A296712.\"\"\"\n height = 0\n d1 = num % 10\n num //= 10\n while num:\n d2 = num % 10\n height += (d1d2)\n d1 = d2\n num //= 10\n return height == 0\n \ndef sequence(start, fn):\n \"\"\"Generate a sequence defined by a function\"\"\"\n num=start-1\n while True:\n num += 1\n while not fn(num): num += 1\n yield num\n\na296712 = sequence(1, riseEqFall)\n\n# Generate the first 200 numbers\nprint(\"The first 200 numbers are:\")\nprint(*itertools.islice(a296712, 200))\n\n# Generate the 10,000,000th number\nprint(\"The 10,000,000th number is:\")\nprint(*itertools.islice(a296712, 10000000-200-1, 10000000-200))\n# It is necessary to subtract 200 from the index, because 200 numbers\n# have already been consumed.\n"} +{"title": "Numeric error propagation", "language": "C", "task": "If \u00a0 '''f''', \u00a0 '''a''', \u00a0 and \u00a0 '''b''' \u00a0 are values with uncertainties \u00a0 \u03c3f, \u00a0 \u03c3a, \u00a0 and \u00a0 \u03c3b, \u00a0 and \u00a0 '''c''' \u00a0 is a constant; \nthen if \u00a0 '''f''' \u00a0 is derived from \u00a0 '''a''', \u00a0 '''b''', \u00a0 and \u00a0 '''c''' \u00a0 in the following ways, \nthen \u00a0 \u03c3f \u00a0 can be calculated as follows:\n\n:;Addition/Subtraction\n:* If \u00a0 f = a \u00b1 c, \u00a0 or \u00a0 f = c \u00b1 a \u00a0 then \u00a0 '''\u03c3f = \u03c3a'''\n:* If \u00a0 f = a \u00b1 b \u00a0 then \u00a0 '''\u03c3f2 = \u03c3a2 + \u03c3b2'''\n\n:;Multiplication/Division\n:* If \u00a0 f = ca \u00a0 or \u00a0 f = ac \u00a0 \u00a0 \u00a0 then \u00a0 '''\u03c3f = |c\u03c3a|'''\n:* If \u00a0 f = ab \u00a0 or \u00a0 f = a / b \u00a0 then \u00a0 '''\u03c3f2 = f2( (\u03c3a / a)2 + (\u03c3b / b)2)'''\n\n:;Exponentiation\n:* If \u00a0 f = ac \u00a0 then \u00a0 '''\u03c3f = |fc(\u03c3a / a)|'''\n\n\nCaution:\n::This implementation of error propagation does not address issues of dependent and independent values. \u00a0 It is assumed that \u00a0 '''a''' \u00a0 and \u00a0 '''b''' \u00a0 are independent and so the formula for multiplication should not be applied to \u00a0 '''a*a''' \u00a0 for example. \u00a0 See \u00a0 the talk page \u00a0 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 \u00b1 1.1y1 = 50 \u00b1 1.2x2 = 200 \u00b1 2.2y2 = 100 \u00b1 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 = \u221a \u00a0 (x1 - x2)\u00b2 \u00a0 + \u00a0 (y1 - y2)\u00b2 \u00a0 \n# Print and display both \u00a0 '''d''' \u00a0 and its error.\n\n \n\n;References:\n* [http://casa.colorado.edu/~benderan/teaching/astr3510/stats.pdf A Guide to Error Propagation] B. Keeney, 2005.\n* Propagation of uncertainty Wikipedia.\n\n\n;Related task:\n* \u00a0 [[Quaternion type]]\n\n", "solution": "\n#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": "Numeric error propagation", "language": "Python", "task": "If \u00a0 '''f''', \u00a0 '''a''', \u00a0 and \u00a0 '''b''' \u00a0 are values with uncertainties \u00a0 \u03c3f, \u00a0 \u03c3a, \u00a0 and \u00a0 \u03c3b, \u00a0 and \u00a0 '''c''' \u00a0 is a constant; \nthen if \u00a0 '''f''' \u00a0 is derived from \u00a0 '''a''', \u00a0 '''b''', \u00a0 and \u00a0 '''c''' \u00a0 in the following ways, \nthen \u00a0 \u03c3f \u00a0 can be calculated as follows:\n\n:;Addition/Subtraction\n:* If \u00a0 f = a \u00b1 c, \u00a0 or \u00a0 f = c \u00b1 a \u00a0 then \u00a0 '''\u03c3f = \u03c3a'''\n:* If \u00a0 f = a \u00b1 b \u00a0 then \u00a0 '''\u03c3f2 = \u03c3a2 + \u03c3b2'''\n\n:;Multiplication/Division\n:* If \u00a0 f = ca \u00a0 or \u00a0 f = ac \u00a0 \u00a0 \u00a0 then \u00a0 '''\u03c3f = |c\u03c3a|'''\n:* If \u00a0 f = ab \u00a0 or \u00a0 f = a / b \u00a0 then \u00a0 '''\u03c3f2 = f2( (\u03c3a / a)2 + (\u03c3b / b)2)'''\n\n:;Exponentiation\n:* If \u00a0 f = ac \u00a0 then \u00a0 '''\u03c3f = |fc(\u03c3a / a)|'''\n\n\nCaution:\n::This implementation of error propagation does not address issues of dependent and independent values. \u00a0 It is assumed that \u00a0 '''a''' \u00a0 and \u00a0 '''b''' \u00a0 are independent and so the formula for multiplication should not be applied to \u00a0 '''a*a''' \u00a0 for example. \u00a0 See \u00a0 the talk page \u00a0 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 \u00b1 1.1y1 = 50 \u00b1 1.2x2 = 200 \u00b1 2.2y2 = 100 \u00b1 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 = \u221a \u00a0 (x1 - x2)\u00b2 \u00a0 + \u00a0 (y1 - y2)\u00b2 \u00a0 \n# Print and display both \u00a0 '''d''' \u00a0 and its error.\n\n \n\n;References:\n* [http://casa.colorado.edu/~benderan/teaching/astr3510/stats.pdf A Guide to Error Propagation] B. Keeney, 2005.\n* Propagation of uncertainty Wikipedia.\n\n\n;Related task:\n* \u00a0 [[Quaternion type]]\n\n", "solution": "from collections import namedtuple\nimport math\n \nclass I(namedtuple('Imprecise', 'value, delta')):\n 'Imprecise type: I(value=0.0, delta=0.0)' \n \n __slots__ = () \n \n def __new__(_cls, value=0.0, delta=0.0):\n 'Defaults to 0.0 \u00b1 delta'\n return super().__new__(_cls, float(value), abs(float(delta)))\n \n def reciprocal(self):\n return I(1. / self.value, self.delta / (self.value**2)) \n \n def __str__(self):\n 'Shorter form of Imprecise as string'\n return 'I(%g, %g)' % self\n \n def __neg__(self):\n return I(-self.value, self.delta)\n \n def __add__(self, other):\n if type(other) == I:\n return I( self.value + other.value, (self.delta**2 + other.delta**2)**0.5 )\n try:\n c = float(other)\n except:\n return NotImplemented\n return I(self.value + c, self.delta)\n\n def __sub__(self, other):\n return self + (-other)\n \n def __radd__(self, other):\n return I.__add__(self, other)\n \n def __mul__(self, other):\n if type(other) == I:\n #if id(self) == id(other): \n # return self ** 2\n a1,b1 = self\n a2,b2 = other\n f = a1 * a2\n return I( f, f * ( (b1 / a1)**2 + (b2 / a2)**2 )**0.5 )\n try:\n c = float(other)\n except:\n return NotImplemented\n return I(self.value * c, self.delta * c)\n \n def __pow__(self, other):\n if type(other) == I:\n return NotImplemented\n try:\n c = float(other)\n except:\n return NotImplemented\n f = self.value ** c\n return I(f, f * c * (self.delta / self.value))\n \n def __rmul__(self, other):\n return I.__mul__(self, other)\n \n def __truediv__(self, other):\n if type(other) == I:\n return self.__mul__(other.reciprocal())\n try:\n c = float(other)\n except:\n return NotImplemented\n return I(self.value / c, self.delta / c)\n \n def __rtruediv__(self, other):\n return other * self.reciprocal()\n \n __div__, __rdiv__ = __truediv__, __rtruediv__\n \nImprecise = I\n\ndef distance(p1, p2):\n x1, y1 = p1\n x2, y2 = p2\n return ((x1 - x2)**2 + (y1 - y2)**2)**0.5\n \nx1 = I(100, 1.1)\nx2 = I(200, 2.2)\ny1 = I( 50, 1.2)\ny2 = I(100, 2.3)\n\np1, p2 = (x1, y1), (x2, y2)\nprint(\"Distance between points\\n p1: %s\\n and p2: %s\\n = %r\" % (\n p1, p2, distance(p1, p2)))"} +{"title": "Numerical and alphabetical suffixes", "language": "CPython 3.7.3", "task": "This task is about expressing numbers with an attached (abutted) suffix multiplier(s), \u00a0 the suffix(es) could be:\n::* \u00a0 an alphabetic (named) multiplier which could be abbreviated\n::* \u00a0 \u00a0metric\u00a0 multiplier(s) which can be specified multiple times\n::* \u00a0 \"binary\" multiplier(s) which can be specified multiple times\n::* \u00a0 explanation marks ('''!''') which indicate a factorial or multifactorial\n\n\nThe (decimal) numbers can be expressed generally as:\n {\u00b1} {digits} {'''.'''} {digits}\n \u2500\u2500\u2500\u2500\u2500\u2500 or \u2500\u2500\u2500\u2500\u2500\u2500\n {\u00b1} {digits} {'''.'''} {digits} {'''E''' or '''e'''} {\u00b1} {digits}\n\nwhere:\n::* \u00a0 numbers won't have embedded blanks \u00a0 (contrary to the expaciated examples above where whitespace was used for readability)\n::* \u00a0 this task will only be dealing with decimal numbers, \u00a0 both in the \u00a0 ''mantissa'' \u00a0 and \u00a0 ''exponent''\n::* \u00a0 \u00b1 \u00a0 indicates an optional plus or minus sign \u00a0 ('''+''' \u00a0 or \u00a0 '''-''')\n::* \u00a0 digits are the decimal digits \u00a0 ('''0''' \u2500\u2500\u25ba '''9''')\n::* \u00a0 the digits can have comma(s) interjected to separate the \u00a0 ''periods'' \u00a0 (thousands) \u00a0 such as: \u00a0 '''12,467,000'''\n::* \u00a0 '''.''' \u00a0 is the decimal point, sometimes also called a \u00a0 ''dot''\n::* \u00a0 '''e''' \u00a0 or \u00a0 '''E''' \u00a0 denotes the use of decimal exponentiation \u00a0 (a number multiplied by raising ten to some power)\n\n\nThis isn't a pure or perfect definition of the way we express decimal numbers, \u00a0 but it should convey the intent for this task.\n\nThe use of the word \u00a0 ''periods'' \u00a0 (thousands) is not meant to confuse, that word (as used above) is what the '''comma''' separates;\nthe groups of decimal digits are called ''periods'', \u00a0 and in almost all cases, are groups of three decimal digits.\n\nIf an \u00a0 '''e''' \u00a0 or \u00a0 '''E''' \u00a0 is specified, there must be a legal number expressed before it, \u00a0 and there must be a legal (exponent) expressed after it.\n\nAlso, there must be some digits expressed in all cases, \u00a0 not just a sign and/or decimal point.\n\nSuperfluous signs, decimal points, exponent numbers, and zeros \u00a0 need not be preserved.\n\nI.E.: \u00a0 \u00a0 \u00a0\n'''+7''' \u00a0 '''007''' \u00a0 '''7.00''' \u00a0 '''7E-0''' \u00a0 '''7E000''' \u00a0 '''70e-1''' \u00a0 \u00a0 could all be expressed as '''7'''\n\nAll numbers to be \"expanded\" can be assumed to be valid and there won't be a requirement to verify their validity.\n\n\n;Abbreviated alphabetic suffixes to be supported \u00a0 (where the capital letters signify the minimum abbreation that can be used):\n '''PAIRs''' multiply the number by '''2''' (as in pairs of shoes or pants)\n '''SCOres''' multiply the number by '''20''' (as '''3score''' would be '''60''')\n '''DOZens''' multiply the number by '''12'''\n '''GRoss''' multiply the number by '''144''' (twelve dozen)\n '''GREATGRoss''' multiply the number by '''1,728''' (a dozen gross)\n '''GOOGOLs''' multiply the number by '''10^100''' (ten raised to the 100\u2283>th power)\n\n\nNote that the plurals are supported, even though they're usually used when expressing exact numbers \u00a0 (She has 2 dozen eggs, and dozens of quavas)\n\n\n;Metric suffixes to be supported \u00a0 (whether or not they're officially sanctioned):\n '''K''' multiply the number by '''10^3''' kilo (1,000)\n '''M''' multiply the number by '''10^6''' mega (1,000,000)\n '''G''' multiply the number by '''10^9''' giga (1,000,000,000)\n '''T''' multiply the number by '''10^12''' tera (1,000,000,000,000)\n '''P''' multiply the number by '''10^15''' peta (1,000,000,000,000,000)\n '''E''' multiply the number by '''10^18''' exa (1,000,000,000,000,000,000)\n '''Z''' multiply the number by '''10^21''' zetta (1,000,000,000,000,000,000,000)\n '''Y''' multiply the number by '''10^24''' yotta (1,000,000,000,000,000,000,000,000)\n '''X''' multiply the number by '''10^27''' xenta (1,000,000,000,000,000,000,000,000,000)\n '''W''' multiply the number by '''10^30''' wekta (1,000,000,000,000,000,000,000,000,000,000)\n '''V''' multiply the number by '''10^33''' vendeka (1,000,000,000,000,000,000,000,000,000,000,000)\n '''U''' multiply the number by '''10^36''' udekta (1,000,000,000,000,000,000,000,000,000,000,000,000)\n\n\n;Binary suffixes to be supported \u00a0 (whether or not they're officially sanctioned):\n '''Ki''' multiply the number by '''2^10''' kibi (1,024)\n '''Mi''' multiply the number by '''2^20''' mebi (1,048,576)\n '''Gi''' multiply the number by '''2^30''' gibi (1,073,741,824)\n '''Ti''' multiply the number by '''2^40''' tebi (1,099,571,627,776)\n '''Pi''' multiply the number by '''2^50''' pebi (1,125,899,906,884,629)\n '''Ei''' multiply the number by '''2^60''' exbi (1,152,921,504,606,846,976)\n '''Zi''' multiply the number by '''2^70''' zeb1 (1,180,591,620,717,411,303,424)\n '''Yi''' multiply the number by '''2^80''' yobi (1,208,925,819,614,629,174,706,176)\n '''Xi''' multiply the number by '''2^90''' xebi (1,237,940,039,285,380,274,899,124,224)\n '''Wi''' multiply the number by '''2^100''' webi (1,267,650,600,228,229,401,496,703,205,376)\n '''Vi''' multiply the number by '''2^110''' vebi (1,298,074,214,633,706,907,132,624,082,305,024)\n '''Ui''' multiply the number by '''2^120''' uebi (1,329,227,995,784,915,872,903,807,060,280,344,576)\n\n\nAll of the metric and binary suffixes can be expressed in \u00a0 lowercase, \u00a0 uppercase, \u00a0 ''or'' \u00a0 mixed case.\n\nAll of the metric and binary suffixes can be \u00a0 ''stacked'' \u00a0 (expressed multiple times), \u00a0 and also be intermixed:\nI.E.: \u00a0 \u00a0 \u00a0 '''123k''' \u00a0 '''123K''' \u00a0 '''123GKi''' \u00a0 '''12.3GiGG''' \u00a0 '''12.3e-7T''' \u00a0 '''.78E100e'''\n \n\n;Factorial suffixes to be supported:\n '''!''' compute the (regular) factorial product: '''5!''' is '''5''' \u00d7 '''4''' \u00d7 '''3''' \u00d7 '''2''' \u00d7 '''1''' = '''120'''\n '''!!''' compute the double factorial product: '''8!''' is '''8''' \u00d7 '''6''' \u00d7 '''4''' \u00d7 '''2''' = '''384'''\n '''!!!''' compute the triple factorial product: '''8!''' is '''8''' \u00d7 '''5''' \u00d7 '''2''' = '''80'''\n '''!!!!''' compute the quadruple factorial product: '''8!''' is '''8''' \u00d7 '''4''' = '''32'''\n '''!!!!!''' compute the quintuple factorial product: '''8!''' is '''8''' \u00d7 '''3''' = '''24'''\n \u00b7\u00b7\u00b7 the number of factorial symbols that can be specified is to be unlimited \u00a0 (as per what can be entered/typed) \u00b7\u00b7\u00b7\n\n\nFactorial suffixes aren't, of course, the usual type of multipliers, but are used here in a similar vein.\n\n\nMultifactorials aren't to be confused with \u00a0 ''super\u2500factorials'' \u00a0 \u00a0 where \u00a0 '''(4!)!''' \u00a0 would be \u00a0 '''(24)!'''.\n\n\n\n;Task:\n::* \u00a0 Using the test cases (below), \u00a0 show the \"expanded\" numbers here, on this page.\n::* \u00a0 For each list, show the input on one line, \u00a0 and also show the output on one line.\n::* \u00a0 When showing the input line, keep the spaces (whitespace) and case (capitalizations) as is.\n::* \u00a0 For each result (list) displayed on one line, separate each number with two blanks.\n::* \u00a0 Add commas to the output numbers were appropriate.\n\n\n;Test cases:\n 2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre\n 1,567 +1.567k 0.1567e-2m\n 25.123kK 25.123m 2.5123e-00002G\n 25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei\n -.25123e-34Vikki 2e-77gooGols\n 9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!!\n\nwhere the last number for the factorials has nine factorial symbols \u00a0 ('''!''') \u00a0 after the \u00a0 '''9'''\n\n\n\n;Related tasks:\n* \u00a0 [[Multifactorial]] \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 (which has a clearer and more succinct definition of multifactorials.)\n* \u00a0 [[Factorial]]\n\n\n\n", "solution": "\nfrom functools import reduce\nfrom operator import mul\nfrom decimal import *\n\ngetcontext().prec = MAX_PREC\n\ndef expand(num):\n suffixes = [\n # (name, min_abbreviation_length, base, exponent)\n ('greatgross', 7, 12, 3),\n ('gross', 2, 12, 2),\n ('dozens', 3, 12, 1),\n ('pairs', 4, 2, 1),\n ('scores', 3, 20, 1),\n ('googols', 6, 10, 100),\n ('ki', 2, 2, 10),\n ('mi', 2, 2, 20),\n ('gi', 2, 2, 30),\n ('ti', 2, 2, 40),\n ('pi', 2, 2, 50),\n ('ei', 2, 2, 60),\n ('zi', 2, 2, 70),\n ('yi', 2, 2, 80),\n ('xi', 2, 2, 90),\n ('wi', 2, 2, 100),\n ('vi', 2, 2, 110),\n ('ui', 2, 2, 120),\n ('k', 1, 10, 3),\n ('m', 1, 10, 6),\n ('g', 1, 10, 9),\n ('t', 1, 10, 12),\n ('p', 1, 10, 15),\n ('e', 1, 10, 18),\n ('z', 1, 10, 21),\n ('y', 1, 10, 24),\n ('x', 1, 10, 27),\n ('w', 1, 10, 30)\n ]\n\n num = num.replace(',', '').strip().lower()\n\n if num[-1].isdigit():\n return float(num)\n\n for i, char in enumerate(reversed(num)):\n if char.isdigit():\n input_suffix = num[-i:]\n num = Decimal(num[:-i])\n break\n\n if input_suffix[0] == '!':\n return reduce(mul, range(int(num), 0, -len(input_suffix)))\n\n while len(input_suffix) > 0:\n for suffix, min_abbrev, base, power in suffixes:\n if input_suffix[:min_abbrev] == suffix[:min_abbrev]:\n for i in range(min_abbrev, len(input_suffix) + 1):\n if input_suffix[:i+1] != suffix[:i+1]:\n num *= base ** power\n input_suffix = input_suffix[i:]\n break\n break\n\n return num\n\n\ntest = \"2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre\\n\\\n 1,567 +1.567k 0.1567e-2m\\n\\\n 25.123kK 25.123m 2.5123e-00002G\\n\\\n 25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei\\n\\\n -.25123e-34Vikki 2e-77gooGols\\n\\\n 9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!!\"\n\nfor test_line in test.split(\"\\n\"):\n test_cases = test_line.split()\n print(\"Input:\", ' '.join(test_cases))\n print(\"Output:\", ' '.join(format(result, ',f').strip('0').strip('.') for result in map(expand, test_cases)))\n"} +{"title": "Odd word problem", "language": "C", "task": ";Task:\nWrite a program that solves the [http://c2.com/cgi/wiki?OddWordProblem 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, \u00a0 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 \u00a0 \"life\" \u00a0 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": "Odd word problem", "language": "Python", "task": ";Task:\nWrite a program that solves the [http://c2.com/cgi/wiki?OddWordProblem 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, \u00a0 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 \u00a0 \"life\" \u00a0 example given above, and also the text:\n:: we,are;not,in,kansas;any,more.\n\n", "solution": "from sys import stdin, stdout\n\ndef char_in(): return stdin.read(1)\ndef char_out(c): stdout.write(c)\n\ndef odd(prev = lambda: None):\n\ta = char_in()\n\tif not a.isalpha():\n\t\tprev()\n\t\tchar_out(a)\n\t\treturn a != '.'\n\n\t# delay action until later, in the shape of a closure\n\tdef clos():\n\t\tchar_out(a)\n\t\tprev()\n\n\treturn odd(clos)\n\ndef even():\n\twhile True:\n\t\tc = char_in()\n\t\tchar_out(c)\n\t\tif not c.isalpha(): return c != '.'\n\ne = False\nwhile odd() if e else even():\n\te = not e"} +{"title": "Odd word problem", "language": "Python 3.3+", "task": ";Task:\nWrite a program that solves the [http://c2.com/cgi/wiki?OddWordProblem 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, \u00a0 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 \u00a0 \"life\" \u00a0 example given above, and also the text:\n:: we,are;not,in,kansas;any,more.\n\n", "solution": "from sys import stdin, stdout\n\ndef fwd(c):\n if c.isalpha():\n return [stdout.write(c), (yield from fwd((yield f)))][1]\n else:\n return c\n\ndef rev(c):\n if c.isalpha():\n return [(yield from rev((yield r))), stdout.write(c)][0]\n else:\n return c\n\ndef fw():\n while True:\n stdout.write((yield from fwd((yield r))))\n\ndef re():\n while True:\n stdout.write((yield from rev((yield f))))\n\nf = fw()\nr = re()\nnext(f)\nnext(r)\n\ncoro = f\nwhile True:\n c = stdin.read(1)\n if not c:\n break\n coro = coro.send(c)"} +{"title": "Old Russian measure of length", "language": "C", "task": ";Task:\nWrite a program to perform a conversion of the old Russian measures of length to the metric system \u00a0 (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:* \u00a0 [https://en.wikipedia.org/wiki/Obsolete_Russian_units_of_measurement#Length Old Russian measure of length]\n\n", "solution": "\n#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\nOutput :\n\nC:\\rosettaCode>metricRussian.exe 1 meter\n1 meter is equal in length to :\n\n0.001000 kilometer\n100.000000 centimeter\n3937.007874 tochka\n393.700787 liniya\n39.370079 diuym\n22.497188 vershok\n5.624297 piad\n3.280840 fut\n1.406074 arshin\n0.468691 sazhen\n0.000937 versta\n0.000134 milia\nC:\\rosettaCode>metricRussian.exe 3 arshin\n3 arshin is equal in length to :\n\n0.002134 kilometer\n2.133600 meter\n213.360000 centimeter\n8400.000000 tochka\n840.000000 liniya\n84.000000 diuym\n48.000000 vershok\n12.000000 piad\n7.000000 fut\n1.000000 sazhen\n0.002000 versta\n0.000286 milia\n\n"} +{"title": "Old Russian measure of length", "language": "Python", "task": ";Task:\nWrite a program to perform a conversion of the old Russian measures of length to the metric system \u00a0 (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:* \u00a0 [https://en.wikipedia.org/wiki/Obsolete_Russian_units_of_measurement#Length Old Russian measure of length]\n\n", "solution": "from sys import argv\n \nunit2mult = {\"arshin\": 0.7112, \"centimeter\": 0.01, \"diuym\": 0.0254,\n \"fut\": 0.3048, \"kilometer\": 1000.0, \"liniya\": 0.00254,\n \"meter\": 1.0, \"milia\": 7467.6, \"piad\": 0.1778,\n \"sazhen\": 2.1336, \"tochka\": 0.000254, \"vershok\": 0.04445,\n \"versta\": 1066.8}\n \nif __name__ == '__main__':\n assert len(argv) == 3, 'ERROR. Need two arguments - number then units'\n try:\n value = float(argv[1])\n except:\n print('ERROR. First argument must be a (float) number')\n raise\n unit = argv[2]\n assert unit in unit2mult, ( 'ERROR. Only know the following units: ' \n + ' '.join(unit2mult.keys()) )\n\n print(\"%g %s to:\" % (value, unit))\n for unt, mlt in sorted(unit2mult.items()):\n print(' %10s: %g' % (unt, value * unit2mult[unit] / mlt))"} +{"title": "Old lady swallowed a fly", "language": "C", "task": ";Task:\nPresent a program which emits the lyrics to the song \u00a0 ''I Knew an Old Lady Who Swallowed a Fly'', \u00a0 taking advantage of the repetitive structure of the song's lyrics. \n\nThis song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.\n\n\n\n", "solution": "#include \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": "Old lady swallowed a fly", "language": "Python", "task": ";Task:\nPresent a program which emits the lyrics to the song \u00a0 ''I Knew an Old Lady Who Swallowed a Fly'', \u00a0 taking advantage of the repetitive structure of the song's lyrics. \n\nThis song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.\n\n\n\n", "solution": "animals = [\n (\"fly\", \"I don't know why she swallowed a fly, perhaps she'll die.\"),\n (\"spider\", \"It wiggled and jiggled and tickled inside her.\"),\n (\"bird\", \"How absurd, to swallow a bird.\"),\n (\"cat\", \"Imagine that, she swallowed a cat.\"),\n (\"dog\", \"What a hog, to swallow a dog.\"),\n (\"goat\", \"She just opened her throat and swallowed a goat.\"),\n (\"cow\", \"I don't know how she swallowed a cow.\"),\n (\"horse\", \"She's dead, of course.\")]\n\nfor i, (animal, lyric) in enumerate(animals):\n print(\"There was an old lady who swallowed a {}.\\n{}\".format(animal, lyric))\n\n if animal == \"horse\": break\n\n for (predator, _), (prey, _) in zip(animals[i:0:-1], animals[i-1::-1]):\n print(\"\\tShe swallowed the {} to catch the {}\".format(predator, prey))\n\n if animal != \"fly\": print(animals[0][1]) # fly lyric\n print() # new line"} +{"title": "One-time pad", "language": "Python", "task": "Implement a One-time pad, for encrypting and decrypting messages.\nTo keep it simple, we will be using letters only.\n\n;Sub-Tasks:\n* '''Generate''' the data for a One-time pad (user needs to specify a filename and length)\n: The important part is to get \"true random\" numbers, e.g. from /dev/random\n* '''encryption / decryption''' ( basically the same operation, much like [[Rot-13]] )\n: For this step, much of [[Vigen\u00e8re cipher]] could be reused,with the key to be read from the file containing the One-time pad.\n* optional: '''management''' of One-time pads: list, mark as used, delete, etc.\n: Somehow, the users needs to keep track which pad to use for which partner.\n\nTo support the management of pad-files:\n* Such files have a file-extension \".1tp\"\n* Lines starting with \"#\" may contain arbitary meta-data (i.e. comments)\n* Lines starting with \"-\" count as \"used\"\n* Whitespace within the otp-data is ignored\n\n\n\nFor example, here is the data from [http://upload.wikimedia.org/wikipedia/commons/6/60/One-time_pad.svg Wikipedia]:\n\n# Example data - Wikipedia - 2014-11-13\n-ZDXWWW EJKAWO FECIFE WSNZIP PXPKIY URMZHI JZTLBC YLGDYJ \n-HTSVTV RRYYEG EXNCGA GGQVRF FHZCIB EWLGGR BZXQDQ DGGIAK \n YHJYEQ TDLCQT HZBSIZ IRZDYS RBYJFZ AIRCWI UCVXTW YKPQMK \n CKHVEX VXYVCS WOGAAZ OUVVON GCNEVR LMBLYB SBDCDC PCGVJX \n QXAUIP PXZQIJ JIUWYH COVWMJ UZOJHL DWHPER UBSRUJ HGAAPR \n CRWVHI FRNTQW AJVWRT ACAKRD OZKIIB VIQGBK IJCWHF GTTSSE \n EXFIPJ KICASQ IOUQTP ZSGXGH YTYCTI BAZSTN JKMFXI RERYWE \n\n\n;See also\n* [https://breakingcode.wordpress.com/2010/02/17/one-time-pad-encryption-in-python/ one time pad encryption in Python]\n* [https://github.com/snapfractalpop/1tp snapfractalpop] - One-Time-Pad Command-Line-Utility (C).\n* [http://search.cpan.org/~sifukurt/Crypt-OTP-2.00/OTP.pm Crypt-OTP-2.00] on CPAN (Perl)\n\n", "solution": "\n\"\"\"One-time pad using an XOR cipher. Requires Python >=3.6.\"\"\"\n\nimport argparse\nimport itertools\nimport pathlib\nimport re\nimport secrets\nimport sys\n\n\n# One-time pad file signature.\nMAGIC = \"#one-time pad\"\n\n\ndef make_keys(n, size):\n \"\"\"Generate ``n`` secure, random keys of ``size`` bytes.\"\"\"\n # We're generating and storing keys in their hexadecimal form to make\n # one-time pad files a little more human readable and to ensure a key\n # can not start with a hyphen.\n return (secrets.token_hex(size) for _ in range(n))\n\n\ndef make_pad(name, pad_size, key_size):\n \"\"\"Create a new one-time pad identified by the given name.\n\n Args:\n name (str): Unique one-time pad identifier.\n pad_size (int): The number of keys (or pages) in the pad.\n key_size (int): The number of bytes per key.\n Returns:\n The new one-time pad as a string.\n \"\"\"\n pad = [\n MAGIC,\n f\"#name={name}\",\n f\"#size={pad_size}\",\n *make_keys(pad_size, key_size),\n ]\n\n return \"\\n\".join(pad)\n\n\ndef xor(message, key):\n \"\"\"Return ``message`` XOR-ed with ``key``.\n\n Args:\n message (bytes): Plaintext or cyphertext to be encrypted or decrypted.\n key (bytes): Encryption and decryption key.\n Returns:\n Plaintext or cyphertext as a byte string.\n \"\"\"\n return bytes(mc ^ kc for mc, kc in zip(message, itertools.cycle(key)))\n\n\ndef use_key(pad):\n \"\"\"Use the next available key from the given one-time pad.\n\n Args:\n pad (str): A one-time pad.\n Returns:\n (str, str) A two-tuple of updated pad and key.\n \"\"\"\n match = re.search(r\"^[a-f0-9]+$\", pad, re.MULTILINE)\n if not match:\n error(\"pad is all used up\")\n\n key = match.group()\n pos = match.start()\n\n return (f\"{pad[:pos]}-{pad[pos:]}\", key)\n\n\ndef log(msg):\n \"\"\"Log a message.\"\"\"\n sys.stderr.write(msg)\n sys.stderr.write(\"\\n\")\n\n\ndef error(msg):\n \"\"\"Exit with an error message.\"\"\"\n sys.stderr.write(msg)\n sys.stderr.write(\"\\n\")\n sys.exit(1)\n\n\ndef write_pad(path, pad_size, key_size):\n \"\"\"Write a new one-time pad to the given path.\n\n Args:\n path (pathlib.Path): Path to write one-time pad to.\n length (int): Number of keys in the pad.\n \"\"\"\n if path.exists():\n error(f\"pad '{path}' already exists\")\n\n with path.open(\"w\") as fd:\n fd.write(make_pad(path.name, pad_size, key_size))\n\n log(f\"New one-time pad written to {path}\")\n\n\ndef main(pad, message, outfile):\n \"\"\"Encrypt or decrypt ``message`` using the given pad.\n\n Args:\n pad (pathlib.Path): Path to one-time pad.\n message (bytes): Plaintext or ciphertext message to encrypt or decrypt.\n outfile: File-like object to write to.\n \"\"\"\n if not pad.exists():\n error(f\"no such pad '{pad}'\")\n\n with pad.open(\"r\") as fd:\n if fd.readline().strip() != MAGIC:\n error(f\"file '{pad}' does not look like a one-time pad\")\n\n # Rewrites the entire one-time pad every time\n with pad.open(\"r+\") as fd:\n updated, key = use_key(fd.read())\n\n fd.seek(0)\n fd.write(updated)\n\n outfile.write(xor(message, bytes.fromhex(key)))\n\n\nif __name__ == \"__main__\":\n # Command line interface\n parser = argparse.ArgumentParser(description=\"One-time pad.\")\n\n parser.add_argument(\n \"pad\",\n help=(\n \"Path to one-time pad. If neither --encrypt or --decrypt \"\n \"are given, will create a new pad.\"\n ),\n )\n\n parser.add_argument(\n \"--length\",\n type=int,\n default=10,\n help=\"Pad size. Ignored if --encrypt or --decrypt are given. Defaults to 10.\",\n )\n\n parser.add_argument(\n \"--key-size\",\n type=int,\n default=64,\n help=\"Key size in bytes. Ignored if --encrypt or --decrypt are given. Defaults to 64.\",\n )\n\n parser.add_argument(\n \"-o\",\n \"--outfile\",\n type=argparse.FileType(\"wb\"),\n default=sys.stdout.buffer,\n help=(\n \"Write encoded/decoded message to a file. Ignored if --encrypt or \"\n \"--decrypt is not given. Defaults to stdout.\"\n ),\n )\n\n group = parser.add_mutually_exclusive_group()\n\n group.add_argument(\n \"--encrypt\",\n metavar=\"FILE\",\n type=argparse.FileType(\"rb\"),\n help=\"Encrypt FILE using the next available key from pad.\",\n )\n group.add_argument(\n \"--decrypt\",\n metavar=\"FILE\",\n type=argparse.FileType(\"rb\"),\n help=\"Decrypt FILE using the next available key from pad.\",\n )\n\n args = parser.parse_args()\n\n if args.encrypt:\n message = args.encrypt.read()\n elif args.decrypt:\n message = args.decrypt.read()\n else:\n message = None\n\n # Sometimes necessary if message came from stdin\n if isinstance(message, str):\n message = message.encode()\n\n pad = pathlib.Path(args.pad).with_suffix(\".1tp\")\n\n if message:\n main(pad, message, args.outfile)\n else:\n write_pad(pad, args.length, args.key_size)\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": "One of n lines in a file", "language": "Python", "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": "from random import randrange\ntry:\n range = xrange\nexcept: pass\n\ndef one_of_n(lines): # lines is any iterable\n choice = None\n for i, line in enumerate(lines):\n if randrange(i+1) == 0:\n choice = line\n return choice\n \ndef one_of_n_test(n=10, trials=1000000):\n bins = [0] * n\n if n:\n for i in range(trials):\n bins[one_of_n(range(n))] += 1\n return bins\n\nprint(one_of_n_test())"} +{"title": "OpenWebNet password", "language": "JavaScript", "task": "Calculate the password requested by ethernet gateways from the Legrand / Bticino MyHome OpenWebNet home automation system when the user's ip address is not in the gateway's whitelist\n\n'''Note:''' Factory default password is '12345'. Changing it is highly recommended !\n\nconversation goes as follows\n\n\u2190 *#*1##\n\u2192 *99*0##\n\u2190 *#603356072##\n\nat which point a password should be sent back, calculated from the \"password open\" that is set in the gateway, and the nonce that was just sent\n\n\u2192 *#25280520##\n\u2190 *#*1##\n", "solution": "\nfunction calcPass (pass, nonce) {\n\tvar flag = true;\n\tvar num1 = 0x0;\n\tvar num2 = 0x0;\n\tvar password = parseInt(pass, 10);\n\t\n\tfor (var c in nonce) {\n\t\tc = nonce[c];\n\t\tif (c!='0') {\n\t\t\tif (flag) num2 = password;\n\t\t\tflag = false;\n\t\t}\n\t\tswitch (c) {\n\t\t\tcase '1':\n\t\t\t\tnum1 = num2 & 0xFFFFFF80;\n\t\t\t\tnum1 = num1 >>> 7;\n\t\t\t\tnum2 = num2 << 25;\n\t\t\t\tnum1 = num1 + num2;\n\t\t\t\tbreak;\n\t\t\tcase '2':\n\t\t\t\tnum1 = num2 & 0xFFFFFFF0;\n\t\t\t\tnum1 = num1 >>> 4;\n\t\t\t\tnum2 = num2 << 28;\n\t\t\t\tnum1 = num1 + num2;\n\t\t\t\tbreak;\n\t\t\tcase '3':\n\t\t\t\tnum1 = num2 & 0xFFFFFFF8;\n\t\t\t\tnum1 = num1 >>> 3;\n\t\t\t\tnum2 = num2 << 29;\n\t\t\t\tnum1 = num1 + num2;\n\t\t\t\tbreak;\n\t\t\tcase '4':\n\t\t\t\tnum1 = num2 << 1;\n\t\t\t\tnum2 = num2 >>> 31;\n\t\t\t\tnum1 = num1 + num2;\n\t\t\t\tbreak;\n\t\t\tcase '5':\n\t\t\t\tnum1 = num2 << 5;\n\t\t\t\tnum2 = num2 >>> 27;\n\t\t\t\tnum1 = num1 + num2;\n\t\t\t\tbreak;\n\t\t\tcase '6':\n\t\t\t\tnum1 = num2 << 12;\n\t\t\t\tnum2 = num2 >>> 20;\n\t\t\t\tnum1 = num1 + num2;\n\t\t\t\tbreak;\n\t\t\tcase '7':\n\t\t\t\tnum1 = num2 & 0x0000FF00;\n\t\t\t\tnum1 = num1 + (( num2 & 0x000000FF ) << 24 );\n\t\t\t\tnum1 = num1 + (( num2 & 0x00FF0000 ) >>> 16 );\n\t\t\t\tnum2 = ( num2 & 0xFF000000 ) >>> 8;\n\t\t\t\tnum1 = num1 + num2;\n\t\t\t\tbreak;\n\t\t\tcase '8':\n\t\t\t\tnum1 = num2 & 0x0000FFFF;\n\t\t\t\tnum1 = num1 << 16;\n\t\t\t\tnum1 = num1 + ( num2 >>> 24 );\n\t\t\t\tnum2 = num2 & 0x00FF0000;\n\t\t\t\tnum2 = num2 >>> 8;\n\t\t\t\tnum1 = num1 + num2;\n\t\t\t\tbreak;\n\t\t\tcase '9':\n\t\t\t\tnum1 = ~num2;\n\t\t\t\tbreak;\n\t\t\tcase '0':\n\t\t\t\tnum1 = num2;\n\t\t\t\tbreak;\n\t\t}\n\t\tnum2 = num1;\n\t}\n\treturn (num1 >>> 0).toString();\n}\n\nexports.calcPass = calcPass;\n\nconsole.log ('openpass initialization');\nfunction testCalcPass (pass, nonce, expected) {\n\tvar res = calcPass (pass, nonce);\n\tvar m = pass + ' ' + nonce + ' ' + res + ' ' + expected;\n\tif (res == parseInt(expected, 10))\n\t\tconsole.log ('PASS '+m);\n\telse\n\t\tconsole.log ('FAIL '+m);\n}\n\ntestCalcPass ('12345', '603356072', '25280520');\ntestCalcPass ('12345', '410501656', '119537670');\ntestCalcPass ('12345', '630292165', '4269684735');\ntestCalcPass ('12345', '523781130', '537331200');\n"} +{"title": "OpenWebNet password", "language": "Python", "task": "Calculate the password requested by ethernet gateways from the Legrand / Bticino MyHome OpenWebNet home automation system when the user's ip address is not in the gateway's whitelist\n\n'''Note:''' Factory default password is '12345'. Changing it is highly recommended !\n\nconversation goes as follows\n\n\u2190 *#*1##\n\u2192 *99*0##\n\u2190 *#603356072##\n\nat which point a password should be sent back, calculated from the \"password open\" that is set in the gateway, and the nonce that was just sent\n\n\u2192 *#25280520##\n\u2190 *#*1##\n", "solution": "\ndef ownCalcPass (password, nonce, test=False) :\n start = True \n num1 = 0\n num2 = 0\n password = int(password)\n if test:\n print(\"password: %08x\" % (password))\n for c in nonce :\n if c != \"0\":\n if start:\n num2 = password\n start = False\n if test:\n print(\"c: %s num1: %08x num2: %08x\" % (c, num1, num2))\n if c == '1':\n num1 = (num2 & 0xFFFFFF80) >> 7\n num2 = num2 << 25\n elif c == '2':\n num1 = (num2 & 0xFFFFFFF0) >> 4\n num2 = num2 << 28\n elif c == '3':\n num1 = (num2 & 0xFFFFFFF8) >> 3\n num2 = num2 << 29\n elif c == '4':\n num1 = num2 << 1\n num2 = num2 >> 31\n elif c == '5':\n num1 = num2 << 5\n num2 = num2 >> 27\n elif c == '6':\n num1 = num2 << 12\n num2 = num2 >> 20\n elif c == '7':\n num1 = num2 & 0x0000FF00 | (( num2 & 0x000000FF ) << 24 ) | (( num2 & 0x00FF0000 ) >> 16 )\n num2 = ( num2 & 0xFF000000 ) >> 8\n elif c == '8':\n num1 = (num2 & 0x0000FFFF) << 16 | ( num2 >> 24 )\n num2 = (num2 & 0x00FF0000) >> 8\n elif c == '9':\n num1 = ~num2\n else :\n num1 = num2\n\n num1 &= 0xFFFFFFFF\n num2 &= 0xFFFFFFFF\n if (c not in \"09\"):\n num1 |= num2\n if test:\n print(\" num1: %08x num2: %08x\" % (num1, num2))\n num2 = num1\n return num1\n\ndef test_passwd_calc(passwd, nonce, expected):\n res = ownCalcPass(passwd, nonce, False)\n m = passwd+' '+nonce+' '+str(res)+' '+str(expected)\n if res == int(expected) :\n print('PASS '+m)\n else :\n print('FAIL '+m)\n\nif __name__ == '__main__':\n test_passwd_calc('12345','603356072','25280520')\n test_passwd_calc('12345','410501656','119537670')\n test_passwd_calc('12345','630292165','4269684735')\n\n"} +{"title": "Operator precedence", "language": "C", "task": ";Task:\nProvide a list of \u00a0 associativity \u00a0 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": "Operator precedence", "language": "JavaScript", "task": ";Task:\nProvide a list of \u00a0 associativity \u00a0 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": "Mozilla Developer Network have a nice list of this at [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence JavaScript Reference:Expressions and operators:Operator Precedence]\n\n"} +{"title": "Operator precedence", "language": "Python", "task": ";Task:\nProvide a list of \u00a0 associativity \u00a0 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": "See [http://docs.python.org/py3k/reference/expressions.html?highlight=precedence#summary this table] and the whole page for details on Python version 3.x\nAn excerpt of which is this table:\n\n{| class=\"wikitable\"\n|-\n! Precedence\n! Operator\n! Description\n|-\n! lowest\n| '''lambda'''\n| Lambda expression\n|-\n!\n| '''if \u2013 else'''\n| Conditional expression\n|-\n!\n| '''or'''\n| Boolean OR\n|-\n!\n| '''and'''\n| Boolean AND\n|-\n!\n| '''not x'''\n| Boolean NOT\n|-\n!\n| '''in, not in, is, is not, <, <=, >, >=, !=, =='''\n| Comparisons, including membership tests and identity tests,\n|-\n!\n| '''|'''\n| Bitwise OR\n|-\n!\n| '''^'''\n| Bitwise XOR\n|-\n!\n| '''&'''\n| Bitwise AND\n|-\n!\n| '''<<, >>'''\n| Shifts\n|-\n!\n| '''+, -'''\n| Addition and subtraction\n|-\n!\n| '''*, /, //, %'''\n| Multiplication, division, remainder [1]\n|-\n!\n| '''+x, -x, ~x'''\n| Positive, negative, bitwise NOT\n|-\n!\n| '''**'''\n| Exponentiation [2]\n|-\n!\n| '''x[index], x[index:index], x(arguments...), x.attribute'''\n| Subscription, slicing, call, attribute reference\n|-\n! highest\n| '''(expressions...), [expressions...], {key:datum...}, {expressions...}'''\n| Binding or tuple display, list display, dictionary display, set display\n|}\n\n;Footnotes:\n# The % operator is also used for string formatting; the same precedence applies.\n# The power operator ** binds less tightly than an arithmetic or bitwise unary operator on its right, that is, 2**-1 is 0.5.\n\n"} +{"title": "Padovan n-step number sequences", "language": "C", "task": "As the [[Fibonacci sequence]] expands to the [[Fibonacci n-step number sequences]]; We similarly expand the [[Padovan sequence]] to form these Padovan n-step number sequences.\n\nThe Fibonacci-like sequences can be defined like this:\n\n For n == 2:\n start: 1, 1\n Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n == 2\n For n == N:\n start: First N terms of R(N-1, x)\n Recurrence: R(N, x) = sum(R(N, x-1) + R(N, x-2) + ... R(N, x-N))\n\nFor this task we similarly define terms of the first 2..n-step Padovan sequences as:\n\n For n == 2:\n start: 1, 1, 1\n Recurrence: R(n, x) = R(n, x-2) + R(n, x-3); for n == 2\n For n == N:\n start: First N + 1 terms of R(N-1, x)\n Recurrence: R(N, x) = sum(R(N, x-2) + R(N, x-3) + ... R(N, x-N-1))\n\nThe initial values of the sequences are:\n:: {| style=\"text-align: left;\" border=\"4\" cellpadding=\"2\" cellspacing=\"2\"\n|+ Padovan n-step sequences\n|- style=\"background-color: rgb(255, 204, 255);\"\n! n !! Values !! [https://oeis.org OEIS] Entry\n|-\n| 2 || 1,1,1,2,2,3,4,5,7,9,12,16,21,28,37, ... || [https://oeis.org/A134816 A134816]: 'Padovan's spiral numbers'\n|-\n| 3 || 1,1,1,2,3,4,6,9,13,19,28,41,60,88,129, ... || [https://oeis.org/A000930 A000930]: 'Narayana's cows sequence'\n|-\n| 4 || 1,1,1,2,3,5,7,11,17,26,40,61,94,144,221, ... || [https://oeis.org/A072465 A072465]: 'A Fibonacci-like model in which each pair of rabbits dies after the birth of their 4th litter'\n|-\n| 5 || 1,1,1,2,3,5,8,12,19,30,47,74,116,182,286, ... || [https://oeis.org/A060961 A060961]: 'Number of compositions (ordered partitions) of n into 1's, 3's and 5's'\n|-\n| 6 || 1,1,1,2,3,5,8,13,20,32,51,81,129,205,326, ... || \n|-\n| 7 || 1,1,1,2,3,5,8,13,21,33,53,85,136,218,349, ... || [https://oeis.org/A117760 A117760]: 'Expansion of 1/(1 - x - x^3 - x^5 - x^7)'\n|-\n| 8 || 1,1,1,2,3,5,8,13,21,34,54,87,140,225,362, ... || \n|-\n|}\n\n\n;Task:\n# Write a function to generate the first t terms, of the first 2..max_n Padovan n-step number sequences as defined above.\n# Use this to print and show here at least the first t=15 values of the first 2..8 n-step sequences. (The [https://oeis.org OEIS] column in the table above should be omitted).\n\n", "solution": "#include \n\nvoid padovanN(int n, size_t t, int *p) {\n int i, j;\n if (n < 2 || t < 3) {\n for (i = 0; i < t; ++i) p[i] = 1;\n return;\n }\n padovanN(n-1, t, p);\n for (i = n + 1; i < t; ++i) {\n p[i] = 0;\n for (j = i - 2; j >= i - n - 1; --j) p[i] += p[j];\n }\n}\n\nint main() {\n int n, i;\n const size_t t = 15;\n int p[t];\n printf(\"First %ld terms of the Padovan n-step number sequences:\\n\", t);\n for (n = 2; n <= 8; ++n) {\n for (i = 0; i < t; ++i) p[i] = 0;\n padovanN(n, t, p);\n printf(\"%d: \", n);\n for (i = 0; i < t; ++i) printf(\"%3d \", p[i]);\n printf(\"\\n\");\n }\n return 0;\n}"} +{"title": "Padovan n-step number sequences", "language": "JavaScript", "task": "As the [[Fibonacci sequence]] expands to the [[Fibonacci n-step number sequences]]; We similarly expand the [[Padovan sequence]] to form these Padovan n-step number sequences.\n\nThe Fibonacci-like sequences can be defined like this:\n\n For n == 2:\n start: 1, 1\n Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n == 2\n For n == N:\n start: First N terms of R(N-1, x)\n Recurrence: R(N, x) = sum(R(N, x-1) + R(N, x-2) + ... R(N, x-N))\n\nFor this task we similarly define terms of the first 2..n-step Padovan sequences as:\n\n For n == 2:\n start: 1, 1, 1\n Recurrence: R(n, x) = R(n, x-2) + R(n, x-3); for n == 2\n For n == N:\n start: First N + 1 terms of R(N-1, x)\n Recurrence: R(N, x) = sum(R(N, x-2) + R(N, x-3) + ... R(N, x-N-1))\n\nThe initial values of the sequences are:\n:: {| style=\"text-align: left;\" border=\"4\" cellpadding=\"2\" cellspacing=\"2\"\n|+ Padovan n-step sequences\n|- style=\"background-color: rgb(255, 204, 255);\"\n! n !! Values !! [https://oeis.org OEIS] Entry\n|-\n| 2 || 1,1,1,2,2,3,4,5,7,9,12,16,21,28,37, ... || [https://oeis.org/A134816 A134816]: 'Padovan's spiral numbers'\n|-\n| 3 || 1,1,1,2,3,4,6,9,13,19,28,41,60,88,129, ... || [https://oeis.org/A000930 A000930]: 'Narayana's cows sequence'\n|-\n| 4 || 1,1,1,2,3,5,7,11,17,26,40,61,94,144,221, ... || [https://oeis.org/A072465 A072465]: 'A Fibonacci-like model in which each pair of rabbits dies after the birth of their 4th litter'\n|-\n| 5 || 1,1,1,2,3,5,8,12,19,30,47,74,116,182,286, ... || [https://oeis.org/A060961 A060961]: 'Number of compositions (ordered partitions) of n into 1's, 3's and 5's'\n|-\n| 6 || 1,1,1,2,3,5,8,13,20,32,51,81,129,205,326, ... || \n|-\n| 7 || 1,1,1,2,3,5,8,13,21,33,53,85,136,218,349, ... || [https://oeis.org/A117760 A117760]: 'Expansion of 1/(1 - x - x^3 - x^5 - x^7)'\n|-\n| 8 || 1,1,1,2,3,5,8,13,21,34,54,87,140,225,362, ... || \n|-\n|}\n\n\n;Task:\n# Write a function to generate the first t terms, of the first 2..max_n Padovan n-step number sequences as defined above.\n# Use this to print and show here at least the first t=15 values of the first 2..8 n-step sequences. (The [https://oeis.org OEIS] column in the table above should be omitted).\n\n", "solution": "(() => {\n \"use strict\";\n\n // ---------- PADOVAN N-STEP NUMBER SERIES -----------\n\n // padovans :: Int -> [Int]\n const padovans = n => {\n // Padovan number series of step N\n const recurrence = ns => [\n ns[0],\n ns.slice(1).concat(\n sum(take(n)(ns))\n )\n ];\n\n\n return 0 > n ? (\n []\n ) : unfoldr(recurrence)(\n take(1 + n)(\n 3 > n ? (\n repeat(1)\n ) : padovans(n - 1)\n )\n );\n };\n\n // ---------------------- TEST -----------------------\n // main :: IO ()\n const main = () =>\n fTable(\"Padovan N-step series:\")(str)(\n xs => xs.map(\n compose(justifyRight(4)(\" \"), str)\n )\n .join(\"\")\n )(\n compose(take(15), padovans)\n )(\n enumFromTo(2)(8)\n );\n\n\n // --------------------- GENERIC ---------------------\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (...fs) =>\n // A function defined by the right-to-left\n // composition of all the functions in fs.\n fs.reduce(\n (f, g) => x => f(g(x)),\n x => x\n );\n\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = m =>\n n => Array.from({\n length: 1 + n - m\n }, (_, i) => m + i);\n\n\n // repeat :: a -> Generator [a]\n const repeat = function* (x) {\n while (true) {\n yield x;\n }\n };\n\n\n // sum :: [Num] -> Num\n const sum = xs =>\n // The numeric sum of all values in xs.\n xs.reduce((a, x) => a + x, 0);\n\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n =>\n // The first n elements of a list,\n // string of characters, or stream.\n xs => \"GeneratorFunction\" !== xs\n .constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat(...Array.from({\n length: n\n }, () => {\n const x = xs.next();\n\n return x.done ? [] : [x.value];\n }));\n\n\n // unfoldr :: (b -> Maybe (a, b)) -> b -> Gen [a]\n const unfoldr = f =>\n // A lazy (generator) list unfolded from a seed value\n // by repeated application of f to a value until no\n // residue remains. Dual to fold/reduce.\n // f returns either Nothing or Just (value, residue).\n // For a strict output list,\n // wrap with `list` or Array.from\n x => (\n function* () {\n let valueResidue = f(x);\n\n while (null !== valueResidue) {\n yield valueResidue[0];\n valueResidue = f(valueResidue[1]);\n }\n }()\n );\n\n // ------------------- FORMATTING --------------------\n\n // fTable :: String -> (a -> String) ->\n // (b -> String) -> (a -> b) -> [a] -> String\n const fTable = s =>\n // Heading -> x display function ->\n // fx display function ->\n // f -> values -> tabular string\n xShow => fxShow => f => xs => {\n const\n ys = xs.map(xShow),\n w = Math.max(...ys.map(y => [...y].length)),\n table = zipWith(\n a => b => `${a.padStart(w, \" \")} ->${b}`\n )(ys)(\n xs.map(x => fxShow(f(x)))\n ).join(\"\\n\");\n\n return `${s}\\n${table}`;\n };\n\n\n // justifyRight :: Int -> Char -> String -> String\n const justifyRight = n =>\n // The string s, preceded by enough padding (with\n // the character c) to reach the string length n.\n c => s => n > s.length ? (\n s.padStart(n, c)\n ) : s;\n\n\n // str :: a -> String\n const str = x => `${x}`;\n\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = f =>\n // A list constructed by zipping with a\n // custom function, rather than with the\n // default tuple constructor.\n xs => ys => take(\n Math.min(xs.length, ys.length)\n )(\n xs.map((x, i) => f(x)(ys[i]))\n );\n\n // MAIN ---\n return main();\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\u2026 || 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* [https://www.youtube.com/watch?v=PsGUEj4w9Cc 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": "Padovan sequence", "language": "JavaScript", "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\u2026 || 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* [https://www.youtube.com/watch?v=PsGUEj4w9Cc The Plastic Ratio] - Numberphile video.\n\n\n", "solution": "(() => {\n \"use strict\";\n\n // ----------------- PADOVAN NUMBERS -----------------\n\n // padovans :: [Int]\n const padovans = () => {\n // Non-finite series of Padovan numbers,\n // defined in terms of recurrence relations.\n const f = ([a, b, c]) => [\n a,\n [b, c, a + b]\n ];\n\n return unfoldr(f)([1, 1, 1]);\n };\n\n\n // padovanFloor :: [Int]\n const padovanFloor = () => {\n // The Padovan series, defined in terms\n // of a floor function.\n const\n // NB JavaScript loses some of this\n // precision at run-time.\n p = 1.324717957244746025960908854,\n s = 1.0453567932525329623;\n\n const f = n => [\n Math.floor(((p ** (n - 1)) / s) + 0.5),\n 1 + n\n ];\n\n return unfoldr(f)(0);\n };\n\n\n // padovanLSystem : [Int]\n const padovanLSystem = () => {\n // An L-system generating terms whose lengths\n // are the values of the Padovan integer series.\n const rule = c =>\n \"A\" === c ? (\n \"B\"\n ) : \"B\" === c ? (\n \"C\"\n ) : \"AB\";\n\n const f = s => [\n s,\n chars(s).flatMap(rule)\n .join(\"\")\n ];\n\n return unfoldr(f)(\"A\");\n };\n\n\n // ---------------------- TEST -----------------------\n // main :: IO ()\n const main = () => {\n // prefixesMatch :: [a] -> [a] -> Bool\n const prefixesMatch = xs =>\n ys => n => and(\n zipWith(a => b => a === b)(\n take(n)(xs)\n )(\n take(n)(ys)\n )\n );\n\n return [\n \"First 20 padovans:\",\n take(20)(padovans()),\n\n \"\\nThe recurrence and floor-based functions\",\n \"match over the first 64 terms:\\n\",\n prefixesMatch(\n padovans()\n )(\n padovanFloor()\n )(64),\n\n \"\\nFirst 10 L-System strings:\",\n take(10)(padovanLSystem()),\n\n \"\\nThe lengths of the first 32 L-System\",\n \"strings match the Padovan sequence:\\n\",\n prefixesMatch(\n padovans()\n )(\n fmap(length)(padovanLSystem())\n )(32)\n ]\n .map(str)\n .join(\"\\n\");\n };\n\n // --------------------- GENERIC ---------------------\n\n // and :: [Bool] -> Bool\n const and = xs =>\n // True unless any value in xs is false.\n [...xs].every(Boolean);\n\n\n // chars :: String -> [Char]\n const chars = s =>\n s.split(\"\");\n\n\n // fmap <$> :: (a -> b) -> Gen [a] -> Gen [b]\n const fmap = f =>\n function* (gen) {\n let v = take(1)(gen);\n\n while (0 < v.length) {\n yield f(v[0]);\n v = take(1)(gen);\n }\n };\n\n\n // length :: [a] -> Int\n const length = xs =>\n // Returns Infinity over objects without finite\n // length. This enables zip and zipWith to choose\n // the shorter argument when one is non-finite,\n // like cycle, repeat etc\n \"GeneratorFunction\" !== xs.constructor\n .constructor.name ? (\n xs.length\n ) : Infinity;\n\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n =>\n // The first n elements of a list,\n // string of characters, or stream.\n xs => \"GeneratorFunction\" !== xs\n .constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat(...Array.from({\n length: n\n }, () => {\n const x = xs.next();\n\n return x.done ? [] : [x.value];\n }));\n\n\n // str :: a -> String\n const str = x =>\n \"string\" !== typeof x ? (\n JSON.stringify(x)\n ) : x;\n\n\n // unfoldr :: (b -> Maybe (a, b)) -> b -> Gen [a]\n const unfoldr = f =>\n // A lazy (generator) list unfolded from a seed value\n // by repeated application of f to a value until no\n // residue remains. Dual to fold/reduce.\n // f returns either Null or just (value, residue).\n // For a strict output list,\n // wrap with `list` or Array.from\n x => (\n function* () {\n let valueResidue = f(x);\n\n while (null !== valueResidue) {\n yield valueResidue[0];\n valueResidue = f(valueResidue[1]);\n }\n }()\n );\n\n\n // zipWithList :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = f =>\n // A list constructed by zipping with a\n // custom function, rather than with the\n // default tuple constructor.\n xs => ys => ((xs_, ys_) => {\n const lng = Math.min(length(xs_), length(ys_));\n\n return take(lng)(xs_).map(\n (x, i) => f(x)(ys_[i])\n );\n })([...xs], [...ys]);\n\n // MAIN ---\n return main();\n})();"} +{"title": "Palindrome dates", "language": "C", "task": "Today \u00a0 ('''2020-02-02''', \u00a0 at the time of this writing) \u00a0 happens to be a palindrome, \u00a0 without the hyphens, \u00a0 not only for those countries which express their dates in the \u00a0 '''yyyy-mm-dd''' \u00a0 format but, \u00a0 unusually, \u00a0 also for countries which use the \u00a0 '''dd-mm-yyyy''' \u00a0 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 \u00a0 '''yyyy-mm-dd''' \u00a0 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(\u00d7tamp);\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": "Palindrome dates", "language": "Python", "task": "Today \u00a0 ('''2020-02-02''', \u00a0 at the time of this writing) \u00a0 happens to be a palindrome, \u00a0 without the hyphens, \u00a0 not only for those countries which express their dates in the \u00a0 '''yyyy-mm-dd''' \u00a0 format but, \u00a0 unusually, \u00a0 also for countries which use the \u00a0 '''dd-mm-yyyy''' \u00a0 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 \u00a0 '''yyyy-mm-dd''' \u00a0 format.\n\n", "solution": "===Functional===\nDefined in terms of string reversal:\n"} +{"title": "Palindrome dates", "language": "Python 3.7", "task": "Today \u00a0 ('''2020-02-02''', \u00a0 at the time of this writing) \u00a0 happens to be a palindrome, \u00a0 without the hyphens, \u00a0 not only for those countries which express their dates in the \u00a0 '''yyyy-mm-dd''' \u00a0 format but, \u00a0 unusually, \u00a0 also for countries which use the \u00a0 '''dd-mm-yyyy''' \u00a0 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 \u00a0 '''yyyy-mm-dd''' \u00a0 format.\n\n", "solution": "'''Palindrome dates'''\n\nfrom datetime import datetime\nfrom itertools import chain\n\n\n# palinDay :: Int -> [ISO Date]\ndef palinDay(y):\n '''A possibly empty list containing the palindromic\n date for the given year, if such a date exists.\n '''\n s = str(y)\n r = s[::-1]\n iso = '-'.join([s, r[0:2], r[2:]])\n try:\n datetime.strptime(iso, '%Y-%m-%d')\n return [iso]\n except ValueError:\n return []\n\n\n# --------------------------TEST---------------------------\n# main :: IO ()\ndef main():\n '''Count and samples of palindromic dates [2021..9999]\n '''\n palinDates = list(chain.from_iterable(\n map(palinDay, range(2021, 10000))\n ))\n for x in [\n 'Count of palindromic dates [2021..9999]:',\n len(palinDates),\n '\\nFirst 15:',\n '\\n'.join(palinDates[0:15]),\n '\\nLast 15:',\n '\\n'.join(palinDates[-15:])\n ]:\n print(x)\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} +{"title": "Palindromic gapful numbers", "language": "C", "task": "Numbers \u00a0 (positive integers expressed in base ten) \u00a0 that are (evenly) divisible by the number formed by the\nfirst and last digit are known as \u00a0 '''gapful numbers'''.\n\n\n''Evenly divisible'' \u00a0 means divisible with \u00a0 no \u00a0 remainder.\n\n\nAll \u00a0 one\u2500 \u00a0 and two\u2500digit \u00a0 numbers have this property and are trivially excluded. \u00a0 Only\nnumbers \u00a0 \u2265 '''100''' \u00a0 will be considered for this Rosetta Code task.\n\n\n;Example:\n'''1037''' \u00a0 is a \u00a0 '''gapful''' \u00a0 number because it is evenly divisible by the\nnumber \u00a0 '''17''' \u00a0 which is formed by the first and last decimal digits\nof \u00a0 '''1037'''. \n\n\nA palindromic number is \u00a0 (for this task, a positive integer expressed in base ten), \u00a0 when the number is \nreversed, \u00a0 is the same as the original number.\n\n\n;Task:\n:* \u00a0 Show \u00a0 (nine sets) \u00a0 the first \u00a0 '''20''' \u00a0 palindromic gapful numbers that \u00a0 ''end'' \u00a0 with:\n:::* \u00a0 the digit \u00a0 '''1'''\n:::* \u00a0 the digit \u00a0 '''2'''\n:::* \u00a0 the digit \u00a0 '''3'''\n:::* \u00a0 the digit \u00a0 '''4'''\n:::* \u00a0 the digit \u00a0 '''5'''\n:::* \u00a0 the digit \u00a0 '''6'''\n:::* \u00a0 the digit \u00a0 '''7'''\n:::* \u00a0 the digit \u00a0 '''8'''\n:::* \u00a0 the digit \u00a0 '''9'''\n:* \u00a0 Show \u00a0 (nine sets, like above) \u00a0 of palindromic gapful numbers:\n:::* \u00a0 the last \u00a0 '''15''' \u00a0 palindromic gapful numbers \u00a0 (out of \u00a0 \u00a0 \u00a0'''100''')\n:::* \u00a0 the last \u00a0 '''10''' \u00a0 palindromic gapful numbers \u00a0 (out of \u00a0 '''1,000''') \u00a0 \u00a0 \u00a0 {optional}\n\n\nFor other ways of expressing the (above) requirements, see the \u00a0 ''discussion'' \u00a0 page.\n\n\n;Note:\nAll palindromic gapful numbers are divisible by eleven. \n\n\n;Related tasks:\n:* \u00a0 [https://rosettacode.org/wiki/Palindrome_detection palindrome detection].\n:* \u00a0 [https://rosettacode.org/wiki/Gapful_numbers gapful numbers].\n\n\n;Also see:\n:* \u00a0 The OEIS entry: \u00a0 [https://oeis.org/A108343 A108343 gapful numbers].\n\n", "solution": "#include \n#include \n#include \n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n integer rev = 0;\n while (n > 0) {\n rev = rev * 10 + (n % 10);\n n /= 10;\n }\n return rev;\n}\n\ntypedef struct palgen_tag {\n integer power;\n integer next;\n int digit;\n bool even;\n} palgen_t;\n\nvoid init_palgen(palgen_t* palgen, int digit) {\n palgen->power = 10;\n palgen->next = digit * palgen->power - 1;\n palgen->digit = digit;\n palgen->even = false;\n}\n\ninteger next_palindrome(palgen_t* p) {\n ++p->next;\n if (p->next == p->power * (p->digit + 1)) {\n if (p->even)\n p->power *= 10;\n p->next = p->digit * p->power;\n p->even = !p->even;\n }\n return p->next * (p->even ? 10 * p->power : p->power)\n + reverse(p->even ? p->next : p->next/10);\n}\n\nbool gapful(integer n) {\n integer m = n;\n while (m >= 10)\n m /= 10;\n return n % (n % 10 + 10 * m) == 0;\n}\n\nvoid print(int len, integer array[][len]) {\n for (int digit = 1; digit < 10; ++digit) {\n printf(\"%d: \", digit);\n for (int i = 0; i < len; ++i)\n printf(\" %llu\", array[digit - 1][i]);\n printf(\"\\n\");\n }\n}\n\nint main() {\n const int n1 = 20, n2 = 15, n3 = 10;\n const int m1 = 100, m2 = 1000;\n\n integer pg1[9][n1];\n integer pg2[9][n2];\n integer pg3[9][n3];\n\n for (int digit = 1; digit < 10; ++digit) {\n palgen_t pgen;\n init_palgen(&pgen, digit);\n for (int i = 0; i < m2; ) {\n integer n = next_palindrome(&pgen);\n if (!gapful(n))\n continue;\n if (i < n1)\n pg1[digit - 1][i] = n;\n else if (i < m1 && i >= m1 - n2)\n pg2[digit - 1][i - (m1 - n2)] = n;\n else if (i >= m2 - n3)\n pg3[digit - 1][i - (m2 - n3)] = n;\n ++i;\n }\n }\n\n printf(\"First %d palindromic gapful numbers ending in:\\n\", n1);\n print(n1, pg1);\n\n printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n2, m1);\n print(n2, pg2);\n\n printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n3, m2);\n print(n3, pg3);\n\n return 0;\n}"} +{"title": "Palindromic gapful numbers", "language": "Python", "task": "Numbers \u00a0 (positive integers expressed in base ten) \u00a0 that are (evenly) divisible by the number formed by the\nfirst and last digit are known as \u00a0 '''gapful numbers'''.\n\n\n''Evenly divisible'' \u00a0 means divisible with \u00a0 no \u00a0 remainder.\n\n\nAll \u00a0 one\u2500 \u00a0 and two\u2500digit \u00a0 numbers have this property and are trivially excluded. \u00a0 Only\nnumbers \u00a0 \u2265 '''100''' \u00a0 will be considered for this Rosetta Code task.\n\n\n;Example:\n'''1037''' \u00a0 is a \u00a0 '''gapful''' \u00a0 number because it is evenly divisible by the\nnumber \u00a0 '''17''' \u00a0 which is formed by the first and last decimal digits\nof \u00a0 '''1037'''. \n\n\nA palindromic number is \u00a0 (for this task, a positive integer expressed in base ten), \u00a0 when the number is \nreversed, \u00a0 is the same as the original number.\n\n\n;Task:\n:* \u00a0 Show \u00a0 (nine sets) \u00a0 the first \u00a0 '''20''' \u00a0 palindromic gapful numbers that \u00a0 ''end'' \u00a0 with:\n:::* \u00a0 the digit \u00a0 '''1'''\n:::* \u00a0 the digit \u00a0 '''2'''\n:::* \u00a0 the digit \u00a0 '''3'''\n:::* \u00a0 the digit \u00a0 '''4'''\n:::* \u00a0 the digit \u00a0 '''5'''\n:::* \u00a0 the digit \u00a0 '''6'''\n:::* \u00a0 the digit \u00a0 '''7'''\n:::* \u00a0 the digit \u00a0 '''8'''\n:::* \u00a0 the digit \u00a0 '''9'''\n:* \u00a0 Show \u00a0 (nine sets, like above) \u00a0 of palindromic gapful numbers:\n:::* \u00a0 the last \u00a0 '''15''' \u00a0 palindromic gapful numbers \u00a0 (out of \u00a0 \u00a0 \u00a0'''100''')\n:::* \u00a0 the last \u00a0 '''10''' \u00a0 palindromic gapful numbers \u00a0 (out of \u00a0 '''1,000''') \u00a0 \u00a0 \u00a0 {optional}\n\n\nFor other ways of expressing the (above) requirements, see the \u00a0 ''discussion'' \u00a0 page.\n\n\n;Note:\nAll palindromic gapful numbers are divisible by eleven. \n\n\n;Related tasks:\n:* \u00a0 [https://rosettacode.org/wiki/Palindrome_detection palindrome detection].\n:* \u00a0 [https://rosettacode.org/wiki/Gapful_numbers gapful numbers].\n\n\n;Also see:\n:* \u00a0 The OEIS entry: \u00a0 [https://oeis.org/A108343 A108343 gapful numbers].\n\n", "solution": "from itertools import count\nfrom pprint import pformat\nimport re\nimport heapq\n\n\ndef pal_part_gen(odd=True):\n for i in count(1):\n fwd = str(i)\n rev = fwd[::-1][1:] if odd else fwd[::-1]\n yield int(fwd + rev)\n\ndef pal_ordered_gen():\n yield from heapq.merge(pal_part_gen(odd=True), pal_part_gen(odd=False))\n\ndef is_gapful(x):\n return (x % (int(str(x)[0]) * 10 + (x % 10)) == 0)\n\nif __name__ == '__main__':\n start = 100\n for mx, last in [(20, 20), (100, 15), (1_000, 10)]:\n print(f\"\\nLast {last} of the first {mx} binned-by-last digit \" \n f\"gapful numbers >= {start}\")\n bin = {i: [] for i in range(1, 10)}\n gen = (i for i in pal_ordered_gen() if i >= start and is_gapful(i))\n while any(len(val) < mx for val in bin.values()):\n g = next(gen)\n val = bin[g % 10]\n if len(val) < mx:\n val.append(g)\n b = {k:v[-last:] for k, v in bin.items()}\n txt = pformat(b, width=220)\n print('', re.sub(r\"[{},\\[\\]]\", '', txt))"} +{"title": "Pancake numbers", "language": "C", "task": "Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers.\n\nThe task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips.\n\n[[Sorting_algorithms/Pancake_sort]] actually performs the sort some giving the number of flips used. How do these compare with p(n)?\n\nFew people know p(20), generously I shall award an extra credit for anyone doing more than p(16).\n\n\n;References\n# [https://www.bbvaopenmind.com/en/science/mathematics/bill-gates-and-the-pancake-problem Bill Gates and the pancake problem]\n# [https://oeis.org/A058986 A058986]\n\n", "solution": "#include \n\nint pancake(int n) {\n int gap = 2, sum = 2, adj = -1;\n while (sum < n) {\n adj++;\n gap = gap * 2 - 1;\n sum += gap;\n }\n return n + adj;\n}\n\nint main() {\n int i, j;\n for (i = 0; i < 4; i++) {\n for (j = 1; j < 6; j++) {\n int n = i * 5 + j;\n printf(\"p(%2d) = %2d \", n, pancake(n));\n }\n printf(\"\\n\");\n }\n return 0;\n}"} +{"title": "Pancake numbers", "language": "Python 3.7", "task": "Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers.\n\nThe task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips.\n\n[[Sorting_algorithms/Pancake_sort]] actually performs the sort some giving the number of flips used. How do these compare with p(n)?\n\nFew people know p(20), generously I shall award an extra credit for anyone doing more than p(16).\n\n\n;References\n# [https://www.bbvaopenmind.com/en/science/mathematics/bill-gates-and-the-pancake-problem Bill Gates and the pancake problem]\n# [https://oeis.org/A058986 A058986]\n\n", "solution": "\"\"\"Pancake numbers. Requires Python>=3.7.\"\"\"\nimport time\n\nfrom collections import deque\nfrom operator import itemgetter\nfrom typing import Tuple\n\nPancakes = Tuple[int, ...]\n\n\ndef flip(pancakes: Pancakes, position: int) -> Pancakes:\n \"\"\"Flip the stack of pancakes at the given position.\"\"\"\n return tuple([*reversed(pancakes[:position]), *pancakes[position:]])\n\n\ndef pancake(n: int) -> Tuple[Pancakes, int]:\n \"\"\"Return the nth pancake number.\"\"\"\n init_stack = tuple(range(1, n + 1))\n stack_flips = {init_stack: 0}\n queue = deque([init_stack])\n\n while queue:\n stack = queue.popleft()\n flips = stack_flips[stack] + 1\n\n for i in range(2, n + 1):\n flipped = flip(stack, i)\n if flipped not in stack_flips:\n stack_flips[flipped] = flips\n queue.append(flipped)\n\n return max(stack_flips.items(), key=itemgetter(1))\n\n\nif __name__ == \"__main__\":\n start = time.time()\n\n for n in range(1, 10):\n pancakes, p = pancake(n)\n print(f\"pancake({n}) = {p:>2}. Example: {list(pancakes)}\")\n\n print(f\"\\nTook {time.time() - start:.3} seconds.\")\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: \u00a0 ''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 \u00a0 pangram \u00a0 (or not) \u00a0 and show its use.\n\n\n;Related tasks:\n:* \u00a0 [https://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters determine if a string has all the same characters]\n:* \u00a0 [https://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters 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": "Pangram checker", "language": "JavaScript", "task": "A pangram is a sentence that contains all the letters of the English alphabet at least once.\n\nFor example: \u00a0 ''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 \u00a0 pangram \u00a0 (or not) \u00a0 and show its use.\n\n\n;Related tasks:\n:* \u00a0 [https://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters determine if a string has all the same characters]\n:* \u00a0 [https://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters determine if a string has all unique characters]\n\n", "solution": "(() => {\n \"use strict\";\n\n // ----------------- PANGRAM CHECKER -----------------\n\n // isPangram :: String -> Bool\n const isPangram = s =>\n 0 === \"abcdefghijklmnopqrstuvwxyz\"\n .split(\"\")\n .filter(c => -1 === s.toLowerCase().indexOf(c))\n .length;\n\n // ---------------------- TEST -----------------------\n return [\n \"is this a pangram\",\n \"The quick brown fox jumps over the lazy dog\"\n ].map(isPangram);\n})();"} +{"title": "Pangram checker", "language": "Python", "task": "A pangram is a sentence that contains all the letters of the English alphabet at least once.\n\nFor example: \u00a0 ''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 \u00a0 pangram \u00a0 (or not) \u00a0 and show its use.\n\n\n;Related tasks:\n:* \u00a0 [https://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters determine if a string has all the same characters]\n:* \u00a0 [https://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters determine if a string has all unique characters]\n\n", "solution": "import string, sys\nif sys.version_info[0] < 3:\n input = raw_input\n\ndef ispangram(sentence, alphabet=string.ascii_lowercase):\n alphaset = set(alphabet)\n return alphaset <= set(sentence.lower())\n\nprint ( ispangram(input('Sentence: ')) )"} +{"title": "Paraffins", "language": "C", "task": "right\n\nThis 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. \u00a0 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. \u00a0 So all paraffins with \u00a0 '''n''' \u00a0 carbon atoms share the empirical formula \u00a0 \u00a0 CnH2n+2\n\nBut for all \u00a0 '''n''' \u2265 4 \u00a0 there are several distinct molecules (\"isomers\") with the same formula but different structures. \n\nThe number of isomers rises rather rapidly when \u00a0 '''n''' \u00a0 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), \u00a0 so rotations or re-orientations of parts of the molecule (without breaking bonds) do not give different isomers. \u00a0 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 \u00a0 '''n''' = 3 \u00a0 there is only one way of linking the carbons despite the different orientations the molecule can be drawn; \u00a0 and with \u00a0 '''n''' = 4 \u00a0 there are two configurations: \n:::* \u00a0 a \u00a0 straight \u00a0 chain: \u00a0 \u00a0 (CH3)(CH2)(CH2)(CH3) \n:::* \u00a0 a branched chain: \u00a0 \u00a0 \u00a0 (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 \u00a0 '''n''' \u00a0 of carbon atoms of a molecule (for instance '''17'''). \n\nThe output is how many different different paraffins there are with \u00a0 '''n''' \u00a0 carbon atoms (for instance \u00a0 24,894 \u00a0 if \u00a0 '''n''' = 17).\n\nThe sequence of those results is visible in the OEIS entry: \u00a0 \n::: \u00a0 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 \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2502\n H \u2500 C \u2500 H H \u2500 C \u2500 C \u2500 H H \u2500 C \u2500 C \u2500 C \u2500 H H \u2500 C \u2500 C \u2500 C \u2500 H\n \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2502\n H H H H H H H \u2502 H\n \u2502\n H \u2500 C \u2500 H\n \u2502\n H \n\n;Links:\n* \u00a0 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* \u00a0 A Haskell implementation:\nhttps://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs\n\n* \u00a0 A Scheme implementation:\nhttp://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm\n\n* \u00a0 A Fortress implementation: \u00a0 \u00a0 \u00a0 \u00a0 (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": "Paraffins", "language": "Python", "task": "right\n\nThis 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. \u00a0 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. \u00a0 So all paraffins with \u00a0 '''n''' \u00a0 carbon atoms share the empirical formula \u00a0 \u00a0 CnH2n+2\n\nBut for all \u00a0 '''n''' \u2265 4 \u00a0 there are several distinct molecules (\"isomers\") with the same formula but different structures. \n\nThe number of isomers rises rather rapidly when \u00a0 '''n''' \u00a0 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), \u00a0 so rotations or re-orientations of parts of the molecule (without breaking bonds) do not give different isomers. \u00a0 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 \u00a0 '''n''' = 3 \u00a0 there is only one way of linking the carbons despite the different orientations the molecule can be drawn; \u00a0 and with \u00a0 '''n''' = 4 \u00a0 there are two configurations: \n:::* \u00a0 a \u00a0 straight \u00a0 chain: \u00a0 \u00a0 (CH3)(CH2)(CH2)(CH3) \n:::* \u00a0 a branched chain: \u00a0 \u00a0 \u00a0 (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 \u00a0 '''n''' \u00a0 of carbon atoms of a molecule (for instance '''17'''). \n\nThe output is how many different different paraffins there are with \u00a0 '''n''' \u00a0 carbon atoms (for instance \u00a0 24,894 \u00a0 if \u00a0 '''n''' = 17).\n\nThe sequence of those results is visible in the OEIS entry: \u00a0 \n::: \u00a0 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 \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2502\n H \u2500 C \u2500 H H \u2500 C \u2500 C \u2500 H H \u2500 C \u2500 C \u2500 C \u2500 H H \u2500 C \u2500 C \u2500 C \u2500 H\n \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2502\n H H H H H H H \u2502 H\n \u2502\n H \u2500 C \u2500 H\n \u2502\n H \n\n;Links:\n* \u00a0 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* \u00a0 A Haskell implementation:\nhttps://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs\n\n* \u00a0 A Scheme implementation:\nhttp://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm\n\n* \u00a0 A Fortress implementation: \u00a0 \u00a0 \u00a0 \u00a0 (this site has been closed)\nhttp://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005\n\n", "solution": "from itertools import count, chain, tee, islice, cycle\nfrom fractions import Fraction\nfrom sys import setrecursionlimit\nsetrecursionlimit(5000)\n\ndef frac(a,b): return a//b if a%b == 0 else Fraction(a,b)\n\n# infinite polynomial class\nclass Poly:\n def __init__(self, gen = None):\n self.gen, self.source = (None, gen) if type(gen) is Poly \\\n else (gen, None)\n\n def __iter__(self):\n # We're essentially tee'ing it everytime the iterator\n # is, well, iterated. This may be excessive.\n return Poly(self)\n\n def getsource(self):\n if self.gen == None:\n s = self.source\n s.getsource()\n s.gen, self.gen = tee(s.gen, 2)\n\n def next(self):\n self.getsource()\n return next(self.gen)\n\n __next__ = next\n\n # Overload \"<<\" as stream input operator. Hey, C++ does it.\n def __lshift__(self, a): self.gen = a\n\n # The other operators are pretty much what one would expect\n def __neg__(self): return Poly(-x for x in self)\n\n def __sub__(a, b): return a + (-b)\n\n def __rsub__(a, n):\n a = Poly(a)\n def gen():\n yield(n - next(a))\n for x in a: yield(-x)\n return Poly(gen())\n\n def __add__(a, b):\n if type(b) is Poly:\n return Poly(x + y for (x,y) in zip(a,b))\n\n a = Poly(a)\n def gen():\n yield(next(a) + b)\n for x in a: yield(x)\n\n return Poly(gen())\n\n def __radd__(a,b):\n return a + b\n\n def __mul__(a,b):\n if not type(b) is Poly:\n return Poly(x*b for x in a)\n\n def gen():\n s = Poly(cycle([0]))\n for y in b:\n s += y*a\n yield(next(s))\n\n return Poly(gen())\n\n def __rmul__(a,b): return a*b\n\n def __truediv__(a,b):\n if not type(b) is Poly:\n return Poly(frac(x, b) for x in a)\n\n a, b = Poly(a), Poly(b)\n def gen():\n r, bb = a,next(b)\n while True:\n aa = next(r)\n q = frac(aa, bb)\n yield(q)\n r -= q*b\n\n return Poly(gen())\n\n def repl(self, n):\n def gen():\n for x in self:\n yield(x)\n for i in range(n-1): yield(0)\n return Poly(gen())\n\n def __pow__(self, n):\n return Poly(self) if n == 1 else self * self**(n-1)\n\ndef S2(a,b): return (a*a + b)/2\ndef S4(a,b,c,d): return a**4/24 + a**2*b/4 + a*c/3 + b**2/8 + d/4\n\nx1 = Poly()\nx2 = x1.repl(2)\nx3 = x1.repl(3)\nx4 = x1.repl(4)\nx1 << chain([1], (x1**3 + 3*x1*x2 + 2*x3)/6)\n\na598 = x1\na678 = Poly(chain([0], S4(x1, x2, x3, x4)))\na599 = S2(x1 - 1, x2 - 1)\na602 = a678 - a599 + x2\n\nfor n,x in zip(count(0), islice(a602, 500)): print(n,x)"} +{"title": "Parse an IP Address", "language": "C", "task": "The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6.\n \n\nTaking the following as inputs:\n::: {| border=\"5\" cellspacing=\"0\" cellpadding=2\n|-\n|127.0.0.1\n|The \"localhost\" IPv4 address\n|-\n|127.0.0.1:80\n|The \"localhost\" IPv4 address, with a specified port (80)\n|-\n|::1\n|The \"localhost\" IPv6 address\n|-\n|[::1]:80\n|The \"localhost\" IPv6 address, with a specified port (80)\n|-\n|2605:2700:0:3::4713:93e3\n|Rosetta Code's primary server's public IPv6 address\n|-\n|[2605:2700:0:3::4713:93e3]:80\n|Rosetta Code's primary server's public IPv6 address, with a specified port (80)\n|}\n\n\n;Task:\nEmit each described IP address as a hexadecimal integer representing the address, the address space, and the port number specified, if any. \n\nIn languages where variant result types are clumsy, the result should be ipv4 or ipv6 address number, something which says which address space was represented, port number and something that says if the port was specified.\n\n\n;Example:\n'''127.0.0.1''' \u00a0 has the address number \u00a0 '''7F000001''' \u00a0 (2130706433 decimal) \nin the ipv4 address space. \n\n'''::ffff:127.0.0.1''' \u00a0 represents the same address in the ipv6 address space where it has the \naddress number \u00a0 '''FFFF7F000001''' \u00a0 (281472812449793 decimal). \n\n'''::1''' \u00a0 has address number \u00a0 '''1''' \u00a0 and serves the same purpose in the ipv6 address \nspace that \u00a0 '''127.0.0.1''' \u00a0 serves in the ipv4 address space.\n\n", "solution": "\n#include \n#include \n\n\nstatic unsigned int _parseDecimal ( const char** pchCursor )\n{\n unsigned int nVal = 0;\n char chNow;\n while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' )\n {\n //shift digit in\n nVal *= 10;\n nVal += chNow - '0';\n\n ++*pchCursor;\n }\n return nVal;\n}\n\n\n\nstatic unsigned int _parseHex ( const char** pchCursor )\n{\n unsigned int nVal = 0;\n char chNow;\n while ( chNow = **pchCursor & 0x5f, //(collapses case, but mutilates digits)\n (chNow >= ('0'&0x5f) && chNow <= ('9'&0x5f)) || \n (chNow >= 'A' && chNow <= 'F') \n )\n {\n unsigned char nybbleValue;\n chNow -= 0x10; //scootch digital values down; hex now offset by x31\n nybbleValue = ( chNow > 9 ? chNow - (0x31-0x0a) : chNow );\n //shift nybble in\n nVal <<= 4;\n nVal += nybbleValue;\n\n ++*pchCursor;\n }\n return nVal;\n}\n\n\n\n//Parse a textual IPv4 or IPv6 address, optionally with port, into a binary\n//array (for the address, in network order), and an optionally provided port.\n//Also, indicate which of those forms (4 or 6) was parsed. Return true on\n//success. ppszText must be a nul-terminated ASCII string. It will be\n//updated to point to the character which terminated parsing (so you can carry\n//on with other things. abyAddr must be 16 bytes. You can provide NULL for\n//abyAddr, nPort, bIsIPv6, if you are not interested in any of those\n//informations. If we request port, but there is no port part, then nPort will\n//be set to 0. There may be no whitespace leading or internal (though this may\n//be used to terminate a successful parse.\n//Note: the binary address and integer port are in network order.\nint ParseIPv4OrIPv6 ( const char** ppszText, \n unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )\n{\n unsigned char* abyAddrLocal;\n unsigned char abyDummyAddr[16];\n\n //find first colon, dot, and open bracket\n const char* pchColon = strchr ( *ppszText, ':' );\n const char* pchDot = strchr ( *ppszText, '.' );\n const char* pchOpenBracket = strchr ( *ppszText, '[' );\n const char* pchCloseBracket = NULL;\n\n\n //we'll consider this to (probably) be IPv6 if we find an open\n //bracket, or an absence of dots, or if there is a colon, and it\n //precedes any dots that may or may not be there\n int bIsIPv6local = NULL != pchOpenBracket || NULL == pchDot ||\n ( NULL != pchColon && ( NULL == pchDot || pchColon < pchDot ) );\n //OK, now do a little further sanity check our initial guess...\n if ( bIsIPv6local )\n {\n //if open bracket, then must have close bracket that follows somewhere\n pchCloseBracket = strchr ( *ppszText, ']' );\n if ( NULL != pchOpenBracket && ( NULL == pchCloseBracket ||\n pchCloseBracket < pchOpenBracket ) )\n return 0;\n }\n else //probably ipv4\n {\n //dots must exist, and precede any colons\n if ( NULL == pchDot || ( NULL != pchColon && pchColon < pchDot ) )\n return 0;\n }\n\n //we figured out this much so far....\n if ( NULL != pbIsIPv6 )\n *pbIsIPv6 = bIsIPv6local;\n \n //especially for IPv6 (where we will be decompressing and validating)\n //we really need to have a working buffer even if the caller didn't\n //care about the results.\n abyAddrLocal = abyAddr; //prefer to use the caller's\n if ( NULL == abyAddrLocal ) //but use a dummy if we must\n abyAddrLocal = abyDummyAddr;\n\n //OK, there should be no correctly formed strings which are miscategorized,\n //and now any format errors will be found out as we continue parsing\n //according to plan.\n if ( ! bIsIPv6local ) //try to parse as IPv4\n {\n //4 dotted quad decimal; optional port if there is a colon\n //since there are just 4, and because the last one can be terminated\n //differently, I'm just going to unroll any potential loop.\n unsigned char* pbyAddrCursor = abyAddrLocal;\n unsigned int nVal;\n const char* pszTextBefore = *ppszText;\n nVal =_parseDecimal ( ppszText ); //get first val\n if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText ) //must be in range and followed by dot and nonempty\n return 0;\n *(pbyAddrCursor++) = (unsigned char) nVal; //stick it in addr\n ++(*ppszText); //past the dot\n\n pszTextBefore = *ppszText;\n nVal =_parseDecimal ( ppszText ); //get second val\n if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )\n return 0;\n *(pbyAddrCursor++) = (unsigned char) nVal;\n ++(*ppszText); //past the dot\n\n pszTextBefore = *ppszText;\n nVal =_parseDecimal ( ppszText ); //get third val\n if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )\n return 0;\n *(pbyAddrCursor++) = (unsigned char) nVal;\n ++(*ppszText); //past the dot\n\n pszTextBefore = *ppszText;\n nVal =_parseDecimal ( ppszText ); //get fourth val\n if ( nVal > 255 || pszTextBefore == *ppszText ) //(we can terminate this one in several ways)\n return 0;\n *(pbyAddrCursor++) = (unsigned char) nVal;\n\n if ( ':' == **ppszText && NULL != pnPort ) //have port part, and we want it\n {\n unsigned short usPortNetwork; //save value in network order\n ++(*ppszText); //past the colon\n pszTextBefore = *ppszText;\n nVal =_parseDecimal ( ppszText );\n if ( nVal > 65535 || pszTextBefore == *ppszText )\n return 0;\n ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;\n ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );\n *pnPort = usPortNetwork;\n return 1;\n }\n else //finished just with ip address\n {\n if ( NULL != pnPort )\n *pnPort = 0; //indicate we have no port part\n return 1;\n }\n }\n else //try to parse as IPv6\n {\n unsigned char* pbyAddrCursor;\n unsigned char* pbyZerosLoc;\n int bIPv4Detected;\n int nIdx;\n //up to 8 16-bit hex quantities, separated by colons, with at most one\n //empty quantity, acting as a stretchy run of zeroes. optional port\n //if there are brackets followed by colon and decimal port number.\n //A further form allows an ipv4 dotted quad instead of the last two\n //16-bit quantities, but only if in the ipv4 space ::ffff:x:x .\n if ( NULL != pchOpenBracket ) //start past the open bracket, if it exists\n *ppszText = pchOpenBracket + 1;\n pbyAddrCursor = abyAddrLocal;\n pbyZerosLoc = NULL; //if we find a 'zero compression' location\n bIPv4Detected = 0;\n for ( nIdx = 0; nIdx < 8; ++nIdx ) //we've got up to 8 of these, so we will use a loop\n {\n const char* pszTextBefore = *ppszText;\n unsigned nVal =_parseHex ( ppszText ); //get value; these are hex\n if ( pszTextBefore == *ppszText ) //if empty, we are zero compressing; note the loc\n {\n if ( NULL != pbyZerosLoc ) //there can be only one!\n {\n //unless it's a terminal empty field, then this is OK, it just means we're done with the host part\n if ( pbyZerosLoc == pbyAddrCursor )\n {\n --nIdx;\n break;\n }\n return 0; //otherwise, it's a format error\n }\n if ( ':' != **ppszText ) //empty field can only be via :\n return 0;\n if ( 0 == nIdx ) //leading zero compression requires an extra peek, and adjustment\n {\n ++(*ppszText);\n if ( ':' != **ppszText )\n return 0;\n }\n\n pbyZerosLoc = pbyAddrCursor;\n ++(*ppszText);\n }\n else\n {\n if ( '.' == **ppszText ) //special case of ipv4 convenience notation\n {\n //who knows how to parse ipv4? we do!\n const char* pszTextlocal = pszTextBefore; //back it up\n unsigned char abyAddrlocal[16];\n int bIsIPv6local;\n int bParseResultlocal = ParseIPv4OrIPv6 ( &pszTextlocal, abyAddrlocal, NULL, &bIsIPv6local );\n *ppszText = pszTextlocal; //success or fail, remember the terminating char\n if ( ! bParseResultlocal || bIsIPv6local ) //must parse and must be ipv4\n return 0;\n //transfer addrlocal into the present location\n *(pbyAddrCursor++) = abyAddrlocal[0];\n *(pbyAddrCursor++) = abyAddrlocal[1];\n *(pbyAddrCursor++) = abyAddrlocal[2];\n *(pbyAddrCursor++) = abyAddrlocal[3];\n ++nIdx; //pretend like we took another short, since the ipv4 effectively is two shorts\n bIPv4Detected = 1; //remember how we got here for further validation later\n break; //totally done with address\n }\n\n if ( nVal > 65535 ) //must be 16 bit quantity\n return 0;\n *(pbyAddrCursor++) = nVal >> 8; //transfer in network order\n *(pbyAddrCursor++) = nVal & 0xff;\n if ( ':' == **ppszText ) //typical case inside; carry on\n {\n ++(*ppszText);\n }\n else //some other terminating character; done with this parsing parts\n {\n break;\n }\n }\n }\n \n //handle any zero compression we found\n if ( NULL != pbyZerosLoc )\n {\n int nHead = (int)( pbyZerosLoc - abyAddrLocal ); //how much before zero compression\n int nTail = nIdx * 2 - (int)( pbyZerosLoc - abyAddrLocal ); //how much after zero compression\n int nZeros = 16 - nTail - nHead; //how much zeros\n memmove ( &abyAddrLocal[16-nTail], pbyZerosLoc, nTail ); //scootch stuff down\n memset ( pbyZerosLoc, 0, nZeros ); //clear the compressed zeros\n }\n \n //validation of ipv4 subspace ::ffff:x.x\n if ( bIPv4Detected )\n {\n static const unsigned char abyPfx[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff };\n if ( 0 != memcmp ( abyAddrLocal, abyPfx, sizeof(abyPfx) ) )\n return 0;\n }\n\n //close bracket\n if ( NULL != pchOpenBracket )\n {\n if ( ']' != **ppszText )\n return 0;\n ++(*ppszText);\n }\n\n if ( ':' == **ppszText && NULL != pnPort ) //have port part, and we want it\n {\n const char* pszTextBefore;\n unsigned int nVal;\n unsigned short usPortNetwork; //save value in network order\n ++(*ppszText); //past the colon\n pszTextBefore = *ppszText;\n pszTextBefore = *ppszText;\n nVal =_parseDecimal ( ppszText );\n if ( nVal > 65535 || pszTextBefore == *ppszText )\n return 0;\n ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;\n ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );\n *pnPort = usPortNetwork;\n return 1;\n }\n else //finished just with ip address\n {\n if ( NULL != pnPort )\n *pnPort = 0; //indicate we have no port part\n return 1;\n }\n }\n\n}\n\n\n//simple version if we want don't care about knowing how much we ate\nint ParseIPv4OrIPv6_2 ( const char* pszText, \n unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )\n{\n const char* pszTextLocal = pszText;\n return ParseIPv4OrIPv6 ( &pszTextLocal, abyAddr, pnPort, pbIsIPv6);\n}\n"} +{"title": "Parse an IP Address", "language": "Python 3.5", "task": "The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6.\n \n\nTaking the following as inputs:\n::: {| border=\"5\" cellspacing=\"0\" cellpadding=2\n|-\n|127.0.0.1\n|The \"localhost\" IPv4 address\n|-\n|127.0.0.1:80\n|The \"localhost\" IPv4 address, with a specified port (80)\n|-\n|::1\n|The \"localhost\" IPv6 address\n|-\n|[::1]:80\n|The \"localhost\" IPv6 address, with a specified port (80)\n|-\n|2605:2700:0:3::4713:93e3\n|Rosetta Code's primary server's public IPv6 address\n|-\n|[2605:2700:0:3::4713:93e3]:80\n|Rosetta Code's primary server's public IPv6 address, with a specified port (80)\n|}\n\n\n;Task:\nEmit each described IP address as a hexadecimal integer representing the address, the address space, and the port number specified, if any. \n\nIn languages where variant result types are clumsy, the result should be ipv4 or ipv6 address number, something which says which address space was represented, port number and something that says if the port was specified.\n\n\n;Example:\n'''127.0.0.1''' \u00a0 has the address number \u00a0 '''7F000001''' \u00a0 (2130706433 decimal) \nin the ipv4 address space. \n\n'''::ffff:127.0.0.1''' \u00a0 represents the same address in the ipv6 address space where it has the \naddress number \u00a0 '''FFFF7F000001''' \u00a0 (281472812449793 decimal). \n\n'''::1''' \u00a0 has address number \u00a0 '''1''' \u00a0 and serves the same purpose in the ipv6 address \nspace that \u00a0 '''127.0.0.1''' \u00a0 serves in the ipv4 address space.\n\n", "solution": "from ipaddress import ip_address\nfrom urllib.parse import urlparse\n\ntests = [\n \"127.0.0.1\",\n \"127.0.0.1:80\",\n \"::1\",\n \"[::1]:80\",\n \"::192.168.0.1\",\n \"2605:2700:0:3::4713:93e3\",\n \"[2605:2700:0:3::4713:93e3]:80\" ]\n\ndef parse_ip_port(netloc):\n try:\n ip = ip_address(netloc)\n port = None\n except ValueError:\n parsed = urlparse('//{}'.format(netloc))\n ip = ip_address(parsed.hostname)\n port = parsed.port\n return ip, port\n\nfor address in tests:\n ip, port = parse_ip_port(address)\n hex_ip = {4:'{:08X}', 6:'{:032X}'}[ip.version].format(int(ip))\n print(\"{:39s} {:>32s} IPv{} port={}\".format(\n str(ip), hex_ip, ip.version, port ))"} +{"title": "Parsing/RPN calculator algorithm", "language": "C", "task": ";Task:\nCreate a stack-based evaluator for an expression in \u00a0 reverse Polish notation (RPN) \u00a0 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 \u00a0 [[Parsing/Shunting-yard algorithm]] \u00a0 task: \n\u00a0 \u00a0 \u00a0 \u00a0 3 4 2 * 1 5 - 2 3 ^ ^ / + \n* Print or display the output here\n\n\n;Notes:\n* \u00a0 '''^''' \u00a0 means exponentiation in the expression above.\n* \u00a0 '''/''' \u00a0 means division.\n\n\n;See also:\n* \u00a0 [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression.\n* \u00a0 Several solutions to [[24 game/Solve]] make use of RPN evaluators (although tracing how they work is not a part of that task).\n* \u00a0 [[Parsing/RPN to infix conversion]].\n* \u00a0 [[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 calculator algorithm", "language": "JavaScript", "task": ";Task:\nCreate a stack-based evaluator for an expression in \u00a0 reverse Polish notation (RPN) \u00a0 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 \u00a0 [[Parsing/Shunting-yard algorithm]] \u00a0 task: \n\u00a0 \u00a0 \u00a0 \u00a0 3 4 2 * 1 5 - 2 3 ^ ^ / + \n* Print or display the output here\n\n\n;Notes:\n* \u00a0 '''^''' \u00a0 means exponentiation in the expression above.\n* \u00a0 '''/''' \u00a0 means division.\n\n\n;See also:\n* \u00a0 [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression.\n* \u00a0 Several solutions to [[24 game/Solve]] make use of RPN evaluators (although tracing how they work is not a part of that task).\n* \u00a0 [[Parsing/RPN to infix conversion]].\n* \u00a0 [[Arithmetic evaluation]].\n\n", "solution": "\nconst e = '3 4 2 * 1 5 - 2 3 ^ ^ / +';\nconst s = [], tokens = e.split(' ');\nfor (const t of tokens) {\n const n = Number(t);\n if (!isNaN(n)) {\n s.push(n);\n } else {\n if (s.length < 2) {\n throw new Error(`${t}: ${s}: insufficient operands.`);\n }\n const o2 = s.pop(), o1 = s.pop();\n switch (t) {\n case '+': s.push(o1 + o2); break;\n case '-': s.push(o1 - o2); break;\n case '*': s.push(o1 * o2); break;\n case '/': s.push(o1 / o2); break;\n case '^': s.push(Math.pow(o1, o2)); break;\n default: throw new Error(`Unrecognized operator: [${t}]`);\n }\n }\n console.log(`${t}: ${s}`);\n}\n\nif (s.length > 1) {\n throw new Error(`${s}: insufficient operators.`);\n}\n"} +{"title": "Parsing/RPN calculator algorithm", "language": "Python", "task": ";Task:\nCreate a stack-based evaluator for an expression in \u00a0 reverse Polish notation (RPN) \u00a0 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 \u00a0 [[Parsing/Shunting-yard algorithm]] \u00a0 task: \n\u00a0 \u00a0 \u00a0 \u00a0 3 4 2 * 1 5 - 2 3 ^ ^ / + \n* Print or display the output here\n\n\n;Notes:\n* \u00a0 '''^''' \u00a0 means exponentiation in the expression above.\n* \u00a0 '''/''' \u00a0 means division.\n\n\n;See also:\n* \u00a0 [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression.\n* \u00a0 Several solutions to [[24 game/Solve]] make use of RPN evaluators (although tracing how they work is not a part of that task).\n* \u00a0 [[Parsing/RPN to infix conversion]].\n* \u00a0 [[Arithmetic evaluation]].\n\n", "solution": "def op_pow(stack):\n b = stack.pop(); a = stack.pop()\n stack.append( a ** b )\ndef op_mul(stack):\n b = stack.pop(); a = stack.pop()\n stack.append( a * b )\ndef op_div(stack):\n b = stack.pop(); a = stack.pop()\n stack.append( a / b )\ndef op_add(stack):\n b = stack.pop(); a = stack.pop()\n stack.append( a + b )\ndef op_sub(stack):\n b = stack.pop(); a = stack.pop()\n stack.append( a - b )\ndef op_num(stack, num):\n stack.append( num )\n \nops = {\n '^': op_pow,\n '*': op_mul,\n '/': op_div,\n '+': op_add,\n '-': op_sub,\n }\n\ndef get_input(inp = None):\n 'Inputs an expression and returns list of tokens'\n \n if inp is None:\n inp = input('expression: ')\n tokens = inp.strip().split()\n return tokens\n\ndef rpn_calc(tokens):\n stack = []\n table = ['TOKEN,ACTION,STACK'.split(',')]\n for token in tokens:\n if token in ops:\n action = 'Apply op to top of stack'\n ops[token](stack)\n table.append( (token, action, ' '.join(str(s) for s in stack)) )\n else:\n action = 'Push num onto top of stack'\n op_num(stack, eval(token))\n table.append( (token, action, ' '.join(str(s) for s in stack)) )\n return table\n\nif __name__ == '__main__':\n rpn = '3 4 2 * 1 5 - 2 3 ^ ^ / +'\n print( 'For RPN expression: %r\\n' % rpn )\n rp = rpn_calc(get_input(rpn))\n maxcolwidths = [max(len(y) for y in x) for x in zip(*rp)]\n row = rp[0]\n print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n for row in rp[1:]:\n print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n\n print('\\n The final output value is: %r' % rp[-1][2])"} +{"title": "Parsing/RPN to infix conversion", "language": "C", "task": ";Task:\nCreate 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* \u00a0 [[Parsing/Shunting-yard algorithm]] \u00a0 for a method of generating an RPN from an infix expression.\n* \u00a0 [[Parsing/RPN calculator algorithm]] \u00a0 for a method of calculating a final value from this output RPN expression.\n* \u00a0 [http://www.rubyquiz.com/quiz148.html Postfix to infix] \u00a0 from the RubyQuiz site.\n\n", "solution": "\n#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/RPN to infix conversion", "language": "JavaScript", "task": ";Task:\nCreate 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* \u00a0 [[Parsing/Shunting-yard algorithm]] \u00a0 for a method of generating an RPN from an infix expression.\n* \u00a0 [[Parsing/RPN calculator algorithm]] \u00a0 for a method of calculating a final value from this output RPN expression.\n* \u00a0 [http://www.rubyquiz.com/quiz148.html Postfix to infix] \u00a0 from the RubyQuiz site.\n\n", "solution": "const Associativity = {\n /** a / b / c = (a / b) / c */\n left: 0,\n /** a ^ b ^ c = a ^ (b ^ c) */\n right: 1,\n /** a + b + c = (a + b) + c = a + (b + c) */\n both: 2,\n};\nconst operators = {\n '+': { precedence: 2, associativity: Associativity.both },\n '-': { precedence: 2, associativity: Associativity.left },\n '*': { precedence: 3, associativity: Associativity.both },\n '/': { precedence: 3, associativity: Associativity.left },\n '^': { precedence: 4, associativity: Associativity.right },\n};\nclass NumberNode {\n constructor(text) { this.text = text; }\n toString() { return this.text; }\n}\nclass InfixNode {\n constructor(fnname, operands) {\n this.fnname = fnname;\n this.operands = operands;\n }\n toString(parentPrecedence = 0) {\n const op = operators[this.fnname];\n const leftAdd = op.associativity === Associativity.right ? 0.01 : 0;\n const rightAdd = op.associativity === Associativity.left ? 0.01 : 0;\n if (this.operands.length !== 2) throw Error(\"invalid operand count\");\n const result = this.operands[0].toString(op.precedence + leftAdd)\n +` ${this.fnname} ${this.operands[1].toString(op.precedence + rightAdd)}`;\n if (parentPrecedence > op.precedence) return `( ${result} )`;\n else return result;\n }\n}\nfunction rpnToTree(tokens) {\n const stack = [];\n console.log(`input = ${tokens}`);\n for (const token of tokens.split(\" \")) {\n if (token in operators) {\n const op = operators[token], arity = 2; // all of these operators take 2 arguments\n if (stack.length < arity) throw Error(\"stack error\");\n stack.push(new InfixNode(token, stack.splice(stack.length - arity)));\n }\n else stack.push(new NumberNode(token));\n console.log(`read ${token}, stack = [${stack.join(\", \")}]`);\n }\n if (stack.length !== 1) throw Error(\"stack error \" + stack);\n return stack[0];\n}\nconst tests = [\n [\"3 4 2 * 1 5 - 2 3 ^ ^ / +\", \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"],\n [\"1 2 + 3 4 + ^ 5 6 + ^\", \"( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )\"],\n [\"1 2 3 + +\", \"1 + 2 + 3\"] // test associativity (1+(2+3)) == (1+2+3)\n];\nfor (const [inp, oup] of tests) {\n const realOup = rpnToTree(inp).toString();\n console.log(realOup === oup ? \"Correct!\" : \"Incorrect!\");\n}"} +{"title": "Parsing/RPN to infix conversion", "language": "Python", "task": ";Task:\nCreate 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* \u00a0 [[Parsing/Shunting-yard algorithm]] \u00a0 for a method of generating an RPN from an infix expression.\n* \u00a0 [[Parsing/RPN calculator algorithm]] \u00a0 for a method of calculating a final value from this output RPN expression.\n* \u00a0 [http://www.rubyquiz.com/quiz148.html Postfix to infix] \u00a0 from the RubyQuiz site.\n\n", "solution": "\n \n\"\"\"\n>>> # EXAMPLE USAGE\n>>> result = rpn_to_infix('3 4 2 * 1 5 - 2 3 ^ ^ / +', VERBOSE=True)\nTOKEN STACK\n3 ['3']\n4 ['3', '4']\n2 ['3', '4', '2']\n* ['3', Node('2','*','4')]\n1 ['3', Node('2','*','4'), '1']\n5 ['3', Node('2','*','4'), '1', '5']\n- ['3', Node('2','*','4'), Node('5','-','1')]\n2 ['3', Node('2','*','4'), Node('5','-','1'), '2']\n3 ['3', Node('2','*','4'), Node('5','-','1'), '2', '3']\n^ ['3', Node('2','*','4'), Node('5','-','1'), Node('3','^','2')]\n^ ['3', Node('2','*','4'), Node(Node('3','^','2'),'^',Node('5','-','1'))]\n/ ['3', Node(Node(Node('3','^','2'),'^',Node('5','-','1')),'/',Node('2','*','4'))]\n+ [Node(Node(Node(Node('3','^','2'),'^',Node('5','-','1')),'/',Node('2','*','4')),'+','3')]\n\"\"\"\n\nprec_dict = {'^':4, '*':3, '/':3, '+':2, '-':2}\nassoc_dict = {'^':1, '*':0, '/':0, '+':0, '-':0}\n \nclass Node:\n def __init__(self,x,op,y=None):\n self.precedence = prec_dict[op]\n self.assocright = assoc_dict[op]\n self.op = op\n self.x,self.y = x,y\n \n def __str__(self):\n \"\"\"\n Building an infix string that evaluates correctly is easy.\n Building an infix string that looks pretty and evaluates\n correctly requires more effort.\n \"\"\"\n # easy case, Node is unary\n if self.y == None:\n return '%s(%s)'%(self.op,str(self.x))\n \n # determine left side string\n str_y = str(self.y)\n if self.y < self or \\\n (self.y == self and self.assocright) or \\\n (str_y[0] is '-' and self.assocright):\n \n str_y = '(%s)'%str_y\n # determine right side string and operator\n str_x = str(self.x)\n str_op = self.op\n if self.op is '+' and not isinstance(self.x, Node) and str_x[0] is '-':\n str_x = str_x[1:]\n str_op = '-'\n elif self.op is '-' and not isinstance(self.x, Node) and str_x[0] is '-':\n str_x = str_x[1:]\n str_op = '+'\n elif self.x < self or \\\n (self.x == self and not self.assocright and \\\n getattr(self.x, 'op', 1) != getattr(self, 'op', 2)):\n \n str_x = '(%s)'%str_x\n return ' '.join([str_y, str_op, str_x])\n \n def __repr__(self):\n \"\"\"\n >>> repr(Node('3','+','4')) == repr(eval(repr(Node('3','+','4'))))\n True\n \"\"\"\n return 'Node(%s,%s,%s)'%(repr(self.x), repr(self.op), repr(self.y))\n \n def __lt__(self, other):\n if isinstance(other, Node):\n return self.precedence < other.precedence\n return self.precedence < prec_dict.get(other,9)\n \n def __gt__(self, other):\n if isinstance(other, Node):\n return self.precedence > other.precedence\n return self.precedence > prec_dict.get(other,9)\n\n def __eq__(self, other):\n if isinstance(other, Node):\n return self.precedence == other.precedence\n return self.precedence > prec_dict.get(other,9)\n \n \n \ndef rpn_to_infix(s, VERBOSE=False):\n \"\"\"\n \n converts rpn notation to infix notation for string s\n \n \"\"\"\n if VERBOSE : print('TOKEN STACK')\n \n stack=[]\n for token in s.replace('^','^').split():\n if token in prec_dict:\n stack.append(Node(stack.pop(),token,stack.pop()))\n else:\n stack.append(token)\n \n # can't use \\t in order to make global docstring pass doctest\n if VERBOSE : print(token+' '*(7-len(token))+repr(stack)) \n \n return str(stack[0])\n \nstrTest = \"3 4 2 * 1 5 - 2 3 ^ ^ / +\"\nstrResult = rpn_to_infix(strTest, VERBOSE=False)\nprint (\"Input: \",strTest)\nprint (\"Output:\",strResult)\n\nprint()\n\nstrTest = \"1 2 + 3 4 + ^ 5 6 + ^\"\nstrResult = rpn_to_infix(strTest, VERBOSE=False)\nprint (\"Input: \",strTest)\nprint (\"Output:\",strResult)\n"} +{"title": "Parsing/Shunting-yard algorithm", "language": "C", "task": ";Task:\nGiven 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": "Parsing/Shunting-yard algorithm", "language": "JavaScript", "task": ";Task:\nGiven 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": "function Stack() {\n this.dataStore = [];\n this.top = 0;\n this.push = push;\n this.pop = pop;\n this.peek = peek;\n this.length = length;\n}\n \nfunction push(element) {\n this.dataStore[this.top++] = element;\n}\n \nfunction pop() {\n return this.dataStore[--this.top];\n}\n \nfunction peek() {\n return this.dataStore[this.top-1];\n}\n \nfunction length() {\n return this.top;\n}\n \nvar infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\ninfix = infix.replace(/\\s+/g, ''); // remove spaces, so infix[i]!=\" \"\n\nvar s = new Stack();\nvar ops = \"-+/*^\";\nvar precedence = {\"^\":4, \"*\":3, \"/\":3, \"+\":2, \"-\":2};\nvar associativity = {\"^\":\"Right\", \"*\":\"Left\", \"/\":\"Left\", \"+\":\"Left\", \"-\":\"Left\"};\nvar token;\nvar postfix = \"\";\nvar o1, o2;\n\nfor (var i = 0; i < infix.length; i++) {\n token = infix[i];\n if (token >= \"0\" && token <= \"9\") { // if token is operand (here limited to 0 <= x <= 9)\n postfix += token + \" \";\n }\n else if (ops.indexOf(token) != -1) { // if token is an operator\n o1 = token;\n o2 = s.peek();\n while (ops.indexOf(o2)!=-1 && ( // while operator token, o2, on top of the stack\n // and o1 is left-associative and its precedence is less than or equal to that of o2\n (associativity[o1] == \"Left\" && (precedence[o1] <= precedence[o2]) ) || \n // the algorithm on wikipedia says: or o1 precedence < o2 precedence, but I think it should be\n // or o1 is right-associative and its precedence is less than that of o2\n (associativity[o1] == \"Right\" && (precedence[o1] < precedence[o2])) \n )){\n postfix += o2 + \" \"; // add o2 to output queue\n s.pop(); // pop o2 of the stack\n o2 = s.peek(); // next round\n }\n s.push(o1); // push o1 onto the stack\n }\n else if (token == \"(\") { // if token is left parenthesis\n s.push(token); // then push it onto the stack\n }\n else if (token == \")\") { // if token is right parenthesis \n while (s.peek() != \"(\"){ // until token at top is (\n postfix += s.pop() + \" \";\n }\n s.pop(); // pop (, but not onto the output queue\n }\n}\npostfix += s.dataStore.reverse().join(\" \");\nprint(postfix);"} +{"title": "Parsing/Shunting-yard algorithm", "language": "Python", "task": ";Task:\nGiven 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": "from collections import namedtuple\nfrom pprint import pprint as pp\n\nOpInfo = namedtuple('OpInfo', 'prec assoc')\nL, R = 'Left Right'.split()\n\nops = {\n '^': OpInfo(prec=4, assoc=R),\n '*': OpInfo(prec=3, assoc=L),\n '/': OpInfo(prec=3, assoc=L),\n '+': OpInfo(prec=2, assoc=L),\n '-': OpInfo(prec=2, assoc=L),\n '(': OpInfo(prec=9, assoc=L),\n ')': OpInfo(prec=0, assoc=L),\n }\n\nNUM, LPAREN, RPAREN = 'NUMBER ( )'.split()\n\n\ndef get_input(inp = None):\n 'Inputs an expression and returns list of (TOKENTYPE, tokenvalue)'\n \n if inp is None:\n inp = input('expression: ')\n tokens = inp.strip().split()\n tokenvals = []\n for token in tokens:\n if token in ops:\n tokenvals.append((token, ops[token]))\n #elif token in (LPAREN, RPAREN):\n # tokenvals.append((token, token))\n else: \n tokenvals.append((NUM, token))\n return tokenvals\n\ndef shunting(tokenvals):\n outq, stack = [], []\n table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')]\n for token, val in tokenvals:\n note = action = ''\n if token is NUM:\n action = 'Add number to output'\n outq.append(val)\n table.append( (val, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n elif token in ops:\n t1, (p1, a1) = token, val\n v = t1\n note = 'Pop ops from stack to output' \n while stack:\n t2, (p2, a2) = stack[-1]\n if (a1 == L and p1 <= p2) or (a1 == R and p1 < p2):\n if t1 != RPAREN:\n if t2 != LPAREN:\n stack.pop()\n action = '(Pop op)'\n outq.append(t2)\n else: \n break\n else: \n if t2 != LPAREN:\n stack.pop()\n action = '(Pop op)'\n outq.append(t2)\n else: \n stack.pop()\n action = '(Pop & discard \"(\")'\n table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n break\n table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n v = note = ''\n else:\n note = ''\n break\n note = '' \n note = '' \n if t1 != RPAREN:\n stack.append((token, val))\n action = 'Push op token to stack'\n else:\n action = 'Discard \")\"'\n table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n note = 'Drain stack to output'\n while stack:\n v = ''\n t2, (p2, a2) = stack[-1]\n action = '(Pop op)'\n stack.pop()\n outq.append(t2)\n table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n v = note = ''\n return table\n\nif __name__ == '__main__':\n infix = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3'\n print( 'For infix expression: %r\\n' % infix )\n rp = shunting(get_input(infix))\n maxcolwidths = [len(max(x, key=len)) for x in zip(*rp)]\n row = rp[0]\n print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n for row in rp[1:]:\n print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n\n print('\\n The final output RPN is: %r' % rp[-1][2])"} +{"title": "Pascal's triangle/Puzzle", "language": "C", "task": "This puzzle involves a [http://xunor.free.fr/en/riddles/auto/pyramidnb.php Pascals Triangle], also known as a [http://xunor.free.fr/en/riddles/auto/pyramidnb.php 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": "\n/* 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's triangle/Puzzle", "language": "Python 2.4+", "task": "This puzzle involves a [http://xunor.free.fr/en/riddles/auto/pyramidnb.php Pascals Triangle], also known as a [http://xunor.free.fr/en/riddles/auto/pyramidnb.php 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": "# Pyramid solver\n# [151]\n# [ ] [ ]\n# [ 40] [ ] [ ]\n# [ ] [ ] [ ] [ ]\n#[ X ] [ 11] [ Y ] [ 4 ] [ Z ]\n# X -Y + Z = 0\n\ndef combine( snl, snr ):\n\n\tcl = {}\n\tif isinstance(snl, int):\n\t\tcl['1'] = snl\n\telif isinstance(snl, string):\n\t\tcl[snl] = 1\n\telse:\n\t\tcl.update( snl)\n\n\tif isinstance(snr, int):\n\t\tn = cl.get('1', 0)\n\t\tcl['1'] = n + snr\n\telif isinstance(snr, string):\n\t\tn = cl.get(snr, 0)\n\t\tcl[snr] = n + 1\n\telse:\n\t\tfor k,v in snr.items():\n\t\t\tn = cl.get(k, 0)\n\t\t\tcl[k] = n+v\n\treturn cl\n\n\ndef constrain(nsum, vn ):\n\tnn = {}\n\tnn.update(vn)\n\tn = nn.get('1', 0)\n\tnn['1'] = n - nsum\n\treturn nn\n\ndef makeMatrix( constraints ):\n\tvmap = set()\n\tfor c in constraints:\n\t\tvmap.update( c.keys())\n\tvmap.remove('1')\n\tnvars = len(vmap)\n\tvmap = sorted(vmap)\t\t# sort here so output is in sorted order\n\tmtx = []\n\tfor c in constraints:\n\t\trow = []\n\t\tfor vv in vmap:\n\t\t\trow.append(float(c.get(vv, 0)))\n\t\trow.append(-float(c.get('1',0)))\n\t\tmtx.append(row)\n\t\n\tif len(constraints) == nvars:\n\t\tprint 'System appears solvable'\n\telif len(constraints) < nvars:\n\t\tprint 'System is not solvable - needs more constraints.'\n\treturn mtx, vmap\n\n\ndef SolvePyramid( vl, cnstr ):\n\n\tvl.reverse()\n\tconstraints = [cnstr]\n\tlvls = len(vl)\n\tfor lvln in range(1,lvls):\n\t\tlvd = vl[lvln]\n\t\tfor k in range(lvls - lvln):\n\t\t\tsn = lvd[k]\n\t\t\tll = vl[lvln-1]\n\t\t\tvn = combine(ll[k], ll[k+1])\n\t\t\tif sn is None:\n\t\t\t\tlvd[k] = vn\n\t\t\telse:\n\t\t\t\tconstraints.append(constrain( sn, vn ))\n\n\tprint 'Constraint Equations:'\n\tfor cstr in constraints:\n\t\tfset = ('%d*%s'%(v,k) for k,v in cstr.items() )\n\t\tprint ' + '.join(fset), ' = 0'\n\n\tmtx,vmap = makeMatrix(constraints)\n\n\tMtxSolve(mtx)\n\n\td = len(vmap)\n\tfor j in range(d):\n\t\tprint vmap[j],'=', mtx[j][d]\n\n\ndef MtxSolve(mtx):\n\t# Simple Matrix solver...\n\n\tmDim = len(mtx)\t\t\t# dimension---\n\tfor j in range(mDim):\n\t\trw0= mtx[j]\n\t\tf = 1.0/rw0[j]\n\t\tfor k in range(j, mDim+1):\n\t\t\trw0[k] *= f\n\t\t\n\t\tfor l in range(1+j,mDim):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\tfor k in range(j, mDim+1):\n\t\t\t\trwl[k] += f * rw0[k]\n\n\t# backsolve part ---\n\tfor j1 in range(1,mDim):\n\t\tj = mDim - j1\n\t\trw0= mtx[j]\n\t\tfor l in range(0, j):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\trwl[j] += f * rw0[j]\n\t\t\trwl[mDim] += f * rw0[mDim]\n\n\treturn mtx\n\n\np = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ]\naddlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 }\nSolvePyramid( p, addlConstraint)"} +{"title": "Pascal matrix generation", "language": "C", "task": "A pascal matrix is a two-dimensional square matrix holding numbers from \u00a0 binomial coefficients \u00a0 and which can be shown as \u00a0 nCr.\n\nShown below are truncated \u00a0 5-by-5 \u00a0 matrices \u00a0 M[i, j] \u00a0 for \u00a0 i,j \u00a0 in range \u00a0 0..4. \n\nA Pascal upper-triangular matrix that is populated with \u00a0 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 \u00a0 iCj \u00a0 (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 \u00a0 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 \u00a0 n-by-n \u00a0 matrices.\n\nUse those functions to display upper, lower, and symmetric Pascal \u00a0 5-by-5 \u00a0 matrices on this page. \n\nThe output should distinguish between different matrices and the rows of each matrix \u00a0 (no showing a list of 25 numbers assuming the reader should split it into rows).\n\n\n;Note: \nThe \u00a0 [[Cholesky decomposition]] \u00a0 of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size. \n\n", "solution": "\n#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": "Pascal matrix generation", "language": "JavaScript", "task": "A pascal matrix is a two-dimensional square matrix holding numbers from \u00a0 binomial coefficients \u00a0 and which can be shown as \u00a0 nCr.\n\nShown below are truncated \u00a0 5-by-5 \u00a0 matrices \u00a0 M[i, j] \u00a0 for \u00a0 i,j \u00a0 in range \u00a0 0..4. \n\nA Pascal upper-triangular matrix that is populated with \u00a0 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 \u00a0 iCj \u00a0 (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 \u00a0 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 \u00a0 n-by-n \u00a0 matrices.\n\nUse those functions to display upper, lower, and symmetric Pascal \u00a0 5-by-5 \u00a0 matrices on this page. \n\nThe output should distinguish between different matrices and the rows of each matrix \u00a0 (no showing a list of 25 numbers assuming the reader should split it into rows).\n\n\n;Note: \nThe \u00a0 [[Cholesky decomposition]] \u00a0 of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size. \n\n", "solution": "(() => {\n 'use strict';\n\n // -------------------PASCAL MATRIX--------------------\n\n // pascalMatrix :: ((Int, Int) -> (Int, Int)) ->\n // Int -> [Int]\n const pascalMatrix = f =>\n n => map(compose(binomialCoefficient, f))(\n range([0, 0], [n - 1, n - 1])\n );\n\n // binomialCoefficient :: (Int, Int) -> Int\n const binomialCoefficient = nk => {\n const [n, k] = Array.from(nk);\n return enumFromThenTo(k)(\n pred(k)\n )(1).reduceRight((a, x) => quot(\n a * succ(n - x)\n )(x), 1);\n };\n\n // ------------------------TEST------------------------\n // main :: IO ()\n const main = () => {\n const matrixSize = 5;\n console.log(intercalate('\\n\\n')(\n zipWith(\n k => xs => k + ':\\n' + showMatrix(matrixSize)(xs)\n )(['Lower', 'Upper', 'Symmetric'])(\n apList(\n map(pascalMatrix)([\n identity, // Lower\n swap, // Upper\n ([a, b]) => [a + b, b] // Symmetric\n ])\n )([matrixSize])\n )\n ));\n };\n\n // ----------------------DISPLAY-----------------------\n\n // showMatrix :: Int -> [Int] -> String\n const showMatrix = n =>\n xs => {\n const\n ks = map(str)(xs),\n w = maximum(map(length)(ks));\n return unlines(\n map(unwords)(chunksOf(n)(\n map(justifyRight(w)(' '))(ks)\n ))\n );\n };\n\n // -----------------GENERIC FUNCTIONS------------------\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = a =>\n b => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // apList (<*>) :: [(a -> b)] -> [a] -> [b]\n const apList = fs =>\n // The sequential application of each of a list\n // of functions to each of a list of values.\n xs => fs.flatMap(\n f => xs.map(f)\n );\n\n // chunksOf :: Int -> [a] -> [[a]]\n const chunksOf = n =>\n xs => enumFromThenTo(0)(n)(\n xs.length - 1\n ).reduce(\n (a, i) => a.concat([xs.slice(i, (n + i))]),\n []\n );\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (...fs) =>\n x => fs.reduceRight((a, f) => f(a), x);\n\n // concat :: [[a]] -> [a]\n // concat :: [String] -> String\n const concat = xs =>\n 0 < xs.length ? (\n xs.every(x => 'string' === typeof x) ? (\n ''\n ) : []\n ).concat(...xs) : xs;\n\n // cons :: a -> [a] -> [a]\n const cons = x =>\n xs => [x].concat(xs);\n\n // enumFromThenTo :: Int -> Int -> Int -> [Int]\n const enumFromThenTo = x1 =>\n x2 => y => {\n const d = x2 - x1;\n return Array.from({\n length: Math.floor(y - x2) / d + 2\n }, (_, i) => x1 + (d * i));\n };\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = m =>\n n => Array.from({\n length: 1 + n - m\n }, (_, i) => m + i);\n\n // fst :: (a, b) -> a\n const fst = tpl =>\n // First member of a pair.\n tpl[0];\n\n // identity :: a -> a\n const identity = x =>\n // The identity function. (`id`, in Haskell)\n x;\n\n // intercalate :: String -> [String] -> String\n const intercalate = s =>\n // The concatenation of xs\n // interspersed with copies of s.\n xs => xs.join(s);\n\n // justifyRight :: Int -> Char -> String -> String\n const justifyRight = n =>\n // The string s, preceded by enough padding (with\n // the character c) to reach the string length n.\n c => s => n > s.length ? (\n s.padStart(n, c)\n ) : s;\n\n // length :: [a] -> Int\n const length = xs =>\n // Returns Infinity over objects without finite\n // length. This enables zip and zipWith to choose\n // the shorter argument when one is non-finite,\n // like cycle, repeat etc\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n\n // liftA2List :: (a -> b -> c) -> [a] -> [b] -> [c]\n const liftA2List = f => xs => ys =>\n // The binary operator f lifted to a function over two\n // lists. f applied to each pair of arguments in the\n // cartesian product of xs and ys.\n xs.flatMap(\n x => ys.map(f(x))\n );\n\n // map :: (a -> b) -> [a] -> [b]\n const map = f =>\n // The list obtained by applying f to each element of xs.\n // (The image of xs under f).\n xs => (Array.isArray(xs) ? (\n xs\n ) : xs.split('')).map(f);\n\n // maximum :: Ord a => [a] -> a\n const maximum = xs =>\n // The largest value in a non-empty list.\n 0 < xs.length ? (\n xs.slice(1).reduce(\n (a, x) => x > a ? (\n x\n ) : a, xs[0]\n )\n ) : undefined;\n\n // pred :: Enum a => a -> a\n const pred = x =>\n x - 1;\n\n // quot :: Int -> Int -> Int\n const quot = n => m => Math.floor(n / m);\n\n // The list of values in the subrange defined by a bounding pair.\n\n // range([0, 2]) -> [0,1,2]\n // range([[0,0], [2,2]])\n // -> [[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]]\n // range([[0,0,0],[1,1,1]])\n // -> [[0,0,0],[0,0,1],[0,1,0],[0,1,1],[1,0,0],[1,0,1],[1,1,0],[1,1,1]]\n\n // range :: Ix a => (a, a) -> [a]\n function range() {\n const\n args = Array.from(arguments),\n ab = 1 !== args.length ? (\n args\n ) : args[0],\n [as, bs] = [ab[0], ab[1]].map(\n x => Array.isArray(x) ? (\n x\n ) : (undefined !== x.type) &&\n (x.type.startsWith('Tuple')) ? (\n Array.from(x)\n ) : [x]\n ),\n an = as.length;\n return (an === bs.length) ? (\n 1 < an ? (\n traverseList(x => x)(\n as.map((_, i) => enumFromTo(as[i])(bs[i]))\n )\n ) : enumFromTo(as[0])(bs[0])\n ) : [];\n };\n\n // snd :: (a, b) -> b\n const snd = tpl => tpl[1];\n\n // str :: a -> String\n const str = x => x.toString();\n\n // succ :: Enum a => a -> a\n const succ = x =>\n 1 + x;\n\n // swap :: (a, b) -> (b, a)\n const swap = ab =>\n // The pair ab with its order reversed.\n Tuple(ab[1])(\n ab[0]\n );\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n =>\n // The first n elements of a list,\n // string of characters, or stream.\n xs => xs.slice(0, n);\n\n // traverseList :: (Applicative f) => (a -> f b) -> [a] -> f [b]\n const traverseList = f =>\n // Collected results of mapping each element\n // of a structure to an action, and evaluating\n // these actions from left to right.\n xs => 0 < xs.length ? (() => {\n const\n vLast = f(xs.slice(-1)[0]),\n t = vLast.type || 'List';\n return xs.slice(0, -1).reduceRight(\n (ys, x) => liftA2List(cons)(f(x))(ys),\n liftA2List(cons)(vLast)([\n []\n ])\n );\n })() : [\n []\n ];\n\n // unlines :: [String] -> String\n const unlines = xs =>\n // A single string formed by the intercalation\n // of a list of strings with the newline character.\n xs.join('\\n');\n\n // unwords :: [String] -> String\n const unwords = xs =>\n // A space-separated string derived\n // from a list of words.\n xs.join(' ');\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = f =>\n // A list constructed by zipping with a\n // custom function, rather than with the\n // default tuple constructor.\n xs => ys => {\n const\n lng = Math.min(length(xs), length(ys)),\n vs = take(lng)(ys);\n return take(lng)(xs)\n .map((x, i) => f(x)(vs[i]));\n };\n\n // MAIN ---\n return main();\n})();"} +{"title": "Pascal matrix generation", "language": "Python", "task": "A pascal matrix is a two-dimensional square matrix holding numbers from \u00a0 binomial coefficients \u00a0 and which can be shown as \u00a0 nCr.\n\nShown below are truncated \u00a0 5-by-5 \u00a0 matrices \u00a0 M[i, j] \u00a0 for \u00a0 i,j \u00a0 in range \u00a0 0..4. \n\nA Pascal upper-triangular matrix that is populated with \u00a0 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 \u00a0 iCj \u00a0 (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 \u00a0 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 \u00a0 n-by-n \u00a0 matrices.\n\nUse those functions to display upper, lower, and symmetric Pascal \u00a0 5-by-5 \u00a0 matrices on this page. \n\nThe output should distinguish between different matrices and the rows of each matrix \u00a0 (no showing a list of 25 numbers assuming the reader should split it into rows).\n\n\n;Note: \nThe \u00a0 [[Cholesky decomposition]] \u00a0 of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size. \n\n", "solution": "from pprint import pprint as pp\n\ndef pascal_upp(n):\n s = [[0] * n for _ in range(n)]\n s[0] = [1] * n\n for i in range(1, n):\n for j in range(i, n):\n s[i][j] = s[i-1][j-1] + s[i][j-1]\n return s\n\ndef pascal_low(n):\n # transpose of pascal_upp(n)\n return [list(x) for x in zip(*pascal_upp(n))]\n\ndef pascal_sym(n):\n s = [[1] * n for _ in range(n)]\n for i in range(1, n):\n for j in range(1, n):\n s[i][j] = s[i-1][j] + s[i][j-1]\n return s\n \n\nif __name__ == \"__main__\":\n n = 5\n print(\"\\nUpper:\")\n pp(pascal_upp(n))\n print(\"\\nLower:\")\n pp(pascal_low(n))\n print(\"\\nSymmetric:\")\n pp(pascal_sym(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 \u2500\u2500\u25ba z\n upper-case letters: A \u2500\u2500\u25ba Z\n digits: 0 \u2500\u2500\u25ba 9\n other printable characters: !\"#$%&'()*+,-./:;<=>?@[]^_{|}~ \n (the above character list excludes white-space, backslash and grave) \n\n\nThe generated password(s) must include \u00a0 ''at least one'' \u00a0 (of each of the four groups):\n lower-case letter, \n upper-case letter,\n digit (numeral), \u00a0 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: \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 Il1 \u00a0 \u00a0 O0 \u00a0 \u00a0 5S \u00a0 \u00a0 2Z \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 where the characters are: \n::::* \u00a0 capital eye, lowercase ell, the digit one\n::::* \u00a0 capital oh, the digit zero \n::::* \u00a0 the digit five, capital ess\n::::* \u00a0 the digit two, capital zee\n\n\n", "solution": "\n#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": "Password generator", "language": "JavaScript", "task": "Create a password generation program which will generate passwords containing random ASCII characters from the following groups:\n lower-case letters: a \u2500\u2500\u25ba z\n upper-case letters: A \u2500\u2500\u25ba Z\n digits: 0 \u2500\u2500\u25ba 9\n other printable characters: !\"#$%&'()*+,-./:;<=>?@[]^_{|}~ \n (the above character list excludes white-space, backslash and grave) \n\n\nThe generated password(s) must include \u00a0 ''at least one'' \u00a0 (of each of the four groups):\n lower-case letter, \n upper-case letter,\n digit (numeral), \u00a0 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: \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 Il1 \u00a0 \u00a0 O0 \u00a0 \u00a0 5S \u00a0 \u00a0 2Z \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 where the characters are: \n::::* \u00a0 capital eye, lowercase ell, the digit one\n::::* \u00a0 capital oh, the digit zero \n::::* \u00a0 the digit five, capital ess\n::::* \u00a0 the digit two, capital zee\n\n\n", "solution": "String.prototype.shuffle = function() {\n return this.split('').sort(() => Math.random() - .5).join('');\n}\n\nfunction createPwd(opts = {}) {\n let len = opts.len || 5, // password length\n num = opts.num || 1, // number of outputs\n noSims = opts.noSims == false ? false : true, // exclude similar?\n out = [],\n cur, i;\n\n let chars = [\n 'abcdefghijkmnopqrstuvwxyz'.split(''),\n 'ABCDEFGHJKLMNPQRTUVWXY'.split(''),\n '346789'.split(''),\n '!\"#$%&()*+,-./:;<=>?@[]^_{|}'.split('')\n ];\n\n if (!noSims) {\n chars[0].push('l');\n chars[1] = chars[1].concat('IOSZ'.split(''));\n chars[2] = chars[2].concat('1250'.split(''));\n }\n\n if (len < 4) {\n console.log('Password length changed to 4 (minimum)');\n len = 4;\n }\n\n while (out.length < num) {\n cur = '';\n // basic requirement\n for (i = 0; i < 4; i++)\n cur += chars[i][Math.floor(Math.random() * chars[i].length)];\n\n while (cur.length < len) {\n let rnd = Math.floor(Math.random() * chars.length);\n cur += chars[rnd][Math.floor(Math.random() * chars[rnd].length)];\n }\n out.push(cur);\n }\n\n for (i = 0; i < out.length; i++) out[i] = out[i].shuffle();\n\n if (out.length == 1) return out[0];\n return out;\n}\n\n// testing\nconsole.log( createPwd() );\nconsole.log( createPwd( {len: 20}) );\nconsole.log( createPwd( {len: 20, num: 2}) );\nconsole.log( createPwd( {len: 20, num: 2, noSims: false}) );\n"} +{"title": "Password generator", "language": "Python", "task": "Create a password generation program which will generate passwords containing random ASCII characters from the following groups:\n lower-case letters: a \u2500\u2500\u25ba z\n upper-case letters: A \u2500\u2500\u25ba Z\n digits: 0 \u2500\u2500\u25ba 9\n other printable characters: !\"#$%&'()*+,-./:;<=>?@[]^_{|}~ \n (the above character list excludes white-space, backslash and grave) \n\n\nThe generated password(s) must include \u00a0 ''at least one'' \u00a0 (of each of the four groups):\n lower-case letter, \n upper-case letter,\n digit (numeral), \u00a0 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: \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 Il1 \u00a0 \u00a0 O0 \u00a0 \u00a0 5S \u00a0 \u00a0 2Z \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 where the characters are: \n::::* \u00a0 capital eye, lowercase ell, the digit one\n::::* \u00a0 capital oh, the digit zero \n::::* \u00a0 the digit five, capital ess\n::::* \u00a0 the digit two, capital zee\n\n\n", "solution": "import random\n\nlowercase = 'abcdefghijklmnopqrstuvwxyz' # same as string.ascii_lowercase\nuppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # same as string.ascii_uppercase\ndigits = '0123456789' # same as string.digits\npunctuation = '!\"#$%&\\'()*+,-./:;<=>?@[]^_{|}~' # like string.punctuation but without backslash \\ nor grave `\n\nallowed = lowercase + uppercase + digits + punctuation\n\nvisually_similar = 'Il1O05S2Z'\n\n\ndef new_password(length:int, readable=True) -> str:\n if length < 4:\n print(\"password length={} is too short,\".format(length),\n \"minimum length=4\")\n return ''\n choice = random.SystemRandom().choice\n while True:\n password_chars = [\n choice(lowercase),\n choice(uppercase),\n choice(digits),\n choice(punctuation)\n ] + random.sample(allowed, length-4)\n if (not readable or \n all(c not in visually_similar for c in password_chars)):\n random.SystemRandom().shuffle(password_chars)\n return ''.join(password_chars)\n\n\ndef password_generator(length, qty=1, readable=True):\n for i in range(qty):\n print(new_password(length, readable))\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 \u00a0 - \u00a0 1130 \u00a0 / \u00a0 vn-1 \u00a0 + \u00a0 3000\u00a0 / \u00a0 (vn-1 * vn-2) \n\n\nAs \u00a0 '''n''' \u00a0 grows larger, the series should converge to \u00a0 '''6''' \u00a0 but small amounts of error will cause it to approach \u00a0 '''100'''.\n\n\n;Task 1:\nDisplay the values of the sequence where \u00a0 n = \u00a0 3, 4, 5, 6, 7, 8, 20, 30, 50 & 100 \u00a0 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''' \u00a0 is offering a new investment account to their customers. \n\nYou first deposit \u00a0 $e - 1 \u00a0 where \u00a0 e \u00a0 is \u00a0 2.7182818... \u00a0 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 \u00a0 25 \u00a0 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.''' \u00a0 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 \u00a0 f(a,b) \u00a0 where \u00a0 a=77617.0 \u00a0 and \u00a0 b=33096.0 \n:::::: f(77617.0, 33096.0) \u00a0 = \u00a0 -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* \u00a0 [https://perso.ens-lyon.fr/jean-michel.muller/chapitre1.pdf Floating-Point Arithmetic] \u00a0 Section 1.3.2 Difficult problems.\n\n", "solution": "\n#include\n#include\n\nvoid firstCase(){\n\tmpf_t a,b,c;\n\t\n\tmpf_inits(a,b,c,NULL);\n\t\n\tmpf_set_str(a,\"0.1\",10);\n\tmpf_set_str(b,\"0.2\",10);\n\tmpf_add(c,a,b);\n\t\n\tgmp_printf(\"\\n0.1 + 0.2 = %.*Ff\",20,c);\n}\n\nvoid pathologicalSeries(){\n\tint n;\n\tmpf_t v1, v2, vn, a1, a2, a3, t2, t3, prod;\n\t\n\tmpf_inits(v1,v2,vn, a1, a2, a3, t2, t3, prod,NULL);\n\t\n\tmpf_set_str(v1,\"2\",10);\n\tmpf_set_str(v2,\"-4\",10);\n\tmpf_set_str(a1,\"111\",10);\n\tmpf_set_str(a2,\"1130\",10);\n\tmpf_set_str(a3,\"3000\",10);\n\t\n\tfor(n=3;n<=100;n++){\n\t\tmpf_div(t2,a2,v2);\n\t\tmpf_mul(prod,v1,v2);\n\t\tmpf_div(t3,a3,prod);\n\t\tmpf_add(vn,a1,t3);\n\t\tmpf_sub(vn,vn,t2);\n\t\t\n\t\tif((n>=3&&n<=8) || n==20 || n==30 || n==50 || n==100){\n\t\t\tgmp_printf(\"\\nv_%d : %.*Ff\",n,(n==3)?1:(n>=4&&n<=7)?6:(n==8)?7:(n==20)?16:(n==30)?24:(n==50)?40:78,vn);\n\t\t}\n\t\t\n\t\tmpf_set(v1,v2);\n\t\tmpf_set(v2,vn);\n\t}\n}\n\nvoid healthySeries(){\n\tint n;\n\t\n\tmpf_t num,denom,result;\n\tmpq_t v1, v2, vn, a1, a2, a3, t2, t3, prod;\n\t\n\tmpf_inits(num,denom,result,NULL);\n\tmpq_inits(v1,v2,vn, a1, a2, a3, t2, t3, prod,NULL);\n\t\n\tmpq_set_str(v1,\"2\",10);\n\tmpq_set_str(v2,\"-4\",10);\n\tmpq_set_str(a1,\"111\",10);\n\tmpq_set_str(a2,\"1130\",10);\n\tmpq_set_str(a3,\"3000\",10);\n\t\n\tfor(n=3;n<=100;n++){\n\t\tmpq_div(t2,a2,v2);\n\t\tmpq_mul(prod,v1,v2);\n\t\tmpq_div(t3,a3,prod);\n\t\tmpq_add(vn,a1,t3);\n\t\tmpq_sub(vn,vn,t2);\n\t\t\n\t\tif((n>=3&&n<=8) || n==20 || n==30 || n==50 || n==100){\n\t\t\tmpf_set_z(num,mpq_numref(vn));\n\t\t\tmpf_set_z(denom,mpq_denref(vn));\n\t\t\tmpf_div(result,num,denom);\n\n\t\t\tgmp_printf(\"\\nv_%d : %.*Ff\",n,(n==3)?1:(n>=4&&n<=7)?6:(n==8)?7:(n==20)?16:(n==30)?24:(n==50)?40:78,result);\n\t\t}\n\t\t\n\t\tmpq_set(v1,v2);\n\t\tmpq_set(v2,vn);\n\t}\n}\n\nint main()\n{\t\n\tmpz_t rangeProd;\n\t\n\tfirstCase();\n\t\n\tprintf(\"\\n\\nPathological Series : \");\n\t\n\tpathologicalSeries();\n\t\n\tprintf(\"\\n\\nNow a bit healthier : \");\n\t\n\thealthySeries();\n\n\treturn 0;\n}\n"} +{"title": "Pathological floating point problems", "language": "Python", "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 \u00a0 - \u00a0 1130 \u00a0 / \u00a0 vn-1 \u00a0 + \u00a0 3000\u00a0 / \u00a0 (vn-1 * vn-2) \n\n\nAs \u00a0 '''n''' \u00a0 grows larger, the series should converge to \u00a0 '''6''' \u00a0 but small amounts of error will cause it to approach \u00a0 '''100'''.\n\n\n;Task 1:\nDisplay the values of the sequence where \u00a0 n = \u00a0 3, 4, 5, 6, 7, 8, 20, 30, 50 & 100 \u00a0 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''' \u00a0 is offering a new investment account to their customers. \n\nYou first deposit \u00a0 $e - 1 \u00a0 where \u00a0 e \u00a0 is \u00a0 2.7182818... \u00a0 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 \u00a0 25 \u00a0 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.''' \u00a0 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 \u00a0 f(a,b) \u00a0 where \u00a0 a=77617.0 \u00a0 and \u00a0 b=33096.0 \n:::::: f(77617.0, 33096.0) \u00a0 = \u00a0 -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* \u00a0 [https://perso.ens-lyon.fr/jean-michel.muller/chapitre1.pdf Floating-Point Arithmetic] \u00a0 Section 1.3.2 Difficult problems.\n\n", "solution": "from fractions import Fraction\n\ndef muller_seq(n:int) -> float:\n seq = [Fraction(0), Fraction(2), Fraction(-4)]\n for i in range(3, n+1):\n next_value = (111 - 1130/seq[i-1]\n + 3000/(seq[i-1]*seq[i-2]))\n seq.append(next_value)\n return float(seq[n])\n\nfor n in [3, 4, 5, 6, 7, 8, 20, 30, 50, 100]:\n print(\"{:4d} -> {}\".format(n, muller_seq(n)))"} +{"title": "Peaceful chess queen armies", "language": "C", "task": "In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces ''not'' of its own colour.\n\n\n\n\n\u21d6\n\u21d1\n\u21d7\n\n\n\n\u21d0\n\u21d0\n\u265b\n\u21d2\n\u21d2\n\n\n\n\u21d9\n\u21d3\n\u21d8\n\n\n\n\u21d9\n\n\u21d3\n\n\u21d8\n\n\n\n\n\u21d3\n\n\n\n\n\n\nThe goal of Peaceful chess queen armies is to arrange m black queens and m white queens on an n-by-n square grid, (the board), so that ''no queen attacks another of a different colour''.\n\n\n;Task:\n# Create a routine to represent two-colour queens on a 2-D board. (Alternating black/white background colours, Unicode chess pieces and other embellishments are not necessary, but may be used at your discretion).\n# Create a routine to generate at least one solution to placing m equal numbers of black and white queens on an n square board.\n# Display here results for the m=4, n=5 case.\n\n\n;References:\n* [http://www.mathopt.org/Optima-Issues/optima62.pdf Peaceably Coexisting Armies of Queens] (Pdf) by Robert A. Bosch. Optima, the Mathematical Programming Socity newsletter, issue 62.\n* [https://oeis.org/A250000 A250000] OEIS\n\n", "solution": "#include \n#include \n#include \n#include \n\nenum Piece {\n Empty,\n Black,\n White,\n};\n\ntypedef struct Position_t {\n int x, y;\n} Position;\n\n///////////////////////////////////////////////\n\nstruct Node_t {\n Position pos;\n struct Node_t *next;\n};\n\nvoid releaseNode(struct Node_t *head) {\n if (head == NULL) return;\n\n releaseNode(head->next);\n head->next = NULL;\n\n free(head);\n}\n\ntypedef struct List_t {\n struct Node_t *head;\n struct Node_t *tail;\n size_t length;\n} List;\n\nList makeList() {\n return (List) { NULL, NULL, 0 };\n}\n\nvoid releaseList(List *lst) {\n if (lst == NULL) return;\n\n releaseNode(lst->head);\n lst->head = NULL;\n lst->tail = NULL;\n}\n\nvoid addNode(List *lst, Position pos) {\n struct Node_t *newNode;\n\n if (lst == NULL) {\n exit(EXIT_FAILURE);\n }\n\n newNode = malloc(sizeof(struct Node_t));\n if (newNode == NULL) {\n exit(EXIT_FAILURE);\n }\n\n newNode->next = NULL;\n newNode->pos = pos;\n\n if (lst->head == NULL) {\n lst->head = lst->tail = newNode;\n } else {\n lst->tail->next = newNode;\n lst->tail = newNode;\n }\n\n lst->length++;\n}\n\nvoid removeAt(List *lst, size_t pos) {\n if (lst == NULL) return;\n\n if (pos == 0) {\n struct Node_t *temp = lst->head;\n\n if (lst->tail == lst->head) {\n lst->tail = NULL;\n }\n\n lst->head = lst->head->next;\n temp->next = NULL;\n\n free(temp);\n lst->length--;\n } else {\n struct Node_t *temp = lst->head;\n struct Node_t *rem;\n size_t i = pos;\n\n while (i-- > 1) {\n temp = temp->next;\n }\n\n rem = temp->next;\n if (rem == lst->tail) {\n lst->tail = temp;\n }\n\n temp->next = rem->next;\n\n rem->next = NULL;\n free(rem);\n\n lst->length--;\n }\n}\n\n///////////////////////////////////////////////\n\nbool isAttacking(Position queen, Position pos) {\n return queen.x == pos.x\n || queen.y == pos.y\n || abs(queen.x - pos.x) == abs(queen.y - pos.y);\n}\n\nbool place(int m, int n, List *pBlackQueens, List *pWhiteQueens) {\n struct Node_t *queenNode;\n bool placingBlack = true;\n int i, j;\n\n if (pBlackQueens == NULL || pWhiteQueens == NULL) {\n exit(EXIT_FAILURE);\n }\n\n if (m == 0) return true;\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n Position pos = { i, j };\n\n queenNode = pBlackQueens->head;\n while (queenNode != NULL) {\n if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || !placingBlack && isAttacking(queenNode->pos, pos)) {\n goto inner;\n }\n queenNode = queenNode->next;\n }\n\n queenNode = pWhiteQueens->head;\n while (queenNode != NULL) {\n if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || placingBlack && isAttacking(queenNode->pos, pos)) {\n goto inner;\n }\n queenNode = queenNode->next;\n }\n\n if (placingBlack) {\n addNode(pBlackQueens, pos);\n placingBlack = false;\n } else {\n addNode(pWhiteQueens, pos);\n if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n return true;\n }\n removeAt(pBlackQueens, pBlackQueens->length - 1);\n removeAt(pWhiteQueens, pWhiteQueens->length - 1);\n placingBlack = true;\n }\n\n inner: {}\n }\n }\n if (!placingBlack) {\n removeAt(pBlackQueens, pBlackQueens->length - 1);\n }\n return false;\n}\n\nvoid printBoard(int n, List *pBlackQueens, List *pWhiteQueens) {\n size_t length = n * n;\n struct Node_t *queenNode;\n char *board;\n size_t i, j, k;\n\n if (pBlackQueens == NULL || pWhiteQueens == NULL) {\n exit(EXIT_FAILURE);\n }\n\n board = calloc(length, sizeof(char));\n if (board == NULL) {\n exit(EXIT_FAILURE);\n }\n\n queenNode = pBlackQueens->head;\n while (queenNode != NULL) {\n board[queenNode->pos.x * n + queenNode->pos.y] = Black;\n queenNode = queenNode->next;\n }\n\n queenNode = pWhiteQueens->head;\n while (queenNode != NULL) {\n board[queenNode->pos.x * n + queenNode->pos.y] = White;\n queenNode = queenNode->next;\n }\n\n for (i = 0; i < length; i++) {\n if (i != 0 && i % n == 0) {\n printf(\"\\n\");\n }\n switch (board[i]) {\n case Black:\n printf(\"B \");\n break;\n case White:\n printf(\"W \");\n break;\n default:\n j = i / n;\n k = i - j * n;\n if (j % 2 == k % 2) {\n printf(\" \");\n } else {\n printf(\"# \");\n }\n break;\n }\n }\n\n printf(\"\\n\\n\");\n}\n\nvoid test(int n, int q) {\n List blackQueens = makeList();\n List whiteQueens = makeList();\n\n printf(\"%d black and %d white queens on a %d x %d board:\\n\", q, q, n, n);\n if (place(q, n, &blackQueens, &whiteQueens)) {\n printBoard(n, &blackQueens, &whiteQueens);\n } else {\n printf(\"No solution exists.\\n\\n\");\n }\n\n releaseList(&blackQueens);\n releaseList(&whiteQueens);\n}\n\nint main() {\n test(2, 1);\n\n test(3, 1);\n test(3, 2);\n\n test(4, 1);\n test(4, 2);\n test(4, 3);\n\n test(5, 1);\n test(5, 2);\n test(5, 3);\n test(5, 4);\n test(5, 5);\n\n test(6, 1);\n test(6, 2);\n test(6, 3);\n test(6, 4);\n test(6, 5);\n test(6, 6);\n\n test(7, 1);\n test(7, 2);\n test(7, 3);\n test(7, 4);\n test(7, 5);\n test(7, 6);\n test(7, 7);\n\n return EXIT_SUCCESS;\n}"} +{"title": "Peaceful chess queen armies", "language": "Python", "task": "In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces ''not'' of its own colour.\n\n\n\n\n\u21d6\n\u21d1\n\u21d7\n\n\n\n\u21d0\n\u21d0\n\u265b\n\u21d2\n\u21d2\n\n\n\n\u21d9\n\u21d3\n\u21d8\n\n\n\n\u21d9\n\n\u21d3\n\n\u21d8\n\n\n\n\n\u21d3\n\n\n\n\n\n\nThe goal of Peaceful chess queen armies is to arrange m black queens and m white queens on an n-by-n square grid, (the board), so that ''no queen attacks another of a different colour''.\n\n\n;Task:\n# Create a routine to represent two-colour queens on a 2-D board. (Alternating black/white background colours, Unicode chess pieces and other embellishments are not necessary, but may be used at your discretion).\n# Create a routine to generate at least one solution to placing m equal numbers of black and white queens on an n square board.\n# Display here results for the m=4, n=5 case.\n\n\n;References:\n* [http://www.mathopt.org/Optima-Issues/optima62.pdf Peaceably Coexisting Armies of Queens] (Pdf) by Robert A. Bosch. Optima, the Mathematical Programming Socity newsletter, issue 62.\n* [https://oeis.org/A250000 A250000] OEIS\n\n", "solution": "from itertools import combinations, product, count\nfrom functools import lru_cache, reduce\n\n\n_bbullet, _wbullet = '\\u2022\\u25E6'\n_or = set.__or__\n\ndef place(m, n):\n \"Place m black and white queens, peacefully, on an n-by-n board\"\n board = set(product(range(n), repeat=2)) # (x, y) tuples\n placements = {frozenset(c) for c in combinations(board, m)}\n for blacks in placements:\n black_attacks = reduce(_or, \n (queen_attacks_from(pos, n) for pos in blacks), \n set())\n for whites in {frozenset(c) # Never on blsck attacking squares\n for c in combinations(board - black_attacks, m)}:\n if not black_attacks & whites:\n return blacks, whites\n return set(), set()\n\n@lru_cache(maxsize=None)\ndef queen_attacks_from(pos, n):\n x0, y0 = pos\n a = set([pos]) # Its position\n a.update((x, y0) for x in range(n)) # Its row\n a.update((x0, y) for y in range(n)) # Its column\n # Diagonals\n for x1 in range(n):\n # l-to-r diag\n y1 = y0 -x0 +x1\n if 0 <= y1 < n: \n a.add((x1, y1))\n # r-to-l diag\n y1 = y0 +x0 -x1\n if 0 <= y1 < n: \n a.add((x1, y1))\n return a\n\ndef pboard(black_white, n):\n \"Print board\"\n if black_white is None: \n blk, wht = set(), set()\n else:\n blk, wht = black_white\n print(f\"## {len(blk)} black and {len(wht)} white queens \"\n f\"on a {n}-by-{n} board:\", end='')\n for x, y in product(range(n), repeat=2):\n if y == 0:\n print()\n xy = (x, y)\n ch = ('?' if xy in blk and xy in wht \n else 'B' if xy in blk\n else 'W' if xy in wht\n else _bbullet if (x + y)%2 else _wbullet)\n print('%s' % ch, end='')\n print()\n\nif __name__ == '__main__':\n n=2\n for n in range(2, 7):\n print()\n for m in count(1):\n ans = place(m, n)\n if ans[0]:\n pboard(ans, n)\n else:\n print (f\"# Can't place {m} queens on a {n}-by-{n} board\")\n break\n #\n print('\\n')\n m, n = 5, 7\n ans = place(m, n)\n pboard(ans, n)"} +{"title": "Pentagram", "language": "C", "task": "right\n\nA 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* [http://proofsfromthebook.com/2013/08/04/angle-sum-of-a-pentagram/ 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": "Pentagram", "language": "Python 3.4.1", "task": "right\n\nA 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* [http://proofsfromthebook.com/2013/08/04/angle-sum-of-a-pentagram/ Angle sum of a pentagram]\n\n", "solution": "import turtle\n\nturtle.bgcolor(\"green\")\nt = turtle.Turtle()\nt.color(\"red\", \"blue\")\nt.begin_fill()\nfor i in range(0, 5):\n t.forward(200)\n t.right(144)\nt.end_fill()"} +{"title": "Pentomino tiling", "language": "Python", "task": "A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes, \nif you don't count rotations and reflections. Most pentominoes can form their own mirror image through \nrotation, but some of them have to be flipped over.\n\n I \n I L N Y \n FF I L NN PP TTT V W X YY ZZ\nFF I L N PP T U U V WW XXX Y Z \n F I LL N P T UUU VVV WW X Y ZZ \n\n\nA Pentomino tiling is an example of an exact cover problem and can take on many forms. \nA traditional tiling presents an 8 by 8 grid, where 4 cells are left uncovered. The other cells are covered \nby the 12 pentomino shapes, without overlaps, with every shape only used once.\n\nThe 4 uncovered cells should be chosen at random. Note that not all configurations are solvable.\n\n\n;Task\nCreate an 8 by 8 tiling and print the result.\n\n\n;Example\n\nF I I I I I L N\nF F F L L L L N\nW F - X Z Z N N\nW W X X X Z N V\nT W W X - Z Z V\nT T T P P V V V\nT Y - P P U U U\nY Y Y Y P U - U\n\n\n;Related tasks\n* Free polyominoes enumeration\n\n", "solution": "from itertools import product\n\nminos = (((197123, 7, 6), (1797, 6, 7), (1287, 6, 7), (196867, 7, 6)),\n ((263937, 6, 6), (197126, 6, 6), (393731, 6, 6), (67332, 6, 6)),\n ((16843011, 7, 5), (2063, 5, 7), (3841, 5, 7), (271, 5, 7), (3848, 5, 7), (50463234, 7, 5), (50397441, 7, 5), (33686019, 7, 5)),\n ((131843, 7, 6), (1798, 6, 7), (775, 6, 7), (1795, 6, 7), (1543, 6, 7), (197377, 7, 6), (197378, 7, 6), (66307, 7, 6)),\n ((132865, 6, 6), (131846, 6, 6), (198146, 6, 6), (132611, 6, 6), (393986, 6, 6), (263938, 6, 6), (67330, 6, 6), (132868, 6, 6)),\n ((1039, 5, 7), (33751554, 7, 5), (16843521, 7, 5), (16974081, 7, 5), (33686274, 7, 5), (3842, 5, 7), (3844, 5, 7), (527, 5, 7)),\n ((1804, 5, 7), (33751297, 7, 5), (33686273, 7, 5), (16974338, 7, 5), (16843522, 7, 5), (782, 5, 7), (3079, 5, 7), (3587, 5, 7)),\n ((263683, 6, 6), (198148, 6, 6), (66310, 6, 6), (393985, 6, 6)),\n ((67329, 6, 6), (131591, 6, 6), (459266, 6, 6), (263940, 6, 6)),\n ((459780, 6, 6), (459009, 6, 6), (263175, 6, 6), (65799, 6, 6)),\n ((4311810305, 8, 4), (31, 4, 8)),\n ((132866, 6, 6),))\n\nboxchar_double_width = ' \u2576\u257a\u2575\u2514\u2515\u2579\u2516\u2517\u2574\u2500\u257c\u2518\u2534\u2536\u251a\u2538\u253a\u2578\u257e\u2501\u2519\u2535\u2537\u251b\u2539\u253b\u2577\u250c\u250d\u2502\u251c\u251d\u257f\u251e\u2521\u2510\u252c\u252e\u2524\u253c\u253e\u2526\u2540\u2544\u2511\u252d\u252f\u2525\u253d\u253f\u2529\u2543\u2547\u257b\u250e\u250f\u257d\u251f\u2522\u2503\u2520\u2523\u2512\u2530\u2532\u2527\u2541\u2546\u2528\u2542\u254a\u2513\u2531\u2533\u252a\u2545\u2548\u252b\u2549\u254b'\nboxchar_single_width = [c + ' \u2500\u2501'[i%3] for i, c in enumerate(boxchar_double_width)]\n\n# choose drawing alphabet based on terminal font\npatterns = boxchar_single_width\n\ntiles = []\nfor row in reversed(minos):\n tiles.append([])\n for n, x, y in row:\n for shift in (b*8 + a for a, b in product(range(x), range(y))):\n tiles[-1].append(n << shift)\n\ndef img(seq):\n b = [[0]*10 for _ in range(10)]\n\n for i, s in enumerate(seq):\n for j, k in product(range(8), range(8)):\n if s & (1<<(j*8 + k)):\n b[j + 1][k + 1] = i + 1\n\n idices = [[0]*9 for _ in range(9)]\n for i, j in product(range(9), range(9)):\n n = (b[i+1][j+1], b[i][j+1], b[i][j], b[i+1][j], b[i+1][j+1])\n idices[i][j] = sum((a != b)*(1 + (not a or not b))*3**i for i, (a,b) in enumerate(zip(n, n[1:])))\n\n return '\\n'.join(''.join(patterns[i] for i in row) for row in idices)\n\ndef tile(board=0, seq=tuple(), tiles=tiles):\n if not tiles:\n yield img(seq)\n return\n\n for c in tiles[0]:\n b = board | c\n\n tnext = [] # not using list comprehension ...\n for t in tiles[1:]:\n tnext.append(tuple(n for n in t if not n&b))\n if not tnext[-1]: break # because early break is faster\n else:\n yield from tile(b, seq + (c,), tnext)\n\nfor x in tile():\n print(x)"} +{"title": "Perfect shuffle", "language": "C", "task": "A perfect shuffle (or [https://en.wikipedia.org/wiki/Faro_shuffle 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\u2660 8\u2660 9\u2660 J\u2660 Q\u2660 K\u2660\u21927\u2660\u00a0 8\u2660\u00a0 9\u2660\u00a0\u00a0J\u2660\u00a0 Q\u2660\u00a0 K\u2660\u21927\u2660 J\u2660 8\u2660 Q\u2660 9\u2660 K\u2660\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"} +{"title": "Perfect shuffle", "language": "JavaScript", "task": "A perfect shuffle (or [https://en.wikipedia.org/wiki/Faro_shuffle 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\u2660 8\u2660 9\u2660 J\u2660 Q\u2660 K\u2660\u21927\u2660\u00a0 8\u2660\u00a0 9\u2660\u00a0\u00a0J\u2660\u00a0 Q\u2660\u00a0 K\u2660\u21927\u2660 J\u2660 8\u2660 Q\u2660 9\u2660 K\u2660\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": "(() => {\n 'use strict';\n\n // shuffleCycleLength :: Int -> Int\n const shuffleCycleLength = deckSize =>\n firstCycle(shuffle, range(1, deckSize))\n .all.length;\n\n // shuffle :: [a] -> [a]\n const shuffle = xs =>\n concat(zip.apply(null, splitAt(div(length(xs), 2), xs)));\n\n // firstycle :: Eq a => (a -> a) -> a -> [a]\n const firstCycle = (f, x) =>\n until(\n m => EqArray(x, m.current),\n m => {\n const fx = f(m.current);\n return {\n current: fx,\n all: m.all.concat([fx])\n };\n }, {\n current: f(x),\n all: [x]\n }\n );\n\n // Two arrays equal ?\n // EqArray :: [a] -> [b] -> Bool\n const EqArray = (xs, ys) => {\n const [nx, ny] = [xs.length, ys.length];\n return nx === ny ? (\n nx > 0 ? (\n xs[0] === ys[0] && EqArray(xs.slice(1), ys.slice(1))\n ) : true\n ) : false;\n };\n\n // GENERIC FUNCTIONS\n\n // zip :: [a] -> [b] -> [(a,b)]\n const zip = (xs, ys) =>\n xs.slice(0, Math.min(xs.length, ys.length))\n .map((x, i) => [x, ys[i]]);\n\n // concat :: [[a]] -> [a]\n const concat = xs => [].concat.apply([], xs);\n\n // splitAt :: Int -> [a] -> ([a],[a])\n const splitAt = (n, xs) => [xs.slice(0, n), xs.slice(n)];\n\n // div :: Num -> Num -> Int\n const div = (x, y) => Math.floor(x / y);\n\n // until :: (a -> Bool) -> (a -> a) -> a -> a\n const until = (p, f, x) => {\n const go = x => p(x) ? x : go(f(x));\n return go(x);\n }\n\n // range :: Int -> Int -> [Int]\n const range = (m, n) =>\n Array.from({\n length: Math.floor(n - m) + 1\n }, (_, i) => m + i);\n\n // length :: [a] -> Int\n // length :: Text -> Int\n const length = xs => xs.length;\n\n // maximumBy :: (a -> a -> Ordering) -> [a] -> a\n const maximumBy = (f, xs) =>\n xs.reduce((a, x) => a === undefined ? x : (\n f(x, a) > 0 ? x : a\n ), undefined);\n\n // transpose :: [[a]] -> [[a]]\n const transpose = xs =>\n xs[0].map((_, iCol) => xs.map((row) => row[iCol]));\n\n // show :: a -> String\n const show = x => JSON.stringify(x, null, 2);\n\n // replicateS :: Int -> String -> String\n const replicateS = (n, s) => {\n let v = s,\n o = '';\n if (n < 1) return o;\n while (n > 1) {\n if (n & 1) o = o.concat(v);\n n >>= 1;\n v = v.concat(v);\n }\n return o.concat(v);\n };\n\n // justifyRight :: Int -> Char -> Text -> Text\n const justifyRight = (n, cFiller, strText) =>\n n > strText.length ? (\n (replicateS(n, cFiller) + strText)\n .slice(-n)\n ) : strText;\n\n // TEST\n return transpose(transpose([\n ['Deck', 'Shuffles']\n ].concat(\n [8, 24, 52, 100, 1020, 1024, 10000]\n .map(n => [n.toString(), shuffleCycleLength(n)\n .toString()\n ])))\n .map(col => { // Right-justified number columns\n const width = length(\n maximumBy((a, b) => length(a) - length(b), col)\n ) + 2;\n\n return col.map(x => justifyRight(width, ' ', x));\n }))\n .map(row => row.join(''))\n .join('\\n');\n})();"} +{"title": "Perfect shuffle", "language": "Python", "task": "A perfect shuffle (or [https://en.wikipedia.org/wiki/Faro_shuffle 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\u2660 8\u2660 9\u2660 J\u2660 Q\u2660 K\u2660\u21927\u2660\u00a0 8\u2660\u00a0 9\u2660\u00a0\u00a0J\u2660\u00a0 Q\u2660\u00a0 K\u2660\u21927\u2660 J\u2660 8\u2660 Q\u2660 9\u2660 K\u2660\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": "\n\"\"\"\nBrute force solution for the Perfect Shuffle problem.\nSee http://oeis.org/A002326 for possible improvements\n\"\"\"\nfrom functools import partial\nfrom itertools import chain\nfrom operator import eq\nfrom typing import (Callable,\n Iterable,\n Iterator,\n List,\n TypeVar)\n\nT = TypeVar('T')\n\n\ndef main():\n print(\"Deck length | Shuffles \")\n for length in (8, 24, 52, 100, 1020, 1024, 10000):\n deck = list(range(length))\n shuffles_needed = spin_number(deck, shuffle)\n print(f\"{length:<11} | {shuffles_needed}\")\n\n\ndef shuffle(deck: List[T]) -> List[T]:\n \"\"\"[1, 2, 3, 4] -> [1, 3, 2, 4]\"\"\"\n half = len(deck) // 2\n return list(chain.from_iterable(zip(deck[:half], deck[half:])))\n\n\ndef spin_number(source: T,\n function: Callable[[T], T]) -> int:\n \"\"\"\n Applies given function to the source\n until the result becomes equal to it,\n returns the number of calls \n \"\"\"\n is_equal_source = partial(eq, source)\n spins = repeat_call(function, source)\n return next_index(is_equal_source,\n spins,\n start=1)\n\n\ndef repeat_call(function: Callable[[T], T],\n value: T) -> Iterator[T]:\n \"\"\"(f, x) -> f(x), f(f(x)), f(f(f(x))), ...\"\"\"\n while True:\n value = function(value)\n yield value\n\n\ndef next_index(predicate: Callable[[T], bool],\n iterable: Iterable[T],\n start: int = 0) -> int:\n \"\"\"\n Returns index of the first element of the iterable\n satisfying given condition\n \"\"\"\n for index, item in enumerate(iterable, start=start):\n if predicate(item):\n return index\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"title": "Perfect totient numbers", "language": "C", "task": "Generate and show here, the first twenty [https://en.wikipedia.org/wiki/Perfect_totient_number Perfect totient numbers].\n\n\n;Related task:\n::* \u00a0 [[Totient function]]\n\n\n;Also see:\n::* \u00a0 the OEIS entry for \u00a0 [http://oeis.org/A082897 perfect totient numbers].\n::* \u00a0 mrob \u00a0 [https://mrob.com/pub/seq/a082897.html list of the first 54]\n\n", "solution": "#include\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\nOutput for multiple runs, a is the default executable file name produced by GCC\n\nC:\\rossetaCode>a 10\nThe first 10 perfect Totient numbers are :\n[ 3, 9, 15, 27, 39, 81, 111, 183, 243, 255]\nC:\\rossetaCode>a 20\nThe first 20 perfect Totient numbers are :\n[ 3, 9, 15, 27, 39, 81, 111, 183, 243, 255, 327, 363, 471, 729, 2187, 2199, 3063, 4359, 4375, 5571]\nC:\\rossetaCode>a 30\nThe first 30 perfect Totient numbers are :\n[ 3, 9, 15, 27, 39, 81, 111, 183, 243, 255, 327, 363, 471, 729, 2187, 2199, 3063, 4359, 4375, 5571, 6561, 8751, 15723, 19683, 36759, 46791, 59049, 65535, 140103, 177147]\nC:\\rossetaCode>a 40\nThe first 40 perfect Totient numbers are :\n[ 3, 9, 15, 27, 39, 81, 111, 183, 243, 255, 327, 363, 471, 729, 2187, 2199, 3063, 4359, 4375, 5571, 6561, 8751, 15723, 19683, 36759, 46791, 59049, 65535, 140103, 177147, 208191, 441027, 531441, 1594323, 4190263, 4782969, 9056583, 14348907, 43046721, 57395631]\n\n"} +{"title": "Perfect totient numbers", "language": "JavaScript", "task": "Generate and show here, the first twenty [https://en.wikipedia.org/wiki/Perfect_totient_number Perfect totient numbers].\n\n\n;Related task:\n::* \u00a0 [[Totient function]]\n\n\n;Also see:\n::* \u00a0 the OEIS entry for \u00a0 [http://oeis.org/A082897 perfect totient numbers].\n::* \u00a0 mrob \u00a0 [https://mrob.com/pub/seq/a082897.html list of the first 54]\n\n", "solution": "(() => {\n 'use strict';\n\n // main :: IO ()\n const main = () =>\n showLog(\n take(20, perfectTotients())\n );\n\n // perfectTotients :: Generator [Int]\n function* perfectTotients() {\n const\n phi = memoized(\n n => length(\n filter(\n k => 1 === gcd(n, k),\n enumFromTo(1, n)\n )\n )\n ),\n imperfect = n => n !== sum(\n tail(iterateUntil(\n x => 1 === x,\n phi,\n n\n ))\n );\n let ys = dropWhileGen(imperfect, enumFrom(1))\n while (true) {\n yield ys.next().value - 1;\n ys = dropWhileGen(imperfect, ys)\n }\n }\n\n // GENERIC FUNCTIONS ----------------------------\n\n // abs :: Num -> Num\n const abs = Math.abs;\n\n // dropWhileGen :: (a -> Bool) -> Gen [a] -> [a]\n const dropWhileGen = (p, xs) => {\n let\n nxt = xs.next(),\n v = nxt.value;\n while (!nxt.done && p(v)) {\n nxt = xs.next();\n v = nxt.value;\n }\n return xs;\n };\n\n // enumFrom :: Int -> [Int]\n function* enumFrom(x) {\n let v = x;\n while (true) {\n yield v;\n v = 1 + v;\n }\n }\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = (m, n) =>\n m <= n ? iterateUntil(\n x => n <= x,\n x => 1 + x,\n m\n ) : [];\n\n // filter :: (a -> Bool) -> [a] -> [a]\n const filter = (f, xs) => xs.filter(f);\n\n // gcd :: Int -> Int -> Int\n const gcd = (x, y) => {\n const\n _gcd = (a, b) => (0 === b ? a : _gcd(b, a % b)),\n abs = Math.abs;\n return _gcd(abs(x), abs(y));\n };\n\n // iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a]\n const iterateUntil = (p, f, x) => {\n const vs = [x];\n let h = x;\n while (!p(h))(h = f(h), vs.push(h));\n return vs;\n };\n\n // Returns Infinity over objects without finite length.\n // This enables zip and zipWith to choose the shorter\n // argument when one is non-finite, like cycle, repeat etc\n\n // length :: [a] -> Int\n const length = xs =>\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n // memoized :: (a -> b) -> (a -> b)\n const memoized = f => {\n const dctMemo = {};\n return x => {\n const v = dctMemo[x];\n return undefined !== v ? v : (dctMemo[x] = f(x));\n };\n };\n\n // showLog :: a -> IO ()\n const showLog = (...args) =>\n console.log(\n args\n .map(JSON.stringify)\n .join(' -> ')\n );\n\n // sum :: [Num] -> Num\n const sum = xs => xs.reduce((a, x) => a + x, 0);\n\n // tail :: [a] -> [a]\n const tail = xs => 0 < xs.length ? xs.slice(1) : [];\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = (n, xs) =>\n 'GeneratorFunction' !== xs.constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // MAIN ---\n main();\n})();"} +{"title": "Perfect totient numbers", "language": "Python", "task": "Generate and show here, the first twenty [https://en.wikipedia.org/wiki/Perfect_totient_number Perfect totient numbers].\n\n\n;Related task:\n::* \u00a0 [[Totient function]]\n\n\n;Also see:\n::* \u00a0 the OEIS entry for \u00a0 [http://oeis.org/A082897 perfect totient numbers].\n::* \u00a0 mrob \u00a0 [https://mrob.com/pub/seq/a082897.html list of the first 54]\n\n", "solution": "from math import gcd\nfrom functools import lru_cache\nfrom itertools import islice, count\n\n@lru_cache(maxsize=None)\ndef \u03c6(n):\n return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)\n\ndef perfect_totient():\n for n0 in count(1):\n parts, n = 0, n0\n while n != 1:\n n = \u03c6(n)\n parts += n\n if parts == n0:\n yield n0\n \n\nif __name__ == '__main__':\n print(list(islice(perfect_totient(), 20)))"} +{"title": "Periodic table", "language": "C", "task": ";Task:\nDisplay the row and column in the periodic table of the given atomic number.\n\n;The periodic table:\nLet us consider the following periodic table representation.\n\n\n __________________________________________________________________________ \n | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |\n | |\n |1 H He |\n | |\n |2 Li Be B C N O F Ne |\n | |\n |3 Na Mg Al Si P S Cl Ar |\n | |\n |4 K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr |\n | |\n |5 Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe |\n | |\n |6 Cs Ba * Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn |\n | |\n |7 Fr Ra \u00b0 Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og |\n |__________________________________________________________________________|\n | |\n | |\n |8 Lantanoidi* La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu |\n | |\n |9 Aktinoidi\u00b0 Ak Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr |\n |__________________________________________________________________________|\n\n\n;Example test cases;\n\n* \u00a0 1 -> 1 1\n* \u00a0 2 -> 1 18\n* \u00a0 29 -> 4 11\n* \u00a0 42 -> 5 6\n* \u00a0 57 -> 8 4\n* \u00a0 58 -> 8 5\n* \u00a0 72 -> 6 4\n* \u00a0 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 [https://en.wikipedia.org/wiki/Periodic_table#/media/File:Simple_Periodic_Table_Chart-blocks.svg here].\n\nThe atomic number is at least 1, at most 118.\n\n\n;See also: \n* \u00a0 [https://en.wikipedia.org/wiki/Periodic_table the periodic table]\n* \u00a0 [https://twitter.com/CompSciFact/status/1537447575573233666 This task was an idea from CompSciFact]\n* \u00a0 [https://ascii.periodni.com/index.html The periodic table in ascii] that was used as template\n\n", "solution": "\n\n#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": "Periodic table", "language": "Python", "task": ";Task:\nDisplay the row and column in the periodic table of the given atomic number.\n\n;The periodic table:\nLet us consider the following periodic table representation.\n\n\n __________________________________________________________________________ \n | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |\n | |\n |1 H He |\n | |\n |2 Li Be B C N O F Ne |\n | |\n |3 Na Mg Al Si P S Cl Ar |\n | |\n |4 K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr |\n | |\n |5 Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe |\n | |\n |6 Cs Ba * Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn |\n | |\n |7 Fr Ra \u00b0 Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og |\n |__________________________________________________________________________|\n | |\n | |\n |8 Lantanoidi* La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu |\n | |\n |9 Aktinoidi\u00b0 Ak Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr |\n |__________________________________________________________________________|\n\n\n;Example test cases;\n\n* \u00a0 1 -> 1 1\n* \u00a0 2 -> 1 18\n* \u00a0 29 -> 4 11\n* \u00a0 42 -> 5 6\n* \u00a0 57 -> 8 4\n* \u00a0 58 -> 8 5\n* \u00a0 72 -> 6 4\n* \u00a0 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 [https://en.wikipedia.org/wiki/Periodic_table#/media/File:Simple_Periodic_Table_Chart-blocks.svg here].\n\nThe atomic number is at least 1, at most 118.\n\n\n;See also: \n* \u00a0 [https://en.wikipedia.org/wiki/Periodic_table the periodic table]\n* \u00a0 [https://twitter.com/CompSciFact/status/1537447575573233666 This task was an idea from CompSciFact]\n* \u00a0 [https://ascii.periodni.com/index.html The periodic table in ascii] that was used as template\n\n", "solution": "\ndef perta(atomic) -> (int, int):\n\n NOBLES = 2, 10, 18, 36, 54, 86, 118\n INTERTWINED = 0, 0, 0, 0, 0, 57, 89\n INTERTWINING_SIZE = 14\n LINE_WIDTH = 18\n\n prev_noble = 0\n for row, noble in enumerate(NOBLES):\n if atomic <= noble: # we are at the good row. We now need to determine the column\n nb_elem = noble - prev_noble # number of elements on that row\n rank = atomic - prev_noble # rank of the input element among elements\n if INTERTWINED[row] and INTERTWINED[row] <= atomic <= INTERTWINED[row] + INTERTWINING_SIZE: # lantanides or actinides\n row += 2\n col = rank + 1\n else: # not a lantanide nor actinide\n # handle empty spaces between 1-2, 4-5 and 12-13.\n nb_empty = LINE_WIDTH - nb_elem # spaces count as columns\n inside_left_element_rank = 2 if noble > 2 else 1\n col = rank + (nb_empty if rank > inside_left_element_rank else 0)\n break\n prev_noble = noble\n return row+1, col\n\n\n\n# small test suite\n\nTESTS = {\n 1: (1, 1),\n 2: (1, 18),\n 29: (4,11),\n 42: (5, 6),\n 58: (8, 5),\n 59: (8, 6),\n 57: (8, 4),\n 71: (8, 18),\n 72: (6, 4),\n 89: (9, 4),\n 90: (9, 5),\n 103: (9, 18),\n}\n\nfor input, out in TESTS.items():\n found = perta(input)\n print('TEST:{:3d} -> '.format(input) + str(found) + (f' ; ERROR: expected {out}' if found != out else ''))\n\n"} +{"title": "Perlin noise", "language": "C", "task": "The \u00a0 '''computer graphics, \u00a0 most notably to procedurally generate textures or heightmaps. \n\nThe Perlin noise is basically a \u00a0 pseudo-random \u00a0 mapping of \u00a0 \\R^d \u00a0 into \u00a0 \\R \u00a0 with an integer \u00a0 d \u00a0 which can be arbitrarily large but which is usually \u00a0 2, \u00a0 3, \u00a0 or \u00a0 4.\n\nEither by using a dedicated library or by implementing the algorithm, show that the Perlin noise \u00a0 (as defined in 2002 in the Java implementation below) \u00a0 of the point in 3D-space with coordinates \u00a0 \u00a0 3.14, \u00a0 42, \u00a0 7 \u00a0 \u00a0 is \u00a0 \u00a0 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": "\n#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": "Perlin noise", "language": "Python", "task": "The \u00a0 '''computer graphics, \u00a0 most notably to procedurally generate textures or heightmaps. \n\nThe Perlin noise is basically a \u00a0 pseudo-random \u00a0 mapping of \u00a0 \\R^d \u00a0 into \u00a0 \\R \u00a0 with an integer \u00a0 d \u00a0 which can be arbitrarily large but which is usually \u00a0 2, \u00a0 3, \u00a0 or \u00a0 4.\n\nEither by using a dedicated library or by implementing the algorithm, show that the Perlin noise \u00a0 (as defined in 2002 in the Java implementation below) \u00a0 of the point in 3D-space with coordinates \u00a0 \u00a0 3.14, \u00a0 42, \u00a0 7 \u00a0 \u00a0 is \u00a0 \u00a0 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": "import math\n\ndef perlin_noise(x, y, z):\n X = math.floor(x) & 255 # FIND UNIT CUBE THAT\n Y = math.floor(y) & 255 # CONTAINS POINT.\n Z = math.floor(z) & 255\n x -= math.floor(x) # FIND RELATIVE X,Y,Z\n y -= math.floor(y) # OF POINT IN CUBE.\n z -= math.floor(z)\n u = fade(x) # COMPUTE FADE CURVES\n v = fade(y) # FOR EACH OF X,Y,Z.\n w = fade(z)\n A = p[X ]+Y; AA = p[A]+Z; AB = p[A+1]+Z # HASH COORDINATES OF\n B = p[X+1]+Y; BA = p[B]+Z; BB = p[B+1]+Z # THE 8 CUBE CORNERS,\n \n return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ), # AND ADD\n grad(p[BA ], x-1, y , z )), # BLENDED\n lerp(u, grad(p[AB ], x , y-1, z ), # RESULTS\n grad(p[BB ], x-1, y-1, z ))),# FROM 8\n lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ), # CORNERS\n grad(p[BA+1], x-1, y , z-1 )), # OF CUBE\n lerp(u, grad(p[AB+1], x , y-1, z-1 ),\n grad(p[BB+1], x-1, y-1, z-1 ))))\n \ndef fade(t): \n return t ** 3 * (t * (t * 6 - 15) + 10)\n \ndef lerp(t, a, b):\n return a + t * (b - a)\n \ndef grad(hash, x, y, z):\n h = hash & 15 # CONVERT LO 4 BITS OF HASH CODE\n u = x if h<8 else y # INTO 12 GRADIENT DIRECTIONS.\n v = y if h<4 else (x if h in (12, 14) else z)\n return (u if (h&1) == 0 else -u) + (v if (h&2) == 0 else -v)\n\np = [None] * 512\npermutation = [151,160,137,91,90,15,\n 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,\n 190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,\n 88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,\n 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,\n 102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,\n 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,\n 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,\n 223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,\n 129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,\n 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,\n 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,\n 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180]\nfor i in range(256):\n p[256+i] = p[i] = permutation[i]\n\nif __name__ == '__main__':\n print(\"%1.17f\" % perlin_noise(3.14, 42, 7))"} +{"title": "Permutations/Derangements", "language": "C", "task": "A [http://mathworld.wolfram.com/Derangement.html 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* \u00a0 Calculate \u00a0 !''20'' \n\n\n;Related tasks:\n* \u00a0 [[Anagrams/Deranged anagrams]]\n* \u00a0 [[Best shuffle]]\n* \u00a0 [[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/Derangements", "language": "Python", "task": "A [http://mathworld.wolfram.com/Derangement.html 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* \u00a0 Calculate \u00a0 !''20'' \n\n\n;Related tasks:\n* \u00a0 [[Anagrams/Deranged anagrams]]\n* \u00a0 [[Best shuffle]]\n* \u00a0 [[Left_factorials]]\n\n\n\n", "solution": "from itertools import permutations\nimport math\n\n\ndef derangements(n):\n 'All deranged permutations of the integers 0..n-1 inclusive'\n return ( perm for perm in permutations(range(n))\n if all(indx != p for indx, p in enumerate(perm)) )\n\ndef subfact(n):\n if n == 2 or n == 0:\n return 1\n elif n == 1:\n return 0\n elif 1 <= n <=18:\n return round(math.factorial(n) / math.e)\n elif n.imag == 0 and n.real == int(n.real) and n > 0:\n return (n-1) * ( subfact(n - 1) + subfact(n - 2) )\n else:\n raise ValueError()\n\ndef _iterlen(iter):\n 'length of an iterator without taking much memory'\n l = 0\n for x in iter:\n l += 1\n return l\n\nif __name__ == '__main__':\n n = 4\n print(\"Derangements of %s\" % (tuple(range(n)),))\n for d in derangements(n):\n print(\" %s\" % (d,))\n\n print(\"\\nTable of n vs counted vs calculated derangements\")\n for n in range(10):\n print(\"%2i %-5i %-5i\" %\n (n, _iterlen(derangements(n)), subfact(n)))\n\n n = 20\n print(\"\\n!%i = %i\" % (n, subfact(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 [http://stackoverflow.com/questions/12884428/generate-sample-of-1-000-000-random-permutations 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# [http://webhome.cs.uvic.ca/~ruskey/Publications/RankPerm/RankPerm.html Ranking and Unranking Permutations in Linear Time] by Myrvold & Ruskey. (Also available via Google [https://docs.google.com/viewer?a=v&q=cache:t8G2xQ3-wlkJ:citeseerx.ist.psu.edu/viewdoc/download%3Fdoi%3D10.1.1.43.4521%26rep%3Drep1%26type%3Dpdf+&hl=en\u2277=uk&pid=bl&srcid=ADGEESgDcCc4JVd_57ziRRFlhDFxpPxoy88eABf9UG_TLXMzfxiC8D__qx4xfY3JAhw_nuPDrZ9gSInX0MbpYjgh807ZfoNtLrl40wdNElw2JMdi94Znv1diM-XYo53D8uelCXnK053L&sig=AHIEtbQtx-sxcVzaZgy9uhniOmETuW4xKg here]).\n# [http://www.davdata.nl/math/ranks.html Ranks] on the DevData site.\n# [http://stackoverflow.com/a/1506337/10562 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/Rank of a permutation", "language": "Python", "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 [http://stackoverflow.com/questions/12884428/generate-sample-of-1-000-000-random-permutations 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# [http://webhome.cs.uvic.ca/~ruskey/Publications/RankPerm/RankPerm.html Ranking and Unranking Permutations in Linear Time] by Myrvold & Ruskey. (Also available via Google [https://docs.google.com/viewer?a=v&q=cache:t8G2xQ3-wlkJ:citeseerx.ist.psu.edu/viewdoc/download%3Fdoi%3D10.1.1.43.4521%26rep%3Drep1%26type%3Dpdf+&hl=en\u2277=uk&pid=bl&srcid=ADGEESgDcCc4JVd_57ziRRFlhDFxpPxoy88eABf9UG_TLXMzfxiC8D__qx4xfY3JAhw_nuPDrZ9gSInX0MbpYjgh807ZfoNtLrl40wdNElw2JMdi94Znv1diM-XYo53D8uelCXnK053L&sig=AHIEtbQtx-sxcVzaZgy9uhniOmETuW4xKg here]).\n# [http://www.davdata.nl/math/ranks.html Ranks] on the DevData site.\n# [http://stackoverflow.com/a/1506337/10562 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": "from math import factorial as fact\nfrom random import randrange\nfrom textwrap import wrap\n\ndef identity_perm(n): \n return list(range(n))\n\ndef unranker1(n, r, pi):\n while n > 0:\n n1, (rdivn, rmodn) = n-1, divmod(r, n)\n pi[n1], pi[rmodn] = pi[rmodn], pi[n1]\n n = n1\n r = rdivn\n return pi\n\ndef init_pi1(n, pi): \n pi1 = [-1] * n\n for i in range(n): \n pi1[pi[i]] = i\n return pi1\n\ndef ranker1(n, pi, pi1):\n if n == 1: \n return 0\n n1 = n-1\n s = pi[n1]\n pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]\n pi1[s], pi1[n1] = pi1[n1], pi1[s]\n return s + n * ranker1(n1, pi, pi1)\n\ndef unranker2(n, r, pi):\n while n > 0:\n n1 = n-1\n s, rmodf = divmod(r, fact(n1))\n pi[n1], pi[s] = pi[s], pi[n1]\n n = n1\n r = rmodf\n return pi\n\ndef ranker2(n, pi, pi1):\n if n == 1: \n return 0\n n1 = n-1\n s = pi[n1]\n pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]\n pi1[s], pi1[n1] = pi1[n1], pi1[s]\n return s * fact(n1) + ranker2(n1, pi, pi1)\n\ndef get_random_ranks(permsize, samplesize): \n perms = fact(permsize)\n ranks = set()\n while len(ranks) < samplesize:\n ranks |= set( randrange(perms) \n for r in range(samplesize - len(ranks)) )\n return ranks \n\ndef test1(comment, unranker, ranker): \n n, samplesize, n2 = 3, 4, 12\n print(comment)\n perms = []\n for r in range(fact(n)):\n pi = identity_perm(n)\n perm = unranker(n, r, pi)\n perms.append((r, perm))\n for r, pi in perms:\n pi1 = init_pi1(n, pi)\n print(' From rank %2i to %r back to %2i' % (r, pi, ranker(n, pi[:], pi1)))\n print('\\n %i random individual samples of %i items:' % (samplesize, n2))\n for r in get_random_ranks(n2, samplesize):\n pi = identity_perm(n2)\n print(' ' + ' '.join('%2i' % i for i in unranker(n2, r, pi)))\n print('')\n\ndef test2(comment, unranker): \n samplesize, n2 = 4, 144\n print(comment)\n print(' %i random individual samples of %i items:' % (samplesize, n2))\n for r in get_random_ranks(n2, samplesize):\n pi = identity_perm(n2)\n print(' ' + '\\n '.join(wrap(repr(unranker(n2, r, pi)))))\n print('')\n\nif __name__ == '__main__':\n test1('First ordering:', unranker1, ranker1)\n test1('Second ordering:', unranker2, ranker2)\n test2('First ordering, large number of perms:', unranker1)"} +{"title": "Permutations by swapping", "language": "C", "task": ";Task:\nGenerate 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\u2013Johnson\u2013Trotter algorithm generates successive permutations where ''adjacent'' items are swapped, but from this discussion adjacency is not a requirement.\n\n\n;References:\n* Steinhaus\u2013Johnson\u2013Trotter algorithm\n* [http://www.cut-the-knot.org/Curriculum/Combinatorics/JohnsonTrotter.shtml Johnson-Trotter Algorithm Listing All Permutations]\n* Heap's algorithm\n* [http://www.gutenberg.org/files/18567/18567-h/18567-h.htm#ch7] Tintinnalogia\n\n\n;Related tasks:\n* \u00a0 [[Matrix arithmetic]]\n* \u00a0 [[Gray code]]\n\n", "solution": "\n#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": "Permutations by swapping", "language": "Python", "task": ";Task:\nGenerate 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\u2013Johnson\u2013Trotter algorithm generates successive permutations where ''adjacent'' items are swapped, but from this discussion adjacency is not a requirement.\n\n\n;References:\n* Steinhaus\u2013Johnson\u2013Trotter algorithm\n* [http://www.cut-the-knot.org/Curriculum/Combinatorics/JohnsonTrotter.shtml Johnson-Trotter Algorithm Listing All Permutations]\n* Heap's algorithm\n* [http://www.gutenberg.org/files/18567/18567-h/18567-h.htm#ch7] Tintinnalogia\n\n\n;Related tasks:\n* \u00a0 [[Matrix arithmetic]]\n* \u00a0 [[Gray code]]\n\n", "solution": "from operator import itemgetter\n \nDEBUG = False # like the built-in __debug__\n \ndef spermutations(n):\n \"\"\"permutations by swapping. Yields: perm, sign\"\"\"\n sign = 1\n p = [[i, 0 if i == 0 else -1] # [num, direction]\n for i in range(n)]\n \n if DEBUG: print ' #', p\n yield tuple(pp[0] for pp in p), sign\n \n while any(pp[1] for pp in p): # moving\n i1, (n1, d1) = max(((i, pp) for i, pp in enumerate(p) if pp[1]),\n key=itemgetter(1))\n sign *= -1\n if d1 == -1:\n # Swap down\n i2 = i1 - 1\n p[i1], p[i2] = p[i2], p[i1]\n # If this causes the chosen element to reach the First or last\n # position within the permutation, or if the next element in the\n # same direction is larger than the chosen element:\n if i2 == 0 or p[i2 - 1][0] > n1:\n # The direction of the chosen element is set to zero\n p[i2][1] = 0\n elif d1 == 1:\n # Swap up\n i2 = i1 + 1\n p[i1], p[i2] = p[i2], p[i1]\n # If this causes the chosen element to reach the first or Last\n # position within the permutation, or if the next element in the\n # same direction is larger than the chosen element:\n if i2 == n - 1 or p[i2 + 1][0] > n1:\n # The direction of the chosen element is set to zero\n p[i2][1] = 0\n if DEBUG: print ' #', p\n yield tuple(pp[0] for pp in p), sign\n \n for i3, pp in enumerate(p):\n n3, d3 = pp\n if n3 > n1:\n pp[1] = 1 if i3 < i2 else -1\n if DEBUG: print ' # Set Moving'\n \n \nif __name__ == '__main__':\n from itertools import permutations\n \n for n in (3, 4):\n print '\\nPermutations and sign of %i items' % n\n sp = set()\n for i in spermutations(n):\n sp.add(i[0])\n print('Perm: %r Sign: %2i' % i)\n #if DEBUG: raw_input('?')\n # Test\n p = set(permutations(range(n)))\n assert sp == p, 'Two methods of generating permutations do not agree'"} +{"title": "Phrase reversals", "language": "C", "task": ";Task:\nGiven 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": "\n#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": "Phrase reversals", "language": "JavaScript", "task": ";Task:\nGiven 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": "(function (p) {\n return [\n p.split('').reverse().join(''),\n\n p.split(' ').map(function (x) {\n return x.split('').reverse().join('');\n }).join(' '),\n\n p.split(' ').reverse().join(' ')\n\n ].join('\\n');\n\n})('rosetta code phrase reversal');"} +{"title": "Phrase reversals", "language": "Python", "task": ";Task:\nGiven 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": "'''String reversals at different levels.'''\n\n\n# reversedCharacters :: String -> String\ndef reversedCharacters(s):\n '''All characters in reversed sequence.'''\n return reverse(s)\n\n\n# wordsWithReversedCharacters :: String -> String\ndef wordsWithReversedCharacters(s):\n '''Characters within each word in reversed sequence.'''\n return unwords(map(reverse, words(s)))\n\n\n# reversedWordOrder :: String -> String\ndef reversedWordOrder(s):\n '''Sequence of words reversed.'''\n return unwords(reverse(words(s)))\n\n\n# TESTS -------------------------------------------------\n# main :: IO()\ndef main():\n '''Tests'''\n\n s = 'rosetta code phrase reversal'\n print(\n tabulated(s + ':\\n')(\n lambda f: f.__name__\n )(lambda s: \"'\" + s + \"'\")(\n lambda f: f(s)\n )([\n reversedCharacters,\n wordsWithReversedCharacters,\n reversedWordOrder\n ])\n )\n\n\n# GENERIC -------------------------------------------------\n\n\n# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n '''Function composition.'''\n return lambda f: lambda x: g(f(x))\n\n\n# reverse :: [a] -> [a]\n# reverse :: String -> String\ndef reverse(xs):\n '''The elements of xs in reverse order.'''\n return xs[::-1] if isinstance(xs, str) else (\n list(reversed(xs))\n )\n\n\n# tabulated :: String -> (a -> String) ->\n# (b -> String) ->\n# (a -> b) -> [a] -> String\ndef tabulated(s):\n '''Heading -> x display function -> fx display function ->\n f -> value list -> tabular string.'''\n def go(xShow, fxShow, f, xs):\n w = max(map(compose(len)(xShow), xs))\n return s + '\\n' + '\\n'.join(\n xShow(x).rjust(w, ' ') + ' -> ' + fxShow(f(x)) for x in xs\n )\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\n# unwords :: [String] -> String\ndef unwords(xs):\n '''A space-separated string derived from a list of words.'''\n return ' '.join(xs)\n\n\n# words :: String -> [String]\ndef words(s):\n '''A list of words delimited by characters\n representing white space.'''\n return s.split()\n\n\nif __name__ == '__main__':\n main()"} +{"title": "Pig the dice game", "language": "C", "task": "The \u00a0 game of Pig \u00a0 is a multiplayer game played with a single six-sided die. \u00a0 The\nobject of the game is to reach \u00a0 '''100''' \u00a0 points or more. \u00a0 \nPlay is taken in turns. \u00a0 On each person's turn that person has the option of either:\n\n:# '''Rolling the dice''': \u00a0 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; \u00a0 or a roll of \u00a0 '''1''' \u00a0 loses the player's total points \u00a0 ''for that turn'' \u00a0 and their turn finishes with play passing to the next player.\n:# '''Holding''': \u00a0 the player's score for that round is added to their total and becomes safe from the effects of throwing a \u00a0 '''1''' \u00a0 (one). \u00a0 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* \u00a0 [[Pig the dice game/Player]]\n\n", "solution": "\n#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": "Pig the dice game", "language": "JavaScript", "task": "The \u00a0 game of Pig \u00a0 is a multiplayer game played with a single six-sided die. \u00a0 The\nobject of the game is to reach \u00a0 '''100''' \u00a0 points or more. \u00a0 \nPlay is taken in turns. \u00a0 On each person's turn that person has the option of either:\n\n:# '''Rolling the dice''': \u00a0 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; \u00a0 or a roll of \u00a0 '''1''' \u00a0 loses the player's total points \u00a0 ''for that turn'' \u00a0 and their turn finishes with play passing to the next player.\n:# '''Holding''': \u00a0 the player's score for that round is added to their total and becomes safe from the effects of throwing a \u00a0 '''1''' \u00a0 (one). \u00a0 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* \u00a0 [[Pig the dice game/Player]]\n\n", "solution": "let players = [\n { name: '', score: 0 },\n { name: '', score: 0 }\n];\nlet curPlayer = 1,\n gameOver = false;\n\nplayers[0].name = prompt('Your name, player #1:').toUpperCase();\nplayers[1].name = prompt('Your name, player #2:').toUpperCase();\n\nfunction roll() { return 1 + Math.floor(Math.random()*6) }\n\nfunction round(player) {\n let curSum = 0,\n quit = false,\n dice;\n alert(`It's ${player.name}'s turn (${player.score}).`);\n while (!quit) {\n dice = roll();\n if (dice == 1) {\n alert('You roll a 1. What a pity!');\n quit = true;\n } else {\n curSum += dice;\n quit = !confirm(`\n You roll a ${dice} (sum: ${curSum}).\\n\n Roll again?\n `);\n if (quit) {\n player.score += curSum;\n if (player.score >= 100) gameOver = true;\n }\n }\n }\n}\n// main\nwhile (!gameOver) {\n if (curPlayer == 0) curPlayer = 1; else curPlayer = 0;\n round(players[curPlayer]);\n if (gameOver) alert(`\n ${players[curPlayer].name} wins (${players[curPlayer].score}).\n `);\n}\n"} +{"title": "Pig the dice game", "language": "Python", "task": "The \u00a0 game of Pig \u00a0 is a multiplayer game played with a single six-sided die. \u00a0 The\nobject of the game is to reach \u00a0 '''100''' \u00a0 points or more. \u00a0 \nPlay is taken in turns. \u00a0 On each person's turn that person has the option of either:\n\n:# '''Rolling the dice''': \u00a0 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; \u00a0 or a roll of \u00a0 '''1''' \u00a0 loses the player's total points \u00a0 ''for that turn'' \u00a0 and their turn finishes with play passing to the next player.\n:# '''Holding''': \u00a0 the player's score for that round is added to their total and becomes safe from the effects of throwing a \u00a0 '''1''' \u00a0 (one). \u00a0 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* \u00a0 [[Pig the dice game/Player]]\n\n", "solution": "#!/usr/bin/python3\n\n'''\nSee: http://en.wikipedia.org/wiki/Pig_(dice)\n\nThis program scores and throws the dice for a two player game of Pig\n\n'''\n\nfrom random import randint\n\nplayercount = 2\nmaxscore = 100\nsafescore = [0] * playercount\nplayer = 0\nscore=0\n\nwhile max(safescore) < maxscore:\n rolling = input(\"Player %i: (%i, %i) Rolling? (Y) \"\n % (player, safescore[player], score)).strip().lower() in {'yes', 'y', ''}\n if rolling:\n rolled = randint(1, 6)\n print(' Rolled %i' % rolled)\n if rolled == 1:\n print(' Bust! you lose %i but still keep your previous %i'\n % (score, safescore[player]))\n score, player = 0, (player + 1) % playercount\n else:\n score += rolled\n else:\n safescore[player] += score\n if safescore[player] >= maxscore:\n break\n print(' Sticking with %i' % safescore[player])\n score, player = 0, (player + 1) % playercount\n \nprint('\\nPlayer %i wins with a score of %i' %(player, safescore[player]))"} +{"title": "Pig the dice game/Player", "language": "Python", "task": ";Task:\nCreate a dice simulator and scorer of [[Pig the dice game]] and add to it the ability to play the game to at least one strategy.\n* State here the play strategies involved.\n* Show play during a game here.\n\n\nAs a stretch goal:\n* Simulate playing the game a number of times with two players of given strategies and report here summary statistics such as, but not restricted to, the influence of going first or which strategy seems stronger.\n\n\n;Game Rules:\nThe 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 one. The player's turn finishes with play passing to the next player.\n\n\n;References\n* Pig (dice)\n* [https://youtu.be/ULhRLGzoXQ0 The Math of Being a Pig] and [https://www.youtube.com/watch?v=zD9-V9Idbug Pigs (extra)] - Numberphile videos featuring Ben Sparks.\n\n", "solution": "#!/usr/bin/python3\n\n'''\nSee: http://en.wikipedia.org/wiki/Pig_(dice)\n\nThis program scores, throws the dice, and plays for an N player game of Pig.\n\n'''\n\nfrom random import randint\nfrom collections import namedtuple\nimport random\nfrom pprint import pprint as pp\nfrom collections import Counter\n\n\nplayercount = 2\nmaxscore = 100\nmaxgames = 100000\n\n\nGame = namedtuple('Game', 'players, maxscore, rounds')\nRound = namedtuple('Round', 'who, start, scores, safe')\n\n\nclass Player():\n def __init__(self, player_index):\n self.player_index = player_index\n\n def __repr__(self):\n return '%s(%i)' % (self.__class__.__name__, self.player_index)\n\n def __call__(self, safescore, scores, game):\n 'Returns boolean True to roll again'\n pass\n\nclass RandPlay(Player):\n def __call__(self, safe, scores, game):\n 'Returns random boolean choice of whether to roll again'\n return bool(random.randint(0, 1))\n\nclass RollTo20(Player):\n def __call__(self, safe, scores, game):\n 'Roll again if this rounds score < 20'\n return (((sum(scores) + safe[self.player_index]) < maxscore) # Haven't won yet\n and(sum(scores) < 20)) # Not at 20 this round\n\nclass Desparat(Player):\n def __call__(self, safe, scores, game):\n 'Roll again if this rounds score < 20 or someone is within 20 of winning'\n return (((sum(scores) + safe[self.player_index]) < maxscore) # Haven't won yet\n and( (sum(scores) < 20) # Not at 20 this round\n or max(safe) >= (maxscore - 20))) # Someone's close\n\n\ndef game__str__(self):\n 'Pretty printer for Game class'\n return (\"Game(players=%r, maxscore=%i,\\n rounds=[\\n %s\\n ])\"\n % (self.players, self.maxscore,\n ',\\n '.join(repr(round) for round in self.rounds)))\nGame.__str__ = game__str__\n\n\ndef winningorder(players, safescores):\n 'Return (players in winning order, their scores)'\n return tuple(zip(*sorted(zip(players, safescores),\n key=lambda x: x[1], reverse=True)))\n\ndef playpig(game):\n '''\n Plays the game of pig returning the players in winning order\n and their scores whilst updating argument game with the details of play.\n '''\n players, maxscore, rounds = game\n playercount = len(players)\n safescore = [0] * playercount # Safe scores for each player\n player = 0 # Who plays this round\n scores=[] # Individual scores this round\n\n while max(safescore) < maxscore:\n startscore = safescore[player]\n rolling = players[player](safescore, scores, game)\n if rolling:\n rolled = randint(1, 6)\n scores.append(rolled)\n if rolled == 1:\n # Bust! \n round = Round(who=players[player],\n start=startscore,\n scores=scores,\n safe=safescore[player])\n rounds.append(round)\n scores, player = [], (player + 1) % playercount\n else:\n # Stick\n safescore[player] += sum(scores)\n round = Round(who=players[player],\n start=startscore,\n scores=scores,\n safe=safescore[player])\n rounds.append(round)\n if safescore[player] >= maxscore:\n break\n scores, player = [], (player + 1) % playercount\n\n # return players in winning order and all scores\n return winningorder(players, safescore)\n\nif __name__ == '__main__':\n game = Game(players=tuple(RandPlay(i) for i in range(playercount)),\n maxscore=20,\n rounds=[])\n print('ONE GAME')\n print('Winning order: %r; Respective scores: %r\\n' % playpig(game))\n print(game)\n game = Game(players=tuple(RandPlay(i) for i in range(playercount)),\n maxscore=maxscore,\n rounds=[])\n algos = (RollTo20, RandPlay, Desparat)\n print('\\n\\nMULTIPLE STATISTICS using %r\\n for %i GAMES'\n % (', '.join(p.__name__ for p in algos), maxgames,))\n winners = Counter(repr(playpig(game._replace(players=tuple(random.choice(algos)(i)\n for i in range(playercount)),\n rounds=[]))[0])\n for i in range(maxgames))\n print(' Players(position) winning on left; occurrences on right:\\n %s'\n % ',\\n '.join(str(w) for w in winners.most_common()))"} +{"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* [http://lodev.org/cgtutor/plasma.html Computer Graphics Tutorial (lodev.org)]\n* [http://www.bidouille.org/prog/plasma Plasma (bidouille.org)]\n\n", "solution": "\n#include\n#include\n#include\n#include\n#include\n\n#define pi M_PI\n\nint main()\n{\n\tCONSOLE_SCREEN_BUFFER_INFO info;\n int cols, rows;\n\ttime_t t;\n\tint i,j;\n\n GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);\n cols = info.srWindow.Right - info.srWindow.Left + 1;\n rows = info.srWindow.Bottom - info.srWindow.Top + 1;\n\t\n\tHANDLE console;\n\t\n\tconsole = GetStdHandle(STD_OUTPUT_HANDLE);\n\t\n\tsystem(\"@clear||cls\");\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tfor(i=0;i\n\n===Graphics version===\nAnd here's the Graphics version, requires the [http://www.cs.colorado.edu/~main/bgi/cs1300/ WinBGIm] library. Prints out usage on incorrect invocation.\n\n#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\n"} +{"title": "Plasma effect", "language": "Python", "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* [http://lodev.org/cgtutor/plasma.html Computer Graphics Tutorial (lodev.org)]\n* [http://www.bidouille.org/prog/plasma Plasma (bidouille.org)]\n\n", "solution": "import math\nimport colorsys\nfrom PIL import Image\n\ndef plasma (w, h):\n\tout = Image.new(\"RGB\", (w, h))\n\tpix = out.load()\n\tfor x in range (w):\n\t\tfor y in range(h):\n\t\t\thue = 4.0 + math.sin(x / 19.0) + math.sin(y / 9.0) \\\n\t\t\t\t+ math.sin((x + y) / 25.0) + math.sin(math.sqrt(x**2.0 + y**2.0) / 8.0)\n\t\t\thsv = colorsys.hsv_to_rgb(hue/8.0, 1, 1)\n\t\t\tpix[x, y] = tuple([int(round(c * 255.0)) for c in hsv])\n\treturn out\n\nif __name__==\"__main__\":\n\tim = plasma(400, 400)\n\tim.show()"} +{"title": "Playfair cipher", "language": "Python", "task": ";Task:\nImplement a Playfair cipher for encryption and decryption.\n\n\nThe user must be able to choose \u00a0 '''J''' \u00a0=\u00a0 '''I''' \u00a0 \u00a0 or \u00a0 no \u00a0 '''Q''' \u00a0 in the alphabet.\n\nThe output of the encrypted and decrypted message must be in capitalized digraphs, separated by spaces.\n\n\n;Output example:\n HI DE TH EG OL DI NT HE TR EX ES TU MP\n\n", "solution": "from string import ascii_uppercase\nfrom itertools import product\nfrom re import findall\n\ndef uniq(seq):\n seen = {}\n return [seen.setdefault(x, x) for x in seq if x not in seen]\n\ndef partition(seq, n):\n return [seq[i : i + n] for i in xrange(0, len(seq), n)]\n\n\n\"\"\"Instantiate a specific encoder/decoder.\"\"\"\ndef playfair(key, from_ = 'J', to = None):\n if to is None:\n to = 'I' if from_ == 'J' else ''\n\n def canonicalize(s):\n return filter(str.isupper, s.upper()).replace(from_, to)\n\n # Build 5x5 matrix.\n m = partition(uniq(canonicalize(key + ascii_uppercase)), 5)\n\n # Pregenerate all forward translations.\n enc = {}\n\n # Map pairs in same row.\n for row in m:\n for i, j in product(xrange(5), repeat=2):\n if i != j:\n enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5]\n\n # Map pairs in same column.\n for c in zip(*m):\n for i, j in product(xrange(5), repeat=2):\n if i != j:\n enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5]\n\n # Map pairs with cross-connections.\n for i1, j1, i2, j2 in product(xrange(5), repeat=4):\n if i1 != i2 and j1 != j2:\n enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1]\n\n # Generate reverse translations.\n dec = dict((v, k) for k, v in enc.iteritems())\n\n def sub_enc(txt):\n lst = findall(r\"(.)(?:(?!\\1)(.))?\", canonicalize(txt))\n return \" \".join(enc[a + (b if b else 'X')] for a, b in lst)\n\n def sub_dec(encoded):\n return \" \".join(dec[p] for p in partition(canonicalize(encoded), 2))\n\n return sub_enc, sub_dec\n\n\n(encode, decode) = playfair(\"Playfair example\")\norig = \"Hide the gold in...the TREESTUMP!!!\"\nprint \"Original:\", orig\nenc = encode(orig)\nprint \"Encoded:\", enc\nprint \"Decoded:\", decode(enc)"} +{"title": "Plot coordinate pairs", "language": "C", "task": ";Task:\nPlot a function represented as \u00a0\u00a0 x,\u00a0 y \u00a0\u00a0 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": "#include \n#include \n#include \n\n#define N 40\ndouble x[N], y[N];\n\nvoid minmax(double x[], int len, double *base, double *step, int *nstep)\n{\n\tint i;\n\tdouble diff, minv, maxv;\n\t*step = 1;\n\n\tminv = maxv = x[0];\n\tfor (i = 1; i < len; i++) {\n\t\tif (minv > x[i]) minv = x[i];\n\t\tif (maxv < x[i]) maxv = x[i];\n\t}\n\tif (minv == maxv) {\n\t\tminv = floor(minv);\n\t\tmaxv = ceil(maxv);\n\t\tif (minv == maxv) {\n\t\t\tminv--;\n\t\t\tmaxv++;\n\t\t}\n\t} else {\n\t\tdiff = maxv - minv;\n\t\twhile (*step < diff) *step *= 10;\n\t\twhile (*step > diff)\t *step /= 10;\n\t\tif (*step > diff / 2)\t *step /= 5;\n\t\telse if (*step > diff / 5) *step /= 2;\n\t}\n\n\t*base = floor(minv / *step) * *step;\n\t*nstep = ceil(maxv / *step) - floor(minv / *step);\n}\n\n/* writes an eps with 400 x 300 dimention, using 12 pt font */\n#define CHARH 12\n#define CHARW 6\n#define DIMX 398\n#define DIMY (300 - CHARH)\n#define BOTY 20.\nint plot(double x[], double y[], int len, char *spec)\n{\n\tint nx, ny, i;\n\tdouble sx, sy, x0, y0;\n\tchar buf[100];\n\tint dx, dy, lx, ly;\n\tdouble ofs_x, ofs_y, grid_x;\n\n\tminmax(x, len, &x0, &sx, &nx);\n\tminmax(y, len, &y0, &sy, &ny);\n\n\tdx = -log10(sx);\n\tdy = -log10(sy);\n\n\tly = 0;\n\tfor (i = 0; i <= ny; i++) {\n\t\tsprintf(buf, \"%g\\n\", y0 + i * sy);\n\t\tif (strlen(buf) > ly) ly = strlen(buf);\n\t}\n\tofs_x = ly * CHARW;\n\n\tprintf(\"%%!PS-Adobe-3.0\\n%%%%BoundingBox: 0 0 400 300\\n\"\n\t\t\"/TimesRoman findfont %d scalefont setfont\\n\"\n\t\t\"/rl{rlineto}def /l{lineto}def /s{setrgbcolor}def \"\n\t\t\"/rm{rmoveto}def /m{moveto}def /st{stroke}def\\n\",\n\t\tCHARH);\n\tfor (i = 0; i <= ny; i++) {\n\t\tofs_y = BOTY + (DIMY - BOTY) / ny * i;\n\t\tprintf(\"0 %g m (%*.*f) show\\n\",\n\t\t\tofs_y - 4, ly, dy, y0 + i * sy);\n\t\tif (i) printf(\"%g %g m 7 0 rl st\\n\",\n\t\t\tofs_x, ofs_y);\n\t}\n\tprintf(\"%g %g m %g %g l st\\n\", ofs_x, BOTY, ofs_x, ofs_y);\n\n\tfor (i = 0; i <= nx; i++) {\n\t\tsprintf(buf, \"%g\", x0 + i * sx);\n\t\tlx = strlen(buf);\n\t\tgrid_x = ofs_x + (DIMX - ofs_x) / nx * i;\n\n\t\tprintf(\"%g %g m (%s) show\\n\", grid_x - CHARW * lx / 2,\n\t\t\tBOTY - 12, buf);\n\t\tif (i) printf(\"%g %g m 0 7 rl st\\n\", grid_x, BOTY);\n\t}\n\tprintf(\"%g %g m %g %g l st\\n\", ofs_x, BOTY, grid_x, BOTY);\n\t\t\n\tif (strchr(spec, 'r'))\t\tprintf(\"1 0 0 s\\n\");\n\telse if (strchr(spec, 'b'))\tprintf(\"0 0 1 s\\n\");\n\telse if (strchr(spec, 'g'))\tprintf(\"0 1 0 s\\n\");\n\telse if (strchr(spec, 'm'))\tprintf(\"1 0 1 s\\n\");\n\n\tif (strchr(spec, 'o'))\n\t\tprintf(\"/o { m 0 3 rm 3 -3 rl -3 -3 rl -3 3 rl closepath st} def \"\n\t\t\t\".5 setlinewidth\\n\");\n\n\tif (strchr(spec, '-')) {\n\t\tfor (i = 0; i < len; i++) {\n\t\t\tprintf(\"%g %g %s \",\n\t\t\t\t(x[i] - x0) / (sx * nx) * (DIMX - ofs_x) + ofs_x,\n\t\t\t\t(y[i] - y0) / (sy * ny) * (DIMY - BOTY) + BOTY,\n\t\t\t\ti ? \"l\" : \"m\");\n\t\t}\n\t\tprintf(\"st\\n\");\n\t}\n\n\tif (strchr(spec, 'o'))\n\t\tfor (i = 0; i < len; i++) {\n\t\t\tprintf(\"%g %g o \",\n\t\t\t\t(x[i] - x0) / (sx * nx) * (DIMX - ofs_x) + ofs_x,\n\t\t\t\t(y[i] - y0) / (sy * ny) * (DIMY - BOTY) + BOTY);\n\t\t}\n\n\tprintf(\"showpage\\n%%EOF\");\n\t\n\treturn 0;\n}\n\nint main()\n{\n\tint i;\n\tfor (i = 0; i < N; i++) {\n\t\tx[i] = (double)i / N * 3.14159 * 6;\n\t\ty[i] = -1337 + (exp(x[i] / 10) + cos(x[i])) / 100;\n\t}\n\t/* string parts: any of \"rgbm\": color; \"-\": draw line; \"o\": draw symbol */\n\tplot(x, y, N, \"r-o\");\n\treturn 0;\n}"} +{"title": "Plot coordinate pairs", "language": "Python", "task": ";Task:\nPlot a function represented as \u00a0\u00a0 x,\u00a0 y \u00a0\u00a0 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": "\nfrom visual import *\nfrom visual.graph import *\n\nplot1 = gdisplay( title='VPython Plot-Demo', \n xtitle='x',\n ytitle='y (click and drag mouse to see coordinates)',\n foreground=color.black,\n background=color.white, \n x=0, y=0,\n width=400, height=400,\n xmin=0, xmax=10, \n ymin=0, ymax=200 )\n\nf1 = gdots(color=color.red) # create plot-object\n\nf1.plot(pos= (0, 2.7), color=color.blue ) # add a single point\nf1.plot(pos=[(1, 2.8), # add a list of points\n (2, 31.4),\n (3, 38.1), \n (4, 58.0),\n (5, 76.2),\n (6, 100.5),\n (7, 130.0),\n (8, 149.3),\n (9, 180.0) ]\n )\nlabel(display=plot1.display, text=\"Look here\",\n pos=(6,100.5), xoffset=30,yoffset=-20 )\n"} +{"title": "Poker hand analyser", "language": "C", "task": "[[Category:Cards]] \n[[Category:Games]]\n\n;Task:\nCreate a program to parse a single five card poker hand and rank it according to this list of poker hands.\n\n\nA poker hand is specified as a space separated list of five playing cards. \n\nEach input card has two characters indicating face and suit. \n\n\n;Example:\n::::'''2d''' \u00a0 \u00a0 \u00a0 (two of diamonds).\n\n\n\nFaces are: \u00a0\u00a0 '''a''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''10''', '''j''', '''q''', '''k'''\n\nSuits are: \u00a0\u00a0 '''h''' (hearts), \u00a0 '''d''' (diamonds), \u00a0 '''c''' (clubs), \u00a0 and \u00a0 '''s''' (spades), \u00a0 or \nalternatively, \u00a0 the unicode card-suit characters: \u00a0\u00a0 \u2665 \u2666 \u2663 \u2660 \n\n\nDuplicate cards are illegal.\n\nThe program should analyze a single hand and produce one of the following outputs:\n straight-flush\n four-of-a-kind\n full-house\n flush\n straight\n three-of-a-kind\n two-pair\n one-pair\n high-card\n invalid\n\n\n;Examples:\n 2\u2665 2\u2666 2\u2663 k\u2663 q\u2666: three-of-a-kind\n 2\u2665 5\u2665 7\u2666 8\u2663 9\u2660: high-card\n a\u2665 2\u2666 3\u2663 4\u2663 5\u2666: straight\n 2\u2665 3\u2665 2\u2666 3\u2663 3\u2666: full-house\n 2\u2665 7\u2665 2\u2666 3\u2663 3\u2666: two-pair\n 2\u2665 7\u2665 7\u2666 7\u2663 7\u2660: four-of-a-kind \n 10\u2665 j\u2665 q\u2665 k\u2665 a\u2665: straight-flush\n 4\u2665 4\u2660 k\u2660 5\u2666 10\u2660: one-pair\n q\u2663 10\u2663 7\u2663 6\u2663 q\u2663: invalid\n\nThe programs output for the above examples should be displayed here on this page.\n\n\n;Extra credit:\n# use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE).\n# allow two jokers\n::* use the symbol \u00a0 '''joker'''\n::* duplicates would be allowed (for jokers only)\n::* five-of-a-kind would then be the highest hand\n\n\n;More extra credit examples:\n joker 2\u2666 2\u2660 k\u2660 q\u2666: three-of-a-kind\n joker 5\u2665 7\u2666 8\u2660 9\u2666: straight\n joker 2\u2666 3\u2660 4\u2660 5\u2660: straight\n joker 3\u2665 2\u2666 3\u2660 3\u2666: four-of-a-kind\n joker 7\u2665 2\u2666 3\u2660 3\u2666: three-of-a-kind\n joker 7\u2665 7\u2666 7\u2660 7\u2663: five-of-a-kind\n joker j\u2665 q\u2665 k\u2665 A\u2665: straight-flush\n joker 4\u2663 k\u2663 5\u2666 10\u2660: one-pair\n joker k\u2663 7\u2663 6\u2663 4\u2663: flush\n joker 2\u2666 joker 4\u2660 5\u2660: straight\n joker Q\u2666 joker A\u2660 10\u2660: straight\n joker Q\u2666 joker A\u2666 10\u2666: straight-flush\n joker 2\u2666 2\u2660 joker q\u2666: four-of-a-kind\n\n\n;Related tasks:\n* [[Playing cards]]\n* [[Card shuffles]]\n* [[Deal cards_for_FreeCell]]\n* [[War Card_Game]]\n* [[Go Fish]]\n\n", "solution": "#include \n#include \n#include \n#include \n\n#define TRUE 1\n#define FALSE 0\n\n#define FACES \"23456789tjqka\"\n#define SUITS \"shdc\"\n\ntypedef int bool;\n\ntypedef struct {\n int face; /* FACES map to 0..12 respectively */\n char suit;\n} card;\n\ncard cards[5];\n\nint compare_card(const void *a, const void *b) {\n card c1 = *(card *)a;\n card c2 = *(card *)b;\n return c1.face - c2.face;\n}\n\nbool equals_card(card c1, card c2) {\n if (c1.face == c2.face && c1.suit == c2.suit) return TRUE;\n return FALSE;\n}\n\nbool are_distinct() {\n int i, j;\n for (i = 0; i < 4; ++i)\n for (j = i + 1; j < 5; ++j)\n if (equals_card(cards[i], cards[j])) return FALSE;\n return TRUE;\n}\n\nbool is_straight() {\n int i;\n qsort(cards, 5, sizeof(card), compare_card);\n if (cards[0].face + 4 == cards[4].face) return TRUE;\n if (cards[4].face == 12 && cards[0].face == 0 &&\n cards[3].face == 3) return TRUE;\n return FALSE;\n}\n\nbool is_flush() {\n int i;\n char suit = cards[0].suit;\n for (i = 1; i < 5; ++i) if (cards[i].suit != suit) return FALSE;\n return TRUE;\n}\n\nconst char *analyze_hand(const char *hand) {\n int i, j, gs = 0;\n char suit, *cp;\n bool found, flush, straight;\n int groups[13];\n if (strlen(hand) != 14) return \"invalid\";\n for (i = 0; i < 14; i += 3) {\n cp = strchr(FACES, tolower(hand[i]));\n if (cp == NULL) return \"invalid\";\n j = i / 3;\n cards[j].face = cp - FACES;\n suit = tolower(hand[i + 1]);\n cp = strchr(SUITS, suit);\n if (cp == NULL) return \"invalid\";\n cards[j].suit = suit;\n }\n if (!are_distinct()) return \"invalid\";\n for (i = 0; i < 13; ++i) groups[i] = 0;\n for (i = 0; i < 5; ++i) groups[cards[i].face]++;\n for (i = 0; i < 13; ++i) if (groups[i] > 0) gs++;\n switch(gs) {\n case 2:\n found = FALSE;\n for (i = 0; i < 13; ++i) if (groups[i] == 4) {\n found = TRUE;\n break;\n }\n if (found) return \"four-of-a-kind\";\n return \"full-house\";\n case 3:\n found = FALSE;\n for (i = 0; i < 13; ++i) if (groups[i] == 3) {\n found = TRUE;\n break;\n }\n if (found) return \"three-of-a-kind\";\n return \"two-pairs\";\n case 4:\n return \"one-pair\";\n default:\n flush = is_flush();\n straight = is_straight();\n if (flush && straight)\n return \"straight-flush\";\n else if (flush)\n return \"flush\";\n else if (straight)\n return \"straight\";\n else\n return \"high-card\";\n }\n}\n\nint main(){\n int i;\n const char *type;\n const char *hands[10] = {\n \"2h 2d 2c kc qd\",\n \"2h 5h 7d 8c 9s\",\n \"ah 2d 3c 4c 5d\",\n \"2h 3h 2d 3c 3d\",\n \"2h 7h 2d 3c 3d\",\n \"2h 7h 7d 7c 7s\",\n \"th jh qh kh ah\",\n \"4h 4s ks 5d ts\",\n \"qc tc 7c 6c 4c\",\n \"ah ah 7c 6c 4c\"\n };\n for (i = 0; i < 10; ++i) {\n type = analyze_hand(hands[i]);\n printf(\"%s: %s\\n\", hands[i], type);\n }\n return 0;\n}"} +{"title": "Poker hand analyser", "language": "JavaScript ECMAScript 6", "task": "[[Category:Cards]] \n[[Category:Games]]\n\n;Task:\nCreate a program to parse a single five card poker hand and rank it according to this list of poker hands.\n\n\nA poker hand is specified as a space separated list of five playing cards. \n\nEach input card has two characters indicating face and suit. \n\n\n;Example:\n::::'''2d''' \u00a0 \u00a0 \u00a0 (two of diamonds).\n\n\n\nFaces are: \u00a0\u00a0 '''a''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''10''', '''j''', '''q''', '''k'''\n\nSuits are: \u00a0\u00a0 '''h''' (hearts), \u00a0 '''d''' (diamonds), \u00a0 '''c''' (clubs), \u00a0 and \u00a0 '''s''' (spades), \u00a0 or \nalternatively, \u00a0 the unicode card-suit characters: \u00a0\u00a0 \u2665 \u2666 \u2663 \u2660 \n\n\nDuplicate cards are illegal.\n\nThe program should analyze a single hand and produce one of the following outputs:\n straight-flush\n four-of-a-kind\n full-house\n flush\n straight\n three-of-a-kind\n two-pair\n one-pair\n high-card\n invalid\n\n\n;Examples:\n 2\u2665 2\u2666 2\u2663 k\u2663 q\u2666: three-of-a-kind\n 2\u2665 5\u2665 7\u2666 8\u2663 9\u2660: high-card\n a\u2665 2\u2666 3\u2663 4\u2663 5\u2666: straight\n 2\u2665 3\u2665 2\u2666 3\u2663 3\u2666: full-house\n 2\u2665 7\u2665 2\u2666 3\u2663 3\u2666: two-pair\n 2\u2665 7\u2665 7\u2666 7\u2663 7\u2660: four-of-a-kind \n 10\u2665 j\u2665 q\u2665 k\u2665 a\u2665: straight-flush\n 4\u2665 4\u2660 k\u2660 5\u2666 10\u2660: one-pair\n q\u2663 10\u2663 7\u2663 6\u2663 q\u2663: invalid\n\nThe programs output for the above examples should be displayed here on this page.\n\n\n;Extra credit:\n# use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE).\n# allow two jokers\n::* use the symbol \u00a0 '''joker'''\n::* duplicates would be allowed (for jokers only)\n::* five-of-a-kind would then be the highest hand\n\n\n;More extra credit examples:\n joker 2\u2666 2\u2660 k\u2660 q\u2666: three-of-a-kind\n joker 5\u2665 7\u2666 8\u2660 9\u2666: straight\n joker 2\u2666 3\u2660 4\u2660 5\u2660: straight\n joker 3\u2665 2\u2666 3\u2660 3\u2666: four-of-a-kind\n joker 7\u2665 2\u2666 3\u2660 3\u2666: three-of-a-kind\n joker 7\u2665 7\u2666 7\u2660 7\u2663: five-of-a-kind\n joker j\u2665 q\u2665 k\u2665 A\u2665: straight-flush\n joker 4\u2663 k\u2663 5\u2666 10\u2660: one-pair\n joker k\u2663 7\u2663 6\u2663 4\u2663: flush\n joker 2\u2666 joker 4\u2660 5\u2660: straight\n joker Q\u2666 joker A\u2660 10\u2660: straight\n joker Q\u2666 joker A\u2666 10\u2666: straight-flush\n joker 2\u2666 2\u2660 joker q\u2666: four-of-a-kind\n\n\n;Related tasks:\n* [[Playing cards]]\n* [[Card shuffles]]\n* [[Deal cards_for_FreeCell]]\n* [[War Card_Game]]\n* [[Go Fish]]\n\n", "solution": "const FACES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'j', 'q', 'k', 'a'];\nconst SUITS = ['\u2665', '\u2666', '\u2663', '\u2660'];\n\nfunction analyzeHand(hand){\n\tlet cards = hand.split(' ').filter(x => x !== 'joker');\n\tlet jokers = hand.split(' ').length - cards.length;\n\t\n\tlet faces = cards.map( card => FACES.indexOf(card.slice(0,-1)) );\n\tlet suits = cards.map( card => SUITS.indexOf(card.slice(-1)) );\n\t\n\tif( cards.some( (card, i, self) => i !== self.indexOf(card) ) || faces.some(face => face === -1) || suits.some(suit => suit === -1) ) \n\t\treturn 'invalid';\n\t\n\tlet flush = suits.every(suit => suit === suits[0]);\n\tlet groups = FACES.map( (face,i) => faces.filter(j => i === j).length).sort( (x, y) => y - x );\n\tlet shifted = faces.map(x => (x + 1) % 13);\n\tlet distance = Math.min( Math.max(...faces) - Math.min(...faces), Math.max(...shifted) - Math.min(...shifted));\n\tlet straight = groups[0] === 1 && distance < 5;\n\tgroups[0] += jokers;\n\t\n\tif (groups[0] === 5) return 'five-of-a-kind'\n\telse if (straight && flush) return 'straight-flush'\n\telse if (groups[0] === 4) return 'four-of-a-kind'\n\telse if (groups[0] === 3 && groups[1] === 2) return 'full-house'\n\telse if (flush) return 'flush'\n\telse if (straight) return 'straight'\n\telse if (groups[0] === 3) return 'three-of-a-kind'\n\telse if (groups[0] === 2 && groups[1] === 2) return 'two-pair'\n\telse if (groups[0] === 2) return 'one-pair'\n\telse return 'high-card';\n}"} +{"title": "Poker hand analyser", "language": "Python", "task": "[[Category:Cards]] \n[[Category:Games]]\n\n;Task:\nCreate a program to parse a single five card poker hand and rank it according to this list of poker hands.\n\n\nA poker hand is specified as a space separated list of five playing cards. \n\nEach input card has two characters indicating face and suit. \n\n\n;Example:\n::::'''2d''' \u00a0 \u00a0 \u00a0 (two of diamonds).\n\n\n\nFaces are: \u00a0\u00a0 '''a''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''10''', '''j''', '''q''', '''k'''\n\nSuits are: \u00a0\u00a0 '''h''' (hearts), \u00a0 '''d''' (diamonds), \u00a0 '''c''' (clubs), \u00a0 and \u00a0 '''s''' (spades), \u00a0 or \nalternatively, \u00a0 the unicode card-suit characters: \u00a0\u00a0 \u2665 \u2666 \u2663 \u2660 \n\n\nDuplicate cards are illegal.\n\nThe program should analyze a single hand and produce one of the following outputs:\n straight-flush\n four-of-a-kind\n full-house\n flush\n straight\n three-of-a-kind\n two-pair\n one-pair\n high-card\n invalid\n\n\n;Examples:\n 2\u2665 2\u2666 2\u2663 k\u2663 q\u2666: three-of-a-kind\n 2\u2665 5\u2665 7\u2666 8\u2663 9\u2660: high-card\n a\u2665 2\u2666 3\u2663 4\u2663 5\u2666: straight\n 2\u2665 3\u2665 2\u2666 3\u2663 3\u2666: full-house\n 2\u2665 7\u2665 2\u2666 3\u2663 3\u2666: two-pair\n 2\u2665 7\u2665 7\u2666 7\u2663 7\u2660: four-of-a-kind \n 10\u2665 j\u2665 q\u2665 k\u2665 a\u2665: straight-flush\n 4\u2665 4\u2660 k\u2660 5\u2666 10\u2660: one-pair\n q\u2663 10\u2663 7\u2663 6\u2663 q\u2663: invalid\n\nThe programs output for the above examples should be displayed here on this page.\n\n\n;Extra credit:\n# use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE).\n# allow two jokers\n::* use the symbol \u00a0 '''joker'''\n::* duplicates would be allowed (for jokers only)\n::* five-of-a-kind would then be the highest hand\n\n\n;More extra credit examples:\n joker 2\u2666 2\u2660 k\u2660 q\u2666: three-of-a-kind\n joker 5\u2665 7\u2666 8\u2660 9\u2666: straight\n joker 2\u2666 3\u2660 4\u2660 5\u2660: straight\n joker 3\u2665 2\u2666 3\u2660 3\u2666: four-of-a-kind\n joker 7\u2665 2\u2666 3\u2660 3\u2666: three-of-a-kind\n joker 7\u2665 7\u2666 7\u2660 7\u2663: five-of-a-kind\n joker j\u2665 q\u2665 k\u2665 A\u2665: straight-flush\n joker 4\u2663 k\u2663 5\u2666 10\u2660: one-pair\n joker k\u2663 7\u2663 6\u2663 4\u2663: flush\n joker 2\u2666 joker 4\u2660 5\u2660: straight\n joker Q\u2666 joker A\u2660 10\u2660: straight\n joker Q\u2666 joker A\u2666 10\u2666: straight-flush\n joker 2\u2666 2\u2660 joker q\u2666: four-of-a-kind\n\n\n;Related tasks:\n* [[Playing cards]]\n* [[Card shuffles]]\n* [[Deal cards_for_FreeCell]]\n* [[War Card_Game]]\n* [[Go Fish]]\n\n", "solution": "from collections import namedtuple\n\nclass Card(namedtuple('Card', 'face, suit')):\n def __repr__(self):\n return ''.join(self)\n\n\nsuit = '\u2665 \u2666 \u2663 \u2660'.split()\n# ordered strings of faces\nfaces = '2 3 4 5 6 7 8 9 10 j q k a'\nlowaces = 'a 2 3 4 5 6 7 8 9 10 j q k'\n# faces as lists\nface = faces.split()\nlowace = lowaces.split()\n\n\ndef straightflush(hand):\n f,fs = ( (lowace, lowaces) if any(card.face == '2' for card in hand)\n else (face, faces) )\n ordered = sorted(hand, key=lambda card: (f.index(card.face), card.suit))\n first, rest = ordered[0], ordered[1:]\n if ( all(card.suit == first.suit for card in rest) and\n ' '.join(card.face for card in ordered) in fs ):\n return 'straight-flush', ordered[-1].face\n return False\n\ndef fourofakind(hand):\n allfaces = [f for f,s in hand]\n allftypes = set(allfaces)\n if len(allftypes) != 2:\n return False\n for f in allftypes:\n if allfaces.count(f) == 4:\n allftypes.remove(f)\n return 'four-of-a-kind', [f, allftypes.pop()]\n else:\n return False\n\ndef fullhouse(hand):\n allfaces = [f for f,s in hand]\n allftypes = set(allfaces)\n if len(allftypes) != 2:\n return False\n for f in allftypes:\n if allfaces.count(f) == 3:\n allftypes.remove(f)\n return 'full-house', [f, allftypes.pop()]\n else:\n return False\n\ndef flush(hand):\n allstypes = {s for f, s in hand}\n if len(allstypes) == 1:\n allfaces = [f for f,s in hand]\n return 'flush', sorted(allfaces,\n key=lambda f: face.index(f),\n reverse=True)\n return False\n\ndef straight(hand):\n f,fs = ( (lowace, lowaces) if any(card.face == '2' for card in hand)\n else (face, faces) )\n ordered = sorted(hand, key=lambda card: (f.index(card.face), card.suit))\n first, rest = ordered[0], ordered[1:]\n if ' '.join(card.face for card in ordered) in fs:\n return 'straight', ordered[-1].face\n return False\n\ndef threeofakind(hand):\n allfaces = [f for f,s in hand]\n allftypes = set(allfaces)\n if len(allftypes) <= 2:\n return False\n for f in allftypes:\n if allfaces.count(f) == 3:\n allftypes.remove(f)\n return ('three-of-a-kind', [f] +\n sorted(allftypes,\n key=lambda f: face.index(f),\n reverse=True))\n else:\n return False\n\ndef twopair(hand):\n allfaces = [f for f,s in hand]\n allftypes = set(allfaces)\n pairs = [f for f in allftypes if allfaces.count(f) == 2]\n if len(pairs) != 2:\n return False\n p0, p1 = pairs\n other = [(allftypes - set(pairs)).pop()]\n return 'two-pair', pairs + other if face.index(p0) > face.index(p1) else pairs[::-1] + other\n\ndef onepair(hand):\n allfaces = [f for f,s in hand]\n allftypes = set(allfaces)\n pairs = [f for f in allftypes if allfaces.count(f) == 2]\n if len(pairs) != 1:\n return False\n allftypes.remove(pairs[0])\n return 'one-pair', pairs + sorted(allftypes,\n key=lambda f: face.index(f),\n reverse=True)\n\ndef highcard(hand):\n allfaces = [f for f,s in hand]\n return 'high-card', sorted(allfaces,\n key=lambda f: face.index(f),\n reverse=True)\n\nhandrankorder = (straightflush, fourofakind, fullhouse,\n flush, straight, threeofakind,\n twopair, onepair, highcard)\n \ndef rank(cards):\n hand = handy(cards)\n for ranker in handrankorder:\n rank = ranker(hand)\n if rank:\n break\n assert rank, \"Invalid: Failed to rank cards: %r\" % cards\n return rank\n\ndef handy(cards='2\u2665 2\u2666 2\u2663 k\u2663 q\u2666'):\n hand = []\n for card in cards.split():\n f, s = card[:-1], card[-1]\n assert f in face, \"Invalid: Don't understand card face %r\" % f\n assert s in suit, \"Invalid: Don't understand card suit %r\" % s\n hand.append(Card(f, s))\n assert len(hand) == 5, \"Invalid: Must be 5 cards in a hand, not %i\" % len(hand)\n assert len(set(hand)) == 5, \"Invalid: All cards in the hand must be unique %r\" % cards\n return hand\n\n\nif __name__ == '__main__':\n hands = [\"2\u2665 2\u2666 2\u2663 k\u2663 q\u2666\",\n \"2\u2665 5\u2665 7\u2666 8\u2663 9\u2660\",\n \"a\u2665 2\u2666 3\u2663 4\u2663 5\u2666\",\n \"2\u2665 3\u2665 2\u2666 3\u2663 3\u2666\",\n \"2\u2665 7\u2665 2\u2666 3\u2663 3\u2666\",\n \"2\u2665 7\u2665 7\u2666 7\u2663 7\u2660\",\n \"10\u2665 j\u2665 q\u2665 k\u2665 a\u2665\"] + [\n \"4\u2665 4\u2660 k\u2660 5\u2666 10\u2660\",\n \"q\u2663 10\u2663 7\u2663 6\u2663 4\u2663\",\n ]\n print(\"%-18s %-15s %s\" % (\"HAND\", \"CATEGORY\", \"TIE-BREAKER\"))\n for cards in hands:\n r = rank(cards)\n print(\"%-18r %-15s %r\" % (cards, r[0], r[1]))"} +{"title": "Polyspiral", "language": "C", "task": "A [http://www.otherwise.com/Jurtle/screenshots_win/assets/DisplayWindow_Full.png 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": "\n#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": "Polyspiral", "language": "JavaScript", "task": "A [http://www.otherwise.com/Jurtle/screenshots_win/assets/DisplayWindow_Full.png 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": "===Version #1 - Plain===\nThis Polyspiral Generator page alows user to enjoy hundreds of polyspirals in different colors.
\nThis is inspired by a discovery made while using the gnuplot. \n(See [[Talk:Polyspiral| Discussion ]] for Polyspiral task.)
\n'''Note:'''\n* Some polyspirals would be degenerated to a single branch of it or even to a single line.
\n* An image uploading is still blocked. But you have a browser!? So, copy/paste/save this page and double click it.\n"} +{"title": "Polyspiral", "language": "Chrome", "task": "A [http://www.otherwise.com/Jurtle/screenshots_win/assets/DisplayWindow_Full.png 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": "\n\n\nPolyspiral Generator\n\n\nColor: \n\nred\ndarkred\ngreen\ndarkgreen\nblue\nnavy\nbrown\nmaroon\nblack\n\u00a0\u00a0\n Direction: \n\u00a0\u00a0\n Range: \n\u00a0\u00a0\n \u00a0\u00a0\n\u00a0\u00a0\u00a0\u00a0Polyspiral\n\n\n\n"} +{"title": "Polyspiral", "language": "Python", "task": "A [http://www.otherwise.com/Jurtle/screenshots_win/assets/DisplayWindow_Full.png 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": "import math\n\nimport pygame\nfrom pygame.locals import *\n\npygame.init()\nscreen = pygame.display.set_mode((1024, 600))\n\npygame.display.set_caption(\"Polyspiral\")\n\nincr = 0\n\nrunning = True\n\nwhile running:\n\tpygame.time.Clock().tick(60)\n\tfor event in pygame.event.get():\n\t\tif event.type==QUIT:\n\t\t\trunning = False\n\t\t\tbreak\n\n\tincr = (incr + 0.05) % 360\n\tx1 = pygame.display.Info().current_w / 2\n\ty1 = pygame.display.Info().current_h / 2\n\tlength = 5\n\tangle = incr\n\n\tscreen.fill((255,255,255))\n\n\tfor i in range(1,151):\n\t\tx2 = x1 + math.cos(angle) * length\n\t\ty2 = y1 + math.sin(angle) * length\n\t\tpygame.draw.line(screen, (255,0,0), (x1, y1), (x2, y2), 1)\n\t\t# pygame.draw.aaline(screen, (255,0,0), (x1, y1), (x2, y2)) # Anti-Aliased\n\t\tx1, y1 = x2, y2\n\t\tlength += 3\n\t\tangle = (angle + incr) % 360\n\n\tpygame.display.flip()\n"} +{"title": "Population count", "language": "GCC", "task": "The \u00a0 ''population count'' \u00a0 is the number of \u00a0 '''1'''s \u00a0 (ones) \u00a0 in the binary representation of a non-negative integer.\n\n''Population count'' \u00a0 is also known as:\n::::* \u00a0 ''pop count''\n::::* \u00a0 ''popcount'' \n::::* \u00a0 ''sideways sum''\n::::* \u00a0 ''bit summation'' \n::::* \u00a0 ''Hamming weight'' \n\n\nFor example, \u00a0 '''5''' \u00a0 (which is \u00a0 '''101''' \u00a0 in binary) \u00a0 has a population count of \u00a0 '''2'''.\n\n\n''[http://mathworld.wolfram.com/EvilNumber.html Evil numbers]'' \u00a0 are non-negative integers that have an \u00a0 ''even'' \u00a0 population count.\n\n''[http://mathworld.wolfram.com/OdiousNumber.html Odious numbers]'' \u00a0 \u00a0 are \u00a0positive integers that have an \u00a0 \u00a0''odd'' \u00a0 population count.\n\n\n;Task:\n* write a function (or routine) to return the population count of a non-negative integer.\n* all computation of the lists below should start with \u00a0 '''0''' \u00a0 (zero indexed).\n:* display the \u00a0 ''pop count'' \u00a0 of the \u00a0 1st \u00a0 thirty powers of \u00a0 '''3''' \u00a0 \u00a0 \u00a0 ('''30''', \u00a0 '''31''', \u00a0 '''32''', \u00a0 '''33''', \u00a0 '''34''', \u00a0 \u2219\u2219\u2219 \u00a0 '''329''').\n:* display the \u00a0 1st \u00a0 thirty \u00a0 \u00a0 ''evil'' \u00a0 \u00a0 numbers.\n:* display the \u00a0 1st \u00a0 thirty \u00a0 ''odious'' \u00a0 numbers.\n* display each list of integers on one line \u00a0 (which may or may not include a title), \u00a0 each set of integers being shown should be properly identified.\n\n\n;See also\n* The On-Line Encyclopedia of Integer Sequences: \u00a0 A000120 population count.\n* The On-Line Encyclopedia of Integer Sequences: \u00a0 A000069 odious numbers.\n* The On-Line Encyclopedia of Integer Sequences: \u00a0 A001969 evil numbers.\n\n", "solution": "#include \n\nint main() {\n {\n unsigned long long n = 1;\n for (int i = 0; i < 30; i++) {\n // __builtin_popcount() for unsigned int\n // __builtin_popcountl() for unsigned long\n // __builtin_popcountll() for unsigned long long\n printf(\"%d \", __builtin_popcountll(n));\n n *= 3;\n }\n printf(\"\\n\");\n }\n\n int od[30];\n int ne = 0, no = 0;\n printf(\"evil : \");\n for (int n = 0; ne+no < 60; n++) {\n if ((__builtin_popcount(n) & 1) == 0) {\n if (ne < 30) {\n\tprintf(\"%d \", n);\n\tne++;\n }\n } else {\n if (no < 30) {\n\tod[no++] = n;\n }\n }\n }\n printf(\"\\n\");\n printf(\"odious: \");\n for (int i = 0; i < 30; i++) {\n printf(\"%d \", od[i]);\n }\n printf(\"\\n\");\n\n return 0;\n}"} +{"title": "Population count", "language": "Python", "task": "The \u00a0 ''population count'' \u00a0 is the number of \u00a0 '''1'''s \u00a0 (ones) \u00a0 in the binary representation of a non-negative integer.\n\n''Population count'' \u00a0 is also known as:\n::::* \u00a0 ''pop count''\n::::* \u00a0 ''popcount'' \n::::* \u00a0 ''sideways sum''\n::::* \u00a0 ''bit summation'' \n::::* \u00a0 ''Hamming weight'' \n\n\nFor example, \u00a0 '''5''' \u00a0 (which is \u00a0 '''101''' \u00a0 in binary) \u00a0 has a population count of \u00a0 '''2'''.\n\n\n''[http://mathworld.wolfram.com/EvilNumber.html Evil numbers]'' \u00a0 are non-negative integers that have an \u00a0 ''even'' \u00a0 population count.\n\n''[http://mathworld.wolfram.com/OdiousNumber.html Odious numbers]'' \u00a0 \u00a0 are \u00a0positive integers that have an \u00a0 \u00a0''odd'' \u00a0 population count.\n\n\n;Task:\n* write a function (or routine) to return the population count of a non-negative integer.\n* all computation of the lists below should start with \u00a0 '''0''' \u00a0 (zero indexed).\n:* display the \u00a0 ''pop count'' \u00a0 of the \u00a0 1st \u00a0 thirty powers of \u00a0 '''3''' \u00a0 \u00a0 \u00a0 ('''30''', \u00a0 '''31''', \u00a0 '''32''', \u00a0 '''33''', \u00a0 '''34''', \u00a0 \u2219\u2219\u2219 \u00a0 '''329''').\n:* display the \u00a0 1st \u00a0 thirty \u00a0 \u00a0 ''evil'' \u00a0 \u00a0 numbers.\n:* display the \u00a0 1st \u00a0 thirty \u00a0 ''odious'' \u00a0 numbers.\n* display each list of integers on one line \u00a0 (which may or may not include a title), \u00a0 each set of integers being shown should be properly identified.\n\n\n;See also\n* The On-Line Encyclopedia of Integer Sequences: \u00a0 A000120 population count.\n* The On-Line Encyclopedia of Integer Sequences: \u00a0 A000069 odious numbers.\n* The On-Line Encyclopedia of Integer Sequences: \u00a0 A001969 evil numbers.\n\n", "solution": ">>> def popcount(n): return bin(n).count(\"1\")\n... \n>>> [popcount(3**i) for i in range(30)]\n[1, 2, 2, 4, 3, 6, 6, 5, 6, 8, 9, 13, 10, 11, 14, 15, 11, 14, 14, 17, 17, 20, 19, 22, 16, 18, 24, 30, 25, 25]\n>>> evil, odious, i = [], [], 0\n>>> while len(evil) < 30 or len(odious) < 30:\n... p = popcount(i)\n... if p % 2: odious.append(i)\n... else: evil.append(i)\n... i += 1\n... \n>>> evil[:30]\n[0, 3, 5, 6, 9, 10, 12, 15, 17, 18, 20, 23, 24, 27, 29, 30, 33, 34, 36, 39, 40, 43, 45, 46, 48, 51, 53, 54, 57, 58]\n>>> odious[:30]\n[1, 2, 4, 7, 8, 11, 13, 14, 16, 19, 21, 22, 25, 26, 28, 31, 32, 35, 37, 38, 41, 42, 44, 47, 49, 50, 52, 55, 56, 59]\n>>> "} +{"title": "Population count", "language": "Python 3", "task": "The \u00a0 ''population count'' \u00a0 is the number of \u00a0 '''1'''s \u00a0 (ones) \u00a0 in the binary representation of a non-negative integer.\n\n''Population count'' \u00a0 is also known as:\n::::* \u00a0 ''pop count''\n::::* \u00a0 ''popcount'' \n::::* \u00a0 ''sideways sum''\n::::* \u00a0 ''bit summation'' \n::::* \u00a0 ''Hamming weight'' \n\n\nFor example, \u00a0 '''5''' \u00a0 (which is \u00a0 '''101''' \u00a0 in binary) \u00a0 has a population count of \u00a0 '''2'''.\n\n\n''[http://mathworld.wolfram.com/EvilNumber.html Evil numbers]'' \u00a0 are non-negative integers that have an \u00a0 ''even'' \u00a0 population count.\n\n''[http://mathworld.wolfram.com/OdiousNumber.html Odious numbers]'' \u00a0 \u00a0 are \u00a0positive integers that have an \u00a0 \u00a0''odd'' \u00a0 population count.\n\n\n;Task:\n* write a function (or routine) to return the population count of a non-negative integer.\n* all computation of the lists below should start with \u00a0 '''0''' \u00a0 (zero indexed).\n:* display the \u00a0 ''pop count'' \u00a0 of the \u00a0 1st \u00a0 thirty powers of \u00a0 '''3''' \u00a0 \u00a0 \u00a0 ('''30''', \u00a0 '''31''', \u00a0 '''32''', \u00a0 '''33''', \u00a0 '''34''', \u00a0 \u2219\u2219\u2219 \u00a0 '''329''').\n:* display the \u00a0 1st \u00a0 thirty \u00a0 \u00a0 ''evil'' \u00a0 \u00a0 numbers.\n:* display the \u00a0 1st \u00a0 thirty \u00a0 ''odious'' \u00a0 numbers.\n* display each list of integers on one line \u00a0 (which may or may not include a title), \u00a0 each set of integers being shown should be properly identified.\n\n\n;See also\n* The On-Line Encyclopedia of Integer Sequences: \u00a0 A000120 population count.\n* The On-Line Encyclopedia of Integer Sequences: \u00a0 A000069 odious numbers.\n* The On-Line Encyclopedia of Integer Sequences: \u00a0 A001969 evil numbers.\n\n", "solution": "'''Population count'''\n\nfrom functools import reduce\n\n\n# popCount :: Int -> Int\ndef popCount(n):\n '''The count of non-zero digits in the binary\n representation of the positive integer n.'''\n def go(x):\n return Just(divmod(x, 2)) if 0 < x else Nothing()\n return sum(unfoldl(go)(n))\n\n\n# -------------------------- TEST --------------------------\ndef main():\n '''Tests'''\n\n print('Population count of first 30 powers of 3:')\n print(' ' + showList(\n [popCount(pow(3, x)) for x in enumFromTo(0)(29)]\n ))\n\n evilNums, odiousNums = partition(\n compose(even, popCount)\n )(enumFromTo(0)(59))\n\n print(\"\\nFirst thirty 'evil' numbers:\")\n print(' ' + showList(evilNums))\n\n print(\"\\nFirst thirty 'odious' numbers:\")\n print(' ' + showList(odiousNums))\n\n\n# ------------------------ GENERIC -------------------------\n\n# Just :: a -> Maybe a\ndef Just(x):\n '''Constructor for an inhabited Maybe (option type) value.\n Wrapper containing the result of a computation.\n '''\n return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n# Nothing :: Maybe a\ndef Nothing():\n '''Constructor for an empty Maybe (option type) value.\n Empty wrapper returned where a computation is not possible.\n '''\n return {'type': 'Maybe', 'Nothing': True}\n\n\n# compose :: ((a -> a), ...) -> (a -> a)\ndef compose(*fs):\n '''Composition, from right to left,\n of a series of functions.\n '''\n def go(f, g):\n def fg(x):\n return f(g(x))\n return fg\n return reduce(go, fs, lambda x: x)\n\n\n# enumFromTo :: Int -> Int -> [Int]\ndef enumFromTo(m):\n '''Enumeration of integer values [m..n]'''\n return lambda n: range(m, 1 + n)\n\n\n# even :: Int -> Bool\ndef even(x):\n '''True if x is an integer\n multiple of two.\n '''\n return 0 == x % 2\n\n\n# partition :: (a -> Bool) -> [a] -> ([a], [a])\ndef partition(p):\n '''The pair of lists of those elements in xs\n which respectively do, and don't\n satisfy the predicate p.\n '''\n\n def go(a, x):\n ts, fs = a\n return (ts + [x], fs) if p(x) else (ts, fs + [x])\n return lambda xs: reduce(go, xs, ([], []))\n\n\n# showList :: [a] -> String\ndef showList(xs):\n '''Stringification of a list.'''\n return '[' + ','.join(repr(x) for x in xs) + ']'\n\n\n# unfoldl(lambda x: Just(((x - 1), x)) if 0 != x else Nothing())(10)\n# -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n# unfoldl :: (b -> Maybe (b, a)) -> b -> [a]\ndef unfoldl(f):\n '''Dual to reduce or foldl.\n Where these reduce a list to a summary value, unfoldl\n builds a list from a seed value.\n Where f returns Just(a, b), a is appended to the list,\n and the residual b is used as the argument for the next\n application of f.\n When f returns Nothing, the completed list is returned.\n '''\n def go(v):\n x, r = v, v\n xs = []\n while True:\n mb = f(x)\n if mb.get('Nothing'):\n return xs\n else:\n x, r = mb.get('Just')\n xs.insert(0, r)\n return xs\n return go\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} +{"title": "Pragmatic directives", "language": "C", "task": "[[Category:Pragmatic directives]]\n\nPragmatic directives cause the language to operate in a specific manner, \u00a0 allowing support for operational variances within the program code \u00a0 (possibly by the loading of specific or alternative modules).\n\n\n;Task:\nList any pragmatic directives supported by the language, \u00a0 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": "\n/*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": "Pragmatic directives", "language": "Python", "task": "[[Category:Pragmatic directives]]\n\nPragmatic directives cause the language to operate in a specific manner, \u00a0 allowing support for operational variances within the program code \u00a0 (possibly by the loading of specific or alternative modules).\n\n\n;Task:\nList any pragmatic directives supported by the language, \u00a0 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": "Python 3.2 (r32:88445, Feb 20 2011, 21:30:00) [MSC v.1500 64 bit (AMD64)] on win32\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> import __future__\n>>> __future__.all_feature_names\n['nested_scopes', 'generators', 'division', 'absolute_import', 'with_statement', 'print_function', 'unicode_literals', 'barry_as_FLUFL']\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": "Prime triangle", "language": "Python", "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": "\n\nfrom numpy import array\n# for Rosetta Code by MG - 20230312\ndef is_prime(n: int) -> bool:\n assert n < 64\n return ((1 << n) & 0x28208a20a08a28ac) != 0\n\ndef prime_triangle_row(a: array, start: int, length: int) -> bool:\n if length == 2:\n return is_prime(a[0] + a[1])\n for i in range(1, length - 1, 1):\n if is_prime(a[start] + a[start + i]):\n a[start + i], a[start + 1] = a[start + 1], a[start + i]\n if prime_triangle_row(a, start + 1, length - 1):\n return True\n a[start + i], a[start + 1] = a[start + 1], a[start + i]\n return False\n\ndef prime_triangle_count(a: array, start: int, length: int) -> int:\n count: int = 0\n if length == 2:\n if is_prime(a[start] + a[start + 1]):\n count += 1\n else:\n for i in range(1, length - 1, 1):\n if is_prime(a[start] + a[start + i]):\n a[start + i], a[start + 1] = a[start + 1], a[start + i]\n count += prime_triangle_count(a, start + 1, length - 1)\n a[start + i], a[start + 1] = a[start + 1], a[start + i]\n return count\n\ndef print_row(a: array):\n if a == []:\n return\n print(\"%2d\"% a[0], end=\" \")\n for x in a[1:]:\n print(\"%2d\"% x, end=\" \")\n print()\n\nfor n in range(2, 21):\n tr: array = [_ for _ in range(1, n + 1)]\n if prime_triangle_row(tr, 0, n):\n print_row(tr)\nprint()\nfor n in range(2, 21):\n tr: array = [_ for _ in range(1, n + 1)]\n if n > 2:\n print(\" \", end=\"\")\n print(prime_triangle_count(tr, 0, n), end=\"\")\nprint()\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. \u00a0 The queue must support at least two operations:\n:# \u00a0 Insertion. \u00a0 An element is added to the queue with a priority (a numeric value).\n:# \u00a0 Top item removal. \u00a0 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 \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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. \u00a0 A typical implementation has \u00a0 '''O(log n)''' \u00a0 insertion and extraction time, \u00a0 where \u00a0 '''n''' \u00a0 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. \u00a0 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": "Priority queue", "language": "Python", "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. \u00a0 The queue must support at least two operations:\n:# \u00a0 Insertion. \u00a0 An element is added to the queue with a priority (a numeric value).\n:# \u00a0 Top item removal. \u00a0 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 \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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. \u00a0 A typical implementation has \u00a0 '''O(log n)''' \u00a0 insertion and extraction time, \u00a0 where \u00a0 '''n''' \u00a0 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. \u00a0 If so, discuss the reasons behind it.\n\n", "solution": ">>> import queue\n>>> help(queue.PriorityQueue)\nHelp on class PriorityQueue in module queue:\n\nclass PriorityQueue(Queue)\n | Variant of Queue that retrieves open entries in priority order (lowest first).\n | \n | Entries are typically tuples of the form: (priority number, data).\n | \n | Method resolution order:\n | PriorityQueue\n | Queue\n | builtins.object\n | \n | Methods inherited from Queue:\n | \n | __init__(self, maxsize=0)\n | \n | empty(self)\n | Return True if the queue is empty, False otherwise (not reliable!).\n | \n | This method is likely to be removed at some point. Use qsize() == 0\n | as a direct substitute, but be aware that either approach risks a race\n | condition where a queue can grow before the result of empty() or\n | qsize() can be used.\n | \n | To create code that needs to wait for all queued tasks to be\n | completed, the preferred technique is to use the join() method.\n | \n | full(self)\n | Return True if the queue is full, False otherwise (not reliable!).\n | \n | This method is likely to be removed at some point. Use qsize() >= n\n | as a direct substitute, but be aware that either approach risks a race\n | condition where a queue can shrink before the result of full() or\n | qsize() can be used.\n | \n | get(self, block=True, timeout=None)\n | Remove and return an item from the queue.\n | \n | If optional args 'block' is true and 'timeout' is None (the default),\n | block if necessary until an item is available. If 'timeout' is\n | a positive number, it blocks at most 'timeout' seconds and raises\n | the Empty exception if no item was available within that time.\n | Otherwise ('block' is false), return an item if one is immediately\n | available, else raise the Empty exception ('timeout' is ignored\n | in that case).\n | \n | get_nowait(self)\n | Remove and return an item from the queue without blocking.\n | \n | Only get an item if one is immediately available. Otherwise\n | raise the Empty exception.\n | \n | join(self)\n | Blocks until all items in the Queue have been gotten and processed.\n | \n | The count of unfinished tasks goes up whenever an item is added to the\n | queue. The count goes down whenever a consumer thread calls task_done()\n | to indicate the item was retrieved and all work on it is complete.\n | \n | When the count of unfinished tasks drops to zero, join() unblocks.\n | \n | put(self, item, block=True, timeout=None)\n | Put an item into the queue.\n | \n | If optional args 'block' is true and 'timeout' is None (the default),\n | block if necessary until a free slot is available. If 'timeout' is\n | a positive number, it blocks at most 'timeout' seconds and raises\n | the Full exception if no free slot was available within that time.\n | Otherwise ('block' is false), put an item on the queue if a free slot\n | is immediately available, else raise the Full exception ('timeout'\n | is ignored in that case).\n | \n | put_nowait(self, item)\n | Put an item into the queue without blocking.\n | \n | Only enqueue the item if a free slot is immediately available.\n | Otherwise raise the Full exception.\n | \n | qsize(self)\n | Return the approximate size of the queue (not reliable!).\n | \n | task_done(self)\n | Indicate that a formerly enqueued task is complete.\n | \n | Used by Queue consumer threads. For each get() used to fetch a task,\n | a subsequent call to task_done() tells the queue that the processing\n | on the task is complete.\n | \n | If a join() is currently blocking, it will resume when all items\n | have been processed (meaning that a task_done() call was received\n | for every item that had been put() into the queue).\n | \n | Raises a ValueError if called more times than there were items\n | placed in the queue.\n | \n | ----------------------------------------------------------------------\n | Data descriptors inherited from Queue:\n | \n | __dict__\n | dictionary for instance variables (if defined)\n | \n | __weakref__\n | list of weak references to the object (if defined)\n\n>>> "} +{"title": "Pseudo-random numbers/Combined recursive generator MRG32k3a", "language": "C", "task": ";[https://www.nag.com/numeric/fl/nagdoc_fl23/pdf/g05/g05intro.pdf 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/Combined recursive generator MRG32k3a", "language": "Python", "task": ";[https://www.nag.com/numeric/fl/nagdoc_fl23/pdf/g05/g05intro.pdf 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": "# Constants\na1 = [0, 1403580, -810728]\nm1 = 2**32 - 209\n#\na2 = [527612, 0, -1370589]\nm2 = 2**32 - 22853\n#\nd = m1 + 1\n\nclass MRG32k3a():\n \n def __init__(self, seed_state=123):\n self.seed(seed_state)\n \n def seed(self, seed_state):\n assert 0 \n"} +{"title": "Pseudo-random numbers/Middle-square method", "language": "C", "task": "; 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/Middle-square method", "language": "Python", "task": "; 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": "seed = 675248\ndef random():\n global seed\n seed = int(str(seed ** 2).zfill(12)[3:9])\n return seed\nfor _ in range(5):\n print(random())\n"} +{"title": "Pseudo-random numbers/PCG32", "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:'''|''' Bitwise or operator\n::https://en.wikipedia.org/wiki/Bitwise_operation#OR\n::Bitwise comparison gives 1 if any of corresponding bits are 1\n:::E.g Binary 00110101 '''|''' Binary 00110011 == Binary 00110111\n\n\n;[https://www.pcg-random.org/download.html#minimal-c-implementation| PCG32] Generator (pseudo-code):\n\nPCG32 has two unsigned 64-bit integers of internal state:\n# '''state''': All 2**64 values may be attained.\n# '''sequence''': Determines which of 2**63 sequences that state iterates through. (Once set together with state at time of seeding will stay constant for this generators lifetime).\n\nValues of sequence allow 2**63 ''different'' sequences of random numbers from the same state.\n\nThe algorithm is given 2 U64 inputs called seed_state, and seed_sequence. The algorithm proceeds in accordance with the following pseudocode:-\n\nconst N<-U64 6364136223846793005\nconst inc<-U64 (seed_sequence << 1) | 1\nstate<-U64 ((inc+seed_state)*N+inc\ndo forever\n xs<-U32 (((state>>18)^state)>>27)\n rot<-INT (state>>59)\n OUTPUT U32 (xs>>rot)|(xs<<((-rot)&31))\n state<-state*N+inc\nend do\n\nNote that this an anamorphism \u2013 dual to catamorphism, and encoded in some languages as a general higher-order `unfold` function, dual to `fold` or `reduce`.\n\n;Task:\n\n* Generate a class/set of functions that generates pseudo-random\nnumbers using the above.\n\n* Show that the first five integers generated with the seed 42, 54\nare: 2707161783 2068313097 3122475824 2211639955 3215226955\n\n \n\n* Show that for an initial seed of 987654321, 1 the counts of 100_000 repetitions of\n\n floor(random_gen.next_float() * 5)\n\n:Is as follows:\n \n 0: 20049, 1: 20022, 2: 20115, 3: 19809, 4: 20005\n\n* Show your output here, on this page.\n\n\n", "solution": "#include \n#include \n#include \n\nconst uint64_t N = 6364136223846793005;\n\nstatic uint64_t state = 0x853c49e6748fea9b;\nstatic uint64_t inc = 0xda3e39cb94b95bdb;\n\nuint32_t pcg32_int() {\n uint64_t old = state;\n state = old * N + inc;\n uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27);\n uint32_t rot = old >> 59;\n return (shifted >> rot) | (shifted << ((~rot + 1) & 31));\n}\n\ndouble pcg32_float() {\n return ((double)pcg32_int()) / (1LL << 32);\n}\n\nvoid pcg32_seed(uint64_t seed_state, uint64_t seed_sequence) {\n state = 0;\n inc = (seed_sequence << 1) | 1;\n pcg32_int();\n state = state + seed_state;\n pcg32_int();\n}\n\nint main() {\n int counts[5] = { 0, 0, 0, 0, 0 };\n int i;\n\n pcg32_seed(42, 54);\n printf(\"%u\\n\", pcg32_int());\n printf(\"%u\\n\", pcg32_int());\n printf(\"%u\\n\", pcg32_int());\n printf(\"%u\\n\", pcg32_int());\n printf(\"%u\\n\", pcg32_int());\n printf(\"\\n\");\n\n pcg32_seed(987654321, 1);\n for (i = 0; i < 100000; i++) {\n int j = (int)floor(pcg32_float() * 5.0);\n counts[j]++;\n }\n\n printf(\"The counts for 100,000 repetitions are:\\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/PCG32", "language": "Python", "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:'''|''' Bitwise or operator\n::https://en.wikipedia.org/wiki/Bitwise_operation#OR\n::Bitwise comparison gives 1 if any of corresponding bits are 1\n:::E.g Binary 00110101 '''|''' Binary 00110011 == Binary 00110111\n\n\n;[https://www.pcg-random.org/download.html#minimal-c-implementation| PCG32] Generator (pseudo-code):\n\nPCG32 has two unsigned 64-bit integers of internal state:\n# '''state''': All 2**64 values may be attained.\n# '''sequence''': Determines which of 2**63 sequences that state iterates through. (Once set together with state at time of seeding will stay constant for this generators lifetime).\n\nValues of sequence allow 2**63 ''different'' sequences of random numbers from the same state.\n\nThe algorithm is given 2 U64 inputs called seed_state, and seed_sequence. The algorithm proceeds in accordance with the following pseudocode:-\n\nconst N<-U64 6364136223846793005\nconst inc<-U64 (seed_sequence << 1) | 1\nstate<-U64 ((inc+seed_state)*N+inc\ndo forever\n xs<-U32 (((state>>18)^state)>>27)\n rot<-INT (state>>59)\n OUTPUT U32 (xs>>rot)|(xs<<((-rot)&31))\n state<-state*N+inc\nend do\n\nNote that this an anamorphism \u2013 dual to catamorphism, and encoded in some languages as a general higher-order `unfold` function, dual to `fold` or `reduce`.\n\n;Task:\n\n* Generate a class/set of functions that generates pseudo-random\nnumbers using the above.\n\n* Show that the first five integers generated with the seed 42, 54\nare: 2707161783 2068313097 3122475824 2211639955 3215226955\n\n \n\n* Show that for an initial seed of 987654321, 1 the counts of 100_000 repetitions of\n\n floor(random_gen.next_float() * 5)\n\n:Is as follows:\n \n 0: 20049, 1: 20022, 2: 20115, 3: 19809, 4: 20005\n\n* Show your output here, on this page.\n\n\n", "solution": "mask64 = (1 << 64) - 1\nmask32 = (1 << 32) - 1\nCONST = 6364136223846793005\n\n\nclass PCG32():\n \n def __init__(self, seed_state=None, seed_sequence=None):\n if all(type(x) == int for x in (seed_state, seed_sequence)):\n self.seed(seed_state, seed_sequence)\n else:\n self.state = self.inc = 0\n \n def seed(self, seed_state, seed_sequence):\n self.state = 0\n self.inc = ((seed_sequence << 1) | 1) & mask64\n self.next_int()\n self.state = (self.state + seed_state)\n self.next_int()\n \n def next_int(self):\n \"return random 32 bit unsigned int\"\n old = self.state\n self.state = ((old * CONST) + self.inc) & mask64\n xorshifted = (((old >> 18) ^ old) >> 27) & mask32\n rot = (old >> 59) & mask32\n answer = (xorshifted >> rot) | (xorshifted << ((-rot) & 31))\n answer = answer &mask32\n \n return answer\n \n def next_float(self):\n \"return random float between 0 and 1\"\n return self.next_int() / (1 << 32)\n \n\nif __name__ == '__main__':\n random_gen = PCG32()\n random_gen.seed(42, 54)\n for i in range(5):\n print(random_gen.next_int())\n \n random_gen.seed(987654321, 1)\n hist = {i:0 for i in range(5)}\n for i in range(100_000):\n hist[int(random_gen.next_float() *5)] += 1\n print(hist)"} +{"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;[https://en.wikipedia.org/wiki/Xorshift#xorshift*| 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": "Pseudo-random numbers/Xorshift star", "language": "Python", "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;[https://en.wikipedia.org/wiki/Xorshift#xorshift*| 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": "mask64 = (1 << 64) - 1\nmask32 = (1 << 32) - 1\nconst = 0x2545F4914F6CDD1D\n\n\n\nclass Xorshift_star():\n \n def __init__(self, seed=0):\n self.state = seed & mask64\n\n def seed(self, num):\n self.state = num & mask64\n \n def next_int(self):\n \"return random int between 0 and 2**32\"\n x = self.state\n x = (x ^ (x >> 12)) & mask64\n x = (x ^ (x << 25)) & mask64\n x = (x ^ (x >> 27)) & mask64\n self.state = x\n answer = (((x * const) & mask64) >> 32) & mask32 \n return answer\n \n def next_float(self):\n \"return random float between 0 and 1\"\n return self.next_int() / (1 << 32)\n \n\nif __name__ == '__main__':\n random_gen = Xorshift_star()\n random_gen.seed(1234567)\n for i in range(5):\n print(random_gen.next_int())\n \n random_gen.seed(987654321)\n hist = {i:0 for i in range(5)}\n for i in range(100_000):\n hist[int(random_gen.next_float() *5)] += 1\n print(hist)"} +{"title": "Pythagoras tree", "language": "C", "task": "right\n\nThe 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": "\n#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": "Pythagoras tree", "language": "Python", "task": "right\n\nThe 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": "from turtle import goto, pu, pd, color, done\n\ndef level(ax, ay, bx, by, depth=0):\n if depth > 0:\n dx,dy = bx-ax, ay-by\n x3,y3 = bx-dy, by-dx\n x4,y4 = ax-dy, ay-dx\n x5,y5 = x4 + (dx - dy)/2, y4 - (dx + dy)/2\n goto(ax, ay), pd()\n for x, y in ((bx, by), (x3, y3), (x4, y4), (ax, ay)):\n goto(x, y)\n pu()\n level(x4,y4, x5,y5, depth - 1)\n level(x5,y5, x3,y3, depth - 1)\n\nif __name__ == '__main__':\n color('red', 'yellow')\n pu()\n level(-100, 500, 100, 500, depth=8)\n done()"} +{"title": "Pythagorean quadruples", "language": "C", "task": "One form of \u00a0 '''Pythagorean quadruples''' \u00a0 is \u00a0 (for positive integers \u00a0 '''a''', \u00a0 '''b''', \u00a0 '''c''', \u00a0 and \u00a0 '''d'''): \n\n\n:::::::: \u00a0 a2 \u00a0 + \u00a0 b2 \u00a0 + \u00a0 c2 \u00a0 \u00a0 = \u00a0 \u00a0 d2 \n\n\nAn example:\n\n:::::::: \u00a0 22 \u00a0 + \u00a0 32 \u00a0 + \u00a0 62 \u00a0 \u00a0 = \u00a0 \u00a0 72 \n\n::::: which is:\n\n:::::::: \u00a0 4 \u00a0\u00a0 + \u00a0 9 \u00a0\u00a0 + \u00a0 36 \u00a0 \u00a0 = \u00a0 \u00a0 49 \n\n\n;Task:\n\nFor positive integers up \u00a0 '''2,200''' \u00a0 (inclusive), \u00a0 for all values of \u00a0 '''a''', \u00a0\n'''b''', \u00a0 '''c''', \u00a0 and \u00a0 '''d''', \nfind \u00a0 (and show here) \u00a0 those values of \u00a0 '''d''' \u00a0 that \u00a0 ''can't'' \u00a0 be represented.\n\nShow the values of \u00a0 '''d''' \u00a0 on one line of output \u00a0 (optionally with a title).\n\n\n;Related tasks:\n* \u00a0 [[Euler's sum of powers conjecture]]. \n* \u00a0 [[Pythagorean triples]].\n\n\n;Reference:\n:* \u00a0 the Wikipedia article: \u00a0 [https://en.wikipedia.org/wiki/Pythagorean_quadruple 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 quadruples", "language": "JavaScript", "task": "One form of \u00a0 '''Pythagorean quadruples''' \u00a0 is \u00a0 (for positive integers \u00a0 '''a''', \u00a0 '''b''', \u00a0 '''c''', \u00a0 and \u00a0 '''d'''): \n\n\n:::::::: \u00a0 a2 \u00a0 + \u00a0 b2 \u00a0 + \u00a0 c2 \u00a0 \u00a0 = \u00a0 \u00a0 d2 \n\n\nAn example:\n\n:::::::: \u00a0 22 \u00a0 + \u00a0 32 \u00a0 + \u00a0 62 \u00a0 \u00a0 = \u00a0 \u00a0 72 \n\n::::: which is:\n\n:::::::: \u00a0 4 \u00a0\u00a0 + \u00a0 9 \u00a0\u00a0 + \u00a0 36 \u00a0 \u00a0 = \u00a0 \u00a0 49 \n\n\n;Task:\n\nFor positive integers up \u00a0 '''2,200''' \u00a0 (inclusive), \u00a0 for all values of \u00a0 '''a''', \u00a0\n'''b''', \u00a0 '''c''', \u00a0 and \u00a0 '''d''', \nfind \u00a0 (and show here) \u00a0 those values of \u00a0 '''d''' \u00a0 that \u00a0 ''can't'' \u00a0 be represented.\n\nShow the values of \u00a0 '''d''' \u00a0 on one line of output \u00a0 (optionally with a title).\n\n\n;Related tasks:\n* \u00a0 [[Euler's sum of powers conjecture]]. \n* \u00a0 [[Pythagorean triples]].\n\n\n;Reference:\n:* \u00a0 the Wikipedia article: \u00a0 [https://en.wikipedia.org/wiki/Pythagorean_quadruple Pythagorean quadruple].\n\n", "solution": "(() => {\n 'use strict';\n\n // main :: IO ()\n const main = () => {\n const xs = takeWhileGen(\n x => 2200 >= x,\n mergeInOrder(\n powersOfTwo(),\n fmapGen(x => 5 * x, powersOfTwo())\n )\n );\n\n return (\n console.log(JSON.stringify(xs)),\n xs\n );\n }\n\n // powersOfTwo :: Gen [Int]\n const powersOfTwo = () =>\n iterate(x => 2 * x, 1);\n\n // mergeInOrder :: Gen [Int] -> Gen [Int] -> Gen [Int]\n const mergeInOrder = (ga, gb) => {\n function* go(ma, mb) {\n let\n a = ma,\n b = mb;\n while (!a.Nothing && !b.Nothing) {\n let\n ta = a.Just,\n tb = b.Just;\n if (fst(ta) < fst(tb)) {\n yield(fst(ta));\n a = uncons(snd(ta))\n } else {\n yield(fst(tb));\n b = uncons(snd(tb))\n }\n }\n }\n return go(uncons(ga), uncons(gb))\n };\n\n\n // GENERIC FUNCTIONS ----------------------------\n\n // fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]\n function* fmapGen(f, gen) {\n const g = gen;\n let v = take(1, g);\n while (0 < v.length) {\n yield(f(v))\n v = take(1, g)\n }\n }\n\n // fst :: (a, b) -> a\n const fst = tpl => tpl[0];\n\n // iterate :: (a -> a) -> a -> Generator [a]\n function* iterate(f, x) {\n let v = x;\n while (true) {\n yield(v);\n v = f(v);\n }\n }\n\n // Just :: a -> Maybe a\n const Just = x => ({\n type: 'Maybe',\n Nothing: false,\n Just: x\n });\n\n // Returns Infinity over objects without finite length\n // this enables zip and zipWith to choose the shorter\n // argument when one is non-finite, like cycle, repeat etc\n\n // length :: [a] -> Int\n const length = xs => xs.length || Infinity;\n\n // Nothing :: Maybe a\n const Nothing = () => ({\n type: 'Maybe',\n Nothing: true,\n });\n\n // snd :: (a, b) -> b\n const snd = tpl => tpl[1];\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = (n, xs) =>\n xs.constructor.constructor.name !== 'GeneratorFunction' ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // takeWhileGen :: (a -> Bool) -> Generator [a] -> [a]\n const takeWhileGen = (p, xs) => {\n const ys = [];\n let\n nxt = xs.next(),\n v = nxt.value;\n while (!nxt.done && p(v)) {\n ys.push(v);\n nxt = xs.next();\n v = nxt.value\n }\n return ys;\n };\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = (a, b) => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // uncons :: [a] -> Maybe (a, [a])\n const uncons = xs => {\n const lng = length(xs);\n return (0 < lng) ? (\n lng < Infinity ? (\n Just(Tuple(xs[0], xs.slice(1))) // Finite list\n ) : (() => {\n const nxt = take(1, xs);\n return 0 < nxt.length ? (\n Just(Tuple(nxt[0], xs))\n ) : Nothing();\n })() // Lazy generator\n ) : Nothing();\n };\n\n // MAIN ---\n return main();\n})();"} +{"title": "Pythagorean quadruples", "language": "Python", "task": "One form of \u00a0 '''Pythagorean quadruples''' \u00a0 is \u00a0 (for positive integers \u00a0 '''a''', \u00a0 '''b''', \u00a0 '''c''', \u00a0 and \u00a0 '''d'''): \n\n\n:::::::: \u00a0 a2 \u00a0 + \u00a0 b2 \u00a0 + \u00a0 c2 \u00a0 \u00a0 = \u00a0 \u00a0 d2 \n\n\nAn example:\n\n:::::::: \u00a0 22 \u00a0 + \u00a0 32 \u00a0 + \u00a0 62 \u00a0 \u00a0 = \u00a0 \u00a0 72 \n\n::::: which is:\n\n:::::::: \u00a0 4 \u00a0\u00a0 + \u00a0 9 \u00a0\u00a0 + \u00a0 36 \u00a0 \u00a0 = \u00a0 \u00a0 49 \n\n\n;Task:\n\nFor positive integers up \u00a0 '''2,200''' \u00a0 (inclusive), \u00a0 for all values of \u00a0 '''a''', \u00a0\n'''b''', \u00a0 '''c''', \u00a0 and \u00a0 '''d''', \nfind \u00a0 (and show here) \u00a0 those values of \u00a0 '''d''' \u00a0 that \u00a0 ''can't'' \u00a0 be represented.\n\nShow the values of \u00a0 '''d''' \u00a0 on one line of output \u00a0 (optionally with a title).\n\n\n;Related tasks:\n* \u00a0 [[Euler's sum of powers conjecture]]. \n* \u00a0 [[Pythagorean triples]].\n\n\n;Reference:\n:* \u00a0 the Wikipedia article: \u00a0 [https://en.wikipedia.org/wiki/Pythagorean_quadruple Pythagorean quadruple].\n\n", "solution": "def quad(top=2200):\n r = [False] * top\n ab = [False] * (top * 2)**2\n for a in range(1, top):\n for b in range(a, top):\n ab[a * a + b * b] = True\n s = 3\n for c in range(1, top):\n s1, s, s2 = s, s + 2, s + 2\n for d in range(c + 1, top):\n if ab[s1]:\n r[d] = True\n s1 += s2\n s2 += 2\n return [i for i, val in enumerate(r) if not val and i]\n \nif __name__ == '__main__':\n n = 2200\n print(f\"Those values of d in 1..{n} that can't be represented: {quad(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). \u00a0 \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. \u00a0 Can your program handle a maximum perimeter of 1,000,000? \u00a0 What about 10,000,000? \u00a0 100,000,000?\n\nNote: the extra credit is not for you to demonstrate how fast your language is compared to others; \u00a0 you need a proper algorithm to solve them in a timely manner.\n\n\n;Related tasks:\n* \u00a0 [[Euler's sum of powers conjecture]] \n* \u00a0 [[List comprehensions]]\n* \u00a0 [[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": "Pythagorean triples", "language": "JavaScript", "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). \u00a0 \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. \u00a0 Can your program handle a maximum perimeter of 1,000,000? \u00a0 What about 10,000,000? \u00a0 100,000,000?\n\nNote: the extra credit is not for you to demonstrate how fast your language is compared to others; \u00a0 you need a proper algorithm to solve them in a timely manner.\n\n\n;Related tasks:\n* \u00a0 [[Euler's sum of powers conjecture]] \n* \u00a0 [[List comprehensions]]\n* \u00a0 [[Pythagorean quadruples]] \n\n", "solution": "(() => {\n \"use strict\";\n\n // Arguments: predicate, maximum perimeter\n // pythTripleCount :: ((Int, Int, Int) -> Bool) -> Int -> Int\n const pythTripleCount = p =>\n maxPerim => {\n const\n xs = enumFromTo(1)(\n Math.floor(maxPerim / 2)\n );\n\n return xs.flatMap(\n x => xs.slice(x).flatMap(\n y => xs.slice(y).flatMap(\n z => ((x + y + z <= maxPerim) &&\n ((x * x) + (y * y) === z * z) &&\n p(x, y, z)) ? [\n [x, y, z]\n ] : []\n )\n )\n ).length;\n };\n\n // ---------------------- TEST -----------------------\n const main = () => [10, 100, 1000]\n .map(n => ({\n maxPerimeter: n,\n triples: pythTripleCount(() => true)(n),\n primitives: pythTripleCount(\n (x, y) => gcd(x)(y) === 1\n )(n)\n }));\n\n\n // ---------------- GENERIC FUNCTIONS ----------------\n\n // abs :: Num -> Num\n const abs =\n // Absolute value of a given number\n // without the sign.\n x => 0 > x ? (\n -x\n ) : x;\n\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = m =>\n n => Array.from({\n length: 1 + n - m\n }, (_, i) => m + i);\n\n\n // gcd :: Integral a => a -> a -> a\n const gcd = x =>\n y => {\n const zero = x.constructor(0);\n const go = (a, b) =>\n zero === b ? (\n a\n ) : go(b, a % b);\n\n return go(abs(x), abs(y));\n };\n\n // MAIN ---\n return main();\n})();"} +{"title": "Pythagorean triples", "language": "Python", "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). \u00a0 \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. \u00a0 Can your program handle a maximum perimeter of 1,000,000? \u00a0 What about 10,000,000? \u00a0 100,000,000?\n\nNote: the extra credit is not for you to demonstrate how fast your language is compared to others; \u00a0 you need a proper algorithm to solve them in a timely manner.\n\n\n;Related tasks:\n* \u00a0 [[Euler's sum of powers conjecture]] \n* \u00a0 [[List comprehensions]]\n* \u00a0 [[Pythagorean quadruples]] \n\n", "solution": "from fractions import gcd\n\n\ndef pt1(maxperimeter=100):\n '''\n# Naive method\n '''\n trips = []\n for a in range(1, maxperimeter):\n aa = a*a\n for b in range(a, maxperimeter-a+1):\n bb = b*b\n for c in range(b, maxperimeter-b-a+1):\n cc = c*c\n if a+b+c > maxperimeter or cc > aa + bb: break\n if aa + bb == cc:\n trips.append((a,b,c, gcd(a, b) == 1))\n return trips\n\ndef pytrip(trip=(3,4,5),perim=100, prim=1):\n a0, b0, c0 = a, b, c = sorted(trip)\n t, firstprim = set(), prim>0\n while a + b + c <= perim:\n t.add((a, b, c, firstprim>0))\n a, b, c, firstprim = a+a0, b+b0, c+c0, False\n #\n t2 = set()\n for a, b, c, firstprim in t:\n a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7\n if a5 - b5 + c7 <= perim:\n t2 |= pytrip(( a - b2 + c2, a2 - b + c2, a2 - b2 + c3), perim, firstprim)\n if a5 + b5 + c7 <= perim:\n t2 |= pytrip(( a + b2 + c2, a2 + b + c2, a2 + b2 + c3), perim, firstprim)\n if -a5 + b5 + c7 <= perim:\n t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim)\n return t | t2\n\ndef pt2(maxperimeter=100):\n '''\n# Parent/child relationship method:\n# http://en.wikipedia.org/wiki/Formulas_for_generating_Pythagorean_triples#XI.\n '''\n trips = pytrip((3,4,5), maxperimeter, 1)\n return trips\n\ndef printit(maxperimeter=100, pt=pt1):\n trips = pt(maxperimeter)\n print(\" Up to a perimeter of %i there are %i triples, of which %i are primitive\"\n % (maxperimeter,\n len(trips),\n len([prim for a,b,c,prim in trips if prim])))\n \nfor algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)):\n print(algo.__doc__)\n for maxperimeter in range(mn, mx+1, mn):\n printit(maxperimeter, algo)\n"} +{"title": "Quaternion type", "language": "C", "task": "complex numbers.\n\nA complex number has a real and complex part, \u00a0 sometimes written as \u00a0 a + bi, \nwhere \u00a0 a \u00a0 and \u00a0 b \u00a0 stand for real numbers, and \u00a0 i \u00a0 stands for the square root of minus 1.\n\nAn example of a complex number might be \u00a0 -3 + 2i, \u00a0 \nwhere the real part, \u00a0 a \u00a0 is \u00a0 '''-3.0''' \u00a0 and the complex part, \u00a0 b \u00a0 is \u00a0 '''+2.0'''. \n\nA quaternion has one real part and ''three'' imaginary parts, \u00a0 i, \u00a0 j, \u00a0 and \u00a0 k. \n\nA quaternion might be written as \u00a0 a + bi + cj + dk. \n\nIn the quaternion numbering system:\n:::* \u00a0 i\u2219i = j\u2219j = k\u2219k = i\u2219j\u2219k = -1, \u00a0 \u00a0 \u00a0 or more simply,\n:::* \u00a0 ii \u00a0= jj \u00a0= kk \u00a0= ijk \u00a0 = -1. \n\nThe order of multiplication is important, as, in general, for two quaternions:\n:::: \u00a0 q1 \u00a0 and \u00a0 q2: \u00a0 \u00a0 q1q2 \u2260 q2q1. \n\nAn example of a quaternion might be \u00a0 1 +2i +3j +4k \n\nThere is a list form of notation where just the numbers are shown and the imaginary multipliers \u00a0 i, \u00a0 j, \u00a0 and \u00a0 k \u00a0 are assumed by position. \n\nSo the example above would be written as \u00a0 (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 \u00a0 r = 7. \n\n\nCreate functions \u00a0 (or classes) \u00a0 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 \u00a0 r \u00a0 and a quaternion \u00a0 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 \u00a0 q1 \u00a0 and \u00a0 q2 \u00a0 is given by: ( a1a2 \u2212 b1b2 \u2212 c1c2 \u2212 d1d2, \u00a0 a1b2 + b1a2 + c1d2 \u2212 d1c2, \u00a0 a1c2 \u2212 b1d2 + c1a2 + d1b2, \u00a0 a1d2 + b1c2 \u2212 c1b2 + d1a2 ) \n# Show that, for the two quaternions \u00a0 q1 \u00a0 and \u00a0 q2: q1q2 \u2260 q2q1 \n\nIf a language has built-in support for quaternions, then use it.\n\n\n;C.f.:\n* \u00a0 [[Vector products]]\n* \u00a0 [http://www.maths.tcd.ie/pub/HistMath/People/Hamilton/QLetter/QLetter.pdf On Quaternions]; \u00a0 or on a new System of Imaginaries in Algebra. \u00a0 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": "Quaternion type", "language": "JavaScript", "task": "complex numbers.\n\nA complex number has a real and complex part, \u00a0 sometimes written as \u00a0 a + bi, \nwhere \u00a0 a \u00a0 and \u00a0 b \u00a0 stand for real numbers, and \u00a0 i \u00a0 stands for the square root of minus 1.\n\nAn example of a complex number might be \u00a0 -3 + 2i, \u00a0 \nwhere the real part, \u00a0 a \u00a0 is \u00a0 '''-3.0''' \u00a0 and the complex part, \u00a0 b \u00a0 is \u00a0 '''+2.0'''. \n\nA quaternion has one real part and ''three'' imaginary parts, \u00a0 i, \u00a0 j, \u00a0 and \u00a0 k. \n\nA quaternion might be written as \u00a0 a + bi + cj + dk. \n\nIn the quaternion numbering system:\n:::* \u00a0 i\u2219i = j\u2219j = k\u2219k = i\u2219j\u2219k = -1, \u00a0 \u00a0 \u00a0 or more simply,\n:::* \u00a0 ii \u00a0= jj \u00a0= kk \u00a0= ijk \u00a0 = -1. \n\nThe order of multiplication is important, as, in general, for two quaternions:\n:::: \u00a0 q1 \u00a0 and \u00a0 q2: \u00a0 \u00a0 q1q2 \u2260 q2q1. \n\nAn example of a quaternion might be \u00a0 1 +2i +3j +4k \n\nThere is a list form of notation where just the numbers are shown and the imaginary multipliers \u00a0 i, \u00a0 j, \u00a0 and \u00a0 k \u00a0 are assumed by position. \n\nSo the example above would be written as \u00a0 (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 \u00a0 r = 7. \n\n\nCreate functions \u00a0 (or classes) \u00a0 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 \u00a0 r \u00a0 and a quaternion \u00a0 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 \u00a0 q1 \u00a0 and \u00a0 q2 \u00a0 is given by: ( a1a2 \u2212 b1b2 \u2212 c1c2 \u2212 d1d2, \u00a0 a1b2 + b1a2 + c1d2 \u2212 d1c2, \u00a0 a1c2 \u2212 b1d2 + c1a2 + d1b2, \u00a0 a1d2 + b1c2 \u2212 c1b2 + d1a2 ) \n# Show that, for the two quaternions \u00a0 q1 \u00a0 and \u00a0 q2: q1q2 \u2260 q2q1 \n\nIf a language has built-in support for quaternions, then use it.\n\n\n;C.f.:\n* \u00a0 [[Vector products]]\n* \u00a0 [http://www.maths.tcd.ie/pub/HistMath/People/Hamilton/QLetter/QLetter.pdf On Quaternions]; \u00a0 or on a new System of Imaginaries in Algebra. \u00a0 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": "var Quaternion = (function() {\n // The Q() function takes an array argument and changes it\n // prototype so that it becomes a Quaternion instance. This is\n // scoped only for prototype member access.\n function Q(a) {\n\ta.__proto__ = proto;\n\treturn a;\n }\n\n // Actual constructor. This constructor converts its arguments to\n // an array, then that array to a Quaternion instance, then\n // returns that instance. (using \"new\" with this constructor is\n // optional)\n function Quaternion() {\n\treturn Q(Array.prototype.slice.call(arguments, 0, 4));\n }\n\n // Prototype for all Quaternions\n const proto = {\n\t// Inherits from a 4-element Array\n\t__proto__ : [0,0,0,0],\n\n\t// Properties -- In addition to Array[0..3] access, we\n\t// also define matching a, b, c, and d properties\n\tget a() this[0],\n\tget b() this[1],\n\tget c() this[2],\n\tget d() this[3],\n\n\t// Methods\n\tnorm : function() Math.sqrt(this.map(function(x) x*x).reduce(function(x,y) x+y)),\n\tnegate : function() Q(this.map(function(x) -x)),\n\tconjugate : function() Q([ this[0] ].concat(this.slice(1).map(function(x) -x))),\n\tadd : function(x) {\n\t if (\"number\" === typeof x) {\n\t\treturn Q([ this[0] + x ].concat(this.slice(1)));\n\t } else {\n\t\treturn Q(this.map(function(v,i) v+x[i]));\n\t }\n\t},\n\tmul : function(r) {\n\t var q = this;\n\t if (\"number\" === typeof r) {\n\t\treturn Q(q.map(function(e) e*r));\n\t } else {\n\t\treturn Q([ q[0] * r[0] - q[1] * r[1] - q[2] * r[2] - q[3] * r[3],\n\t\t\t q[0] * r[1] + q[1] * r[0] + q[2] * r[3] - q[3] * r[2],\n\t\t\t q[0] * r[2] - q[1] * r[3] + q[2] * r[0] + q[3] * r[1],\n\t\t\t q[0] * r[3] + q[1] * r[2] - q[2] * r[1] + q[3] * r[0] ]);\n\t }\n\t},\n\tequals : function(q) this.every(function(v,i) v === q[i]),\n\ttoString : function() (this[0] + \" + \" + this[1] + \"i + \"+this[2] + \"j + \" + this[3] + \"k\").replace(/\\+ -/g, '- ')\n };\n\n Quaternion.prototype = proto;\n return Quaternion;\n})();"} +{"title": "Quaternion type", "language": "Python", "task": "complex numbers.\n\nA complex number has a real and complex part, \u00a0 sometimes written as \u00a0 a + bi, \nwhere \u00a0 a \u00a0 and \u00a0 b \u00a0 stand for real numbers, and \u00a0 i \u00a0 stands for the square root of minus 1.\n\nAn example of a complex number might be \u00a0 -3 + 2i, \u00a0 \nwhere the real part, \u00a0 a \u00a0 is \u00a0 '''-3.0''' \u00a0 and the complex part, \u00a0 b \u00a0 is \u00a0 '''+2.0'''. \n\nA quaternion has one real part and ''three'' imaginary parts, \u00a0 i, \u00a0 j, \u00a0 and \u00a0 k. \n\nA quaternion might be written as \u00a0 a + bi + cj + dk. \n\nIn the quaternion numbering system:\n:::* \u00a0 i\u2219i = j\u2219j = k\u2219k = i\u2219j\u2219k = -1, \u00a0 \u00a0 \u00a0 or more simply,\n:::* \u00a0 ii \u00a0= jj \u00a0= kk \u00a0= ijk \u00a0 = -1. \n\nThe order of multiplication is important, as, in general, for two quaternions:\n:::: \u00a0 q1 \u00a0 and \u00a0 q2: \u00a0 \u00a0 q1q2 \u2260 q2q1. \n\nAn example of a quaternion might be \u00a0 1 +2i +3j +4k \n\nThere is a list form of notation where just the numbers are shown and the imaginary multipliers \u00a0 i, \u00a0 j, \u00a0 and \u00a0 k \u00a0 are assumed by position. \n\nSo the example above would be written as \u00a0 (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 \u00a0 r = 7. \n\n\nCreate functions \u00a0 (or classes) \u00a0 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 \u00a0 r \u00a0 and a quaternion \u00a0 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 \u00a0 q1 \u00a0 and \u00a0 q2 \u00a0 is given by: ( a1a2 \u2212 b1b2 \u2212 c1c2 \u2212 d1d2, \u00a0 a1b2 + b1a2 + c1d2 \u2212 d1c2, \u00a0 a1c2 \u2212 b1d2 + c1a2 + d1b2, \u00a0 a1d2 + b1c2 \u2212 c1b2 + d1a2 ) \n# Show that, for the two quaternions \u00a0 q1 \u00a0 and \u00a0 q2: q1q2 \u2260 q2q1 \n\nIf a language has built-in support for quaternions, then use it.\n\n\n;C.f.:\n* \u00a0 [[Vector products]]\n* \u00a0 [http://www.maths.tcd.ie/pub/HistMath/People/Hamilton/QLetter/QLetter.pdf On Quaternions]; \u00a0 or on a new System of Imaginaries in Algebra. \u00a0 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": "from collections import namedtuple\nimport math\n\nclass Q(namedtuple('Quaternion', 'real, i, j, k')):\n 'Quaternion type: Q(real=0.0, i=0.0, j=0.0, k=0.0)' \n\n __slots__ = () \n\n def __new__(_cls, real=0.0, i=0.0, j=0.0, k=0.0):\n 'Defaults all parts of quaternion to zero'\n return super().__new__(_cls, float(real), float(i), float(j), float(k))\n\n def conjugate(self):\n return Q(self.real, -self.i, -self.j, -self.k)\n\n def _norm2(self):\n return sum( x*x for x in self)\n\n def norm(self):\n return math.sqrt(self._norm2())\n\n def reciprocal(self):\n n2 = self._norm2()\n return Q(*(x / n2 for x in self.conjugate())) \n\n def __str__(self):\n 'Shorter form of Quaternion as string'\n return 'Q(%g, %g, %g, %g)' % self\n\n def __neg__(self):\n return Q(-self.real, -self.i, -self.j, -self.k)\n\n def __add__(self, other):\n if type(other) == Q:\n return Q( *(s+o for s,o in zip(self, other)) )\n try:\n f = float(other)\n except:\n return NotImplemented\n return Q(self.real + f, self.i, self.j, self.k)\n\n def __radd__(self, other):\n return Q.__add__(self, other)\n\n def __mul__(self, other):\n if type(other) == Q:\n a1,b1,c1,d1 = self\n a2,b2,c2,d2 = other\n return Q(\n a1*a2 - b1*b2 - c1*c2 - d1*d2,\n a1*b2 + b1*a2 + c1*d2 - d1*c2,\n a1*c2 - b1*d2 + c1*a2 + d1*b2,\n a1*d2 + b1*c2 - c1*b2 + d1*a2 )\n try:\n f = float(other)\n except:\n return NotImplemented\n return Q(self.real * f, self.i * f, self.j * f, self.k * f)\n\n def __rmul__(self, other):\n return Q.__mul__(self, other)\n\n def __truediv__(self, other):\n if type(other) == Q:\n return self.__mul__(other.reciprocal())\n try:\n f = float(other)\n except:\n return NotImplemented\n return Q(self.real / f, self.i / f, self.j / f, self.k / f)\n\n def __rtruediv__(self, other):\n return other * self.reciprocal()\n\n __div__, __rdiv__ = __truediv__, __rtruediv__\n\nQuaternion = Q \n\nq = Q(1, 2, 3, 4)\nq1 = Q(2, 3, 4, 5)\nq2 = Q(3, 4, 5, 6)\nr = 7"} +{"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 \u00a0 '''quine''' \u00a0 (named after Willard Van Orman Quine) \u00a0 is also known as:\n::* \u00a0 ''self-reproducing automata'' \u00a0 (1972)\n::* \u00a0 ''self-replicating program'' \u00a0 \u00a0 \u00a0 \u00a0 or \u00a0 ''self-replicating computer program''\n::* \u00a0 ''self-reproducing program''\u00a0 \u00a0 \u00a0 or \u00a0 ''self-reproducing computer program''\n::* \u00a0 ''self-copying program'' \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 or \u00a0 ''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 [http://www.nyx.net/~gthompso/quine.htm Quine] page.'''\n\n\n;Related task:\n:* \u00a0 [https://rosettacode.org/wiki/Print_itself 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": "Quine", "language": "SpiderMonkey", "task": "A quine is a self-referential program that can, \nwithout any external access, output its own source. \n\n\nA \u00a0 '''quine''' \u00a0 (named after Willard Van Orman Quine) \u00a0 is also known as:\n::* \u00a0 ''self-reproducing automata'' \u00a0 (1972)\n::* \u00a0 ''self-replicating program'' \u00a0 \u00a0 \u00a0 \u00a0 or \u00a0 ''self-replicating computer program''\n::* \u00a0 ''self-reproducing program''\u00a0 \u00a0 \u00a0 or \u00a0 ''self-reproducing computer program''\n::* \u00a0 ''self-copying program'' \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 or \u00a0 ''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 [http://www.nyx.net/~gthompso/quine.htm Quine] page.'''\n\n\n;Related task:\n:* \u00a0 [https://rosettacode.org/wiki/Print_itself print itself].\n\n", "solution": "(function(){str=[\"(function(){str=[F].join(String.fromCharCode(34));str=str.replace(/F/,String.fromCharCode(34)+str+String.fromCharCode(34));console.log(str)})()\"].join(String.fromCharCode(34));str=str.replace(/F/,String.fromCharCode(34)+str+String.fromCharCode(34));console.log(str)})()"} +{"title": "Quine", "language": "Python 2.x and 3.x", "task": "A quine is a self-referential program that can, \nwithout any external access, output its own source. \n\n\nA \u00a0 '''quine''' \u00a0 (named after Willard Van Orman Quine) \u00a0 is also known as:\n::* \u00a0 ''self-reproducing automata'' \u00a0 (1972)\n::* \u00a0 ''self-replicating program'' \u00a0 \u00a0 \u00a0 \u00a0 or \u00a0 ''self-replicating computer program''\n::* \u00a0 ''self-reproducing program''\u00a0 \u00a0 \u00a0 or \u00a0 ''self-reproducing computer program''\n::* \u00a0 ''self-copying program'' \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 or \u00a0 ''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 [http://www.nyx.net/~gthompso/quine.htm Quine] page.'''\n\n\n;Related task:\n:* \u00a0 [https://rosettacode.org/wiki/Print_itself print itself].\n\n", "solution": "import sys,inspect;sys.stdout.write(inspect.getsource(inspect.currentframe()))"} +{"title": "Quine", "language": "Python 3.x and 2.6+", "task": "A quine is a self-referential program that can, \nwithout any external access, output its own source. \n\n\nA \u00a0 '''quine''' \u00a0 (named after Willard Van Orman Quine) \u00a0 is also known as:\n::* \u00a0 ''self-reproducing automata'' \u00a0 (1972)\n::* \u00a0 ''self-replicating program'' \u00a0 \u00a0 \u00a0 \u00a0 or \u00a0 ''self-replicating computer program''\n::* \u00a0 ''self-reproducing program''\u00a0 \u00a0 \u00a0 or \u00a0 ''self-reproducing computer program''\n::* \u00a0 ''self-copying program'' \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 or \u00a0 ''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 [http://www.nyx.net/~gthompso/quine.htm Quine] page.'''\n\n\n;Related task:\n:* \u00a0 [https://rosettacode.org/wiki/Print_itself print itself].\n\n", "solution": "x = 'x = {!r};print(x.format(x))';print(x.format(x))"} +{"title": "Quine", "language": "Python 3.8+", "task": "A quine is a self-referential program that can, \nwithout any external access, output its own source. \n\n\nA \u00a0 '''quine''' \u00a0 (named after Willard Van Orman Quine) \u00a0 is also known as:\n::* \u00a0 ''self-reproducing automata'' \u00a0 (1972)\n::* \u00a0 ''self-replicating program'' \u00a0 \u00a0 \u00a0 \u00a0 or \u00a0 ''self-replicating computer program''\n::* \u00a0 ''self-reproducing program''\u00a0 \u00a0 \u00a0 or \u00a0 ''self-reproducing computer program''\n::* \u00a0 ''self-copying program'' \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 or \u00a0 ''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 [http://www.nyx.net/~gthompso/quine.htm Quine] page.'''\n\n\n;Related task:\n:* \u00a0 [https://rosettacode.org/wiki/Print_itself print itself].\n\n", "solution": "data = (\n\t'ZGF0YSA9ICgKCSc=',\n\t'JywKCSc=',\n\t'JwopCnByZWZpeCwgc2VwYXJhdG9yLCBzdWZmaXggPSAoZC5kZWNvZGUoJ2Jhc2U2NCcpIGZvciBkIGluIGRhdGEpCnByaW50IHByZWZpeCArIGRhdGFbMF0gKyBzZXBhcmF0b3IgKyBkYXRhWzFdICsgc2VwYXJhdG9yICsgZGF0YVsyXSArIHN1ZmZpeA=='\n)\nprefix, separator, suffix = (d.decode('base64') for d in data)\nprint prefix + data[0] + separator + data[1] + separator + data[2] + suffix"} +{"title": "RIPEMD-160", "language": "C", "task": "'''RIPEMD-160''' is another hash function; it computes a 160-bit message digest.\n\nThere is a [http://homes.esat.kuleuven.be/~bosselae/ripemd160.html RIPEMD-160 home page], with test vectors and [http://www.esat.kuleuven.be/~bosselae/ripemd/rmd160.txt 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 \u201cRosetta Code\u201d. \nYou may either call an RIPEMD-160 library, or implement RIPEMD-160 in your language.\n\n", "solution": "\n#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": "RIPEMD-160", "language": "Python", "task": "'''RIPEMD-160''' is another hash function; it computes a 160-bit message digest.\n\nThere is a [http://homes.esat.kuleuven.be/~bosselae/ripemd160.html RIPEMD-160 home page], with test vectors and [http://www.esat.kuleuven.be/~bosselae/ripemd/rmd160.txt 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 \u201cRosetta Code\u201d. \nYou may either call an RIPEMD-160 library, or implement RIPEMD-160 in your language.\n\n", "solution": "Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit (AMD64)] on win32\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> import hashlib\n>>> h = hashlib.new('ripemd160')\n>>> h.update(b\"Rosetta Code\")\n>>> h.hexdigest()\n'b3be159860842cebaa7174c8fff0aa9e50a5199f'\n>>> "} +{"title": "RPG attributes generator", "language": "C", "task": "[[Category:Simple]]\n'''RPG''' \u00a0 = \u00a0 Role Playing Game.\n\n\n\nYou're running a tabletop RPG, and your players are creating characters.\n\nEach character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma.\n\nOne way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll.\n\nSome players like to assign values to their attributes in the order they're rolled.\n\nTo ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied:\n\n* The total of all character attributes must be at least 75.\n* At least two of the attributes must be at least 15.\n\nHowever, this can require a lot of manual dice rolling. A programatic solution would be much faster.\n\n\n;Task:\nWrite a program that:\n# Generates 4 random, whole values between 1 and 6.\n# Saves the sum of the 3 largest values.\n# Generates a total of 6 values this way.\n# Displays the total, and all 6 values once finished.\n\n* The order in which each value was generated must be preserved.\n* The total of all 6 values must be at least 75.\n* At least 2 of the values must be 15 or more.\n\n", "solution": "#include \n#include \n#include \n\nint compareInts(const void *i1, const void *i2) {\n int a = *((int *)i1);\n int b = *((int *)i2);\n return a - b;\n}\n\nint main() {\n int i, j, nsum, vsum, vcount, values[6], numbers[4];\n srand(time(NULL));\n for (;;) {\n vsum = 0;\n for (i = 0; i < 6; ++i) {\n for (j = 0; j < 4; ++j) {\n numbers[j] = 1 + rand() % 6;\n }\n qsort(numbers, 4, sizeof(int), compareInts);\n nsum = 0;\n for (j = 1; j < 4; ++j) {\n nsum += numbers[j];\n }\n values[i] = nsum;\n vsum += values[i];\n }\n if (vsum < 75) continue;\n vcount = 0;\n for (j = 0; j < 6; ++j) {\n if (values[j] >= 15) vcount++;\n }\n if (vcount < 2) continue;\n printf(\"The 6 random numbers generated are:\\n\");\n printf(\"[\");\n for (j = 0; j < 6; ++j) printf(\"%d \", values[j]);\n printf(\"\\b]\\n\");\n printf(\"\\nTheir sum is %d and %d of them are >= 15\\n\", vsum, vcount);\n break;\n }\n return 0;\n}"} +{"title": "RPG attributes generator", "language": "Python", "task": "[[Category:Simple]]\n'''RPG''' \u00a0 = \u00a0 Role Playing Game.\n\n\n\nYou're running a tabletop RPG, and your players are creating characters.\n\nEach character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma.\n\nOne way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll.\n\nSome players like to assign values to their attributes in the order they're rolled.\n\nTo ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied:\n\n* The total of all character attributes must be at least 75.\n* At least two of the attributes must be at least 15.\n\nHowever, this can require a lot of manual dice rolling. A programatic solution would be much faster.\n\n\n;Task:\nWrite a program that:\n# Generates 4 random, whole values between 1 and 6.\n# Saves the sum of the 3 largest values.\n# Generates a total of 6 values this way.\n# Displays the total, and all 6 values once finished.\n\n* The order in which each value was generated must be preserved.\n* The total of all 6 values must be at least 75.\n* At least 2 of the values must be 15 or more.\n\n", "solution": "import random\nrandom.seed()\nattributes_total = 0\ncount = 0\n\nwhile attributes_total < 75 or count < 2:\n attributes = []\n\n for attribute in range(0, 6):\n rolls = []\n \n for roll in range(0, 4):\n result = random.randint(1, 6)\n rolls.append(result)\n \n sorted_rolls = sorted(rolls)\n largest_3 = sorted_rolls[1:]\n rolls_total = sum(largest_3)\n \n if rolls_total >= 15:\n count += 1\n \n attributes.append(rolls_total)\n\n attributes_total = sum(attributes)\n \nprint(attributes_total, attributes)"} +{"title": "Ramanujan's constant", "language": "Python", "task": "Calculate Ramanujan's constant (as described on the [http://oeis.org/wiki/Ramanujan%27s_constant OEIS site]) with at least\n32 digits of precision, by the method of your choice. Optionally, if using the \ud835\udc52**(\u03c0*\u221a''x'') approach,\nshow that when evaluated with the last four [https://en.wikipedia.org/wiki/Heegner_number Heegner numbers]\nthe result is ''almost'' an integer.\n\n", "solution": "from mpmath import mp\nheegner = [19,43,67,163]\nmp.dps = 50\nx = mp.exp(mp.pi*mp.sqrt(163))\nprint(\"calculated Ramanujan's constant: {}\".format(x))\nprint(\"Heegner numbers yielding 'almost' integers:\")\nfor i in heegner:\n print(\" for {}: {} ~ {} error: {}\".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))\n"} +{"title": "Ramer-Douglas-Peucker line simplification", "language": "C", "task": "The \u00a0 '''Ramer\u2013Douglas\u2013Peucker''' \u00a0 algorithm is a line simplification algorithm for reducing the number of points used to define its shape. \n\n\n;Task:\nUsing the \u00a0 '''Ramer\u2013Douglas\u2013Peucker''' \u00a0 algorithm, simplify the \u00a0 2D \u00a0 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: \u00a0 '''1.0'''. \n\nDisplay the remaining points here.\n\n\n;Reference:\n:* \u00a0 the Wikipedia article: \u00a0 [https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm 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": "Ramer-Douglas-Peucker line simplification", "language": "JavaScript", "task": "The \u00a0 '''Ramer\u2013Douglas\u2013Peucker''' \u00a0 algorithm is a line simplification algorithm for reducing the number of points used to define its shape. \n\n\n;Task:\nUsing the \u00a0 '''Ramer\u2013Douglas\u2013Peucker''' \u00a0 algorithm, simplify the \u00a0 2D \u00a0 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: \u00a0 '''1.0'''. \n\nDisplay the remaining points here.\n\n\n;Reference:\n:* \u00a0 the Wikipedia article: \u00a0 [https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm Ramer-Douglas-Peucker algorithm].\n\n", "solution": "/**\n * @typedef {{\n * x: (!number),\n * y: (!number)\n * }}\n */\nlet pointType;\n\n/**\n * @param {!Array} l\n * @param {number} eps\n */\nconst RDP = (l, eps) => {\n const last = l.length - 1;\n const p1 = l[0];\n const p2 = l[last];\n const x21 = p2.x - p1.x;\n const y21 = p2.y - p1.y;\n\n const [dMax, x] = l.slice(1, last)\n .map(p => Math.abs(y21 * p.x - x21 * p.y + p2.x * p1.y - p2.y * p1.x))\n .reduce((p, c, i) => {\n const v = Math.max(p[0], c);\n return [v, v === p[0] ? p[1] : i + 1];\n }, [-1, 0]);\n\n if (dMax > eps) {\n return [...RDP(l.slice(0, x + 1), eps), ...RDP(l.slice(x), eps).slice(1)];\n }\n return [l[0], l[last]]\n};\n\nconst points = [\n {x: 0, y: 0},\n {x: 1, y: 0.1},\n {x: 2, y: -0.1},\n {x: 3, y: 5},\n {x: 4, y: 6},\n {x: 5, y: 7},\n {x: 6, y: 8.1},\n {x: 7, y: 9},\n {x: 8, y: 9},\n {x: 9, y: 9}];\n\nconsole.log(RDP(points, 1));"} +{"title": "Ramer-Douglas-Peucker line simplification", "language": "Python", "task": "The \u00a0 '''Ramer\u2013Douglas\u2013Peucker''' \u00a0 algorithm is a line simplification algorithm for reducing the number of points used to define its shape. \n\n\n;Task:\nUsing the \u00a0 '''Ramer\u2013Douglas\u2013Peucker''' \u00a0 algorithm, simplify the \u00a0 2D \u00a0 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: \u00a0 '''1.0'''. \n\nDisplay the remaining points here.\n\n\n;Reference:\n:* \u00a0 the Wikipedia article: \u00a0 [https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm Ramer-Douglas-Peucker algorithm].\n\n", "solution": "from __future__ import print_function\nfrom shapely.geometry import LineString\n \nif __name__==\"__main__\":\n\tline = LineString([(0,0),(1,0.1),(2,-0.1),(3,5),(4,6),(5,7),(6,8.1),(7,9),(8,9),(9,9)])\n\tprint (line.simplify(1.0, preserve_topology=False))"} +{"title": "Random Latin squares", "language": "C", "task": "A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once.\nFor the purposes of this task, a random Latin square of size n is a Latin square constructed or generated by a probabilistic procedure such that the probability of any particular Latin square of size n being produced is non-zero.\n\n;Example n=4 randomised Latin square:\n0 2 3 1\n2 1 0 3\n3 0 1 2\n1 3 2 0\n\n;Task:\n# Create a function/routine/procedure/method/... that given n generates a randomised Latin square of size n.\n# Use the function to generate ''and show here'', two randomly generated squares of size 5.\n\n;Note: \nStrict ''uniformity'' in the random generation is a hard problem and '''not''' a requirement of the task.\n\n;Related tasks:\n* [[Latin Squares in reduced form/Randomizing using Jacobson and Matthews\u2019 Technique]]\n* [[Latin Squares in reduced form]]\n\n;Reference:\n* Wikipedia: Latin square\n* OEIS: A002860\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\n// low <= num < high\nint randInt(int low, int high) {\n return (rand() % (high - low)) + low;\n}\n\n// shuffle an array of n elements\nvoid shuffle(int *const array, const int n) {\n if (n > 1) {\n int i;\n for (i = 0; i < n - 1; i++) {\n int j = randInt(i, n);\n\n int t = array[i];\n array[i] = array[j];\n array[j] = t;\n }\n }\n}\n\n// print an n * n array\nvoid printSquare(const int *const latin, const int n) {\n int i, j;\n for (i = 0; i < n; i++) {\n printf(\"[\");\n for (j = 0; j < n; j++) {\n if (j > 0) {\n printf(\", \");\n }\n printf(\"%d\", latin[i * n + j]);\n }\n printf(\"]\\n\");\n }\n printf(\"\\n\");\n}\n\nvoid latinSquare(const int n) {\n int *latin, *used;\n int i, j, k;\n\n if (n <= 0) {\n printf(\"[]\\n\");\n return;\n }\n\n // allocate\n latin = (int *)malloc(n * n * sizeof(int));\n if (!latin) {\n printf(\"Failed to allocate memory.\");\n return;\n }\n\n // initialize\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n latin[i * n + j] = j;\n }\n }\n\n // first row\n shuffle(latin, n);\n\n // middle row(s)\n for (i = 1; i < n - 1; i++) {\n bool shuffled = false;\n\n while (!shuffled) {\n shuffle(&latin[i * n], n);\n\n for (k = 0; k < i; k++) {\n for (j = 0; j < n; j++) {\n if (latin[k * n + j] == latin[i * n + j]) {\n goto shuffling;\n }\n }\n }\n shuffled = true;\n\n shuffling: {}\n }\n }\n\n //last row\n used = (int *)malloc(n * sizeof(int));\n for (j = 0; j < n; j++) {\n memset(used, 0, n * sizeof(int));\n for (i = 0; i < n - 1; i++) {\n used[latin[i * n + j]] = 1;\n }\n for (k = 0; k < n; k++) {\n if (used[k] == 0) {\n latin[(n - 1) * n + j] = k;\n break;\n }\n }\n }\n free(used);\n\n // print the result\n printSquare(latin, n);\n free(latin);\n}\n\nint main() {\n // initialze the random number generator\n srand((unsigned int)time((time_t)0));\n\n latinSquare(5);\n latinSquare(5);\n latinSquare(10);\n\n return 0;\n}"} +{"title": "Random Latin squares", "language": "Python", "task": "A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once.\nFor the purposes of this task, a random Latin square of size n is a Latin square constructed or generated by a probabilistic procedure such that the probability of any particular Latin square of size n being produced is non-zero.\n\n;Example n=4 randomised Latin square:\n0 2 3 1\n2 1 0 3\n3 0 1 2\n1 3 2 0\n\n;Task:\n# Create a function/routine/procedure/method/... that given n generates a randomised Latin square of size n.\n# Use the function to generate ''and show here'', two randomly generated squares of size 5.\n\n;Note: \nStrict ''uniformity'' in the random generation is a hard problem and '''not''' a requirement of the task.\n\n;Related tasks:\n* [[Latin Squares in reduced form/Randomizing using Jacobson and Matthews\u2019 Technique]]\n* [[Latin Squares in reduced form]]\n\n;Reference:\n* Wikipedia: Latin square\n* OEIS: A002860\n\n", "solution": "from random import choice, shuffle\nfrom copy import deepcopy\n\ndef rls(n):\n if n <= 0:\n return []\n else:\n symbols = list(range(n))\n square = _rls(symbols)\n return _shuffle_transpose_shuffle(square)\n\n\ndef _shuffle_transpose_shuffle(matrix):\n square = deepcopy(matrix)\n shuffle(square)\n trans = list(zip(*square))\n shuffle(trans)\n return trans\n\n\ndef _rls(symbols):\n n = len(symbols)\n if n == 1:\n return [symbols]\n else:\n sym = choice(symbols)\n symbols.remove(sym)\n square = _rls(symbols)\n square.append(square[0].copy())\n for i in range(n):\n square[i].insert(i, sym)\n return square\n\ndef _to_text(square):\n if square:\n width = max(len(str(sym)) for row in square for sym in row)\n txt = '\\n'.join(' '.join(f\"{sym:>{width}}\" for sym in row)\n for row in square)\n else:\n txt = ''\n return txt\n\ndef _check(square):\n transpose = list(zip(*square))\n assert _check_rows(square) and _check_rows(transpose), \\\n \"Not a Latin square\"\n\ndef _check_rows(square):\n if not square:\n return True\n set_row0 = set(square[0])\n return all(len(row) == len(set(row)) and set(row) == set_row0\n for row in square)\n\n\nif __name__ == '__main__':\n for i in [3, 3, 5, 5, 12]:\n square = rls(i)\n print(_to_text(square))\n _check(square)\n print()"} +{"title": "Random number generator (device)", "language": "C", "task": "[[Category:Input Output]]\n\n;Task:\nIf your system has a means to generate random numbers involving not only a software algorithm \u00a0 (like the /dev/urandom devices in Unix), \u00a0 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 (device)", "language": "MinGW", "task": "[[Category:Input Output]]\n\n;Task:\nIf your system has a means to generate random numbers involving not only a software algorithm \u00a0 (like the /dev/urandom devices in Unix), \u00a0 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 /* printf */\n#include \n#include /* CryptAcquireContext, CryptGenRandom */\n\nint\nmain()\n{\n HCRYPTPROV p;\n ULONG i;\n\n if (CryptAcquireContext(&p, NULL, NULL,\n PROV_RSA_FULL, CRYPT_VERIFYCONTEXT) == FALSE) {\n fputs(\"CryptAcquireContext failed.\\n\", stderr);\n return 1;\n }\n if (CryptGenRandom(p, sizeof i, (BYTE *)&i) == FALSE) {\n fputs(\"CryptGenRandom failed.\\n\", stderr);\n return 1;\n }\n printf(\"%lu\\n\", i);\n CryptReleaseContext(p, 0);\n return 0;\n}"} +{"title": "Random number generator (device)", "language": "GCC", "task": "[[Category:Input Output]]\n\n;Task:\nIf your system has a means to generate random numbers involving not only a software algorithm \u00a0 (like the /dev/urandom devices in Unix), \u00a0 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": "\n#include \n#include \n\n/*\n (C) 2020 J.G.A. Debaere, all rights reserved 2020/10/29\n\n Put into Public Domain for individuals only \n \n Tested with NIST, Diehard, Diehard 3.31\n \n gcc -lm ./jpsrand_f.c -o ./jpsrand_f.o\n\n dieharder -a -f /tmp/tmp.bin\n\n\tI consider it TRNG, \n\t\n\tusing Time, Hardddisk and Memory as the hardware component\n\n\tNo warranty of any kind, \"AS IS\"\n\t \n\tLast time I tested ( 2021/07/07 ) with dieharder:\n\t \n\trgb_bitdist\t\t| 8| 100000| 100|0.99716738| WEAK \t\n\trgb_lagged_sum\t| 3| 1000000| 100|0.99661184| WEAK \n\t \n\tOut of 114 tests, rest PASSED\n\n Obviously, it changes per run :)\n\t\n*/\n\nunsigned int jps_rand()\n{\n /* (C) 2020 J.G.A. Debaere, all rights reserved */\n \n #include \n\n #include \n\n struct timeval current_time ;\n \n DIR *folder ;\n \n struct dirent *en ; \n \n folder = opendir ( \".\" ) ;\n\n while ( ( folder ) && ( en = readdir ( folder ) ) != NULL )\n\n asm ( \"nop\" ) ;\n \n closedir ( folder ) ;\n \n gettimeofday( \u00a4t_time, NULL ) ;\n \n unsigned int t = ( current_time.tv_sec * current_time.tv_usec / 17.17 ) ; \n \n return t ;\n}\n\nint main() \n{ \n FILE * f1;\n\n f1 = fopen(\"/tmp/tmp.bin\", \"wb\");\n\n\n unsigned int t = ( unsigned int ) jps_rand() ;\n \n for ( unsigned int k = 0; k < 40000000 ; k++ )\n {\n t = jps_rand () ;\n\n fwrite ( &t, sizeof( unsigned int ), 1, f1 ) ;\n }\n \n fflush(f1);\n \n fclose(f1);\n \n return 0; \n} \n\n"} +{"title": "Random number generator (device)", "language": "Python", "task": "[[Category:Input Output]]\n\n;Task:\nIf your system has a means to generate random numbers involving not only a software algorithm \u00a0 (like the /dev/urandom devices in Unix), \u00a0 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": "import random\nrand = random.SystemRandom()\nrand.randint(1,10)"} +{"title": "Random sentence from book", "language": "Python", "task": "* Read in the book \"[http://www.gutenberg.org/files/36/36-0.txt The War of the Worlds]\", by H. G. Wells.\n* Skip to the start of the book, proper.\n* Remove extraneous punctuation, but keep at least sentence-ending punctuation characters . ! and ?\n* Keep account of what words follow words and how many times it is seen, (treat sentence terminators as words too).\n* Keep account of what words follow ''two'' words and how many times it is seen, (again treating sentence terminators as words too).\n* Assume that a sentence starts with a not to be shown full-stop character then ''use a weighted random choice'' of the possible words that may follow a full-stop to add to the sentence.\n* Then repeatedly add words to the sentence based on weighted random choices of what words my follow the last two words to extend the sentence.\n* Stop after adding a sentence ending punctuation character.\n* Tidy and then print the sentence.\n\n\nShow examples of random sentences generated.\n\n;Related task\n* [[Markov_chain_text_generator]]\n\n\n", "solution": "from urllib.request import urlopen\nimport re\nfrom string import punctuation\nfrom collections import Counter, defaultdict\nimport random\n\n\n# The War of the Worlds, by H. G. Wells\ntext_url = 'http://www.gutenberg.org/files/36/36-0.txt'\ntext_start = 'No one would have believed'\n\nsentence_ending = '.!?'\nsentence_pausing = ',;:'\n\ndef read_book(text_url, text_start) -> str:\n with urlopen(text_url) as book:\n text = book.read().decode('utf-8')\n return text[text.index(text_start):]\n\ndef remove_punctuation(text: str, keep=sentence_ending+sentence_pausing)-> str:\n \"Remove punctuation, keeping some\"\n to_remove = ''.join(set(punctuation) - set(keep))\n text = text.translate(str.maketrans(to_remove, ' ' * len(to_remove))).strip()\n text = re.sub(fr\"[^a-zA-Z0-9{keep}\\n ]+\", ' ', text)\n # Remove duplicates and put space around remaining punctuation\n if keep:\n text = re.sub(f\"([{keep}])+\", r\" \\1 \", text).strip()\n if text[-1] not in sentence_ending:\n text += ' .'\n return text.lower()\n\ndef word_follows_words(txt_with_pauses_and_endings):\n \"return dict of freq of words following one/two words\"\n words = ['.'] + txt_with_pauses_and_endings.strip().split()\n\n # count of what word follows this\n word2next = defaultdict(lambda :defaultdict(int))\n word2next2 = defaultdict(lambda :defaultdict(int))\n for lh, rh in zip(words, words[1:]):\n word2next[lh][rh] += 1\n for lh, mid, rh in zip(words, words[1:], words[2:]):\n word2next2[(lh, mid)][rh] += 1\n\n return dict(word2next), dict(word2next2)\n\ndef gen_sentence(word2next, word2next2) -> str:\n\n s = ['.']\n s += random.choices(*zip(*word2next[s[-1]].items()))\n while True:\n s += random.choices(*zip(*word2next2[(s[-2], s[-1])].items()))\n if s[-1] in sentence_ending:\n break\n\n s = ' '.join(s[1:]).capitalize()\n s = re.sub(fr\" ([{sentence_ending+sentence_pausing}])\", r'\\1', s)\n s = re.sub(r\" re\\b\", \"'re\", s)\n s = re.sub(r\" s\\b\", \"'s\", s)\n s = re.sub(r\"\\bi\\b\", \"I\", s)\n\n return s\n\nif __name__ == \"__main__\":\n txt_with_pauses_and_endings = remove_punctuation(read_book(text_url, text_start))\n word2next, word2next2 = word_follows_words(txt_with_pauses_and_endings)\n #%%\n sentence = gen_sentence(word2next, word2next2)\n print(sentence)"} +{"title": "Range consolidation", "language": "C", "task": "Define a range of numbers \u00a0 '''R''', \u00a0 with bounds \u00a0 '''b0''' \u00a0 and \u00a0 '''b1''' \u00a0 covering all numbers ''between and including both bounds''. \n\n\nThat range can be shown as:\n::::::::: '''[b0, b1]'''\n:::::::: \u00a0\u00a0 or equally as:\n::::::::: '''[b1, b0]'''\n\n\nGiven two ranges, the act of consolidation between them compares the two ranges:\n* \u00a0 If one range covers all of the other then the result is that encompassing range.\n* \u00a0 If the ranges touch or intersect then the result is \u00a0 ''one'' \u00a0 new single range covering the overlapping ranges.\n* \u00a0 Otherwise the act of consolidation is to return the two non-touching ranges.\n\n\nGiven \u00a0 '''N''' \u00a0 ranges where \u00a0 '''N > 2''' \u00a0 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 \u00a0 '''N < 2''' \u00a0 then range consolidation has no strict meaning and the input can be returned. \n\n\n;Example 1:\n: \u00a0 Given the two ranges \u00a0 '''[1, 2.5]''' \u00a0 and \u00a0 '''[3, 4.2]''' \u00a0 then \n: \u00a0 there is no common region between the ranges and the result is the same as the input.\n\n\n;Example 2:\n: \u00a0 Given the two ranges \u00a0 '''[1, 2.5]''' \u00a0 and \u00a0 '''[1.8, 4.7]''' \u00a0 then \n: \u00a0 there is : \u00a0 an overlap \u00a0 '''[2.5, 1.8]''' \u00a0 between the ranges and \n: \u00a0 the result is the single range \u00a0 '''[1, 4.7]'''. \n: \u00a0 Note that order of bounds in a range is not (yet) stated.\n\n\n;Example 3:\n: \u00a0 Given the two ranges \u00a0 '''[6.1, 7.2]''' \u00a0 and \u00a0 '''[7.2, 8.3]''' \u00a0 then \n: \u00a0 they touch at \u00a0 '''7.2''' \u00a0 and \n: \u00a0 the result is the single range \u00a0 '''[6.1, 8.3]'''. \n\n\n;Example 4:\n: \u00a0 Given the three ranges \u00a0 '''[1, 2]''' \u00a0 and \u00a0 '''[4, 8]''' \u00a0 and \u00a0 '''[2, 5]''' \n: \u00a0 then there is no intersection of the ranges \u00a0 '''[1, 2]''' \u00a0 and \u00a0 '''[4, 8]''' \n: \u00a0 but the ranges \u00a0 '''[1, 2]''' \u00a0 and \u00a0 '''[2, 5]''' \u00a0 overlap and \n: \u00a0 consolidate to produce the range \u00a0 '''[1, 5]'''. \n: \u00a0 This range, in turn, overlaps the other range \u00a0 '''[4, 8]''', \u00a0 and \n: \u00a0 so consolidates to the final output of the single range \u00a0 '''[1, 8]'''.\n\n\n;Task:\nLet a normalized range display show the smaller bound to the left; \u00a0 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 consolidation", "language": "JavaScript", "task": "Define a range of numbers \u00a0 '''R''', \u00a0 with bounds \u00a0 '''b0''' \u00a0 and \u00a0 '''b1''' \u00a0 covering all numbers ''between and including both bounds''. \n\n\nThat range can be shown as:\n::::::::: '''[b0, b1]'''\n:::::::: \u00a0\u00a0 or equally as:\n::::::::: '''[b1, b0]'''\n\n\nGiven two ranges, the act of consolidation between them compares the two ranges:\n* \u00a0 If one range covers all of the other then the result is that encompassing range.\n* \u00a0 If the ranges touch or intersect then the result is \u00a0 ''one'' \u00a0 new single range covering the overlapping ranges.\n* \u00a0 Otherwise the act of consolidation is to return the two non-touching ranges.\n\n\nGiven \u00a0 '''N''' \u00a0 ranges where \u00a0 '''N > 2''' \u00a0 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 \u00a0 '''N < 2''' \u00a0 then range consolidation has no strict meaning and the input can be returned. \n\n\n;Example 1:\n: \u00a0 Given the two ranges \u00a0 '''[1, 2.5]''' \u00a0 and \u00a0 '''[3, 4.2]''' \u00a0 then \n: \u00a0 there is no common region between the ranges and the result is the same as the input.\n\n\n;Example 2:\n: \u00a0 Given the two ranges \u00a0 '''[1, 2.5]''' \u00a0 and \u00a0 '''[1.8, 4.7]''' \u00a0 then \n: \u00a0 there is : \u00a0 an overlap \u00a0 '''[2.5, 1.8]''' \u00a0 between the ranges and \n: \u00a0 the result is the single range \u00a0 '''[1, 4.7]'''. \n: \u00a0 Note that order of bounds in a range is not (yet) stated.\n\n\n;Example 3:\n: \u00a0 Given the two ranges \u00a0 '''[6.1, 7.2]''' \u00a0 and \u00a0 '''[7.2, 8.3]''' \u00a0 then \n: \u00a0 they touch at \u00a0 '''7.2''' \u00a0 and \n: \u00a0 the result is the single range \u00a0 '''[6.1, 8.3]'''. \n\n\n;Example 4:\n: \u00a0 Given the three ranges \u00a0 '''[1, 2]''' \u00a0 and \u00a0 '''[4, 8]''' \u00a0 and \u00a0 '''[2, 5]''' \n: \u00a0 then there is no intersection of the ranges \u00a0 '''[1, 2]''' \u00a0 and \u00a0 '''[4, 8]''' \n: \u00a0 but the ranges \u00a0 '''[1, 2]''' \u00a0 and \u00a0 '''[2, 5]''' \u00a0 overlap and \n: \u00a0 consolidate to produce the range \u00a0 '''[1, 5]'''. \n: \u00a0 This range, in turn, overlaps the other range \u00a0 '''[4, 8]''', \u00a0 and \n: \u00a0 so consolidates to the final output of the single range \u00a0 '''[1, 8]'''.\n\n\n;Task:\nLet a normalized range display show the smaller bound to the left; \u00a0 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": "(() => {\n 'use strict';\n\n const main = () => {\n\n // consolidated :: [(Float, Float)] -> [(Float, Float)]\n const consolidated = xs =>\n foldl((abetc, xy) =>\n 0 < abetc.length ? (() => {\n const\n etc = abetc.slice(1),\n [a, b] = abetc[0],\n [x, y] = xy;\n\n return y >= b ? (\n cons(xy, etc)\n ) : y >= a ? (\n cons([x, b], etc)\n ) : cons(xy, abetc);\n })() : [xy],\n [],\n sortBy(flip(comparing(fst)),\n map(([a, b]) => a < b ? (\n [a, b]\n ) : [b, a],\n xs\n )\n )\n );\n\n // TEST -------------------------------------------\n console.log(\n tabulated(\n 'Range consolidations:',\n JSON.stringify,\n JSON.stringify,\n consolidated,\n [\n [\n [1.1, 2.2]\n ],\n [\n [6.1, 7.2],\n [7.2, 8.3]\n ],\n [\n [4, 3],\n [2, 1]\n ],\n [\n [4, 3],\n [2, 1],\n [-1, -2],\n [3.9, 10]\n ],\n [\n [1, 3],\n [-6, -1],\n [-4, -5],\n [8, 2],\n [-6, -6]\n ]\n ]\n )\n );\n };\n\n // GENERIC FUNCTIONS ----------------------------\n\n // comparing :: (a -> b) -> (a -> a -> Ordering)\n const comparing = f =>\n (x, y) => {\n const\n a = f(x),\n b = f(y);\n return a < b ? -1 : (a > b ? 1 : 0);\n };\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (f, g) => x => f(g(x));\n\n // cons :: a -> [a] -> [a]\n const cons = (x, xs) => [x].concat(xs);\n\n // flip :: (a -> b -> c) -> b -> a -> c\n const flip = f =>\n 1 < f.length ? (\n (a, b) => f(b, a)\n ) : (x => y => f(y)(x));\n\n // foldl :: (a -> b -> a) -> a -> [b] -> a\n const foldl = (f, a, xs) => xs.reduce(f, a);\n\n // fst :: (a, b) -> a\n const fst = tpl => tpl[0];\n\n // justifyRight :: Int -> Char -> String -> String\n const justifyRight = (n, cFiller, s) =>\n n > s.length ? (\n s.padStart(n, cFiller)\n ) : s;\n\n // Returns Infinity over objects without finite length.\n // This enables zip and zipWith to choose the shorter\n // argument when one is non-finite, like cycle, repeat etc\n\n // length :: [a] -> Int\n const length = xs =>\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) =>\n (Array.isArray(xs) ? (\n xs\n ) : xs.split('')).map(f);\n\n // maximumBy :: (a -> a -> Ordering) -> [a] -> a\n const maximumBy = (f, xs) =>\n 0 < xs.length ? (\n xs.slice(1)\n .reduce((a, x) => 0 < f(x, a) ? x : a, xs[0])\n ) : undefined;\n\n // sortBy :: (a -> a -> Ordering) -> [a] -> [a]\n const sortBy = (f, xs) =>\n xs.slice()\n .sort(f);\n\n // tabulated :: String -> (a -> String) ->\n // (b -> String) ->\n // (a -> b) -> [a] -> String\n const tabulated = (s, xShow, fxShow, f, xs) => {\n // Heading -> x display function ->\n // fx display function ->\n // f -> values -> tabular string\n const\n ys = map(xShow, xs),\n w = maximumBy(comparing(x => x.length), ys).length,\n rows = zipWith(\n (a, b) => justifyRight(w, ' ', a) + ' -> ' + b,\n ys,\n map(compose(fxShow, f), xs)\n );\n return s + '\\n' + unlines(rows);\n };\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = (n, xs) =>\n 'GeneratorFunction' !== xs.constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = (f, xs, ys) => {\n const\n lng = Math.min(length(xs), length(ys)),\n as = take(lng, xs),\n bs = take(lng, ys);\n return Array.from({\n length: lng\n }, (_, i) => f(as[i], bs[i], i));\n };\n\n // MAIN ---\n return main();\n})();"} +{"title": "Range consolidation", "language": "Python", "task": "Define a range of numbers \u00a0 '''R''', \u00a0 with bounds \u00a0 '''b0''' \u00a0 and \u00a0 '''b1''' \u00a0 covering all numbers ''between and including both bounds''. \n\n\nThat range can be shown as:\n::::::::: '''[b0, b1]'''\n:::::::: \u00a0\u00a0 or equally as:\n::::::::: '''[b1, b0]'''\n\n\nGiven two ranges, the act of consolidation between them compares the two ranges:\n* \u00a0 If one range covers all of the other then the result is that encompassing range.\n* \u00a0 If the ranges touch or intersect then the result is \u00a0 ''one'' \u00a0 new single range covering the overlapping ranges.\n* \u00a0 Otherwise the act of consolidation is to return the two non-touching ranges.\n\n\nGiven \u00a0 '''N''' \u00a0 ranges where \u00a0 '''N > 2''' \u00a0 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 \u00a0 '''N < 2''' \u00a0 then range consolidation has no strict meaning and the input can be returned. \n\n\n;Example 1:\n: \u00a0 Given the two ranges \u00a0 '''[1, 2.5]''' \u00a0 and \u00a0 '''[3, 4.2]''' \u00a0 then \n: \u00a0 there is no common region between the ranges and the result is the same as the input.\n\n\n;Example 2:\n: \u00a0 Given the two ranges \u00a0 '''[1, 2.5]''' \u00a0 and \u00a0 '''[1.8, 4.7]''' \u00a0 then \n: \u00a0 there is : \u00a0 an overlap \u00a0 '''[2.5, 1.8]''' \u00a0 between the ranges and \n: \u00a0 the result is the single range \u00a0 '''[1, 4.7]'''. \n: \u00a0 Note that order of bounds in a range is not (yet) stated.\n\n\n;Example 3:\n: \u00a0 Given the two ranges \u00a0 '''[6.1, 7.2]''' \u00a0 and \u00a0 '''[7.2, 8.3]''' \u00a0 then \n: \u00a0 they touch at \u00a0 '''7.2''' \u00a0 and \n: \u00a0 the result is the single range \u00a0 '''[6.1, 8.3]'''. \n\n\n;Example 4:\n: \u00a0 Given the three ranges \u00a0 '''[1, 2]''' \u00a0 and \u00a0 '''[4, 8]''' \u00a0 and \u00a0 '''[2, 5]''' \n: \u00a0 then there is no intersection of the ranges \u00a0 '''[1, 2]''' \u00a0 and \u00a0 '''[4, 8]''' \n: \u00a0 but the ranges \u00a0 '''[1, 2]''' \u00a0 and \u00a0 '''[2, 5]''' \u00a0 overlap and \n: \u00a0 consolidate to produce the range \u00a0 '''[1, 5]'''. \n: \u00a0 This range, in turn, overlaps the other range \u00a0 '''[4, 8]''', \u00a0 and \n: \u00a0 so consolidates to the final output of the single range \u00a0 '''[1, 8]'''.\n\n\n;Task:\nLet a normalized range display show the smaller bound to the left; \u00a0 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": "def normalize(s):\n return sorted(sorted(bounds) for bounds in s if bounds)\n\ndef consolidate(ranges):\n norm = normalize(ranges)\n for i, r1 in enumerate(norm):\n if r1:\n for r2 in norm[i+1:]:\n if r2 and r1[-1] >= r2[0]: # intersect?\n r1[:] = [r1[0], max(r1[-1], r2[-1])]\n r2.clear()\n return [rnge for rnge in norm if rnge]\n\nif __name__ == '__main__':\n for s in [\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]],\n ]:\n print(f\"{str(s)[1:-1]} => {str(consolidate(s))[1:-1]}\")\n"} +{"title": "Range expansion", "language": "C", "task": ";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* \u00a0 [[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, \u2147)) 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 expansion", "language": "JavaScript", "task": ";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* \u00a0 [[Range extraction]]\n\n", "solution": "#!/usr/bin/env js\n\nfunction main() {\n print(rangeExpand('-6,-3--1,3-5,7-11,14,15,17-20'));\n}\n\nfunction rangeExpand(rangeExpr) {\n \n function getFactors(term) {\n var matches = term.match(/(-?[0-9]+)-(-?[0-9]+)/);\n if (!matches) return {first:Number(term)};\n return {first:Number(matches[1]), last:Number(matches[2])};\n }\n \n function expandTerm(term) {\n var factors = getFactors(term);\n if (factors.length < 2) return [factors.first];\n var range = [];\n for (var n = factors.first; n <= factors.last; n++) {\n range.push(n);\n }\n return range;\n }\n \n var result = [];\n var terms = rangeExpr.split(/,/);\n for (var t in terms) {\n result = result.concat(expandTerm(terms[t]));\n }\n \n return result;\n}\n\nmain();\n"} +{"title": "Range expansion", "language": "Python", "task": ";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* \u00a0 [[Range extraction]]\n\n", "solution": "def rangeexpand(txt):\n lst = []\n for r in txt.split(','):\n if '-' in r[1:]:\n r0, r1 = r[1:].split('-', 1)\n lst += range(int(r[0] + r0), int(r1) + 1)\n else:\n lst.append(int(r))\n return lst\n\nprint(rangeexpand('-6,-3--1,3-5,7-11,14,15,17-20'))"} +{"title": "Range expansion", "language": "Python 3.7", "task": ";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* \u00a0 [[Range extraction]]\n\n", "solution": "'''Range expansion'''\n\nfrom functools import (reduce)\n\n\n# ------------------- EXPANSION FUNCTION -------------------\n\n# rangeExpansion :: String -> [Int]\ndef rangeExpansion(s):\n '''List of integers expanded from a\n comma-delimited string of individual\n numbers and hyphenated ranges.\n '''\n def go(a, x):\n tpl = breakOn('-')(x[1:])\n r = tpl[1]\n return a + (\n [int(x)] if not r\n else enumFromTo(int(x[0] + tpl[0]))(\n int(r[1:])\n )\n )\n return reduce(go, s.split(','), [])\n\n\n# -------------------------- TEST --------------------------\ndef main():\n '''Expansion test'''\n\n print(\n fTable(__doc__ + ':')(\n lambda x: \"\\n'\" + str(x) + \"'\"\n )(lambda x: '\\n\\n\\t' + showList(x))(\n rangeExpansion\n )([\n '-6,-3--1,3-5,7-11,14,15,17-20'\n ])\n )\n\n\n# ------------------- GENERIC FUNCTIONS --------------------\n\n# breakOn :: String -> String -> (String, String)\ndef breakOn(needle):\n '''A tuple of:\n 1. the prefix of haystack before needle,\n 2. the remainder of haystack, starting\n with needle.\n '''\n def go(haystack):\n xs = haystack.split(needle)\n return (xs[0], haystack[len(xs[0]):]) if (\n 1 < len(xs)\n ) else (haystack, '')\n return lambda haystack: go(haystack) if (\n needle\n ) else None\n\n\n# enumFromTo :: Int -> Int -> [Int]\ndef enumFromTo(m):\n '''Enumeration of integer values [m..n]\n '''\n return lambda n: list(range(m, 1 + n))\n\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> \n fx display function -> f -> xs -> tabular string.\n '''\n def gox(xShow):\n def gofx(fxShow):\n def gof(f):\n def goxs(xs):\n ys = [xShow(x) for x in xs]\n w = max(map(len, ys))\n\n def arrowed(x, y):\n return y.rjust(w, ' ') + ' -> ' + (\n fxShow(f(x))\n )\n return s + '\\n' + '\\n'.join(\n map(arrowed, xs, ys)\n )\n return goxs\n return gof\n return gofx\n return gox\n\n\n# showList :: [a] -> String\ndef showList(xs):\n '''Stringification of a list.\n '''\n return '[' + ','.join(str(x) for x in xs) + ']'\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} +{"title": "Range extraction", "language": "C", "task": ";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* \u00a0 [[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": "Range extraction", "language": "JavaScript", "task": ";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* \u00a0 [[Range expansion]]\n\n", "solution": "(function () {\n 'use strict';\n\n // rangeFormat :: [Int] -> String\n var rangeFormat = function (xs) {\n return splitBy(function (a, b) {\n return b - a > 1;\n }, xs)\n .map(rangeString)\n .join(',');\n };\n\n // rangeString :: [Int] -> String\n var rangeString = function (xs) {\n return xs.length > 2 ? [head(xs), last(xs)].map(show)\n .join('-') : xs.join(',');\n };\n\n // GENERIC FUNCTIONS\n\n // Splitting not on a delimiter, but whenever the relationship between\n // two consecutive items matches a supplied predicate function\n\n // splitBy :: (a -> a -> Bool) -> [a] -> [[a]]\n var splitBy = function (f, xs) {\n if (xs.length < 2) return [xs];\n var h = head(xs),\n lstParts = xs.slice(1)\n .reduce(function (a, x) {\n var acc = a[0],\n active = a[1],\n prev = a[2];\n\n return f(prev, x) ? (\n [acc.concat([active]), [x], x]\n ) : [acc, active.concat(x), x];\n }, [\n [],\n [h], h\n ]);\n return lstParts[0].concat([lstParts[1]]);\n };\n\n // head :: [a] -> a\n var head = function (xs) {\n return xs.length ? xs[0] : undefined;\n };\n\n // last :: [a] -> a\n var last = function (xs) {\n return xs.length ? xs.slice(-1)[0] : undefined;\n };\n\n // show :: a -> String\n var show = function (x) {\n return JSON.stringify(x);\n };\n\n // TEST\n return rangeFormat([0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16,\n 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32,\n 33, 35, 36, 37, 38, 39\n ]);\n})();"} +{"title": "Range extraction", "language": "Python", "task": ";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* \u00a0 [[Range expansion]]\n\n", "solution": "def range_extract(lst):\n 'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints'\n lenlst = len(lst)\n i = 0\n while i< lenlst:\n low = lst[i]\n while i = 2:\n yield (low, hi)\n elif hi - low == 1:\n yield (low,)\n yield (hi,)\n else:\n yield (low,)\n i += 1\n\ndef printr(ranges):\n print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r)\n for r in ranges ) )\n\nif __name__ == '__main__':\n for lst in [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7,\n 8, 9, 10, 11, 14, 15, 17, 18, 19, 20],\n [0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22,\n 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]:\n #print(list(range_extract(lst)))\n printr(range_extract(lst))"} +{"title": "Rate counter", "language": "C", "task": "Of 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": "Rate counter", "language": "JavaScript", "task": "Of 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": "function millis() { // Gets current time in milliseconds.\n return (new Date()).getTime();\n}\n\n/* Executes function 'func' n times, returns array of execution times. */\nfunction benchmark(n, func, args) {\n var times = [];\n for (var i=0; i\n"} +{"title": "Rate counter", "language": "Python", "task": "Of 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": "import subprocess\nimport time\n\nclass Tlogger(object):\n def __init__(self):\n self.counts = 0\n self.tottime = 0.0\n self.laststart = 0.0\n self.lastreport = time.time()\n\n def logstart(self):\n self.laststart = time.time()\n\n def logend(self):\n self.counts +=1\n self.tottime += (time.time()-self.laststart)\n if (time.time()-self.lastreport)>5.0: # report once every 5 seconds\n self.report()\n\n def report(self):\n if ( self.counts > 4*self.tottime):\n print \"Subtask execution rate: %f times/second\"% (self.counts/self.tottime);\n else:\n print \"Average execution time: %f seconds\"%(self.tottime/self.counts);\n self.lastreport = time.time()\n\n\ndef taskTimer( n, subproc_args ):\n logger = Tlogger()\n\n for x in range(n):\n logger.logstart()\n p = subprocess.Popen(subproc_args)\n p.wait()\n logger.logend()\n logger.report()\n\n\nimport timeit\nimport sys\n\ndef main( ):\n\n # for accurate timing of code segments \n s = \"\"\"j = [4*n for n in range(50)]\"\"\"\n timer = timeit.Timer(s)\n rzlts = timer.repeat(5, 5000)\n for t in rzlts:\n print \"Time for 5000 executions of statement = \",t\n \n # subprocess execution timing\n print \"#times:\",sys.argv[1]\n print \"Command:\",sys.argv[2:]\n print \"\"\n for k in range(3):\n taskTimer( int(sys.argv[1]), sys.argv[2:])\n\nmain()"} +{"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, \u00a0 and store it in a variable or in memory \u00a0 (for potential future use within the program if the code were to become embedded). \n\nIf the file does not contain seven lines, \u00a0 or the seventh line is empty, \u00a0 or too big to be retrieved, \u00a0 output an appropriate message. \n\nIf no special semantics are available for obtaining the required line, \u00a0 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, \u00a0 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": "Read a specific line from a file", "language": "Python", "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, \u00a0 and store it in a variable or in memory \u00a0 (for potential future use within the program if the code were to become embedded). \n\nIf the file does not contain seven lines, \u00a0 or the seventh line is empty, \u00a0 or too big to be retrieved, \u00a0 output an appropriate message. \n\nIf no special semantics are available for obtaining the required line, \u00a0 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, \u00a0 it is permissible to output the extracted data to standard output.\n\n", "solution": "from itertools import islice\n\nwith open('xxx.txt') as f:\n try:\n line = next(islice(f, 6, 7))\n except StopIteration:\n print('Not 7 lines in file')"} +{"title": "Recaman's sequence", "language": "C", "task": "The '''Recam\u00e1n's sequence''' generates Natural numbers.\n\nStarting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is '''both''' positive ''and'' has not been previousely generated.\n\nIf the conditions ''don't'' hold then a(n) = a(n-1) + n.\n\n\n;Task:\n# Generate and show here the first 15 members of the sequence.\n# Find and show here, the first duplicated number in the sequence.\n# '''Optionally''': Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated.\n\n\n;References:\n* [https://oeis.org/A005132 A005132], The On-Line Encyclopedia of Integer Sequences.\n* [https://www.youtube.com/watch?v=FGC5TdIiT9U The Slightly Spooky Recam\u00e1n Sequence], Numberphile video.\n* [https://en.wikipedia.org/wiki/Recam%C3%A1n%27s_sequence Recam\u00e1n's sequence], on Wikipedia.\n\n", "solution": "#include \n#include \n#include \n\ntypedef int bool;\n\nint main() {\n int i, n, k = 0, next, *a;\n bool foundDup = FALSE;\n gboolean alreadyUsed;\n GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal);\n GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equal);\n a = malloc(400000 * sizeof(int));\n a[0] = 0;\n g_hash_table_add(used, GINT_TO_POINTER(0));\n g_hash_table_add(used1000, GINT_TO_POINTER(0));\n\n for (n = 1; n <= 15 || !foundDup || k < 1001; ++n) {\n next = a[n - 1] - n;\n if (next < 1 || g_hash_table_contains(used, GINT_TO_POINTER(next))) {\n next += 2 * n;\n }\n alreadyUsed = g_hash_table_contains(used, GINT_TO_POINTER(next));\n a[n] = next;\n\n if (!alreadyUsed) {\n g_hash_table_add(used, GINT_TO_POINTER(next));\n if (next >= 0 && next <= 1000) {\n g_hash_table_add(used1000, GINT_TO_POINTER(next));\n }\n }\n\n if (n == 14) {\n printf(\"The first 15 terms of the Recaman's sequence are: \");\n printf(\"[\");\n for (i = 0; i < 15; ++i) printf(\"%d \", a[i]);\n printf(\"\\b]\\n\");\n }\n\n if (!foundDup && alreadyUsed) {\n printf(\"The first duplicated term is a[%d] = %d\\n\", n, next);\n foundDup = TRUE;\n }\n k = g_hash_table_size(used1000);\n\n if (k == 1001) {\n printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n);\n }\n }\n g_hash_table_destroy(used);\n g_hash_table_destroy(used1000);\n free(a);\n return 0;\n}"} +{"title": "Recaman's sequence", "language": "JavaScript", "task": "The '''Recam\u00e1n's sequence''' generates Natural numbers.\n\nStarting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is '''both''' positive ''and'' has not been previousely generated.\n\nIf the conditions ''don't'' hold then a(n) = a(n-1) + n.\n\n\n;Task:\n# Generate and show here the first 15 members of the sequence.\n# Find and show here, the first duplicated number in the sequence.\n# '''Optionally''': Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated.\n\n\n;References:\n* [https://oeis.org/A005132 A005132], The On-Line Encyclopedia of Integer Sequences.\n* [https://www.youtube.com/watch?v=FGC5TdIiT9U The Slightly Spooky Recam\u00e1n Sequence], Numberphile video.\n* [https://en.wikipedia.org/wiki/Recam%C3%A1n%27s_sequence Recam\u00e1n's sequence], on Wikipedia.\n\n", "solution": "(() => {\n const main = () => {\n\n console.log(\n 'First 15 Recaman:\\n' +\n recamanUpto(i => 15 === i)\n );\n\n console.log(\n '\\n\\nFirst duplicated Recaman:\\n' +\n last(recamanUpto(\n (_, set, rs) => set.size !== rs.length\n ))\n );\n\n const setK = new Set(enumFromTo(0, 1000));\n console.log(\n '\\n\\nNumber of Recaman terms needed to generate' +\n '\\nall integers from [0..1000]:\\n' +\n (recamanUpto(\n (_, setR) => isSubSetOf(setK, setR)\n ).length - 1)\n );\n };\n\n // RECAMAN --------------------------------------------\n\n // recamanUpto :: (Int -> Set Int > [Int] -> Bool) -> [Int]\n const recamanUpto = p => {\n let\n i = 1,\n r = 0, // First term of series\n rs = [r];\n const seen = new Set(rs);\n while (!p(i, seen, rs)) {\n r = nextR(seen, i, r);\n seen.add(r);\n rs.push(r);\n i++;\n }\n return rs;\n }\n\n // Next Recaman number.\n\n // nextR :: Set Int -> Int -> Int\n const nextR = (seen, i, n) => {\n const back = n - i;\n return (0 > back || seen.has(back)) ? (\n n + i\n ) : back;\n };\n\n // GENERIC --------------------------------------------\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = (m, n) =>\n m <= n ? iterateUntil(\n x => n <= x,\n x => 1 + x,\n m\n ) : [];\n\n // isSubsetOf :: Ord a => Set a -> Set a -> Bool\n const isSubSetOf = (a, b) => {\n for (let x of a) {\n if (!b.has(x)) return false;\n }\n return true;\n };\n\n // iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a]\n const iterateUntil = (p, f, x) => {\n const vs = [x];\n let h = x;\n while (!p(h))(h = f(h), vs.push(h));\n return vs;\n };\n\n // last :: [a] -> a\n const last = xs =>\n 0 < xs.length ? xs.slice(-1)[0] : undefined;\n\n // MAIN ------------------------------------------------\n return main();\n})();"} +{"title": "Recaman's sequence", "language": "Python", "task": "The '''Recam\u00e1n's sequence''' generates Natural numbers.\n\nStarting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is '''both''' positive ''and'' has not been previousely generated.\n\nIf the conditions ''don't'' hold then a(n) = a(n-1) + n.\n\n\n;Task:\n# Generate and show here the first 15 members of the sequence.\n# Find and show here, the first duplicated number in the sequence.\n# '''Optionally''': Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated.\n\n\n;References:\n* [https://oeis.org/A005132 A005132], The On-Line Encyclopedia of Integer Sequences.\n* [https://www.youtube.com/watch?v=FGC5TdIiT9U The Slightly Spooky Recam\u00e1n Sequence], Numberphile video.\n* [https://en.wikipedia.org/wiki/Recam%C3%A1n%27s_sequence Recam\u00e1n's sequence], on Wikipedia.\n\n", "solution": "from itertools import islice\n\nclass Recamans():\n \"Recam\u00e1n's sequence generator callable class\"\n def __init__(self):\n self.a = None # Set of results so far\n self.n = None # n'th term (counting from zero)\n \n def __call__(self):\n \"Recam\u00e1n's sequence generator\"\n nxt = 0\n a, n = {nxt}, 0\n self.a = a\n self.n = n\n yield nxt\n while True:\n an1, n = nxt, n + 1\n nxt = an1 - n\n if nxt < 0 or nxt in a:\n nxt = an1 + n\n a.add(nxt)\n self.n = n\n yield nxt\n\nif __name__ == '__main__':\n recamans = Recamans()\n print(\"First fifteen members of Recamans sequence:\", \n list(islice(recamans(), 15)))\n\n so_far = set()\n for term in recamans():\n if term in so_far:\n print(f\"First duplicate number in series is: a({recamans.n}) = {term}\")\n break\n so_far.add(term)\n \n n = 1_000\n setn = set(range(n + 1)) # The target set of numbers to be covered\n for _ in recamans():\n if setn.issubset(recamans.a):\n print(f\"Range 0 ..{n} is covered by terms up to a({recamans.n})\")\n break"} +{"title": "Remove lines from a file", "language": "C", "task": ";Task:\nRemove 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": "Remove lines from a file", "language": "Python", "task": ";Task:\nRemove 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": "#!/usr/bin/env python\n\nimport fileinput, sys\n\nfname, start, count = sys.argv[1:4]\nstart, count = int(start), int(count)\n\nfor line in fileinput.input(fname, inplace=1, backup='.orig'):\n if start <= fileinput.lineno() < start + count:\n pass\n else:\n print line.rstrip(\"\\n\")\nfileinput.close()"} +{"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. \u00a0 (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": "\n#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": "Rep-string", "language": "JavaScript", "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. \u00a0 (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": "(() => {\n 'use strict';\n\n const main = () => {\n\n // REP-CYCLES -------------------------------------\n\n // repCycles :: String -> [String]\n const repCycles = s => {\n const n = s.length;\n return filter(\n x => s === take(n, cycle(x)).join(''),\n tail(inits(take(quot(n, 2), s)))\n );\n };\n\n // TEST -------------------------------------------\n console.log(fTable(\n 'Longest cycles:\\n',\n str,\n xs => 0 < xs.length ? concat(last(xs)) : '(none)',\n repCycles,\n [\n '1001110011',\n '1110111011',\n '0010010010',\n '1010101010',\n '1111111111',\n '0100101101',\n '0100100',\n '101',\n '11',\n '00',\n '1'\n ]\n ));\n };\n\n // GENERIC FUNCTIONS ----------------------------------\n\n // concat :: [[a]] -> [a]\n // concat :: [String] -> String\n const concat = xs =>\n 0 < xs.length ? (() => {\n const unit = 'string' !== typeof xs[0] ? (\n []\n ) : '';\n return unit.concat.apply(unit, xs);\n })() : [];\n\n // cycle :: [a] -> Generator [a]\n function* cycle(xs) {\n const lng = xs.length;\n let i = 0;\n while (true) {\n yield(xs[i])\n i = (1 + i) % lng;\n }\n }\n\n // filter :: (a -> Bool) -> [a] -> [a]\n const filter = (f, xs) => xs.filter(f);\n\n // fTable :: String -> (a -> String) -> \n // (b -> String) -> (a -> b) -> [a] -> String\n const fTable = (s, xShow, fxShow, f, xs) => {\n // Heading -> x display function ->\n // fx display function ->\n // f -> values -> tabular string\n const\n ys = xs.map(xShow),\n w = Math.max(...ys.map(length));\n return s + '\\n' + zipWith(\n (a, b) => a.padStart(w, ' ') + ' -> ' + b,\n ys,\n xs.map(x => fxShow(f(x)))\n ).join('\\n');\n };\n\n // inits([1, 2, 3]) -> [[], [1], [1, 2], [1, 2, 3]\n // inits('abc') -> [\"\", \"a\", \"ab\", \"abc\"]\n\n // inits :: [a] -> [[a]]\n // inits :: String -> [String]\n const inits = xs => [\n []\n ]\n .concat(('string' === typeof xs ? xs.split('') : xs)\n .map((_, i, lst) => lst.slice(0, 1 + i)));\n\n // last :: [a] -> a\n const last = xs =>\n 0 < xs.length ? xs.slice(-1)[0] : undefined;\n\n // Returns Infinity over objects without finite length.\n // This enables zip and zipWith to choose the shorter\n // argument when one is non-finite, like cycle, repeat etc\n\n // length :: [a] -> Int\n const length = xs =>\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n // quot :: Int -> Int -> Int\n const quot = (n, m) => Math.floor(n / m);\n\n // str :: a -> String\n const str = x => x.toString();\n\n // tail :: [a] -> [a]\n const tail = xs => 0 < xs.length ? xs.slice(1) : [];\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = (n, xs) =>\n 'GeneratorFunction' !== xs.constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // Use of `take` and `length` here allows zipping with non-finite lists\n // i.e. generators like cycle, repeat, iterate.\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = (f, xs, ys) => {\n const\n lng = Math.min(length(xs), length(ys)),\n as = take(lng, xs),\n bs = take(lng, ys);\n return Array.from({\n length: lng\n }, (_, i) => f(as[i], bs[i], i));\n };\n\n // MAIN ---\n return main();\n})();"} +{"title": "Rep-string", "language": "Python", "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. \u00a0 (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": "def is_repeated(text):\n 'check if the first part of the string is repeated throughout the string'\n for x in range(len(text)//2, 0, -1):\n if text.startswith(text[x:]): return x\n return 0\n\nmatchstr = \"\"\"\\\n1001110011\n1110111011\n0010010010\n1010101010\n1111111111\n0100101101\n0100100\n101\n11\n00\n1\n\"\"\"\nfor line in matchstr.split():\n ln = is_repeated(line)\n print('%r has a repetition length of %i i.e. %s' \n % (line, ln, repr(line[:ln]) if ln else '*not* a rep-string'))"} +{"title": "Repeat", "language": "C", "task": ";Task:\nWrite 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": "Repeat", "language": "Python", "task": ";Task:\nWrite 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": "#!/usr/bin/python\ndef repeat(f,n):\n for i in range(n):\n f();\n\ndef procedure():\n print(\"Example\");\n\nrepeat(procedure,3); #prints \"Example\" (without quotes) three times, separated by newlines."} +{"title": "Repeat", "language": "Python 3.7", "task": ";Task:\nWrite 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": "'''Application of a given function, repeated N times'''\n\nfrom itertools import repeat\nfrom functools import reduce\nfrom inspect import getsource\n\n\n# applyN :: Int -> (a -> a) -> a -> a\ndef applyN(n):\n '''n compounding applications of the supplied\n function f. Equivalent to Church numeral n.\n '''\n def go(f):\n return lambda x: reduce(\n lambda a, g: g(a), repeat(f, n), x\n )\n return lambda f: go(f)\n\n\n# MAIN ----------------------------------------------------\ndef main():\n '''Tests - compounding repetition\n of function application.\n '''\n def f(x):\n return x + 'Example\\n'\n\n def g(x):\n return 2 * x\n\n def h(x):\n return 1.05 * x\n\n print(\n fTable(__doc__ + ':')(\n lambda fx: '\\nRepeated * 3:\\n (' + (\n getsource(fst(fx)).strip() + ')(' +\n repr(snd(fx)) + ')'\n )\n )(str)(\n liftA2(applyN(3))(fst)(snd)\n )([(f, '\\n'), (g, 1), (h, 100)])\n )\n\n\n# GENERIC -------------------------------------------------\n\n# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n '''Right to left function composition.'''\n return lambda f: lambda x: g(f(x))\n\n\n# fst :: (a, b) -> a\ndef fst(tpl):\n '''First member of a pair.'''\n return tpl[0]\n\n\n# liftA2 :: (a0 -> b -> c) -> (a -> a0) -> (a -> b) -> a -> c\ndef liftA2(op):\n '''Lift a binary function to a composition\n over two other functions.\n liftA2 (*) (+ 2) (+ 3) 7 == 90\n '''\n def go(f, g):\n return lambda x: op(\n f(x)\n )(g(x))\n return lambda f: lambda g: go(f, g)\n\n\n# snd :: (a, b) -> b\ndef snd(tpl):\n '''Second member of a pair.'''\n return tpl[1]\n\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\n '''\n def go(xShow, fxShow, f, xs):\n ys = [xShow(x) for x in xs]\n w = max(map(len, ys))\n return s + '\\n' + '\\n'.join(map(\n lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n xs, ys\n ))\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} +{"title": "Repunit primes", "language": "Python", "task": "portmanteau of the words \"repetition\" and \"unit\", with unit being \"unit value\"... or in laymans terms, '''1'''. So 1, 11, 111, 1111 & 11111 are all repunits.\n\nEvery standard integer base has repunits since every base has the digit 1. This task involves finding the repunits in different bases that are prime.\n\nIn base two, the repunits 11, 111, 11111, 1111111, etc. are prime. (These correspond to the Mersenne primes.) \n\nIn base three: 111, 1111111, 1111111111111, etc.\n\n''Repunit primes, by definition, are also [[circular primes]].''\n\nAny repunit in any base having a composite number of digits is necessarily composite. Only repunits (in any base) having a prime number of digits ''might'' be prime.\n\n\nRather than expanding the repunit out as a giant list of '''1'''s or converting to base 10, it is common to just list the ''number'' of '''1'''s in the repunit; effectively the digit count. The base two repunit primes listed above would be represented as: 2, 3, 5, 7, etc.\n\nMany of these sequences exist on OEIS, though they aren't specifically listed as \"repunit prime digits\" sequences. \n\nSome bases have very few repunit primes. Bases 4, 8, and likely 16 have only one. Base 9 has none at all. Bases above 16 may have repunit primes as well... but this task is getting large enough already.\n\n\n;Task\n\n* For bases 2 through 16, Find and show, here on this page, the repunit primes as digit counts, up to a limit of 1000.\n\n\n;Stretch\n\n* Increase the limit to 2700 (or as high as you have patience for.)\n\n\n;See also\n\n;* Wikipedia: Repunit primes\n;* OEIS:A000043 - Mersenne exponents: primes p such that 2^p - 1 is prime. Then 2^p - 1 is called a Mersenne prime (base 2)\n;* OEIS:A028491 - Numbers k such that (3^k - 1)/2 is prime (base 3)\n;* OEIS:A004061 - Numbers n such that (5^n - 1)/4 is prime (base 5)\n;* OEIS:A004062 - Numbers n such that (6^n - 1)/5 is prime (base 6)\n;* OEIS:A004063 - Numbers k such that (7^k - 1)/6 is prime (base 7)\n;* OEIS:A004023 - Indices of prime repunits: numbers n such that 11...111 (with n 1's) = (10^n - 1)/9 is prime (base 10)\n;* OEIS:A005808 - Numbers k such that (11^k - 1)/10 is prime (base 11)\n;* OEIS:A004064 - Numbers n such that (12^n - 1)/11 is prime (base 12)\n;* OEIS:A016054 - Numbers n such that (13^n - 1)/12 is prime (base 13)\n;* OEIS:A006032 - Numbers k such that (14^k - 1)/13 is prime (base 14)\n;* OEIS:A006033 - Numbers n such that (15^n - 1)/14 is prime (base 15)\n;* Related task: Circular primes\n\n\n\n", "solution": "from sympy import isprime\nfor b in range(2, 17):\n print(b, [n for n in range(2, 1001) if isprime(n) and isprime(int('1'*n, base=b))])"} +{"title": "Resistor mesh", "language": "C", "task": "right\n\n;Task:\nGiven \u00a0 10\u00d710 \u00a0 grid nodes \u00a0 (as shown in the image) \u00a0 interconnected by \u00a0 1\u03a9 \u00a0 resistors as shown,\nfind the resistance between points \u00a0 '''A''' \u00a0 and \u00a0 '''B'''.\n\n\n;See also:\n* \u00a0 (humor, nerd sniping) \u00a0 [http://xkcd.com/356/ xkcd.com cartoon] (you can solve that for extra credits)\n* \u00a0 [https://www.paulinternet.nl/?page=resistors 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": "Resistor mesh", "language": "JavaScript", "task": "right\n\n;Task:\nGiven \u00a0 10\u00d710 \u00a0 grid nodes \u00a0 (as shown in the image) \u00a0 interconnected by \u00a0 1\u03a9 \u00a0 resistors as shown,\nfind the resistance between points \u00a0 '''A''' \u00a0 and \u00a0 '''B'''.\n\n\n;See also:\n* \u00a0 (humor, nerd sniping) \u00a0 [http://xkcd.com/356/ xkcd.com cartoon] (you can solve that for extra credits)\n* \u00a0 [https://www.paulinternet.nl/?page=resistors An article on how to calculate this and an implementation in Mathematica]\n\n", "solution": "\n// Vector addition, scalar multiplication & dot product:\nconst add = (u, v) => {let i = u.length; while(i--) u[i] += v[i]; return u;};\nconst sub = (u, v) => {let i = u.length; while(i--) u[i] -= v[i]; return u;};\nconst mul = (a, u) => {let i = u.length; while(i--) u[i] *= a; return u;};\nconst dot = (u, v) => {let s = 0, i = u.length; while(i--) s += u[i]*v[i]; return s;};\n\nconst W = 10, H = 10, A = 11, B = 67; \n\nfunction getAdjacent(node){ // Adjacency lists for square grid\n let list = [], x = node % W, y = Math.floor(node / W);\n if (x > 0) list.push(node - 1);\n if (y > 0) list.push(node - W);\n if (x < W - 1) list.push(node + 1);\n if (y < H - 1) list.push(node + W);\n return list;\n}\n\nfunction linOp(u){ // LHS of the linear equation\n let v = new Float64Array(W * H);\n for(let i = 0; i < v.length; i++){\n if ( i === A || i === B ) {\n v[i] = u[i];\n continue;\n }\n // For each node other then A, B calculate the net current flow:\n for(let j of getAdjacent(i)){\n v[i] += (j === A || j === B) ? u[i] : u[i] - u[j];\n }\n }\n return v;\n}\n\nfunction getRHS(phiA = 1, phiB = 0){ // RHS of the linear equation\n let b = new Float64Array(W * H);\n // Setting boundary conditions (electric potential at A and B):\n b[A] = phiA;\n b[B] = phiB;\n for(let j of getAdjacent(A)) b[j] = phiA;\n for(let j of getAdjacent(B)) b[j] = phiB;\n return b;\n}\n\nfunction init(phiA = 1, phiB = 0){ // initialize unknown vector\n let u = new Float64Array(W * H);\n u[A] = phiA;\n u[B] = phiB; \n return u;\n}\n\nfunction solveLinearSystem(err = 1e-20){ // conjugate gradient solver\n\n let b = getRHS();\n let u = init();\n let r = sub(linOp(u), b);\n let p = r;\n let e = dot(r,r);\n\n while(true){\n let Ap = linOp(p);\n let alpha = e / dot(p, Ap);\n u = sub(u, mul(alpha, p.slice()));\n r = sub(linOp(u), b); \n let e_new = dot(r,r);\n let beta = e_new / e;\n\n if(e_new < err) return u;\n\n e = e_new;\n p = add(r, mul(beta, p));\n }\n}\n\nfunction getResistance(u){\n let curr = 0;\n for(let j of getAdjacent(A)) curr += u[A] - u[j];\n return 1 / curr;\n}\n\nlet phi = solveLinearSystem();\nlet res = getResistance(phi);\nconsole.log(`R = ${res} Ohm`);\n"} +{"title": "Resistor mesh", "language": "Python", "task": "right\n\n;Task:\nGiven \u00a0 10\u00d710 \u00a0 grid nodes \u00a0 (as shown in the image) \u00a0 interconnected by \u00a0 1\u03a9 \u00a0 resistors as shown,\nfind the resistance between points \u00a0 '''A''' \u00a0 and \u00a0 '''B'''.\n\n\n;See also:\n* \u00a0 (humor, nerd sniping) \u00a0 [http://xkcd.com/356/ xkcd.com cartoon] (you can solve that for extra credits)\n* \u00a0 [https://www.paulinternet.nl/?page=resistors An article on how to calculate this and an implementation in Mathematica]\n\n", "solution": "DIFF_THRESHOLD = 1e-40\n\nclass Fixed:\n FREE = 0\n A = 1\n B = 2\n\nclass Node:\n __slots__ = [\"voltage\", \"fixed\"]\n def __init__(self, v=0.0, f=Fixed.FREE):\n self.voltage = v\n self.fixed = f\n\ndef set_boundary(m):\n m[1][1] = Node( 1.0, Fixed.A)\n m[6][7] = Node(-1.0, Fixed.B)\n\ndef calc_difference(m, d):\n h = len(m)\n w = len(m[0])\n total = 0.0\n\n for i in xrange(h):\n for j in xrange(w):\n v = 0.0\n n = 0\n if i != 0: v += m[i-1][j].voltage; n += 1\n if j != 0: v += m[i][j-1].voltage; n += 1\n if i < h-1: v += m[i+1][j].voltage; n += 1\n if j < w-1: v += m[i][j+1].voltage; n += 1\n v = m[i][j].voltage - v / n\n\n d[i][j].voltage = v\n if m[i][j].fixed == Fixed.FREE:\n total += v ** 2\n return total\n\ndef iter(m):\n h = len(m)\n w = len(m[0])\n difference = [[Node() for j in xrange(w)] for i in xrange(h)]\n\n while True:\n set_boundary(m) # Enforce boundary conditions.\n if calc_difference(m, difference) < DIFF_THRESHOLD:\n break\n for i, di in enumerate(difference):\n for j, dij in enumerate(di):\n m[i][j].voltage -= dij.voltage\n\n cur = [0.0] * 3\n for i, di in enumerate(difference):\n for j, dij in enumerate(di):\n cur[m[i][j].fixed] += (dij.voltage *\n (bool(i) + bool(j) + (i < h-1) + (j < w-1)))\n\n return (cur[Fixed.A] - cur[Fixed.B]) / 2.0\n\ndef main():\n w = h = 10\n mesh = [[Node() for j in xrange(w)] for i in xrange(h)]\n print \"R = %.16f\" % (2 / iter(mesh))\n\nmain()"} +{"title": "Reverse words in a string", "language": "C", "task": ";Task:\nReverse the order of all tokens in each of a number of strings and display the result; \u00a0 the order of characters within a token should not be modified.\n\n\n;Example:\nHey you, Bub! \u00a0 would be shown reversed as: \u00a0 Bub! you, Hey \n\n\nTokens are any non-space characters separated by spaces (formally, white-space); \u00a0 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. \u00a0 Multiple or superfluous spaces may be compressed into a single space.\n\nSome strings have no tokens, so an empty string \u00a0 (or one just containing spaces) \u00a0 would be the result.\n\n'''Display''' the strings in order \u00a0 (1st, 2nd, 3rd, \u00b7\u00b7\u00b7), \u00a0 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 \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n 1 \u2551 ---------- Ice and Fire ------------ \u2551\n 2 \u2551 \u2551 \u25c4\u2500\u2500\u2500 a blank line here.\n 3 \u2551 fire, in end will world the say Some \u2551\n 4 \u2551 ice. in say Some \u2551\n 5 \u2551 desire of tasted I've what From \u2551\n 6 \u2551 fire. favor who those with hold I \u2551\n 7 \u2551 \u2551 \u25c4\u2500\u2500\u2500 a blank line here.\n 8 \u2551 ... elided paragraph last ... \u2551\n 9 \u2551 \u2551 \u25c4\u2500\u2500\u2500 a blank line here.\n 10 \u2551 Frost Robert ----------------------- \u2551\n \u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d\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": "Reverse words in a string", "language": "JavaScript", "task": ";Task:\nReverse the order of all tokens in each of a number of strings and display the result; \u00a0 the order of characters within a token should not be modified.\n\n\n;Example:\nHey you, Bub! \u00a0 would be shown reversed as: \u00a0 Bub! you, Hey \n\n\nTokens are any non-space characters separated by spaces (formally, white-space); \u00a0 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. \u00a0 Multiple or superfluous spaces may be compressed into a single space.\n\nSome strings have no tokens, so an empty string \u00a0 (or one just containing spaces) \u00a0 would be the result.\n\n'''Display''' the strings in order \u00a0 (1st, 2nd, 3rd, \u00b7\u00b7\u00b7), \u00a0 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 \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n 1 \u2551 ---------- Ice and Fire ------------ \u2551\n 2 \u2551 \u2551 \u25c4\u2500\u2500\u2500 a blank line here.\n 3 \u2551 fire, in end will world the say Some \u2551\n 4 \u2551 ice. in say Some \u2551\n 5 \u2551 desire of tasted I've what From \u2551\n 6 \u2551 fire. favor who those with hold I \u2551\n 7 \u2551 \u2551 \u25c4\u2500\u2500\u2500 a blank line here.\n 8 \u2551 ... elided paragraph last ... \u2551\n 9 \u2551 \u2551 \u25c4\u2500\u2500\u2500 a blank line here.\n 10 \u2551 Frost Robert ----------------------- \u2551\n \u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d\n\n\n;Cf.\n* [[Phrase reversals]]\n\n", "solution": "var strReversed =\n\"---------- Ice and Fire ------------\\n\\\n\\n\\\nfire, in end will world the say Some\\n\\\nice. in say Some\\n\\\ndesire of tasted I've what From\\n\\\nfire. favor who those with hold I\\n\\\n\\n\\\n... elided paragraph last ...\\n\\\n\\n\\\nFrost Robert -----------------------\";\n \nfunction reverseString(s) {\n return s.split('\\n').map(\n function (line) {\n return line.split(/\\s/).reverse().join(' ');\n }\n ).join('\\n');\n}\n \nconsole.log(\n reverseString(strReversed)\n);"} +{"title": "Reverse words in a string", "language": "Python", "task": ";Task:\nReverse the order of all tokens in each of a number of strings and display the result; \u00a0 the order of characters within a token should not be modified.\n\n\n;Example:\nHey you, Bub! \u00a0 would be shown reversed as: \u00a0 Bub! you, Hey \n\n\nTokens are any non-space characters separated by spaces (formally, white-space); \u00a0 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. \u00a0 Multiple or superfluous spaces may be compressed into a single space.\n\nSome strings have no tokens, so an empty string \u00a0 (or one just containing spaces) \u00a0 would be the result.\n\n'''Display''' the strings in order \u00a0 (1st, 2nd, 3rd, \u00b7\u00b7\u00b7), \u00a0 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 \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n 1 \u2551 ---------- Ice and Fire ------------ \u2551\n 2 \u2551 \u2551 \u25c4\u2500\u2500\u2500 a blank line here.\n 3 \u2551 fire, in end will world the say Some \u2551\n 4 \u2551 ice. in say Some \u2551\n 5 \u2551 desire of tasted I've what From \u2551\n 6 \u2551 fire. favor who those with hold I \u2551\n 7 \u2551 \u2551 \u25c4\u2500\u2500\u2500 a blank line here.\n 8 \u2551 ... elided paragraph last ... \u2551\n 9 \u2551 \u2551 \u25c4\u2500\u2500\u2500 a blank line here.\n 10 \u2551 Frost Robert ----------------------- \u2551\n \u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d\n\n\n;Cf.\n* [[Phrase reversals]]\n\n", "solution": " text = '''\\\n---------- Ice and Fire ------------\n\nfire, in end will world the say Some\nice. in say Some\ndesire of tasted I've what From\nfire. favor who those with hold I\n\n... elided paragraph last ...\n\nFrost Robert -----------------------'''\n\nfor line in text.split('\\n'): print(' '.join(line.split()[::-1]))"} +{"title": "Roman numerals/Decode", "language": "C", "task": ";Task:\nCreate 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 \u00a0 (zeroes). \n\n'''1990''' is rendered as \u00a0 '''MCMXC''' \u00a0 \u00a0 (1000 = M, \u00a0 900 = CM, \u00a0 90 = XC) \u00a0 \u00a0 and \n'''2008''' is rendered as \u00a0 '''MMVIII''' \u00a0 \u00a0 \u00a0 (2000 = MM, \u00a0 8 = VIII).\n \nThe Roman numeral for '''1666''', \u00a0 '''MDCLXVI''', \u00a0 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/Decode", "language": "SpiderMonkey", "task": ";Task:\nCreate 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 \u00a0 (zeroes). \n\n'''1990''' is rendered as \u00a0 '''MCMXC''' \u00a0 \u00a0 (1000 = M, \u00a0 900 = CM, \u00a0 90 = XC) \u00a0 \u00a0 and \n'''2008''' is rendered as \u00a0 '''MMVIII''' \u00a0 \u00a0 \u00a0 (2000 = MM, \u00a0 8 = VIII).\n \nThe Roman numeral for '''1666''', \u00a0 '''MDCLXVI''', \u00a0 uses each letter in descending order.\n\n", "solution": "var Roman = {\n Values: [['CM', 900], ['CD', 400], ['XC', 90], ['XL', 40], ['IV', 4], \n ['IX', 9], ['V', 5], ['X', 10], ['L', 50], \n ['C', 100], ['M', 1000], ['I', 1], ['D', 500]],\n UnmappedStr : 'Q',\n parse: function(str) {\n var result = 0\n for (var i=0; i\n"} +{"title": "Roman numerals/Decode", "language": "Python", "task": ";Task:\nCreate 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 \u00a0 (zeroes). \n\n'''1990''' is rendered as \u00a0 '''MCMXC''' \u00a0 \u00a0 (1000 = M, \u00a0 900 = CM, \u00a0 90 = XC) \u00a0 \u00a0 and \n'''2008''' is rendered as \u00a0 '''MMVIII''' \u00a0 \u00a0 \u00a0 (2000 = MM, \u00a0 8 = VIII).\n \nThe Roman numeral for '''1666''', \u00a0 '''MDCLXVI''', \u00a0 uses each letter in descending order.\n\n", "solution": "_rdecode = dict(zip('MDCLXVI', (1000, 500, 100, 50, 10, 5, 1)))\n\ndef decode( roman ):\n result = 0\n for r, r1 in zip(roman, roman[1:]):\n rd, rd1 = _rdecode[r], _rdecode[r1]\n result += -rd if rd < rd1 else rd\n return result + _rdecode[roman[-1]]\n\nif __name__ == '__main__':\n for r in 'MCMXC MMVIII MDCLXVI'.split():\n print( r, decode(r) )"} +{"title": "Roman numerals/Encode", "language": "C", "task": "[[Category:String_manipulation]]\n\n;Task:\nCreate 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": "Roman numerals/Encode", "language": "JavaScript", "task": "[[Category:String_manipulation]]\n\n;Task:\nCreate 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": "(function () {\n 'use strict';\n\n\n // If the Roman is a string, pass any delimiters through\n\n // (Int | String) -> String\n function romanTranscription(a) {\n if (typeof a === 'string') {\n var ps = a.split(/\\d+/),\n dlm = ps.length > 1 ? ps[1] : undefined;\n\n return (dlm ? a.split(dlm)\n .map(function (x) {\n return Number(x);\n }) : [a])\n .map(roman)\n .join(dlm);\n } else return roman(a);\n }\n\n // roman :: Int -> String\n function roman(n) {\n return [[1000, \"M\"], [900, \"CM\"], [500, \"D\"], [400, \"CD\"], [100,\n \"C\"], [90, \"XC\"], [50, \"L\"], [40, \"XL\"], [10, \"X\"], [9,\n \"IX\"], [5, \"V\"], [4, \"IV\"], [1, \"I\"]]\n .reduce(function (a, lstPair) {\n var m = a.remainder,\n v = lstPair[0];\n\n return (v > m ? a : {\n remainder: m % v,\n roman: a.roman + Array(\n Math.floor(m / v) + 1\n )\n .join(lstPair[1])\n });\n }, {\n remainder: n,\n roman: ''\n }).roman; \n }\n\n // TEST\n\n return [2016, 1990, 2008, \"14.09.2015\", 2000, 1666].map(\n romanTranscription);\n\n})();"} +{"title": "Roman numerals/Encode", "language": "Python", "task": "[[Category:String_manipulation]]\n\n;Task:\nCreate 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": "def toRoman(n):\n res=''\t\t#converts int to str(Roman numeral)\n reg=n\t\t#using the numerals (M,D,C,L,X,V,I)\n if reg<4000:#no more than three repetitions\n while reg>=1000:\t#thousands up to MMM\n res+='M'\t\t#MAX is MMMCMXCIX\n reg-=1000\t\t\n if reg>=900:\t\t#nine hundreds in 900-999\n res+='CM'\n reg-=900\n if reg>=500:\t\t#five hudreds in 500-899\n res+='D'\n reg-=500\n if reg>=400:\t\t#four hundreds in 400-499\n res+='CD'\n reg-=400\n while reg>=100:\t\t#hundreds in 100-399\n res+='C'\n reg-=100\n if reg>=90:\t\t\t#nine tens in 90-99\n res+='XC'\n reg-=90\n if reg>=50:\t\t\t#five Tens in 50-89\n res+='L'\n reg-=50\n if reg>=40:\n res+='XL'\t\t#four Tens\n reg-=40\n while reg>=10:\n res+=\"X\"\t\t#tens\n reg-=10\n if reg>=9:\n res+='IX'\t\t#nine Units\n reg-=9\n if reg>=5:\n res+='V'\t\t#five Units\n reg-=5\n if reg>=4:\n res+='IV'\t\t#four Units\n reg-=4\n while reg>0:\t\t#three or less Units\n res+='I'\n reg-=1\n return res"} +{"title": "Roman numerals/Encode", "language": "Python 3", "task": "[[Category:String_manipulation]]\n\n;Task:\nCreate 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": "'''Encoding Roman Numerals'''\n\nfrom functools import reduce\nfrom itertools import chain\n\n\n# romanFromInt :: Int -> String\ndef romanFromInt(n):\n '''A string of Roman numerals encoding an integer.'''\n def go(a, ms):\n m, s = ms\n q, r = divmod(a, m)\n return (r, s * q)\n\n return concat(snd(mapAccumL(go)(n)(\n zip([\n 1000, 900, 500, 400, 100, 90, 50,\n 40, 10, 9, 5, 4, 1\n ], [\n 'M', 'CM', 'D', 'CD', 'C', 'XC', 'L',\n 'XL', 'X', 'IX', 'V', 'IV', 'I'\n ])\n )))\n\n\n# ------------------------- TEST -------------------------\n# main :: IO ()\ndef main():\n '''Sample of years'''\n for s in [\n romanFromInt(x) for x in [\n 1666, 1990, 2008, 2016, 2018, 2020\n ]\n ]:\n print(s)\n\n\n# ------------------ GENERIC FUNCTIONS -------------------\n\n# concat :: [[a]] -> [a]\n# concat :: [String] -> String\ndef concat(xxs):\n '''The concatenation of all the elements in a list.'''\n xs = list(chain.from_iterable(xxs))\n unit = '' if isinstance(xs, str) else []\n return unit if not xs else (\n ''.join(xs) if isinstance(xs[0], str) else xs\n )\n\n\n# mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])\ndef mapAccumL(f):\n '''A tuple of an accumulation and a list derived by a\n combined map and fold,\n with accumulation from left to right.'''\n def go(a, x):\n tpl = f(a[0], x)\n return (tpl[0], a[1] + [tpl[1]])\n return lambda acc: lambda xs: (\n reduce(go, xs, (acc, []))\n )\n\n\n# snd :: (a, b) -> b\ndef snd(tpl):\n '''Second component of a tuple.'''\n return tpl[1]\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} +{"title": "Rosetta Code/Rank languages by number of users", "language": "Python", "task": "[[Category:Text processing]]\n[[Category:Networking and Web Interaction]]\n[[Category:Sorting]]\n[[Category:Rosetta Code related]]\n\n;Task:\nSort most popular programming languages based on the number of users on Rosetta Code. \n\nShow the languages with at least 100 users.\n\n\n;A method to solve the task:\nUsers of a computer programming language \u00a0 '''X''' \u00a0 are those referenced in the page: \n https://rosettacode.org/wiki/Category:X_User, or preferably: \n https://rosettacode.org/mw/index.php?title=Category:X_User&redirect=no to avoid re-directions. \n\nIn order to find the list of such categories, \u00a0 it's possible to first parse the entries of: \n http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000. \n\nThen download and parse each computer language \u00a0 ''users'' \u00a0 category to find the number of users of that computer language.\n\n\nSample output on 18 February 2019:\nLanguage Users\n--------------------------\nC 391\nJava 276\nC++ 275\nPython 262\nJavaScript 238\nPerl 171\nPHP 167\nSQL 138\nUNIX Shell 131\nBASIC 120\nC sharp 118\nPascal 116\nHaskell 102\n\nA Rosetta Code user usually declares using a language with the mylang template. This template is expected to appear on the User page. However, in some cases it appears in a user Talk page. It's not necessary to take this into account. For instance, among the 373 C users in the table above, 3 are actually declared in a Talk page.\n\n", "solution": "\"\"\"Rank languages by number of users. Requires Python >=3.5\"\"\"\n\nimport requests\n\n# MediaWiki API URL.\nURL = \"http://rosettacode.org/mw/api.php\"\n\n# Query string parameters\nPARAMS = {\n \"action\": \"query\",\n \"format\": \"json\",\n \"formatversion\": 2,\n \"generator\": \"categorymembers\",\n \"gcmtitle\": \"Category:Language users\",\n \"gcmlimit\": 500,\n \"prop\": \"categoryinfo\",\n}\n\n\ndef fetch_data():\n counts = {}\n continue_ = {\"continue\": \"\"}\n\n # Keep making HTTP requests to the MediaWiki API if more records are\n # available.\n while continue_:\n resp = requests.get(URL, params={**PARAMS, **continue_})\n resp.raise_for_status()\n\n data = resp.json()\n\n # Grab the title (language) and size (count) only.\n counts.update(\n {\n p[\"title\"]: p.get(\"categoryinfo\", {}).get(\"size\", 0)\n for p in data[\"query\"][\"pages\"]\n }\n )\n\n continue_ = data.get(\"continue\", {})\n\n return counts\n\n\nif __name__ == \"__main__\":\n # Request data from the MediaWiki API.\n counts = fetch_data()\n\n # Filter out languages that have less than 100 users.\n at_least_100 = [(lang, count) for lang, count in counts.items() if count >= 100]\n\n # Sort languages by number of users\n top_languages = sorted(at_least_100, key=lambda x: x[1], reverse=True)\n\n # Pretty print\n for i, lang in enumerate(top_languages):\n print(f\"{i+1:<5}{lang[0][9:][:-5]:<20}{lang[1]}\")\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 \u00a0 fourth-order Runge\u2013Kutta method \u00a0 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": "Runge-Kutta method", "language": "JavaScript", "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 \u00a0 fourth-order Runge\u2013Kutta method \u00a0 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": "\nfunction rk4(y, x, dx, f) {\n var k1 = dx * f(x, y),\n k2 = dx * f(x + dx / 2.0, +y + k1 / 2.0),\n k3 = dx * f(x + dx / 2.0, +y + k2 / 2.0),\n k4 = dx * f(x + dx, +y + k3);\n\n return y + (k1 + 2.0 * k2 + 2.0 * k3 + k4) / 6.0;\n}\n\nfunction f(x, y) {\n return x * Math.sqrt(y);\n}\n\nfunction actual(x) {\n return (1/16) * (x*x+4)*(x*x+4);\n}\n\nvar y = 1.0,\n x = 0.0,\n step = 0.1,\n steps = 0,\n maxSteps = 101,\n sampleEveryN = 10;\n\nwhile (steps < maxSteps) {\n if (steps%sampleEveryN === 0) {\n console.log(\"y(\" + x + \") = \\t\" + y + \"\\t \u00b1 \" + (actual(x) - y).toExponential());\n }\n\n y = rk4(y, x, step, f);\n\n // using integer math for the step addition\n // to prevent floating point errors as 0.2 + 0.1 != 0.3\n x = ((x * 10) + (step * 10)) / 10;\n steps += 1;\n}\n"} +{"title": "Runge-Kutta method", "language": "Python", "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 \u00a0 fourth-order Runge\u2013Kutta method \u00a0 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": "from math import sqrt\n \ndef rk4(f, x0, y0, x1, n):\n vx = [0] * (n + 1)\n vy = [0] * (n + 1)\n h = (x1 - x0) / float(n)\n vx[0] = x = x0\n vy[0] = y = y0\n for i in range(1, n + 1):\n k1 = h * f(x, y)\n k2 = h * f(x + 0.5 * h, y + 0.5 * k1)\n k3 = h * f(x + 0.5 * h, y + 0.5 * k2)\n k4 = h * f(x + h, y + k3)\n vx[i] = x = x0 + i * h\n vy[i] = y = y + (k1 + k2 + k2 + k3 + k3 + k4) / 6\n return vx, vy\n \ndef f(x, y):\n return x * sqrt(y)\n \nvx, vy = rk4(f, 0, 1, 10, 100)\nfor x, y in list(zip(vx, vy))[::10]:\n print(\"%4.1f %10.5f %+12.4e\" % (x, y, y - (4 + x * x)**2 / 16))\n\n 0.0 1.00000 +0.0000e+00\n 1.0 1.56250 -1.4572e-07\n 2.0 4.00000 -9.1948e-07\n 3.0 10.56250 -2.9096e-06\n 4.0 24.99999 -6.2349e-06\n 5.0 52.56249 -1.0820e-05\n 6.0 99.99998 -1.6595e-05\n 7.0 175.56248 -2.3518e-05\n 8.0 288.99997 -3.1565e-05\n 9.0 451.56246 -4.0723e-05\n10.0 675.99995 -5.0983e-05"} +{"title": "Runtime evaluation", "language": "JavaScript", "task": ";Task:\nDemonstrate a language's ability for programs to execute code written in the language provided at runtime. \n\nShow what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.\n\nYou may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.\n\nFor a more constrained task giving a specific program fragment to evaluate, see [[Eval in environment]].\n\n", "solution": "\nvar foo = eval('{value: 42}');\neval('var bar = \"Hello, world!\";');\n\ntypeof foo; // 'object'\ntypeof bar; // 'string'\n"} +{"title": "Runtime evaluation/In an environment", "language": "JavaScript", "task": "Do so in a way which:\n* does not involve string manipulation of the input source code\n* is plausibly extensible to a runtime-chosen set of bindings rather than just x\n* does not make x a ''global'' variable\n\n\nor note that these are impossible.\n\n\n;See also:\n* For more general examples and language-specific details, see [[Eval]].\n* [[Dynamic variable names]] is a similar task.\n\n", "solution": "function evalWithX(expr, a, b) {\n var x = a;\n var atA = eval(expr);\n x = b;\n var atB = eval(expr);\n return atB - atA;\n}"} +{"title": "Runtime evaluation/In an environment", "language": "Python", "task": "Do so in a way which:\n* does not involve string manipulation of the input source code\n* is plausibly extensible to a runtime-chosen set of bindings rather than just x\n* does not make x a ''global'' variable\n\n\nor note that these are impossible.\n\n\n;See also:\n* For more general examples and language-specific details, see [[Eval]].\n* [[Dynamic variable names]] is a similar task.\n\n", "solution": ">>> def eval_with_args(code, **kwordargs):\n\treturn eval(code, kwordargs)\n\n>>> code = '2 ** x'\n>>> eval_with_args(code, x=5) - eval_with_args(code, x=3)\n24\n>>> code = '3 * x + y'\n>>> eval_with_args(code, x=5, y=2) - eval_with_args(code, x=3, y=1)\n7"} +{"title": "SHA-1", "language": "C", "task": "'''SHA-1''' or '''SHA1''' is a one-way hash function; \nit computes a 160-bit message digest. \nSHA-1 often appears in security protocols; for example, \nmany HTTPS websites use RSA with SHA-1 to secure their connections. \nBitTorrent uses SHA-1 to verify downloads. \nGit and Mercurial use SHA-1 digests to identify commits.\n\nA US government standard, FIPS 180-1, defines SHA-1.\n\nFind the SHA-1 message digest for a string of [[octet]]s. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.\n\nThis is much faster than a brute force attack of 280 operations. USgovernment [http://csrc.nist.gov/groups/ST/hash/statement.html deprecated SHA-1]. \nFor production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.}}\n", "solution": "#include \n#include \n#include \n#include \n\nint main()\n{\n int i;\n unsigned char result[SHA_DIGEST_LENGTH];\n const char *string = \"Rosetta Code\";\n \n SHA1(string, strlen(string), result);\n \n for(i = 0; i < SHA_DIGEST_LENGTH; i++)\n printf(\"%02x%c\", result[i], i < (SHA_DIGEST_LENGTH-1) ? ' ' : '\\n');\n \n return EXIT_SUCCESS;\n}"} +{"title": "SHA-1", "language": "Python", "task": "'''SHA-1''' or '''SHA1''' is a one-way hash function; \nit computes a 160-bit message digest. \nSHA-1 often appears in security protocols; for example, \nmany HTTPS websites use RSA with SHA-1 to secure their connections. \nBitTorrent uses SHA-1 to verify downloads. \nGit and Mercurial use SHA-1 digests to identify commits.\n\nA US government standard, FIPS 180-1, defines SHA-1.\n\nFind the SHA-1 message digest for a string of [[octet]]s. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.\n\nThis is much faster than a brute force attack of 280 operations. USgovernment [http://csrc.nist.gov/groups/ST/hash/statement.html deprecated SHA-1]. \nFor production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.}}\n", "solution": "import hashlib\nh = hashlib.sha1()\nh.update(bytes(\"Ars longa, vita brevis\", encoding=\"ASCII\"))\nh.hexdigest()\n# \"e640d285242886eb96ab80cbf858389b3df52f43\""} +{"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* [https://www.youtube.com/watch?v=U9qU20VmvaU 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": "Sailors, coconuts and a monkey problem", "language": "JavaScript", "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* [https://www.youtube.com/watch?v=U9qU20VmvaU 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": "(function () {\n\n // wakeSplit :: Int -> Int -> Int -> Int\n function wakeSplit(intNuts, intSailors, intDepth) {\n var nDepth = intDepth !== undefined ? intDepth : intSailors,\n portion = Math.floor(intNuts / intSailors),\n remain = intNuts % intSailors;\n\n return 0 >= portion || remain !== (nDepth ? 1 : 0) ?\n null : nDepth ? wakeSplit(\n intNuts - portion - remain, intSailors, nDepth - 1\n ) : intNuts;\n }\n\n // TEST for 5, 6, and 7 intSailors\n return [5, 6, 7].map(function (intSailors) {\n var intNuts = intSailors;\n\n while (!wakeSplit(intNuts, intSailors)) intNuts += 1;\n\n return intNuts;\n });\n})();"} +{"title": "Sailors, coconuts and a monkey problem", "language": "Python", "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* [https://www.youtube.com/watch?v=U9qU20VmvaU 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": "def monkey_coconuts(sailors=5):\n \"Parameterised the number of sailors using an inner loop including the last mornings case\" \n nuts = sailors\n while True:\n n0, wakes = nuts, []\n for sailor in range(sailors + 1):\n portion, remainder = divmod(n0, sailors)\n wakes.append((n0, portion, remainder))\n if portion <= 0 or remainder != (1 if sailor != sailors else 0):\n nuts += 1\n break\n n0 = n0 - portion - remainder\n else:\n break\n return nuts, wakes\n\nif __name__ == \"__main__\":\n for sailors in [5, 6]:\n nuts, wake_stats = monkey_coconuts(sailors)\n print(\"\\nFor %i sailors the initial nut count is %i\" % (sailors, nuts))\n print(\"On each waking, the nut count, portion taken, and monkeys share are:\\n \", \n ',\\n '.join(repr(ws) for ws in wake_stats))"} +{"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": "Same fringe", "language": "Python", "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": "try:\n from itertools import zip_longest as izip_longest # Python 3.x\nexcept:\n from itertools import izip_longest # Python 2.6+\n\ndef fringe(tree):\n \"\"\"Yield tree members L-to-R depth first,\n as if stored in a binary tree\"\"\"\n for node1 in tree:\n if isinstance(node1, tuple):\n for node2 in fringe(node1):\n yield node2\n else:\n yield node1\n\ndef same_fringe(tree1, tree2):\n return all(node1 == node2 for node1, node2 in\n izip_longest(fringe(tree1), fringe(tree2)))\n\nif __name__ == '__main__':\n a = 1, 2, 3, 4, 5, 6, 7, 8\n b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8))))\n c = (((1, 2), 3), 4), 5, 6, 7, 8\n\n x = 1, 2, 3, 4, 5, 6, 7, 8, 9\n y = 0, 2, 3, 4, 5, 6, 7, 8\n z = 1, 2, (4, 3), 5, 6, 7, 8\n\n assert same_fringe(a, a)\n assert same_fringe(a, b)\n assert same_fringe(a, c)\n\n assert not same_fringe(a, x)\n assert not same_fringe(a, y)\n assert not same_fringe(a, z)"} +{"title": "Search in paragraph's text", "language": "Python", "task": "The goal is to verify the presence of a word or regular expression within several paragraphs of text (structured or not) and to format the output of the relevant paragraphs before putting them on the standard output.\n\nSo here, let\u2019s imagine that we are trying to verify the presence of a keyword \"SystemError\" within what I want to call \"the paragraphs\" \"Traceback (most recent call last):\" in the file Traceback.txt\n\n\ncat Traceback.txt :\n\n2018-06-19 23:19:34,877 ERROR Processes plugin raised an exception.\nTraceback (most recent call last):\n File \"/usr/lib/python3/dist-packages/landscape/sysinfo/sysinfo.py\", line 99, in run\n result = plugin.run()\n File \"/usr/lib/python3/dist-packages/landscape/sysinfo/processes.py\", line 18, in run\n for process_info in info.get_all_process_info():\n File \"/usr/lib/python3/dist-packages/landscape/lib/process.py\", line 39, in get_all_process_info\n process_info = self.get_process_info(process_id)\n File \"/usr/lib/python3/dist-packages/landscape/lib/process.py\", line 61, in get_process_info\n cmd_line = file.readline()\n File \"/usr/lib/python3.6/encodings/ascii.py\", line 26, in decode\n return codecs.ascii_decode(input, self.errors)[0]\nUnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 152: ordinal not in range(128)\n\n2018-06-19 23:19:34,877 ERROR Processes plugin raised an exception.\nTraceback (most recent call last):\n vmodl.fault.SystemError: (vmodl.fault.SystemError) {\n dynamicType = ,\n dynamicProperty = (vmodl.DynamicProperty) [],\n msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',\n faultCause = ,\n faultMessage = (vmodl.LocalizableMessage) [],\n reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'\n }\n\n[Tue Jan 21 16:16:19.250245 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] Traceback (most recent call last):\n[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir\n[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.\n[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.\n\n[Tue Jan 21 17:16:19.250245 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] Traceback (most recent call last):\n[Tue Jan 21 17:16:19.250679 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] File \"/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi\", line 5, in \n[Tue Jan 21 17:16:19.251735 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] from test import app as application\n[Tue Jan 21 17:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] ImportError: cannot import name app\n\n2021-04-23 17:13:14,425 ERROR Network plugin raised an exception.\nTraceback (most recent call last):\n File \"/usr/lib/python3/dist-packages/landscape/sysinfo/sysinfo.py\", line 99, \nin run\n result = plugin.run()\n File \"/usr/lib/python3/dist-packages/landscape/sysinfo/network.py\", line 36, \nin run\n device_info = self._get_device_info()\n File \"/usr/lib/python3/dist-packages/landscape/lib/network.py\", line 163, in \nget_active_device_info\n speed, duplex = get_network_interface_speed(\n File \"/usr/lib/python3/dist-packages/landscape/lib/network.py\", line 249, in \nget_network_interface_speed\n res = status_cmd.tostring()\nAttributeError: 'array.array' object has no attribute 'tostring'\n\n11/01 18:24:57.726 ERROR| log:0072| post-test sysinfo error: 11/01 18:24:57.727 ERROR| traceback:0013| Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File \"/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py\", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File \"/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py\", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| TypeError: 'NoneType' object is not iterable\n\n12/01 19:24:57.726 ERROR| log:0072| post-test sysinfo error: 11/01 18:24:57.727 ERROR| traceback:0013| Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File \"/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py\", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File \"/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py\", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory\n\nTraceback (most recent call last):\n File \"/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py\", line 1492, in WaitForUpdateTask\n WaitForTask(task)\n File \"/usr/lib/vmware-vpx/pyJack/pyVim/task.py\", line 123, in WaitForTask\n raise task.info.error\n vmodl.fault.SystemError: (vmodl.fault.SystemError) {\n dynamicType = ,\n dynamicProperty = (vmodl.DynamicProperty) [],\n msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',\n faultCause = ,\n faultMessage = (vmodl.LocalizableMessage) [],\n reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'\n }\n\n\nThe expected result must be formated with ---------------- for paragraph's separator AND \"Traceback (most recent call last):\" as the beginning of each relevant's paragraph :\n\n\nTraceback (most recent call last):\n vmodl.fault.SystemError: (vmodl.fault.SystemError) {\n dynamicType = ,\n dynamicProperty = (vmodl.DynamicProperty) [],\n msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',\n faultCause = ,\n faultMessage = (vmodl.LocalizableMessage) [],\n reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'\n }\n----------------\nTraceback (most recent call last):\n[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir\n[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.\n[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.\n----------------\nTraceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File \"/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py\", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File \"/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py\", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory\n----------------\nTraceback (most recent call last):\n File \"/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py\", line 1492, in WaitForUpdateTask\n WaitForTask(task)\n File \"/usr/lib/vmware-vpx/pyJack/pyVim/task.py\", line 123, in WaitForTask\n raise task.info.error\n vmodl.fault.SystemError: (vmodl.fault.SystemError) {\n dynamicType = ,\n dynamicProperty = (vmodl.DynamicProperty) [],\n msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',\n faultCause = ,\n faultMessage = (vmodl.LocalizableMessage) [],\n reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'\n }\n----------------\n\n", "solution": "\nwith open('Traceback.txt', 'r' ) as f:\n rawText = f.read()\n\nparagraphs = rawText.split( \"\\n\\n\" )\n\nfor p in paragraphs:\n if \"SystemError\" in p:\n\n index = p.find( \"Traceback (most recent call last):\" )\n\n if -1 != index:\n print( p[index:] )\n print( \"----------------\" )\n"} +{"title": "Selectively replace multiple instances of a character within a string", "language": "C", "task": "[[Category: String manipulation]] \n[[Category:Simple]]\n[[Category:Strings]]\n;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": "\n#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": "Selectively replace multiple instances of a character within a string", "language": "JavaScript", "task": "[[Category: String manipulation]] \n[[Category:Simple]]\n[[Category:Strings]]\n;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": "function findNth(s, c, n) {\n if (n === 1) return s.indexOf(c);\n return s.indexOf(c, findNth(s, c, n - 1) + 1);\n}\n\nfunction selectiveReplace(s, ops) {\n const chars = Array.from(s);\n for ([n, old, rep] of ops) {\n chars[findNth(s, old, n)] = rep;\n }\n return chars.join(\"\");\n}\n\nconsole.log(\n selectiveReplace(\"abracadabra\", [\n [1, \"a\", \"A\"], // the first 'a' with 'A'\n [2, \"a\", \"B\"], // the second 'a' with 'B'\n [4, \"a\", \"C\"], // the fourth 'a' with 'C'\n [5, \"a\", \"D\"], // the fifth 'a' with 'D'\n [1, \"b\", \"E\"], // the first 'b' with 'E'\n [2, \"r\", \"F\"], // the second 'r' with 'F'\n ])\n);"} +{"title": "Selectively replace multiple instances of a character within a string", "language": "Python", "task": "[[Category: String manipulation]] \n[[Category:Simple]]\n[[Category:Strings]]\n;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": "import functools\n\nfrom typing import Iterable\nfrom typing import Tuple\n\n\n@functools.cache\ndef find_nth(s: str, sub: str, n: int) -> int:\n assert n >= 1\n if n == 1:\n return s.find(sub)\n return s.find(sub, find_nth(s, sub, n - 1) + 1)\n\n\ndef selective_replace(s: str, ops: Iterable[Tuple[int, str, str]]) -> str:\n chars = list(s)\n for n, old, new in ops:\n chars[find_nth(s, old, n)] = new\n return \"\".join(chars)\n\n\nprint(\n selective_replace(\n \"abracadabra\",\n [\n (1, \"a\", \"A\"), # the first 'a' with 'A'\n (2, \"a\", \"B\"), # the second 'a' with 'B'\n (4, \"a\", \"C\"), # the fourth 'a' with 'C'\n (5, \"a\", \"D\"), # the fifth 'a' with 'D'\n (1, \"b\", \"E\"), # the first 'b' with 'E'\n (2, \"r\", \"F\"), # the second 'r' with 'F'\n ],\n )\n)"} +{"title": "Self-describing numbers", "language": "C", "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, \u00a0 '''2020''' \u00a0 is a four-digit self describing number:\n\n* \u00a0 position \u00a0 0 \u00a0 has value \u00a0 2 \u00a0 and there are two 0s in the number;\n* \u00a0 position \u00a0 1 \u00a0 has value \u00a0 0 \u00a0 and there are no 1s in the number;\n* \u00a0 position \u00a0 2 \u00a0 has value \u00a0 2 \u00a0 and there are two 2s;\n* \u00a0 position \u00a0 3 \u00a0 has value \u00a0 0 \u00a0 and there are zero 3s.\n\n\nSelf-describing numbers < 100.000.000\u00a0 are: \u00a0 \u00a0 1210, \u00a0 2020, \u00a0 21200, \u00a0 3211000, \u00a0 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* \u00a0 [[Fours is the number of letters in the ...]]\n* \u00a0 [[Look-and-say sequence]]\n* \u00a0 [[Number names]]\n* \u00a0 [[Self-referential sequence]]\n* \u00a0 [[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": "Self-describing numbers", "language": "SpiderMonkey", "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, \u00a0 '''2020''' \u00a0 is a four-digit self describing number:\n\n* \u00a0 position \u00a0 0 \u00a0 has value \u00a0 2 \u00a0 and there are two 0s in the number;\n* \u00a0 position \u00a0 1 \u00a0 has value \u00a0 0 \u00a0 and there are no 1s in the number;\n* \u00a0 position \u00a0 2 \u00a0 has value \u00a0 2 \u00a0 and there are two 2s;\n* \u00a0 position \u00a0 3 \u00a0 has value \u00a0 0 \u00a0 and there are zero 3s.\n\n\nSelf-describing numbers < 100.000.000\u00a0 are: \u00a0 \u00a0 1210, \u00a0 2020, \u00a0 21200, \u00a0 3211000, \u00a0 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* \u00a0 [[Fours is the number of letters in the ...]]\n* \u00a0 [[Look-and-say sequence]]\n* \u00a0 [[Number names]]\n* \u00a0 [[Self-referential sequence]]\n* \u00a0 [[Spelling of ordinal numbers]]\n\n", "solution": "function is_self_describing(n) {\n var digits = Number(n).toString().split(\"\").map(function(elem) {return Number(elem)});\n var len = digits.length;\n var count = digits.map(function(x){return 0});\n\n digits.forEach(function(digit, idx, ary) {\n if (digit >= count.length)\n return false\n count[digit] ++;\n });\n\n return digits.equals(count);\n}\n\nArray.prototype.equals = function(other) {\n if (this === other)\n return true; // same object\n if (this.length != other.length)\n return false;\n for (idx in this)\n if (this[idx] !== other[idx])\n return false;\n return true;\n}\n\nfor (var i=1; i<=3300000; i++)\n if (is_self_describing(i))\n print(i);"} +{"title": "Self-describing numbers", "language": "Python", "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, \u00a0 '''2020''' \u00a0 is a four-digit self describing number:\n\n* \u00a0 position \u00a0 0 \u00a0 has value \u00a0 2 \u00a0 and there are two 0s in the number;\n* \u00a0 position \u00a0 1 \u00a0 has value \u00a0 0 \u00a0 and there are no 1s in the number;\n* \u00a0 position \u00a0 2 \u00a0 has value \u00a0 2 \u00a0 and there are two 2s;\n* \u00a0 position \u00a0 3 \u00a0 has value \u00a0 0 \u00a0 and there are zero 3s.\n\n\nSelf-describing numbers < 100.000.000\u00a0 are: \u00a0 \u00a0 1210, \u00a0 2020, \u00a0 21200, \u00a0 3211000, \u00a0 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* \u00a0 [[Fours is the number of letters in the ...]]\n* \u00a0 [[Look-and-say sequence]]\n* \u00a0 [[Number names]]\n* \u00a0 [[Self-referential sequence]]\n* \u00a0 [[Spelling of ordinal numbers]]\n\n", "solution": ">>> def isSelfDescribing(n):\n\ts = str(n)\n\treturn all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))\n\n>>> [x for x in range(4000000) if isSelfDescribing(x)]\n[1210, 2020, 21200, 3211000]\n>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]\n[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]"} +{"title": "Self numbers", "language": "C", "task": "A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.\n\nThe task is:\n Display the first 50 self numbers;\n I believe that the 100000000th self number is 1022727208. You should either confirm or dispute my conjecture.\n\n224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it.\n\n;See also: \n\n;*OEIS: A003052 - Self numbers or Colombian numbers\n;*Wikipedia: Self numbers\n\n", "solution": "#include \n#include \n#include \n\ntypedef unsigned char bool;\n\n#define TRUE 1\n#define FALSE 0\n#define MILLION 1000000\n#define BILLION 1000 * MILLION\n#define MAX_COUNT 2*BILLION + 9*9 + 1\n\nvoid sieve(bool *sv) {\n int n = 0, s[8], a, b, c, d, e, f, g, h, i, j;\n for (a = 0; a < 2; ++a) {\n for (b = 0; b < 10; ++b) {\n s[0] = a + b;\n for (c = 0; c < 10; ++c) {\n s[1] = s[0] + c;\n for (d = 0; d < 10; ++d) {\n s[2] = s[1] + d;\n for (e = 0; e < 10; ++e) {\n s[3] = s[2] + e;\n for (f = 0; f < 10; ++f) {\n s[4] = s[3] + f;\n for (g = 0; g < 10; ++g) {\n s[5] = s[4] + g;\n for (h = 0; h < 10; ++h) {\n s[6] = s[5] + h;\n for (i = 0; i < 10; ++i) {\n s[7] = s[6] + i;\n for (j = 0; j < 10; ++j) {\n sv[s[7] + j+ n++] = TRUE;\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n}\n\nint main() {\n int count = 0;\n clock_t begin = clock();\n bool *p, *sv = (bool*) calloc(MAX_COUNT, sizeof(bool));\n sieve(sv);\n printf(\"The first 50 self numbers are:\\n\");\n for (p = sv; p < sv + MAX_COUNT; ++p) {\n if (!*p) {\n if (++count <= 50) printf(\"%ld \", p-sv);\n if (count == 100 * MILLION) {\n printf(\"\\n\\nThe 100 millionth self number is %ld\\n\", p-sv);\n break;\n }\n }\n }\n free(sv);\n printf(\"Took %lf seconds.\\n\", (double)(clock() - begin) / CLOCKS_PER_SEC);\n return 0;\n}"} +{"title": "Self numbers", "language": "Python 2.7", "task": "A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.\n\nThe task is:\n Display the first 50 self numbers;\n I believe that the 100000000th self number is 1022727208. You should either confirm or dispute my conjecture.\n\n224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it.\n\n;See also: \n\n;*OEIS: A003052 - Self numbers or Colombian numbers\n;*Wikipedia: Self numbers\n\n", "solution": "class DigitSumer :\n def __init__(self): \n sumdigit = lambda n : sum( map( int,str( n )))\n self.t = [sumdigit( i ) for i in xrange( 10000 )]\n def __call__ ( self,n ):\n r = 0\n while n >= 10000 :\n n,q = divmod( n,10000 )\n r += self.t[q]\n return r + self.t[n] \n\n\ndef self_numbers ():\n d = DigitSumer()\n s = set([])\n i = 1\n while 1 :\n n = i + d( i )\n if i in s :\n s.discard( i )\n else:\n yield i\n s.add( n )\n i += 1\n\nimport time\np = 100\nt = time.time()\nfor i,s in enumerate( self_numbers(),1 ):\n if i <= 50 : \n print s,\n if i == 50 : print\n if i == p :\n print '%7.1f sec %9dth = %d'%( time.time()-t,i,s )\n p *= 10"} +{"title": "Semordnilap", "language": "C", "task": "A [https://en.wiktionary.org/wiki/semordnilap#Noun 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 [http://wiki.puzzlers.org/pub/wordlists/unixdict.txt 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": "Semordnilap", "language": "JavaScript", "task": "A [https://en.wiktionary.org/wiki/semordnilap#Noun 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 [http://wiki.puzzlers.org/pub/wordlists/unixdict.txt 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": "#!/usr/bin/env node\nvar fs = require('fs');\nvar sys = require('sys');\n\nvar dictFile = process.argv[2] || \"unixdict.txt\";\n\nvar dict = {};\nfs.readFileSync(dictFile)\n .toString()\n .split('\\n')\n .forEach(function(word) {\n dict[word] = word.split(\"\").reverse().join(\"\");\n });\n\nfunction isSemordnilap(word) { return dict[dict[word]]; };\n\nvar semordnilaps = []\nfor (var key in dict) {\n if (isSemordnilap(key)) {\n var rev = dict[key];\n if (key < rev) {\n semordnilaps.push([key,rev]) ;\n }\n }\n}\n\nvar count = semordnilaps.length;\nsys.puts(\"There are \" + count + \" semordnilaps in \" +\n dictFile + \". Here are 5:\" );\n\nvar indices=[]\nfor (var i=0; i\n\n===Rhino===\n"} +{"title": "Semordnilap", "language": "Rhino 1.7", "task": "A [https://en.wiktionary.org/wiki/semordnilap#Noun 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 [http://wiki.puzzlers.org/pub/wordlists/unixdict.txt 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": "#!/usr/bin/env rhino\n\nimportPackage (java.io)\n\nvar dictFile = arguments[0] || \"unixdict.txt\";\n\nvar reader = new BufferedReader(new FileReader(dictFile));\nvar dict = {};\nvar word;\nwhile (word = reader.readLine()) {\n dict[word] = word.split(\"\").reverse().join(\"\");\n}\n\nfunction isSemordnilap(word) { return dict[dict[word]]; };\n\nvar semordnilaps = []\nfor (var key in dict) {\n if (isSemordnilap(key)) {\n var rev = dict[key];\n if (key < rev) {\n semordnilaps.push([key,rev]) ;\n }\n }\n}\n\nvar count = semordnilaps.length;\nprint(\"There are \" + count + \" semordnilaps in \" +\n dictFile + \". Here are 5:\" );\nvar indices=[]\nfor (var i=0; i\n"} +{"title": "Semordnilap", "language": "Python", "task": "A [https://en.wiktionary.org/wiki/semordnilap#Noun 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 [http://wiki.puzzlers.org/pub/wordlists/unixdict.txt 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": ">>> with open('unixdict.txt') as f:\n\twordset = set(f.read().strip().split())\n\n>>> revlist = (''.join(word[::-1]) for word in wordset)\n>>> pairs = set((word, rev) for word, rev in zip(wordset, revlist) \n if word < rev and rev in wordset)\n>>> len(pairs)\n158\n>>> sorted(pairs, key=lambda p: (len(p[0]), p))[-5:]\n[('damon', 'nomad'), ('lager', 'regal'), ('leper', 'repel'), ('lever', 'revel'), ('kramer', 'remark')]\n>>> "} +{"title": "Semordnilap", "language": "Python 3.7", "task": "A [https://en.wiktionary.org/wiki/semordnilap#Noun 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 [http://wiki.puzzlers.org/pub/wordlists/unixdict.txt 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": "'''Dictionary words paired by equivalence under reversal'''\n\nfrom functools import (reduce)\nfrom itertools import (chain)\nimport urllib.request\n\n\n# semordnilaps :: [String] -> [String]\ndef semordnilaps(xs):\n '''The subset of words in a list which\n are paired (by equivalence under reversal)\n with other words in that list.\n '''\n def go(tpl, w):\n (s, ws) = tpl\n if w[::-1] in s:\n return (s, ws + [w])\n else:\n s.add(w)\n return (s, ws)\n return reduce(go, xs, (set(), []))[1]\n\n\n# TEST ----------------------------------------------------\ndef main():\n '''Test'''\n\n url = 'http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'\n ws = semordnilaps(\n urllib.request.urlopen(\n url\n ).read().splitlines()\n )\n print(\n fTable(\n __doc__ + ':\\n\\n(longest of ' +\n str(len(ws)) + ' in ' + url + ')\\n'\n )(snd)(fst)(identity)(\n sorted(\n concatMap(\n lambda x: (\n lambda s=x.decode('utf8'): [\n (s, s[::-1])\n ] if 4 < len(x) else []\n )()\n )(ws),\n key=compose(len)(fst),\n reverse=True\n )\n )\n )\n\n\n# GENERIC -------------------------------------------------\n\n# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n '''Right to left function composition.'''\n return lambda f: lambda x: g(f(x))\n\n\n# concatMap :: (a -> [b]) -> [a] -> [b]\ndef concatMap(f):\n '''A concatenated list over which a function has been mapped.\n The list monad can be derived by using a function f which\n wraps its output in a list,\n (using an empty list to represent computational failure).'''\n return lambda xs: list(\n chain.from_iterable(map(f, xs))\n )\n\n\n# FORMATTING ----------------------------------------------\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\n '''\n def go(xShow, fxShow, f, xs):\n ys = [xShow(x) for x in xs]\n w = max(map(len, ys))\n return s + '\\n' + '\\n'.join(map(\n lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n xs, ys\n ))\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\n# fst :: (a, b) -> a\ndef fst(tpl):\n '''First member of a pair.'''\n return tpl[0]\n\n\n# identity :: a -> a\ndef identity(x):\n '''The identity function.'''\n return x\n\n\n# snd :: (a, b) -> b\ndef snd(tpl):\n '''Second member of a pair.'''\n return tpl[1]\n\n\nif __name__ == '__main__':\n main()"} +{"title": "Sequence: nth number with exactly n divisors", "language": "C", "task": "Calculate the sequence where each term an is the nth that has '''n''' divisors.\n\n;Task\n\nShow here, on this page, at least the first '''15''' terms of the sequence.\n\n;See also\n\n:*OEIS:A073916\n\n;Related tasks\n\n:*[[Sequence: smallest number greater than previous term with exactly n divisors]]\n:*[[Sequence: smallest number with exactly n divisors]]\n\n", "solution": "#include \n#include \n#include \n#include \n\n#define LIMIT 15\nint smallPrimes[LIMIT];\n\nstatic void sieve() {\n int i = 2, j;\n int p = 5;\n\n smallPrimes[0] = 2;\n smallPrimes[1] = 3;\n\n while (i < LIMIT) {\n for (j = 0; j < i; j++) {\n if (smallPrimes[j] * smallPrimes[j] <= p) {\n if (p % smallPrimes[j] == 0) {\n p += 2;\n break;\n }\n } else {\n smallPrimes[i++] = p;\n p += 2;\n break;\n }\n }\n }\n}\n\nstatic bool is_prime(uint64_t n) {\n uint64_t i;\n\n for (i = 0; i < LIMIT; i++) {\n if (n % smallPrimes[i] == 0) {\n return n == smallPrimes[i];\n }\n }\n\n i = smallPrimes[LIMIT - 1] + 2;\n for (; i * i <= n; i += 2) {\n if (n % i == 0) {\n return false;\n }\n }\n\n return true;\n}\n\nstatic uint64_t divisor_count(uint64_t n) {\n uint64_t count = 1;\n uint64_t d;\n\n while (n % 2 == 0) {\n n /= 2;\n count++;\n }\n\n for (d = 3; d * d <= n; d += 2) {\n uint64_t q = n / d;\n uint64_t r = n % d;\n uint64_t dc = 0;\n while (r == 0) {\n dc += count;\n n = q;\n q = n / d;\n r = n % d;\n }\n count += dc;\n }\n\n if (n != 1) {\n return count *= 2;\n }\n return count;\n}\n\nstatic uint64_t OEISA073916(size_t n) {\n uint64_t count = 0;\n uint64_t result = 0;\n size_t i;\n\n if (is_prime(n)) {\n return (uint64_t)pow(smallPrimes[n - 1], n - 1);\n }\n\n for (i = 1; count < n; i++) {\n if (n % 2 == 1) {\n // The solution for an odd (non-prime) term is always a square number\n uint64_t root = (uint64_t)sqrt(i);\n if (root * root != i) {\n continue;\n }\n }\n if (divisor_count(i) == n) {\n count++;\n result = i;\n }\n }\n\n return result;\n}\n\nint main() {\n size_t n;\n\n sieve();\n\n for (n = 1; n <= LIMIT; n++) {\n if (n == 13) {\n printf(\"A073916(%lu) = One more bit needed to represent result.\\n\", n);\n } else {\n printf(\"A073916(%lu) = %llu\\n\", n, OEISA073916(n));\n }\n }\n\n return 0;\n}"} +{"title": "Sequence: nth number with exactly n divisors", "language": "Python", "task": "Calculate the sequence where each term an is the nth that has '''n''' divisors.\n\n;Task\n\nShow here, on this page, at least the first '''15''' terms of the sequence.\n\n;See also\n\n:*OEIS:A073916\n\n;Related tasks\n\n:*[[Sequence: smallest number greater than previous term with exactly n divisors]]\n:*[[Sequence: smallest number with exactly n divisors]]\n\n", "solution": "\ndef divisors(n):\n divs = [1]\n for ii in range(2, int(n ** 0.5) + 3):\n if n % ii == 0:\n divs.append(ii)\n divs.append(int(n / ii))\n divs.append(n)\n return list(set(divs))\n\n\ndef is_prime(n):\n return len(divisors(n)) == 2\n\n\ndef primes():\n ii = 1\n while True:\n ii += 1\n if is_prime(ii):\n yield ii\n\n\ndef prime(n):\n generator = primes()\n for ii in range(n - 1):\n generator.__next__()\n return generator.__next__()\n\n\ndef n_divisors(n):\n ii = 0\n while True:\n ii += 1\n if len(divisors(ii)) == n:\n yield ii\n\n\ndef sequence(max_n=None):\n if max_n is not None:\n for ii in range(1, max_n + 1):\n if is_prime(ii):\n yield prime(ii) ** (ii - 1)\n else:\n generator = n_divisors(ii)\n for jj, out in zip(range(ii - 1), generator):\n pass\n yield generator.__next__()\n else:\n ii = 1\n while True:\n ii += 1\n if is_prime(ii):\n yield prime(ii) ** (ii - 1)\n else:\n generator = n_divisors(ii)\n for jj, out in zip(range(ii - 1), generator):\n pass\n yield generator.__next__()\n\n\nif __name__ == '__main__':\n for item in sequence(15):\n print(item)\n"} +{"title": "Sequence: smallest number greater than previous term with exactly n divisors", "language": "C", "task": "Calculate the sequence where each term an is the '''smallest natural number''' greater than the previous term, that has exactly '''n''' divisors.\n\n\n;Task\nShow here, on this page, at least the first '''15''' terms of the sequence.\n\n\n;See also\n:* OEIS:A069654\n\n\n;Related tasks\n:* [[Sequence: smallest number with exactly n divisors]]\n:* [[Sequence: nth number with exactly n divisors\u200e\u200e]]\n\n", "solution": "#include \n\n#define MAX 15\n\nint count_divisors(int n) {\n int i, count = 0;\n for (i = 1; i * i <= n; ++i) {\n if (!(n % i)) {\n if (i == n / i)\n count++;\n else\n count += 2;\n }\n }\n return count;\n}\n\nint main() {\n int i, next = 1;\n printf(\"The first %d terms of the sequence are:\\n\", MAX);\n for (i = 1; next <= MAX; ++i) {\n if (next == count_divisors(i)) { \n printf(\"%d \", i);\n next++;\n }\n }\n printf(\"\\n\");\n return 0;\n}"} +{"title": "Sequence: smallest number greater than previous term with exactly n divisors", "language": "Python", "task": "Calculate the sequence where each term an is the '''smallest natural number''' greater than the previous term, that has exactly '''n''' divisors.\n\n\n;Task\nShow here, on this page, at least the first '''15''' terms of the sequence.\n\n\n;See also\n:* OEIS:A069654\n\n\n;Related tasks\n:* [[Sequence: smallest number with exactly n divisors]]\n:* [[Sequence: nth number with exactly n divisors\u200e\u200e]]\n\n", "solution": "\ndef divisors(n):\n divs = [1]\n for ii in range(2, int(n ** 0.5) + 3):\n if n % ii == 0:\n divs.append(ii)\n divs.append(int(n / ii))\n divs.append(n)\n return list(set(divs))\n\n\ndef sequence(max_n=None):\n previous = 0\n n = 0\n while True:\n n += 1\n ii = previous\n if max_n is not None:\n if n > max_n:\n break\n while True:\n ii += 1\n if len(divisors(ii)) == n:\n yield ii\n previous = ii\n break\n\n\nif __name__ == '__main__':\n for item in sequence(15):\n print(item)\n"} +{"title": "Sequence: smallest number with exactly n divisors", "language": "C", "task": "Calculate the sequence where each term \u00a0 an \u00a0 is the '''smallest natural number''' that has exactly \u00a0 '''n''' \u00a0 divisors.\n\n\n;Task\nShow here, on this page, at least the first \u00a0'''15'''\u00a0 terms of the sequence.\n\n\n;Related tasks:\n:* [[Sequence: smallest number greater than previous term with exactly n divisors]]\n:* [[Sequence: nth number with exactly n divisors\u200e\u200e]]\n\n\n;See also:\n:* OEIS:A005179\n\n", "solution": "#include \n\n#define MAX 15\n\nint count_divisors(int n) {\n int i, count = 0;\n for (i = 1; i * i <= n; ++i) {\n if (!(n % i)) {\n if (i == n / i)\n count++;\n else\n count += 2;\n }\n }\n return count;\n}\n\nint main() {\n int i, k, n, seq[MAX];\n for (i = 0; i < MAX; ++i) seq[i] = 0;\n printf(\"The first %d terms of the sequence are:\\n\", MAX);\n for (i = 1, n = 0; n < MAX; ++i) {\n k = count_divisors(i);\n if (k <= MAX && seq[k - 1] == 0) {\n seq[k - 1] = i;\n ++n;\n }\n }\n for (i = 0; i < MAX; ++i) printf(\"%d \", seq[i]);\n printf(\"\\n\");\n return 0;\n}"} +{"title": "Sequence: smallest number with exactly n divisors", "language": "JavaScript", "task": "Calculate the sequence where each term \u00a0 an \u00a0 is the '''smallest natural number''' that has exactly \u00a0 '''n''' \u00a0 divisors.\n\n\n;Task\nShow here, on this page, at least the first \u00a0'''15'''\u00a0 terms of the sequence.\n\n\n;Related tasks:\n:* [[Sequence: smallest number greater than previous term with exactly n divisors]]\n:* [[Sequence: nth number with exactly n divisors\u200e\u200e]]\n\n\n;See also:\n:* OEIS:A005179\n\n", "solution": "(() => {\n 'use strict';\n\n // a005179 :: () -> [Int]\n const a005179 = () =>\n fmapGen(\n n => find(\n compose(\n eq(n),\n succ,\n length,\n properDivisors\n )\n )(enumFrom(1)).Just\n )(enumFrom(1));\n\n\n // ------------------------TEST------------------------\n // main :: IO ()\n const main = () =>\n console.log(\n take(15)(\n a005179()\n )\n );\n\n // [1,2,4,6,16,12,64,24,36,48,1024,60,4096,192,144]\n\n\n // -----------------GENERIC FUNCTIONS------------------\n\n // Just :: a -> Maybe a\n const Just = x => ({\n type: 'Maybe',\n Nothing: false,\n Just: x\n });\n\n // Nothing :: Maybe a\n const Nothing = () => ({\n type: 'Maybe',\n Nothing: true,\n });\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = a =>\n b => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (...fs) =>\n fs.reduce(\n (f, g) => x => f(g(x)),\n x => x\n );\n\n // enumFrom :: Enum a => a -> [a]\n function* enumFrom(x) {\n // A non-finite succession of enumerable\n // values, starting with the value x.\n let v = x;\n while (true) {\n yield v;\n v = succ(v);\n }\n };\n\n // eq (==) :: Eq a => a -> a -> Bool\n const eq = a =>\n // True when a and b are equivalent in the terms\n // defined below for their shared data type.\n b => a === b;\n\n // find :: (a -> Bool) -> Gen [a] -> Maybe a\n const find = p => xs => {\n const mb = until(tpl => {\n const nxt = tpl[0];\n return nxt.done || p(nxt.value);\n })(\n tpl => Tuple(tpl[1].next())(\n tpl[1]\n )\n )(Tuple(xs.next())(xs))[0];\n return mb.done ? (\n Nothing()\n ) : Just(mb.value);\n }\n\n // fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]\n const fmapGen = f =>\n function*(gen) {\n let v = take(1)(gen);\n while (0 < v.length) {\n yield(f(v[0]))\n v = take(1)(gen)\n }\n };\n\n // group :: [a] -> [[a]]\n const group = xs => {\n // A list of lists, each containing only equal elements,\n // such that the concatenation of these lists is xs.\n const go = xs =>\n 0 < xs.length ? (() => {\n const\n h = xs[0],\n i = xs.findIndex(x => h !== x);\n return i !== -1 ? (\n [xs.slice(0, i)].concat(go(xs.slice(i)))\n ) : [xs];\n })() : [];\n return go(xs);\n };\n\n // length :: [a] -> Int\n const length = xs =>\n // Returns Infinity over objects without finite\n // length. This enables zip and zipWith to choose\n // the shorter argument when one is non-finite,\n // like cycle, repeat etc\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n // liftA2List :: (a -> b -> c) -> [a] -> [b] -> [c]\n const liftA2List = f => xs => ys =>\n // The binary operator f lifted to a function over two\n // lists. f applied to each pair of arguments in the\n // cartesian product of xs and ys.\n xs.flatMap(\n x => ys.map(f(x))\n );\n\n // mul (*) :: Num a => a -> a -> a\n const mul = a => b => a * b;\n\n // properDivisors :: Int -> [Int]\n const properDivisors = n =>\n // The ordered divisors of n,\n // excluding n itself.\n 1 < n ? (\n sort(group(primeFactors(n)).reduce(\n (a, g) => liftA2List(mul)(a)(\n scanl(mul)([1])(g)\n ),\n [1]\n )).slice(0, -1)\n ) : [];\n\n // primeFactors :: Int -> [Int]\n const primeFactors = n => {\n // A list of the prime factors of n.\n const\n go = x => {\n const\n root = Math.floor(Math.sqrt(x)),\n m = until(\n ([q, _]) => (root < q) || (0 === (x % q))\n )(\n ([_, r]) => [step(r), 1 + r]\n )(\n [0 === x % 2 ? 2 : 3, 1]\n )[0];\n return m > root ? (\n [x]\n ) : ([m].concat(go(Math.floor(x / m))));\n },\n step = x => 1 + (x << 2) - ((x >> 1) << 1);\n return go(n);\n };\n\n // scanl :: (b -> a -> b) -> b -> [a] -> [b]\n const scanl = f => startValue => xs =>\n xs.reduce((a, x) => {\n const v = f(a[0])(x);\n return Tuple(v)(a[1].concat(v));\n }, Tuple(startValue)([startValue]))[1];\n\n // sort :: Ord a => [a] -> [a]\n const sort = xs => xs.slice()\n .sort((a, b) => a < b ? -1 : (a > b ? 1 : 0));\n\n // succ :: Enum a => a -> a\n const succ = x =>\n 1 + x;\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n =>\n // The first n elements of a list,\n // string of characters, or stream.\n xs => 'GeneratorFunction' !== xs\n .constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // until :: (a -> Bool) -> (a -> a) -> a -> a\n const until = p => f => x => {\n let v = x;\n while (!p(v)) v = f(v);\n return v;\n };\n\n // MAIN ---\n return main();\n})();"} +{"title": "Sequence: smallest number with exactly n divisors", "language": "Python", "task": "Calculate the sequence where each term \u00a0 an \u00a0 is the '''smallest natural number''' that has exactly \u00a0 '''n''' \u00a0 divisors.\n\n\n;Task\nShow here, on this page, at least the first \u00a0'''15'''\u00a0 terms of the sequence.\n\n\n;Related tasks:\n:* [[Sequence: smallest number greater than previous term with exactly n divisors]]\n:* [[Sequence: nth number with exactly n divisors\u200e\u200e]]\n\n\n;See also:\n:* OEIS:A005179\n\n", "solution": "def divisors(n):\n divs = [1]\n for ii in range(2, int(n ** 0.5) + 3):\n if n % ii == 0:\n divs.append(ii)\n divs.append(int(n / ii))\n divs.append(n)\n return list(set(divs))\n\n\ndef sequence(max_n=None):\n n = 0\n while True:\n n += 1\n ii = 0\n if max_n is not None:\n if n > max_n:\n break\n while True:\n ii += 1\n if len(divisors(ii)) == n:\n yield ii\n break\n\n\nif __name__ == '__main__':\n for item in sequence(15):\n print(item)"} +{"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 consolidation", "language": "JavaScript", "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": "(() => {\n 'use strict';\n\n // consolidated :: Ord a => [Set a] -> [Set a]\n const consolidated = xs => {\n const go = (s, xs) =>\n 0 !== xs.length ? (() => {\n const h = xs[0];\n return 0 === intersection(h, s).size ? (\n [h].concat(go(s, tail(xs)))\n ) : go(union(h, s), tail(xs));\n })() : [s];\n return foldr(go, [], xs);\n };\n\n\n // TESTS ----------------------------------------------\n const main = () =>\n map(xs => intercalate(\n ', and ',\n map(showSet, consolidated(xs))\n ),\n map(x => map(\n s => new Set(chars(s)),\n x\n ),\n [\n ['ab', 'cd'],\n ['ab', 'bd'],\n ['ab', 'cd', 'db'],\n ['hik', 'ab', 'cd', 'db', 'fgh']\n ]\n )\n ).join('\\n');\n\n\n // GENERIC FUNCTIONS ----------------------------------\n\n // chars :: String -> [Char]\n const chars = s => s.split('');\n\n // concat :: [[a]] -> [a]\n // concat :: [String] -> String\n const concat = xs =>\n 0 < xs.length ? (() => {\n const unit = 'string' !== typeof xs[0] ? (\n []\n ) : '';\n return unit.concat.apply(unit, xs);\n })() : [];\n\n // elems :: Dict -> [a]\n // elems :: Set -> [a]\n const elems = x =>\n 'Set' !== x.constructor.name ? (\n Object.values(x)\n ) : Array.from(x.values());\n\n // flip :: (a -> b -> c) -> b -> a -> c\n const flip = f =>\n 1 < f.length ? (\n (a, b) => f(b, a)\n ) : (x => y => f(y)(x));\n\n // Note that that the Haskell signature of foldr differs from that of\n // foldl - the positions of accumulator and current value are reversed\n\n // foldr :: (a -> b -> b) -> b -> [a] -> b\n const foldr = (f, a, xs) => xs.reduceRight(flip(f), a);\n\n // intercalate :: [a] -> [[a]] -> [a]\n // intercalate :: String -> [String] -> String\n const intercalate = (sep, xs) =>\n 0 < xs.length && 'string' === typeof sep &&\n 'string' === typeof xs[0] ? (\n xs.join(sep)\n ) : concat(intersperse(sep, xs));\n\n // intersection :: Ord a => Set a -> Set a -> Set a\n const intersection = (s, s1) =>\n new Set([...s].filter(x => s1.has(x)));\n\n // intersperse :: a -> [a] -> [a]\n // intersperse :: Char -> String -> String\n const intersperse = (sep, xs) => {\n const bln = 'string' === typeof xs;\n return xs.length > 1 ? (\n (bln ? concat : x => x)(\n (bln ? (\n xs.split('')\n ) : xs)\n .slice(1)\n .reduce((a, x) => a.concat([sep, x]), [xs[0]])\n )) : xs;\n };\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) => xs.map(f);\n\n // showSet :: Set -> String\n const showSet = s =>\n intercalate(elems(s), ['{', '}']);\n\n // sort :: Ord a => [a] -> [a]\n const sort = xs => xs.slice()\n .sort((a, b) => a < b ? -1 : (a > b ? 1 : 0));\n\n // tail :: [a] -> [a]\n const tail = xs => 0 < xs.length ? xs.slice(1) : [];\n\n // union :: Ord a => Set a -> Set a -> Set a\n const union = (s, s1) =>\n Array.from(s1.values())\n .reduce(\n (a, x) => (a.add(x), a),\n new Set(s)\n );\n\n // MAIN ---\n return main();\n})();"} +{"title": "Set consolidation", "language": "Python", "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": "def _test(consolidate=consolidate):\n \n def freze(list_of_sets):\n 'return a set of frozensets from the list of sets to allow comparison'\n return set(frozenset(s) for s in list_of_sets)\n \n # Define some variables\n A,B,C,D,E,F,G,H,I,J,K = 'A,B,C,D,E,F,G,H,I,J,K'.split(',')\n # Consolidate some lists of sets\n assert (freze(consolidate([{A,B}, {C,D}])) == freze([{'A', 'B'}, {'C', 'D'}]))\n assert (freze(consolidate([{A,B}, {B,D}])) == freze([{'A', 'B', 'D'}]))\n assert (freze(consolidate([{A,B}, {C,D}, {D,B}])) == freze([{'A', 'C', 'B', 'D'}]))\n assert (freze(consolidate([{H,I,K}, {A,B}, {C,D}, {D,B}, {F,G,H}])) ==\n freze([{'A', 'C', 'B', 'D'}, {'G', 'F', 'I', 'H', 'K'}]))\n assert (freze(consolidate([{A,H}, {H,I,K}, {A,B}, {C,D}, {D,B}, {F,G,H}])) ==\n freze([{'A', 'C', 'B', 'D', 'G', 'F', 'I', 'H', 'K'}]))\n assert (freze(consolidate([{H,I,K}, {A,B}, {C,D}, {D,B}, {F,G,H}, {A,H}])) ==\n freze([{'A', 'C', 'B', 'D', 'G', 'F', 'I', 'H', 'K'}]))\n # Confirm order-independence\n from copy import deepcopy\n import itertools\n sets = [{H,I,K}, {A,B}, {C,D}, {D,B}, {F,G,H}, {A,H}]\n answer = consolidate(deepcopy(sets))\n for perm in itertools.permutations(sets):\n assert consolidate(deepcopy(perm)) == answer\n \n assert (answer == [{'A', 'C', 'B', 'D', 'G', 'F', 'I', 'H', 'K'}])\n assert (len(list(itertools.permutations(sets))) == 720)\n \n print('_test(%s) complete' % consolidate.__name__)\n\nif __name__ == '__main__':\n _test(consolidate)\n _test(conso)"} +{"title": "Set of real numbers", "language": "C", "task": "All real numbers form the uncountable set \u211d. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers ''a'' and ''b'' where ''a'' \u2264 ''b''. There are actually four cases for the meaning of \"between\", depending on open or closed boundary:\n* [''a'', ''b'']: {''x'' | ''a'' \u2264 ''x'' and ''x'' \u2264 ''b'' }\n* (''a'', ''b''): {''x'' | ''a'' < ''x'' and ''x'' < ''b'' }\n* [''a'', ''b''): {''x'' | ''a'' \u2264 ''x'' and ''x'' < ''b'' }\n* (''a'', ''b'']: {''x'' | ''a'' < ''x'' and ''x'' \u2264 ''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'' \u2208 ''A'': determine if ''x'' is an element of ''A''\n:: example: 1 is in [1, 2), while 2, 3, ... are not.\n:* ''A'' \u222a ''B'': union of ''A'' and ''B'', i.e. {''x'' | ''x'' \u2208 ''A'' or ''x'' \u2208 ''B''}\n:: example: [0, 2) \u222a (1, 3) = [0, 3); [0, 1) \u222a (2, 3] = well, [0, 1) \u222a (2, 3]\n:* ''A'' \u2229 ''B'': intersection of ''A'' and ''B'', i.e. {''x'' | ''x'' \u2208 ''A'' and ''x'' \u2208 ''B''}\n:: example: [0, 2) \u2229 (1, 3) = (1, 2); [0, 1) \u2229 (2, 3] = empty set\n:* ''A'' - ''B'': difference between ''A'' and ''B'', also written as ''A'' \\ ''B'', i.e. {''x'' | ''x'' \u2208 ''A'' and ''x'' \u2209 ''B''}\n:: example: [0, 2) \u2212 (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] \u222a [0, 2)\n:* [0, 2) \u2229 (1, 2]\n:* [0, 3) \u2212 (0, 1)\n:* [0, 3) \u2212 [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 ''[http://www.wolframalpha.com/input/?i=%7Csin%28pi+x2%29%7C%3E1%2F2%2C+0+%3C+x+%3C+10 A]'' = {''x'' | 0 < ''x'' < 10 and |sin(\u03c0 ''x''\u00b2)| > 1/2 }, ''[http://www.wolframalpha.com/input/?i=%7Csin%28pi+x%29%7C%3E1%2F2%2C+0+%3C+x+%3C+10 B]'' = {''x'' | 0 < ''x'' < 10 and |sin(\u03c0 ''x'')| > 1/2}, calculate the length of the real axis covered by the set ''A'' \u2212 ''B''. Note that \n|sin(\u03c0 ''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": "Set of real numbers", "language": "Python", "task": "All real numbers form the uncountable set \u211d. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers ''a'' and ''b'' where ''a'' \u2264 ''b''. There are actually four cases for the meaning of \"between\", depending on open or closed boundary:\n* [''a'', ''b'']: {''x'' | ''a'' \u2264 ''x'' and ''x'' \u2264 ''b'' }\n* (''a'', ''b''): {''x'' | ''a'' < ''x'' and ''x'' < ''b'' }\n* [''a'', ''b''): {''x'' | ''a'' \u2264 ''x'' and ''x'' < ''b'' }\n* (''a'', ''b'']: {''x'' | ''a'' < ''x'' and ''x'' \u2264 ''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'' \u2208 ''A'': determine if ''x'' is an element of ''A''\n:: example: 1 is in [1, 2), while 2, 3, ... are not.\n:* ''A'' \u222a ''B'': union of ''A'' and ''B'', i.e. {''x'' | ''x'' \u2208 ''A'' or ''x'' \u2208 ''B''}\n:: example: [0, 2) \u222a (1, 3) = [0, 3); [0, 1) \u222a (2, 3] = well, [0, 1) \u222a (2, 3]\n:* ''A'' \u2229 ''B'': intersection of ''A'' and ''B'', i.e. {''x'' | ''x'' \u2208 ''A'' and ''x'' \u2208 ''B''}\n:: example: [0, 2) \u2229 (1, 3) = (1, 2); [0, 1) \u2229 (2, 3] = empty set\n:* ''A'' - ''B'': difference between ''A'' and ''B'', also written as ''A'' \\ ''B'', i.e. {''x'' | ''x'' \u2208 ''A'' and ''x'' \u2209 ''B''}\n:: example: [0, 2) \u2212 (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] \u222a [0, 2)\n:* [0, 2) \u2229 (1, 2]\n:* [0, 3) \u2212 (0, 1)\n:* [0, 3) \u2212 [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 ''[http://www.wolframalpha.com/input/?i=%7Csin%28pi+x2%29%7C%3E1%2F2%2C+0+%3C+x+%3C+10 A]'' = {''x'' | 0 < ''x'' < 10 and |sin(\u03c0 ''x''\u00b2)| > 1/2 }, ''[http://www.wolframalpha.com/input/?i=%7Csin%28pi+x%29%7C%3E1%2F2%2C+0+%3C+x+%3C+10 B]'' = {''x'' | 0 < ''x'' < 10 and |sin(\u03c0 ''x'')| > 1/2}, calculate the length of the real axis covered by the set ''A'' \u2212 ''B''. Note that \n|sin(\u03c0 ''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": "class Setr():\n def __init__(self, lo, hi, includelo=True, includehi=False):\n self.eqn = \"(%i<%sX<%s%i)\" % (lo,\n '=' if includelo else '',\n '=' if includehi else '',\n hi)\n\n def __contains__(self, X):\n return eval(self.eqn, locals())\n\n # union\n def __or__(self, b):\n ans = Setr(0,0)\n ans.eqn = \"(%sor%s)\" % (self.eqn, b.eqn)\n return ans\n\n # intersection\n def __and__(self, b):\n ans = Setr(0,0)\n ans.eqn = \"(%sand%s)\" % (self.eqn, b.eqn)\n return ans\n\n # difference\n def __sub__(self, b):\n ans = Setr(0,0)\n ans.eqn = \"(%sand not%s)\" % (self.eqn, b.eqn)\n return ans\n\n def __repr__(self):\n return \"Setr%s\" % self.eqn\n\n\nsets = [\n Setr(0,1, 0,1) | Setr(0,2, 1,0),\n Setr(0,2, 1,0) & Setr(1,2, 0,1),\n Setr(0,3, 1,0) - Setr(0,1, 0,0),\n Setr(0,3, 1,0) - Setr(0,1, 1,1),\n]\nsettexts = '(0, 1] \u222a [0, 2);[0, 2) \u2229 (1, 2];[0, 3) \u2212 (0, 1);[0, 3) \u2212 [0, 1]'.split(';')\n\nfor s,t in zip(sets, settexts):\n print(\"Set %s %s. %s\" % (t,\n ', '.join(\"%scludes %i\"\n % ('in' if v in s else 'ex', v)\n for v in range(3)),\n s.eqn))"} +{"title": "Set right-adjacent bits", "language": "Python", "task": "Given a left-to-right ordered collection of e bits, b, where 1 <= e <= 10000, \nand a zero or more integer n :\n* Output the result of setting the n bits to the right of any set bit in b \n(if those bits are present in b and therefore also preserving the width, e).\n \n'''Some examples:''' \n\n Set of examples showing how one bit in a nibble gets changed:\n \n n = 2; Width e = 4:\n \n Input b: 1000\n Result: 1110\n \n Input b: 0100\n Result: 0111\n \n Input b: 0010\n Result: 0011\n \n Input b: 0000\n Result: 0000\n \n Set of examples with the same input with set bits of varying distance apart:\n \n n = 0; Width e = 66:\n \n Input b: 010000000000100000000010000000010000000100000010000010000100010010\n Result: 010000000000100000000010000000010000000100000010000010000100010010\n \n n = 1; Width e = 66:\n \n Input b: 010000000000100000000010000000010000000100000010000010000100010010\n Result: 011000000000110000000011000000011000000110000011000011000110011011\n \n n = 2; Width e = 66:\n \n Input b: 010000000000100000000010000000010000000100000010000010000100010010\n Result: 011100000000111000000011100000011100000111000011100011100111011111\n \n n = 3; Width e = 66:\n \n Input b: 010000000000100000000010000000010000000100000010000010000100010010\n Result: 011110000000111100000011110000011110000111100011110011110111111111\n\n'''Task:'''\n\n* Implement a routine to perform the setting of right-adjacent bits on representations of bits that will scale over the given range of input width e.\n* Use it to show, here, the results for the input examples above.\n* Print the output aligned in a way that allows easy checking by eye of the binary input vs output.\n\n", "solution": "from operator import or_\nfrom functools import reduce\n\ndef set_right_adjacent_bits(n: int, b: int) -> int:\n return reduce(or_, (b >> x for x in range(n+1)), 0)\n\n\nif __name__ == \"__main__\":\n print(\"SAME n & Width.\\n\")\n n = 2 # bits to the right of set bits, to also set\n bits = \"1000 0100 0010 0000\"\n first = True\n for b_str in bits.split():\n b = int(b_str, 2)\n e = len(b_str)\n if first:\n first = False\n print(f\"n = {n}; Width e = {e}:\\n\")\n result = set_right_adjacent_bits(n, b)\n print(f\" Input b: {b:0{e}b}\")\n print(f\" Result: {result:0{e}b}\\n\")\n \n print(\"SAME Input & Width.\\n\")\n #bits = \"01000010001001010110\"\n bits = '01' + '1'.join('0'*x for x in range(10, 0, -1))\n for n in range(4):\n first = True\n for b_str in bits.split():\n b = int(b_str, 2)\n e = len(b_str)\n if first:\n first = False\n print(f\"n = {n}; Width e = {e}:\\n\")\n result = set_right_adjacent_bits(n, b)\n print(f\" Input b: {b:0{e}b}\")\n print(f\" Result: {result:0{e}b}\\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": "\n#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": "Shoelace formula for polygonal area", "language": "JavaScript", "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": "(() => {\n \"use strict\";\n\n // ------- SHOELACE FORMULA FOR POLYGONAL AREA -------\n\n // shoelaceArea :: [(Float, Float)] -> Float\n const shoeLaceArea = vertices => abs(\n uncurry(subtract)(\n ap(zip)(compose(tail, cycle))(\n vertices\n )\n .reduce(\n (a, x) => [0, 1].map(b => {\n const n = Number(b);\n\n return a[n] + (\n x[0][n] * x[1][Number(!b)]\n );\n }),\n [0, 0]\n )\n )\n ) / 2;\n\n\n // ----------------------- TEST -----------------------\n const main = () => {\n const ps = [\n [3, 4],\n [5, 11],\n [12, 8],\n [9, 5],\n [5, 6]\n ];\n\n return [\n \"Polygonal area by shoelace formula:\",\n `${JSON.stringify(ps)} -> ${shoeLaceArea(ps)}`\n ]\n .join(\"\\n\");\n };\n\n\n // ---------------- GENERIC FUNCTIONS -----------------\n\n // abs :: Num -> Num\n const abs = x =>\n // Absolute value of a given number\n // without the sign.\n 0 > x ? -x : x;\n\n\n // ap :: (a -> b -> c) -> (a -> b) -> (a -> c)\n const ap = f =>\n // Applicative instance for functions.\n // f(x) applied to g(x).\n g => x => f(x)(\n g(x)\n );\n\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (...fs) =>\n // A function defined by the right-to-left\n // composition of all the functions in fs.\n fs.reduce(\n (f, g) => x => f(g(x)),\n x => x\n );\n\n\n // cycle :: [a] -> Generator [a]\n const cycle = function* (xs) {\n // An infinite repetition of xs,\n // from which an arbitrary prefix\n // may be taken.\n const lng = xs.length;\n let i = 0;\n\n while (true) {\n yield xs[i];\n i = (1 + i) % lng;\n }\n };\n\n\n // length :: [a] -> Int\n const length = xs =>\n // Returns Infinity over objects without finite\n // length. This enables zip and zipWith to choose\n // the shorter argument when one is non-finite,\n // like cycle, repeat etc\n \"GeneratorFunction\" !== xs.constructor\n .constructor.name ? (\n xs.length\n ) : Infinity;\n\n\n // subtract :: Num -> Num -> Num\n const subtract = x =>\n y => y - x;\n\n\n // tail :: [a] -> [a]\n const tail = xs =>\n // A new list consisting of all\n // items of xs except the first.\n \"GeneratorFunction\" !== xs.constructor\n .constructor.name ? (\n Boolean(xs.length) ? (\n xs.slice(1)\n ) : undefined\n ) : (take(1)(xs), xs);\n\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n =>\n // The first n elements of a list,\n // string of characters, or stream.\n xs => \"GeneratorFunction\" !== xs\n .constructor.constructor.name ? (\n xs.slice(0, n)\n ) : Array.from({\n length: n\n }, () => {\n const x = xs.next();\n\n return x.done ? [] : [x.value];\n }).flat();\n\n\n // uncurry :: (a -> b -> c) -> ((a, b) -> c)\n const uncurry = f =>\n // A function over a pair, derived\n // from a curried function.\n (...args) => {\n const [x, y] = Boolean(args.length % 2) ? (\n args[0]\n ) : args;\n\n return f(x)(y);\n };\n\n\n // zip :: [a] -> [b] -> [(a, b)]\n const zip = xs => ys => {\n const\n n = Math.min(length(xs), length(ys)),\n vs = take(n)(ys);\n\n return take(n)(xs)\n .map((x, i) => [x, vs[i]]);\n };\n\n\n // MAIN ---\n return main();\n})();"} +{"title": "Shoelace formula for polygonal area", "language": "Python", "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": "\n# Even simpler:\n# In python we can take an advantage of that x[-1] refers to the last element in an array, same as x[N-1].\n# Introducing the index i=[0,1,2,...,N-1]; i-1=[-1,0,...,N-2]; N is the number of vertices of a polygon.\n# Thus x[i] is a sequence of the x-coordinate of the polygon vertices, x[i-1] is the sequence shifted by 1 index.\n# Note that the shift must be negative. The positive shift x[i+1] results in an error: x[N] index out of bound.\n\nimport numpy as np\n# x,y are arrays containing coordinates of the polygon vertices\nx=np.array([3,5,12,9,5]) \ny=np.array([4,11,8,5,6]) \ni=np.arange(len(x))\n#Area=np.sum(x[i-1]*y[i]-x[i]*y[i-1])*0.5 # signed area, positive if the vertex sequence is counterclockwise\nArea=np.abs(np.sum(x[i-1]*y[i]-x[i]*y[i-1])*0.5) # one line of code for the shoelace formula\n\n# Remember that applying the Shoelace formula\n# will result in a loss of precision if x,y have big offsets.\n# Remove the offsets first, e.g. \n# x=x-np.mean(x);y=y-np.mean(y)\n# or\n# x=x-x[0];y=y-y[0]\n# before applying the Shoelace formula. \n\n"} +{"title": "Shoelace formula for polygonal area", "language": "Python 3.7", "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": "'''Polygonal area by shoelace formula'''\n\nfrom itertools import cycle, islice\nfrom functools import reduce\nfrom operator import sub\n\n# --------- SHOELACE FORMULA FOR POLYGONAL AREA ----------\n\n# shoelaceArea :: [(Float, Float)] -> Float\ndef shoelaceArea(xys):\n '''Area of polygon with vertices\n at (x, y) points in xys.\n '''\n def go(a, tpl):\n l, r = a\n (x, y), (dx, dy) = tpl\n return l + x * dy, r + y * dx\n\n return abs(sub(*reduce(\n go,\n zip(\n xys,\n islice(cycle(xys), 1, None)\n ),\n (0, 0)\n ))) / 2\n\n\n# ------------------------- TEST -------------------------\n# main :: IO()\ndef main():\n '''Sample calculation'''\n\n ps = [(3, 4), (5, 11), (12, 8), (9, 5), (5, 6)]\n print(__doc__ + ':')\n print(repr(ps) + ' -> ' + str(shoelaceArea(ps)))\n\n\nif __name__ == '__main__':\n main()"} +{"title": "Shortest common supersequence", "language": "C", "task": "The \u00a0 '''shortest common supersequence''' \u00a0 is a problem closely related to the \u00a0 [[longest common subsequence]], \u00a0 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 = \u201cabcbdab\u201d and v = \u201cbdcaba\u201d.\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": "Shortest common supersequence", "language": "Python", "task": "The \u00a0 '''shortest common supersequence''' \u00a0 is a problem closely related to the \u00a0 [[longest common subsequence]], \u00a0 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 = \u201cabcbdab\u201d and v = \u201cbdcaba\u201d.\n\n\n\n;Also see:\n* Wikipedia: shortest common supersequence \n\n", "solution": "\n# Use the Longest Common Subsequence algorithm\n\ndef shortest_common_supersequence(a, b):\n lcs = longest_common_subsequence(a, b)\n scs = \"\"\n # Consume lcs\n while len(lcs) > 0:\n if a[0]==lcs[0] and b[0]==lcs[0]:\n # Part of the LCS, so consume from all strings\n scs += lcs[0]\n lcs = lcs[1:]\n a = a[1:]\n b = b[1:]\n elif a[0]==lcs[0]:\n scs += b[0]\n b = b[1:]\n else:\n scs += a[0]\n a = a[1:]\n # append remaining characters\n return scs + a + b\n"} +{"title": "Show ASCII table", "language": "C", "task": ";Task:\nShow \u00a0[https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/ASCII-Table.svg/1261px-ASCII-Table.svg.png the ASCII character set] \u00a0from values \u00a0 '''32''' \u00a0 to \u00a0 '''127''' \u00a0 (decimal) \u00a0 in a table format.\n\n\n\n", "solution": "#include \n\nint main() {\n int i, j;\n char k[4];\n for (i = 0; i < 16; ++i) {\n for (j = 32 + i; j < 128; j += 16) {\n switch (j) {\n default: sprintf(k, \"%c\", j); break;\n case 32: sprintf(k, \"Spc\"); break;\n case 127: sprintf(k, \"Del\"); break;\n }\n printf(\"%3d : %-3s \", j, k);\n }\n printf(\"\\n\");\n }\n return 0;\n}"} +{"title": "Show ASCII table", "language": "JavaScript", "task": ";Task:\nShow \u00a0[https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/ASCII-Table.svg/1261px-ASCII-Table.svg.png the ASCII character set] \u00a0from values \u00a0 '''32''' \u00a0 to \u00a0 '''127''' \u00a0 (decimal) \u00a0 in a table format.\n\n\n\n", "solution": "(() => {\n\n \"use strict\";\n\n // ------------------- ASCII TABLE -------------------\n\n // asciiTable :: String\n const asciiTable = () =>\n transpose(\n chunksOf(16)(\n enumFromTo(32)(127)\n .map(asciiEntry)\n )\n )\n .map(\n xs => xs.map(justifyLeft(12)(\" \"))\n .join(\"\")\n )\n .join(\"\\n\");\n\n // asciiEntry :: Int -> String\n const asciiEntry = n => {\n const k = asciiName(n);\n\n return \"\" === k ? (\n \"\"\n ) : `${justifyRight(4)(\" \")(n.toString())} : ${k}`;\n };\n\n // asciiName :: Int -> String\n const asciiName = n =>\n 32 > n || 127 < n ? (\n \"\"\n ) : 32 === n ? (\n \"Spc\"\n ) : 127 === n ? (\n \"Del\"\n ) : chr(n);\n\n // ---------------- GENERIC FUNCTIONS ----------------\n\n // chr :: Int -> Char\n const chr = x =>\n // The character at unix code-point x.\n String.fromCodePoint(x);\n\n\n // chunksOf :: Int -> [a] -> [[a]]\n const chunksOf = n => {\n // xs split into sublists of length n.\n // The last sublist will be short if n\n // does not evenly divide the length of xs .\n const go = xs => {\n const chunk = xs.slice(0, n);\n\n return 0 < chunk.length ? (\n [chunk].concat(\n go(xs.slice(n))\n )\n ) : [];\n };\n\n return go;\n };\n\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = m =>\n n => Array.from({\n length: 1 + n - m\n }, (_, i) => m + i);\n\n\n // justifyLeft :: Int -> Char -> String -> String\n const justifyLeft = n =>\n // The string s, followed by enough padding (with\n // the character c) to reach the string length n.\n c => s => n > s.length ? (\n s.padEnd(n, c)\n ) : s;\n\n\n // justifyRight :: Int -> Char -> String -> String\n const justifyRight = n =>\n // The string s, preceded by enough padding (with\n // the character c) to reach the string length n.\n c => s => Boolean(s) ? (\n s.padStart(n, c)\n ) : \"\";\n\n\n // transpose :: [[a]] -> [[a]]\n const transpose = rows =>\n // The columns of the input transposed\n // into new rows.\n // This version assumes input rows of even length.\n 0 < rows.length ? rows[0].map(\n (x, i) => rows.flatMap(\n v => v[i]\n )\n ) : [];\n\n\n // MAIN ---\n return asciiTable();\n})();"} +{"title": "Show ASCII table", "language": "Python", "task": ";Task:\nShow \u00a0[https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/ASCII-Table.svg/1261px-ASCII-Table.svg.png the ASCII character set] \u00a0from values \u00a0 '''32''' \u00a0 to \u00a0 '''127''' \u00a0 (decimal) \u00a0 in a table format.\n\n\n\n", "solution": "\nfor i in range(16):\n for j in range(32+i, 127+1, 16):\n if j == 32:\n k = 'Spc'\n elif j == 127:\n k = 'Del'\n else:\n k = chr(j)\n print(\"%3d : %-3s\" % (j,k), end=\"\")\n print()\n"} +{"title": "Show the epoch", "language": "C", "task": ";Task: \nChoose popular date libraries used by your language and show the \u00a0 epoch \u00a0 those libraries use. \n\nA demonstration is preferable \u00a0 (e.g. setting the internal representation of the date to 0 ms/ns/etc., \u00a0 or another way that will still show the epoch even if it is changed behind the scenes by the implementers), \u00a0 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* \u00a0 [[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": "Show the epoch", "language": "Python", "task": ";Task: \nChoose popular date libraries used by your language and show the \u00a0 epoch \u00a0 those libraries use. \n\nA demonstration is preferable \u00a0 (e.g. setting the internal representation of the date to 0 ms/ns/etc., \u00a0 or another way that will still show the epoch even if it is changed behind the scenes by the implementers), \u00a0 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* \u00a0 [[Date format]]\n\n", "solution": ">>> import time\n>>> time.asctime(time.gmtime(0))\n'Thu Jan 1 00:00:00 1970'\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* [http://ecademy.agnesscott.edu/~lriddle/ifs/pentagon/pentagon.htm Sierpinski pentagon]\n\n", "solution": "\n#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"} +{"title": "Sierpinski pentagon", "language": "JavaScript", "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* [http://ecademy.agnesscott.edu/~lriddle/ifs/pentagon/pentagon.htm Sierpinski pentagon]\n\n", "solution": "\n\n\n\n\n\nClick Pentaflake to iterate.\u00a0 Order: 0\u00a0\u00a0\n \t\u00a0\u00a0\n \t(Reset anytime: to start new Pentaflake and change color.)\n \t\n\n\n\n"} +{"title": "Sierpinski pentagon", "language": "Python", "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* [http://ecademy.agnesscott.edu/~lriddle/ifs/pentagon/pentagon.htm Sierpinski pentagon]\n\n", "solution": "from turtle import *\nimport math\nspeed(0) # 0 is the fastest speed. Otherwise, 1 (slow) to 10 (fast)\nhideturtle() # hide the default turtle\n\npart_ratio = 2 * math.cos(math.radians(72))\nside_ratio = 1 / (part_ratio + 2)\n\nhide_turtles = True # show/hide turtles as they draw\npath_color = \"black\" # path color\nfill_color = \"black\" # fill color\n\n# turtle, size\ndef pentagon(t, s):\n t.color(path_color, fill_color)\n t.pendown()\n t.right(36)\n t.begin_fill()\n for i in range(5):\n t.forward(s)\n t.right(72)\n t.end_fill()\n\n# iteration, turtle, size\ndef sierpinski(i, t, s):\n t.setheading(0)\n new_size = s * side_ratio\n \n if i > 1:\n i -= 1\n \n # create four more turtles\n for j in range(4):\n t.right(36)\n short = s * side_ratio / part_ratio\n dist = [short, s, s, short][j]\n \n # spawn a turtle\n spawn = Turtle()\n if hide_turtles:spawn.hideturtle()\n spawn.penup()\n spawn.setposition(t.position())\n spawn.setheading(t.heading())\n spawn.forward(dist)\n \n # recurse for spawned turtles\n sierpinski(i, spawn, new_size)\n \n # recurse for parent turtle\n sierpinski(i, t, new_size)\n \n else:\n # draw a pentagon\n pentagon(t, s)\n # delete turtle\n del t\n\ndef main():\n t = Turtle()\n t.hideturtle()\n t.penup()\n screen = t.getscreen()\n y = screen.window_height()\n t.goto(0, y/2-20)\n \n i = 5 # depth. i >= 1\n size = 300 # side length\n \n # so the spawned turtles move only the distance to an inner pentagon\n size *= part_ratio\n \n # begin recursion\n sierpinski(i, t, size)\n\nmain()"} +{"title": "Sierpinski triangle/Graphical", "language": "C", "task": "Produce a graphical representation of a Sierpinski triangle of order N in any orientation. \n\nAn example of Sierpinski's triangle (order = 8) looks like this: \n[[File:Sierpinski_Triangle_Unicon.PNG]]\n\n", "solution": "#include \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": "Sierpinski triangle/Graphical", "language": "JavaScript", "task": "Produce a graphical representation of a Sierpinski triangle of order N in any orientation. \n\nAn example of Sierpinski's triangle (order = 8) looks like this: \n[[File:Sierpinski_Triangle_Unicon.PNG]]\n\n", "solution": ";Note:\n* \"Order\" to calculate a size of resulting plot/matrix is not used in this algorithm, Instead, construction is done in accordance to a square \u00a0 m x m matrix. In our case it should be equal to a size of the square canvas.\n* Change canvas setting from size \"640\" to \"1280\". You will discover that density of dots in plotted triangle is stable for this algorithm. Size of the plotted figure is constantly increasing in the S-E direction. Also, the number of all triangles in N-W triangular part of the canvas is always the same.\n* So, in this case it could be called: \"Sierpinski ever-expanding field of triangles\".\n
\n"} +{"title": "Sierpinski triangle/Graphical", "language": "Chrome", "task": "Produce a graphical representation of a Sierpinski triangle of order N in any orientation. \n\nAn example of Sierpinski's triangle (order = 8) looks like this: \n[[File:Sierpinski_Triangle_Unicon.PNG]]\n\n", "solution": "\n\n\nSierpinski Triangle Fractal\n\n\nPlease click to start and/or change color: \n\u00a0\u00a0\n Sierpinski triangle fractal\n\n\n\n"} +{"title": "Sierpinski triangle/Graphical", "language": "Python", "task": "Produce a graphical representation of a Sierpinski triangle of order N in any orientation. \n\nAn example of Sierpinski's triangle (order = 8) looks like this: \n[[File:Sierpinski_Triangle_Unicon.PNG]]\n\n", "solution": "##########################################################################################\n#\t\tThe drawing function\n#\t\t--------------------\n#\n# level\t\tlevel of Sierpinski triangle (minimum value = 1)\n# ss\t\tscreensize (Draws on a screen of size ss x ss. Default value = 400.)\n#-----------------------------------------------------------------------------------------\ndef DrawSierpinskiTriangle(level, ss=400):\n\t# typical values\n\tturn = 0\t\t# initial turn (0 to start horizontally)\n\tangle=60.0 \t\t# in degrees\n\n\t# Initialize the turtle\n\tturtle.hideturtle()\n\tturtle.screensize(ss,ss)\n\tturtle.penup()\n\tturtle.degrees()\n\n\t# The starting point on the canvas\n\tfwd0 = float(ss)\n\tpoint=array([-fwd0/2.0, -fwd0/2.0])\n\n\t# Setting up the Lindenmayer system\n\t# Assuming that the triangle will be drawn in the following way:\n\t#\t1.) Start at a point\n\t#\t2.) Draw a straight line - the horizontal line (H)\n\t#\t3.) Bend twice by 60 degrees to the left (--)\n\t#\t4.) Draw a straight line - the slanted line (X)\n\t#\t5.) Bend twice by 60 degrees to the left (--)\n\t#\t6.) Draw a straight line - another slanted line (X)\n\t# \t\tThis produces the triangle in the first level. (so the axiom to begin with is H--X--X)\n\t#\t7.) For the next level replace each horizontal line using\n\t#\t\tX->XX\n\t#\t\tH -> H--X++H++X--H\n\t#\t\t\tThe lengths will be halved.\n\n\n\tdecode = {'-':Left, '+':Right, 'X':Forward, 'H':Forward}\n\taxiom = 'H--X--X'\n\n\t# Start the drawing\n\tturtle.goto(point[0], point[1])\n\tturtle.pendown()\n\tturtle.hideturtle()\n\tturt=turtle.getpen()\n\tstartposition=turt.clone()\n\n\t# Get the triangle in the Lindenmayer system\n\tfwd = fwd0/(2.0**level)\n\tpath = axiom\n\tfor i in range(0,level):\n\t\tpath=path.replace('X','XX')\n\t\tpath=path.replace('H','H--X++H++X--H')\n\n\t# Draw it.\n\tfor i in path:\n\t\t[turn, point, fwd, angle, turt]=decode[i](turn, point, fwd, angle, turt)\n##########################################################################################\n\nDrawSierpinskiTriangle(5)\n"} +{"title": "Simple turtle graphics", "language": "Python", "task": "The first turtle graphic discussed in [https://mindstorms.media.mit.edu Mindstorms: Children, Computers, and Powerful Ideas] by Seymour Papert is a simple drawing of a house. It is a square with a triangle on top for the roof. \n\nFor a slightly more advanced audience, a more practical introduction to turtle graphics might be to draw a bar chart. \n\nthumb\n\n;Task:\n::* Create a function (or subroutine) that uses turtle graphics to draw a house of a specified size as depicted. Optionally make it lovely by adding details such as, for example, doors and windows.\n\n::* Create a function (or subroutine) that takes a list (array, vector) of non-negative numbers and draws a bar chart from them, scaled to fit exactly in a square of a specified size. The enclosing square need not be drawn. \n\n::* Both functions should return the turtle to the location it was at and facing in the same direction as it was immediately before the function was executed. \n\n", "solution": "from turtle import *\n\ndef rectangle(width, height):\n for _ in range(2):\n forward(height)\n left(90)\n forward(width)\n left(90)\n \ndef square(size):\n rectangle(size, size)\n\ndef triangle(size):\n for _ in range(3):\n forward(size)\n right(120)\n \ndef house(size):\n right(180)\n square(size)\n triangle(size)\n right(180)\n \ndef barchart(lst, size):\n scale = size/max(lst)\n width = size/len(lst)\n for i in lst:\n rectangle(i*scale, width)\n penup()\n forward(width)\n pendown()\n penup()\n back(size)\n pendown()\n \nclearscreen()\nhideturtle()\nhouse(150)\npenup()\nforward(10)\npendown()\nbarchart([0.5, (1/3), 2, 1.3, 0.5], 200)\npenup()\nback(10)\npendown()"} +{"title": "Singular value decomposition", "language": "C", "task": "A is any m by n matrix, square or rectangular. Its rank is r. We will diagonalize this A, but not by X^{\u22121}AX.\nThe eigenvectors in X have three big problems: They are usually not orthogonal, there\nare not always enough eigenvectors, and Ax = \u03bbx requires A to be a square matrix. The\nsingular vectors of A solve all those problems in a perfect way. \n\n[https://math.mit.edu/classes/18.095/2016IAP/lec2/SVD_Notes.pdf The Singular Value Decomposition (SVD)] \n\nAccording to the web page above, for any rectangular matrix A, we can decomposite it as A=U\u03a3V^T\n\n''' Task Description''' \n\nFirstly, input two numbers \"m\" and \"n\". \n\nThen, input a square/rectangular matrix A^{m\\times n}. \n\nFinally, output U,\u03a3,V with respect to A.\n\n''' Example ''' \n\nSample Input\n\n2 2\n3 0\n4 5\n \n\nFrom the input above we can know that A is a 2 by 2 matrix. \n\nSample Output\n \n0.31622776601683794 -0.9486832980505138\n0.9486832980505138 0.31622776601683794\n\n6.708203932499369 0\n0 2.23606797749979\n\n0.7071067811865475 -0.7071067811865475\n0.7071067811865475 0.7071067811865475\n \n\nThe output may vary depending your choice of the data types. \n\n'''Remark''' \n\n1. It\u2019s encouraged to implement the algorithm by yourself while using libraries is still acceptible. \n\n2. The algorithm should be applicable for general case(m\\times n).\n\n\n", "solution": "#include \n#include \n\n/* Custom function for printing a gsl_matrix in matrix form. */\nvoid gsl_matrix_print(const gsl_matrix *M) {\n int rows = M->size1;\n int cols = M->size2;\n for (int i = 0; i < rows; i++) {\n printf(\"|\");\n for (int j = 0; j < cols; j++) {\n printf(\"% 12.10f \", gsl_matrix_get(M, i, j));\n }\n printf(\"\\b|\\n\");\n }\n printf(\"\\n\");\n}\n\nint main(){\n double a[] = {3, 0, 4, 5};\n gsl_matrix_view A = gsl_matrix_view_array(a, 2, 2);\n gsl_matrix *V = gsl_matrix_alloc(2, 2);\n gsl_vector *S = gsl_vector_alloc(2);\n gsl_vector *work = gsl_vector_alloc(2);\n\n /* V is returned here in untransposed form. */\n gsl_linalg_SV_decomp(&A.matrix, V, S, work);\n gsl_matrix_transpose(V);\n double s[] = {S->data[0], 0, 0, S->data[1]};\n gsl_matrix_view SM = gsl_matrix_view_array(s, 2, 2);\n\n printf(\"U:\\n\");\n gsl_matrix_print(&A.matrix);\n\n printf(\"S:\\n\");\n gsl_matrix_print(&SM.matrix);\n\n printf(\"VT:\\n\");\n gsl_matrix_print(V);\n \n gsl_matrix_free(V);\n gsl_vector_free(S);\n gsl_vector_free(work);\n return 0;\n}"} +{"title": "Singular value decomposition", "language": "Python", "task": "A is any m by n matrix, square or rectangular. Its rank is r. We will diagonalize this A, but not by X^{\u22121}AX.\nThe eigenvectors in X have three big problems: They are usually not orthogonal, there\nare not always enough eigenvectors, and Ax = \u03bbx requires A to be a square matrix. The\nsingular vectors of A solve all those problems in a perfect way. \n\n[https://math.mit.edu/classes/18.095/2016IAP/lec2/SVD_Notes.pdf The Singular Value Decomposition (SVD)] \n\nAccording to the web page above, for any rectangular matrix A, we can decomposite it as A=U\u03a3V^T\n\n''' Task Description''' \n\nFirstly, input two numbers \"m\" and \"n\". \n\nThen, input a square/rectangular matrix A^{m\\times n}. \n\nFinally, output U,\u03a3,V with respect to A.\n\n''' Example ''' \n\nSample Input\n\n2 2\n3 0\n4 5\n \n\nFrom the input above we can know that A is a 2 by 2 matrix. \n\nSample Output\n \n0.31622776601683794 -0.9486832980505138\n0.9486832980505138 0.31622776601683794\n\n6.708203932499369 0\n0 2.23606797749979\n\n0.7071067811865475 -0.7071067811865475\n0.7071067811865475 0.7071067811865475\n \n\nThe output may vary depending your choice of the data types. \n\n'''Remark''' \n\n1. It\u2019s encouraged to implement the algorithm by yourself while using libraries is still acceptible. \n\n2. The algorithm should be applicable for general case(m\\times n).\n\n\n", "solution": "\nfrom numpy import *\nA = matrix([[3, 0], [4, 5]])\nU, Sigma, VT = linalg.svd(A)\nprint(U)\nprint(Sigma)\nprint(VT)\n"} +{"title": "Smith numbers", "language": "C", "task": "sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. \n\nBy definition, all primes are ''excluded'' as they (naturally) satisfy this condition!\n\nSmith numbers are also known as \u00a0 ''joke'' \u00a0 numbers.\n\n\n;Example\nUsing the number '''166'''\nFind the prime factors of '''166''' which are: '''2''' x '''83'''\nThen, take those two prime factors and sum all their decimal digits: '''2 + 8 + 3''' which is '''13'''\nThen, take the decimal digits of '''166''' and add their decimal digits: '''1 + 6 + 6''' which is '''13'''\nTherefore, the number '''166''' is a Smith number.\n\n\n;Task\nWrite a program to find all Smith numbers ''below'' 10000.\n\n\n;See also\n* from Wikipedia: \u00a0 [[https://en.wikipedia.org/wiki/Smith_number Smith number]].\n* from MathWorld: \u00a0 [[http://mathworld.wolfram.com/SmithNumber.html Smith number]]. \n* from OEIS A6753: \u00a0 [[https://oeis.org/A006753 OEIS sequence A6753]].\n* from OEIS A104170: \u00a0 [[https://oeis.org/A104170 Number of Smith numbers below 10^n]]. \n* from The Prime pages: \u00a0 [[http://primes.utm.edu/glossary/xpage/SmithNumber.html Smith numbers]].\n\n", "solution": "\n#include \n#include \n#include \n\nint numPrimeFactors(unsigned x) {\n unsigned p = 2;\n int pf = 0;\n if (x == 1)\n return 1;\n else {\n while (true) {\n if (!(x % p)) {\n pf++;\n x /= p;\n if (x == 1)\n return pf;\n }\n else\n ++p;\n }\n }\n}\n\nvoid primeFactors(unsigned x, unsigned* arr) {\n unsigned p = 2;\n int pf = 0;\n if (x == 1)\n arr[pf] = 1;\n else {\n while (true) {\n if (!(x % p)) {\n arr[pf++] = p;\n x /= p;\n if (x == 1)\n return;\n }\n else\n p++;\n }\n }\n}\n\nunsigned sumDigits(unsigned x) {\n unsigned sum = 0, y;\n while (x) {\n y = x % 10;\n sum += y;\n x /= 10;\n }\n return sum;\n}\n\nunsigned sumFactors(unsigned* arr, int size) {\n unsigned sum = 0;\n for (int a = 0; a < size; a++)\n sum += sumDigits(arr[a]);\n return sum;\n}\n\nvoid listAllSmithNumbers(unsigned x) {\n unsigned *arr;\n for (unsigned a = 4; a < x; a++) {\n int numfactors = numPrimeFactors(a);\n arr = (unsigned*)malloc(numfactors * sizeof(unsigned));\n if (numfactors < 2)\n continue;\t\n primeFactors(a, arr);\t\n if (sumDigits(a) == sumFactors(arr,numfactors))\n printf(\"%4u \",a);\n free(arr);\n }\n}\n\nint main(int argc, char* argv[]) {\n printf(\"All the Smith Numbers < 10000 are:\\n\");\n listAllSmithNumbers(10000);\n return 0;\n}\n"} +{"title": "Smith numbers", "language": "JavaScript", "task": "sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. \n\nBy definition, all primes are ''excluded'' as they (naturally) satisfy this condition!\n\nSmith numbers are also known as \u00a0 ''joke'' \u00a0 numbers.\n\n\n;Example\nUsing the number '''166'''\nFind the prime factors of '''166''' which are: '''2''' x '''83'''\nThen, take those two prime factors and sum all their decimal digits: '''2 + 8 + 3''' which is '''13'''\nThen, take the decimal digits of '''166''' and add their decimal digits: '''1 + 6 + 6''' which is '''13'''\nTherefore, the number '''166''' is a Smith number.\n\n\n;Task\nWrite a program to find all Smith numbers ''below'' 10000.\n\n\n;See also\n* from Wikipedia: \u00a0 [[https://en.wikipedia.org/wiki/Smith_number Smith number]].\n* from MathWorld: \u00a0 [[http://mathworld.wolfram.com/SmithNumber.html Smith number]]. \n* from OEIS A6753: \u00a0 [[https://oeis.org/A006753 OEIS sequence A6753]].\n* from OEIS A104170: \u00a0 [[https://oeis.org/A104170 Number of Smith numbers below 10^n]]. \n* from The Prime pages: \u00a0 [[http://primes.utm.edu/glossary/xpage/SmithNumber.html Smith numbers]].\n\n", "solution": "(() => {\n 'use strict';\n\n // isSmith :: Int -> Bool\n const isSmith = n => {\n const pfs = primeFactors(n);\n return (1 < pfs.length || n !== pfs[0]) && (\n sumDigits(n) === pfs.reduce(\n (a, x) => a + sumDigits(x),\n 0\n )\n );\n };\n\n // TEST -----------------------------------------------\n\n // main :: IO ()\n const main = () => {\n\n // lowSmiths :: [Int]\n const lowSmiths = enumFromTo(2)(9999)\n .filter(isSmith);\n\n // lowSmithCount :: Int\n const lowSmithCount = lowSmiths.length;\n return [\n \"Count of Smith Numbers below 10k:\",\n show(lowSmithCount),\n \"\\nFirst 15 Smith Numbers:\",\n unwords(take(15)(lowSmiths)),\n \"\\nLast 12 Smith Numbers below 10000:\",\n unwords(drop(lowSmithCount - 12)(lowSmiths))\n ].join('\\n');\n };\n\n // SMITH ----------------------------------------------\n\n // primeFactors :: Int -> [Int]\n const primeFactors = x => {\n const go = n => {\n const fs = take(1)(\n dropWhile(x => 0 != n % x)(\n enumFromTo(2)(\n floor(sqrt(n))\n )\n )\n );\n return 0 === fs.length ? [n] : fs.concat(\n go(floor(n / fs[0]))\n );\n };\n return go(x);\n };\n\n // sumDigits :: Int -> Int\n const sumDigits = n =>\n unfoldl(\n x => 0 === x ? (\n Nothing()\n ) : Just(quotRem(x)(10))\n )(n).reduce((a, x) => a + x, 0);\n\n\n // GENERIC --------------------------------------------\n\n // Nothing :: Maybe a\n const Nothing = () => ({\n type: 'Maybe',\n Nothing: true,\n });\n\n // Just :: a -> Maybe a\n const Just = x => ({\n type: 'Maybe',\n Nothing: false,\n Just: x\n });\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = a => b => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // drop :: Int -> [a] -> [a]\n // drop :: Int -> String -> String\n const drop = n => xs =>\n xs.slice(n)\n\n\n // dropWhile :: (a -> Bool) -> [a] -> [a]\n // dropWhile :: (Char -> Bool) -> String -> String\n const dropWhile = p => xs => {\n const lng = xs.length;\n return 0 < lng ? xs.slice(\n until(i => i === lng || !p(xs[i]))(\n i => 1 + i\n )(0)\n ) : [];\n };\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = m => n =>\n Array.from({\n length: 1 + n - m\n }, (_, i) => m + i);\n\n // floor :: Num -> Int\n const floor = Math.floor;\n\n\n // quotRem :: Int -> Int -> (Int, Int)\n const quotRem = m => n =>\n Tuple(Math.floor(m / n))(\n m % n\n );\n\n // show :: a -> String\n const show = x => JSON.stringify(x, null, 2);\n\n // sqrt :: Num -> Num\n const sqrt = n =>\n (0 <= n) ? Math.sqrt(n) : undefined;\n\n // sum :: [Num] -> Num\n const sum = xs => xs.reduce((a, x) => a + x, 0);\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n => xs =>\n 'GeneratorFunction' !== xs.constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n\n // unfoldl :: (b -> Maybe (b, a)) -> b -> [a]\n const unfoldl = f => v => {\n let\n xr = [v, v],\n xs = [];\n while (true) {\n const mb = f(xr[0]);\n if (mb.Nothing) {\n return xs\n } else {\n xr = mb.Just;\n xs = [xr[1]].concat(xs);\n }\n }\n };\n\n // until :: (a -> Bool) -> (a -> a) -> a -> a\n const until = p => f => x => {\n let v = x;\n while (!p(v)) v = f(v);\n return v;\n };\n\n // unwords :: [String] -> String\n const unwords = xs => xs.join(' ');\n\n return main();\n})();"} +{"title": "Smith numbers", "language": "Python", "task": "sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. \n\nBy definition, all primes are ''excluded'' as they (naturally) satisfy this condition!\n\nSmith numbers are also known as \u00a0 ''joke'' \u00a0 numbers.\n\n\n;Example\nUsing the number '''166'''\nFind the prime factors of '''166''' which are: '''2''' x '''83'''\nThen, take those two prime factors and sum all their decimal digits: '''2 + 8 + 3''' which is '''13'''\nThen, take the decimal digits of '''166''' and add their decimal digits: '''1 + 6 + 6''' which is '''13'''\nTherefore, the number '''166''' is a Smith number.\n\n\n;Task\nWrite a program to find all Smith numbers ''below'' 10000.\n\n\n;See also\n* from Wikipedia: \u00a0 [[https://en.wikipedia.org/wiki/Smith_number Smith number]].\n* from MathWorld: \u00a0 [[http://mathworld.wolfram.com/SmithNumber.html Smith number]]. \n* from OEIS A6753: \u00a0 [[https://oeis.org/A006753 OEIS sequence A6753]].\n* from OEIS A104170: \u00a0 [[https://oeis.org/A104170 Number of Smith numbers below 10^n]]. \n* from The Prime pages: \u00a0 [[http://primes.utm.edu/glossary/xpage/SmithNumber.html Smith numbers]].\n\n", "solution": "from sys import stdout\n\n\ndef factors(n):\n rt = []\n f = 2\n if n == 1:\n rt.append(1);\n else:\n while 1:\n if 0 == ( n % f ):\n rt.append(f);\n n //= f\n if n == 1:\n return rt\n else:\n f += 1\n return rt\n\n\ndef sum_digits(n):\n sum = 0\n while n > 0:\n m = n % 10\n sum += m\n n -= m\n n //= 10\n\n return sum\n\n\ndef add_all_digits(lst):\n sum = 0\n for i in range (len(lst)):\n sum += sum_digits(lst[i])\n\n return sum\n\n\ndef list_smith_numbers(cnt):\n for i in range(4, cnt):\n fac = factors(i)\n if len(fac) > 1:\n if sum_digits(i) == add_all_digits(fac):\n stdout.write(\"{0} \".format(i) )\n\n# entry point\nlist_smith_numbers(10_000)"} +{"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": "\n#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": "Soloway's recurring rainfall", "language": "Python", "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": "\nimport sys\n\ndef get_next_input():\n try:\n num = int(input(\"Enter rainfall int, 99999 to quit: \"))\n except:\n print(\"Invalid input\")\n return get_next_input()\n return num\n\ncurrent_average = 0.0\ncurrent_count = 0\n\nwhile True:\n next = get_next_input()\n\n if next == 99999:\n sys.exit()\n else:\n current_count += 1\n current_average = current_average + (1.0/current_count)*next - (1.0/current_count)*current_average\n \n print(\"New average: \", current_average)\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 \u201c1\u201d 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 \u201c1\u201d 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": "Solve a Hidato puzzle", "language": "Python", "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 \u201c1\u201d 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 \u201c1\u201d 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": "board = []\ngiven = []\nstart = None\n\ndef setup(s):\n global board, given, start\n lines = s.splitlines()\n ncols = len(lines[0].split())\n nrows = len(lines)\n board = [[-1] * (ncols + 2) for _ in xrange(nrows + 2)]\n\n for r, row in enumerate(lines):\n for c, cell in enumerate(row.split()):\n if cell == \"__\" :\n board[r + 1][c + 1] = 0\n continue\n elif cell == \".\":\n continue # -1\n else:\n val = int(cell)\n board[r + 1][c + 1] = val\n given.append(val)\n if val == 1:\n start = (r + 1, c + 1)\n given.sort()\n\ndef solve(r, c, n, next=0):\n if n > given[-1]:\n return True\n if board[r][c] and board[r][c] != n:\n return False\n if board[r][c] == 0 and given[next] == n:\n return False\n\n back = 0\n if board[r][c] == n:\n next += 1\n back = n\n\n board[r][c] = n\n for i in xrange(-1, 2):\n for j in xrange(-1, 2):\n if solve(r + i, c + j, n + 1, next):\n return True\n board[r][c] = back\n return False\n\ndef print_board():\n d = {-1: \" \", 0: \"__\"}\n bmax = max(max(r) for r in board)\n form = \"%\" + str(len(str(bmax)) + 1) + \"s\"\n for r in board[1:-1]:\n print \"\".join(form % d.get(c, str(c)) for c in r[1:-1])\n\nhi = \"\"\"\\\n__ 33 35 __ __ . . .\n__ __ 24 22 __ . . .\n__ __ __ 21 __ __ . .\n__ 26 __ 13 40 11 . .\n27 __ __ __ 9 __ 1 .\n . . __ __ 18 __ __ .\n . . . . __ 7 __ __\n . . . . . . 5 __\"\"\"\n\nsetup(hi)\nprint_board()\nsolve(start[0], start[1], 1)\nprint\nprint_board()"} +{"title": "Solve a Holy Knight's tour", "language": "JavaScript", "task": "right\n\nChess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies. \n\nThis kind of knight's tour puzzle is similar to \u00a0 Hidato.\n\nThe present task is to produce a solution to such problems. At least demonstrate your program by solving the following:\n\n\n;Example:\n\n 0 0 0 \n 0 0 0 \n 0 0 0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n1 0 0 0 0 0 0\n 0 0 0\n 0 0 0\n\n\nNote that the zeros represent the available squares, not the pennies.\n\nExtra credit is available for other interesting examples.\n\n\n;Related tasks:\n* [[A* search algorithm]]\n* [[Knight's tour]]\n* [[N-queens problem]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Hopido puzzle]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "(() => {\n 'use strict';\n\n // problems :: [[String]]\n const problems = [\n [\n \" 000 \" //\n , \" 0 00 \" //\n , \" 0000000\" //\n , \"000 0 0\" //\n , \"0 0 000\" //\n , \"1000000 \" //\n , \" 00 0 \" //\n , \" 000 \" //\n ],\n [\n \"-----1-0-----\" //\n , \"-----0-0-----\" //\n , \"----00000----\" //\n , \"-----000-----\" //\n , \"--0--0-0--0--\" //\n , \"00000---00000\" //\n , \"--00-----00--\" //\n , \"00000---00000\" //\n , \"--0--0-0--0--\" //\n , \"-----000-----\" //\n , \"----00000----\" //\n , \"-----0-0-----\" //\n , \"-----0-0-----\" //\n ]\n ];\n\n // GENERIC FUNCTIONS ------------------------------------------------------\n\n // comparing :: (a -> b) -> (a -> a -> Ordering)\n const comparing = f =>\n (x, y) => {\n const\n a = f(x),\n b = f(y);\n return a < b ? -1 : a > b ? 1 : 0\n };\n\n // concat :: [[a]] -> [a] | [String] -> String\n const concat = xs =>\n xs.length > 0 ? (() => {\n const unit = typeof xs[0] === 'string' ? '' : [];\n return unit.concat.apply(unit, xs);\n })() : [];\n\n // charColRow :: Char -> [String] -> Maybe (Int, Int)\n const charColRow = (c, rows) =>\n foldr((a, xs, iRow) =>\n a.nothing ? (() => {\n const mbiCol = elemIndex(c, xs);\n return mbiCol.nothing ? mbiCol : {\n just: [mbiCol.just, iRow],\n nothing: false\n };\n })() : a, {\n nothing: true\n }, rows);\n\n // 2 or more arguments\n // curry :: Function -> Function\n const curry = (f, ...args) => {\n const go = xs => xs.length >= f.length ? (f.apply(null, xs)) :\n function () {\n return go(xs.concat(Array.from(arguments)));\n };\n return go([].slice.call(args, 1));\n };\n\n // elem :: Eq a => a -> [a] -> Bool\n const elem = (x, xs) => xs.indexOf(x) !== -1;\n\n // elemIndex :: Eq a => a -> [a] -> Maybe Int\n const elemIndex = (x, xs) => {\n const i = xs.indexOf(x);\n return {\n nothing: i === -1,\n just: i\n };\n };\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = (m, n) =>\n Array.from({\n length: Math.floor(n - m) + 1\n }, (_, i) => m + i);\n\n // filter :: (a -> Bool) -> [a] -> [a]\n const filter = (f, xs) => xs.filter(f);\n\n // findIndex :: (a -> Bool) -> [a] -> Maybe Int\n const findIndex = (f, xs) => {\n for (var i = 0, lng = xs.length; i < lng; i++) {\n if (f(xs[i])) return {\n nothing: false,\n just: i\n };\n }\n return {\n nothing: true\n };\n };\n\n // foldl :: (b -> a -> b) -> b -> [a] -> b\n const foldl = (f, a, xs) => xs.reduce(f, a);\n\n // foldr (a -> b -> b) -> b -> [a] -> b\n const foldr = (f, a, xs) => xs.reduceRight(f, a);\n\n // groupBy :: (a -> a -> Bool) -> [a] -> [[a]]\n const groupBy = (f, xs) => {\n const dct = xs.slice(1)\n .reduce((a, x) => {\n const\n h = a.active.length > 0 ? a.active[0] : undefined,\n blnGroup = h !== undefined && f(h, x);\n return {\n active: blnGroup ? a.active.concat([x]) : [x],\n sofar: blnGroup ? a.sofar : a.sofar.concat([a.active])\n };\n }, {\n active: xs.length > 0 ? [xs[0]] : [],\n sofar: []\n });\n return dct.sofar.concat(dct.active.length > 0 ? [dct.active] : []);\n };\n\n // intercalate :: String -> [a] -> String\n const intercalate = (s, xs) => xs.join(s);\n\n // intersectBy::(a - > a - > Bool) - > [a] - > [a] - > [a]\n const intersectBy = (eq, xs, ys) =>\n (xs.length > 0 && ys.length > 0) ?\n xs.filter(x => ys.some(curry(eq)(x))) : [];\n\n // justifyRight :: Int -> Char -> Text -> Text\n const justifyRight = (n, cFiller, strText) =>\n n > strText.length ? (\n (cFiller.repeat(n) + strText)\n .slice(-n)\n ) : strText;\n\n // length :: [a] -> Int\n const length = xs => xs.length;\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) => xs.map(f);\n\n // mappendComparing :: [(a -> b)] -> (a -> a -> Ordering)\n const mappendComparing = fs => (x, y) =>\n fs.reduce((ord, f) => {\n if (ord !== 0) return ord;\n const\n a = f(x),\n b = f(y);\n return a < b ? -1 : a > b ? 1 : 0\n }, 0);\n\n // maximumBy :: (a -> a -> Ordering) -> [a] -> a\n const maximumBy = (f, xs) =>\n xs.reduce((a, x) => a === undefined ? x : (\n f(x, a) > 0 ? x : a\n ), undefined);\n\n // min :: Ord a => a -> a -> a\n const min = (a, b) => b < a ? b : a;\n\n // replicate :: Int -> a -> [a]\n const replicate = (n, a) => {\n let v = [a],\n o = [];\n if (n < 1) return o;\n while (n > 1) {\n if (n & 1) o = o.concat(v);\n n >>= 1;\n v = v.concat(v);\n }\n return o.concat(v);\n };\n\n // sortBy :: (a -> a -> Ordering) -> [a] -> [a]\n const sortBy = (f, xs) => xs.slice()\n .sort(f);\n\n // splitOn :: String -> String -> [String]\n const splitOn = (s, xs) => xs.split(s);\n\n // take :: Int -> [a] -> [a]\n const take = (n, xs) => xs.slice(0, n);\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // until :: (a -> Bool) -> (a -> a) -> a -> a\n const until = (p, f, x) => {\n let v = x;\n while (!p(v)) v = f(v);\n return v;\n };\n\n // zip :: [a] -> [b] -> [(a,b)]\n const zip = (xs, ys) =>\n xs.slice(0, Math.min(xs.length, ys.length))\n .map((x, i) => [x, ys[i]]);\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = (f, xs, ys) =>\n Array.from({\n length: min(xs.length, ys.length)\n }, (_, i) => f(xs[i], ys[i]));\n\n // HOLY KNIGHT's TOUR FUNCTIONS -------------------------------------------\n\n // kmoves :: (Int, Int) -> [(Int, Int)]\n const kmoves = ([x, y]) => map(\n ([a, b]) => [a + x, b + y], [\n [1, 2],\n [1, -2],\n [-1, 2],\n [-1, -2],\n [2, 1],\n [2, -1],\n [-2, 1],\n [-2, -1]\n ]);\n\n // rowPosns :: Int -> String -> [(Int, Int)]\n const rowPosns = (iRow, s) => {\n return foldl((a, x, i) => (elem(x, ['0', '1']) ? (\n a.concat([\n [i, iRow]\n ])\n ) : a), [], splitOn('', s));\n };\n\n // hash :: (Int, Int) -> String\n const hash = ([col, row]) => col.toString() + '.' + row.toString();\n\n // Start node, and degree-sorted cache of moves from each node\n // All node references are hash strings (for this cache)\n\n // problemModel :: [[String]] -> {cache: {nodeKey: [nodeKey], start:String}}\n const problemModel = boardLines => {\n const\n steps = foldl((a, xs, i) =>\n a.concat(rowPosns(i, xs)), [], boardLines),\n courseMoves = (xs, [x, y]) => intersectBy(\n ([a, b], [c, d]) => a === c && b === d, kmoves([x, y]), xs\n ),\n maybeStart = charColRow('1', boardLines);\n return {\n start: maybeStart.nothing ? '' : hash(maybeStart.just),\n boardWidth: boardLines.length > 0 ? boardLines[0].length : 0,\n stepCount: steps.length,\n cache: (() => {\n const moveCache = foldl((a, xy) => (\n a[hash(xy)] = map(hash, courseMoves(steps, xy)),\n a\n ), {}, steps),\n lstMoves = Object.keys(moveCache),\n dctDegree = foldl((a, k) =>\n (a[k] = moveCache[k].length,\n a), {}, lstMoves);\n\n return foldl((a, k) => (\n a[k] = sortBy(comparing(x => dctDegree[x]), moveCache[k]),\n a\n ), {}, lstMoves);\n })()\n };\n };\n\n // firstSolution :: {nodeKey: [nodeKey]} -> Int ->\n // nodeKey -> nodeKey -> [nodeKey] ->\n // -> {path::[nodeKey], pathLen::Int, found::Bool}\n const firstSolution = (dctMoves, intTarget, strStart, strNodeKey, path) => {\n const\n intPath = path.length,\n moves = dctMoves[strNodeKey];\n\n if ((intTarget - intPath) < 2 && elem(strStart, moves)) {\n return {\n nothing: false,\n just: [strStart, strNodeKey].concat(path),\n pathLen: intTarget\n };\n }\n\n const\n nexts = filter(k => !elem(k, path), moves),\n intNexts = nexts.length,\n lstFullPath = [strNodeKey].concat(path);\n\n // Until we find a full path back to start\n return until(\n x => (x.nothing === false || x.i >= intNexts),\n x => {\n const\n idx = x.i,\n dctSoln = firstSolution(\n dctMoves, intTarget, strStart, nexts[idx], lstFullPath\n );\n return {\n i: idx + 1,\n nothing: dctSoln.nothing,\n just: dctSoln.just,\n pathLen: dctSoln.pathLen\n };\n }, {\n nothing: true,\n just: [],\n i: 0\n }\n );\n };\n\n // maybeTour :: [String] -> {\n // nothing::Bool, Just::[nodeHash], i::Int: pathLen::Int }\n const maybeTour = trackLines => {\n const\n dctModel = problemModel(trackLines),\n strStart = dctModel.start;\n return strStart !== '' ? firstSolution(\n dctModel.cache, dctModel.stepCount, strStart, strStart, []\n ) : {\n nothing: true\n };\n };\n\n // showLine :: Int -> Int -> String -> Maybe (Int, Int) ->\n // [(Int, Int, String)] -> String\n const showLine = curry((intCell, strFiller, maybeStart, xs) => {\n const\n blnSoln = maybeStart.nothing,\n [startCol, startRow] = blnSoln ? [0, 0] : maybeStart.just;\n return foldl((a, [iCol, iRow, sVal], i, xs) => ({\n col: iCol + 1,\n txt: a.txt +\n concat(replicate((iCol - a.col) * intCell, strFiller)) +\n justifyRight(\n intCell, strFiller,\n (blnSoln ? sVal : (\n iRow === startRow &&\n iCol === startCol ? '1' : '0')\n )\n )\n }), {\n col: 0,\n txt: ''\n },\n xs\n )\n .txt\n });\n\n // solutionString :: [String] -> Int -> String\n const solutionString = (boardLines, iProblem) => {\n const\n dtePre = Date.now(),\n intCols = boardLines.length > 0 ? boardLines[0].length : 0,\n soln = maybeTour(boardLines),\n intMSeconds = Date.now() - dtePre;\n\n if (soln.nothing) return 'No solution found \u2026';\n\n const\n kCol = 0,\n kRow = 1,\n kSeq = 2,\n steps = soln.just,\n lstTriples = zipWith((h, n) => {\n const [col, row] = map(\n x => parseInt(x, 10), splitOn('.', h)\n );\n return [col, row, n.toString()];\n },\n steps,\n enumFromTo(1, soln.pathLen)),\n cellWidth = length(maximumBy(\n comparing(x => length(x[kSeq])), lstTriples\n )[kSeq]) + 1,\n lstGroups = groupBy(\n (a, b) => a[kRow] === b[kRow],\n sortBy(\n mappendComparing([x => x[kRow], x => x[kCol]]),\n lstTriples\n )),\n startXY = take(2, lstTriples[0]),\n strMap = 'PROBLEM ' + (parseInt(iProblem, 10) + 1) + '.\\n\\n' +\n unlines(map(showLine(cellWidth, ' ', {\n nothing: false,\n just: startXY\n }), lstGroups)),\n strSoln = 'First solution found in c. ' +\n intMSeconds + ' milliseconds:\\n\\n' +\n unlines(map(showLine(cellWidth, ' ', {\n nothing: true,\n just: startXY\n }), lstGroups)) + '\\n\\n';\n\n console.log(strSoln);\n return strMap + '\\n\\n' + strSoln;\n };\n\n // TEST -------------------------------------------------------------------\n return unlines(map(solutionString, problems));\n})();"} +{"title": "Solve a Holy Knight's tour", "language": "Python", "task": "right\n\nChess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies. \n\nThis kind of knight's tour puzzle is similar to \u00a0 Hidato.\n\nThe present task is to produce a solution to such problems. At least demonstrate your program by solving the following:\n\n\n;Example:\n\n 0 0 0 \n 0 0 0 \n 0 0 0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n1 0 0 0 0 0 0\n 0 0 0\n 0 0 0\n\n\nNote that the zeros represent the available squares, not the pennies.\n\nExtra credit is available for other interesting examples.\n\n\n;Related tasks:\n* [[A* search algorithm]]\n* [[Knight's tour]]\n* [[N-queens problem]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Hopido puzzle]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "\nfrom sys import stdout\nmoves = [\n [-1, -2], [1, -2], [-1, 2], [1, 2],\n [-2, -1], [-2, 1], [2, -1], [2, 1]\n]\n\n\ndef solve(pz, sz, sx, sy, idx, cnt):\n if idx > cnt:\n return 1\n\n for i in range(len(moves)):\n x = sx + moves[i][0]\n y = sy + moves[i][1]\n if sz > x > -1 and sz > y > -1 and pz[x][y] == 0:\n pz[x][y] = idx\n if 1 == solve(pz, sz, x, y, idx + 1, cnt):\n return 1\n pz[x][y] = 0\n\n return 0\n\n\ndef find_solution(pz, sz):\n p = [[-1 for j in range(sz)] for i in range(sz)]\n idx = x = y = cnt = 0\n for j in range(sz):\n for i in range(sz):\n if pz[idx] == \"x\":\n p[i][j] = 0\n cnt += 1\n elif pz[idx] == \"s\":\n p[i][j] = 1\n cnt += 1\n x = i\n y = j\n idx += 1\n\n if 1 == solve(p, sz, x, y, 2, cnt):\n for j in range(sz):\n for i in range(sz):\n if p[i][j] != -1:\n stdout.write(\" {:0{}d}\".format(p[i][j], 2))\n else:\n stdout.write(\" \")\n print()\n else:\n print(\"Cannot solve this puzzle!\")\n\n\n# entry point\nfind_solution(\".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..\", 8)\nprint()\nfind_solution(\".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....\", 13)\n"} +{"title": "Solve a Hopido puzzle", "language": "Python", "task": "Hopido puzzles are similar to Hidato. The most important difference is that the only moves allowed are: hop over one tile diagonally; and over two tiles horizontally and vertically. It should be possible to start anywhere in the path, the end point isn't indicated and there are no intermediate clues. [http://gamesandinnovation.com/2010/02/10/hopido-design-post-mortem/ Hopido Design Post Mortem] contains the following:\n\n\"Big puzzles represented another problem. Up until quite late in the project our puzzle solver was painfully slow with most puzzles above 7\u00d77 tiles. Testing the solution from each starting point could take hours. If the tile layout was changed even a little, the whole puzzle had to be tested again. We were just about to give up the biggest puzzles entirely when our programmer suddenly came up with a magical algorithm that cut the testing process down to only minutes. Hooray!\"\n\nKnowing the kindness in the heart of every contributor to Rosetta Code, I know that we shall feel that as an act of humanity we must solve these puzzles for them in let's say milliseconds.\n\nExample:\n\n . 0 0 . 0 0 .\n 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0\n . 0 0 0 0 0 .\n . . 0 0 0 . .\n . . . 0 . . .\n\nExtra credits are available for other interesting designs.\n\n\n;Related tasks:\n* [[A* search algorithm]]\n* [[Solve a Holy Knight's tour]]\n* [[Knight's tour]]\n* [[N-queens problem]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Holy Knight's tour]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "\nfrom sys import stdout\n\nneighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]]\ncnt = 0\npWid = 0\npHei = 0\n\n\ndef is_valid(a, b):\n return -1 < a < pWid and -1 < b < pHei\n\n\ndef iterate(pa, x, y, v):\n if v > cnt:\n return 1\n\n for i in range(len(neighbours)):\n a = x + neighbours[i][0]\n b = y + neighbours[i][1]\n if is_valid(a, b) and pa[a][b] == 0:\n pa[a][b] = v\n r = iterate(pa, a, b, v + 1)\n if r == 1:\n return r\n pa[a][b] = 0\n return 0\n\n\ndef solve(pz, w, h):\n global cnt, pWid, pHei\n\n pa = [[-1 for j in range(h)] for i in range(w)]\n f = 0\n pWid = w\n pHei = h\n for j in range(h):\n for i in range(w):\n if pz[f] == \"1\":\n pa[i][j] = 0\n cnt += 1\n f += 1\n\n for y in range(h):\n for x in range(w):\n if pa[x][y] == 0:\n pa[x][y] = 1\n if 1 == iterate(pa, x, y, 2):\n return 1, pa\n pa[x][y] = 0\n\n return 0, pa\n\nr = solve(\"011011011111111111111011111000111000001000\", 7, 6)\nif r[0] == 1:\n for j in range(6):\n for i in range(7):\n if r[1][i][j] == -1:\n stdout.write(\" \")\n else:\n stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n print()\nelse:\n stdout.write(\"No solution!\")\n"} +{"title": "Solve a Numbrix puzzle", "language": "Python", "task": "Numbrix puzzles are similar to Hidato. \nThe most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). \nPublished puzzles also tend not to have holes in the grid and may not always indicate the end node. \nTwo examples follow:\n\n;Example 1\nProblem.\n\n 0 0 0 0 0 0 0 0 0\n 0 0 46 45 0 55 74 0 0\n 0 38 0 0 43 0 0 78 0\n 0 35 0 0 0 0 0 71 0\n 0 0 33 0 0 0 59 0 0\n 0 17 0 0 0 0 0 67 0\n 0 18 0 0 11 0 0 64 0\n 0 0 24 21 0 1 2 0 0\n 0 0 0 0 0 0 0 0 0\n\nSolution.\n\n 49 50 51 52 53 54 75 76 81\n 48 47 46 45 44 55 74 77 80\n 37 38 39 40 43 56 73 78 79\n 36 35 34 41 42 57 72 71 70\n 31 32 33 14 13 58 59 68 69\n 30 17 16 15 12 61 60 67 66\n 29 18 19 20 11 62 63 64 65\n 28 25 24 21 10 1 2 3 4\n 27 26 23 22 9 8 7 6 5\n\n;Example 2\nProblem.\n\n 0 0 0 0 0 0 0 0 0\n 0 11 12 15 18 21 62 61 0\n 0 6 0 0 0 0 0 60 0\n 0 33 0 0 0 0 0 57 0\n 0 32 0 0 0 0 0 56 0\n 0 37 0 1 0 0 0 73 0\n 0 38 0 0 0 0 0 72 0\n 0 43 44 47 48 51 76 77 0\n 0 0 0 0 0 0 0 0 0\n\nSolution.\n\n 9 10 13 14 19 20 63 64 65\n 8 11 12 15 18 21 62 61 66\n 7 6 5 16 17 22 59 60 67\n 34 33 4 3 24 23 58 57 68\n 35 32 31 2 25 54 55 56 69\n 36 37 30 1 26 53 74 73 70\n 39 38 29 28 27 52 75 72 71\n 40 43 44 47 48 51 76 77 78\n 41 42 45 46 49 50 81 80 79\n\n;Task\nWrite a program to solve puzzles of this ilk, \ndemonstrating your program by solving the above examples. \nExtra credit for other interesting examples.\n\n\n;Related tasks:\n* [[A* search algorithm]]\n* [[Solve a Holy Knight's tour]]\n* [[Knight's tour]]\n* [[N-queens problem]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Holy Knight's tour]]\n* [[Solve a Hopido puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "\nfrom sys import stdout\nneighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]]\nexists = []\nlastNumber = 0\nwid = 0\nhei = 0\n\n\ndef find_next(pa, x, y, z):\n for i in range(4):\n a = x + neighbours[i][0]\n b = y + neighbours[i][1]\n if wid > a > -1 and hei > b > -1:\n if pa[a][b] == z:\n return a, b\n\n return -1, -1\n\n\ndef find_solution(pa, x, y, z):\n if z > lastNumber:\n return 1\n if exists[z] == 1:\n s = find_next(pa, x, y, z)\n if s[0] < 0:\n return 0\n return find_solution(pa, s[0], s[1], z + 1)\n\n for i in range(4):\n a = x + neighbours[i][0]\n b = y + neighbours[i][1]\n if wid > a > -1 and hei > b > -1:\n if pa[a][b] == 0:\n pa[a][b] = z\n r = find_solution(pa, a, b, z + 1)\n if r == 1:\n return 1\n pa[a][b] = 0\n\n return 0\n\n\ndef solve(pz, w, h):\n global lastNumber, wid, hei, exists\n\n lastNumber = w * h\n wid = w\n hei = h\n exists = [0 for j in range(lastNumber + 1)]\n\n pa = [[0 for j in range(h)] for i in range(w)]\n st = pz.split()\n idx = 0\n for j in range(h):\n for i in range(w):\n if st[idx] == \".\":\n idx += 1\n else:\n pa[i][j] = int(st[idx])\n exists[pa[i][j]] = 1\n idx += 1\n\n x = 0\n y = 0\n t = w * h + 1\n for j in range(h):\n for i in range(w):\n if pa[i][j] != 0 and pa[i][j] < t:\n t = pa[i][j]\n x = i\n y = j\n\n return find_solution(pa, x, y, t + 1), pa\n\n\ndef show_result(r):\n if r[0] == 1:\n for j in range(hei):\n for i in range(wid):\n stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n print()\n else:\n stdout.write(\"No Solution!\\n\")\n\n print()\n\n\nr = solve(\". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17\"\n \" . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1 2 . . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\". . . . . . . . . . 11 12 15 18 21 62 61 . . 6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37\"\n \" . 1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55\"\n \" . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\", 9, 9)\nshow_result(r)\n"} +{"title": "Sort an outline at every level", "language": "Python", "task": ";Task:\nWrite and test a function over an indented plain text outline which either:\n# Returns a copy of the outline in which the sub-lists at every level of indentation are sorted, or\n# reports that the indentation characters or widths are not consistent enough to make the outline structure clear.\n\n\n\nYour code should detect and warn of at least two types of inconsistent indentation:\n* inconsistent use of whitespace characters (e.g. mixed use of tabs and spaces)\n* inconsistent indent widths. For example, an indentation with an odd number of spaces in an outline in which the unit indent appears to be 2 spaces, or 4 spaces.\n\n\nYour code should be able to detect and handle both tab-indented, and space-indented (e.g. 4 space, 2 space etc) outlines, without being given any advance warning of the indent characters used, or the size of the indent units.\n\nYou should also be able to specify different types of sort, for example, as a minimum, both ascending and descending lexical sorts.\n\nYour sort should not alter the type or size of the indentation units used in the input outline.\n\n\n(For an application of [https://packagecontrol.io/packages/Indent%20Respectful%20Sort Indent Respectful Sort], see the Sublime Text package of that name. The Python source text [https://github.com/mvnural/sublime-indent-respectful-sort] is available for inspection on Github).\n\n\n'''Tests'''\n\n* Sort every level of the (4 space indented) outline below lexically, once ascending and once descending.\nzeta\n beta\n gamma\n lambda\n kappa\n mu\n delta\nalpha\n theta\n iota\n epsilon\n\n* Do the same with a tab-indented equivalent of the same outline.\n\nzeta\n\tgamma\n\t\tmu\n\t\tlambda\n\t\tkappa\n\tdelta\n\tbeta\nalpha\n\ttheta\n\tiota\n\tepsilon\n\n\nThe output sequence of an ascending lexical sort of each level should be:\n\nalpha\n epsilon\n iota\n theta\nzeta\n beta\n delta\n gamma\n kappa\n lambda\n mu\n\nThe output sequence of a descending lexical sort of each level should be:\n\nzeta\n gamma\n mu\n lambda\n kappa\n delta\n beta\nalpha\n theta\n iota\n epsilon\n\n* Attempt to separately sort each of the following two outlines, reporting any inconsistencies detected in their indentations by your validation code.\n\nalpha\n epsilon\n\tiota\n theta\nzeta\n beta\n delta\n gamma\n \tkappa\n lambda\n mu\nzeta\n beta\n gamma\n lambda\n kappa\n mu\n delta\nalpha\n theta\n iota\n epsilon\n\n\n\n;Related tasks:\n\n:* \u00a0 [[Functional_coverage_tree]]\n:* \u00a0 [[Display_an_outline_as_a_nested_table]]\n\n\n", "solution": "'''Sort an outline at every level'''\n\n\nfrom itertools import chain, product, takewhile, tee\nfrom functools import cmp_to_key, reduce\n\n\n# ------------- OUTLINE SORTED AT EVERY LEVEL --------------\n\n# sortedOutline :: (Tree String -> Tree String -> Ordering)\n# -> String\n# -> Either String String\ndef sortedOutline(cmp):\n '''Either a message reporting inconsistent\n indentation, or an outline sorted at every\n level by the supplied comparator function.\n '''\n def go(outlineText):\n indentTuples = indentTextPairs(\n outlineText.splitlines()\n )\n return bindLR(\n minimumIndent(enumerate(indentTuples))\n )(lambda unitIndent: Right(\n outlineFromForest(\n unitIndent,\n nest(foldTree(\n lambda x: lambda xs: Node(x)(\n sorted(xs, key=cmp_to_key(cmp))\n )\n )(Node('')(\n forestFromIndentLevels(\n indentLevelsFromLines(\n unitIndent\n )(indentTuples)\n )\n )))\n )\n ))\n return go\n\n\n# -------------------------- TEST --------------------------\n# main :: IO ()\ndef main():\n '''Ascending and descending sorts attempted on\n space-indented and tab-indented outlines, both\n well-formed and ill-formed.\n '''\n\n ascending = comparing(root)\n descending = flip(ascending)\n\n spacedOutline = '''\nzeta\n beta\n gamma\n lambda\n kappa\n mu\n delta\nalpha\n theta\n iota\n epsilon'''\n\n tabbedOutline = '''\nzeta\n\tbeta\n\tgamma\n\t\tlambda\n\t\tkappa\n\t\tmu\n\tdelta\nalpha\n\ttheta\n\tiota\n\tepsilon'''\n\n confusedOutline = '''\nalpha\n epsilon\n\tiota\n theta\nzeta\n beta\n delta\n gamma\n \tkappa\n lambda\n mu'''\n\n raggedOutline = '''\nzeta\n beta\n gamma\n lambda\n kappa\n mu\n delta\nalpha\n theta\n iota\n epsilon'''\n\n def displaySort(kcmp):\n '''Sort function output with labelled comparator\n for a set of four labelled outlines.\n '''\n k, cmp = kcmp\n return [\n tested(cmp, k, label)(\n outline\n ) for (label, outline) in [\n ('4-space indented', spacedOutline),\n ('tab indented', tabbedOutline),\n ('Unknown 1', confusedOutline),\n ('Unknown 2', raggedOutline)\n ]\n ]\n\n def tested(cmp, cmpName, outlineName):\n '''Print either message or result.\n '''\n def go(outline):\n print('\\n' + outlineName, cmpName + ':')\n either(print)(print)(\n sortedOutline(cmp)(outline)\n )\n return go\n\n # Tests applied to two comparators:\n ap([\n displaySort\n ])([\n (\"(A -> Z)\", ascending),\n (\"(Z -> A)\", descending)\n ])\n\n\n# ------------- OUTLINE PARSING AND RENDERING --------------\n\n# forestFromIndentLevels :: [(Int, a)] -> [Tree a]\ndef forestFromIndentLevels(tuples):\n '''A list of trees derived from a list of values paired\n with integers giving their levels of indentation.\n '''\n def go(xs):\n if xs:\n intIndent, v = xs[0]\n firstTreeLines, rest = span(\n lambda x: intIndent < x[0]\n )(xs[1:])\n return [Node(v)(go(firstTreeLines))] + go(rest)\n else:\n return []\n return go(tuples)\n\n\n# indentLevelsFromLines :: String -> [(String, String)]\n# -> [(Int, String)]\ndef indentLevelsFromLines(indentUnit):\n '''Each input line stripped of leading\n white space, and tupled with a preceding integer\n giving its level of indentation from 0 upwards.\n '''\n def go(xs):\n w = len(indentUnit)\n return [\n (len(x[0]) // w, x[1])\n for x in xs\n ]\n return go\n\n\n# indentTextPairs :: [String] -> (String, String)\ndef indentTextPairs(xs):\n '''A list of (indent, bodyText) pairs.'''\n def indentAndText(s):\n pfx = list(takewhile(lambda c: c.isspace(), s))\n return (pfx, s[len(pfx):])\n return [indentAndText(x) for x in xs]\n\n\n# outlineFromForest :: String -> [Tree String] -> String\ndef outlineFromForest(tabString, forest):\n '''An indented outline serialisation of forest,\n using tabString as the unit of indentation.\n '''\n def go(indent):\n def serial(node):\n return [indent + root(node)] + list(\n concatMap(\n go(tabString + indent)\n )(nest(node))\n )\n return serial\n return '\\n'.join(\n concatMap(go(''))(forest)\n )\n\n\n# --------------- MINIMUM INDENT, OR ANOMALY ---------------\n\n# minimumIndent :: [(Int, [Char])]\n# -> Either String String\ndef minimumIndent(indexedPrefixes):\n '''Either a message, if indentation characters are\n mixed, or indentation widths are inconsistent,\n or the smallest consistent non-empty indentation.\n '''\n (xs, ts) = tee(indexedPrefixes)\n (ys, zs) = tee(ts)\n\n def mindentLR(charSet):\n if list(charSet):\n def w(x):\n return len(x[1][0])\n\n unit = min(filter(w, ys), key=w)[1][0]\n unitWidth = len(unit)\n\n def widthCheck(a, ix):\n '''Is there a line number at which\n an anomalous indent width is seen?\n '''\n wx = len(ix[1][0])\n return a if (a or 0 == wx) else (\n ix[0] if 0 != wx % unitWidth else a\n )\n oddLine = reduce(widthCheck, zs, None)\n return Left(\n 'Inconsistent indentation width at line ' + (\n str(1 + oddLine)\n )\n ) if oddLine else Right(''.join(unit))\n else:\n return Right('')\n\n def tabSpaceCheck(a, ics):\n '''Is there a line number at which a\n variant indent character is used?\n '''\n charSet = a[0].union(set(ics[1][0]))\n return a if a[1] else (\n charSet, ics[0] if 1 < len(charSet) else None\n )\n\n indentCharSet, mbAnomalyLine = reduce(\n tabSpaceCheck, xs, (set([]), None)\n )\n return bindLR(\n Left(\n 'Mixed indent characters found in line ' + str(\n 1 + mbAnomalyLine\n )\n ) if mbAnomalyLine else Right(list(indentCharSet))\n )(mindentLR)\n\n\n# ------------------------ GENERIC -------------------------\n\n# Left :: a -> Either a b\ndef Left(x):\n '''Constructor for an empty Either (option type) value\n with an associated string.\n '''\n return {'type': 'Either', 'Right': None, 'Left': x}\n\n\n# Right :: b -> Either a b\ndef Right(x):\n '''Constructor for a populated Either (option type) value'''\n return {'type': 'Either', 'Left': None, 'Right': x}\n\n\n# Node :: a -> [Tree a] -> Tree a\ndef Node(v):\n '''Constructor for a Tree node which connects a\n value of some kind to a list of zero or\n more child trees.\n '''\n return lambda xs: {'type': 'Tree', 'root': v, 'nest': xs}\n\n\n# ap (<*>) :: [(a -> b)] -> [a] -> [b]\ndef ap(fs):\n '''The application of each of a list of functions,\n to each of a list of values.\n '''\n def go(xs):\n return [\n f(x) for (f, x)\n in product(fs, xs)\n ]\n return go\n\n\n# bindLR (>>=) :: Either a -> (a -> Either b) -> Either b\ndef bindLR(m):\n '''Either monad injection operator.\n Two computations sequentially composed,\n with any value produced by the first\n passed as an argument to the second.\n '''\n def go(mf):\n return (\n mf(m.get('Right')) if None is m.get('Left') else m\n )\n return go\n\n\n# comparing :: (a -> b) -> (a -> a -> Ordering)\ndef comparing(f):\n '''An ordering function based on\n a property accessor f.\n '''\n def go(x, y):\n fx = f(x)\n fy = f(y)\n return -1 if fx < fy else (1 if fx > fy else 0)\n return go\n\n\n# concatMap :: (a -> [b]) -> [a] -> [b]\ndef concatMap(f):\n '''A concatenated list over which a function has been mapped.\n The list monad can be derived by using a function f which\n wraps its output in a list,\n (using an empty list to represent computational failure).\n '''\n def go(xs):\n return chain.from_iterable(map(f, xs))\n return go\n\n\n# either :: (a -> c) -> (b -> c) -> Either a b -> c\ndef either(fl):\n '''The application of fl to e if e is a Left value,\n or the application of fr to e if e is a Right value.\n '''\n return lambda fr: lambda e: fl(e['Left']) if (\n None is e['Right']\n ) else fr(e['Right'])\n\n\n# flip :: (a -> b -> c) -> b -> a -> c\ndef flip(f):\n '''The binary function f with its\n arguments reversed.\n '''\n return lambda a, b: f(b, a)\n\n\n# foldTree :: (a -> [b] -> b) -> Tree a -> b\ndef foldTree(f):\n '''The catamorphism on trees. A summary\n value defined by a depth-first fold.\n '''\n def go(node):\n return f(root(node))([\n go(x) for x in nest(node)\n ])\n return go\n\n\n# nest :: Tree a -> [Tree a]\ndef nest(t):\n '''Accessor function for children of tree node.'''\n return t.get('nest')\n\n\n# root :: Tree a -> a\ndef root(t):\n '''Accessor function for data of tree node.'''\n return t.get('root')\n\n\n# span :: (a -> Bool) -> [a] -> ([a], [a])\ndef span(p):\n '''The longest (possibly empty) prefix of xs\n that contains only elements satisfying p,\n tupled with the remainder of xs.\n span p xs is equivalent to\n (takeWhile p xs, dropWhile p xs).\n '''\n def match(ab):\n b = ab[1]\n return not b or not p(b[0])\n\n def f(ab):\n a, b = ab\n return a + [b[0]], b[1:]\n\n def go(xs):\n return until(match)(f)(([], xs))\n return go\n\n\n# until :: (a -> Bool) -> (a -> a) -> a -> a\ndef until(p):\n '''The result of repeatedly applying f until p holds.\n The initial seed value is x.\n '''\n def go(f):\n def g(x):\n v = x\n while not p(v):\n v = f(v)\n return v\n return g\n return go\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} +{"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: '\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588'\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\" -> \u2581\u2581\u2588\u2588\n:: (Aiming to use just two spark levels)\n\n:: \"0, 999, 4000, 4999, 7000, 7999\" -> \u2581\u2581\u2585\u2585\u2588\u2588\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": "\n#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\nInvocation and output :\n\n/home/aamrun/rosettaCode>./sparkLine 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1\nMax : 8.000000,Min : 1.000000,Range : 7.000000\n\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588\u2587\u2586\u2585\u2584\u2583\u2582\u2581\n/home/aamrun/rosettaCode>./sparkLine 1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5\nMax : 7.500000,Min : 0.500000,Range : 7.000000\n\u2582\u2581\u2584\u2583\u2586\u2585\u2588\u2587\n\n"} +{"title": "Sparkline in unicode", "language": "JavaScript", "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: '\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588'\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\" -> \u2581\u2581\u2588\u2588\n:: (Aiming to use just two spark levels)\n\n:: \"0, 999, 4000, 4999, 7000, 7999\" -> \u2581\u2581\u2585\u2585\u2588\u2588\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": "(() => {\n 'use strict';\n\n const main = () => {\n\n // sparkLine :: [Num] -> String\n const sparkLine = xs => {\n const hist = dataBins(8)(xs);\n return unlines([\n concat(map(\n i => '\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588' [i],\n hist.indexes\n )),\n unwords(xs),\n [\n 'Min: ' + hist.min,\n 'Mean: ' + hist.mean.toFixed(2),\n 'Median: ' + hist.median,\n 'Max: ' + hist.max,\n ].join('\\t'),\n ''\n ]);\n };\n\n\n // dataBins :: Int -> [Num] ->\n // {indexes:: [Int], min:: Float, max:: Float,\n // range :: Float, lbounds :: [Float]}\n const dataBins = intBins => xs => {\n const\n iLast = intBins - 1,\n ys = sort(xs),\n mn = ys[0],\n mx = last(ys),\n rng = mx - mn,\n w = rng / intBins,\n lng = xs.length,\n mid = lng / 2,\n lbounds = map(\n i => mn + (w * i),\n enumFromTo(1, iLast)\n );\n return {\n indexes: map(\n x => {\n const mb = findIndex(b => b > x, lbounds);\n return mb.Nothing ? (\n iLast\n ) : mb.Just;\n },\n xs\n ),\n lbounds: lbounds,\n min: mn,\n median: even(lng) ? (\n sum([ys[mid - 1], ys[mid]]) / 2\n ) : ys[Math.floor(mid)],\n mean: sum(xs) / lng,\n max: mx,\n range: rng\n };\n };\n\n // numbersFromString :: String -> [Float]\n const numbersFromString = s =>\n map(x => parseFloat(x, 10),\n s.split(/[,\\s]+/)\n );\n\n return unlines(map(\n compose(sparkLine, numbersFromString),\n [\n '0, 1, 19, 20',\n '0, 999, 4000, 4999, 7000, 7999',\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 ]\n ));\n };\n\n // GENERIC FUNCTIONS ----------------------------\n\n // Just :: a -> Maybe a\n const Just = x => ({\n type: 'Maybe',\n Nothing: false,\n Just: x\n });\n\n // Nothing :: Maybe a\n const Nothing = () => ({\n type: 'Maybe',\n Nothing: true,\n });\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (f, g) => x => f(g(x));\n\n // concat :: [[a]] -> [a]\n // concat :: [String] -> String\n const concat = xs =>\n 0 < xs.length ? (() => {\n const unit = 'string' !== typeof xs[0] ? (\n []\n ) : '';\n return unit.concat.apply(unit, xs);\n })() : [];\n\n\n // enumFromTo :: (Int, Int) -> [Int]\n const enumFromTo = (m, n) =>\n Array.from({\n length: 1 + n - m\n }, (_, i) => m + i);\n\n // even :: Int -> Bool\n const even = n => 0 === n % 2;\n\n // last :: [a] -> a\n const last = xs =>\n 0 < xs.length ? xs.slice(-1)[0] : undefined;\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) =>\n (Array.isArray(xs) ? (\n xs\n ) : xs.split('')).map(f);\n\n // sort :: Ord a => [a] -> [a]\n const sort = xs => xs.slice()\n .sort((a, b) => a < b ? -1 : (a > b ? 1 : 0));\n\n\n // findIndex :: (a -> Bool) -> [a] -> Maybe Int\n const findIndex = (p, xs) => {\n const\n i = (\n 'string' !== typeof xs ? (\n xs\n ) : xs.split('')\n ).findIndex(p);\n return -1 !== i ? (\n Just(i)\n ) : Nothing();\n };\n\n // sum :: [Num] -> Num\n const sum = xs => xs.reduce((a, x) => a + x, 0);\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // unwords :: [String] -> String\n const unwords = xs => xs.join(' ');\n\n // MAIN ---\n return main();\n})();"} +{"title": "Sparkline in unicode", "language": "Python", "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: '\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588'\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\" -> \u2581\u2581\u2588\u2588\n:: (Aiming to use just two spark levels)\n\n:: \"0, 999, 4000, 4999, 7000, 7999\" -> \u2581\u2581\u2585\u2585\u2588\u2588\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": "# -*- coding: utf-8 -*-\n\n# Unicode: 9601, 9602, 9603, 9604, 9605, 9606, 9607, 9608\nbar = '\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588'\nbarcount = len(bar)\n\ndef sparkline(numbers):\n mn, mx = min(numbers), max(numbers)\n extent = mx - mn\n sparkline = ''.join(bar[min([barcount - 1,\n int((n - mn) / extent * barcount)])]\n for n in numbers)\n return mn, mx, sparkline\n\nif __name__ == '__main__':\n import re\n \n for line in (\"0 0 1 1; 0 1 19 20; 0 999 4000 4999 7000 7999;\"\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 \").split(';'):\n print(\"\\nNumbers:\", line)\n numbers = [float(n) for n in re.split(r'[\\s,]+', line.strip())]\n mn, mx, sp = sparkline(numbers)\n print(' min: %5f; max: %5f' % (mn, mx))\n print(\" \" + sp)"} +{"title": "Spelling of ordinal numbers", "language": "C", "task": "'''Ordinal numbers''' \u00a0 (as used in this Rosetta Code task), \u00a0 are numbers that describe the \u00a0 ''position'' \u00a0 of something in a list.\n\nIt is this context that ordinal numbers will be used, using an English-spelled name of an ordinal number.\n\n\nThe ordinal numbers are \u00a0 (at least, one form of them):\n 1st 2nd 3rd 4th 5th 6th 7th \u00b7\u00b7\u00b7 99th 100th \u00b7\u00b7\u00b7 1000000000th \u00b7\u00b7\u00b7 etc\n\nsometimes expressed as:\n 1st 2nd 3rd 4th 5th 6th 7th \u00b7\u00b7\u00b7 99th 100th \u00b7\u00b7\u00b7 1000000000th \u00b7\u00b7\u00b7\n\n\nFor this task, the following (English-spelled form) will be used:\n first second third fourth fifth sixth seventh ninety-nineth one hundredth one billionth\n\n\nFurthermore, the American version of numbers will be used here \u00a0 (as opposed to the British).\n\n'''2,000,000,000''' \u00a0 is two billion, \u00a0 ''not'' \u00a0 two milliard.\n\n\n;Task:\nWrite a driver and a function (subroutine/routine \u00b7\u00b7\u00b7) that returns the English-spelled ordinal version of a specified number \u00a0 (a positive integer).\n\nOptionally, try to support as many forms of an integer that can be expressed: \u00a0 '''123''' \u00a0 '''00123.0''' \u00a0 '''1.23e2''' \u00a0 all are forms of the same integer.\n\nShow all output here.\n\n\n;Test cases:\nUse (at least) the test cases of:\n 1 2 3 4 5 11 65 100 101 272 23456 8007006005004003\n\n\n;Related tasks:\n* \u00a0 [[Number names]]\n* \u00a0 [[N'th]]\n\n", "solution": "#include \n#include \n#include \n#include \n\ntypedef uint64_t integer;\n\ntypedef struct number_names_tag {\n const char* cardinal;\n const char* ordinal;\n} number_names;\n\nconst number_names small[] = {\n { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\ntypedef struct named_number_tag {\n const char* cardinal;\n const char* ordinal;\n integer number;\n} named_number;\n\nconst named_number named_numbers[] = {\n { \"hundred\", \"hundredth\", 100 },\n { \"thousand\", \"thousandth\", 1000 },\n { \"million\", \"millionth\", 1000000 },\n { \"billion\", \"billionth\", 1000000000 },\n { \"trillion\", \"trillionth\", 1000000000000 },\n { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_small_name(const number_names* n, bool ordinal) {\n return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst char* get_big_name(const named_number* n, bool ordinal) {\n return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst named_number* get_named_number(integer n) {\n const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]);\n for (size_t i = 0; i + 1 < names_len; ++i) {\n if (n < named_numbers[i + 1].number)\n return &named_numbers[i];\n }\n return &named_numbers[names_len - 1];\n}\n\nvoid append_number_name(GString* gstr, integer n, bool ordinal) {\n if (n < 20)\n g_string_append(gstr, get_small_name(&small[n], ordinal));\n else if (n < 100) {\n if (n % 10 == 0) {\n g_string_append(gstr, get_small_name(&tens[n/10 - 2], ordinal));\n } else {\n g_string_append(gstr, get_small_name(&tens[n/10 - 2], false));\n g_string_append_c(gstr, '-');\n g_string_append(gstr, get_small_name(&small[n % 10], ordinal));\n }\n } else {\n const named_number* num = get_named_number(n);\n integer p = num->number;\n append_number_name(gstr, n/p, false);\n g_string_append_c(gstr, ' ');\n if (n % p == 0) {\n g_string_append(gstr, get_big_name(num, ordinal));\n } else {\n g_string_append(gstr, get_big_name(num, false));\n g_string_append_c(gstr, ' ');\n append_number_name(gstr, n % p, ordinal);\n }\n }\n}\n\nGString* number_name(integer n, bool ordinal) {\n GString* result = g_string_sized_new(8);\n append_number_name(result, n, ordinal);\n return result;\n}\n\nvoid test_ordinal(integer n) {\n GString* name = number_name(n, true);\n printf(\"%llu: %s\\n\", n, name->str);\n g_string_free(name, TRUE);\n}\n\nint main() {\n test_ordinal(1);\n test_ordinal(2);\n test_ordinal(3);\n test_ordinal(4);\n test_ordinal(5);\n test_ordinal(11);\n test_ordinal(15);\n test_ordinal(21);\n test_ordinal(42);\n test_ordinal(65);\n test_ordinal(98);\n test_ordinal(100);\n test_ordinal(101);\n test_ordinal(272);\n test_ordinal(300);\n test_ordinal(750);\n test_ordinal(23456);\n test_ordinal(7891233);\n test_ordinal(8007006005004003LL);\n return 0;\n}"} +{"title": "Spelling of ordinal numbers", "language": "Python", "task": "'''Ordinal numbers''' \u00a0 (as used in this Rosetta Code task), \u00a0 are numbers that describe the \u00a0 ''position'' \u00a0 of something in a list.\n\nIt is this context that ordinal numbers will be used, using an English-spelled name of an ordinal number.\n\n\nThe ordinal numbers are \u00a0 (at least, one form of them):\n 1st 2nd 3rd 4th 5th 6th 7th \u00b7\u00b7\u00b7 99th 100th \u00b7\u00b7\u00b7 1000000000th \u00b7\u00b7\u00b7 etc\n\nsometimes expressed as:\n 1st 2nd 3rd 4th 5th 6th 7th \u00b7\u00b7\u00b7 99th 100th \u00b7\u00b7\u00b7 1000000000th \u00b7\u00b7\u00b7\n\n\nFor this task, the following (English-spelled form) will be used:\n first second third fourth fifth sixth seventh ninety-nineth one hundredth one billionth\n\n\nFurthermore, the American version of numbers will be used here \u00a0 (as opposed to the British).\n\n'''2,000,000,000''' \u00a0 is two billion, \u00a0 ''not'' \u00a0 two milliard.\n\n\n;Task:\nWrite a driver and a function (subroutine/routine \u00b7\u00b7\u00b7) that returns the English-spelled ordinal version of a specified number \u00a0 (a positive integer).\n\nOptionally, try to support as many forms of an integer that can be expressed: \u00a0 '''123''' \u00a0 '''00123.0''' \u00a0 '''1.23e2''' \u00a0 all are forms of the same integer.\n\nShow all output here.\n\n\n;Test cases:\nUse (at least) the test cases of:\n 1 2 3 4 5 11 65 100 101 272 23456 8007006005004003\n\n\n;Related tasks:\n* \u00a0 [[Number names]]\n* \u00a0 [[N'th]]\n\n", "solution": "irregularOrdinals = {\n\t\"one\": \"first\",\n\t\"two\": \"second\",\n\t\"three\": \"third\",\n\t\"five\": \"fifth\",\n\t\"eight\": \"eighth\",\n\t\"nine\": \"ninth\",\n\t\"twelve\": \"twelfth\",\n}\n\ndef num2ordinal(n):\n conversion = int(float(n))\n num = spell_integer(conversion)\n hyphen = num.rsplit(\"-\", 1)\n num = num.rsplit(\" \", 1)\n delim = \" \"\n if len(num[-1]) > len(hyphen[-1]):\n num = hyphen\n delim = \"-\"\n \n if num[-1] in irregularOrdinals:\n num[-1] = delim + irregularOrdinals[num[-1]]\n elif num[-1].endswith(\"y\"):\n num[-1] = delim + num[-1][:-1] + \"ieth\"\n else:\n num[-1] = delim + num[-1] + \"th\"\n return \"\".join(num)\n \nif __name__ == \"__main__\":\n tests = \"1 2 3 4 5 11 65 100 101 272 23456 8007006005004003 123 00123.0 1.23e2\".split()\n for num in tests:\n print(\"{} => {}\".format(num, num2ordinal(num)))\n\n\n#This is a copy of the code from https://rosettacode.org/wiki/Number_names#Python\n\nTENS = [None, None, \"twenty\", \"thirty\", \"forty\",\n \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\nSMALL = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\",\n \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\nHUGE = [None, None] + [h + \"illion\" \n for h in (\"m\", \"b\", \"tr\", \"quadr\", \"quint\", \"sext\", \n \"sept\", \"oct\", \"non\", \"dec\")]\n \ndef nonzero(c, n, connect=''):\n return \"\" if n == 0 else connect + c + spell_integer(n)\n \ndef last_and(num):\n if ',' in num:\n pre, last = num.rsplit(',', 1)\n if ' and ' not in last:\n last = ' and' + last\n num = ''.join([pre, ',', last])\n return num\n \ndef big(e, n):\n if e == 0:\n return spell_integer(n)\n elif e == 1:\n return spell_integer(n) + \" thousand\"\n else:\n return spell_integer(n) + \" \" + HUGE[e]\n \ndef base1000_rev(n):\n # generates the value of the digits of n in base 1000\n # (i.e. 3-digit chunks), in reverse.\n while n != 0:\n n, r = divmod(n, 1000)\n yield r\n \ndef spell_integer(n):\n if n < 0:\n return \"minus \" + spell_integer(-n)\n elif n < 20:\n return SMALL[n]\n elif n < 100:\n a, b = divmod(n, 10)\n return TENS[a] + nonzero(\"-\", b)\n elif n < 1000:\n a, b = divmod(n, 100)\n return SMALL[a] + \" hundred\" + nonzero(\" \", b, ' and')\n else:\n num = \", \".join([big(e, x) for e, x in\n enumerate(base1000_rev(n)) if x][::-1])\n return last_and(num)"} +{"title": "Sphenic numbers", "language": "C", "task": ";Definitions\nA '''sphenic number''' is a positive integer that is the product of three distinct prime numbers. More technically it's a square-free 3-almost prime (see Related tasks below).\n\nFor the purposes of this task, a '''sphenic triplet''' is a group of three sphenic numbers which are consecutive. \n\nNote that sphenic quadruplets are not possible because every fourth consecutive positive integer is divisible by 4 (= 2 x 2) and its prime factors would not therefore be distinct.\n\n;Examples\n30 (= 2 x 3 x 5) is a sphenic number and is also clearly the first one.\n\n[1309, 1310, 1311] is a sphenic triplet because 1309 (= 7 x 11 x 17), 1310 (= 2 x 5 x 31) and 1311 (= 3 x 19 x 23) are 3 consecutive sphenic numbers.\n\n;Task\nCalculate and show here:\n\n1. All sphenic numbers less than 1,000.\n\n2. All sphenic triplets less than 10,000.\n\n;Stretch\n\n3. How many sphenic numbers are there less than 1 million?\n\n4. How many sphenic triplets are there less than 1 million?\n\n5. What is the 200,000th sphenic number and its 3 prime factors?\n\n6. What is the 5,000th sphenic triplet?\n\nHint: you only need to consider sphenic numbers less than 1 million to answer 5. and 6.\n\n;References\n\n* Wikipedia: Sphenic number\n* OEIS:A007304 - Sphenic numbers\n* OEIS:A165936 - Sphenic triplets (in effect)\n\n;Related tasks\n* [[Almost prime]]\n* [[Square-free integers]]\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nbool *sieve(int limit) {\n int i, p;\n limit++;\n // True denotes composite, false denotes prime.\n bool *c = calloc(limit, sizeof(bool)); // all false by default\n c[0] = true;\n c[1] = true;\n for (i = 4; i < limit; i += 2) c[i] = true;\n p = 3; // Start from 3.\n while (true) {\n int p2 = p * p;\n if (p2 >= limit) break;\n for (i = p2; i < limit; i += 2 * p) c[i] = true;\n while (true) {\n p += 2;\n if (!c[p]) break;\n }\n }\n return c;\n}\n\nvoid primeFactors(int n, int *factors, int *length) {\n if (n < 2) return;\n int count = 0;\n int inc[8] = {4, 2, 4, 2, 4, 6, 2, 6};\n while (!(n%2)) {\n factors[count++] = 2;\n n /= 2;\n }\n while (!(n%3)) {\n factors[count++] = 3;\n n /= 3;\n }\n while (!(n%5)) {\n factors[count++] = 5;\n n /= 5;\n }\n for (int k = 7, i = 0; k*k <= n; ) {\n if (!(n%k)) {\n factors[count++] = k;\n n /= k;\n } else {\n k += inc[i];\n i = (i + 1) % 8;\n }\n }\n if (n > 1) {\n factors[count++] = n;\n }\n *length = count;\n}\n\nint compare(const void* a, const void* b) {\n int arg1 = *(const int*)a;\n int arg2 = *(const int*)b;\n if (arg1 < arg2) return -1;\n if (arg1 > arg2) return 1;\n return 0;\n}\n\nint main() {\n const int limit = 1000000;\n int limit2 = (int)cbrt((double)limit);\n int i, j, k, pc = 0, count = 0, prod, res;\n bool *c = sieve(limit/6);\n for (i = 0; i < limit/6; ++i) {\n if (!c[i]) ++pc;\n }\n int *primes = (int *)malloc(pc * sizeof(int));\n for (i = 0, j = 0; i < limit/6; ++i) {\n if (!c[i]) primes[j++] = i;\n }\n int *sphenic = (int *)malloc(210000 * sizeof(int));\n printf(\"Sphenic numbers less than 1,000:\\n\");\n for (i = 0; i < pc-2; ++i) {\n if (primes[i] > limit2) break;\n for (j = i+1; j < pc-1; ++j) {\n prod = primes[i] * primes[j];\n if (prod * primes[j+1] >= limit) break;\n for (k = j+1; k < pc; ++k) {\n res = prod * primes[k];\n if (res >= limit) break;\n sphenic[count++] = res;\n }\n }\n }\n qsort(sphenic, count, sizeof(int), compare);\n for (i = 0; ; ++i) {\n if (sphenic[i] >= 1000) break;\n printf(\"%3d \", sphenic[i]);\n if (!((i+1) % 15)) printf(\"\\n\");\n }\n printf(\"\\nSphenic triplets less than 10,000:\\n\");\n int tripCount = 0, s, t = 0;\n for (i = 0; i < count - 2; ++i) {\n s = sphenic[i];\n if (sphenic[i+1] == s+1 && sphenic[i+2] == s+2) {\n tripCount++;\n if (s < 9998) {\n printf(\"[%d, %d, %d] \", s, s+1, s+2);\n if (!(tripCount % 3)) printf(\"\\n\");\n }\n if (tripCount == 5000) t = s;\n }\n }\n setlocale(LC_NUMERIC, \"\");\n printf(\"\\nThere are %'d sphenic numbers less than 1,000,000.\\n\", count);\n printf(\"There are %'d sphenic triplets less than 1,000,000.\\n\", tripCount);\n s = sphenic[199999];\n int factors[10], length = 0;\n primeFactors(s, factors, &length);\n printf(\"The 200,000th sphenic number is %'d (\", s);\n for (i = 0; i < length; ++i) {\n printf(\"%d\", factors[i]);\n if (i < length-1) printf(\"*\");\n }\n printf(\").\\n\");\n printf(\"The 5,000th sphenic triplet is [%d, %d, %d].\\n\", t, t+1, t+2);\n free(c);\n free(primes);\n free(sphenic);\n return 0;\n}"} +{"title": "Sphenic numbers", "language": "Python", "task": ";Definitions\nA '''sphenic number''' is a positive integer that is the product of three distinct prime numbers. More technically it's a square-free 3-almost prime (see Related tasks below).\n\nFor the purposes of this task, a '''sphenic triplet''' is a group of three sphenic numbers which are consecutive. \n\nNote that sphenic quadruplets are not possible because every fourth consecutive positive integer is divisible by 4 (= 2 x 2) and its prime factors would not therefore be distinct.\n\n;Examples\n30 (= 2 x 3 x 5) is a sphenic number and is also clearly the first one.\n\n[1309, 1310, 1311] is a sphenic triplet because 1309 (= 7 x 11 x 17), 1310 (= 2 x 5 x 31) and 1311 (= 3 x 19 x 23) are 3 consecutive sphenic numbers.\n\n;Task\nCalculate and show here:\n\n1. All sphenic numbers less than 1,000.\n\n2. All sphenic triplets less than 10,000.\n\n;Stretch\n\n3. How many sphenic numbers are there less than 1 million?\n\n4. How many sphenic triplets are there less than 1 million?\n\n5. What is the 200,000th sphenic number and its 3 prime factors?\n\n6. What is the 5,000th sphenic triplet?\n\nHint: you only need to consider sphenic numbers less than 1 million to answer 5. and 6.\n\n;References\n\n* Wikipedia: Sphenic number\n* OEIS:A007304 - Sphenic numbers\n* OEIS:A165936 - Sphenic triplets (in effect)\n\n;Related tasks\n* [[Almost prime]]\n* [[Square-free integers]]\n\n", "solution": "\"\"\" rosettacode.org task Sphenic_numbers \"\"\"\n\n\nfrom sympy import factorint\n\nsphenics1m, sphenic_triplets1m = [], []\n\nfor i in range(3, 1_000_000):\n d = factorint(i)\n if len(d) == 3 and sum(d.values()) == 3:\n sphenics1m.append(i)\n if len(sphenics1m) > 2 and i - sphenics1m[-3] == 2 and i - sphenics1m[-2] == 1:\n sphenic_triplets1m.append(i)\n\nprint('Sphenic numbers less than 1000:')\nfor i, n in enumerate(sphenics1m):\n if n < 1000:\n print(f'{n : 5}', end='\\n' if (i + 1) % 15 == 0 else '')\n else:\n break\n\nprint('\\n\\nSphenic triplets less than 10_000:')\nfor i, n in enumerate(sphenic_triplets1m):\n if n < 10_000:\n print(f'({n - 2} {n - 1} {n})', end='\\n' if (i + 1) % 3 == 0 else ' ')\n else:\n break\n\nprint('\\nThere are', len(sphenics1m), 'sphenic numbers and', len(sphenic_triplets1m),\n 'sphenic triplets less than 1 million.')\n\nS2HK = sphenics1m[200_000 - 1]\nT5K = sphenic_triplets1m[5000 - 1]\nprint(f'The 200_000th sphenic number is {S2HK}, with prime factors {list(factorint(S2HK).keys())}.')\nprint(f'The 5000th sphenic triplet is ({T5K - 2} {T5K - 1} {T5K}).')\n"} +{"title": "Split a character string based on change of character", "language": "C", "task": ";Task:\nSplit a (character) string into comma (plus a blank) delimited\nstrings based on a change of character \u00a0 (left to right).\n\nShow the output here \u00a0 (use the 1st example below).\n\n\nBlanks should be treated as any other character \u00a0 (except\nthey are problematic to display clearly). \u00a0 The same applies\nto commas.\n\n\nFor instance, the string: \n gHHH5YY++///\\ \nshould be split and show: \n g, HHH, 5, YY, ++, ///, \\ \n\n", "solution": "#include \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": "Split a character string based on change of character", "language": "JavaScript", "task": ";Task:\nSplit a (character) string into comma (plus a blank) delimited\nstrings based on a change of character \u00a0 (left to right).\n\nShow the output here \u00a0 (use the 1st example below).\n\n\nBlanks should be treated as any other character \u00a0 (except\nthey are problematic to display clearly). \u00a0 The same applies\nto commas.\n\n\nFor instance, the string: \n gHHH5YY++///\\ \nshould be split and show: \n g, HHH, 5, YY, ++, ///, \\ \n\n", "solution": "(() => {\n \"use strict\";\n\n // ----------- SPLIT ON CHARACTER CHANGES ------------\n const main = () =>\n group(\"gHHH5YY++///\\\\\")\n .map(x => x.join(\"\"))\n .join(\", \");\n\n\n // --------------------- GENERIC ---------------------\n\n // group :: [a] -> [[a]]\n const group = xs =>\n // A list of lists, each containing only\n // elements equal under (===), such that the\n // concatenation of these lists is xs.\n groupBy(a => b => a === b)(xs);\n\n\n // groupBy :: (a -> a -> Bool) [a] -> [[a]]\n const groupBy = eqOp =>\n // A list of lists, each containing only elements\n // equal under the given equality operator,\n // such that the concatenation of these lists is xs.\n xs => 0 < xs.length ? (() => {\n const [h, ...t] = xs;\n const [groups, g] = t.reduce(\n ([gs, a], x) => eqOp(x)(a[0]) ? (\n Tuple(gs)([...a, x])\n ) : Tuple([...gs, a])([x]),\n Tuple([])([h])\n );\n\n return [...groups, g];\n })() : [];\n\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = a =>\n b => ({\n type: \"Tuple\",\n \"0\": a,\n \"1\": b,\n length: 2,\n *[Symbol.iterator]() {\n for (const k in this) {\n if (!isNaN(k)) {\n yield this[k];\n }\n }\n }\n });\n\n // MAIN ---\n return main();\n})();"} +{"title": "Split a character string based on change of character", "language": "Python", "task": ";Task:\nSplit a (character) string into comma (plus a blank) delimited\nstrings based on a change of character \u00a0 (left to right).\n\nShow the output here \u00a0 (use the 1st example below).\n\n\nBlanks should be treated as any other character \u00a0 (except\nthey are problematic to display clearly). \u00a0 The same applies\nto commas.\n\n\nFor instance, the string: \n gHHH5YY++///\\ \nshould be split and show: \n g, HHH, 5, YY, ++, ///, \\ \n\n", "solution": "from itertools import groupby\n\ndef splitter(text):\n return ', '.join(''.join(group) for key, group in groupby(text))\n\nif __name__ == '__main__':\n txt = 'gHHH5YY++///\\\\' # Note backslash is the Python escape char.\n print(f'Input: {txt}\\nSplit: {splitter(txt)}')"} +{"title": "Square-free integers", "language": "C", "task": ";Task:\nWrite a function to test if a number is \u00a0 ''square-free''.\n\n\nA \u00a0 ''square-free'' \u00a0 is an integer which is divisible by no perfect square other\nthan \u00a0 '''1''' \u00a0 (unity).\n\nFor this task, only positive square-free numbers will be used.\n\n\n\nShow here (on this page) all square-free integers (in a horizontal format) that are between:\n::* \u00a0 '''1''' \u00a0 \u2500\u2500\u2500\u25ba \u00a0 '''145''' \u00a0 \u00a0 (inclusive)\n::* \u00a0 '''1''' trillion \u00a0 \u2500\u2500\u2500\u25ba \u00a0 '''1''' trillion + '''145''' \u00a0 \u00a0 (inclusive)\n\n\n(One trillion = 1,000,000,000,000)\n\n\nShow here (on this page) the count of square-free integers from:\n::* \u00a0 '''1''' \u00a0 \u2500\u2500\u2500\u25ba \u00a0 one hundred \u00a0 \u00a0 (inclusive)\n::* \u00a0 '''1''' \u00a0 \u2500\u2500\u2500\u25ba \u00a0 one thousand \u00a0 \u00a0 (inclusive)\n::* \u00a0 '''1''' \u00a0 \u2500\u2500\u2500\u25ba \u00a0 ten thousand \u00a0 \u00a0 (inclusive)\n::* \u00a0 '''1''' \u00a0 \u2500\u2500\u2500\u25ba \u00a0 one hundred thousand \u00a0 \u00a0 (inclusive)\n::* \u00a0 '''1''' \u00a0 \u2500\u2500\u2500\u25ba \u00a0 one million \u00a0 \u00a0 (inclusive)\n\n\n;See also:\n:* \u00a0 the Wikipedia entry: \u00a0 [https://wikipedia.org/wiki/Square-free_integer square-free integer]\n\n", "solution": "#include \n#include \n#include \n\n#define TRUE 1\n#define FALSE 0\n#define TRILLION 1000000000000\n\ntypedef unsigned char bool;\ntypedef unsigned long long uint64;\n\nvoid sieve(uint64 limit, uint64 *primes, uint64 *length) {\n uint64 i, count, p, p2;\n bool *c = calloc(limit + 1, sizeof(bool)); /* composite = TRUE */\n primes[0] = 2;\n count = 1;\n /* no need to process even numbers > 2 */\n p = 3;\n for (;;) {\n p2 = p * p;\n if (p2 > limit) break;\n for (i = p2; i <= limit; i += 2 * p) c[i] = TRUE;\n for (;;) {\n p += 2;\n if (!c[p]) break;\n }\n }\n for (i = 3; i <= limit; i += 2) {\n if (!c[i]) primes[count++] = i;\n }\n *length = count;\n free(c);\n}\n\nvoid squareFree(uint64 from, uint64 to, uint64 *results, uint64 *len) { \n uint64 i, j, p, p2, np, count = 0, limit = (uint64)sqrt((double)to);\n uint64 *primes = malloc((limit + 1) * sizeof(uint64));\n bool add;\n sieve(limit, primes, &np);\n for (i = from; i <= to; ++i) {\n add = TRUE;\n for (j = 0; j < np; ++j) {\n p = primes[j];\n p2 = p * p;\n if (p2 > i) break;\n if (i % p2 == 0) {\n add = FALSE;\n break;\n }\n }\n if (add) results[count++] = i;\n }\n *len = count;\n free(primes);\n}\n\nint main() {\n uint64 i, *sf, len;\n /* allocate enough memory to deal with all examples */\n sf = malloc(1000000 * sizeof(uint64));\n printf(\"Square-free integers from 1 to 145:\\n\");\n squareFree(1, 145, sf, &len);\n for (i = 0; i < len; ++i) {\n if (i > 0 && i % 20 == 0) {\n printf(\"\\n\");\n }\n printf(\"%4lld\", sf[i]);\n }\n\n printf(\"\\n\\nSquare-free integers from %ld to %ld:\\n\", TRILLION, TRILLION + 145);\n squareFree(TRILLION, TRILLION + 145, sf, &len);\n for (i = 0; i < len; ++i) {\n if (i > 0 && i % 5 == 0) {\n printf(\"\\n\");\n }\n printf(\"%14lld\", sf[i]);\n }\n\n printf(\"\\n\\nNumber of square-free integers:\\n\");\n int a[5] = {100, 1000, 10000, 100000, 1000000};\n for (i = 0; i < 5; ++i) {\n squareFree(1, a[i], sf, &len);\n printf(\" from %d to %d = %lld\\n\", 1, a[i], len);\n }\n free(sf);\n return 0; \n}"} +{"title": "Square-free integers", "language": "Python", "task": ";Task:\nWrite a function to test if a number is \u00a0 ''square-free''.\n\n\nA \u00a0 ''square-free'' \u00a0 is an integer which is divisible by no perfect square other\nthan \u00a0 '''1''' \u00a0 (unity).\n\nFor this task, only positive square-free numbers will be used.\n\n\n\nShow here (on this page) all square-free integers (in a horizontal format) that are between:\n::* \u00a0 '''1''' \u00a0 \u2500\u2500\u2500\u25ba \u00a0 '''145''' \u00a0 \u00a0 (inclusive)\n::* \u00a0 '''1''' trillion \u00a0 \u2500\u2500\u2500\u25ba \u00a0 '''1''' trillion + '''145''' \u00a0 \u00a0 (inclusive)\n\n\n(One trillion = 1,000,000,000,000)\n\n\nShow here (on this page) the count of square-free integers from:\n::* \u00a0 '''1''' \u00a0 \u2500\u2500\u2500\u25ba \u00a0 one hundred \u00a0 \u00a0 (inclusive)\n::* \u00a0 '''1''' \u00a0 \u2500\u2500\u2500\u25ba \u00a0 one thousand \u00a0 \u00a0 (inclusive)\n::* \u00a0 '''1''' \u00a0 \u2500\u2500\u2500\u25ba \u00a0 ten thousand \u00a0 \u00a0 (inclusive)\n::* \u00a0 '''1''' \u00a0 \u2500\u2500\u2500\u25ba \u00a0 one hundred thousand \u00a0 \u00a0 (inclusive)\n::* \u00a0 '''1''' \u00a0 \u2500\u2500\u2500\u25ba \u00a0 one million \u00a0 \u00a0 (inclusive)\n\n\n;See also:\n:* \u00a0 the Wikipedia entry: \u00a0 [https://wikipedia.org/wiki/Square-free_integer square-free integer]\n\n", "solution": "\nimport math\n\ndef SquareFree ( _number ) :\n\tmax = (int) (math.sqrt ( _number ))\n\n\tfor root in range ( 2, max+1 ):\t\t\t\t\t# Create a custom prime sieve\n\t\tif 0 == _number % ( root * root ):\n\t\t\treturn False\n\n\treturn True\n\ndef ListSquareFrees( _start, _end ):\n\tcount = 0\n\tfor i in range ( _start, _end+1 ):\n\t\tif True == SquareFree( i ):\n\t\t\tprint ( \"{}\\t\".format(i), end=\"\" )\n\t\t\tcount += 1\n\n\tprint ( \"\\n\\nTotal count of square-free numbers between {} and {}: {}\".format(_start, _end, count))\n\nListSquareFrees( 1, 100 )\nListSquareFrees( 1000000000000, 1000000000145 )\n"} +{"title": "Square but not cube", "language": "C", "task": ";Task:\nShow the first \u00a0 '''30''' \u00a0 positive integers which are squares but not cubes of such integers.\n\nOptionally, show also the first \u00a0 '''3''' \u00a0 positive integers which are both squares and cubes, \u00a0 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": "Square but not cube", "language": "JavaScript", "task": ";Task:\nShow the first \u00a0 '''30''' \u00a0 positive integers which are squares but not cubes of such integers.\n\nOptionally, show also the first \u00a0 '''3''' \u00a0 positive integers which are both squares and cubes, \u00a0 and mark them as such.\n\n", "solution": "(() => {\n 'use strict';\n\n const main = () =>\n unlines(map(\n x => x.toString() + (\n isCube(x) ? (\n ` (cube of ${cubeRootInt(x)} and square of ${\n Math.pow(x, 1/2)\n })`\n ) : ''\n ),\n map(x => x * x, enumFromTo(1, 33))\n ));\n\n // isCube :: Int -> Bool\n const isCube = n =>\n n === Math.pow(cubeRootInt(n), 3);\n\n // cubeRootInt :: Int -> Int\n const cubeRootInt = n => Math.round(Math.pow(n, 1 / 3));\n \n\n // GENERIC FUNCTIONS ----------------------------------\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = (m, n) =>\n m <= n ? iterateUntil(\n x => n <= x,\n x => 1 + x,\n m\n ) : [];\n\n // iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a]\n const iterateUntil = (p, f, x) => {\n const vs = [x];\n let h = x;\n while (!p(h))(h = f(h), vs.push(h));\n return vs;\n };\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) => xs.map(f);\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // MAIN ---\n return main();\n})();"} +{"title": "Square but not cube", "language": "Python", "task": ";Task:\nShow the first \u00a0 '''30''' \u00a0 positive integers which are squares but not cubes of such integers.\n\nOptionally, show also the first \u00a0 '''3''' \u00a0 positive integers which are both squares and cubes, \u00a0 and mark them as such.\n\n", "solution": "# nonCubeSquares :: Int -> [(Int, Bool)]\ndef nonCubeSquares(n):\n upto = enumFromTo(1)\n ns = upto(n)\n setCubes = set(x ** 3 for x in ns)\n ms = upto(n + len(set(x * x for x in ns).intersection(\n setCubes\n )))\n return list(tuple([x * x, x in setCubes]) for x in ms)\n\n\n# squareListing :: [(Int, Bool)] -> [String]\ndef squareListing(xs):\n justifyIdx = justifyRight(len(str(1 + len(xs))))(' ')\n justifySqr = justifyRight(1 + len(str(xs[-1][0])))(' ')\n return list(\n '(' + str(1 + idx) + '^2 = ' + str(n) +\n ' = ' + str(round(n ** (1 / 3))) + '^3)' if bln else (\n justifyIdx(1 + idx) + ' ->' +\n justifySqr(n)\n )\n for idx, (n, bln) in enumerate(xs)\n )\n\n\ndef main():\n print(\n unlines(\n squareListing(\n nonCubeSquares(30)\n )\n )\n )\n\n\n# GENERIC ------------------------------------------------------------------\n\n# enumFromTo :: Int -> Int -> [Int]\ndef enumFromTo(m):\n return lambda n: list(range(m, 1 + n))\n\n\n# justifyRight :: Int -> Char -> String -> String\ndef justifyRight(n):\n return lambda cFiller: lambda a: (\n ((n * cFiller) + str(a))[-n:]\n )\n\n\n# unlines :: [String] -> String\ndef unlines(xs):\n return '\\n'.join(xs)\n\n\nmain()"} +{"title": "Stair-climbing puzzle", "language": "C", "task": "From [http://lambda-the-ultimate.org/node/1872 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": "Stair-climbing puzzle", "language": "Python", "task": "From [http://lambda-the-ultimate.org/node/1872 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": "def step_up1():\n \"\"\"Straightforward implementation: keep track of how many level we\n need to ascend, and stop when this count is zero.\"\"\"\n deficit = 1\n while deficit > 0:\n if step():\n deficit -= 1\n else:\n deficit += 1"} +{"title": "Start from a main routine", "language": "C", "task": "Some languages (like Gambas and Visual Basic) support two startup modes. \u00a0 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. \u00a0 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": "\n#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": "Statistics/Normal distribution", "language": "Python", "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": "from __future__ import division\nimport matplotlib.pyplot as plt \nimport random\n\nmean, stddev, size = 50, 4, 100000\ndata = [random.gauss(mean, stddev) for c in range(size)]\n\nmn = sum(data) / size\nsd = (sum(x*x for x in data) / size \n - (sum(data) / size) ** 2) ** 0.5\n\nprint(\"Sample mean = %g; Stddev = %g; max = %g; min = %g for %i values\" \n % (mn, sd, max(data), min(data), size))\n\nplt.hist(data,bins=50)"} +{"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#* \u00a0 \u00a0 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#* \u00a0 \u00a0 1, 1, 2\n# Append the considered member of the sequence to the end of the sequence:\n#* \u00a0 \u00a0 1, 1, 2, 1\n# Consider the next member of the series, (the third member i.e. 2)\n# GOTO 3\n#*\n#* \u00a0 \u00a0 \u00a0 \u00a0 \u2500\u2500\u2500 Expanding another loop we get: \u2500\u2500\u2500\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#* \u00a0 \u00a0 1, 1, 2, 1, 3\n# Append the considered member of the sequence to the end of the sequence:\n#* \u00a0 \u00a0 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:* \u00a0 [[Fusc sequence]].\n:* \u00a0 [[Continued fraction/Arithmetic]]\n\n\n;Ref:\n* [https://www.youtube.com/watch?v=DpwUVExX27E Infinite Fractions - Numberphile] (Video).\n* [http://www.ams.org/samplings/feature-column/fcarc-stern-brocot Trees, Teeth, and Time: The mathematics of clock making].\n* [https://oeis.org/A002487 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": "Stern-Brocot sequence", "language": "JavaScript", "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#* \u00a0 \u00a0 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#* \u00a0 \u00a0 1, 1, 2\n# Append the considered member of the sequence to the end of the sequence:\n#* \u00a0 \u00a0 1, 1, 2, 1\n# Consider the next member of the series, (the third member i.e. 2)\n# GOTO 3\n#*\n#* \u00a0 \u00a0 \u00a0 \u00a0 \u2500\u2500\u2500 Expanding another loop we get: \u2500\u2500\u2500\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#* \u00a0 \u00a0 1, 1, 2, 1, 3\n# Append the considered member of the sequence to the end of the sequence:\n#* \u00a0 \u00a0 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:* \u00a0 [[Fusc sequence]].\n:* \u00a0 [[Continued fraction/Arithmetic]]\n\n\n;Ref:\n* [https://www.youtube.com/watch?v=DpwUVExX27E Infinite Fractions - Numberphile] (Video).\n* [http://www.ams.org/samplings/feature-column/fcarc-stern-brocot Trees, Teeth, and Time: The mathematics of clock making].\n* [https://oeis.org/A002487 A002487] The On-Line Encyclopedia of Integer Sequences.\n\n", "solution": "(() => {\n 'use strict';\n\n const main = () => {\n\n // sternBrocot :: Generator [Int]\n const sternBrocot = () => {\n const go = xs => {\n const x = snd(xs);\n return tail(append(xs, [fst(xs) + x, x]));\n };\n return fmapGen(head, iterate(go, [1, 1]));\n };\n\n\n // TESTS ------------------------------------------\n const\n sbs = take(1200, sternBrocot()),\n ixSB = zip(sbs, enumFrom(1));\n\n return unlines(map(\n JSON.stringify,\n [\n take(15, sbs),\n take(10,\n map(listFromTuple,\n nubBy(\n on(eq, fst),\n sortBy(\n comparing(fst),\n takeWhile(x => 12 !== fst(x), ixSB)\n )\n )\n )\n ),\n listFromTuple(\n take(1, dropWhile(x => 100 !== fst(x), ixSB))[0]\n ),\n all(tpl => 1 === gcd(fst(tpl), snd(tpl)),\n take(1000, zip(sbs, tail(sbs)))\n )\n ]\n ));\n };\n\n // GENERIC ABSTRACTIONS -------------------------------\n\n // Just :: a -> Maybe a\n const Just = x => ({\n type: 'Maybe',\n Nothing: false,\n Just: x\n });\n\n // Nothing :: Maybe a\n const Nothing = () => ({\n type: 'Maybe',\n Nothing: true,\n });\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = (a, b) => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // | Absolute value.\n\n // abs :: Num -> Num\n const abs = Math.abs;\n\n // Determines whether all elements of the structure\n // satisfy the predicate.\n\n // all :: (a -> Bool) -> [a] -> Bool\n const all = (p, xs) => xs.every(p);\n\n // append (++) :: [a] -> [a] -> [a]\n // append (++) :: String -> String -> String\n const append = (xs, ys) => xs.concat(ys);\n\n // chr :: Int -> Char\n const chr = String.fromCodePoint;\n\n // comparing :: (a -> b) -> (a -> a -> Ordering)\n const comparing = f =>\n (x, y) => {\n const\n a = f(x),\n b = f(y);\n return a < b ? -1 : (a > b ? 1 : 0);\n };\n\n // dropWhile :: (a -> Bool) -> [a] -> [a]\n // dropWhile :: (Char -> Bool) -> String -> String\n const dropWhile = (p, xs) => {\n const lng = xs.length;\n return 0 < lng ? xs.slice(\n until(\n i => i === lng || !p(xs[i]),\n i => 1 + i,\n 0\n )\n ) : [];\n };\n\n // enumFrom :: a -> [a]\n function* enumFrom(x) {\n let v = x;\n while (true) {\n yield v;\n v = succ(v);\n }\n }\n\n // eq (==) :: Eq a => a -> a -> Bool\n const eq = (a, b) => {\n const t = typeof a;\n return t !== typeof b ? (\n false\n ) : 'object' !== t ? (\n 'function' !== t ? (\n a === b\n ) : a.toString() === b.toString()\n ) : (() => {\n const aks = Object.keys(a);\n return aks.length !== Object.keys(b).length ? (\n false\n ) : aks.every(k => eq(a[k], b[k]));\n })();\n };\n\n // fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]\n function* fmapGen(f, gen) {\n const g = gen;\n let v = take(1, g)[0];\n while (0 < v.length) {\n yield(f(v))\n v = take(1, g)[0]\n }\n }\n\n // fst :: (a, b) -> a\n const fst = tpl => tpl[0];\n\n // gcd :: Int -> Int -> Int\n const gcd = (x, y) => {\n const\n _gcd = (a, b) => (0 === b ? a : _gcd(b, a % b)),\n abs = Math.abs;\n return _gcd(abs(x), abs(y));\n };\n\n // head :: [a] -> a\n const head = xs => xs.length ? xs[0] : undefined;\n\n // isChar :: a -> Bool\n const isChar = x =>\n ('string' === typeof x) && (1 === x.length);\n\n // iterate :: (a -> a) -> a -> Gen [a]\n function* iterate(f, x) {\n let v = x;\n while (true) {\n yield(v);\n v = f(v);\n }\n }\n\n // Returns Infinity over objects without finite length\n // this enables zip and zipWith to choose the shorter\n // argument when one is non-finite, like cycle, repeat etc\n\n // length :: [a] -> Int\n const length = xs => xs.length || Infinity;\n\n // listFromTuple :: (a, a ...) -> [a]\n const listFromTuple = tpl =>\n Array.from(tpl);\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) => xs.map(f);\n\n // nubBy :: (a -> a -> Bool) -> [a] -> [a]\n const nubBy = (p, xs) => {\n const go = xs => 0 < xs.length ? (() => {\n const x = xs[0];\n return [x].concat(\n go(xs.slice(1)\n .filter(y => !p(x, y))\n )\n )\n })() : [];\n return go(xs);\n };\n\n // e.g. sortBy(on(compare,length), xs)\n\n // on :: (b -> b -> c) -> (a -> b) -> a -> a -> c\n const on = (f, g) => (a, b) => f(g(a), g(b));\n\n // ord :: Char -> Int\n const ord = c => c.codePointAt(0);\n\n // snd :: (a, b) -> b\n const snd = tpl => tpl[1];\n\n // sortBy :: (a -> a -> Ordering) -> [a] -> [a]\n const sortBy = (f, xs) =>\n xs.slice()\n .sort(f);\n\n // succ :: Enum a => a -> a\n const succ = x =>\n isChar(x) ? (\n chr(1 + ord(x))\n ) : isNaN(x) ? (\n undefined\n ) : 1 + x;\n\n // tail :: [a] -> [a]\n const tail = xs => 0 < xs.length ? xs.slice(1) : [];\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = (n, xs) =>\n xs.constructor.constructor.name !== 'GeneratorFunction' ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // takeWhile :: (a -> Bool) -> [a] -> [a]\n // takeWhile :: (Char -> Bool) -> String -> String\n const takeWhile = (p, xs) =>\n xs.constructor.constructor.name !==\n 'GeneratorFunction' ? (() => {\n const lng = xs.length;\n return 0 < lng ? xs.slice(\n 0,\n until(\n i => lng === i || !p(xs[i]),\n i => 1 + i,\n 0\n )\n ) : [];\n })() : takeWhileGen(p, xs);\n\n // takeWhileGen :: (a -> Bool) -> Gen [a] -> [a]\n const takeWhileGen = (p, xs) => {\n const ys = [];\n let\n nxt = xs.next(),\n v = nxt.value;\n while (!nxt.done && p(v)) {\n ys.push(v);\n nxt = xs.next();\n v = nxt.value\n }\n return ys;\n };\n\n // uncons :: [a] -> Maybe (a, [a])\n const uncons = xs => {\n const lng = length(xs);\n return (0 < lng) ? (\n lng < Infinity ? (\n Just(Tuple(xs[0], xs.slice(1))) // Finite list\n ) : (() => {\n const nxt = take(1, xs);\n return 0 < nxt.length ? (\n Just(Tuple(nxt[0], xs))\n ) : Nothing();\n })() // Lazy generator\n ) : Nothing();\n };\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // until :: (a -> Bool) -> (a -> a) -> a -> a\n const until = (p, f, x) => {\n let v = x;\n while (!p(v)) v = f(v);\n return v;\n };\n\n // Use of `take` and `length` here allows for zipping with non-finite\n // lists - i.e. generators like cycle, repeat, iterate.\n\n // zip :: [a] -> [b] -> [(a, b)]\n const zip = (xs, ys) => {\n const lng = Math.min(length(xs), length(ys));\n return Infinity !== lng ? (() => {\n const bs = take(lng, ys);\n return take(lng, xs).map((x, i) => Tuple(x, bs[i]));\n })() : zipGen(xs, ys);\n };\n\n // zipGen :: Gen [a] -> Gen [b] -> Gen [(a, b)]\n const zipGen = (ga, gb) => {\n function* go(ma, mb) {\n let\n a = ma,\n b = mb;\n while (!a.Nothing && !b.Nothing) {\n let\n ta = a.Just,\n tb = b.Just\n yield(Tuple(fst(ta), fst(tb)));\n a = uncons(snd(ta));\n b = uncons(snd(tb));\n }\n }\n return go(uncons(ga), uncons(gb));\n };\n\n // MAIN ---\n return main();\n})();"} +{"title": "Stern-Brocot sequence", "language": "Python", "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#* \u00a0 \u00a0 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#* \u00a0 \u00a0 1, 1, 2\n# Append the considered member of the sequence to the end of the sequence:\n#* \u00a0 \u00a0 1, 1, 2, 1\n# Consider the next member of the series, (the third member i.e. 2)\n# GOTO 3\n#*\n#* \u00a0 \u00a0 \u00a0 \u00a0 \u2500\u2500\u2500 Expanding another loop we get: \u2500\u2500\u2500\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#* \u00a0 \u00a0 1, 1, 2, 1, 3\n# Append the considered member of the sequence to the end of the sequence:\n#* \u00a0 \u00a0 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:* \u00a0 [[Fusc sequence]].\n:* \u00a0 [[Continued fraction/Arithmetic]]\n\n\n;Ref:\n* [https://www.youtube.com/watch?v=DpwUVExX27E Infinite Fractions - Numberphile] (Video).\n* [http://www.ams.org/samplings/feature-column/fcarc-stern-brocot Trees, Teeth, and Time: The mathematics of clock making].\n* [https://oeis.org/A002487 A002487] The On-Line Encyclopedia of Integer Sequences.\n\n", "solution": "def stern_brocot(predicate=lambda series: len(series) < 20):\n \"\"\"\\\n Generates members of the stern-brocot series, in order, returning them when the predicate becomes false\n\n >>> print('The first 10 values:',\n stern_brocot(lambda series: len(series) < 10)[:10])\n The first 10 values: [1, 1, 2, 1, 3, 2, 3, 1, 4, 3]\n >>>\n \"\"\"\n\n sb, i = [1, 1], 0\n while predicate(sb):\n sb += [sum(sb[i:i + 2]), sb[i + 1]]\n i += 1\n return sb\n\n\nif __name__ == '__main__':\n from fractions import gcd\n\n n_first = 15\n print('The first %i values:\\n ' % n_first,\n stern_brocot(lambda series: len(series) < n_first)[:n_first])\n print()\n n_max = 10\n for n_occur in list(range(1, n_max + 1)) + [100]:\n print('1-based index of the first occurrence of %3i in the series:' % n_occur,\n stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1)\n # The following would be much faster. Note that new values always occur at odd indices\n # len(stern_brocot(lambda series: n_occur != series[-2])) - 1)\n\n print()\n n_gcd = 1000\n s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd]\n assert all(gcd(prev, this) == 1\n for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'"} +{"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(\u227b, max)) {\n fprintf(stderr, \"Out of memory\\n\");\n return 1;\n }\n print_stirling_numbers(\u227b, max);\n stirling_cache_destroy(\u227b);\n return 0;\n}"} +{"title": "Stirling numbers of the first kind", "language": "Python", "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": "\ncomputed = {}\n\ndef sterling1(n, k):\n\tkey = str(n) + \",\" + str(k)\n\n\tif key in computed.keys():\n\t\treturn computed[key]\n\tif n == k == 0:\n\t\treturn 1\n\tif n > 0 and k == 0:\n\t\treturn 0\n\tif k > n:\n\t\treturn 0\n\tresult = sterling1(n - 1, k - 1) + (n - 1) * sterling1(n - 1, k)\n\tcomputed[key] = result\n\treturn result\n\nprint(\"Unsigned Stirling numbers of the first kind:\")\nMAX = 12\nprint(\"n/k\".ljust(10), end=\"\")\nfor n in range(MAX + 1):\n\tprint(str(n).rjust(10), end=\"\")\nprint()\nfor n in range(MAX + 1):\n\tprint(str(n).ljust(10), end=\"\")\n\tfor k in range(n + 1):\n\t\tprint(str(sterling1(n, k)).rjust(10), end=\"\")\n\tprint()\nprint(\"The maximum value of S1(100, k) = \")\nprevious = 0\nfor k in range(1, 100 + 1):\n\tcurrent = sterling1(100, k)\n\tif current > previous:\n\t\tprevious = current\n\telse:\n\t\tprint(\"{0}\\n({1} digits, k = {2})\\n\".format(previous, len(str(previous)), k - 1))\n\t\tbreak\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(\u227b, max)) {\n fprintf(stderr, \"Out of memory\\n\");\n return 1;\n }\n print_stirling_numbers(\u227b, max);\n stirling_cache_destroy(\u227b);\n return 0;\n}"} +{"title": "Stirling numbers of the second kind", "language": "Python", "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": "\ncomputed = {}\n\ndef sterling2(n, k):\n\tkey = str(n) + \",\" + str(k)\n\n\tif key in computed.keys():\n\t\treturn computed[key]\n\tif n == k == 0:\n\t\treturn 1\n\tif (n > 0 and k == 0) or (n == 0 and k > 0):\n\t\treturn 0\n\tif n == k:\n\t\treturn 1\n\tif k > n:\n\t\treturn 0\n\tresult = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)\n\tcomputed[key] = result\n\treturn result\n\nprint(\"Stirling numbers of the second kind:\")\nMAX = 12\nprint(\"n/k\".ljust(10), end=\"\")\nfor n in range(MAX + 1):\n\tprint(str(n).rjust(10), end=\"\")\nprint()\nfor n in range(MAX + 1):\n\tprint(str(n).ljust(10), end=\"\")\n\tfor k in range(n + 1):\n\t\tprint(str(sterling2(n, k)).rjust(10), end=\"\")\n\tprint()\nprint(\"The maximum value of S2(100, k) = \")\nprevious = 0\nfor k in range(1, 100 + 1):\n\tcurrent = sterling2(100, k)\n\tif current > previous:\n\t\tprevious = current\n\telse:\n\t\tprint(\"{0}\\n({1} digits, k = {2})\\n\".format(previous, len(str(previous)), k - 1))\n\t\tbreak\n"} +{"title": "Strassen's algorithm", "language": "Python", "task": ";Description\nIn linear algebra, the Strassen algorithm \u00a0 (named after Volker Strassen), \u00a0 is an algorithm for matrix multiplication. \n\nIt is faster than the standard matrix multiplication algorithm and is useful in practice for large matrices, \u00a0 but would be slower than the fastest known algorithms for extremely large matrices.\n\n\n;Task\nWrite a routine, function, procedure etc. in your language to implement the Strassen algorithm for matrix multiplication.\n\nWhile practical implementations of Strassen's algorithm usually switch to standard methods of matrix multiplication for small enough sub-matrices (currently anything less than \u00a0 512\u00d7512 \u00a0 according to Wikipedia), \u00a0 for the purposes of this task you should not switch until reaching a size of 1 or 2.\n\n\n;Related task\n:* [[Matrix multiplication]]\n\n\n;See also\n:* Wikipedia article\n\n", "solution": "\"\"\"Matrix multiplication using Strassen's algorithm. Requires Python >= 3.7.\"\"\"\n\nfrom __future__ import annotations\nfrom itertools import chain\nfrom typing import List\nfrom typing import NamedTuple\nfrom typing import Optional\n\n\nclass Shape(NamedTuple):\n rows: int\n cols: int\n\n\nclass Matrix(List):\n \"\"\"A matrix implemented as a two-dimensional list.\"\"\"\n\n @classmethod\n def block(cls, blocks) -> Matrix:\n \"\"\"Return a new Matrix assembled from nested blocks.\"\"\"\n m = Matrix()\n for hblock in blocks:\n for row in zip(*hblock):\n m.append(list(chain.from_iterable(row)))\n\n return m\n\n def dot(self, b: Matrix) -> Matrix:\n \"\"\"Return a new Matrix that is the product of this matrix and matrix `b`.\n Uses 'simple' or 'naive' matrix multiplication.\"\"\"\n assert self.shape.cols == b.shape.rows\n m = Matrix()\n for row in self:\n new_row = []\n for c in range(len(b[0])):\n col = [b[r][c] for r in range(len(b))]\n new_row.append(sum(x * y for x, y in zip(row, col)))\n m.append(new_row)\n return m\n\n def __matmul__(self, b: Matrix) -> Matrix:\n return self.dot(b)\n\n def __add__(self, b: Matrix) -> Matrix:\n \"\"\"Matrix addition.\"\"\"\n assert self.shape == b.shape\n rows, cols = self.shape\n return Matrix(\n [[self[i][j] + b[i][j] for j in range(cols)] for i in range(rows)]\n )\n\n def __sub__(self, b: Matrix) -> Matrix:\n \"\"\"Matrix subtraction.\"\"\"\n assert self.shape == b.shape\n rows, cols = self.shape\n return Matrix(\n [[self[i][j] - b[i][j] for j in range(cols)] for i in range(rows)]\n )\n\n def strassen(self, b: Matrix) -> Matrix:\n \"\"\"Return a new Matrix that is the product of this matrix and matrix `b`.\n Uses strassen algorithm.\"\"\"\n rows, cols = self.shape\n\n assert rows == cols, \"matrices must be square\"\n assert self.shape == b.shape, \"matrices must be the same shape\"\n assert rows and (rows & rows - 1) == 0, \"shape must be a power of 2\"\n\n if rows == 1:\n return self.dot(b)\n\n p = rows // 2 # partition\n\n a11 = Matrix([n[:p] for n in self[:p]])\n a12 = Matrix([n[p:] for n in self[:p]])\n a21 = Matrix([n[:p] for n in self[p:]])\n a22 = Matrix([n[p:] for n in self[p:]])\n\n b11 = Matrix([n[:p] for n in b[:p]])\n b12 = Matrix([n[p:] for n in b[:p]])\n b21 = Matrix([n[:p] for n in b[p:]])\n b22 = Matrix([n[p:] for n in b[p:]])\n\n m1 = (a11 + a22).strassen(b11 + b22)\n m2 = (a21 + a22).strassen(b11)\n m3 = a11.strassen(b12 - b22)\n m4 = a22.strassen(b21 - b11)\n m5 = (a11 + a12).strassen(b22)\n m6 = (a21 - a11).strassen(b11 + b12)\n m7 = (a12 - a22).strassen(b21 + b22)\n\n c11 = m1 + m4 - m5 + m7\n c12 = m3 + m5\n c21 = m2 + m4\n c22 = m1 - m2 + m3 + m6\n\n return Matrix.block([[c11, c12], [c21, c22]])\n\n def round(self, ndigits: Optional[int] = None) -> Matrix:\n return Matrix([[round(i, ndigits) for i in row] for row in self])\n\n @property\n def shape(self) -> Shape:\n cols = len(self[0]) if self else 0\n return Shape(len(self), cols)\n\n\ndef examples():\n a = Matrix(\n [\n [1, 2],\n [3, 4],\n ]\n )\n b = Matrix(\n [\n [5, 6],\n [7, 8],\n ]\n )\n c = Matrix(\n [\n [1, 1, 1, 1],\n [2, 4, 8, 16],\n [3, 9, 27, 81],\n [4, 16, 64, 256],\n ]\n )\n d = Matrix(\n [\n [4, -3, 4 / 3, -1 / 4],\n [-13 / 3, 19 / 4, -7 / 3, 11 / 24],\n [3 / 2, -2, 7 / 6, -1 / 4],\n [-1 / 6, 1 / 4, -1 / 6, 1 / 24],\n ]\n )\n e = Matrix(\n [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n ]\n )\n f = Matrix(\n [\n [1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1],\n ]\n )\n\n print(\"Naive matrix multiplication:\")\n print(f\" a * b = {a @ b}\")\n print(f\" c * d = {(c @ d).round()}\")\n print(f\" e * f = {e @ f}\")\n\n print(\"Strassen's matrix multiplication:\")\n print(f\" a * b = {a.strassen(b)}\")\n print(f\" c * d = {c.strassen(d).round()}\")\n print(f\" e * f = {e.strassen(f)}\")\n\n\nif __name__ == \"__main__\":\n examples()\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 \u00a0 ''N'' \u00a0 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": "Stream merge", "language": "Python", "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 \u00a0 ''N'' \u00a0 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": "import heapq\nimport sys\n\nsources = sys.argv[1:]\nfor item in heapq.merge(open(source) for source in sources):\n print(item)"} +{"title": "Strip control codes and extended characters from a string", "language": "C", "task": ";Task:\nStrip control codes and extended characters from a string. \n\n\nThe solution should demonstrate how to achieve each of the following results:\n:* \u00a0 a string with control codes stripped (but extended characters not stripped)\n:* \u00a0 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"} +{"title": "Strip control codes and extended characters from a string", "language": "JavaScript", "task": ";Task:\nStrip control codes and extended characters from a string. \n\n\nThe solution should demonstrate how to achieve each of the following results:\n:* \u00a0 a string with control codes stripped (but extended characters not stripped)\n:* \u00a0 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": "(function (strTest) {\n\n // s -> s\n function strip(s) {\n return s.split('').filter(function (x) {\n var n = x.charCodeAt(0);\n \n return 31 < n && 127 > n;\n }).join('');\n }\n\n return strip(strTest);\n\n})(\"\\ba\\x00b\\n\\rc\\fd\\xc3\");"} +{"title": "Strip control codes and extended characters from a string", "language": "Python", "task": ";Task:\nStrip control codes and extended characters from a string. \n\n\nThe solution should demonstrate how to achieve each of the following results:\n:* \u00a0 a string with control codes stripped (but extended characters not stripped)\n:* \u00a0 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": "stripped = lambda s: \"\".join(i for i in s if 31 < ord(i) < 127)\n\nprint(stripped(\"\\ba\\x00b\\n\\rc\\fd\\xc3\"))"} +{"title": "Subleq", "language": "C", "task": "One-Instruction Set Computer (OISC). \n\nIt is named after its only instruction, which is '''SU'''btract and '''B'''ranch if '''L'''ess than or '''EQ'''ual to zero. \n\n;Task\nYour task is to create an interpreter which emulates a SUBLEQ machine.\n\nThe machine's memory consists of an array of signed integers. \u00a0 These integers may be interpreted in three ways:\n::::* \u00a0 simple numeric values \n::::* \u00a0 memory addresses \n::::* \u00a0 characters for input or output\n\nAny reasonable word size that accommodates all three of the above uses is fine. \n\nThe program should load the initial contents of the emulated machine's memory, set the instruction pointer to the first address (which is defined to be address 0), and begin emulating the machine, which works as follows:\n:# \u00a0 Let '''A''' be the value in the memory location identified by the instruction pointer; \u00a0 let '''B''' and '''C''' be the values stored in the next two consecutive addresses in memory.\n:# \u00a0 Advance the instruction pointer three words, to point at the address ''after'' the address containing '''C'''.\n:# \u00a0 If '''A''' is \u00a0 '''-1''' \u00a0 (negative unity), \u00a0 then a character is read from the machine's input and its numeric value stored in the address given by '''B'''. \u00a0 '''C''' is unused.\n:# \u00a0 If '''B''' is \u00a0 '''-1''' \u00a0 (negative unity), \u00a0 then the number contained in the address given by '''A''' is interpreted as a character and written to the machine's output. \u00a0 '''C''' is unused.\n:# \u00a0 Otherwise, both '''A''' and '''B''' are treated as addresses. \u00a0 The number contained in address '''A''' is subtracted from the number in address '''B''' (and the difference left in address '''B'''). \u00a0 If the result is positive, execution continues uninterrupted; if the result is zero or negative, the number in '''C''' becomes the new instruction pointer.\n:# \u00a0 If the instruction pointer becomes negative, execution halts.\n\nYour solution may initialize the emulated machine's memory in any convenient manner, but if you accept it as input, it should be a separate input stream from the one fed to the emulated machine once it is running. And if fed as text input, it should be in the form of raw subleq \"machine code\" - whitespace-separated decimal numbers, with no symbolic names or other assembly-level extensions, to be loaded into memory starting at address \u00a0 '''0''' \u00a0 (zero).\n\nFor purposes of this task, show the output of your solution when fed the below \u00a0 \"Hello, world!\" \u00a0 program. \n\nAs written, this example assumes ASCII or a superset of it, such as any of the Latin-N character sets or Unicode; \u00a0 you may translate the numbers representing characters (starting with 72=ASCII 'H') into another character set if your implementation runs in a non-ASCII-compatible environment. If 0 is not an appropriate terminator in your character set, the program logic will need some adjustment as well.\n\n15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0\n\nThe above \"machine code\" corresponds to something like this in a hypothetical assembler language for a signed 8-bit version of the machine:\n\nstart:\n 0f 11 ff subleq (zero), (message), -1\n 11 ff ff subleq (message), -1, -1 ; output character at message\n 10 01 ff subleq (neg1), (start+1), -1\n 10 03 ff subleq (neg1), (start+3), -1\n 0f 0f 00 subleq (zero), (zero), start\n; useful constants\nzero: \n 00 .data 0 \nneg1: \n ff .data -1\n; the message to print\nmessage: .data \"Hello, world!\\n\\0\"\n 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a 00\n\n", "solution": "#include \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\", #);\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": "Subleq", "language": "Python", "task": "One-Instruction Set Computer (OISC). \n\nIt is named after its only instruction, which is '''SU'''btract and '''B'''ranch if '''L'''ess than or '''EQ'''ual to zero. \n\n;Task\nYour task is to create an interpreter which emulates a SUBLEQ machine.\n\nThe machine's memory consists of an array of signed integers. \u00a0 These integers may be interpreted in three ways:\n::::* \u00a0 simple numeric values \n::::* \u00a0 memory addresses \n::::* \u00a0 characters for input or output\n\nAny reasonable word size that accommodates all three of the above uses is fine. \n\nThe program should load the initial contents of the emulated machine's memory, set the instruction pointer to the first address (which is defined to be address 0), and begin emulating the machine, which works as follows:\n:# \u00a0 Let '''A''' be the value in the memory location identified by the instruction pointer; \u00a0 let '''B''' and '''C''' be the values stored in the next two consecutive addresses in memory.\n:# \u00a0 Advance the instruction pointer three words, to point at the address ''after'' the address containing '''C'''.\n:# \u00a0 If '''A''' is \u00a0 '''-1''' \u00a0 (negative unity), \u00a0 then a character is read from the machine's input and its numeric value stored in the address given by '''B'''. \u00a0 '''C''' is unused.\n:# \u00a0 If '''B''' is \u00a0 '''-1''' \u00a0 (negative unity), \u00a0 then the number contained in the address given by '''A''' is interpreted as a character and written to the machine's output. \u00a0 '''C''' is unused.\n:# \u00a0 Otherwise, both '''A''' and '''B''' are treated as addresses. \u00a0 The number contained in address '''A''' is subtracted from the number in address '''B''' (and the difference left in address '''B'''). \u00a0 If the result is positive, execution continues uninterrupted; if the result is zero or negative, the number in '''C''' becomes the new instruction pointer.\n:# \u00a0 If the instruction pointer becomes negative, execution halts.\n\nYour solution may initialize the emulated machine's memory in any convenient manner, but if you accept it as input, it should be a separate input stream from the one fed to the emulated machine once it is running. And if fed as text input, it should be in the form of raw subleq \"machine code\" - whitespace-separated decimal numbers, with no symbolic names or other assembly-level extensions, to be loaded into memory starting at address \u00a0 '''0''' \u00a0 (zero).\n\nFor purposes of this task, show the output of your solution when fed the below \u00a0 \"Hello, world!\" \u00a0 program. \n\nAs written, this example assumes ASCII or a superset of it, such as any of the Latin-N character sets or Unicode; \u00a0 you may translate the numbers representing characters (starting with 72=ASCII 'H') into another character set if your implementation runs in a non-ASCII-compatible environment. If 0 is not an appropriate terminator in your character set, the program logic will need some adjustment as well.\n\n15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0\n\nThe above \"machine code\" corresponds to something like this in a hypothetical assembler language for a signed 8-bit version of the machine:\n\nstart:\n 0f 11 ff subleq (zero), (message), -1\n 11 ff ff subleq (message), -1, -1 ; output character at message\n 10 01 ff subleq (neg1), (start+1), -1\n 10 03 ff subleq (neg1), (start+3), -1\n 0f 0f 00 subleq (zero), (zero), start\n; useful constants\nzero: \n 00 .data 0 \nneg1: \n ff .data -1\n; the message to print\nmessage: .data \"Hello, world!\\n\\0\"\n 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a 00\n\n", "solution": "import sys\n\ndef subleq(a):\n i = 0\n try:\n while i >= 0:\n if a[i] == -1:\n a[a[i + 1]] = ord(sys.stdin.read(1))\n elif a[i + 1] == -1:\n print(chr(a[a[i]]), end=\"\")\n else:\n a[a[i + 1]] -= a[a[i]]\n if a[a[i + 1]] <= 0:\n i = a[i + 2]\n continue\n i += 3\n except (ValueError, IndexError, KeyboardInterrupt):\n print(\"abort\")\n print(a)\n\nsubleq([15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15,\n 0, 0, -1, 72, 101, 108, 108, 111, 44, 32, 119, 111,\n 114, 108, 100, 33, 10, 0])"} +{"title": "Substring/Top and tail", "language": "C", "task": "[[Category:String manipulation]]\nThe 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": "Substring/Top and tail", "language": "JavaScript", "task": "[[Category:String manipulation]]\nThe 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": "alert(\"knight\".slice(1)); // strip first character\nalert(\"socks\".slice(0, -1)); // strip last character\nalert(\"brooms\".slice(1, -1)); // strip both first and last characters"} +{"title": "Substring/Top and tail", "language": "Python", "task": "[[Category:String manipulation]]\nThe 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": "from functools import (reduce)\n\n\ndef main():\n for xs in transpose(\n (chunksOf(3)(\n ap([tail, init, compose(init)(tail)])(\n ['knights', 'socks', 'brooms']\n )\n ))\n ):\n print(xs)\n\n\n# GENERIC -------------------------------------------------\n\n# tail :: [a] -> [a]\ndef tail(xs):\n return xs[1:]\n\n\n# init::[a] - > [a]\ndef init(xs):\n return xs[:-1]\n\n\n# ap (<*>) :: [(a -> b)] -> [a] -> [b]\ndef ap(fs):\n return lambda xs: reduce(\n lambda a, f: a + reduce(\n lambda a, x: a + [f(x)], xs, []\n ), fs, []\n )\n\n\n# chunksOf :: Int -> [a] -> [[a]]\ndef chunksOf(n):\n return lambda xs: reduce(\n lambda a, i: a + [xs[i:n + i]],\n range(0, len(xs), n), []\n ) if 0 < n else []\n\n\n# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n return lambda f: lambda x: g(f(x))\n\n\n# transpose :: [[a]] -> [[a]]\ndef transpose(xs):\n return list(map(list, zip(*xs)))\n\n\nif __name__ == '__main__':\n main()"} +{"title": "Suffixation of decimal numbers", "language": "cpython 3.7.3", "task": "'''Suffixation''': \u00a0 a letter or a group of letters added to the end of a word to change its meaning.\n::::::: \u00a0 \u00a0 \u00a0 \u2500\u2500\u2500\u2500\u2500 \u00a0 or, as used herein \u00a0 \u2500\u2500\u2500\u2500\u2500\n'''Suffixation''': \u00a0 the addition of a metric or \"binary\" metric suffix to a number, with/without rounding.\n\n\n;Task:\nWrite a function(s) to append (if possible) \u00a0 a metric \u00a0 or \u00a0 a \"binary\" metric \u00a0 suffix to a\nnumber \u00a0 (displayed in decimal).\n\nThe number may be rounded \u00a0 (as per user specification) \u00a0 (via shortening of the number when the number of\ndigits past the decimal point are to be used).\n\n\n;Task requirements:\n::* \u00a0 write a function (or functions) to add \u00a0 (if possible) \u00a0 a suffix to a number\n::* \u00a0 the function(s) should be able to express the number (possibly with a suffix) in as many decimal digits as specified\n::* \u00a0 the sign should be preserved \u00a0 (if present)\n::* \u00a0 the number may have commas within the number \u00a0 (the commas need not be preserved)\n::* \u00a0 the number may have a decimal point and/or an exponent as in: \u00a0 -123.7e-01\n::* \u00a0 the suffix that might be appended should be in uppercase; \u00a0 however, the \u00a0 '''i''' \u00a0 should be in lowercase\n::* \u00a0 support:\n::::* \u00a0 the\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 metric suffixes: \u00a0 '''K\u00a0 M\u00a0 G\u00a0 T\u00a0 P\u00a0 E\u00a0 Z\u00a0 Y\u00a0 X\u00a0 W\u00a0 V\u00a0 U'''\n::::* \u00a0 the binary metric suffixes: \u00a0 '''Ki Mi Gi Ti Pi Ei Zi Yi Xi Wi Vi Ui'''\n::::* \u00a0 the (full name) suffix: \u00a0 '''googol''' \u00a0 (lowercase) \u00a0 (equal to '''1e100''') \u00a0 \u00a0 (optional)\n::::* \u00a0 a number of decimal digits past the decimal point \u00a0 (with rounding). \u00a0 The default is to display all significant digits\n::* \u00a0 validation of the (supplied/specified) arguments is optional but recommended\n::* \u00a0 display \u00a0 (with identifying text):\n::::* \u00a0 the original number \u00a0 (with identifying text)\n::::* \u00a0 the number of digits past the decimal point being used \u00a0 (or none, if not specified)\n::::* \u00a0 the type of suffix being used \u00a0 (metric or \"binary\" metric)\n::::* \u00a0 the (new) number with the appropriate \u00a0 (if any) \u00a0 suffix\n::::* \u00a0 all output here on this page\n\n\n;Metric suffixes to be supported \u00a0 (whether or not they're officially sanctioned):\n '''K''' multiply the number by '''10^3''' kilo (1,000)\n '''M''' multiply the number by '''10^6''' mega (1,000,000)\n '''G''' multiply the number by '''10^9''' giga (1,000,000,000)\n '''T''' multiply the number by '''10^12''' tera (1,000,000,000,000)\n '''P''' multiply the number by '''10^15''' peta (1,000,000,000,000,000)\n '''E''' multiply the number by '''10^18''' exa (1,000,000,000,000,000,000)\n '''Z''' multiply the number by '''10^21''' zetta (1,000,000,000,000,000,000,000)\n '''Y''' multiply the number by '''10^24''' yotta (1,000,000,000,000,000,000,000,000)\n '''X''' multiply the number by '''10^27''' xenta (1,000,000,000,000,000,000,000,000,000)\n '''W''' multiply the number by '''10^30''' wekta (1,000,000,000,000,000,000,000,000,000,000)\n '''V''' multiply the number by '''10^33''' vendeka (1,000,000,000,000,000,000,000,000,000,000,000)\n '''U''' multiply the number by '''10^36''' udekta (1,000,000,000,000,000,000,000,000,000,000,000,000)\n\n\n;\"Binary\" suffixes to be supported \u00a0 (whether or not they're officially sanctioned):\n '''Ki''' multiply the number by '''2^10''' kibi (1,024)\n '''Mi''' multiply the number by '''2^20''' mebi (1,048,576)\n '''Gi''' multiply the number by '''2^30''' gibi (1,073,741,824)\n '''Ti''' multiply the number by '''2^40''' tebi (1,099,571,627,776)\n '''Pi''' multiply the number by '''2^50''' pebi (1,125,899,906,884,629)\n '''Ei''' multiply the number by '''2^60''' exbi (1,152,921,504,606,846,976)\n '''Zi''' multiply the number by '''2^70''' zebi (1,180,591,620,717,411,303,424)\n '''Yi''' multiply the number by '''2^80''' yobi (1,208,925,819,614,629,174,706,176)\n '''Xi''' multiply the number by '''2^90''' xebi (1,237,940,039,285,380,274,899,124,224)\n '''Wi''' multiply the number by '''2^100''' webi (1,267,650,600,228,229,401,496,703,205,376)\n '''Vi''' multiply the number by '''2^110''' vebi (1,298,074,214,633,706,907,132,624,082,305,024)\n '''Ui''' multiply the number by '''2^120''' uebi (1,329,227,995,784,915,872,903,807,060,280,344,576)\n\n\n;For instance, with this pseudo\u2500code:\n /* 1st arg: the number to be transformed.*/\n /* 2nd arg: # digits past the dec. point.*/\n /* 3rd arg: the type of suffix to use. */\n /* 2 indicates \"binary\" suffix.*/\n /* 10 indicates decimal suffix.*/\n a = '456,789,100,000,000' /* \"A\" has eight trailing zeros. */\n say ' aa=' suffize(a) /* Display a suffized number to terminal.*/\n /* The \"1\" below shows one decimal \u00b7\u00b7\u00b7*/\n /* digit past the decimal point. */\n n = suffize(a, 1) /* SUFFIZE is the function name. */\n n = suffize(a, 1, 10) /* (identical to the above statement.) */\n say ' n=' n /* Display value of N to terminal. */\n /* Note the rounding that occurs. */\n f = suffize(a, 1, 2) /* SUFFIZE with one fractional digit */\n say ' f=' f /* Display value of F to terminal. */\n /* Display value in \"binary\" metric. */\n bin = suffize(a, 5, 2) /* SUFFIZE with binary metric suffix. */\n say 'bin=' bin /* Display value of BIN to terminal. */\n win = suffize(a, 0, 2) /* SUFFIZE with binary metric suffix. */\n say 'win=' win /* Display value of WIN to terminal. */\n xvi = ' +16777216 ' /* this used to be a big computer \u00b7\u00b7\u00b7 */\n big = suffize(xvi, , 2) /* SUFFIZE with binary metric suffix. */\n say 'big=' big /* Display value of BIG to terminal. */\nwould display:\n aa= 456.7891T\n n= 456.8T\n f= 415.4Ti\n bin= 415.44727Ti\n win= 415Ti\n big= 16Mi\n\n\n;Use these test cases:\n 87,654,321\n -998,877,665,544,332,211,000 3\n +112,233 0\n 16,777,216 1\n 456,789,100,000,000 2\n 456,789,100,000,000 2 10\n 456,789,100,000,000 5 2\n 456,789,100,000.000e+00 0 10\n +16777216 , 2\n 1.2e101\n (your primary disk free space) 1 \u25c4\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0 optional\n\n\nUse whatever parameterizing your computer language supports, \u00a0 and it's permitted to create as many\nseparate functions as are needed \u00a0 (if needed) \u00a0 if \u00a0 function arguments aren't allowed to\nbe omitted or varied.\n\n\n", "solution": "\nimport math\nimport os\n\n\ndef suffize(num, digits=None, base=10):\n suffixes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'X', 'W', 'V', 'U', 'googol']\n\n exponent_distance = 10 if base == 2 else 3\n num = num.strip().replace(',', '')\n num_sign = num[0] if num[0] in '+-' else ''\n\n num = abs(float(num))\n\n if base == 10 and num >= 1e100:\n suffix_index = 13\n num /= 1e100\n elif num > 1:\n magnitude = math.floor(math.log(num, base))\n suffix_index = min(math.floor(magnitude / exponent_distance), 12)\n num /= base ** (exponent_distance * suffix_index)\n else:\n suffix_index = 0\n\n if digits is not None:\n num_str = f'{num:.{digits}f}'\n else:\n num_str = f'{num:.3f}'.strip('0').strip('.')\n\n return num_sign + num_str + suffixes[suffix_index] + ('i' if base == 2 else '')\n\n\ntests = [('87,654,321',),\n ('-998,877,665,544,332,211,000', 3),\n ('+112,233', 0),\n ('16,777,216', 1),\n ('456,789,100,000,000', 2),\n ('456,789,100,000,000', 2, 10),\n ('456,789,100,000,000', 5, 2),\n ('456,789,100,000.000e+00', 0, 10),\n ('+16777216', None, 2),\n ('1.2e101',)]\n\nfor test in tests:\n print(' '.join(str(i) for i in test) + ' : ' + suffize(*test))\n"} +{"title": "Sum and product puzzle", "language": "C", "task": "Solve the \"Impossible Puzzle\":\n\nX and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in this paragraph.\n\nThe following conversation occurs:\n\n* S says \"P does not know X and Y.\"\n* P says \"Now I know X and Y.\"\n* S says \"Now I also know X and Y!\"\n\nWhat are X and Y?\n}}\n\n\nIt can be hard to wrap one's head around what the three lines of dialog between S (the \"sum guy\") and P (the \"product guy\") convey about the values of X and Y.\nSo for your convenience, here's a break-down:\n\n{| class=\"wikitable\"\n|-\n! \n! Quote\n! Implied fact\n|-\n! 1) \n| S says \"P does not know X and Y.\"\n| For every possible sum decomposition of the number X+Y, the product has in turn ''more than one'' product decomposition.\n|-\n! 2)\n| P says \"Now I know X and Y.\"\n| The number X*Y has ''only one'' product decomposition for which fact 1 is true.\n|-\n! 3)\n| S says \"Now I also know X and Y.\"\n| The number X+Y has ''only one'' sum decomposition for which fact 2 is true.\n|}\n\nTerminology:\n* ''\"sum decomposition\" of a number'' = Any pair of positive integers (A, B) so that A+B equals the number. Here, with the additional constraint 2 \u2264 A < B.\n* ''\"product decomposition\" of a number'' = Any pair of positive integers (A, B) so that A*B equals the number. Here, with the additional constraint 2 \u2264 A < B.\n\n\nYour program can solve the puzzle by considering all possible pairs (X, Y) in the range 2 \u2264 X < Y \u2264 98, and then successively eliminating candidates based on the three facts. It turns out only one solution remains!\nSee the Python example for an implementation that uses this approach with a few optimizations.\n\n\n* \u00a0 Wikipedia: \u00a0 Sum and Product Puzzle\n\n", "solution": "#include \n#include \n#include \n\ntypedef struct node_t {\n int x, y;\n struct node_t *prev, *next;\n} node;\n\nnode *new_node(int x, int y) {\n node *n = malloc(sizeof(node));\n n->x = x;\n n->y = y;\n n->next = NULL;\n n->prev = NULL;\n return n;\n}\n\nvoid free_node(node **n) {\n if (n == NULL) {\n return;\n }\n\n (*n)->prev = NULL;\n (*n)->next = NULL;\n\n free(*n);\n\n *n = NULL;\n}\n\ntypedef struct list_t {\n node *head;\n node *tail;\n} list;\n\nlist make_list() {\n list lst = { NULL, NULL };\n return lst;\n}\n\nvoid append_node(list *const lst, int x, int y) {\n if (lst == NULL) {\n return;\n }\n\n node *n = new_node(x, y);\n\n if (lst->head == NULL) {\n lst->head = n;\n lst->tail = n;\n } else {\n n->prev = lst->tail;\n lst->tail->next = n;\n lst->tail = n;\n }\n}\n\nvoid remove_node(list *const lst, const node *const n) {\n if (lst == NULL || n == NULL) {\n return;\n }\n\n if (n->prev != NULL) {\n n->prev->next = n->next;\n if (n->next != NULL) {\n n->next->prev = n->prev;\n } else {\n lst->tail = n->prev;\n }\n } else {\n if (n->next != NULL) {\n n->next->prev = NULL;\n lst->head = n->next;\n }\n }\n\n free_node(&n);\n}\n\nvoid free_list(list *const lst) {\n node *ptr;\n\n if (lst == NULL) {\n return;\n }\n ptr = lst->head;\n\n while (ptr != NULL) {\n node *nxt = ptr->next;\n free_node(&ptr);\n ptr = nxt;\n }\n\n lst->head = NULL;\n lst->tail = NULL;\n}\n\nvoid print_list(const list *lst) {\n node *it;\n\n if (lst == NULL) {\n return;\n }\n\n for (it = lst->head; it != NULL; it = it->next) {\n int sum = it->x + it->y;\n int prod = it->x * it->y;\n printf(\"[%d, %d] S=%d P=%d\\n\", it->x, it->y, sum, prod);\n }\n}\n\nvoid print_count(const list *const lst) {\n node *it;\n int c = 0;\n\n if (lst == NULL) {\n return;\n }\n\n for (it = lst->head; it != NULL; it = it->next) {\n c++;\n }\n\n if (c == 0) {\n printf(\"no candidates\\n\");\n } else if (c == 1) {\n printf(\"one candidate\\n\");\n } else {\n printf(\"%d candidates\\n\", c);\n }\n}\n\nvoid setup(list *const lst) {\n int x, y;\n\n if (lst == NULL) {\n return;\n }\n\n // numbers must be greater than 1\n for (x = 2; x <= 98; x++) {\n // numbers must be unique, and sum no more than 100\n for (y = x + 1; y <= 98; y++) {\n if (x + y <= 100) {\n append_node(lst, x, y);\n }\n }\n }\n}\n\nvoid remove_by_sum(list *const lst, const int sum) {\n node *it;\n\n if (lst == NULL) {\n return;\n }\n\n it = lst->head;\n while (it != NULL) {\n int s = it->x + it->y;\n\n if (s == sum) {\n remove_node(lst, it);\n it = lst->head;\n } else {\n it = it->next;\n }\n }\n}\n\nvoid remove_by_prod(list *const lst, const int prod) {\n node *it;\n\n if (lst == NULL) {\n return;\n }\n\n it = lst->head;\n while (it != NULL) {\n int p = it->x * it->y;\n\n if (p == prod) {\n remove_node(lst, it);\n it = lst->head;\n } else {\n it = it->next;\n }\n }\n}\n\nvoid statement1(list *const lst) {\n short *unique = calloc(100000, sizeof(short));\n node *it, *nxt;\n\n for (it = lst->head; it != NULL; it = it->next) {\n int prod = it->x * it->y;\n unique[prod]++;\n }\n\n it = lst->head;\n while (it != NULL) {\n int prod = it->x * it->y;\n nxt = it->next;\n if (unique[prod] == 1) {\n remove_by_sum(lst, it->x + it->y);\n it = lst->head;\n } else {\n it = nxt;\n }\n }\n\n free(unique);\n}\n\nvoid statement2(list *const candidates) {\n short *unique = calloc(100000, sizeof(short));\n node *it, *nxt;\n\n for (it = candidates->head; it != NULL; it = it->next) {\n int prod = it->x * it->y;\n unique[prod]++;\n }\n\n it = candidates->head;\n while (it != NULL) {\n int prod = it->x * it->y;\n nxt = it->next;\n if (unique[prod] > 1) {\n remove_by_prod(candidates, prod);\n it = candidates->head;\n } else {\n it = nxt;\n }\n }\n\n free(unique);\n}\n\nvoid statement3(list *const candidates) {\n short *unique = calloc(100, sizeof(short));\n node *it, *nxt;\n\n for (it = candidates->head; it != NULL; it = it->next) {\n int sum = it->x + it->y;\n unique[sum]++;\n }\n\n it = candidates->head;\n while (it != NULL) {\n int sum = it->x + it->y;\n nxt = it->next;\n if (unique[sum] > 1) {\n remove_by_sum(candidates, sum);\n it = candidates->head;\n } else {\n it = nxt;\n }\n }\n\n free(unique);\n}\n\nint main() {\n list candidates = make_list();\n\n setup(&candidates);\n print_count(&candidates);\n\n statement1(&candidates);\n print_count(&candidates);\n\n statement2(&candidates);\n print_count(&candidates);\n\n statement3(&candidates);\n print_count(&candidates);\n\n print_list(&candidates);\n\n free_list(&candidates);\n return 0;\n}"} +{"title": "Sum and product puzzle", "language": "JavaScript", "task": "Solve the \"Impossible Puzzle\":\n\nX and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in this paragraph.\n\nThe following conversation occurs:\n\n* S says \"P does not know X and Y.\"\n* P says \"Now I know X and Y.\"\n* S says \"Now I also know X and Y!\"\n\nWhat are X and Y?\n}}\n\n\nIt can be hard to wrap one's head around what the three lines of dialog between S (the \"sum guy\") and P (the \"product guy\") convey about the values of X and Y.\nSo for your convenience, here's a break-down:\n\n{| class=\"wikitable\"\n|-\n! \n! Quote\n! Implied fact\n|-\n! 1) \n| S says \"P does not know X and Y.\"\n| For every possible sum decomposition of the number X+Y, the product has in turn ''more than one'' product decomposition.\n|-\n! 2)\n| P says \"Now I know X and Y.\"\n| The number X*Y has ''only one'' product decomposition for which fact 1 is true.\n|-\n! 3)\n| S says \"Now I also know X and Y.\"\n| The number X+Y has ''only one'' sum decomposition for which fact 2 is true.\n|}\n\nTerminology:\n* ''\"sum decomposition\" of a number'' = Any pair of positive integers (A, B) so that A+B equals the number. Here, with the additional constraint 2 \u2264 A < B.\n* ''\"product decomposition\" of a number'' = Any pair of positive integers (A, B) so that A*B equals the number. Here, with the additional constraint 2 \u2264 A < B.\n\n\nYour program can solve the puzzle by considering all possible pairs (X, Y) in the range 2 \u2264 X < Y \u2264 98, and then successively eliminating candidates based on the three facts. It turns out only one solution remains!\nSee the Python example for an implementation that uses this approach with a few optimizations.\n\n\n* \u00a0 Wikipedia: \u00a0 Sum and Product Puzzle\n\n", "solution": "(function () {\n 'use strict';\n\n // GENERIC FUNCTIONS\n\n // concatMap :: (a -> [b]) -> [a] -> [b]\n var concatMap = function concatMap(f, xs) {\n return [].concat.apply([], xs.map(f));\n },\n\n // curry :: ((a, b) -> c) -> a -> b -> c\n curry = function curry(f) {\n return function (a) {\n return function (b) {\n return f(a, b);\n };\n };\n },\n\n // intersectBy :: (a - > a - > Bool) - > [a] - > [a] - > [a]\n intersectBy = function intersectBy(eq, xs, ys) {\n return xs.length && ys.length ? xs.filter(function (x) {\n return ys.some(curry(eq)(x));\n }) : [];\n },\n\n // range :: Int -> Int -> Maybe Int -> [Int]\n range = function range(m, n, step) {\n var d = (step || 1) * (n >= m ? 1 : -1);\n return Array.from({\n length: Math.floor((n - m) / d) + 1\n }, function (_, i) {\n return m + i * d;\n });\n };\n\n // PROBLEM FUNCTIONS\n\n // add, mul :: (Int, Int) -> Int\n var add = function add(xy) {\n return xy[0] + xy[1];\n },\n mul = function mul(xy) {\n return xy[0] * xy[1];\n };\n\n // sumEq, mulEq :: (Int, Int) -> [(Int, Int)]\n var sumEq = function sumEq(p) {\n var addP = add(p);\n return s1.filter(function (q) {\n return add(q) === addP;\n });\n },\n mulEq = function mulEq(p) {\n var mulP = mul(p);\n return s1.filter(function (q) {\n return mul(q) === mulP;\n });\n };\n\n // pairEQ :: ((a, a) -> (a, a)) -> Bool\n var pairEQ = function pairEQ(a, b) {\n return a[0] === b[0] && a[1] === b[1];\n };\n\n // MAIN\n\n // xs :: [Int]\n var xs = range(1, 100);\n\n // s1 s2, s3, s4 :: [(Int, Int)]\n var s1 = concatMap(function (x) {\n return concatMap(function (y) {\n return 1 < x && x < y && x + y < 100 ? [\n [x, y]\n ] : [];\n }, xs);\n }, xs),\n\n s2 = s1.filter(function (p) {\n return sumEq(p).every(function (q) {\n return mulEq(q).length > 1;\n });\n }),\n\n s3 = s2.filter(function (p) {\n return intersectBy(pairEQ, mulEq(p), s2).length === 1;\n }),\n\n s4 = s3.filter(function (p) {\n return intersectBy(pairEQ, sumEq(p), s3).length === 1;\n });\n\n return s4;\n})();\n"} +{"title": "Sum and product puzzle", "language": "Python", "task": "Solve the \"Impossible Puzzle\":\n\nX and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in this paragraph.\n\nThe following conversation occurs:\n\n* S says \"P does not know X and Y.\"\n* P says \"Now I know X and Y.\"\n* S says \"Now I also know X and Y!\"\n\nWhat are X and Y?\n}}\n\n\nIt can be hard to wrap one's head around what the three lines of dialog between S (the \"sum guy\") and P (the \"product guy\") convey about the values of X and Y.\nSo for your convenience, here's a break-down:\n\n{| class=\"wikitable\"\n|-\n! \n! Quote\n! Implied fact\n|-\n! 1) \n| S says \"P does not know X and Y.\"\n| For every possible sum decomposition of the number X+Y, the product has in turn ''more than one'' product decomposition.\n|-\n! 2)\n| P says \"Now I know X and Y.\"\n| The number X*Y has ''only one'' product decomposition for which fact 1 is true.\n|-\n! 3)\n| S says \"Now I also know X and Y.\"\n| The number X+Y has ''only one'' sum decomposition for which fact 2 is true.\n|}\n\nTerminology:\n* ''\"sum decomposition\" of a number'' = Any pair of positive integers (A, B) so that A+B equals the number. Here, with the additional constraint 2 \u2264 A < B.\n* ''\"product decomposition\" of a number'' = Any pair of positive integers (A, B) so that A*B equals the number. Here, with the additional constraint 2 \u2264 A < B.\n\n\nYour program can solve the puzzle by considering all possible pairs (X, Y) in the range 2 \u2264 X < Y \u2264 98, and then successively eliminating candidates based on the three facts. It turns out only one solution remains!\nSee the Python example for an implementation that uses this approach with a few optimizations.\n\n\n* \u00a0 Wikipedia: \u00a0 Sum and Product Puzzle\n\n", "solution": "#!/usr/bin/env python\n\nfrom collections import Counter\n\ndef decompose_sum(s):\n return [(a,s-a) for a in range(2,int(s/2+1))]\n\n# Generate all possible pairs\nall_pairs = set((a,b) for a in range(2,100) for b in range(a+1,100) if a+b<100)\n\n# Fact 1 --> Select pairs for which all sum decompositions have non-unique product\nproduct_counts = Counter(c*d for c,d in all_pairs)\nunique_products = set((a,b) for a,b in all_pairs if product_counts[a*b]==1)\ns_pairs = [(a,b) for a,b in all_pairs if\n all((x,y) not in unique_products for (x,y) in decompose_sum(a+b))]\n\n# Fact 2 --> Select pairs for which the product is unique\nproduct_counts = Counter(c*d for c,d in s_pairs)\np_pairs = [(a,b) for a,b in s_pairs if product_counts[a*b]==1]\n\n# Fact 3 --> Select pairs for which the sum is unique\nsum_counts = Counter(c+d for c,d in p_pairs)\nfinal_pairs = [(a,b) for a,b in p_pairs if sum_counts[a+b]==1]\n\nprint(final_pairs)"} +{"title": "Sum digits of an integer", "language": "C", "task": ";Task:\nTake a \u00a0 Natural Number \u00a0 in a given base and return the sum of its digits:\n:* \u00a0 '''1'''10 \u00a0 \u00a0 \u00a0 \u00a0 sums to \u00a0 '''1'''\n:* \u00a0 '''1234'''10 \u00a0 sums to \u00a0 '''10'''\n:* \u00a0 '''fe'''16 \u00a0 \u00a0 \u00a0 sums to \u00a0 '''29'''\n:* \u00a0 '''f0e'''16 \u00a0 \u00a0 sums to \u00a0 '''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 digits of an integer", "language": "JavaScript", "task": ";Task:\nTake a \u00a0 Natural Number \u00a0 in a given base and return the sum of its digits:\n:* \u00a0 '''1'''10 \u00a0 \u00a0 \u00a0 \u00a0 sums to \u00a0 '''1'''\n:* \u00a0 '''1234'''10 \u00a0 sums to \u00a0 '''10'''\n:* \u00a0 '''fe'''16 \u00a0 \u00a0 \u00a0 sums to \u00a0 '''29'''\n:* \u00a0 '''f0e'''16 \u00a0 \u00a0 sums to \u00a0 '''29'''\n\n", "solution": "function sumDigits(n) {\n\tn += ''\n\tfor (var s=0, i=0, e=n.length; i')\n"} +{"title": "Sum digits of an integer", "language": "Python", "task": ";Task:\nTake a \u00a0 Natural Number \u00a0 in a given base and return the sum of its digits:\n:* \u00a0 '''1'''10 \u00a0 \u00a0 \u00a0 \u00a0 sums to \u00a0 '''1'''\n:* \u00a0 '''1234'''10 \u00a0 sums to \u00a0 '''10'''\n:* \u00a0 '''fe'''16 \u00a0 \u00a0 \u00a0 sums to \u00a0 '''29'''\n:* \u00a0 '''f0e'''16 \u00a0 \u00a0 sums to \u00a0 '''29'''\n\n", "solution": "def sumDigits(num, base=10):\n if base < 2:\n print(\"Error: base must be at least 2\")\n return\n num, sum = abs(num), 0\n while num >= base:\n num, rem = divmod(num, base)\n sum += rem\n return sum + num\n\nprint(sumDigits(1))\nprint(sumDigits(12345))\nprint(sumDigits(-123045))\nprint(sumDigits(0xfe, 16))\nprint(sumDigits(0xf0e, 16))"} +{"title": "Sum multiples of 3 and 5", "language": "C", "task": ";Task:\nThe 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 [https://projecteuler.net/problem=1 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 multiples of 3 and 5", "language": "JavaScript", "task": ";Task:\nThe 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 [https://projecteuler.net/problem=1 Project Euler problem 1].\n\n'''Extra credit:''' do this efficiently for ''n'' = 1e20 or higher.\n\n", "solution": "(function (lstFactors, intExponent) {\n\n // [n] -> n -> n\n function sumMultiplesBelow(lstIntegers, limit) {\n return range(1, limit - 1).filter(function (x) {\n return isMultiple(lstIntegers, x);\n }).reduce(function (a, n) {\n return a + n;\n }, 0)\n }\n\n // [n] -> n -> bool\n function isMultiple(lst, n) {\n var i = lng;\n while (i--)\n if (n % (lst[i]) === 0) return true;\n return false;\n }\n\n // [m..n]\n function range(m, n) {\n var a = Array(n - m + 1),\n i = n + 1;\n while (i--) a[i - 1] = i;\n return a;\n }\n\n\n /* TESTING */\n\n // [[a]] -> bool -> s -> s\n function wikiTable(lstRows, blnHeaderRow, strStyle) {\n return '{| class=\"wikitable\" ' + (\n strStyle ? 'style=\"' + strStyle + '\"' : ''\n ) + lstRows.map(function (lstRow, iRow) {\n var strDelim = ((blnHeaderRow && !iRow) ? '!' : '|');\n\n return '\\n|-\\n' + strDelim + ' ' + lstRow.map(function (v) {\n return typeof v === 'undefined' ? ' ' : v;\n }).join(' ' + strDelim + strDelim + ' ');\n }).join('') + '\\n|}';\n }\n\n var lng = lstFactors.length,\n lstSorted = lstFactors.slice(0).sort();\n\n var lstTable = [['Below', 'Sum']].concat(\n range(1, intExponent).map(function (x) {\n var pwr = Math.pow(10, x);\n\n return ['10^' + x, sumMultiplesBelow(lstSorted, pwr)];\n })\n );\n\n return 'For ' + JSON.stringify(lstFactors) + ':\\n\\n' +\n wikiTable(lstTable, true) + '\\n\\n' +\n JSON.stringify(lstTable);\n\n})([3, 5], 8);"} +{"title": "Sum multiples of 3 and 5", "language": "Python", "task": ";Task:\nThe 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 [https://projecteuler.net/problem=1 Project Euler problem 1].\n\n'''Extra credit:''' do this efficiently for ''n'' = 1e20 or higher.\n\n", "solution": "def sum35a(n):\n 'Direct count'\n # note: ranges go to n-1\n return sum(x for x in range(n) if x%3==0 or x%5==0)\n\ndef sum35b(n): \n \"Count all the 3's; all the 5's; minus double-counted 3*5's\"\n # note: ranges go to n-1\n return sum(range(3, n, 3)) + sum(range(5, n, 5)) - sum(range(15, n, 15))\n \ndef sum35c(n):\n 'Sum the arithmetic progressions: sum3 + sum5 - sum15'\n consts = (3, 5, 15)\n # Note: stop at n-1\n divs = [(n-1) // c for c in consts]\n sums = [d*c*(1+d)/2 for d,c in zip(divs, consts)]\n return sums[0] + sums[1] - sums[2]\n\n#test\nfor n in range(1001):\n sa, sb, sc = sum35a(n), sum35b(n), sum35c(n)\n assert sa == sb == sc # python tests aren't like those of c.\n\nprint('For n = %7i -> %i\\n' % (n, sc))\n\n# Pretty patterns\nfor p in range(7):\n print('For n = %7i -> %i' % (10**p, sum35c(10**p)))\n\n# Scalability \np = 20\nprint('\\nFor n = %20i -> %i' % (10**p, sum35c(10**p)))"} +{"title": "Sum of elements below main diagonal of matrix", "language": "C", "task": ";Task:\nFind 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::: \u2500\u2500\u2500 \u00a0 Matrix to be used: \u00a0 \u2500\u2500\u2500\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": "\n#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": "Sum of elements below main diagonal of matrix", "language": "JavaScript", "task": ";Task:\nFind 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::: \u2500\u2500\u2500 \u00a0 Matrix to be used: \u00a0 \u2500\u2500\u2500\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": "(() => {\n \"use strict\";\n\n // -------- LOWER TRIANGLE OF A SQUARE MATRIX --------\n\n // lowerTriangle :: [[a]] -> Either String [[a]]\n const lowerTriangle = matrix =>\n // Either a message, if the matrix is not square,\n // or the lower triangle of the matrix.\n isSquare(matrix) ? (\n Right(\n matrix.reduce(\n ([n, rows], xs) => [\n 1 + n,\n rows.concat([xs.slice(0, n)])\n ],\n [0, []]\n )[1]\n )\n ) : Left(\"Not a square matrix\");\n\n\n // isSquare :: [[a]] -> Bool\n const isSquare = rows => {\n // True if the length of every row in the matrix\n // matches the number of rows in the matrix.\n const n = rows.length;\n\n return rows.every(x => n === x.length);\n };\n\n // ---------------------- TEST -----------------------\n const main = () =>\n either(\n msg => `Lower triangle undefined :: ${msg}`\n )(\n rows => sum([].concat(...rows))\n )(\n lowerTriangle([\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 );\n\n // --------------------- GENERIC ---------------------\n\n // Left :: a -> Either a b\n const Left = x => ({\n type: \"Either\",\n Left: x\n });\n\n\n // Right :: b -> Either a b\n const Right = x => ({\n type: \"Either\",\n Right: x\n });\n\n\n // either :: (a -> c) -> (b -> c) -> Either a b -> c\n const either = fl =>\n // Application of the function fl to the\n // contents of any Left value in e, or\n // the application of fr to its Right value.\n fr => e => e.Left ? (\n fl(e.Left)\n ) : fr(e.Right);\n\n\n // sum :: [Num] -> Num\n const sum = xs =>\n // The numeric sum of all values in xs.\n xs.reduce((a, x) => a + x, 0);\n\n // MAIN ---\n return main();\n})();"} +{"title": "Sum of elements below main diagonal of matrix", "language": "Python", "task": ";Task:\nFind 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::: \u2500\u2500\u2500 \u00a0 Matrix to be used: \u00a0 \u2500\u2500\u2500\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": "'''Lower triangle of a matrix'''\n\nfrom itertools import chain, islice\nfrom functools import reduce\n\n\n# lowerTriangle :: [[a]] -> None | [[a]]\ndef lowerTriangle(matrix):\n '''Either None, if the matrix is not square, or\n the rows of the matrix, each containing only\n those values that form part of the lower triangle.\n '''\n def go(n_rows, xs):\n n, rows = n_rows\n return 1 + n, rows + [list(islice(xs, n))]\n\n return reduce(\n go,\n matrix,\n (0, [])\n )[1] if isSquare(matrix) else None\n\n\n# isSquare :: [[a]] -> Bool\ndef isSquare(matrix):\n '''True if all rows of the matrix share\n the length of the matrix itself.\n '''\n n = len(matrix)\n return all([n == len(x) for x in matrix])\n\n\n# ------------------------- TEST -------------------------\n# main :: IO ()\ndef main():\n '''Sum of integers in the lower triangle of a matrix.\n '''\n rows = lowerTriangle([\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\n print(\n \"Not a square matrix.\" if None is rows else (\n sum(chain(*rows))\n )\n )\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} +{"title": "Sum to 100", "language": "Microsoft Visual Studio 2015", "task": ";Task:\nFind solutions to the \u00a0 ''sum to one hundred'' \u00a0 puzzle.\n\n\nAdd (insert) the mathematical\noperators \u00a0 \u00a0 '''+''' \u00a0 or \u00a0 '''-''' \u00a0 \u00a0 (plus\nor minus) \u00a0 before any of the digits in the\ndecimal numeric string \u00a0 '''123456789''' \u00a0 such that the\nresulting mathematical expression adds up to a\nparticular sum \u00a0 (in this iconic case, \u00a0 '''100''').\n\n\nExample: \n 123 + 4 - 5 + 67 - 89 = 100 \n\nShow all output here.\n\n\n:* \u00a0 Show all solutions that sum to \u00a0 '''100''' \n:* \u00a0 Show the sum that has the maximum \u00a0 ''number'' \u00a0 of solutions \u00a0 (from zero to infinity\u2021)\n:* \u00a0 Show the lowest positive sum that \u00a0 ''can't'' \u00a0 be expressed \u00a0 (has no solutions), \u00a0 using the rules for this task\n:* \u00a0 Show the ten highest numbers that can be expressed using the rules for this task \u00a0 (extra credit)\n\n\u2021 \u00a0 (where \u00a0 ''infinity'' \u00a0 would be a relatively small \u00a0 123,456,789)\n\n\nAn example of a sum that can't be expressed \u00a0 (within the rules of this task) \u00a0 is: \u00a0 '''5074'''\n(which, \u00a0 of course, \u00a0 isn't the lowest positive sum that can't be expressed).\n\n", "solution": "/* \n * RossetaCode: Sum to 100, C99, an algorithm using ternary numbers.\n *\n * Find solutions to the \"sum to one hundred\" puzzle.\n */\n\n#include \n#include \n\n/*\n * There are only 13122 (i.e. 2*3**8) different possible expressions,\n * thus we can encode them as positive integer numbers from 0 to 13121.\n */\n#define NUMBER_OF_EXPRESSIONS (2 * 3*3*3*3 * 3*3*3*3 )\nenum OP { ADD, SUB, JOIN };\ntypedef int (*cmp)(const void*, const void*);\n\n// Replacing struct Expression and struct CountSum by a tuple like \n// struct Pair { int first; int last; } is possible but would make the source\n// code less readable.\n\nstruct Expression{ \n int sum;\n int code;\n}expressions[NUMBER_OF_EXPRESSIONS];\nint expressionsLength = 0;\nint compareExpressionBySum(const struct Expression* a, const struct Expression* b){\n return a->sum - b->sum;\n}\n\nstruct CountSum{ \n int counts; \n int sum; \n}countSums[NUMBER_OF_EXPRESSIONS];\nint countSumsLength = 0;\nint compareCountSumsByCount(const struct CountSum* a, const struct CountSum* b){\n return a->counts - b->counts;\n}\n\nint evaluate(int code){\n int value = 0, number = 0, power = 1;\n for ( int k = 9; k >= 1; k-- ){\n number = power*k + number;\n switch( code % 3 ){\n case ADD: value = value + number; number = 0; power = 1; break;\n case SUB: value = value - number; number = 0; power = 1; break;\n case JOIN: power = power * 10 ; break;\n }\n code /= 3;\n }\n return value; \n}\n\nvoid print(int code){\n static char s[19]; char* p = s;\n int a = 19683, b = 6561; \n for ( int k = 1; k <= 9; k++ ){\n switch((code % a) / b){\n case ADD: if ( k > 1 ) *p++ = '+'; break;\n case SUB: *p++ = '-'; break;\n }\n a = b;\n b = b / 3;\n *p++ = '0' + k;\n }\n *p = 0;\n printf(\"%9d = %s\\n\", evaluate(code), s);\n}\n\nvoid comment(char* string){\n printf(\"\\n\\n%s\\n\\n\", string);\n}\n\nvoid init(void){ \n for ( int i = 0; i < NUMBER_OF_EXPRESSIONS; i++ ){\n expressions[i].sum = evaluate(i);\n expressions[i].code = i;\n }\n expressionsLength = NUMBER_OF_EXPRESSIONS;\n qsort(expressions,expressionsLength,sizeof(struct Expression),(cmp)compareExpressionBySum);\n\n int j = 0;\n countSums[0].counts = 1;\n countSums[0].sum = expressions[0].sum;\n for ( int i = 0; i < expressionsLength; i++ ){\n if ( countSums[j].sum != expressions[i].sum ){\n j++;\n countSums[j].counts = 1;\n countSums[j].sum = expressions[i].sum;\n } \n else\n countSums[j].counts++;\n }\n countSumsLength = j + 1;\n qsort(countSums,countSumsLength,sizeof(struct CountSum),(cmp)compareCountSumsByCount);\n}\n\nint main(void){\n\n init();\n\n comment(\"Show all solutions that sum to 100\"); \n const int givenSum = 100;\n struct Expression ex = { givenSum, 0 };\n struct Expression* found;\n if ( found = bsearch(&ex,expressions,expressionsLength,\n sizeof(struct Expression),(cmp)compareExpressionBySum) ){\n while ( found != expressions && (found-1)->sum == givenSum )\n found--;\n while ( found != &expressions[expressionsLength] && found->sum == givenSum )\n print(found++->code);\n }\n\n comment(\"Show the positve sum that has the maximum number of solutions\");\n int maxSumIndex = countSumsLength - 1;\n while( countSums[maxSumIndex].sum < 0 )\n maxSumIndex--;\n printf(\"%d has %d solutions\\n\", \n countSums[maxSumIndex].sum, countSums[maxSumIndex].counts);\n\n comment(\"Show the lowest positive number that can't be expressed\");\n for ( int value = 0; ; value++ ){\n struct Expression ex = { value, 0 };\n if (!bsearch(&ex,expressions,expressionsLength,\n sizeof(struct Expression),(cmp)compareExpressionBySum)){\n printf(\"%d\\n\", value);\n break;\n }\n }\n\n comment(\"Show the ten highest numbers that can be expressed\");\n for ( int i = expressionsLength-1; i >= expressionsLength-10; i-- )\n print(expressions[i].code);\n \n return 0;\n}"} +{"title": "Sum to 100", "language": "JavaScript", "task": ";Task:\nFind solutions to the \u00a0 ''sum to one hundred'' \u00a0 puzzle.\n\n\nAdd (insert) the mathematical\noperators \u00a0 \u00a0 '''+''' \u00a0 or \u00a0 '''-''' \u00a0 \u00a0 (plus\nor minus) \u00a0 before any of the digits in the\ndecimal numeric string \u00a0 '''123456789''' \u00a0 such that the\nresulting mathematical expression adds up to a\nparticular sum \u00a0 (in this iconic case, \u00a0 '''100''').\n\n\nExample: \n 123 + 4 - 5 + 67 - 89 = 100 \n\nShow all output here.\n\n\n:* \u00a0 Show all solutions that sum to \u00a0 '''100''' \n:* \u00a0 Show the sum that has the maximum \u00a0 ''number'' \u00a0 of solutions \u00a0 (from zero to infinity\u2021)\n:* \u00a0 Show the lowest positive sum that \u00a0 ''can't'' \u00a0 be expressed \u00a0 (has no solutions), \u00a0 using the rules for this task\n:* \u00a0 Show the ten highest numbers that can be expressed using the rules for this task \u00a0 (extra credit)\n\n\u2021 \u00a0 (where \u00a0 ''infinity'' \u00a0 would be a relatively small \u00a0 123,456,789)\n\n\nAn example of a sum that can't be expressed \u00a0 (within the rules of this task) \u00a0 is: \u00a0 '''5074'''\n(which, \u00a0 of course, \u00a0 isn't the lowest positive sum that can't be expressed).\n\n", "solution": "(function () {\n 'use strict';\n\n // GENERIC FUNCTIONS ----------------------------------------------------\n\n // permutationsWithRepetition :: Int -> [a] -> [[a]]\n var permutationsWithRepetition = function (n, as) {\n return as.length > 0 ?\n foldl1(curry(cartesianProduct)(as), replicate(n, as)) : [];\n };\n\n // cartesianProduct :: [a] -> [b] -> [[a, b]]\n var cartesianProduct = function (xs, ys) {\n return [].concat.apply([], xs.map(function (x) {\n return [].concat.apply([], ys.map(function (y) {\n return [\n [x].concat(y)\n ];\n }));\n }));\n };\n\n // curry :: ((a, b) -> c) -> a -> b -> c\n var curry = function (f) {\n return function (a) {\n return function (b) {\n return f(a, b);\n };\n };\n };\n\n // flip :: (a -> b -> c) -> b -> a -> c\n var flip = function (f) {\n return function (a, b) {\n return f.apply(null, [b, a]);\n };\n };\n\n // foldl1 :: (a -> a -> a) -> [a] -> a\n var foldl1 = function (f, xs) {\n return xs.length > 0 ? xs.slice(1)\n .reduce(f, xs[0]) : [];\n };\n\n // replicate :: Int -> a -> [a]\n var replicate = function (n, a) {\n var v = [a],\n o = [];\n if (n < 1) return o;\n while (n > 1) {\n if (n & 1) o = o.concat(v);\n n >>= 1;\n v = v.concat(v);\n }\n return o.concat(v);\n };\n\n // group :: Eq a => [a] -> [[a]]\n var group = function (xs) {\n return groupBy(function (a, b) {\n return a === b;\n }, xs);\n };\n\n // groupBy :: (a -> a -> Bool) -> [a] -> [[a]]\n var groupBy = function (f, xs) {\n var dct = xs.slice(1)\n .reduce(function (a, x) {\n var h = a.active.length > 0 ? a.active[0] : undefined,\n blnGroup = h !== undefined && f(h, x);\n\n return {\n active: blnGroup ? a.active.concat(x) : [x],\n sofar: blnGroup ? a.sofar : a.sofar.concat([a.active])\n };\n }, {\n active: xs.length > 0 ? [xs[0]] : [],\n sofar: []\n });\n return dct.sofar.concat(dct.active.length > 0 ? [dct.active] : []);\n };\n\n // compare :: a -> a -> Ordering\n var compare = function (a, b) {\n return a < b ? -1 : a > b ? 1 : 0;\n };\n\n // on :: (b -> b -> c) -> (a -> b) -> a -> a -> c\n var on = function (f, g) {\n return function (a, b) {\n return f(g(a), g(b));\n };\n };\n\n // nub :: [a] -> [a]\n var nub = function (xs) {\n return nubBy(function (a, b) {\n return a === b;\n }, xs);\n };\n\n // nubBy :: (a -> a -> Bool) -> [a] -> [a]\n var nubBy = function (p, xs) {\n var x = xs.length ? xs[0] : undefined;\n\n return x !== undefined ? [x].concat(nubBy(p, xs.slice(1)\n .filter(function (y) {\n return !p(x, y);\n }))) : [];\n };\n\n // find :: (a -> Bool) -> [a] -> Maybe a\n var find = function (f, xs) {\n for (var i = 0, lng = xs.length; i < lng; i++) {\n if (f(xs[i], i)) return xs[i];\n }\n return undefined;\n };\n\n // Int -> [a] -> [a]\n var take = function (n, xs) {\n return xs.slice(0, n);\n };\n\n // unlines :: [String] -> String\n var unlines = function (xs) {\n return xs.join('\\n');\n };\n\n // show :: a -> String\n var show = function (x) {\n return JSON.stringify(x);\n }; //, null, 2);\n\n // head :: [a] -> a\n var head = function (xs) {\n return xs.length ? xs[0] : undefined;\n };\n\n // tail :: [a] -> [a]\n var tail = function (xs) {\n return xs.length ? xs.slice(1) : undefined;\n };\n\n // length :: [a] -> Int\n var length = function (xs) {\n return xs.length;\n };\n\n // SIGNED DIGIT SEQUENCES (mapped to sums and to strings)\n\n // data Sign :: [ 0 | 1 | -1 ] = ( Unsigned | Plus | Minus )\n // asSum :: [Sign] -> Int\n var asSum = function (xs) {\n var dct = xs.reduceRight(function (a, sign, i) {\n var d = i + 1; // zero-based index to [1-9] positions\n if (sign !== 0) {\n // Sum increased, digits cleared\n return {\n digits: [],\n n: a.n + sign * parseInt([d].concat(a.digits)\n .join(''), 10)\n };\n } else return { // Digits extended, sum unchanged\n digits: [d].concat(a.digits),\n n: a.n\n };\n }, {\n digits: [],\n n: 0\n });\n return dct.n + (\n dct.digits.length > 0 ? parseInt(dct.digits.join(''), 10) : 0\n );\n };\n\n // data Sign :: [ 0 | 1 | -1 ] = ( Unsigned | Plus | Minus )\n // asString :: [Sign] -> String\n var asString = function (xs) {\n var ns = xs.reduce(function (a, sign, i) {\n var d = (i + 1)\n .toString();\n return sign === 0 ? a + d : a + (sign > 0 ? ' +' : ' -') + d;\n }, '');\n\n return ns[0] === '+' ? tail(ns) : ns;\n };\n\n // SUM T0 100 ------------------------------------------------------------\n\n // universe :: [[Sign]]\n var universe = permutationsWithRepetition(9, [0, 1, -1])\n .filter(function (x) {\n return x[0] !== 1;\n });\n\n // allNonNegativeSums :: [Int]\n var allNonNegativeSums = universe.map(asSum)\n .filter(function (x) {\n return x >= 0;\n })\n .sort();\n\n // uniqueNonNegativeSums :: [Int]\n var uniqueNonNegativeSums = nub(allNonNegativeSums);\n\n return [\"Sums to 100:\\n\", unlines(universe.filter(function (x) {\n return asSum(x) === 100;\n })\n .map(asString)),\n\n \"\\n\\n10 commonest sums (sum, followed by number of routes to it):\\n\",\n show(take(10, group(allNonNegativeSums)\n .sort(on(flip(compare), length))\n .map(function (xs) {\n return [xs[0], xs.length];\n }))),\n\n \"\\n\\nFirst positive integer not expressible as a sum of this kind:\\n\",\n show(find(function (x, i) {\n return x !== i;\n }, uniqueNonNegativeSums.sort(compare)) - 1), // zero-based index\n\n \"\\n10 largest sums:\\n\",\n show(take(10, uniqueNonNegativeSums.sort(flip(compare))))\n ].join('\\n') + '\\n';\n})();"} +{"title": "Sum to 100", "language": "Python", "task": ";Task:\nFind solutions to the \u00a0 ''sum to one hundred'' \u00a0 puzzle.\n\n\nAdd (insert) the mathematical\noperators \u00a0 \u00a0 '''+''' \u00a0 or \u00a0 '''-''' \u00a0 \u00a0 (plus\nor minus) \u00a0 before any of the digits in the\ndecimal numeric string \u00a0 '''123456789''' \u00a0 such that the\nresulting mathematical expression adds up to a\nparticular sum \u00a0 (in this iconic case, \u00a0 '''100''').\n\n\nExample: \n 123 + 4 - 5 + 67 - 89 = 100 \n\nShow all output here.\n\n\n:* \u00a0 Show all solutions that sum to \u00a0 '''100''' \n:* \u00a0 Show the sum that has the maximum \u00a0 ''number'' \u00a0 of solutions \u00a0 (from zero to infinity\u2021)\n:* \u00a0 Show the lowest positive sum that \u00a0 ''can't'' \u00a0 be expressed \u00a0 (has no solutions), \u00a0 using the rules for this task\n:* \u00a0 Show the ten highest numbers that can be expressed using the rules for this task \u00a0 (extra credit)\n\n\u2021 \u00a0 (where \u00a0 ''infinity'' \u00a0 would be a relatively small \u00a0 123,456,789)\n\n\nAn example of a sum that can't be expressed \u00a0 (within the rules of this task) \u00a0 is: \u00a0 '''5074'''\n(which, \u00a0 of course, \u00a0 isn't the lowest positive sum that can't be expressed).\n\n", "solution": "from itertools import product, islice\n\n\ndef expr(p):\n return \"{}1{}2{}3{}4{}5{}6{}7{}8{}9\".format(*p)\n\n\ndef gen_expr():\n op = ['+', '-', '']\n return [expr(p) for p in product(op, repeat=9) if p[0] != '+']\n\n\ndef all_exprs():\n values = {}\n for expr in gen_expr():\n val = eval(expr)\n if val not in values:\n values[val] = 1\n else:\n values[val] += 1\n return values\n\n\ndef sum_to(val):\n for s in filter(lambda x: x[0] == val, map(lambda x: (eval(x), x), gen_expr())):\n print(s)\n\n\ndef max_solve():\n print(\"Sum {} has the maximum number of solutions: {}\".\n format(*max(all_exprs().items(), key=lambda x: x[1])))\n\n\ndef min_solve():\n values = all_exprs()\n for i in range(123456789):\n if i not in values:\n print(\"Lowest positive sum that can't be expressed: {}\".format(i))\n return\n\n\ndef highest_sums(n=10):\n sums = map(lambda x: x[0],\n islice(sorted(all_exprs().items(), key=lambda x: x[0], reverse=True), n))\n print(\"Highest Sums: {}\".format(list(sums)))\n\n\nsum_to(100)\nmax_solve()\nmin_solve()\nhighest_sums()"} +{"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* \u00a0 [[Fours is the number of letters in the ...]]\n* \u00a0 [[Look-and-say sequence]]\n* \u00a0 [[Number names]]\n* \u00a0 [[Self-describing numbers]]\n* \u00a0 [[Spelling of ordinal numbers]]\n\n\n\n\n\n;Also see:\n* \u00a0 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": "Summarize and say sequence", "language": "Python", "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* \u00a0 [[Fours is the number of letters in the ...]]\n* \u00a0 [[Look-and-say sequence]]\n* \u00a0 [[Number names]]\n* \u00a0 [[Self-describing numbers]]\n* \u00a0 [[Spelling of ordinal numbers]]\n\n\n\n\n\n;Also see:\n* \u00a0 The On-Line Encyclopedia of Integer Sequences.\n\n", "solution": "from itertools import groupby, permutations\n\ndef A036058(number):\n return ''.join( str(len(list(g))) + k\n for k,g in groupby(sorted(str(number), reverse=True)) )\n\ndef A036058_length(numberstring='0', printit=False):\n iterations, last_three, queue_index = 1, ([None] * 3), 0\n\n def A036058(number):\n # rely on external reverse-sort of digits of number\n return ''.join( str(len(list(g))) + k\n for k,g in groupby(number) )\n\n while True:\n if printit:\n print(\" %2i %s\" % (iterations, numberstring))\n numberstring = ''.join(sorted(numberstring, reverse=True))\n if numberstring in last_three:\n break\n assert iterations < 1000000\n last_three[queue_index], numberstring = numberstring, A036058(numberstring)\n iterations += 1\n queue_index +=1\n queue_index %=3\n return iterations\n \ndef max_A036058_length( start_range=range(11) ):\n already_done = set()\n max_len = (-1, [])\n for n in start_range:\n sn = str(n)\n sns = tuple(sorted(sn, reverse=True))\n if sns not in already_done:\n already_done.add(sns)\n size = A036058_length(sns)\n if size > max_len[0]:\n max_len = (size, [n])\n elif size == max_len[0]:\n max_len[1].append(n)\n return max_len\n\nlenmax, starts = max_A036058_length( range(1000000) )\n\n# Expand\nallstarts = []\nfor n in starts:\n allstarts += [int(''.join(x))\n for x in set(k\n for k in permutations(str(n), 4)\n if k[0] != '0')]\nallstarts = [x for x in sorted(allstarts) if x < 1000000]\n\nprint ( '''\\\nThe longest length, followed by the number(s) with the longest sequence length\nfor starting sequence numbers below 1000000 are:\n Iterations = %i and sequence-starts = %s.''' % (lenmax, allstarts) )\n\nprint ( '''\nNote that only the first of any sequences with the same digits is printed below.\n(The others will differ only in their first term)''' )\n\nfor n in starts:\n print()\n A036058_length(str(n), printit=True)"} +{"title": "Super-d numbers", "language": "C", "task": "A super-d number is a positive, decimal (base ten) integer \u00a0 '''n''' \u00a0 such that \u00a0 '''d \u00d7 nd''' \u00a0 has at least \u00a0 '''d''' \u00a0 consecutive digits \u00a0 '''d''' \u00a0 where\n 2 \u2264 d \u2264 9\nFor instance, 753 is a super-3 number because 3 \u00d7 7533 = 1280873331.\n\n\n'''Super-d''' \u00a0 numbers are also shown on \u00a0 '''MathWorld'''\u2122 \u00a0 as \u00a0 '''super-''d'' ''' \u00a0 or \u00a0 '''super-''d'''''.\n\n\n;Task:\n:* Write a function/procedure/routine to find super-d numbers.\n:* For \u00a0 '''d=2''' \u00a0 through \u00a0 '''d=6''', \u00a0 use the routine to show the first \u00a0 '''10''' \u00a0 super-d numbers.\n\n\n;Extra credit:\n:* Show the first \u00a0 '''10''' \u00a0 super-7, super-8, and/or super-9 numbers \u00a0 (optional).\n\n\n;See also:\n:* \u00a0 [http://mathworld.wolfram.com/Super-dNumber.html Wolfram MathWorld - Super-d Number].\n:* \u00a0 [http://oeis.org/A014569 OEIS: A014569 - Super-3 Numbers].\n\n", "solution": "#include \n#include \n#include \n#include \n\nint main() {\n for (unsigned int d = 2; d <= 9; ++d) {\n printf(\"First 10 super-%u numbers:\\n\", d);\n char digits[16] = { 0 };\n memset(digits, '0' + d, d);\n mpz_t bignum;\n mpz_init(bignum);\n for (unsigned int count = 0, n = 1; count < 10; ++n) {\n mpz_ui_pow_ui(bignum, n, d);\n mpz_mul_ui(bignum, bignum, d);\n char* str = mpz_get_str(NULL, 10, bignum);\n if (strstr(str, digits)) {\n printf(\"%u \", n);\n ++count;\n }\n free(str);\n }\n mpz_clear(bignum);\n printf(\"\\n\");\n }\n return 0;\n}"} +{"title": "Super-d numbers", "language": "Python", "task": "A super-d number is a positive, decimal (base ten) integer \u00a0 '''n''' \u00a0 such that \u00a0 '''d \u00d7 nd''' \u00a0 has at least \u00a0 '''d''' \u00a0 consecutive digits \u00a0 '''d''' \u00a0 where\n 2 \u2264 d \u2264 9\nFor instance, 753 is a super-3 number because 3 \u00d7 7533 = 1280873331.\n\n\n'''Super-d''' \u00a0 numbers are also shown on \u00a0 '''MathWorld'''\u2122 \u00a0 as \u00a0 '''super-''d'' ''' \u00a0 or \u00a0 '''super-''d'''''.\n\n\n;Task:\n:* Write a function/procedure/routine to find super-d numbers.\n:* For \u00a0 '''d=2''' \u00a0 through \u00a0 '''d=6''', \u00a0 use the routine to show the first \u00a0 '''10''' \u00a0 super-d numbers.\n\n\n;Extra credit:\n:* Show the first \u00a0 '''10''' \u00a0 super-7, super-8, and/or super-9 numbers \u00a0 (optional).\n\n\n;See also:\n:* \u00a0 [http://mathworld.wolfram.com/Super-dNumber.html Wolfram MathWorld - Super-d Number].\n:* \u00a0 [http://oeis.org/A014569 OEIS: A014569 - Super-3 Numbers].\n\n", "solution": "from itertools import islice, count\n\ndef superd(d):\n if d != int(d) or not 2 <= d <= 9:\n raise ValueError(\"argument must be integer from 2 to 9 inclusive\")\n tofind = str(d) * d\n for n in count(2):\n if tofind in str(d * n ** d):\n yield n\n\nif __name__ == '__main__':\n for d in range(2, 9):\n print(f\"{d}:\", ', '.join(str(n) for n in islice(superd(d), 10)))"} +{"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": "\n#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"} +{"title": "Superellipse", "language": "JavaScript", "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": "\nvar n = 2.5, a = 200, b = 200, ctx;\n\nfunction point( x, y ) {\n ctx.fillRect( x, y, 1, 1);\n}\n\nfunction start() {\n var can = document.createElement('canvas');\n can.width = can.height = 600;\n ctx = can.getContext( \"2d\" );\n ctx.rect( 0, 0, can.width, can.height );\n ctx.fillStyle = \"#000000\"; ctx.fill();\n document.body.appendChild( can );\n\n ctx.fillStyle = \"#ffffff\";\n for( var t = 0; t < 1000; t += .1 ) {\n x = Math.pow( Math.abs( Math.cos( t ) ), 2 / n ) * a * Math.sign( Math.cos( t ) );\n y = Math.pow( Math.abs( Math.sin( t ) ), 2 / n ) * b * Math.sign( Math.sin( t ) );\n\n point( x + ( can.width >> 1 ), y + ( can.height >> 1 ) );\n }\n}\n"} +{"title": "Superellipse", "language": "Python", "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": "\n# Superellipse drawing in Python 2.7.9\n# pic can see at http://www.imgup.cz/image/712\n\nimport matplotlib.pyplot as plt\nfrom math import sin, cos, pi\n\ndef sgn(x):\n\treturn ((x>0)-(x<0))*1\n\na,b,n=200,200,2.5 # param n making shape\nna=2/n\nstep=100 # accuracy\npiece=(pi*2)/step\nxp=[];yp=[]\n\nt=0\nfor t1 in range(step+1):\n\t# because sin^n(x) is mathematically the same as (sin(x))^n...\n\tx=(abs((cos(t)))**na)*a*sgn(cos(t))\n\ty=(abs((sin(t)))**na)*b*sgn(sin(t))\n\txp.append(x);yp.append(y)\n\tt+=piece\n\nplt.plot(xp,yp) # plotting all point from array xp, yp\nplt.title(\"Superellipse with parameter \"+str(n))\nplt.show()\n"} +{"title": "Superpermutation minimisation", "language": "C", "task": "A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.\n\nFor example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'. \nThe permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'.\n\nA too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'.\n\nA little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end.\n\nThe \"too obvious\" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations.\n\nShow descriptions and comparisons of algorithms used here, and select the \"Best\" algorithm as being the one generating shorter superpermutations.\n\nThe problem of generating the shortest superpermutation for each N ''might'' be NP complete, although the minimal strings for small values of N have been found by brute -force searches.\n\n\n\n\n;Reference:\n* [http://www.njohnston.ca/2013/04/the-minimal-superpermutation-problem/ The Minimal Superpermutation Problem]. by Nathaniel Johnston.\n* [http://oeis.org/A180632 oeis A180632] gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872.\n* [https://www.youtube.com/watch?v=wJGE4aEWc28 Superpermutations - Numberphile]. A video\n* [https://www.youtube.com/watch?v=OZzIvl1tbPo Superpermutations: the maths problem solved by 4chan - Standupmaths]. A video of recent (2018) mathematical progress.\n* [https://www.youtube.com/watch?v=_tpNuulTeSQ New Superpermutations Discovered!] Standupmaths & Numberphile.\n\n", "solution": "#include \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": "Superpermutation minimisation", "language": "Python", "task": "A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.\n\nFor example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'. \nThe permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'.\n\nA too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'.\n\nA little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end.\n\nThe \"too obvious\" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations.\n\nShow descriptions and comparisons of algorithms used here, and select the \"Best\" algorithm as being the one generating shorter superpermutations.\n\nThe problem of generating the shortest superpermutation for each N ''might'' be NP complete, although the minimal strings for small values of N have been found by brute -force searches.\n\n\n\n\n;Reference:\n* [http://www.njohnston.ca/2013/04/the-minimal-superpermutation-problem/ The Minimal Superpermutation Problem]. by Nathaniel Johnston.\n* [http://oeis.org/A180632 oeis A180632] gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872.\n* [https://www.youtube.com/watch?v=wJGE4aEWc28 Superpermutations - Numberphile]. A video\n* [https://www.youtube.com/watch?v=OZzIvl1tbPo Superpermutations: the maths problem solved by 4chan - Standupmaths]. A video of recent (2018) mathematical progress.\n* [https://www.youtube.com/watch?v=_tpNuulTeSQ New Superpermutations Discovered!] Standupmaths & Numberphile.\n\n", "solution": "\"Generate a short Superpermutation of n characters A... as a string using various algorithms.\"\n\n\nfrom __future__ import print_function, division\n\nfrom itertools import permutations\nfrom math import factorial\nimport string\nimport datetime\nimport gc\n\n\n\nMAXN = 7\n\n\ndef s_perm0(n):\n \"\"\"\n Uses greedy algorithm of adding another char (or two, or three, ...)\n until an unseen perm is formed in the last n chars\n \"\"\"\n allchars = string.ascii_uppercase[:n]\n allperms = [''.join(p) for p in permutations(allchars)]\n sp, tofind = allperms[0], set(allperms[1:])\n while tofind:\n for skip in range(1, n):\n for trial_add in (''.join(p) for p in permutations(sp[-n:][:skip])):\n #print(sp, skip, trial_add)\n trial_perm = (sp + trial_add)[-n:]\n if trial_perm in tofind:\n #print(sp, skip, trial_add)\n sp += trial_add\n tofind.discard(trial_perm)\n trial_add = None # Sentinel\n break\n if trial_add is None:\n break\n assert all(perm in sp for perm in allperms) # Check it is a superpermutation\n return sp\n\ndef s_perm1(n):\n \"\"\"\n Uses algorithm of concatenating all perms in order if not already part\n of concatenation.\n \"\"\"\n allchars = string.ascii_uppercase[:n]\n allperms = [''.join(p) for p in sorted(permutations(allchars))]\n perms, sp = allperms[::], ''\n while perms:\n nxt = perms.pop()\n if nxt not in sp:\n sp += nxt\n assert all(perm in sp for perm in allperms)\n return sp\n\ndef s_perm2(n):\n \"\"\"\n Uses algorithm of concatenating all perms in order first-last-nextfirst-\n nextlast... if not already part of concatenation.\n \"\"\"\n allchars = string.ascii_uppercase[:n]\n allperms = [''.join(p) for p in sorted(permutations(allchars))]\n perms, sp = allperms[::], ''\n while perms:\n nxt = perms.pop(0)\n if nxt not in sp:\n sp += nxt\n if perms:\n nxt = perms.pop(-1)\n if nxt not in sp:\n sp += nxt\n assert all(perm in sp for perm in allperms)\n return sp\n\ndef _s_perm3(n, cmp):\n \"\"\"\n Uses algorithm of concatenating all perms in order first,\n next_with_LEASTorMOST_chars_in_same_position_as_last_n_chars, ...\n \"\"\"\n allchars = string.ascii_uppercase[:n]\n allperms = [''.join(p) for p in sorted(permutations(allchars))]\n perms, sp = allperms[::], ''\n while perms:\n lastn = sp[-n:]\n nxt = cmp(perms,\n key=lambda pm:\n sum((ch1 == ch2) for ch1, ch2 in zip(pm, lastn)))\n perms.remove(nxt)\n if nxt not in sp:\n sp += nxt\n assert all(perm in sp for perm in allperms)\n return sp\n\ndef s_perm3_max(n):\n \"\"\"\n Uses algorithm of concatenating all perms in order first,\n next_with_MOST_chars_in_same_position_as_last_n_chars, ...\n \"\"\"\n return _s_perm3(n, max)\n\ndef s_perm3_min(n):\n \"\"\"\n Uses algorithm of concatenating all perms in order first,\n next_with_LEAST_chars_in_same_position_as_last_n_chars, ...\n \"\"\"\n return _s_perm3(n, min)\n\n\nlongest = [factorial(n) * n for n in range(MAXN + 1)]\nweight, runtime = {}, {}\nprint(__doc__)\nfor algo in [s_perm0, s_perm1, s_perm2, s_perm3_max, s_perm3_min]:\n print('\\n###\\n### %s\\n###' % algo.__name__)\n print(algo.__doc__)\n weight[algo.__name__], runtime[algo.__name__] = 1, datetime.timedelta(0)\n for n in range(1, MAXN + 1):\n gc.collect()\n gc.disable()\n t = datetime.datetime.now()\n sp = algo(n)\n t = datetime.datetime.now() - t\n gc.enable()\n runtime[algo.__name__] += t\n lensp = len(sp)\n wt = (lensp / longest[n]) ** 2\n print(' For N=%i: SP length %5i Max: %5i Weight: %5.2f'\n % (n, lensp, longest[n], wt))\n weight[algo.__name__] *= wt\n weight[algo.__name__] **= 1 / n # Geometric mean\n weight[algo.__name__] = 1 / weight[algo.__name__]\n print('%*s Overall Weight: %5.2f in %.1f seconds.'\n % (29, '', weight[algo.__name__], runtime[algo.__name__].total_seconds()))\n\nprint('\\n###\\n### Algorithms ordered by shortest superpermutations first\\n###')\nprint('\\n'.join('%12s (%.3f)' % kv for kv in\n sorted(weight.items(), key=lambda keyvalue: -keyvalue[1])))\n \nprint('\\n###\\n### Algorithms ordered by shortest runtime first\\n###')\nprint('\\n'.join('%12s (%.3f)' % (k, v.total_seconds()) for k, v in\n sorted(runtime.items(), key=lambda keyvalue: keyvalue[1])))\n"} +{"title": "Sylvester's sequence", "language": "Python", "task": "In number theory, '''Sylvester's sequence''' is an integer sequence in which each term of the sequence is the product of the previous terms, plus one.\n\nIts values grow doubly exponentially, and the sum of its reciprocals forms a series of unit fractions that converges to '''1''' more rapidly than any other series of unit fractions with the same number of terms. \n\nFurther, the sum of the first '''k''' terms of the infinite series of reciprocals provides the closest possible underestimate of '''1''' by any k-term Egyptian fraction.\n\n\n;Task:\n* Write a routine (function, procedure, generator, whatever) to calculate '''Sylvester's sequence'''.\n* Use that routine to show the values of the first '''10''' elements in the sequence.\n* Show the sum of the reciprocals of the first '''10''' elements on the sequence, ideally as an exact fraction.\n\n\n;Related tasks:\n* [[Egyptian fractions]]\n* [[Harmonic series]]\n\n\n;See also: \n* OEIS A000058 - Sylvester's sequence\n\n", "solution": "'''Sylvester's sequence'''\n\nfrom functools import reduce\nfrom itertools import count, islice\n\n\n# sylvester :: [Int]\ndef sylvester():\n '''Non-finite stream of the terms\n of Sylvester's sequence.\n (OEIS A000058)\n '''\n def go(n):\n return 1 + reduce(\n lambda a, x: a * go(x),\n range(0, n),\n 1\n ) if 0 != n else 2\n\n return map(go, count(0))\n\n\n# ------------------------- TEST -------------------------\n# main :: IO ()\ndef main():\n '''First terms, and sum of reciprocals.'''\n\n print(\"First 10 terms of OEIS A000058:\")\n xs = list(islice(sylvester(), 10))\n print('\\n'.join([\n str(x) for x in xs\n ]))\n\n print(\"\\nSum of the reciprocals of the first 10 terms:\")\n print(\n reduce(lambda a, x: a + 1 / x, xs, 0)\n )\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} +{"title": "Tarjan", "language": "Python", "task": "[[Category:Algorithm]]\n\n\nTarjan's algorithm is an algorithm in graph theory for finding the strongly connected components of a graph. \n\nIt runs in linear time, matching the time bound for alternative methods including Kosaraju's algorithm and the path-based strong component algorithm. \n\nTarjan's Algorithm is named for its discoverer, Robert Tarjan.\n\n\n;References:\n* The article on Wikipedia.\n\nSee also: [[Kosaraju]]\n\n", "solution": "from collections import defaultdict\n\ndef from_edges(edges):\n '''translate list of edges to list of nodes'''\n\n class Node:\n def __init__(self):\n # root is one of:\n # None: not yet visited\n # -1: already processed\n # non-negative integer: what Wikipedia pseudo code calls 'lowlink'\n self.root = None\n self.succ = []\n\n nodes = defaultdict(Node)\n for v,w in edges:\n nodes[v].succ.append(nodes[w])\n\n for i,v in nodes.items(): # name the nodes for final output\n v.id = i\n\n return nodes.values()\n\ndef trajan(V):\n def strongconnect(v, S):\n v.root = pos = len(S)\n S.append(v)\n\n for w in v.succ:\n if w.root is None: # not yet visited\n yield from strongconnect(w, S)\n\n if w.root >= 0: # still on stack\n v.root = min(v.root, w.root)\n\n if v.root == pos: # v is the root, return everything above\n res, S[pos:] = S[pos:], []\n for w in res:\n w.root = -1\n yield [r.id for r in res]\n\n for v in V:\n if v.root is None:\n yield from strongconnect(v, [])\n\n\ntables = [ # table 1\n [(1,2), (3,1), (3,6), (6,7), (7,6), (2,3), (4,2),\n (4,3), (4,5), (5,6), (5,4), (8,5), (8,7), (8,6)],\n\n # table 2\n [('A', 'B'), ('B', 'C'), ('C', 'A'), ('A', 'Other')]]\n\nfor table in (tables):\n for g in trajan(from_edges(table)):\n print(g)\n print()"} +{"title": "Tau function", "language": "C", "task": "[[Category:Mathematics]]\n\nGiven a positive integer, count the number of its positive divisors.\n\n\n;Task\nShow the result for the first \u00a0 '''100''' \u00a0 positive integers.\n\n\n;Related task\n* \u00a0[[Tau number]]\n\n", "solution": "#include \n\n// See https://en.wikipedia.org/wiki/Divisor_function\nunsigned int divisor_count(unsigned int n) {\n unsigned int total = 1;\n // Deal with powers of 2 first\n for (; (n & 1) == 0; n >>= 1) {\n ++total;\n }\n // Odd prime factors up to the square root\n for (unsigned int p = 3; p * p <= n; p += 2) {\n unsigned int count = 1;\n for (; n % p == 0; n /= p) {\n ++count;\n }\n total *= count;\n }\n // If n > 1 then it's prime\n if (n > 1) {\n total *= 2;\n }\n return total;\n}\n\nint main() {\n const unsigned int limit = 100;\n unsigned int n;\n\n printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n for (n = 1; n <= limit; ++n) {\n printf(\"%3d\", divisor_count(n));\n if (n % 20 == 0) {\n printf(\"\\n\");\n }\n }\n\n return 0;\n}"} +{"title": "Tau function", "language": "Python", "task": "[[Category:Mathematics]]\n\nGiven a positive integer, count the number of its positive divisors.\n\n\n;Task\nShow the result for the first \u00a0 '''100''' \u00a0 positive integers.\n\n\n;Related task\n* \u00a0[[Tau number]]\n\n", "solution": "def factorize(n):\n assert(isinstance(n, int))\n if n < 0: \n n = -n \n if n < 2: \n return \n k = 0 \n while 0 == n%2: \n k += 1 \n n //= 2 \n if 0 < k: \n yield (2,k) \n p = 3 \n while p*p <= n: \n k = 0 \n while 0 == n%p: \n k += 1 \n n //= p \n if 0 < k: \n yield (p,k)\n p += 2 \n if 1 < n: \n yield (n,1) \n\ndef tau(n): \n assert(n != 0) \n ans = 1 \n for (p,k) in factorize(n): \n ans *= 1 + k\n return ans\n\nif __name__ == \"__main__\":\n print(*map(tau, range(1, 101)))"} +{"title": "Teacup rim text", "language": "C", "task": "On a set of coasters we have, there's a picture of a teacup. \u00a0 On the rim of the teacup the word \u00a0 '''TEA''' \u00a0 appears a number of times separated by bullet characters \u00a0 (\u2022). \n\nIt occurred to me that if the bullet were removed and the words run together, \u00a0 you could start at any letter and still end up with a meaningful three-letter word. \n\nSo start at the \u00a0 '''T''' \u00a0 and read \u00a0 '''TEA'''. \u00a0 Start at the \u00a0 '''E''' \u00a0 and read \u00a0 '''EAT''', \u00a0 or start at the \u00a0 '''A''' \u00a0 and read \u00a0 '''ATE'''.\n\nThat got me thinking that maybe there are other words that could be used rather that \u00a0 '''TEA'''. \u00a0 And that's just English. \u00a0 What about Italian or Greek or ... um ... Telugu. \n\nFor English, we will use the unixdict (now) located at: \u00a0 [http://wiki.puzzlers.org/pub/wordlists/unixdict.txt unixdict.txt]. \n\n(This will maintain continuity with other Rosetta Code tasks that also use it.)\n\n\n;Task:\nSearch for a set of words that could be printed around the edge of a teacup. \u00a0 The words in each set are to be of the same length, that length being greater than two (thus precluding \u00a0 '''AH''' \u00a0 and \u00a0 '''HA''', \u00a0 for example.) \n\nHaving listed a set, for example \u00a0 ['''ate tea eat'''], \u00a0 refrain from displaying permutations of that set, e.g.: \u00a0 ['''eat tea ate'''] \u00a0 etc. \n\nThe words should also be made of more than one letter \u00a0 (thus precluding \u00a0 '''III''' \u00a0 and \u00a0 '''OOO''' \u00a0 etc.) \n\nThe relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second. \u00a0 The first letter of the second becomes the last letter of the third. \u00a0 So \u00a0 '''ATE''' \u00a0 becomes \u00a0 '''TEA''' \u00a0 and \u00a0 '''TEA''' \u00a0 becomes \u00a0 '''EAT'''. \n\nAll of the possible permutations, using this particular permutation technique, must be words in the list. \n\nThe set you generate for \u00a0 '''ATE''' \u00a0 will never included the word \u00a0 '''ETA''' \u00a0 as that cannot be reached via the first-to-last movement method. \n\nDisplay one line for each set of teacup rim words.\n\n\n\n", "solution": "#include \n#include \n#include \n#include \n\nint string_compare(gconstpointer p1, gconstpointer p2) {\n const char* const* s1 = p1;\n const char* const* s2 = p2;\n return strcmp(*s1, *s2);\n}\n\nGPtrArray* load_dictionary(const char* file, GError** error_ptr) {\n GError* error = NULL;\n GIOChannel* channel = g_io_channel_new_file(file, \"r\", &error);\n if (channel == NULL) {\n g_propagate_error(error_ptr, error);\n return NULL;\n }\n GPtrArray* dict = g_ptr_array_new_full(1024, g_free);\n GString* line = g_string_sized_new(64);\n gsize term_pos;\n while (g_io_channel_read_line_string(channel, line, &term_pos,\n &error) == G_IO_STATUS_NORMAL) {\n char* word = g_strdup(line->str);\n word[term_pos] = '\\0';\n g_ptr_array_add(dict, word);\n }\n g_string_free(line, TRUE);\n g_io_channel_unref(channel);\n if (error != NULL) {\n g_propagate_error(error_ptr, error);\n g_ptr_array_free(dict, TRUE);\n return NULL;\n }\n g_ptr_array_sort(dict, string_compare);\n return dict;\n}\n\nvoid rotate(char* str, size_t len) {\n char c = str[0];\n memmove(str, str + 1, len - 1);\n str[len - 1] = c;\n}\n\nchar* dictionary_search(const GPtrArray* dictionary, const char* word) {\n char** result = bsearch(&word, dictionary->pdata, dictionary->len,\n sizeof(char*), string_compare);\n return result != NULL ? *result : NULL;\n}\n\nvoid find_teacup_words(GPtrArray* dictionary) {\n GHashTable* found = g_hash_table_new(g_str_hash, g_str_equal);\n GPtrArray* teacup_words = g_ptr_array_new();\n GString* temp = g_string_sized_new(8);\n for (size_t i = 0, n = dictionary->len; i < n; ++i) {\n char* word = g_ptr_array_index(dictionary, i);\n size_t len = strlen(word);\n if (len < 3 || g_hash_table_contains(found, word))\n continue;\n g_ptr_array_set_size(teacup_words, 0);\n g_string_assign(temp, word);\n bool is_teacup_word = true;\n for (size_t i = 0; i < len - 1; ++i) {\n rotate(temp->str, len);\n char* w = dictionary_search(dictionary, temp->str);\n if (w == NULL) {\n is_teacup_word = false;\n break;\n }\n if (strcmp(word, w) != 0 && !g_ptr_array_find(teacup_words, w, NULL))\n g_ptr_array_add(teacup_words, w);\n }\n if (is_teacup_word && teacup_words->len > 0) {\n printf(\"%s\", word);\n g_hash_table_add(found, word);\n for (size_t i = 0; i < teacup_words->len; ++i) {\n char* teacup_word = g_ptr_array_index(teacup_words, i);\n printf(\" %s\", teacup_word);\n g_hash_table_add(found, teacup_word);\n }\n printf(\"\\n\");\n }\n }\n g_string_free(temp, TRUE);\n g_ptr_array_free(teacup_words, TRUE);\n g_hash_table_destroy(found);\n}\n\nint main(int argc, char** argv) {\n if (argc != 2) {\n fprintf(stderr, \"usage: %s dictionary\\n\", argv[0]);\n return EXIT_FAILURE;\n }\n GError* error = NULL;\n GPtrArray* dictionary = load_dictionary(argv[1], &error);\n if (dictionary == NULL) {\n if (error != NULL) {\n fprintf(stderr, \"Cannot load dictionary file '%s': %s\\n\",\n argv[1], error->message);\n g_error_free(error);\n }\n return EXIT_FAILURE;\n }\n find_teacup_words(dictionary);\n g_ptr_array_free(dictionary, TRUE);\n return EXIT_SUCCESS;\n}"} +{"title": "Teacup rim text", "language": "JavaScript", "task": "On a set of coasters we have, there's a picture of a teacup. \u00a0 On the rim of the teacup the word \u00a0 '''TEA''' \u00a0 appears a number of times separated by bullet characters \u00a0 (\u2022). \n\nIt occurred to me that if the bullet were removed and the words run together, \u00a0 you could start at any letter and still end up with a meaningful three-letter word. \n\nSo start at the \u00a0 '''T''' \u00a0 and read \u00a0 '''TEA'''. \u00a0 Start at the \u00a0 '''E''' \u00a0 and read \u00a0 '''EAT''', \u00a0 or start at the \u00a0 '''A''' \u00a0 and read \u00a0 '''ATE'''.\n\nThat got me thinking that maybe there are other words that could be used rather that \u00a0 '''TEA'''. \u00a0 And that's just English. \u00a0 What about Italian or Greek or ... um ... Telugu. \n\nFor English, we will use the unixdict (now) located at: \u00a0 [http://wiki.puzzlers.org/pub/wordlists/unixdict.txt unixdict.txt]. \n\n(This will maintain continuity with other Rosetta Code tasks that also use it.)\n\n\n;Task:\nSearch for a set of words that could be printed around the edge of a teacup. \u00a0 The words in each set are to be of the same length, that length being greater than two (thus precluding \u00a0 '''AH''' \u00a0 and \u00a0 '''HA''', \u00a0 for example.) \n\nHaving listed a set, for example \u00a0 ['''ate tea eat'''], \u00a0 refrain from displaying permutations of that set, e.g.: \u00a0 ['''eat tea ate'''] \u00a0 etc. \n\nThe words should also be made of more than one letter \u00a0 (thus precluding \u00a0 '''III''' \u00a0 and \u00a0 '''OOO''' \u00a0 etc.) \n\nThe relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second. \u00a0 The first letter of the second becomes the last letter of the third. \u00a0 So \u00a0 '''ATE''' \u00a0 becomes \u00a0 '''TEA''' \u00a0 and \u00a0 '''TEA''' \u00a0 becomes \u00a0 '''EAT'''. \n\nAll of the possible permutations, using this particular permutation technique, must be words in the list. \n\nThe set you generate for \u00a0 '''ATE''' \u00a0 will never included the word \u00a0 '''ETA''' \u00a0 as that cannot be reached via the first-to-last movement method. \n\nDisplay one line for each set of teacup rim words.\n\n\n\n", "solution": "===Set() objects===\nReading a local dictionary with the macOS JS for Automation library:\n"} +{"title": "Teacup rim text", "language": "JXA", "task": "On a set of coasters we have, there's a picture of a teacup. \u00a0 On the rim of the teacup the word \u00a0 '''TEA''' \u00a0 appears a number of times separated by bullet characters \u00a0 (\u2022). \n\nIt occurred to me that if the bullet were removed and the words run together, \u00a0 you could start at any letter and still end up with a meaningful three-letter word. \n\nSo start at the \u00a0 '''T''' \u00a0 and read \u00a0 '''TEA'''. \u00a0 Start at the \u00a0 '''E''' \u00a0 and read \u00a0 '''EAT''', \u00a0 or start at the \u00a0 '''A''' \u00a0 and read \u00a0 '''ATE'''.\n\nThat got me thinking that maybe there are other words that could be used rather that \u00a0 '''TEA'''. \u00a0 And that's just English. \u00a0 What about Italian or Greek or ... um ... Telugu. \n\nFor English, we will use the unixdict (now) located at: \u00a0 [http://wiki.puzzlers.org/pub/wordlists/unixdict.txt unixdict.txt]. \n\n(This will maintain continuity with other Rosetta Code tasks that also use it.)\n\n\n;Task:\nSearch for a set of words that could be printed around the edge of a teacup. \u00a0 The words in each set are to be of the same length, that length being greater than two (thus precluding \u00a0 '''AH''' \u00a0 and \u00a0 '''HA''', \u00a0 for example.) \n\nHaving listed a set, for example \u00a0 ['''ate tea eat'''], \u00a0 refrain from displaying permutations of that set, e.g.: \u00a0 ['''eat tea ate'''] \u00a0 etc. \n\nThe words should also be made of more than one letter \u00a0 (thus precluding \u00a0 '''III''' \u00a0 and \u00a0 '''OOO''' \u00a0 etc.) \n\nThe relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second. \u00a0 The first letter of the second becomes the last letter of the third. \u00a0 So \u00a0 '''ATE''' \u00a0 becomes \u00a0 '''TEA''' \u00a0 and \u00a0 '''TEA''' \u00a0 becomes \u00a0 '''EAT'''. \n\nAll of the possible permutations, using this particular permutation technique, must be words in the list. \n\nThe set you generate for \u00a0 '''ATE''' \u00a0 will never included the word \u00a0 '''ETA''' \u00a0 as that cannot be reached via the first-to-last movement method. \n\nDisplay one line for each set of teacup rim words.\n\n\n\n", "solution": "(() => {\n 'use strict';\n\n // main :: IO ()\n const main = () =>\n showGroups(\n circularWords(\n // Local copy of:\n // https://www.mit.edu/~ecprice/wordlist.10000\n lines(readFile('~/mitWords.txt'))\n )\n );\n\n // circularWords :: [String] -> [String]\n const circularWords = ws =>\n ws.filter(isCircular(new Set(ws)), ws);\n\n // isCircular :: Set String -> String -> Bool\n const isCircular = lexicon => w => {\n const iLast = w.length - 1;\n return 1 < iLast && until(\n ([i, bln, s]) => iLast < i || !bln,\n ([i, bln, s]) => [1 + i, lexicon.has(s), rotated(s)],\n [0, true, rotated(w)]\n )[1];\n };\n\n // DISPLAY --------------------------------------------\n\n // showGroups :: [String] -> String\n const showGroups = xs =>\n unlines(map(\n gp => map(snd, gp).join(' -> '),\n groupBy(\n (a, b) => fst(a) === fst(b),\n sortBy(\n comparing(fst),\n map(x => Tuple(concat(sort(chars(x))), x),\n xs\n )\n )\n ).filter(gp => 1 < gp.length)\n ));\n\n\n // MAC OS JS FOR AUTOMATION ---------------------------\n\n // readFile :: FilePath -> IO String\n const readFile = fp => {\n const\n e = $(),\n uw = ObjC.unwrap,\n s = uw(\n $.NSString.stringWithContentsOfFileEncodingError(\n $(fp)\n .stringByStandardizingPath,\n $.NSUTF8StringEncoding,\n e\n )\n );\n return undefined !== s ? (\n s\n ) : uw(e.localizedDescription);\n };\n\n // GENERIC FUNCTIONS ----------------------------------\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = (a, b) => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // chars :: String -> [Char]\n const chars = s => s.split('');\n\n // comparing :: (a -> b) -> (a -> a -> Ordering)\n const comparing = f =>\n (x, y) => {\n const\n a = f(x),\n b = f(y);\n return a < b ? -1 : (a > b ? 1 : 0);\n };\n\n // concat :: [[a]] -> [a]\n // concat :: [String] -> String\n const concat = xs =>\n 0 < xs.length ? (() => {\n const unit = 'string' !== typeof xs[0] ? (\n []\n ) : '';\n return unit.concat.apply(unit, xs);\n })() : [];\n\n // fst :: (a, b) -> a\n const fst = tpl => tpl[0];\n\n // groupBy :: (a -> a -> Bool) -> [a] -> [[a]]\n const groupBy = (f, xs) => {\n const tpl = xs.slice(1)\n .reduce((a, x) => {\n const h = a[1].length > 0 ? a[1][0] : undefined;\n return (undefined !== h) && f(h, x) ? (\n Tuple(a[0], a[1].concat([x]))\n ) : Tuple(a[0].concat([a[1]]), [x]);\n }, Tuple([], 0 < xs.length ? [xs[0]] : []));\n return tpl[0].concat([tpl[1]]);\n };\n\n // lines :: String -> [String]\n const lines = s => s.split(/[\\r\\n]/);\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) =>\n (Array.isArray(xs) ? (\n xs\n ) : xs.split('')).map(f);\n\n // rotated :: String -> String\n const rotated = xs =>\n xs.slice(1) + xs[0];\n\n // showLog :: a -> IO ()\n const showLog = (...args) =>\n console.log(\n args\n .map(JSON.stringify)\n .join(' -> ')\n );\n\n // snd :: (a, b) -> b\n const snd = tpl => tpl[1];\n\n // sort :: Ord a => [a] -> [a]\n const sort = xs => xs.slice()\n .sort((a, b) => a < b ? -1 : (a > b ? 1 : 0));\n\n // sortBy :: (a -> a -> Ordering) -> [a] -> [a]\n const sortBy = (f, xs) =>\n xs.slice()\n .sort(f);\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // until :: (a -> Bool) -> (a -> a) -> a -> a\n const until = (p, f, x) => {\n let v = x;\n while (!p(v)) v = f(v);\n return v;\n };\n\n // MAIN ---\n return main();\n})();"} +{"title": "Teacup rim text", "language": "Python", "task": "On a set of coasters we have, there's a picture of a teacup. \u00a0 On the rim of the teacup the word \u00a0 '''TEA''' \u00a0 appears a number of times separated by bullet characters \u00a0 (\u2022). \n\nIt occurred to me that if the bullet were removed and the words run together, \u00a0 you could start at any letter and still end up with a meaningful three-letter word. \n\nSo start at the \u00a0 '''T''' \u00a0 and read \u00a0 '''TEA'''. \u00a0 Start at the \u00a0 '''E''' \u00a0 and read \u00a0 '''EAT''', \u00a0 or start at the \u00a0 '''A''' \u00a0 and read \u00a0 '''ATE'''.\n\nThat got me thinking that maybe there are other words that could be used rather that \u00a0 '''TEA'''. \u00a0 And that's just English. \u00a0 What about Italian or Greek or ... um ... Telugu. \n\nFor English, we will use the unixdict (now) located at: \u00a0 [http://wiki.puzzlers.org/pub/wordlists/unixdict.txt unixdict.txt]. \n\n(This will maintain continuity with other Rosetta Code tasks that also use it.)\n\n\n;Task:\nSearch for a set of words that could be printed around the edge of a teacup. \u00a0 The words in each set are to be of the same length, that length being greater than two (thus precluding \u00a0 '''AH''' \u00a0 and \u00a0 '''HA''', \u00a0 for example.) \n\nHaving listed a set, for example \u00a0 ['''ate tea eat'''], \u00a0 refrain from displaying permutations of that set, e.g.: \u00a0 ['''eat tea ate'''] \u00a0 etc. \n\nThe words should also be made of more than one letter \u00a0 (thus precluding \u00a0 '''III''' \u00a0 and \u00a0 '''OOO''' \u00a0 etc.) \n\nThe relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second. \u00a0 The first letter of the second becomes the last letter of the third. \u00a0 So \u00a0 '''ATE''' \u00a0 becomes \u00a0 '''TEA''' \u00a0 and \u00a0 '''TEA''' \u00a0 becomes \u00a0 '''EAT'''. \n\nAll of the possible permutations, using this particular permutation technique, must be words in the list. \n\nThe set you generate for \u00a0 '''ATE''' \u00a0 will never included the word \u00a0 '''ETA''' \u00a0 as that cannot be reached via the first-to-last movement method. \n\nDisplay one line for each set of teacup rim words.\n\n\n\n", "solution": "'''Teacup rim text'''\n\nfrom itertools import chain, groupby\nfrom os.path import expanduser\nfrom functools import reduce\n\n\n# main :: IO ()\ndef main():\n '''Circular anagram groups, of more than one word,\n and containing words of length > 2, found in:\n https://www.mit.edu/~ecprice/wordlist.10000\n '''\n print('\\n'.join(\n concatMap(circularGroup)(\n anagrams(3)(\n # Reading from a local copy.\n lines(readFile('~/mitWords.txt'))\n )\n )\n ))\n\n\n# anagrams :: Int -> [String] -> [[String]]\ndef anagrams(n):\n '''Groups of anagrams, of minimum group size n,\n found in the given word list.\n '''\n def go(ws):\n def f(xs):\n return [\n [snd(x) for x in xs]\n ] if n <= len(xs) >= len(xs[0][0]) else []\n return concatMap(f)(groupBy(fst)(sorted(\n [(''.join(sorted(w)), w) for w in ws],\n key=fst\n )))\n return go\n\n\n# circularGroup :: [String] -> [String]\ndef circularGroup(ws):\n '''Either an empty list, or a list containing\n a string showing any circular subset found in ws.\n '''\n lex = set(ws)\n iLast = len(ws) - 1\n # If the set contains one word that is circular,\n # then it must contain all of them.\n (i, blnCircular) = until(\n lambda tpl: tpl[1] or (tpl[0] > iLast)\n )(\n lambda tpl: (1 + tpl[0], isCircular(lex)(ws[tpl[0]]))\n )(\n (0, False)\n )\n return [' -> '.join(allRotations(ws[i]))] if blnCircular else []\n\n\n# isCircular :: Set String -> String -> Bool\ndef isCircular(lexicon):\n '''True if all of a word's rotations\n are found in the given lexicon.\n '''\n def go(w):\n def f(tpl):\n (i, _, x) = tpl\n return (1 + i, x in lexicon, rotated(x))\n\n iLast = len(w) - 1\n return until(\n lambda tpl: iLast < tpl[0] or (not tpl[1])\n )(f)(\n (0, True, rotated(w))\n )[1]\n return go\n\n\n# allRotations :: String -> [String]\ndef allRotations(w):\n '''All rotations of the string w.'''\n return takeIterate(len(w) - 1)(\n rotated\n )(w)\n\n\n# GENERIC -------------------------------------------------\n\n# concatMap :: (a -> [b]) -> [a] -> [b]\ndef concatMap(f):\n '''A concatenated list over which a function has been mapped.\n The list monad can be derived by using a function f which\n wraps its output in a list,\n (using an empty list to represent computational failure).\n '''\n def go(xs):\n return chain.from_iterable(map(f, xs))\n return go\n\n\n# fst :: (a, b) -> a\ndef fst(tpl):\n '''First member of a pair.'''\n return tpl[0]\n\n\n# groupBy :: (a -> b) -> [a] -> [[a]]\ndef groupBy(f):\n '''The elements of xs grouped,\n preserving order, by equality\n in terms of the key function f.\n '''\n def go(xs):\n return [\n list(x[1]) for x in groupby(xs, key=f)\n ]\n return go\n\n\n# lines :: String -> [String]\ndef lines(s):\n '''A list of strings,\n (containing no newline characters)\n derived from a single new-line delimited string.\n '''\n return s.splitlines()\n\n\n# mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])\ndef mapAccumL(f):\n '''A tuple of an accumulation and a list derived by a\n combined map and fold,\n with accumulation from left to right.\n '''\n def go(a, x):\n tpl = f(a[0], x)\n return (tpl[0], a[1] + [tpl[1]])\n return lambda acc: lambda xs: (\n reduce(go, xs, (acc, []))\n )\n\n\n# readFile :: FilePath -> IO String\ndef readFile(fp):\n '''The contents of any file at the path\n derived by expanding any ~ in fp.\n '''\n with open(expanduser(fp), 'r', encoding='utf-8') as f:\n return f.read()\n\n\n# rotated :: String -> String\ndef rotated(s):\n '''A string rotated 1 character to the right.'''\n return s[1:] + s[0]\n\n\n# snd :: (a, b) -> b\ndef snd(tpl):\n '''Second member of a pair.'''\n return tpl[1]\n\n\n# takeIterate :: Int -> (a -> a) -> a -> [a]\ndef takeIterate(n):\n '''Each value of n iterations of f\n over a start value of x.\n '''\n def go(f):\n def g(x):\n def h(a, i):\n v = f(a) if i else x\n return (v, v)\n return mapAccumL(h)(x)(\n range(0, 1 + n)\n )[1]\n return g\n return go\n\n\n# until :: (a -> Bool) -> (a -> a) -> a -> a\ndef until(p):\n '''The result of repeatedly applying f until p holds.\n The initial seed value is x.\n '''\n def go(f):\n def g(x):\n v = x\n while not p(v):\n v = f(v)\n return v\n return g\n return go\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} +{"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": "Temperature conversion", "language": "JavaScript", "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": "var k2c = k => k - 273.15\nvar k2r = k => k * 1.8\nvar k2f = k => k2r(k) - 459.67\n\nNumber.prototype.toMaxDecimal = function (d) {\n return +this.toFixed(d) + ''\n}\n\nfunction kCnv(k) {\n document.write( k,'K\u00b0 = ', k2c(k).toMaxDecimal(2),'C\u00b0 = ', k2r(k).toMaxDecimal(2),'R\u00b0 = ', k2f(k).toMaxDecimal(2),'F\u00b0' ) \n}\n \nkCnv(21)\nkCnv(295)"} +{"title": "Temperature conversion", "language": "Python", "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": ">>> toK = {'C': (lambda c: c + 273.15),\n 'F': (lambda f: (f + 459.67) / 1.8),\n 'R': (lambda r: r / 1.8),\n 'K': (lambda k: k) }\n>>> while True:\n magnitude, unit = input(' ? ').split()\n k = toK[unit](float(magnitude))\n print(\"%g Kelvin = %g Celsius = %g Fahrenheit = %g Rankine degrees.\"\n % (k, k - 273.15, k * 1.8 - 459.67, k * 1.8))\n\n \n ? 222.2 K\n222.2 Kelvin = -50.95 Celsius = -59.71 Fahrenheit = 399.96 Rankine degrees.\n ? -50.95 C\n222.2 Kelvin = -50.95 Celsius = -59.71 Fahrenheit = 399.96 Rankine degrees.\n ? -59.71 F\n222.2 Kelvin = -50.95 Celsius = -59.71 Fahrenheit = 399.96 Rankine degrees.\n ? 399.96 R\n222.2 Kelvin = -50.95 Celsius = -59.71 Fahrenheit = 399.96 Rankine degrees.\n ? "} +{"title": "Terminal control/Coloured text", "language": "C", "task": "[[Category:Terminal control]]\n\n;Task:\nDisplay 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/Coloured text", "language": "Python", "task": "[[Category:Terminal control]]\n\n;Task:\nDisplay 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": "\nfrom colorama import init, Fore, Back, Style\ninit(autoreset=True)\n\nprint Fore.RED + \"FATAL ERROR! Cannot write to /boot/vmlinuz-3.2.0-33-generic\"\nprint Back.BLUE + Fore.YELLOW + \"What a cute console!\"\nprint \"This is an %simportant%s word\" % (Style.BRIGHT, Style.NORMAL)\nprint Fore.YELLOW + \"Rosetta Code!\"\nprint Fore.CYAN + \"Rosetta Code!\"\nprint Fore.GREEN + \"Rosetta Code!\"\nprint Fore.MAGENTA + \"Rosetta Code!\"\nprint Back.YELLOW + Fore.BLUE + Style.BRIGHT + \" \" * 40 + \" == Good Bye!\"\n"} +{"title": "Terminal control/Unicode output", "language": "C", "task": "[[Category:Terminal control]]\n[[Category:Unicode]]\nThe 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": "\n#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": "Terminal control/Unicode output", "language": "Python", "task": "[[Category:Terminal control]]\n[[Category:Unicode]]\nThe 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": "import sys\n\nif \"UTF-8\" in sys.stdout.encoding:\n print(\"\u25b3\")\nelse:\n raise Exception(\"Terminal can't handle UTF-8\")"} +{"title": "Test integerness", "language": "C", "task": "Mathematically,\n* the rational numbers '''Q''',\n* which are included in the real numbers '''R''',\n* which can be generalized to the complex numbers '''C'''.\n\n\nThis means that each of those larger sets, and the data types used to represent them, include some integers.\n\n\nGiven a rational, real, or complex number of any type, test whether it is mathematically an integer.\n\nYour code should handle all numeric data types commonly used in your programming language.\n\nDiscuss any limitations of your code.\n\n\nFor the purposes of this task, integerness means that a number could theoretically be represented as an integer at no loss of precision ''(given an infinitely wide integer type)''.\nIn other words:\n\n{| class=\"wikitable\"\n|-\n! Set\n! Common representation\n! C++ type\n! Considered an integer...\n|-\n| rational numbers '''Q'''\n| fraction\n| std::ratio\n| ...if its denominator is 1 (in reduced form)\n|-\n| rowspan=2 | real numbers '''Z'''''(approximated)''\n| fixed-point\n| \n| ...if it has no non-zero digits after the decimal point\n|-\n| floating-point\n| float, double\n| ...if the number of significant decimal places of its mantissa isn't greater than its exponent\n|-\n| complex numbers '''C'''\n| pair of real numbers\n| std::complex\n| ...if its real part is considered an integer and its imaginary part is zero\n|}\n\n\nOptionally, make your code accept a tolerance parameter for fuzzy testing. The tolerance is the maximum amount by which the number may differ from the nearest integer, to still be considered an integer.\n\nThis is useful in practice, because when dealing with approximate numeric types (such as floating point), there may already be round-off errors from previous calculations. For example, a float value of 0.9999999998 might actually be intended to represent the integer 1.\n\n\n{| 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 \u2013 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": "\n#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": "Test integerness", "language": "Python", "task": "Mathematically,\n* the rational numbers '''Q''',\n* which are included in the real numbers '''R''',\n* which can be generalized to the complex numbers '''C'''.\n\n\nThis means that each of those larger sets, and the data types used to represent them, include some integers.\n\n\nGiven a rational, real, or complex number of any type, test whether it is mathematically an integer.\n\nYour code should handle all numeric data types commonly used in your programming language.\n\nDiscuss any limitations of your code.\n\n\nFor the purposes of this task, integerness means that a number could theoretically be represented as an integer at no loss of precision ''(given an infinitely wide integer type)''.\nIn other words:\n\n{| class=\"wikitable\"\n|-\n! Set\n! Common representation\n! C++ type\n! Considered an integer...\n|-\n| rational numbers '''Q'''\n| fraction\n| std::ratio\n| ...if its denominator is 1 (in reduced form)\n|-\n| rowspan=2 | real numbers '''Z'''''(approximated)''\n| fixed-point\n| \n| ...if it has no non-zero digits after the decimal point\n|-\n| floating-point\n| float, double\n| ...if the number of significant decimal places of its mantissa isn't greater than its exponent\n|-\n| complex numbers '''C'''\n| pair of real numbers\n| std::complex\n| ...if its real part is considered an integer and its imaginary part is zero\n|}\n\n\nOptionally, make your code accept a tolerance parameter for fuzzy testing. The tolerance is the maximum amount by which the number may differ from the nearest integer, to still be considered an integer.\n\nThis is useful in practice, because when dealing with approximate numeric types (such as floating point), there may already be round-off errors from previous calculations. For example, a float value of 0.9999999998 might actually be intended to represent the integer 1.\n\n\n{| 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 \u2013 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": ">>> def isint(f): \n return complex(f).imag == 0 and complex(f).real.is_integer()\n\n>>> [isint(f) for f in (1.0, 2, (3.0+0.0j), 4.1, (3+4j), (5.6+0j))]\n[True, True, True, False, False, False]\n\n>>> # Test cases\n...\n>>> isint(25.000000)\nTrue\n>>> isint(24.999999)\nFalse\n>>> isint(25.000100)\nFalse\n>>> isint(-2.1e120)\nTrue\n>>> isint(-5e-2)\nFalse\n>>> isint(float('nan'))\nFalse\n>>> isint(float('inf'))\nFalse\n>>> isint(5.0+0.0j)\nTrue\n>>> isint(5-5j)\nFalse\n"} +{"title": "Textonyms", "language": "C", "task": "When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms.\n\nAssuming the digit keys are mapped to letters as follows:\n 2 -> ABC\n 3 -> DEF\n 4 -> GHI\n 5 -> JKL\n 6 -> MNO\n 7 -> PQRS\n 8 -> TUV\n 9 -> WXYZ \n\n\n;Task:\nWrite a program that finds textonyms in a list of words such as \u00a0 \n[[Textonyms/wordlist]] \u00a0 or \u00a0 \n[http://www.puzzlers.org/pub/wordlists/unixdict.txt unixdict.txt].\n\nThe task should produce a report:\n\n There are #{0} words in #{1} which can be represented by the digit key mapping.\n They require #{2} digit combinations to represent them.\n #{3} digit combinations represent Textonyms.\n\nWhere:\n #{0} is the number of words in the list which can be represented by the digit key mapping.\n #{1} is the URL of the wordlist being used.\n #{2} is the number of digit combinations required to represent the words in #{0}.\n #{3} is the number of #{2} which represent more than one word.\n\nAt your discretion show a couple of examples of your solution displaying Textonyms. \n\nE.G.:\n\n 2748424767 -> \"Briticisms\", \"criticisms\"\n\n\n;Extra credit:\nUse a word list and keypad mapping other than English.\n\n\n\n", "solution": "#include \n#include \n#include \n#include \n\nchar text_char(char c) {\n switch (c) {\n case 'a': case 'b': case 'c':\n return '2';\n case 'd': case 'e': case 'f':\n return '3';\n case 'g': case 'h': case 'i':\n return '4';\n case 'j': case 'k': case 'l':\n return '5';\n case 'm': case 'n': case 'o':\n return '6';\n case 'p': case 'q': case 'r': case 's':\n return '7';\n case 't': case 'u': case 'v':\n return '8';\n case 'w': case 'x': case 'y': case 'z':\n return '9';\n default:\n return 0;\n }\n}\n\nbool text_string(const GString* word, GString* text) {\n g_string_set_size(text, word->len);\n for (size_t i = 0; i < word->len; ++i) {\n char c = text_char(g_ascii_tolower(word->str[i]));\n if (c == 0)\n return false;\n text->str[i] = c;\n }\n return true;\n}\n\ntypedef struct textonym_tag {\n const char* text;\n size_t length;\n GPtrArray* words;\n} textonym_t;\n\nint compare_by_text_length(const void* p1, const void* p2) {\n const textonym_t* t1 = p1;\n const textonym_t* t2 = p2;\n if (t1->length > t2->length)\n return -1;\n if (t1->length < t2->length)\n return 1;\n return strcmp(t1->text, t2->text);\n}\n\nint compare_by_word_count(const void* p1, const void* p2) {\n const textonym_t* t1 = p1;\n const textonym_t* t2 = p2;\n if (t1->words->len > t2->words->len)\n return -1;\n if (t1->words->len < t2->words->len)\n return 1;\n return strcmp(t1->text, t2->text);\n}\n\nvoid print_words(GPtrArray* words) {\n for (guint i = 0, n = words->len; i < n; ++i) {\n if (i > 0)\n printf(\", \");\n printf(\"%s\", g_ptr_array_index(words, i));\n }\n printf(\"\\n\");\n}\n\nvoid print_top_words(GArray* textonyms, guint top) {\n for (guint i = 0; i < top; ++i) {\n const textonym_t* t = &g_array_index(textonyms, textonym_t, i);\n printf(\"%s = \", t->text);\n print_words(t->words);\n }\n}\n\nvoid free_strings(gpointer ptr) {\n g_ptr_array_free(ptr, TRUE);\n}\n\nbool find_textonyms(const char* filename, GError** error_ptr) {\n GError* error = NULL;\n GIOChannel* channel = g_io_channel_new_file(filename, \"r\", &error);\n if (channel == NULL) {\n g_propagate_error(error_ptr, error);\n return false;\n }\n GHashTable* ht = g_hash_table_new_full(g_str_hash, g_str_equal,\n g_free, free_strings);\n GString* word = g_string_sized_new(64);\n GString* text = g_string_sized_new(64);\n guint count = 0;\n gsize term_pos;\n while (g_io_channel_read_line_string(channel, word, &term_pos,\n &error) == G_IO_STATUS_NORMAL) {\n g_string_truncate(word, term_pos);\n if (!text_string(word, text))\n continue;\n GPtrArray* words = g_hash_table_lookup(ht, text->str);\n if (words == NULL) {\n words = g_ptr_array_new_full(1, g_free);\n g_hash_table_insert(ht, g_strdup(text->str), words);\n }\n g_ptr_array_add(words, g_strdup(word->str));\n ++count;\n }\n g_io_channel_unref(channel);\n g_string_free(word, TRUE);\n g_string_free(text, TRUE);\n if (error != NULL) {\n g_propagate_error(error_ptr, error);\n g_hash_table_destroy(ht);\n return false;\n }\n\n GArray* words = g_array_new(FALSE, FALSE, sizeof(textonym_t));\n GHashTableIter iter;\n gpointer key, value;\n g_hash_table_iter_init(&iter, ht);\n while (g_hash_table_iter_next(&iter, &key, &value)) {\n GPtrArray* v = value;\n if (v->len > 1) {\n textonym_t textonym;\n textonym.text = key;\n textonym.length = strlen(key);\n textonym.words = v;\n g_array_append_val(words, textonym);\n }\n }\n\n printf(\"There are %u words in '%s' which can be represented by the digit key mapping.\\n\",\n count, filename);\n guint size = g_hash_table_size(ht);\n printf(\"They require %u digit combinations to represent them.\\n\", size);\n guint textonyms = words->len;\n printf(\"%u digit combinations represent Textonyms.\\n\", textonyms);\n\n guint top = 5;\n if (textonyms < top)\n top = textonyms;\n\n printf(\"\\nTop %u by number of words:\\n\", top);\n g_array_sort(words, compare_by_word_count);\n print_top_words(words, top);\n \n printf(\"\\nTop %u by length:\\n\", top);\n g_array_sort(words, compare_by_text_length);\n print_top_words(words, top);\n\n g_array_free(words, TRUE);\n g_hash_table_destroy(ht);\n return true;\n}\n\nint main(int argc, char** argv) {\n if (argc != 2) {\n fprintf(stderr, \"usage: %s word-list\\n\", argv[0]);\n return EXIT_FAILURE;\n }\n GError* error = NULL;\n if (!find_textonyms(argv[1], &error)) {\n if (error != NULL) {\n fprintf(stderr, \"%s: %s\\n\", argv[1], error->message);\n g_error_free(error);\n }\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n}"} +{"title": "Textonyms", "language": "Python", "task": "When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms.\n\nAssuming the digit keys are mapped to letters as follows:\n 2 -> ABC\n 3 -> DEF\n 4 -> GHI\n 5 -> JKL\n 6 -> MNO\n 7 -> PQRS\n 8 -> TUV\n 9 -> WXYZ \n\n\n;Task:\nWrite a program that finds textonyms in a list of words such as \u00a0 \n[[Textonyms/wordlist]] \u00a0 or \u00a0 \n[http://www.puzzlers.org/pub/wordlists/unixdict.txt unixdict.txt].\n\nThe task should produce a report:\n\n There are #{0} words in #{1} which can be represented by the digit key mapping.\n They require #{2} digit combinations to represent them.\n #{3} digit combinations represent Textonyms.\n\nWhere:\n #{0} is the number of words in the list which can be represented by the digit key mapping.\n #{1} is the URL of the wordlist being used.\n #{2} is the number of digit combinations required to represent the words in #{0}.\n #{3} is the number of #{2} which represent more than one word.\n\nAt your discretion show a couple of examples of your solution displaying Textonyms. \n\nE.G.:\n\n 2748424767 -> \"Briticisms\", \"criticisms\"\n\n\n;Extra credit:\nUse a word list and keypad mapping other than English.\n\n\n\n", "solution": "from collections import defaultdict\nimport urllib.request\n\nCH2NUM = {ch: str(num) for num, chars in enumerate('abc def ghi jkl mno pqrs tuv wxyz'.split(), 2) for ch in chars}\nURL = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'\n\n\ndef getwords(url):\n return urllib.request.urlopen(url).read().decode(\"utf-8\").lower().split()\n\ndef mapnum2words(words):\n number2words = defaultdict(list)\n reject = 0\n for word in words:\n try:\n number2words[''.join(CH2NUM[ch] for ch in word)].append(word)\n except KeyError:\n # Reject words with non a-z e.g. '10th'\n reject += 1\n return dict(number2words), reject\n\ndef interactiveconversions():\n global inp, ch, num\n while True:\n inp = input(\"\\nType a number or a word to get the translation and textonyms: \").strip().lower()\n if inp:\n if all(ch in '23456789' for ch in inp):\n if inp in num2words:\n print(\" Number {0} has the following textonyms in the dictionary: {1}\".format(inp, ', '.join(\n num2words[inp])))\n else:\n print(\" Number {0} has no textonyms in the dictionary.\".format(inp))\n elif all(ch in CH2NUM for ch in inp):\n num = ''.join(CH2NUM[ch] for ch in inp)\n print(\" Word {0} is{1} in the dictionary and is number {2} with textonyms: {3}\".format(\n inp, ('' if inp in wordset else \"n't\"), num, ', '.join(num2words[num])))\n else:\n print(\" I don't understand %r\" % inp)\n else:\n print(\"Thank you\")\n break\n\n\nif __name__ == '__main__':\n words = getwords(URL)\n print(\"Read %i words from %r\" % (len(words), URL))\n wordset = set(words)\n num2words, reject = mapnum2words(words)\n morethan1word = sum(1 for w in num2words if len(num2words[w]) > 1)\n maxwordpernum = max(len(values) for values in num2words.values())\n print(\"\"\"\nThere are {0} words in {1} which can be represented by the Textonyms mapping.\nThey require {2} digit combinations to represent them.\n{3} digit combinations represent Textonyms.\\\n\"\"\".format(len(words) - reject, URL, len(num2words), morethan1word))\n\n print(\"\\nThe numbers mapping to the most words map to %i words each:\" % maxwordpernum)\n maxwpn = sorted((key, val) for key, val in num2words.items() if len(val) == maxwordpernum)\n for num, wrds in maxwpn:\n print(\" %s maps to: %s\" % (num, ', '.join(wrds)))\n\n interactiveconversions()"} +{"title": "The Name Game", "language": "C", "task": "Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song \"The Name Game\".\n\n\nThe regular verse\n\nUnless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.\nThe verse for the name 'Gary' would be like this:\n\n Gary, Gary, bo-bary\n Banana-fana fo-fary\n Fee-fi-mo-mary\n Gary! \n\nAt the end of every line, the name gets repeated without the first letter: Gary becomes ary\nIf we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:\n\n (X), (X), bo-b(Y)\n Banana-fana fo-f(Y)\n Fee-fi-mo-m(Y)\n (X)! \n\nVowel as first letter of the name\n\nIf you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.\nThe verse looks like this:\n\n Earl, Earl, bo-bearl\n Banana-fana fo-fearl\n Fee-fi-mo-mearl\n Earl! \n\n'B', 'F' or 'M' as first letter of the name\n\nIn case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.\nThe line which would 'rebuild' the name (e.g. bo-billy) is sung without the first letter of the name.\nThe verse for the name Billy looks like this:\n\n Billy, Billy, bo-illy\n Banana-fana fo-filly\n Fee-fi-mo-milly\n Billy! \n\nFor the name 'Felix', this would be right:\n\n Felix, Felix, bo-belix\n Banana-fana fo-elix\n Fee-fi-mo-melix\n Felix!\n\n\n", "solution": "#include \n#include \n\nvoid print_verse(const char *name) {\n char *x, *y; \n int b = 1, f = 1, m = 1, i = 1;\n\n /* ensure name is in title-case */\n x = strdup(name); \n x[0] = toupper(x[0]);\n for (; x[i]; ++i) x[i] = tolower(x[i]);\n \n if (strchr(\"AEIOU\", x[0])) {\n y = strdup(x);\n y[0] = tolower(y[0]); \n }\n else {\n y = x + 1;\n }\n\n switch(x[0]) {\n case 'B': b = 0; break;\n case 'F': f = 0; break;\n case 'M': m = 0; break;\n default : break;\n }\n \n printf(\"%s, %s, bo-%s%s\\n\", x, x, (b) ? \"b\" : \"\", y);\n printf(\"Banana-fana fo-%s%s\\n\", (f) ? \"f\" : \"\", y);\n printf(\"Fee-fi-mo-%s%s\\n\", (m) ? \"m\" : \"\", y);\n printf(\"%s!\\n\\n\", x);\n}\n\nint main() {\n int i;\n const char *names[6] = {\"gARY\", \"Earl\", \"Billy\", \"Felix\", \"Mary\", \"sHIRley\"};\n for (i = 0; i < 6; ++i) print_verse(names[i]);\n return 0;\n}"} +{"title": "The Name Game", "language": "JavaScript", "task": "Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song \"The Name Game\".\n\n\nThe regular verse\n\nUnless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.\nThe verse for the name 'Gary' would be like this:\n\n Gary, Gary, bo-bary\n Banana-fana fo-fary\n Fee-fi-mo-mary\n Gary! \n\nAt the end of every line, the name gets repeated without the first letter: Gary becomes ary\nIf we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:\n\n (X), (X), bo-b(Y)\n Banana-fana fo-f(Y)\n Fee-fi-mo-m(Y)\n (X)! \n\nVowel as first letter of the name\n\nIf you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.\nThe verse looks like this:\n\n Earl, Earl, bo-bearl\n Banana-fana fo-fearl\n Fee-fi-mo-mearl\n Earl! \n\n'B', 'F' or 'M' as first letter of the name\n\nIn case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.\nThe line which would 'rebuild' the name (e.g. bo-billy) is sung without the first letter of the name.\nThe verse for the name Billy looks like this:\n\n Billy, Billy, bo-illy\n Banana-fana fo-filly\n Fee-fi-mo-milly\n Billy! \n\nFor the name 'Felix', this would be right:\n\n Felix, Felix, bo-belix\n Banana-fana fo-elix\n Fee-fi-mo-melix\n Felix!\n\n\n", "solution": "function singNameGame(name) {\n\n // normalize name\n name = name.toLowerCase();\n name = name[0].toUpperCase() + name.slice(1);\n\n // ... and sometimes y\n // let's pray this works\n let firstVowelPos = (function() {\n let vowels =\n 'aeiou\u00e0\u00e1\u00e2\u00e3\u00e4\u00e5\u00e6\u00e8\u00e9\u00ea\u00eb\u00ec\u00ed\u00ee\u00ef\u00f2\u00f3\u00f4\u00f5\u00f6\u00f8\u00f9\u00fa\u00fb\u00fc\u0101\u0103\u0105\u0113\u0115\u0117\u0119\u011b\u0129\u012b\u012d\u012f\u0131\u0133\u014d\u014f\u0151\u0153\u0169\u016b\u016d\u016f\u0171\u0173'\n .split('');\n function isVowel(char) {\n return vowels.indexOf(char) >= 0;\n }\n if (isVowel(name[0].toLowerCase())) return 0;\n if (name[0] == 'Y' && !isVowel(name[1])) return 0;\n if (name[0] == 'Y' && isVowel(name[1])) return 1;\n vowels = vowels.concat(vowels, 'y\u00ff\u00fd'.split(''));\n for (let i = 1; i < name.length; i++)\n if (isVowel(name[i])) return i;\n })();\n\n let init = name[0].toLowerCase(),\n trunk = name.slice(firstVowelPos).toLowerCase(),\n b = trunk, f = trunk, m = trunk;\n\n switch (init) {\n case 'b': f = 'f' + trunk; m = 'm' + trunk; break;\n case 'f': b = 'b' + trunk; m = 'm' + trunk; break;\n case 'm': b = 'b' + trunk; f = 'f' + trunk; break;\n default: b = 'b' + trunk; f = 'f' + trunk; m = 'm' + trunk;\n }\n\n return `\n ${name}, ${name}, bo-${b}\n Banana-fana fo-${f}\n Fee-fi-fo-mo-${m}\n ${name}!\n `\n}\n\n// testing\nlet names =\n 'Gary Earl Billy Felix Mary Christine Brian Yvonne Yannick'.split(' ');\nfor (let i = 0; i < names.length; i++)\n document.write(singNameGame(names[i]));"} +{"title": "The Name Game", "language": "Python", "task": "Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song \"The Name Game\".\n\n\nThe regular verse\n\nUnless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.\nThe verse for the name 'Gary' would be like this:\n\n Gary, Gary, bo-bary\n Banana-fana fo-fary\n Fee-fi-mo-mary\n Gary! \n\nAt the end of every line, the name gets repeated without the first letter: Gary becomes ary\nIf we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:\n\n (X), (X), bo-b(Y)\n Banana-fana fo-f(Y)\n Fee-fi-mo-m(Y)\n (X)! \n\nVowel as first letter of the name\n\nIf you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.\nThe verse looks like this:\n\n Earl, Earl, bo-bearl\n Banana-fana fo-fearl\n Fee-fi-mo-mearl\n Earl! \n\n'B', 'F' or 'M' as first letter of the name\n\nIn case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.\nThe line which would 'rebuild' the name (e.g. bo-billy) is sung without the first letter of the name.\nThe verse for the name Billy looks like this:\n\n Billy, Billy, bo-illy\n Banana-fana fo-filly\n Fee-fi-mo-milly\n Billy! \n\nFor the name 'Felix', this would be right:\n\n Felix, Felix, bo-belix\n Banana-fana fo-elix\n Fee-fi-mo-melix\n Felix!\n\n\n", "solution": "def print_verse(n):\n l = ['b', 'f', 'm']\n s = n[1:]\n if str.lower(n[0]) in l:\n l[l.index(str.lower(n[0]))] = ''\n elif n[0] in ['A', 'E', 'I', 'O', 'U']:\n s = str.lower(n)\n print('{0}, {0}, bo-{2}{1}\\nBanana-fana fo-{3}{1}\\nFee-fi-mo-{4}{1}\\n{0}!\\n'.format(n, s, *l))\n\n# Assume that the names are in title-case and they're more than one character long\nfor n in ['Gary', 'Earl', 'Billy', 'Felix', 'Mary']:\n print_verse(n)"} +{"title": "The Twelve Days of Christmas", "language": "C", "task": ";Task:\nWrite a program that outputs the lyrics of the Christmas carol ''The Twelve Days of Christmas''. \nThe lyrics can be found [http://www.lyricsmode.com/lyrics/c/christmas_carols/the_twelve_days_of_christmas.html 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": "\n#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": "The Twelve Days of Christmas", "language": "JavaScript", "task": ";Task:\nWrite a program that outputs the lyrics of the Christmas carol ''The Twelve Days of Christmas''. \nThe lyrics can be found [http://www.lyricsmode.com/lyrics/c/christmas_carols/the_twelve_days_of_christmas.html 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": "JSON.stringify(\n (function (\n strPrepn,\n strHoliday,\n strUnit,\n strRole,\n strProcess,\n strRecipient\n ) {\n var lstOrdinal =\n 'first second third fourth fifth sixth\\\n seventh eighth ninth tenth eleventh twelfth'\n .split(/\\s+/),\n lngUnits = lstOrdinal.length,\n\n lstGoods =\n 'A partridge in a pear tree.\\\n Two turtle doves\\\n Three french hens\\\n Four calling birds\\\n Five golden rings\\\n Six geese a-laying\\\n Seven swans a-swimming\\\n Eight maids a-milking\\\n Nine ladies dancing\\\n Ten lords a-leaping\\\n Eleven pipers piping\\\n Twelve drummers drumming'\n .split(/\\s{2,}/),\n\n lstReversed = (function () {\n var lst = lstGoods.slice(0);\n return (lst.reverse(), lst);\n })(),\n\n strProvenance = [strRole, strProcess, strRecipient + ':'].join(' '),\n\n strPenultimate = lstReversed[lngUnits - 2] + ' and',\n strFinal = lstGoods[0];\n\n return lstOrdinal.reduce(\n function (sofar, day, i) {\n return sofar.concat(\n [\n [\n [ // abstraction of line 1\n strPrepn,\n 'the',\n lstOrdinal[i],\n strUnit,\n 'of',\n strHoliday\n ].join(' '),\n strProvenance\n ].concat( // reversed descent through memory\n (i > 1 ? [lstGoods[i]] : []).concat(\n lstReversed.slice(\n lngUnits - i,\n lngUnits - 2\n )\n ).concat( // penultimate line ends with 'and'\n [\n strPenultimate,\n strFinal\n ].slice(i ? 0 : 1)\n )\n )\n ]\n );\n }, []\n );\n })(\n 'On', 'Christmas', 'day', 'my true love', 'gave to', 'me'\n ), null, 2\n);"} +{"title": "The Twelve Days of Christmas", "language": "Python", "task": ";Task:\nWrite a program that outputs the lyrics of the Christmas carol ''The Twelve Days of Christmas''. \nThe lyrics can be found [http://www.lyricsmode.com/lyrics/c/christmas_carols/the_twelve_days_of_christmas.html 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": "gifts = '''\\\nA partridge in a pear tree.\nTwo turtle doves\nThree french hens\nFour calling birds\nFive golden rings\nSix geese a-laying\nSeven swans a-swimming\nEight maids a-milking\nNine ladies dancing\nTen lords a-leaping\nEleven pipers piping\nTwelve drummers drumming'''.split('\\n')\n\ndays = '''first second third fourth fifth\n sixth seventh eighth ninth tenth\n eleventh twelfth'''.split()\n\nfor n, day in enumerate(days, 1):\n g = gifts[:n][::-1]\n print(('\\nOn the %s day of Christmas\\nMy true love gave to me:\\n' % day) +\n '\\n'.join(g[:-1]) +\n (' and\\n' + g[-1] if n > 1 else g[-1].capitalize()))"} +{"title": "Thue-Morse", "language": "C", "task": ";Task:\nCreate a [http://en.wikipedia.org/wiki/Thue%E2%80%93Morse_sequence Thue-Morse sequence].\n\n\n;See also\n* \u00a0 YouTube entry: [https://www.youtube.com/watch?v=prh72BLNjIk The Fairest Sharing Sequence Ever]\n* \u00a0 YouTube entry: [https://www.youtube.com/watch?v=Tt5TTid6YXk Math and OCD - My story with the Thue-Morse sequence]\n* \u00a0 Task: [[Fairshare between two and more]]\n\n", "solution": "#include \n#include \n#include \n\nint main(int argc, char *argv[]){\n\tchar sequence[256+1] = \"0\";\n\tchar inverse[256+1] = \"1\";\n\tchar buffer[256+1];\n\tint i;\n\t\n\tfor(i = 0; i < 8; i++){\n\t\tstrcpy(buffer, sequence);\n\t\tstrcat(sequence, inverse);\n\t\tstrcat(inverse, buffer);\n\t}\n\t\n\tputs(sequence);\n\treturn 0;\n}"} +{"title": "Thue-Morse", "language": "JavaScript", "task": ";Task:\nCreate a [http://en.wikipedia.org/wiki/Thue%E2%80%93Morse_sequence Thue-Morse sequence].\n\n\n;See also\n* \u00a0 YouTube entry: [https://www.youtube.com/watch?v=prh72BLNjIk The Fairest Sharing Sequence Ever]\n* \u00a0 YouTube entry: [https://www.youtube.com/watch?v=Tt5TTid6YXk Math and OCD - My story with the Thue-Morse sequence]\n* \u00a0 Task: [[Fairshare between two and more]]\n\n", "solution": "(() => {\n 'use strict';\n\n // thueMorsePrefixes :: () -> [[Int]]\n const thueMorsePrefixes = () =>\n iterate(\n ap(append)(\n map(x => 1 - x)\n )\n )([0]);\n\n // ----------------------- TEST -----------------------\n const main = () =>\n // Fifth iteration.\n // 2 ^ 5 = 32 terms of the Thue-Morse sequence.\n showList(\n index(thueMorsePrefixes())(\n 5\n )\n );\n\n\n // ---------------- GENERIC FUNCTIONS -----------------\n\n // ap :: (a -> b -> c) -> (a -> b) -> a -> c\n const ap = f =>\n // Applicative instance for functions.\n // f(x) applied to g(x).\n g => x => f(x)(\n g(x)\n );\n\n\n // append (++) :: [a] -> [a] -> [a]\n // append (++) :: String -> String -> String\n const append = xs =>\n // A list or string composed by\n // the concatenation of two others.\n ys => xs.concat(ys);\n\n\n // index (!!) :: Generator (Int, a) -> Int -> Maybe a\n const index = xs =>\n i => (take(i)(xs), xs.next().value);\n\n\n // iterate :: (a -> a) -> a -> Gen [a]\n const iterate = f =>\n function*(x) {\n let v = x;\n while (true) {\n yield(v);\n v = f(v);\n }\n };\n\n\n // map :: (a -> b) -> [a] -> [b]\n const map = f =>\n // The list obtained by applying f\n // to each element of xs.\n // (The image of xs under f).\n xs => xs.map(f);\n\n\n // showList :: [a] -> String\n const showList = xs =>\n '[' + xs.map(x => x.toString())\n .join(',')\n .replace(/[\\\"]/g, '') + ']';\n\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n =>\n // The first n elements of a list,\n // string of characters, or stream.\n xs => 'GeneratorFunction' !== xs\n .constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // MAIN ---\n return main();\n})();"} +{"title": "Thue-Morse", "language": "Python", "task": ";Task:\nCreate a [http://en.wikipedia.org/wiki/Thue%E2%80%93Morse_sequence Thue-Morse sequence].\n\n\n;See also\n* \u00a0 YouTube entry: [https://www.youtube.com/watch?v=prh72BLNjIk The Fairest Sharing Sequence Ever]\n* \u00a0 YouTube entry: [https://www.youtube.com/watch?v=Tt5TTid6YXk Math and OCD - My story with the Thue-Morse sequence]\n* \u00a0 Task: [[Fairshare between two and more]]\n\n", "solution": "\nm='0'\nprint(m)\nfor i in range(0,6):\n m0=m\n m=m.replace('0','a')\n m=m.replace('1','0')\n m=m.replace('a','1')\n m=m0+m\n print(m)\n"} +{"title": "Tonelli-Shanks algorithm", "language": "C", "task": "In computational number theory, the Tonelli\u2013Shanks algorithm is a technique for solving for '''x''' in a congruence of the form:\n\n:: x2 \u2261 n (mod p)\n\nwhere '''n''' is an integer which is a quadratic residue (mod p), '''p''' is an odd prime, and '''x,n \u2208 Fp''' where Fp = {0, 1, ..., p - 1}.\n\nIt is used in [https://en.wikipedia.org/wiki/Rabin_cryptosystem cryptography] techniques.\n\n\nTo apply the algorithm, we need the Legendre symbol:\n\nThe Legendre symbol '''(a | p)''' denotes the value of a(p-1)/2 (mod p).\n* '''(a | p) \u2261 1''' \u00a0\u00a0 if '''a''' is a square (mod p)\n* '''(a | p) \u2261 -1''' \u00a0\u00a0 if '''a''' is not a square (mod p)\n* '''(a | p) \u2261 0''' \u00a0\u00a0 if '''a''' \u2261 0 (mod p) \n\n\n;Algorithm pseudo-code:\n\nAll \u2261 are taken to mean (mod p) unless stated otherwise.\n\n* Input: '''p''' an odd prime, and an integer '''n''' .\n* Step 0: Check that '''n''' is indeed a square: (n | p) must be \u2261 1 .\n* Step 1: By factoring out powers of 2 from p - 1, find '''q''' and '''s''' such that p - 1 = q2s with '''q''' odd .\n** If p \u2261 3 (mod 4) (i.e. s = 1), output the two solutions r \u2261 \u00b1 n(p+1)/4 .\n* Step 2: Select a non-square '''z''' such that (z | p) \u2261 -1 and set c \u2261 zq .\n* Step 3: Set r \u2261 n(q+1)/2, t \u2261 nq, m = s .\n* Step 4: Loop the following:\n** If t \u2261 1, output '''r''' and '''p - r''' .\n** Otherwise find, by repeated squaring, the lowest '''i''', 0 < i < m , such that t2i \u2261 1 .\n** Let b \u2261 c2(m - i - 1), and set r \u2261 rb, t \u2261 tb2, c \u2261 b2 and m = i .\n\n\n\n;Task:\nImplement the above algorithm. \n\nFind solutions (if any) for \n* n = 10 p = 13\n* n = 56 p = 101\n* n = 1030 p = 10009\n* n = 1032 p = 10009\n* n = 44402 p = 100049 \n\n;Extra credit:\n* n = 665820697 p = 1000000009 \n* n = 881398088036 p = 1000000000039 \n* n = 41660815127637347468140745042827704103445750172002 p = 10^50 + 577 \t\n\n\n;See also:\n* [[Modular exponentiation]]\n* [[Cipolla's algorithm]]\n\n", "solution": "#include \n#include \n#include \n\nuint64_t modpow(uint64_t a, uint64_t b, uint64_t n) {\n uint64_t x = 1, y = a;\n while (b > 0) {\n if (b % 2 == 1) {\n x = (x * y) % n; // multiplying with base\n }\n y = (y * y) % n; // squaring the base\n b /= 2;\n }\n return x % n;\n}\n\nstruct Solution {\n uint64_t root1, root2;\n bool exists;\n};\n\nstruct Solution makeSolution(uint64_t root1, uint64_t root2, bool exists) {\n struct Solution sol;\n sol.root1 = root1;\n sol.root2 = root2;\n sol.exists = exists;\n return sol;\n}\n\nstruct Solution ts(uint64_t n, uint64_t p) {\n uint64_t q = p - 1;\n uint64_t ss = 0;\n uint64_t z = 2;\n uint64_t c, r, t, m;\n\n if (modpow(n, (p - 1) / 2, p) != 1) {\n return makeSolution(0, 0, false);\n }\n\n while ((q & 1) == 0) {\n ss += 1;\n q >>= 1;\n }\n\n if (ss == 1) {\n uint64_t r1 = modpow(n, (p + 1) / 4, p);\n return makeSolution(r1, p - r1, true);\n }\n\n while (modpow(z, (p - 1) / 2, p) != p - 1) {\n z++;\n }\n\n c = modpow(z, q, p);\n r = modpow(n, (q + 1) / 2, p);\n t = modpow(n, q, p);\n m = ss;\n\n while (true) {\n uint64_t i = 0, zz = t;\n uint64_t b = c, e;\n if (t == 1) {\n return makeSolution(r, p - r, true);\n }\n while (zz != 1 && i < (m - 1)) {\n zz = zz * zz % p;\n i++;\n }\n e = m - i - 1;\n while (e > 0) {\n b = b * b % p;\n e--;\n }\n r = r * b % p;\n c = b * b % p;\n t = t * c % p;\n m = i;\n }\n}\n\nvoid test(uint64_t n, uint64_t p) {\n struct Solution sol = ts(n, p);\n printf(\"n = %llu\\n\", n);\n printf(\"p = %llu\\n\", p);\n if (sol.exists) {\n printf(\"root1 = %llu\\n\", sol.root1);\n printf(\"root2 = %llu\\n\", sol.root2);\n } else {\n printf(\"No solution exists\\n\");\n }\n printf(\"\\n\");\n}\n\nint main() {\n test(10, 13);\n test(56, 101);\n test(1030, 10009);\n test(1032, 10009);\n test(44402, 100049);\n\n return 0;\n}"} +{"title": "Tonelli-Shanks algorithm", "language": "Python 3", "task": "In computational number theory, the Tonelli\u2013Shanks algorithm is a technique for solving for '''x''' in a congruence of the form:\n\n:: x2 \u2261 n (mod p)\n\nwhere '''n''' is an integer which is a quadratic residue (mod p), '''p''' is an odd prime, and '''x,n \u2208 Fp''' where Fp = {0, 1, ..., p - 1}.\n\nIt is used in [https://en.wikipedia.org/wiki/Rabin_cryptosystem cryptography] techniques.\n\n\nTo apply the algorithm, we need the Legendre symbol:\n\nThe Legendre symbol '''(a | p)''' denotes the value of a(p-1)/2 (mod p).\n* '''(a | p) \u2261 1''' \u00a0\u00a0 if '''a''' is a square (mod p)\n* '''(a | p) \u2261 -1''' \u00a0\u00a0 if '''a''' is not a square (mod p)\n* '''(a | p) \u2261 0''' \u00a0\u00a0 if '''a''' \u2261 0 (mod p) \n\n\n;Algorithm pseudo-code:\n\nAll \u2261 are taken to mean (mod p) unless stated otherwise.\n\n* Input: '''p''' an odd prime, and an integer '''n''' .\n* Step 0: Check that '''n''' is indeed a square: (n | p) must be \u2261 1 .\n* Step 1: By factoring out powers of 2 from p - 1, find '''q''' and '''s''' such that p - 1 = q2s with '''q''' odd .\n** If p \u2261 3 (mod 4) (i.e. s = 1), output the two solutions r \u2261 \u00b1 n(p+1)/4 .\n* Step 2: Select a non-square '''z''' such that (z | p) \u2261 -1 and set c \u2261 zq .\n* Step 3: Set r \u2261 n(q+1)/2, t \u2261 nq, m = s .\n* Step 4: Loop the following:\n** If t \u2261 1, output '''r''' and '''p - r''' .\n** Otherwise find, by repeated squaring, the lowest '''i''', 0 < i < m , such that t2i \u2261 1 .\n** Let b \u2261 c2(m - i - 1), and set r \u2261 rb, t \u2261 tb2, c \u2261 b2 and m = i .\n\n\n\n;Task:\nImplement the above algorithm. \n\nFind solutions (if any) for \n* n = 10 p = 13\n* n = 56 p = 101\n* n = 1030 p = 10009\n* n = 1032 p = 10009\n* n = 44402 p = 100049 \n\n;Extra credit:\n* n = 665820697 p = 1000000009 \n* n = 881398088036 p = 1000000000039 \n* n = 41660815127637347468140745042827704103445750172002 p = 10^50 + 577 \t\n\n\n;See also:\n* [[Modular exponentiation]]\n* [[Cipolla's algorithm]]\n\n", "solution": "def legendre(a, p):\n return pow(a, (p - 1) // 2, p)\n\ndef tonelli(n, p):\n assert legendre(n, p) == 1, \"not a square (mod p)\"\n q = p - 1\n s = 0\n while q % 2 == 0:\n q //= 2\n s += 1\n if s == 1:\n return pow(n, (p + 1) // 4, p)\n for z in range(2, p):\n if p - 1 == legendre(z, p):\n break\n c = pow(z, q, p)\n r = pow(n, (q + 1) // 2, p)\n t = pow(n, q, p)\n m = s\n t2 = 0\n while (t - 1) % p != 0:\n t2 = (t * t) % p\n for i in range(1, m):\n if (t2 - 1) % p == 0:\n break\n t2 = (t2 * t2) % p\n b = pow(c, 1 << (m - i - 1), p)\n r = (r * b) % p\n c = (b * b) % p\n t = (t * c) % p\n m = i\n return r\n\nif __name__ == '__main__':\n ttest = [(10, 13), (56, 101), (1030, 10009), (44402, 100049),\n\t (665820697, 1000000009), (881398088036, 1000000000039),\n (41660815127637347468140745042827704103445750172002, 10**50 + 577)]\n for n, p in ttest:\n r = tonelli(n, p)\n assert (r * r - n) % p == 0\n print(\"n = %d p = %d\" % (n, p))\n print(\"\\t roots : %d %d\" % (r, p - r))"} +{"title": "Top rank per group", "language": "C", "task": ";Task:\nFind the top \u00a0 ''N'' \u00a0 salaries in each department, \u00a0 where \u00a0 ''N'' \u00a0 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": "Top rank per group", "language": "JavaScript", "task": ";Task:\nFind the top \u00a0 ''N'' \u00a0 salaries in each department, \u00a0 where \u00a0 ''N'' \u00a0 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": "var data = [\n {name: \"Tyler Bennett\", id: \"E10297\", salary: 32000, dept: \"D101\"},\n {name: \"John Rappl\", id: \"E21437\", salary: 47000, dept: \"D050\"},\n {name: \"George Woltman\", id: \"E00127\", salary: 53500, dept: \"D101\"},\n {name: \"Adam Smith\", id: \"E63535\", salary: 18000, dept: \"D202\"},\n {name: \"Claire Buckman\", id: \"E39876\", salary: 27800, dept: \"D202\"},\n {name: \"David McClellan\", id: \"E04242\", salary: 41500, dept: \"D101\"},\n {name: \"Rich Holcomb\", id: \"E01234\", salary: 49500, dept: \"D202\"},\n {name: \"Nathan Adams\", id: \"E41298\", salary: 21900, dept: \"D050\"},\n {name: \"Richard Potter\", id: \"E43128\", salary: 15900, dept: \"D101\"},\n {name: \"David Motsinger\", id: \"E27002\", salary: 19250, dept: \"D202\"},\n {name: \"Tim Sampair\", id: \"E03033\", salary: 27000, dept: \"D101\"},\n {name: \"Kim Arlich\", id: \"E10001\", salary: 57000, dept: \"D190\"},\n {name: \"Timothy Grove\", id: \"E16398\", salary: 29900, dept: \"D190\"},\n];\n\nfunction top_rank(n) {\n var by_dept = group_by_dept(data);\n for (var dept in by_dept) {\n output(dept);\n for (var i = 0; i < n && i < by_dept[dept].length; i++) {\n var emp = by_dept[dept][i];\n output(emp.name + \", id=\" + emp.id + \", salary=\" + emp.salary);\n }\n output(\"\");\n }\n}\n\n// group by dept, and sort by salary\nfunction group_by_dept(data) {\n var by_dept = {};\n for (var idx in data) {\n var dept = data[idx].dept;\n if ( ! has_property(by_dept, dept)) {\n by_dept[dept] = new Array();\n }\n by_dept[dept].push(data[idx]);\n }\n for (var dept in by_dept) {\n // numeric sort\n by_dept[dept].sort(function (a,b){return b.salary - a.salary});\n }\n return by_dept;\n}\n\nfunction has_property(obj, propname) {\n return typeof(obj[propname]) != \"undefined\";\n}\n\nfunction output(str) {\n try {\n WScript.Echo(str); // WSH\n } catch(err) {\n print(str); // Rhino\n }\n}\n\ntop_rank(3);\n"} +{"title": "Top rank per group", "language": "Python", "task": ";Task:\nFind the top \u00a0 ''N'' \u00a0 salaries in each department, \u00a0 where \u00a0 ''N'' \u00a0 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": "from collections import defaultdict\nfrom heapq import nlargest\n \ndata = [('Employee Name', 'Employee ID', 'Salary', 'Department'),\n ('Tyler Bennett', 'E10297', 32000, 'D101'),\n ('John Rappl', 'E21437', 47000, 'D050'),\n ('George Woltman', 'E00127', 53500, 'D101'),\n ('Adam Smith', 'E63535', 18000, 'D202'),\n ('Claire Buckman', 'E39876', 27800, 'D202'),\n ('David McClellan', 'E04242', 41500, 'D101'),\n ('Rich Holcomb', 'E01234', 49500, 'D202'),\n ('Nathan Adams', 'E41298', 21900, 'D050'),\n ('Richard Potter', 'E43128', 15900, 'D101'),\n ('David Motsinger', 'E27002', 19250, 'D202'),\n ('Tim Sampair', 'E03033', 27000, 'D101'),\n ('Kim Arlich', 'E10001', 57000, 'D190'),\n ('Timothy Grove', 'E16398', 29900, 'D190')]\n \ndepartments = defaultdict(list)\nfor rec in data[1:]:\n departments[rec[-1]].append(rec)\n \nN = 3\nformat = \" %-15s \" * len(data[0])\nfor department, recs in sorted(departments.items()):\n print (\"Department %s\" % department)\n print (format % data[0])\n for rec in nlargest(N, recs, key=lambda rec: rec[-2]):\n print (format % rec)\n"} +{"title": "Topic variable", "language": "Python", "task": "Several programming languages offer syntax shortcuts to deal with the notion of \"current\" or \"topic\" variable.\n\nA topic variable is a special variable with a very short name which can also often be omitted.\n\nDemonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.\n\nFor instance you can (but you don't have to) show how the topic variable can be used by assigning the number 3 to it and then computing its square and square root.\n\n", "solution": ">>> 3\n3\n>>> _*_, _**0.5\n(9, 1.7320508075688772)\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 \u00a0 n \u00a0 cards numbered \u00a0 1..n \u00a0 on both of their faces, for example the arrangement of four cards given by \u00a0 [2, 4, 1, 3] \u00a0 where the leftmost card is on top. \n\nA round is composed of reversing the first \u00a0 m \u00a0 cards where \u00a0 m \u00a0 is the value of the topmost card. \n\nRounds are repeated until the topmost card is the number \u00a0 1 \u00a0 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 \u00a0 1 \u00a0 is on top.\n\n\nFor a particular number \u00a0 n \u00a0 of cards, \u00a0 topswops(n) \u00a0 is the maximum swaps needed for any starting permutation of the \u00a0 n \u00a0 cards.\n\n\n;Task:\nThe task is to generate and show here a table of \u00a0 n \u00a0 vs \u00a0 topswops(n) \u00a0 for \u00a0 n \u00a0 in the range \u00a0 1..10 \u00a0 inclusive.\n\n\n;Note:\nTopswops \u00a0 is also known as \u00a0 [http://www.haskell.org/haskellwiki/Shootout/Fannkuch Fannkuch] \u00a0 from the German word \u00a0 ''Pfannkuchen'' \u00a0 meaning \u00a0 [http://youtu.be/3biN6nQYqZY pancake].\n\n\n;Related tasks:\n* \u00a0 [[Number reversal game]]\n* \u00a0 [[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": "Topswops", "language": "Python", "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 \u00a0 n \u00a0 cards numbered \u00a0 1..n \u00a0 on both of their faces, for example the arrangement of four cards given by \u00a0 [2, 4, 1, 3] \u00a0 where the leftmost card is on top. \n\nA round is composed of reversing the first \u00a0 m \u00a0 cards where \u00a0 m \u00a0 is the value of the topmost card. \n\nRounds are repeated until the topmost card is the number \u00a0 1 \u00a0 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 \u00a0 1 \u00a0 is on top.\n\n\nFor a particular number \u00a0 n \u00a0 of cards, \u00a0 topswops(n) \u00a0 is the maximum swaps needed for any starting permutation of the \u00a0 n \u00a0 cards.\n\n\n;Task:\nThe task is to generate and show here a table of \u00a0 n \u00a0 vs \u00a0 topswops(n) \u00a0 for \u00a0 n \u00a0 in the range \u00a0 1..10 \u00a0 inclusive.\n\n\n;Note:\nTopswops \u00a0 is also known as \u00a0 [http://www.haskell.org/haskellwiki/Shootout/Fannkuch Fannkuch] \u00a0 from the German word \u00a0 ''Pfannkuchen'' \u00a0 meaning \u00a0 [http://youtu.be/3biN6nQYqZY pancake].\n\n\n;Related tasks:\n* \u00a0 [[Number reversal game]]\n* \u00a0 [[Sorting algorithms/Pancake sort]]\n\n", "solution": "try:\n import psyco\n psyco.full()\nexcept ImportError:\n pass\n\nbest = [0] * 16\n\ndef try_swaps(deck, f, s, d, n):\n if d > best[n]:\n best[n] = d\n\n i = 0\n k = 1 << s\n while s:\n k >>= 1\n s -= 1\n if deck[s] == -1 or deck[s] == s:\n break\n i |= k\n if (i & f) == i and d + best[s] <= best[n]:\n return d\n s += 1\n\n deck2 = list(deck)\n k = 1\n for i2 in xrange(1, s):\n k <<= 1\n if deck2[i2] == -1:\n if f & k: continue\n elif deck2[i2] != i2:\n continue\n\n deck[i2] = i2\n deck2[:i2 + 1] = reversed(deck[:i2 + 1])\n try_swaps(deck2, f | k, s, 1 + d, n)\n\ndef topswops(n):\n best[n] = 0\n deck0 = [-1] * 16\n deck0[0] = 0\n try_swaps(deck0, 1, n, 0, n)\n return best[n]\n\nfor i in xrange(1, 13):\n print \"%2d: %d\" % (i, topswops(i))"} +{"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 \u00a0 (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 \u00a0 21.56503660... .\n\n\n;Related task:\n* \u00a0 [[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": "Total circles area", "language": "Python", "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 \u00a0 (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 \u00a0 21.56503660... .\n\n\n;Related task:\n* \u00a0 [[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": "from collections import namedtuple\n\nCircle = namedtuple(\"Circle\", \"x y r\")\n\ncircles = [\n Circle( 1.6417233788, 1.6121789534, 0.0848270516),\n Circle(-1.4944608174, 1.2077959613, 1.1039549836),\n Circle( 0.6110294452, -0.6907087527, 0.9089162485),\n Circle( 0.3844862411, 0.2923344616, 0.2375743054),\n Circle(-0.2495892950, -0.3832854473, 1.0845181219),\n Circle( 1.7813504266, 1.6178237031, 0.8162655711),\n Circle(-0.1985249206, -0.8343333301, 0.0538864941),\n Circle(-1.7011985145, -0.1263820964, 0.4776976918),\n Circle(-0.4319462812, 1.4104420482, 0.7886291537),\n Circle( 0.2178372997, -0.9499557344, 0.0357871187),\n Circle(-0.6294854565, -1.3078893852, 0.7653357688),\n Circle( 1.7952608455, 0.6281269104, 0.2727652452),\n Circle( 1.4168575317, 1.0683357171, 1.1016025378),\n Circle( 1.4637371396, 0.9463877418, 1.1846214562),\n Circle(-0.5263668798, 1.7315156631, 1.4428514068),\n Circle(-1.2197352481, 0.9144146579, 1.0727263474),\n Circle(-0.1389358881, 0.1092805780, 0.7350208828),\n Circle( 1.5293954595, 0.0030278255, 1.2472867347),\n Circle(-0.5258728625, 1.3782633069, 1.3495508831),\n Circle(-0.1403562064, 0.2437382535, 1.3804956588),\n Circle( 0.8055826339, -0.0482092025, 0.3327165165),\n Circle(-0.6311979224, 0.7184578971, 0.2491045282),\n Circle( 1.4685857879, -0.8347049536, 1.3670667538),\n Circle(-0.6855727502, 1.6465021616, 1.0593087096),\n Circle( 0.0152957411, 0.0638919221, 0.9771215985)]\n\ndef main():\n # compute the bounding box of the circles\n x_min = min(c.x - c.r for c in circles)\n x_max = max(c.x + c.r for c in circles)\n y_min = min(c.y - c.r for c in circles)\n y_max = max(c.y + c.r for c in circles)\n\n box_side = 500\n\n dx = (x_max - x_min) / box_side\n dy = (y_max - y_min) / box_side\n\n count = 0\n\n for r in xrange(box_side):\n y = y_min + r * dy\n for c in xrange(box_side):\n x = x_min + c * dx\n if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2)\n for circle in circles):\n count += 1\n\n print \"Approximated area:\", count * dx * dy\n\nmain()"} +{"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 [http://bitsavers.org/pdf/stanford/cs_techReports/STAN-CS-76-562_EarlyDevelPgmgLang_Aug76.pdf 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: \u00a0 \u00a0 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 \u00a0 ''' ''S'' ''' \u00a0 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": "\n#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": "Trabb Pardo\u2013Knuth algorithm", "language": "JavaScript", "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 [http://bitsavers.org/pdf/stanford/cs_techReports/STAN-CS-76-562_EarlyDevelPgmgLang_Aug76.pdf 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: \u00a0 \u00a0 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 \u00a0 ''' ''S'' ''' \u00a0 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": "#!/usr/bin/env js\n\nfunction main() {\n var nums = getNumbers(11);\n nums.reverse();\n for (var i in nums) {\n pardoKnuth(nums[i], fn, 400);\n }\n}\n\nfunction pardoKnuth(n, f, max) {\n var res = f(n);\n putstr('f(' + String(n) + ')');\n if (res > max) {\n print(' is too large');\n } else {\n print(' = ' + String(res));\n } \n}\n\nfunction fn(x) {\n return Math.pow(Math.abs(x), 0.5) + 5 * Math.pow(x, 3);\n}\n\nfunction getNumbers(n) {\n var nums = [];\n print('Enter', n, 'numbers.');\n for (var i = 1; i <= n; i++) {\n putstr(' ' + i + ': ');\n var num = readline();\n nums.push(Number(num)); \n }\n return nums;\n}\n\nmain();\n"} +{"title": "Trabb Pardo\u2013Knuth algorithm", "language": "Python", "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 [http://bitsavers.org/pdf/stanford/cs_techReports/STAN-CS-76-562_EarlyDevelPgmgLang_Aug76.pdf 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: \u00a0 \u00a0 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 \u00a0 ''' ''S'' ''' \u00a0 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": "Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> def f(x): return abs(x) ** 0.5 + 5 * x**3\n\n>>> print(', '.join('%s:%s' % (x, v if v<=400 else \"TOO LARGE!\")\n\t for x,v in ((y, f(float(y))) for y in input('\\nnumbers: ').strip().split()[:11][::-1])))\n\n11 numbers: 1 2 3 4 5 6 7 8 9 10 11\n11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0\n>>> "} +{"title": "Trabb Pardo\u2013Knuth algorithm", "language": "Python 3.10", "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 [http://bitsavers.org/pdf/stanford/cs_techReports/STAN-CS-76-562_EarlyDevelPgmgLang_Aug76.pdf 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: \u00a0 \u00a0 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 \u00a0 ''' ''S'' ''' \u00a0 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": "import math\n\ndef f(x):\n return math.sqrt(abs(x)) + 5 * x**3\n\ndef ask_numbers(n=11):\n print(f'Enter {n} numbers:')\n return (float(input('>')) for _ in range(n))\n\nif __name__ == '__main__':\n for x in ask_numbers().reverse():\n if (result := f(x)) > 400:\n print(f'f({x}): overflow')\n else:\n print(f'f({x}) = {result}')"} +{"title": "Tree datastructures", "language": "Python", "task": "The following shows a tree of data with nesting denoted by visual levels of indentation:\nRosettaCode\n rocks\n code\n comparison\n wiki\n mocks\n trolling\n\nA common datastructure for trees is to define node structures having a name and a, (possibly empty), list of child nodes. The nesting of nodes captures the indentation of the tree. Lets call this '''the nest form'''.\n# E.g. if child nodes are surrounded by brackets\n# and separated by commas then:\nRosettaCode(rocks(code, ...), ...)\n# But only an _example_\n\nAnother datastructure for trees is to construct from the root an ordered list of the nodes level of indentation and the name of that node. The indentation for the root node is zero; node 'rocks is indented by one level from the left, and so on. Lets call this '''the indent form'''.\n0 RosettaCode\n1 rocks\n2 code\n...\n\n;Task:\n# Create/use a nest datastructure format and textual representation for arbitrary trees.\n# Create/use an indent datastructure format and textual representation for arbitrary trees.\n# Create methods/classes/proceedures/routines etc to:\n## Change from a nest tree datastructure to an indent one.\n## Change from an indent tree datastructure to a nest one\n# Use the above to encode the example at the start into the nest format, and show it.\n# transform the initial nest format to indent format and show it.\n# transform the indent format to final nest format and show it.\n# Compare initial and final nest formats which should be the same.\n\n;Note:\n* It's all about showing aspects of the contrasting datastructures as they hold the tree.\n* Comparing nested datastructures is secondary - saving formatted output as a string then a string compare would suffice for this task, if its easier.\n\n\nShow all output on this page.\n\n", "solution": "from pprint import pprint as pp\n\ndef to_indent(node, depth=0, flat=None):\n if flat is None:\n flat = []\n if node:\n flat.append((depth, node[0]))\n for child in node[1]:\n to_indent(child, depth + 1, flat)\n return flat\n\ndef to_nest(lst, depth=0, level=None):\n if level is None:\n level = []\n while lst:\n d, name = lst[0]\n if d == depth:\n children = []\n level.append((name, children))\n lst.pop(0)\n elif d > depth: # down\n to_nest(lst, d, children)\n elif d < depth: # up\n return\n return level[0] if level else None\n \nif __name__ == '__main__':\n print('Start Nest format:')\n nest = ('RosettaCode', [('rocks', [('code', []), ('comparison', []), ('wiki', [])]), \n ('mocks', [('trolling', [])])])\n pp(nest, width=25)\n\n print('\\n... To Indent format:')\n as_ind = to_indent(nest)\n pp(as_ind, width=25)\n\n print('\\n... To Nest format:')\n as_nest = to_nest(as_ind)\n pp(as_nest, width=25)\n\n if nest != as_nest:\n print(\"Whoops round-trip issues\")"} +{"title": "Tree from nesting levels", "language": "Python", "task": "Given a flat list of integers greater than zero, representing object nesting\nlevels, e.g. [1, 2, 4],\ngenerate a tree formed from nested lists of those nesting level integers where:\n* Every int appears, in order, at its depth of nesting.\n* If the next level int is greater than the previous then it appears in a sub-list of the list containing the previous item\n\n\nThe generated tree data structure should ideally be in a languages nested list format that can\nbe used for further calculations rather than something just calculated for printing.\n\n\nAn input of [1, 2, 4] should produce the equivalent of: [1, [2, [[4]]]]\nwhere 1 is at depth1, 2 is two deep and 4 is nested 4 deep.\n\n[1, 2, 4, 2, 2, 1] should produce [1, [2, [[4]], 2, 2], 1]. \nAll the nesting integers are in the same order but at the correct nesting\nlevels.\n\nSimilarly [3, 1, 3, 1] should generate [[[3]], 1, [[3]], 1]\n\n;Task:\nGenerate and show here the results for the following inputs:\n:* []\n:* [1, 2, 4]\n:* [3, 1, 3, 1]\n:* [1, 2, 3, 1]\n:* [3, 2, 1, 3]\n:* [3, 3, 3, 1, 1, 3, 3, 3]\n", "solution": "def to_tree(x, index=0, depth=1):\n so_far = []\n while index < len(x):\n this = x[index]\n if this == depth:\n so_far.append(this)\n elif this > depth:\n index, deeper = to_tree(x, index, depth + 1)\n so_far.append(deeper)\n else: # this < depth:\n index -=1\n break\n index += 1\n return (index, so_far) if depth > 1 else so_far\n\n\nif __name__ == \"__main__\":\n from pprint import pformat\n\n def pnest(nest:list, width: int=9) -> str:\n text = pformat(nest, width=width).replace('\\n', '\\n ')\n print(f\" OR {text}\\n\")\n\n exercises = [\n [],\n [1, 2, 4],\n [3, 1, 3, 1],\n [1, 2, 3, 1],\n [3, 2, 1, 3],\n [3, 3, 3, 1, 1, 3, 3, 3],\n ]\n for flat in exercises:\n nest = to_tree(flat)\n print(f\"{flat} NESTS TO: {nest}\")\n pnest(nest)"} +{"title": "Tropical algebra overloading", "language": "Python", "task": "In algebra, a max tropical semiring (also called a max-plus algebra) is the semiring\n(\u211d \u222a -Inf, \u2295, \u2297) containing the ring of real numbers \u211d augmented by negative infinity,\nthe max function (returns the greater of two real numbers), and addition.\n\nIn max tropical algebra, x \u2295 y = max(x, y) and x \u2297 y = x + y. The identity for \u2295\nis -Inf (the max of any number with -infinity is that number), and the identity for \u2297 is 0.\n\n;Task:\n\n* Define functions or, if the language supports the symbols as operators, operators for \u2295 and \u2297 that fit the above description. If the language does not support \u2295 and \u2297 as operators but allows overloading operators for a new object type, you may instead overload + and * for a new min tropical albrbraic type. If you cannot overload operators in the language used, define ordinary functions for the purpose. \n\nShow that 2 \u2297 -2 is 0, -0.001 \u2295 -Inf is -0.001, 0 \u2297 -Inf is -Inf, 1.5 \u2295 -1 is 1.5, and -0.5 \u2297 0 is -0.5.\n\n* Define exponentiation as serial \u2297, and in general that a to the power of b is a * b, where a is a real number and b must be a positive integer. Use either \u2191 or similar up arrow or the carat ^, as an exponentiation operator if this can be used to overload such \"exponentiation\" in the language being used. Calculate 5 \u2191 7 using this definition.\n\n* Max tropical algebra is distributive, so that\n\n a \u2297 (b \u2295 c) equals a \u2297 b \u2295 b \u2297 c, \n\nwhere \u2297 has precedence over \u2295. Demonstrate that 5 \u2297 (8 \u2295 7) equals 5 \u2297 8 \u2295 5 \u2297 7.\n\n* If the language used does not support operator overloading, you may use ordinary function names such as tropicalAdd(x, y) and tropicalMul(x, y).\n\n\n;See also\n:;*[[https://en.wikipedia.org/wiki/Tropical_semiring#tropical_algebra Tropical algebra]]\n:;*[[https://arxiv.org/pdf/1908.07012.pdf Tropical geometry review article]]\n:;*[[https://en.wikipedia.org/wiki/Operator_overloading Operator overloading]]\n\n\n", "solution": "from numpy import Inf\n\nclass MaxTropical:\n \"\"\"\n Class for max tropical algebra.\n x + y is max(x, y) and X * y is x + y\n \"\"\"\n def __init__(self, x=0):\n self.x = x\n\n def __str__(self):\n return str(self.x)\n\n def __add__(self, other):\n return MaxTropical(max(self.x, other.x))\n\n def __mul__(self, other):\n return MaxTropical(self.x + other.x)\n\n def __pow__(self, other):\n assert other.x // 1 == other.x and other.x > 0, \"Invalid Operation\" \n return MaxTropical(self.x * other.x)\n\n def __eq__(self, other):\n return self.x == other.x\n\n\nif __name__ == \"__main__\":\n a = MaxTropical(-2)\n b = MaxTropical(-1)\n c = MaxTropical(-0.5)\n d = MaxTropical(-0.001)\n e = MaxTropical(0)\n f = MaxTropical(0.5)\n g = MaxTropical(1)\n h = MaxTropical(1.5)\n i = MaxTropical(2)\n j = MaxTropical(5)\n k = MaxTropical(7)\n l = MaxTropical(8)\n m = MaxTropical(-Inf)\n\n print(\"2 * -2 == \", i * a)\n print(\"-0.001 + -Inf == \", d + m)\n print(\"0 * -Inf == \", e * m)\n print(\"1.5 + -1 == \", h + b)\n print(\"-0.5 * 0 == \", c * e)\n print(\"5**7 == \", j**k)\n print(\"5 * (8 + 7)) == \", j * (l + k))\n print(\"5 * 8 + 5 * 7 == \", j * l + j * k)\n print(\"5 * (8 + 7) == 5 * 8 + 5 * 7\", j * (l + k) == j * l + j * k)\n\n"} +{"title": "Truncate a file", "language": "C", "task": "[[Category:File System Operations]]\n\n;Task:\nTruncate a file to a specific length. \u00a0 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. \u00a0 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. \u00a0 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": "Truncate a file", "language": "MinGW", "task": "[[Category:File System Operations]]\n\n;Task:\nTruncate a file to a specific length. \u00a0 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. \u00a0 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. \u00a0 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": "#include \n#include \n#include \n\n/* Print \"message: last Win32 error\" to stderr. */\nvoid\noops(const wchar_t *message)\n{\n\twchar_t *buf;\n\tDWORD error;\n\n\tbuf = NULL;\n\terror = GetLastError();\n\tFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |\n\t FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n\t NULL, error, 0, (wchar_t *)&buf, 0, NULL);\n\n\tif (buf) {\n\t\tfwprintf(stderr, L\"%ls: %ls\", message, buf);\n\t\tLocalFree(buf);\n\t} else {\n\t\t/* FormatMessageW failed. */\n\t\tfwprintf(stderr, L\"%ls: unknown error 0x%x\\n\",\n\t\t message, error);\n\t}\n}\n\nint\ndotruncate(wchar_t *fn, LARGE_INTEGER fp)\n{\n\tHANDLE fh;\n\n\tfh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);\n\tif (fh == INVALID_HANDLE_VALUE) {\n\t\toops(fn);\n\t\treturn 1;\n\t}\n\n\tif (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||\n\t SetEndOfFile(fh) == 0) {\n\t\toops(fn);\n\t\tCloseHandle(fh);\n\t\treturn 1;\n\t}\n\n\tCloseHandle(fh);\n\treturn 0;\n}\n\n/*\n * Truncate or extend a file to the given length.\n */\nint\nmain()\n{\n\tLARGE_INTEGER fp;\n\tint argc;\n\twchar_t **argv, *fn, junk[2];\n\n\t/* MinGW never provides wmain(argc, argv). */\n\targv = CommandLineToArgvW(GetCommandLineW(), &argc);\n\tif (argv == NULL) {\n\t\toops(L\"CommandLineToArgvW\");\n\t\treturn 1;\n\t}\n\n\tif (argc != 3) {\n\t\tfwprintf(stderr, L\"usage: %ls filename length\\n\", argv[0]);\n\t\treturn 1;\n\t}\n\n\tfn = argv[1];\n\n\t/* fp = argv[2] converted to a LARGE_INTEGER. */\n\tif (swscanf(argv[2], L\"%lld%1ls\", &fp.QuadPart, &junk) != 1) {\n\t\tfwprintf(stderr, L\"%ls: not a number\\n\", argv[2]);\n\t\treturn 1;\n\t}\n\n\treturn dotruncate(fn, fp);\n}"} +{"title": "Truncate a file", "language": "Python", "task": "[[Category:File System Operations]]\n\n;Task:\nTruncate a file to a specific length. \u00a0 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. \u00a0 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. \u00a0 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": "\ndef truncate_file(name, length):\n if not os.path.isfile(name):\n return False\n if length >= os.path.getsize(name):\n return False\n with open(name, 'ab') as f:\n f.truncate(length)\n return True\n"} +{"title": "Truth table", "language": "C", "task": "A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function.\n\n\n;Task:\n# Input a Boolean function from the user as a string then calculate and print a formatted truth table for the given function. (One can assume that the user input is correct).\n# Print and show output for Boolean functions of two and three input variables, but any program should not be limited to that many variables in the function. \n# Either reverse-polish or infix notation expressions are allowed.\n\n\n;Related tasks:\n* \u00a0 [[Boolean values]]\n* \u00a0 [[Ternary logic]]\n\n\n;See also:\n* \u00a0 [http://mathworld.wolfram.com/TruthTable.html Wolfram MathWorld entry on truth tables].\n* \u00a0 [http://www.google.co.uk/search?q=truth+table&hl=en&client=firefox-a&hs=Om7&rls=org.mozilla:en-GB:official&prmd=imvns&tbm=isch&tbo=u&source=univ&sa=X&ei=C0uuTtjuH4Wt8gOF4dmYCw&ved=0CDUQsAQ&biw=941&bih=931&sei=%20Jk-uTuKKD4Sg8QOFkPGcCw some \"truth table\" examples from Google].\n\n", "solution": "#include \n#include \n#include \n\n#define TRUE 1\n#define FALSE 0\n#define STACK_SIZE 80\n#define BUFFER_SIZE 100\n\ntypedef int bool;\n\ntypedef struct {\n char name;\n bool val;\n} var;\n\ntypedef struct {\n int top;\n bool els[STACK_SIZE];\n} stack_of_bool;\n\nchar expr[BUFFER_SIZE];\nint expr_len;\nvar vars[24];\nint vars_len;\n\n/* stack manipulation functions */\n\nbool is_full(stack_of_bool *sp) {\n return sp->top == STACK_SIZE - 1;\n}\n\nbool is_empty(stack_of_bool *sp) {\n return sp->top == -1;\n}\n\nbool peek(stack_of_bool *sp) {\n if (!is_empty(sp))\n return sp->els[sp->top];\n else {\n printf(\"Stack is empty.\\n\");\n exit(1);\n }\n}\n\nvoid push(stack_of_bool *sp, bool val) {\n if (!is_full(sp)) {\n sp->els[++(sp->top)] = val;\n }\n else {\n printf(\"Stack is full.\\n\");\n exit(1);\n }\n}\n\nbool pop(stack_of_bool *sp) {\n if (!is_empty(sp))\n return sp->els[(sp->top)--];\n else {\n printf(\"\\nStack is empty.\\n\");\n exit(1);\n }\n}\n\nvoid make_empty(stack_of_bool *sp) {\n sp->top = -1; \n}\n\nint elems_count(stack_of_bool *sp) {\n return (sp->top) + 1; \n}\n\nbool is_operator(const char c) {\n return c == '&' || c == '|' || c == '!' || c == '^';\n}\n\nint vars_index(const char c) {\n int i;\n for (i = 0; i < vars_len; ++i) {\n if (vars[i].name == c) return i;\n }\n return -1;\n}\n\nbool eval_expr() {\n int i, vi;\n char e;\n stack_of_bool s;\n stack_of_bool *sp = &s\n make_empty(sp);\n for (i = 0; i < expr_len; ++i) {\n e = expr[i];\n if (e == 'T')\n push(sp, TRUE);\n else if (e == 'F')\n push(sp, FALSE);\n else if((vi = vars_index(e)) >= 0) {\n push(sp, vars[vi].val);\n }\n else switch(e) {\n case '&':\n push(sp, pop(sp) & pop(sp));\n break;\n case '|':\n push(sp, pop(sp) | pop(sp));\n break;\n case '!':\n push(sp, !pop(sp));\n break;\n case '^':\n push(sp, pop(sp) ^ pop(sp));\n break;\n default:\n printf(\"\\nNon-conformant character '%c' in expression.\\n\", e);\n exit(1);\n }\n }\n if (elems_count(sp) != 1) {\n printf(\"\\nStack should contain exactly one element.\\n\");\n exit(1);\n }\n return peek(sp);\n}\n\nvoid set_vars(int pos) {\n int i;\n if (pos > vars_len) {\n printf(\"\\nArgument to set_vars can't be greater than the number of variables.\\n\");\n exit(1);\n }\n else if (pos == vars_len) {\n for (i = 0; i < vars_len; ++i) {\n printf((vars[i].val) ? \"T \" : \"F \");\n }\n printf(\"%c\\n\", (eval_expr()) ? 'T' : 'F');\n }\n else {\n vars[pos].val = FALSE;\n set_vars(pos + 1);\n vars[pos].val = TRUE;\n set_vars(pos + 1);\n }\n}\n\n/* removes whitespace and converts to upper case */\nvoid process_expr() {\n int i, count = 0;\n for (i = 0; expr[i]; ++i) {\n if (!isspace(expr[i])) expr[count++] = toupper(expr[i]);\n }\n expr[count] = '\\0';\n}\n\nint main() {\n int i, h;\n char e;\n printf(\"Accepts single-character variables (except for 'T' and 'F',\\n\");\n printf(\"which specify explicit true or false values), postfix, with\\n\");\n printf(\"&|!^ for and, or, not, xor, respectively; optionally\\n\");\n printf(\"seperated by whitespace. Just enter nothing to quit.\\n\");\n\n while (TRUE) {\n printf(\"\\nBoolean expression: \");\n fgets(expr, BUFFER_SIZE, stdin);\n fflush(stdin); \n process_expr();\n expr_len = strlen(expr); \n if (expr_len == 0) break;\n vars_len = 0;\n for (i = 0; i < expr_len; ++i) {\n e = expr[i];\n if (!is_operator(e) && e != 'T' && e != 'F' && vars_index(e) == -1) {\n vars[vars_len].name = e;\n vars[vars_len].val = FALSE;\n vars_len++;\n }\n }\n printf(\"\\n\");\n if (vars_len == 0) {\n printf(\"No variables were entered.\\n\");\n } \n else {\n for (i = 0; i < vars_len; ++i)\n printf(\"%c \", vars[i].name);\n printf(\"%s\\n\", expr);\n h = vars_len * 3 + expr_len;\n for (i = 0; i < h; ++i) printf(\"=\");\n printf(\"\\n\");\n set_vars(0);\n }\n }\n return 0;\n}"} +{"title": "Truth table", "language": "Python", "task": "A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function.\n\n\n;Task:\n# Input a Boolean function from the user as a string then calculate and print a formatted truth table for the given function. (One can assume that the user input is correct).\n# Print and show output for Boolean functions of two and three input variables, but any program should not be limited to that many variables in the function. \n# Either reverse-polish or infix notation expressions are allowed.\n\n\n;Related tasks:\n* \u00a0 [[Boolean values]]\n* \u00a0 [[Ternary logic]]\n\n\n;See also:\n* \u00a0 [http://mathworld.wolfram.com/TruthTable.html Wolfram MathWorld entry on truth tables].\n* \u00a0 [http://www.google.co.uk/search?q=truth+table&hl=en&client=firefox-a&hs=Om7&rls=org.mozilla:en-GB:official&prmd=imvns&tbm=isch&tbo=u&source=univ&sa=X&ei=C0uuTtjuH4Wt8gOF4dmYCw&ved=0CDUQsAQ&biw=941&bih=931&sei=%20Jk-uTuKKD4Sg8QOFkPGcCw some \"truth table\" examples from Google].\n\n", "solution": "from itertools import product\n\nwhile True:\n bexp = input('\\nBoolean expression: ')\n bexp = bexp.strip()\n if not bexp:\n print(\"\\nThank you\")\n break\n code = compile(bexp, '', 'eval')\n names = code.co_names\n print('\\n' + ' '.join(names), ':', bexp)\n for values in product(range(2), repeat=len(names)):\n env = dict(zip(names, values))\n print(' '.join(str(v) for v in values), ':', eval(code, env))\n"} +{"title": "Two bullet roulette", "language": "C", "task": "The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street:\n\n A revolver handgun has a revolving cylinder with six chambers for bullets.\n \n It is loaded with the following procedure:\n\n 1. Check the first chamber to the right of the trigger for a bullet. If a bullet\n is seen, the cylinder is rotated one chamber clockwise and the next chamber\n checked until an empty chamber is found.\n\n 2. A cartridge containing a bullet is placed in the empty chamber.\n\n 3. The cylinder is then rotated one chamber clockwise.\n \n To randomize the cylinder's position, the cylinder is spun, which causes the cylinder to take\n a random position from 1 to 6 chamber rotations clockwise from its starting position.\n \n When the trigger is pulled the gun will fire if there is a bullet in position 0, which is just\n counterclockwise from the loading position.\n \n The gun is unloaded by removing all cartridges from the cylinder.\n \n According to the legend, a suicidal Russian imperial military officer plays a game of Russian\n roulette by putting two bullets in a six-chamber cylinder and pulls the trigger twice.\n If the gun fires with a trigger pull, this is considered a successful suicide.\n \n The cylinder is always spun before the first shot, but it may or may not be spun after putting\n in the first bullet and may or may not be spun after taking the first shot.\n \n Which of the following situations produces the highest probability of suicide?\n \n A. Spinning the cylinder after loading the first bullet, and spinning again after the first shot.\n\n B. Spinning the cylinder after loading the first bullet only.\n\n C. Spinning the cylinder after firing the first shot only.\n\n D. Not spinning the cylinder either after loading the first bullet or after the first shot.\n\n E. The probability is the same for all cases.\n\n\n;Task:\n# Run a repeated simulation of each of the above scenario, calculating the percentage of suicide with a randomization of the four spinning, loading and firing order scenarios.\n# Show the results as a percentage of deaths for each type of scenario.\n# The hand calculated probabilities are 5/9, 7/12, 5/9, and 1/2. A correct program should produce results close enough to those to allow a correct response to the interview question. \n\n\n;Reference:\nYoutube video on the Russian 1895 Nagant revolver [[https://www.youtube.com/watch?v=Dh1mojMaEtM]]\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nstatic int nextInt(int size) {\n return rand() % size;\n}\n\nstatic bool cylinder[6];\n\nstatic void rshift() {\n bool t = cylinder[5];\n int i;\n for (i = 4; i >= 0; i--) {\n cylinder[i + 1] = cylinder[i];\n }\n cylinder[0] = t;\n}\n\nstatic void unload() {\n int i;\n for (i = 0; i < 6; i++) {\n cylinder[i] = false;\n }\n}\n\nstatic void load() {\n while (cylinder[0]) {\n rshift();\n }\n cylinder[0] = true;\n rshift();\n}\n\nstatic void spin() {\n int lim = nextInt(6) + 1;\n int i;\n for (i = 1; i < lim; i++) {\n rshift();\n }\n}\n\nstatic bool fire() {\n bool shot = cylinder[0];\n rshift();\n return shot;\n}\n\nstatic int method(const char *s) {\n unload();\n for (; *s != '\\0'; s++) {\n switch (*s) {\n case 'L':\n load();\n break;\n case 'S':\n spin();\n break;\n case 'F':\n if (fire()) {\n return 1;\n }\n break;\n }\n }\n return 0;\n}\n\nstatic void append(char *out, const char *txt) {\n if (*out != '\\0') {\n strcat(out, \", \");\n }\n strcat(out, txt);\n}\n\nstatic void mstring(const char *s, char *out) {\n for (; *s != '\\0'; s++) {\n switch (*s) {\n case 'L':\n append(out, \"load\");\n break;\n case 'S':\n append(out, \"spin\");\n break;\n case 'F':\n append(out, \"fire\");\n break;\n }\n }\n}\n\nstatic void test(char *src) {\n char buffer[41] = \"\";\n const int tests = 100000;\n int sum = 0;\n int t;\n double pc;\n\n for (t = 0; t < tests; t++) {\n sum += method(src);\n }\n\n mstring(src, buffer);\n pc = 100.0 * sum / tests;\n\n printf(\"%-40s produces %6.3f%% deaths.\\n\", buffer, pc);\n}\n\nint main() {\n srand(time(0));\n\n test(\"LSLSFSF\");\n test(\"LSLSFF\");\n test(\"LLSFSF\");\n test(\"LLSFF\");\n\n return 0;\n}"} +{"title": "Two bullet roulette", "language": "JavaScript", "task": "The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street:\n\n A revolver handgun has a revolving cylinder with six chambers for bullets.\n \n It is loaded with the following procedure:\n\n 1. Check the first chamber to the right of the trigger for a bullet. If a bullet\n is seen, the cylinder is rotated one chamber clockwise and the next chamber\n checked until an empty chamber is found.\n\n 2. A cartridge containing a bullet is placed in the empty chamber.\n\n 3. The cylinder is then rotated one chamber clockwise.\n \n To randomize the cylinder's position, the cylinder is spun, which causes the cylinder to take\n a random position from 1 to 6 chamber rotations clockwise from its starting position.\n \n When the trigger is pulled the gun will fire if there is a bullet in position 0, which is just\n counterclockwise from the loading position.\n \n The gun is unloaded by removing all cartridges from the cylinder.\n \n According to the legend, a suicidal Russian imperial military officer plays a game of Russian\n roulette by putting two bullets in a six-chamber cylinder and pulls the trigger twice.\n If the gun fires with a trigger pull, this is considered a successful suicide.\n \n The cylinder is always spun before the first shot, but it may or may not be spun after putting\n in the first bullet and may or may not be spun after taking the first shot.\n \n Which of the following situations produces the highest probability of suicide?\n \n A. Spinning the cylinder after loading the first bullet, and spinning again after the first shot.\n\n B. Spinning the cylinder after loading the first bullet only.\n\n C. Spinning the cylinder after firing the first shot only.\n\n D. Not spinning the cylinder either after loading the first bullet or after the first shot.\n\n E. The probability is the same for all cases.\n\n\n;Task:\n# Run a repeated simulation of each of the above scenario, calculating the percentage of suicide with a randomization of the four spinning, loading and firing order scenarios.\n# Show the results as a percentage of deaths for each type of scenario.\n# The hand calculated probabilities are 5/9, 7/12, 5/9, and 1/2. A correct program should produce results close enough to those to allow a correct response to the interview question. \n\n\n;Reference:\nYoutube video on the Russian 1895 Nagant revolver [[https://www.youtube.com/watch?v=Dh1mojMaEtM]]\n\n", "solution": "\nlet Pistol = function(method) {\n this.fired = false;\n this.cylinder = new Array(6).fill(false);\n this.trigger = 0;\n this.rshift = function() {\n this.trigger = this.trigger == 0 ? 5 : this.trigger-1;\n }\n this.load = function() {\n while (this.cylinder[this.trigger]) this.rshift();\n this.cylinder[this.trigger] = true;\n this.rshift();\n }\n // actually we don't need this here: just for completeness\n this.unload = function() { this.cylinder.fill(false); }\n\n this.spin = function() { this.trigger = Math.floor(Math.random() * 6); }\n this.fire = function() {\n if (this.cylinder[this.trigger]) this.fired = true;\n this.rshift();\n }\n this.exec = function() {\n if (!method) console.error('No method provided');\n else {\n method = method.toUpperCase();\n for (let x = 0; x < method.length; x++)\n switch (method[x]) {\n case 'F' : this.fire(); break;\n case 'L' : this.load(); break;\n case 'S' : this.spin(); break;\n case 'U' : this.unload(); break;\n default: console.error(`Unknown character in method: ${method[x]}`);\n }\n return this.fired;\n }\n }\n}\n\n// simulating\nconst ITERATIONS = 25e4;\nlet methods = 'lslsfsf lslsff llsfsf llsff'.split(' '),\n bodyCount;\nconsole.log(`@ ${ITERATIONS.toLocaleString('en')} iterations:`);\nconsole.log();\nfor (let x = 0; x < methods.length; x++) {\n bodyCount = 0;\n for (let y = 1; y <= ITERATIONS; y++)\n if (new Pistol(methods[x]).exec()) bodyCount++;\n console.log(`${methods[x]}:`);\n console.log(`deaths: ${bodyCount.toLocaleString('en')} (${(bodyCount / ITERATIONS * 100).toPrecision(3)} %) `);\n console.log();\n}\n"} +{"title": "Two bullet roulette", "language": "Python", "task": "The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street:\n\n A revolver handgun has a revolving cylinder with six chambers for bullets.\n \n It is loaded with the following procedure:\n\n 1. Check the first chamber to the right of the trigger for a bullet. If a bullet\n is seen, the cylinder is rotated one chamber clockwise and the next chamber\n checked until an empty chamber is found.\n\n 2. A cartridge containing a bullet is placed in the empty chamber.\n\n 3. The cylinder is then rotated one chamber clockwise.\n \n To randomize the cylinder's position, the cylinder is spun, which causes the cylinder to take\n a random position from 1 to 6 chamber rotations clockwise from its starting position.\n \n When the trigger is pulled the gun will fire if there is a bullet in position 0, which is just\n counterclockwise from the loading position.\n \n The gun is unloaded by removing all cartridges from the cylinder.\n \n According to the legend, a suicidal Russian imperial military officer plays a game of Russian\n roulette by putting two bullets in a six-chamber cylinder and pulls the trigger twice.\n If the gun fires with a trigger pull, this is considered a successful suicide.\n \n The cylinder is always spun before the first shot, but it may or may not be spun after putting\n in the first bullet and may or may not be spun after taking the first shot.\n \n Which of the following situations produces the highest probability of suicide?\n \n A. Spinning the cylinder after loading the first bullet, and spinning again after the first shot.\n\n B. Spinning the cylinder after loading the first bullet only.\n\n C. Spinning the cylinder after firing the first shot only.\n\n D. Not spinning the cylinder either after loading the first bullet or after the first shot.\n\n E. The probability is the same for all cases.\n\n\n;Task:\n# Run a repeated simulation of each of the above scenario, calculating the percentage of suicide with a randomization of the four spinning, loading and firing order scenarios.\n# Show the results as a percentage of deaths for each type of scenario.\n# The hand calculated probabilities are 5/9, 7/12, 5/9, and 1/2. A correct program should produce results close enough to those to allow a correct response to the interview question. \n\n\n;Reference:\nYoutube video on the Russian 1895 Nagant revolver [[https://www.youtube.com/watch?v=Dh1mojMaEtM]]\n\n", "solution": "\"\"\" Russian roulette problem \"\"\"\nimport numpy as np\n\nclass Revolver:\n \"\"\" simulates 6-shot revolving cylinger pistol \"\"\"\n\n def __init__(self):\n \"\"\" start unloaded \"\"\"\n self.cylinder = np.array([False] * 6)\n\n def unload(self):\n \"\"\" empty all chambers of cylinder \"\"\"\n self.cylinder[:] = False\n\n def load(self):\n \"\"\" load a chamber (advance til empty if full already), then advance once \"\"\"\n while self.cylinder[1]:\n self.cylinder[:] = np.roll(self.cylinder, 1)\n self.cylinder[1] = True\n\n def spin(self):\n \"\"\" spin cylinder, randomizing position of chamber to be fired \"\"\"\n self.cylinder[:] = np.roll(self.cylinder, np.random.randint(1, high=7))\n\n def fire(self):\n \"\"\" pull trigger of revolver, return True if fired, False if did not fire \"\"\"\n shot = self.cylinder[0]\n self.cylinder[:] = np.roll(self.cylinder, 1)\n return shot\n\n def LSLSFSF(self):\n \"\"\" load, spin, load, spin, fire, spin, fire \"\"\"\n self.unload()\n self.load()\n self.spin()\n self.load()\n self.spin()\n if self.fire():\n return True\n self.spin()\n if self.fire():\n return True\n return False\n\n def LSLSFF(self):\n \"\"\" load, spin, load, spin, fire, fire \"\"\"\n self.unload()\n self.load()\n self.spin()\n self.load()\n self.spin()\n if self.fire():\n return True\n if self.fire():\n return True\n return False\n\n def LLSFSF(self):\n \"\"\" load, load, spin, fire, spin, fire \"\"\"\n self.unload()\n self.load()\n self.load()\n self.spin()\n if self.fire():\n return True\n self.spin()\n if self.fire():\n return True\n return False\n\n def LLSFF(self):\n \"\"\" load, load, spin, fire, fire \"\"\"\n self.unload()\n self.load()\n self.load()\n self.spin()\n if self.fire():\n return True\n if self.fire():\n return True\n return False\n\n\nif __name__ == '__main__':\n\n REV = Revolver()\n TESTCOUNT = 100000\n for (name, method) in [['load, spin, load, spin, fire, spin, fire', REV.LSLSFSF],\n ['load, spin, load, spin, fire, fire', REV.LSLSFF],\n ['load, load, spin, fire, spin, fire', REV.LLSFSF],\n ['load, load, spin, fire, fire', REV.LLSFF]]:\n\n percentage = 100 * sum([method() for _ in range(TESTCOUNT)]) / TESTCOUNT\n print(\"Method\", name, \"produces\", percentage, \"per cent deaths.\")\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, \u00a0 in this task, \u00a0 we will focus on some of the data format standards, \u00a0 with an imaginary physical+electrical implementation which converts physical UPC bar codes to ASCII \u00a0 (with spaces and \u00a0 '''#''' \u00a0 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, \u00a0 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 \u00a0 (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): \u00a0 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::* \u00a0 It begins with at least 9 spaces \u00a0 (which our imaginary bar code reader unfortunately doesn't always reproduce properly), \n::* \u00a0 then has a \u00a0 \u00a0 ''' # # ''' \u00a0 \u00a0 sequence marking the start of the sequence, \n::* \u00a0 then has the six \"left hand\" digits, \n::* \u00a0 then has a \u00a0 ''' # # ''' \u00a0 sequence in the middle, \n::* \u00a0 then has the six \"right hand digits\", \n::* \u00a0 then has another \u00a0 ''' # # ''' \u00a0 (end sequence), \u00a0 and finally, \n::* \u00a0 then ends with nine trailing spaces \u00a0 (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 \u00a0 (3,1,3,1,3,1,3,1,3,1,3,1) \u00a0 and add the products.\n\nThe sum (mod 10) must be '''0''' \u00a0 (must have a zero as its last digit) \u00a0 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": "UPC", "language": "Python", "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, \u00a0 in this task, \u00a0 we will focus on some of the data format standards, \u00a0 with an imaginary physical+electrical implementation which converts physical UPC bar codes to ASCII \u00a0 (with spaces and \u00a0 '''#''' \u00a0 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, \u00a0 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 \u00a0 (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): \u00a0 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::* \u00a0 It begins with at least 9 spaces \u00a0 (which our imaginary bar code reader unfortunately doesn't always reproduce properly), \n::* \u00a0 then has a \u00a0 \u00a0 ''' # # ''' \u00a0 \u00a0 sequence marking the start of the sequence, \n::* \u00a0 then has the six \"left hand\" digits, \n::* \u00a0 then has a \u00a0 ''' # # ''' \u00a0 sequence in the middle, \n::* \u00a0 then has the six \"right hand digits\", \n::* \u00a0 then has another \u00a0 ''' # # ''' \u00a0 (end sequence), \u00a0 and finally, \n::* \u00a0 then ends with nine trailing spaces \u00a0 (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 \u00a0 (3,1,3,1,3,1,3,1,3,1,3,1) \u00a0 and add the products.\n\nThe sum (mod 10) must be '''0''' \u00a0 (must have a zero as its last digit) \u00a0 if the UPC number has been read correctly.\n\n", "solution": "\"\"\"UPC-A barcode reader. Requires Python =>3.6\"\"\"\nimport itertools\nimport re\n\nRE_BARCODE = re.compile(\n r\"^(?P +)\" # quiet zone\n r\"(?P# #)\" # start guard\n r\"(?P[ #]{42})\" # left digits\n r\"(?P # # )\" # middle guard\n r\"(?P[ #]{42})\" # right digits\n r\"(?P# #)\" # end guard\n r\"(?P +)$\" # quiet zone\n)\n\nLEFT_DIGITS = {\n (0, 0, 0, 1, 1, 0, 1): 0,\n (0, 0, 1, 1, 0, 0, 1): 1,\n (0, 0, 1, 0, 0, 1, 1): 2,\n (0, 1, 1, 1, 1, 0, 1): 3,\n (0, 1, 0, 0, 0, 1, 1): 4,\n (0, 1, 1, 0, 0, 0, 1): 5,\n (0, 1, 0, 1, 1, 1, 1): 6,\n (0, 1, 1, 1, 0, 1, 1): 7,\n (0, 1, 1, 0, 1, 1, 1): 8,\n (0, 0, 0, 1, 0, 1, 1): 9,\n}\n\nRIGHT_DIGITS = {\n (1, 1, 1, 0, 0, 1, 0): 0,\n (1, 1, 0, 0, 1, 1, 0): 1,\n (1, 1, 0, 1, 1, 0, 0): 2,\n (1, 0, 0, 0, 0, 1, 0): 3,\n (1, 0, 1, 1, 1, 0, 0): 4,\n (1, 0, 0, 1, 1, 1, 0): 5,\n (1, 0, 1, 0, 0, 0, 0): 6,\n (1, 0, 0, 0, 1, 0, 0): 7,\n (1, 0, 0, 1, 0, 0, 0): 8,\n (1, 1, 1, 0, 1, 0, 0): 9,\n}\n\n\nMODULES = {\n \" \": 0,\n \"#\": 1,\n}\n\nDIGITS_PER_SIDE = 6\nMODULES_PER_DIGIT = 7\n\n\nclass ParityError(Exception):\n \"\"\"Exception raised when a parity error is found.\"\"\"\n\n\nclass ChecksumError(Exception):\n \"\"\"Exception raised when check digit does not match.\"\"\"\n\n\ndef group(iterable, n):\n \"\"\"Chunk the iterable into groups of size ``n``.\"\"\"\n args = [iter(iterable)] * n\n return tuple(itertools.zip_longest(*args))\n\n\ndef parse(barcode):\n \"\"\"Return the 12 digits represented by the given barcode. Raises a\n ParityError if any digit fails the parity check.\"\"\"\n match = RE_BARCODE.match(barcode)\n\n # Translate bars and spaces to 1s and 0s so we can do arithmetic\n # with them. Group \"modules\" into chunks of 7 as we go.\n left = group((MODULES[c] for c in match.group(\"left\")), MODULES_PER_DIGIT)\n right = group((MODULES[c] for c in match.group(\"right\")), MODULES_PER_DIGIT)\n\n # Parity check\n left, right = check_parity(left, right)\n\n # Lookup digits\n return tuple(\n itertools.chain(\n (LEFT_DIGITS[d] for d in left),\n (RIGHT_DIGITS[d] for d in right),\n )\n )\n\n\ndef check_parity(left, right):\n \"\"\"Check left and right parity. Flip left and right if the barcode\n was scanned upside down.\"\"\"\n # When reading from left to right, each digit on the left should\n # have odd parity, and each digit on the right should have even\n # parity.\n left_parity = sum(sum(d) % 2 for d in left)\n right_parity = sum(sum(d) % 2 for d in right)\n\n # Use left and right parity to check if the barcode was scanned\n # upside down. Flip it if it was.\n if left_parity == 0 and right_parity == DIGITS_PER_SIDE:\n _left = tuple(tuple(reversed(d)) for d in reversed(right))\n right = tuple(tuple(reversed(d)) for d in reversed(left))\n left = _left\n elif left_parity != DIGITS_PER_SIDE or right_parity != 0:\n # Error condition. Mixed parity.\n error = tuple(\n itertools.chain(\n (LEFT_DIGITS.get(d, \"_\") for d in left),\n (RIGHT_DIGITS.get(d, \"_\") for d in right),\n )\n )\n raise ParityError(\" \".join(str(d) for d in error))\n\n return left, right\n\n\ndef checksum(digits):\n \"\"\"Return the check digit for the given digits. Raises a\n ChecksumError if the check digit does not match.\"\"\"\n odds = (digits[i] for i in range(0, 11, 2))\n evens = (digits[i] for i in range(1, 10, 2))\n\n check_digit = (sum(odds) * 3 + sum(evens)) % 10\n\n if check_digit != 0:\n check_digit = 10 - check_digit\n\n if digits[-1] != check_digit:\n raise ChecksumError(str(check_digit))\n\n return check_digit\n\n\ndef main():\n barcodes = [\n \" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # \",\n \" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # \",\n \" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # \",\n \" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # \",\n \" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # \",\n \" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # \",\n \" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # \",\n \" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # \",\n \" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # \",\n \" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # \",\n \" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### ## ## # ### # # \",\n ]\n\n for barcode in barcodes:\n try:\n digits = parse(barcode)\n except ParityError as err:\n print(f\"{err} parity error!\")\n continue\n\n try:\n check_digit = checksum(digits)\n except ChecksumError as err:\n print(f\"{' '.join(str(d) for d in digits)} checksum error! ({err})\")\n continue\n\n print(f\"{' '.join(str(d) for d in digits)}\")\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"title": "URL decoding", "language": "C", "task": "[[Category:String manipulation]]\n\nThis task \u00a0 (the reverse of \u00a0 [[URL encoding]] \u00a0 and distinct from \u00a0 [[URL parser]]) \u00a0 is to provide a function \nor mechanism to convert an URL-encoded string into its original unencoded form.\n\n\n;Test cases:\n* \u00a0 The encoded string \u00a0 \"http%3A%2F%2Ffoo%20bar%2F\" \u00a0 should be reverted to the unencoded form \u00a0 \"http://foo bar/\".\n\n* \u00a0 The encoded string \u00a0 \"google.com/search?q=%60Abdu%27l-Bah%C3%A1\" \u00a0 should revert to the unencoded form \u00a0 \"google.com/search?q=`Abdu'l-Bah\u00e1\".\n\n* \u00a0 The encoded string \u00a0 \"%25%32%35\" \u00a0 should revert to the unencoded form \u00a0 \"%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 decoding", "language": "Python", "task": "[[Category:String manipulation]]\n\nThis task \u00a0 (the reverse of \u00a0 [[URL encoding]] \u00a0 and distinct from \u00a0 [[URL parser]]) \u00a0 is to provide a function \nor mechanism to convert an URL-encoded string into its original unencoded form.\n\n\n;Test cases:\n* \u00a0 The encoded string \u00a0 \"http%3A%2F%2Ffoo%20bar%2F\" \u00a0 should be reverted to the unencoded form \u00a0 \"http://foo bar/\".\n\n* \u00a0 The encoded string \u00a0 \"google.com/search?q=%60Abdu%27l-Bah%C3%A1\" \u00a0 should revert to the unencoded form \u00a0 \"google.com/search?q=`Abdu'l-Bah\u00e1\".\n\n* \u00a0 The encoded string \u00a0 \"%25%32%35\" \u00a0 should revert to the unencoded form \u00a0 \"%25\" and '''not''' \"%\".\n\n", "solution": "\n#Python 2.X\nimport urllib\nprint urllib.unquote(\"http%3A%2F%2Ffoo%20bar%2F\")\n#Python 3.5+\nfrom urllib.parse import unquote\nprint(unquote('http%3A%2F%2Ffoo%20bar%2F'))\n"} +{"title": "URL encoding", "language": "C", "task": "[[Category:String manipulation]]\n[[Category: Encodings]]\n\n;Task:\nProvide 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 [http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#url-encoded-form-data 4.10.22.5 URL-encoded form data], says to preserve \"-._*\", and to encode space \" \" to \"+\".\n** [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI#description 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* \u00a0 [[URL decoding]]\n* \u00a0 [[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": "URL encoding", "language": "JavaScript", "task": "[[Category:String manipulation]]\n[[Category: Encodings]]\n\n;Task:\nProvide 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 [http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#url-encoded-form-data 4.10.22.5 URL-encoded form data], says to preserve \"-._*\", and to encode space \" \" to \"+\".\n** [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI#description 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* \u00a0 [[URL decoding]]\n* \u00a0 [[URL parser]]\n\n", "solution": "var normal = 'http://foo/bar/';\nvar encoded = encodeURIComponent(normal);"} +{"title": "URL encoding", "language": "Python", "task": "[[Category:String manipulation]]\n[[Category: Encodings]]\n\n;Task:\nProvide 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 [http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#url-encoded-form-data 4.10.22.5 URL-encoded form data], says to preserve \"-._*\", and to encode space \" \" to \"+\".\n** [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI#description 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* \u00a0 [[URL decoding]]\n* \u00a0 [[URL parser]]\n\n", "solution": "import urllib\ns = 'http://foo/bar/'\ns = urllib.quote(s)"} +{"title": "URL parser", "language": "JavaScript", "task": "[[Category:String manipulation]]\n[[Category:Parser]]\n\nURLs are strings with a simple syntax:\n scheme://[username:password@]domain[:port]/path?query_string#fragment_id\n\n\n;Task:\nParse a well-formed URL to retrieve the relevant information: \u00a0 '''scheme''', '''domain''', '''path''', ...\n\n\nNote: \u00a0 this task has nothing to do with [[URL encoding]] or [[URL decoding]].\n\n\nAccording to the standards, the characters:\n:::: \u00a0 ! * ' ( ) ; : @ & = + $ , / ? % # [ ] \nonly need to be percent-encoded \u00a0 ('''%''') \u00a0 in case of possible confusion. \n\nAlso note that the '''path''', '''query''' and '''fragment''' are case sensitive, even if the '''scheme''' and '''domain''' are not.\n\nThe way the returned information is provided (set of variables, array, structured, record, object,...) \nis language-dependent and left to the programmer, but the code should be clear enough to reuse.\n\nExtra credit is given for clear error diagnostics.\n\n* \u00a0 Here is the official standard: \u00a0 \u00a0 https://tools.ietf.org/html/rfc3986, \n* \u00a0 and here is a simpler \u00a0 BNF: \u00a0 \u00a0 http://www.w3.org/Addressing/URL/5_URI_BNF.html.\n\n\n;Test cases:\nAccording to T. Berners-Lee\n \n'''foo://example.com:8042/over/there?name=ferret#nose''' \u00a0 \u00a0 should parse into:\n::* \u00a0 scheme = foo\n::* \u00a0 domain = example.com\n::* \u00a0 port = :8042\n::* \u00a0 path = over/there\n::* \u00a0 query = name=ferret\n::* \u00a0 fragment = nose\n\n\n'''urn:example:animal:ferret:nose''' \u00a0 \u00a0 should parse into:\n::* \u00a0 scheme = urn\n::* \u00a0 path = example:animal:ferret:nose\n\n\n'''other URLs that must be parsed include:'''\n:* \u00a0 jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true \n:* \u00a0 ftp://ftp.is.co.za/rfc/rfc1808.txt \n:* \u00a0 http://www.ietf.org/rfc/rfc2396.txt#header1 \n:* \u00a0 ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two \n:* \u00a0 mailto:John.Doe@example.com \n:* \u00a0 news:comp.infosystems.www.servers.unix \n:* \u00a0 tel:+1-816-555-1212 \n:* \u00a0 telnet://192.0.2.16:80/ \n:* \u00a0 urn:oasis:names:specification:docbook:dtd:xml:4.1.2 \n\n", "solution": "[\n {\n \"hash\": \"#nose\",\n \"host\": \"example.com:8042\",\n \"hostname\": \"example.com\",\n \"origin\": \"foo://example.com:8042\",\n \"pathname\": \"/over/there\",\n \"port\": \"8042\",\n \"protocol\": \"foo:\",\n \"search\": \"?name=ferret\"\n },\n {\n \"hash\": \"\",\n \"host\": \"\",\n \"hostname\": \"\",\n \"origin\": \"urn://\",\n \"pathname\": \"example:animal:ferret:nose\",\n \"port\": \"\",\n \"protocol\": \"urn:\",\n \"search\": \"\"\n },\n {\n \"hash\": \"\",\n \"host\": \"\",\n \"hostname\": \"\",\n \"origin\": \"jdbc://\",\n \"pathname\": \"mysql://test_user:ouupppssss@localhost:3306/sakila\",\n \"port\": \"\",\n \"protocol\": \"jdbc:\",\n \"search\": \"?profileSQL=true\"\n },\n {\n \"hash\": \"\",\n \"host\": \"ftp.is.co.za\",\n \"hostname\": \"ftp.is.co.za\",\n \"origin\": \"ftp://ftp.is.co.za\",\n \"pathname\": \"/rfc/rfc1808.txt\",\n \"port\": \"\",\n \"protocol\": \"ftp:\",\n \"search\": \"\"\n },\n {\n \"hash\": \"#header1\",\n \"host\": \"www.ietf.org\",\n \"hostname\": \"www.ietf.org\",\n \"origin\": \"http://www.ietf.org\",\n \"pathname\": \"/rfc/rfc2396.txt\",\n \"port\": \"\",\n \"protocol\": \"http:\",\n \"search\": \"\"\n },\n {\n \"hash\": \"\",\n \"host\": \"[2001:db8::7]\",\n \"hostname\": \"[2001:db8::7]\",\n \"origin\": \"ldap://[2001:db8::7]\",\n \"pathname\": \"/c=GB\",\n \"port\": \"\",\n \"protocol\": \"ldap:\",\n \"search\": \"?objectClass=one&objectClass=two\"\n },\n {\n \"hash\": \"\",\n \"host\": \"\",\n \"hostname\": \"\",\n \"origin\": \"mailto://\",\n \"pathname\": \"John.Doe@example.com\",\n \"port\": \"\",\n \"protocol\": \"mailto:\",\n \"search\": \"\"\n },\n {\n \"hash\": \"\",\n \"host\": \"\",\n \"hostname\": \"\",\n \"origin\": \"news://\",\n \"pathname\": \"comp.infosystems.www.servers.unix\",\n \"port\": \"\",\n \"protocol\": \"news:\",\n \"search\": \"\"\n },\n {\n \"hash\": \"\",\n \"host\": \"\",\n \"hostname\": \"\",\n \"origin\": \"tel://\",\n \"pathname\": \"+1-816-555-1212\",\n \"port\": \"\",\n \"protocol\": \"tel:\",\n \"search\": \"\"\n },\n {\n \"hash\": \"\",\n \"host\": \"192.0.2.16:80\",\n \"hostname\": \"192.0.2.16\",\n \"origin\": \"telnet://192.0.2.16:80\",\n \"pathname\": \"/\",\n \"port\": \"80\",\n \"protocol\": \"telnet:\",\n \"search\": \"\"\n },\n {\n \"hash\": \"\",\n \"host\": \"\",\n \"hostname\": \"\",\n \"origin\": \"urn://\",\n \"pathname\": \"oasis:names:specification:docbook:dtd:xml:4.1.2\",\n \"port\": \"\",\n \"protocol\": \"urn:\",\n \"search\": \"\"\n },\n {\n \"hash\": \"\",\n \"host\": \"example.com\",\n \"hostname\": \"example.com\",\n \"origin\": \"ssh://example.com\",\n \"pathname\": \"\",\n \"port\": \"\",\n \"protocol\": \"ssh:\",\n \"search\": \"\"\n },\n {\n \"hash\": \"\",\n \"host\": \"example.com\",\n \"hostname\": \"example.com\",\n \"origin\": \"https://example.com\",\n \"pathname\": \"/place\",\n \"port\": \"\",\n \"protocol\": \"https:\",\n \"search\": \"\"\n },\n {\n \"hash\": \"\",\n \"host\": \"example.com\",\n \"hostname\": \"example.com\",\n \"origin\": \"http://example.com\",\n \"pathname\": \"/\",\n \"port\": \"\",\n \"protocol\": \"http:\",\n \"search\": \"?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64\"\n }\n]"} +{"title": "URL parser", "language": "Python", "task": "[[Category:String manipulation]]\n[[Category:Parser]]\n\nURLs are strings with a simple syntax:\n scheme://[username:password@]domain[:port]/path?query_string#fragment_id\n\n\n;Task:\nParse a well-formed URL to retrieve the relevant information: \u00a0 '''scheme''', '''domain''', '''path''', ...\n\n\nNote: \u00a0 this task has nothing to do with [[URL encoding]] or [[URL decoding]].\n\n\nAccording to the standards, the characters:\n:::: \u00a0 ! * ' ( ) ; : @ & = + $ , / ? % # [ ] \nonly need to be percent-encoded \u00a0 ('''%''') \u00a0 in case of possible confusion. \n\nAlso note that the '''path''', '''query''' and '''fragment''' are case sensitive, even if the '''scheme''' and '''domain''' are not.\n\nThe way the returned information is provided (set of variables, array, structured, record, object,...) \nis language-dependent and left to the programmer, but the code should be clear enough to reuse.\n\nExtra credit is given for clear error diagnostics.\n\n* \u00a0 Here is the official standard: \u00a0 \u00a0 https://tools.ietf.org/html/rfc3986, \n* \u00a0 and here is a simpler \u00a0 BNF: \u00a0 \u00a0 http://www.w3.org/Addressing/URL/5_URI_BNF.html.\n\n\n;Test cases:\nAccording to T. Berners-Lee\n \n'''foo://example.com:8042/over/there?name=ferret#nose''' \u00a0 \u00a0 should parse into:\n::* \u00a0 scheme = foo\n::* \u00a0 domain = example.com\n::* \u00a0 port = :8042\n::* \u00a0 path = over/there\n::* \u00a0 query = name=ferret\n::* \u00a0 fragment = nose\n\n\n'''urn:example:animal:ferret:nose''' \u00a0 \u00a0 should parse into:\n::* \u00a0 scheme = urn\n::* \u00a0 path = example:animal:ferret:nose\n\n\n'''other URLs that must be parsed include:'''\n:* \u00a0 jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true \n:* \u00a0 ftp://ftp.is.co.za/rfc/rfc1808.txt \n:* \u00a0 http://www.ietf.org/rfc/rfc2396.txt#header1 \n:* \u00a0 ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two \n:* \u00a0 mailto:John.Doe@example.com \n:* \u00a0 news:comp.infosystems.www.servers.unix \n:* \u00a0 tel:+1-816-555-1212 \n:* \u00a0 telnet://192.0.2.16:80/ \n:* \u00a0 urn:oasis:names:specification:docbook:dtd:xml:4.1.2 \n\n", "solution": "import urllib.parse as up # urlparse for Python v2\n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1#fragment')\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\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\u20134 bytes representing that character in the UTF-8 encoding. \n\nThen you have to write the corresponding decoder that takes a sequence of 1\u20134 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\n\u00f6 LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6\n\u0416 CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96\n\u20ac EURO SIGN U+20AC E2 82 AC\n\ud834\udd1e MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E\n\n\nProvided below is a reference implementation in Common Lisp.\n\n", "solution": "\n#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": "UTF-8 encode and decode", "language": "JavaScript", "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\u20134 bytes representing that character in the UTF-8 encoding. \n\nThen you have to write the corresponding decoder that takes a sequence of 1\u20134 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\n\u00f6 LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6\n\u0416 CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96\n\u20ac EURO SIGN U+20AC E2 82 AC\n\ud834\udd1e MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E\n\n\nProvided below is a reference implementation in Common Lisp.\n\n", "solution": "\n/***************************************************************************\\\n|* Pure UTF-8 handling without detailed error reporting functionality. *|\n|***************************************************************************|\n|* utf8encode *|\n|* < String character or UInt32 code point *|\n|* > Uint8Array encoded_character *|\n|* | ErrorString *|\n|* *|\n|* utf8encode takes a string or uint32 representing a single code point *|\n|* as its argument and returns an array of length 1 up to 4 containing *|\n|* utf8 code units representing that character. *|\n|***************************************************************************|\n|* utf8decode *|\n|* < Unit8Array [highendbyte highmidendbyte lowmidendbyte lowendbyte] *|\n|* > uint32 character *|\n|* | ErrorString *|\n|* *|\n|* utf8decode takes an array of one to four uint8 representing utf8 code *|\n|* units and returns a uint32 representing that code point. *|\n\\***************************************************************************/\n\nconst\n utf8encode=\n n=>\n (m=>\n m<0x80\n ?Uint8Array.from(\n [ m>>0&0x7f|0x00])\n :m<0x800\n ?Uint8Array.from(\n [ m>>6&0x1f|0xc0,m>>0&0x3f|0x80])\n :m<0x10000\n ?Uint8Array.from(\n [ m>>12&0x0f|0xe0,m>>6&0x3f|0x80,m>>0&0x3f|0x80])\n :m<0x110000\n ?Uint8Array.from(\n [ m>>18&0x07|0xf0,m>>12&0x3f|0x80,m>>6&0x3f|0x80,m>>0&0x3f|0x80])\n :(()=>{throw'Invalid Unicode Code Point!'})())\n ( typeof n==='string'\n ?n.codePointAt(0)\n :n&0x1fffff),\n utf8decode=\n ([m,n,o,p])=>\n m<0x80\n ?( m&0x7f)<<0\n :0xc1{throw'Invalid UTF-8 encoding!'})()\n"} +{"title": "UTF-8 encode and decode", "language": "Python", "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\u20134 bytes representing that character in the UTF-8 encoding. \n\nThen you have to write the corresponding decoder that takes a sequence of 1\u20134 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\n\u00f6 LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6\n\u0416 CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96\n\u20ac EURO SIGN U+20AC E2 82 AC\n\ud834\udd1e MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E\n\n\nProvided below is a reference implementation in Common Lisp.\n\n", "solution": "\n#!/usr/bin/env python3\nfrom unicodedata import name\n\n\ndef unicode_code(ch):\n return 'U+{:04x}'.format(ord(ch))\n\n\ndef utf8hex(ch):\n return \" \".join([hex(c)[2:] for c in ch.encode('utf8')]).upper()\n\n\nif __name__ == \"__main__\":\n print('{:<11} {:<36} {:<15} {:<15}'.format('Character', 'Name', 'Unicode', 'UTF-8 encoding (hex)'))\n chars = ['A', '\u00f6', '\u0416', '\u20ac', '\ud834\udd1e']\n for char in chars:\n print('{:<11} {:<36} {:<15} {:<15}'.format(char, name(char), unicode_code(char), utf8hex(char)))"} +{"title": "Ultra useful primes", "language": "C", "task": "An '''ultra-useful prime''' is a member of the sequence where each '''a(n)''' is the smallest positive integer '''k''' such that '''2(2n) - k''' is prime.\n\n'''''k''' must always be an odd number since 2 to any power is always even.''\n\n\n;Task\n\n* Find and show here, on this page, the first '''10''' elements of the sequence.\n\n\n;Stretch \n\n* Find and show the next several elements. (The numbers get really big really fast. Only nineteen elements have been identified as of this writing.)\n\n\n;See also\n\n* OEIS:A058220 - Ultra-useful primes: smallest k such that 2^(2^n) - k is prime\n \n\n", "solution": "#include \n#include \n\nint a(unsigned int n) {\n int k;\n mpz_t p;\n mpz_init_set_ui(p, 1);\n mpz_mul_2exp(p, p, 1 << n);\n mpz_sub_ui(p, p, 1);\n for (k = 1; ; k += 2) {\n if (mpz_probab_prime_p(p, 15) > 0) return k;\n mpz_sub_ui(p, p, 2);\n }\n}\n\nint main() {\n unsigned int n;\n printf(\" n k\\n\");\n printf(\"----------\\n\");\n for (n = 1; n < 15; ++n) printf(\"%2d %d\\n\", n, a(n));\n return 0;\n}"} +{"title": "Unbias a random generator", "language": "C", "task": ";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 [http://en.wikipedia.org/wiki/Randomness_extractor#Von_Neumann_extractor 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": "Unbias a random generator", "language": "Python", "task": ";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 [http://en.wikipedia.org/wiki/Randomness_extractor#Von_Neumann_extractor Von Neumann debiasing], first described in a 1951 paper.\n\n", "solution": "from __future__ import print_function\nimport random\n\ndef randN(N):\n \" 1,0 random generator factory with 1 appearing 1/N'th of the time\"\n return lambda: random.randrange(N) == 0\n\ndef unbiased(biased):\n 'uses a biased() generator of 1 or 0, to create an unbiased one'\n this, that = biased(), biased()\n while this == that: # Loop until 10 or 01\n this, that = biased(), biased()\n return this # return the first\n\nif __name__ == '__main__':\n from collections import namedtuple\n\n Stats = namedtuple('Stats', 'count1 count0 percent')\n\n for N in range(3, 7):\n biased = randN(N)\n v = [biased() for x in range(1000000)]\n v1, v0 = v.count(1), v.count(0)\n print ( \"Biased(%i) = %r\" % (N, Stats(v1, v0, 100. * v1/(v1 + v0))) )\n\n v = [unbiased(biased) for x in range(1000000)]\n v1, v0 = v.count(1), v.count(0)\n print ( \" Unbiased = %r\" % (Stats(v1, v0, 100. * v1/(v1 + v0)), ) )"} +{"title": "Unicode strings", "language": "C", "task": "As the world gets smaller each day, internationalization becomes more and more important. \u00a0 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:* \u00a0 How easy is it to present Unicode strings in source code? \n:* \u00a0 Can Unicode literals be written directly, or be part of identifiers/keywords/etc?\n:* \u00a0 How well can the language communicate with the rest of the world? \n:* \u00a0 Is it good at input/output with Unicode?\n:* \u00a0 Is it convenient to manipulate Unicode strings in the language?\n:* \u00a0 How broad/deep does the language support Unicode? \n:* \u00a0 What encodings (e.g. UTF-8, UTF-16, etc) can be used? \n:* \u00a0 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* \u00a0 [[Unicode variable names]]\n* \u00a0 [[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": "Unicode strings", "language": "Python", "task": "As the world gets smaller each day, internationalization becomes more and more important. \u00a0 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:* \u00a0 How easy is it to present Unicode strings in source code? \n:* \u00a0 Can Unicode literals be written directly, or be part of identifiers/keywords/etc?\n:* \u00a0 How well can the language communicate with the rest of the world? \n:* \u00a0 Is it good at input/output with Unicode?\n:* \u00a0 Is it convenient to manipulate Unicode strings in the language?\n:* \u00a0 How broad/deep does the language support Unicode? \n:* \u00a0 What encodings (e.g. UTF-8, UTF-16, etc) can be used? \n:* \u00a0 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* \u00a0 [[Unicode variable names]]\n* \u00a0 [[Terminal control/Display an extended character]]\n\n", "solution": "#!/usr/bin/env python\n# -*- coding: latin-1 -*-\n\nu = 'abcd\u00e9'\nprint(ord(u[-1]))"} +{"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\u20131937.)\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": "Universal Turing machine", "language": "FireFox", "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\u20131937.)\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": "function tm(d,s,e,i,b,t,... r) {\n\tdocument.write(d, '')\n\tif (i<0||i>=t.length) return\n\tvar re=new RegExp(b,'g')\n\twrite('*',s,i,t=t.split(''))\n\tvar p={}; r.forEach(e=>((s,r,w,m,n)=>{p[s+'.'+r]={w,n,m:[0,1,-1][1+'RL'.indexOf(m)]}})(... e.split(/[ .:,]+/)))\n\tfor (var n=1; s!=e; n+=1) {\n\t\twith (p[s+'.'+t[i]]) t[i]=w,s=n,i+=m\n\t\tif (i==-1) i=0,t.unshift(b)\n\t\telse if (i==t.length) t[i]=b\n\t\twrite(n,s,i,t)\n\t}\n\tdocument.write('')\n\tfunction write(n, s, i, t) {\n\t\tt = t.join('')\n\t\tt = t.substring(0,i) + '' + t.charAt(i) + '' + t.substr(i+1)\n\t\tdocument.write((' '+n).slice(-3).replace(/ /g,'\u00a0'), ': ', s, ' [', t.replace(re,'\u00a0'), ']', '')\n\t}\n}\n\ntm( 'Unary incrementer',\n//\t s e i b t\n\t'a', 'h', 0, 'B', '111',\n//\t s.r: w, m, n\n\t'a.1: 1, L, a',\n\t'a.B: 1, S, h'\n)\n\ntm( 'Unary adder',\n\t1, 0, 0, '0', '1110111',\n\t'1.1: 0, R, 2', // write 0 rigth goto 2\n\t'2.1: 1, R, 2', // while (1) rigth\n\t'2.0: 1, S, 0' // write 1 stay halt\n)\n\ntm( 'Three-state busy beaver',\n\t1, 0, 0, '0', '0',\n\t'1.0: 1, R, 2',\n\t'1.1: 1, R, 0',\n\t'2.0: 0, R, 3',\n\t'2.1: 1, R, 2',\n\t'3.0: 1, L, 3',\n\t'3.1: 1, L, 1'\n)"} +{"title": "Universal Turing machine", "language": "Python", "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\u20131937.)\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": "from __future__ import print_function\n\ndef run_utm(\n state = None,\n blank = None,\n rules = [],\n tape = [],\n halt = None,\n pos = 0):\n st = state\n if not tape: tape = [blank]\n if pos < 0: pos += len(tape)\n if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n while True:\n print(st, '\\t', end=\" \")\n for i, v in enumerate(tape):\n if i == pos: print(\"[%s]\" % (v,), end=\" \")\n else: print(v, end=\" \")\n print()\n\n if st == halt: break\n if (st, tape[pos]) not in rules: break\n\n (v1, dr, s1) = rules[(st, tape[pos])]\n tape[pos] = v1\n if dr == 'left':\n if pos > 0: pos -= 1\n else: tape.insert(0, blank)\n if dr == 'right':\n pos += 1\n if pos >= len(tape): tape.append(blank) \n st = s1\n \n\n# EXAMPLES\n \nprint(\"incr machine\\n\")\nrun_utm(\n halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n [\"q0 1 1 right q0\".split(),\n\t\t \"q0 B 1 stay qf\".split()]\n )\n )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n [\"a 0 1 right b\".split(),\n \"a 1 1 left c\".split(),\n \"b 0 1 left a\".split(),\n \"b 1 1 right b\".split(),\n \"c 0 1 left b\".split(),\n \"c 1 1 stay halt\".split()]\n )\n )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left C\".split(),\n\t\t\"C 1 2 left D\".split(),\n\t\t\"C 2 2 left C\".split(),\n\t\t\"C 3 2 left E\".split(),\n\t\t\"D 1 1 left D\".split(),\n\t\t\"D 2 2 left D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n )\n )\n"} +{"title": "Unix/ls", "language": "C", "task": ";Task:\nWrite a program that will list everything in the current folder, \u00a0 similar to:\n:::* \u00a0 the Unix utility \u00a0 \u201cls\u201d \u00a0 [http://man7.org/linux/man-pages/man1/ls.1.html] \u00a0 \u00a0 \u00a0 or \n:::* \u00a0 the Windows terminal command \u00a0 \u201cDIR\u201d \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 \u00a0 `/foo`, \u00a0 it should print:\n\nbar\n\nand when the program is executed in \u00a0 `/foo/bar`, \u00a0 it should print:\n\n1\n2\na\nb\n\n\n", "solution": "\n#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": "Unix/ls", "language": "Python", "task": ";Task:\nWrite a program that will list everything in the current folder, \u00a0 similar to:\n:::* \u00a0 the Unix utility \u00a0 \u201cls\u201d \u00a0 [http://man7.org/linux/man-pages/man1/ls.1.html] \u00a0 \u00a0 \u00a0 or \n:::* \u00a0 the Windows terminal command \u00a0 \u201cDIR\u201d \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 \u00a0 `/foo`, \u00a0 it should print:\n\nbar\n\nand when the program is executed in \u00a0 `/foo/bar`, \u00a0 it should print:\n\n1\n2\na\nb\n\n\n", "solution": ">>> import os\n>>> print('\\n'.join(sorted(os.listdir('.'))))\nDLLs\nDoc\nLICENSE.txt\nLib\nNEWS.txt\nREADME.txt\nScripts\nTools\ninclude\nlibs\npython.exe\npythonw.exe\ntcl\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, \u00a0 ''and'' \u00a0 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\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 a 2-character ISO country code (A-Z)\n\u2502\u00a0\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 a 9-character security code (A-Z, 0-9)\n\u2502\u00a0\u2502\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u250c\u2500\u2500 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 \u21921030000033311635103.\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 \u00a0 \u2500\u2500\u2500 \u00a0 you can just call the existing function from that task. \u00a0 (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. \u00a0 Your function should simply return a Boolean result. \u00a0 See [[#Raku]] for a reference solution.)\n\n\nRelated task:\n* [[Luhn test of credit card numbers]]\n\n\n;Also see:\n* [https://www.isincodes.net/validate-isin/ 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": "Validate International Securities Identification Number", "language": "Python", "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, \u00a0 ''and'' \u00a0 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\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 a 2-character ISO country code (A-Z)\n\u2502\u00a0\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 a 9-character security code (A-Z, 0-9)\n\u2502\u00a0\u2502\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u250c\u2500\u2500 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 \u21921030000033311635103.\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 \u00a0 \u2500\u2500\u2500 \u00a0 you can just call the existing function from that task. \u00a0 (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. \u00a0 Your function should simply return a Boolean result. \u00a0 See [[#Raku]] for a reference solution.)\n\n\nRelated task:\n* [[Luhn test of credit card numbers]]\n\n\n;Also see:\n* [https://www.isincodes.net/validate-isin/ Interactive online ISIN validator]\n* Wikipedia article: International Securities Identification Number\n\n", "solution": "def check_isin(a):\n if len(a) != 12 or not all(c.isalpha() for c in a[:2]) or not all(c.isalnum() for c in a[2:]):\n return False\n s = \"\".join(str(int(c, 36)) for c in a)\n return 0 == (sum(sum(divmod(2 * (ord(c) - 48), 10)) for c in s[-2::-2]) +\n sum(ord(c) - 48 for c in s[::-2])) % 10\n\n# A more readable version \ndef check_isin_alt(a):\n if len(a) != 12:\n return False\n s = []\n for i, c in enumerate(a):\n if c.isdigit():\n if i < 2:\n return False\n s.append(ord(c) - 48)\n elif c.isupper():\n if i == 11:\n return False\n s += divmod(ord(c) - 55, 10)\n else:\n return False\n v = sum(s[::-2])\n for k in s[-2::-2]:\n k = 2 * k\n v += k - 9 if k > 9 else k\n return v % 10 == 0\n\n[check_isin(s) for s in [\"US0378331005\", \"US0373831005\", \"U50378331005\", \"US03378331005\",\n \"AU0000XVGZA3\", \"AU0000VXGZA3\", \"FR0000988040\"]]\n\n# [True, False, False, False, True, True, True]"} +{"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* [https://www.youtube.com/watch?v=etMJxB-igrc 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 Eck sequence", "language": "JavaScript", "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* [https://www.youtube.com/watch?v=etMJxB-igrc Don't Know (the Van Eck Sequence) - Numberphile video].\n* Wikipedia Article: Van Eck's Sequence.\n* OEIS sequence: A181391.\n\n", "solution": "(() => {\n 'use strict';\n\n // vanEck :: Int -> [Int]\n const vanEck = n =>\n reverse(\n churchNumeral(n)(\n xs => 0 < xs.length ? cons(\n maybe(\n 0, succ,\n elemIndex(xs[0], xs.slice(1))\n ),\n xs\n ) : [0]\n )([])\n );\n\n // TEST -----------------------------------------------\n const main = () => {\n console.log('VanEck series:\\n')\n showLog('First 10 terms', vanEck(10))\n showLog('Terms 991-1000', vanEck(1000).slice(990))\n };\n\n // GENERIC FUNCTIONS ----------------------------------\n\n // Just :: a -> Maybe a\n const Just = x => ({\n type: 'Maybe',\n Nothing: false,\n Just: x\n });\n\n // Nothing :: Maybe a\n const Nothing = () => ({\n type: 'Maybe',\n Nothing: true,\n });\n\n // churchNumeral :: Int -> (a -> a) -> a -> a\n const churchNumeral = n => f => x =>\n Array.from({\n length: n\n }, () => f)\n .reduce((a, g) => g(a), x)\n\n // cons :: a -> [a] -> [a]\n const cons = (x, xs) => [x].concat(xs)\n\n // elemIndex :: Eq a => a -> [a] -> Maybe Int\n const elemIndex = (x, xs) => {\n const i = xs.indexOf(x);\n return -1 === i ? (\n Nothing()\n ) : Just(i);\n };\n\n // maybe :: b -> (a -> b) -> Maybe a -> b\n const maybe = (v, f, m) =>\n m.Nothing ? v : f(m.Just);\n\n // reverse :: [a] -> [a]\n const reverse = xs =>\n 'string' !== typeof xs ? (\n xs.slice(0).reverse()\n ) : xs.split('').reverse().join('');\n\n // showLog :: a -> IO ()\n const showLog = (...args) =>\n console.log(\n args\n .map(JSON.stringify)\n .join(' -> ')\n );\n\n // succ :: Int -> Int\n const succ = x => 1 + x;\n\n // MAIN ---\n return main();\n})();"} +{"title": "Van Eck sequence", "language": "Python", "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* [https://www.youtube.com/watch?v=etMJxB-igrc Don't Know (the Van Eck Sequence) - Numberphile video].\n* Wikipedia Article: Van Eck's Sequence.\n* OEIS sequence: A181391.\n\n", "solution": "def van_eck():\n n, seen, val = 0, {}, 0\n while True:\n yield val\n last = {val: n}\n val = n - seen.get(val, n)\n seen.update(last)\n n += 1\n#%%\nif __name__ == '__main__':\n print(\"Van Eck: first 10 terms: \", list(islice(van_eck(), 10)))\n print(\"Van Eck: terms 991 - 1000:\", list(islice(van_eck(), 1000))[-10:])"} +{"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 \u201cpoint\u201d, 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* [http://www.puc-rio.br/marco.ind/quasi_mc.html#low_discrep 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": "Van der Corput sequence", "language": "Python", "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 \u201cpoint\u201d, 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* [http://www.puc-rio.br/marco.ind/quasi_mc.html#low_discrep The Basic Low Discrepancy Sequences]\n* [[Non-decimal radices/Convert]]\n* Van der Corput sequence\n\n", "solution": ">>> [vdc(i) for i in range(10)]\n[0, 0.5, 0.25, 0.75, 0.125, 0.625, 0.375, 0.875, 0.0625, 0.5625]\n>>> [vdc(i, 3) for i in range(10)]\n[0, 0.3333333333333333, 0.6666666666666666, 0.1111111111111111, 0.4444444444444444, 0.7777777777777777, 0.2222222222222222, 0.5555555555555556, 0.8888888888888888, 0.037037037037037035]\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": "Variable declaration reset", "language": "Python", "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": "\ns = [1, 2, 2, 3, 4, 4, 5]\n \nfor i in range(len(s)):\n curr = s[i]\n if i > 0 and curr == prev:\n print(i)\n prev = curr\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: \u00a0 (X, Y, Z). \n\nIf you imagine a graph with the \u00a0 '''x''' \u00a0 and \u00a0 '''y''' \u00a0 axis being at right angles to each other and having a third, \u00a0 '''z''' \u00a0 axis coming out of the page, then a triplet of numbers, \u00a0 (X, Y, Z) \u00a0 would represent a point in the region, \u00a0 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''' \u00a0 \u00a0 \u00a0 (a scalar quantity)\n:::: A \u2022 B = a1b1 \u00a0 + \u00a0 a2b2 \u00a0 + \u00a0 a3b3 \n* '''The cross product''' \u00a0 \u00a0 \u00a0 (a vector quantity)\n:::: A x B = (a2b3\u00a0 - \u00a0 a3b2, \u00a0 \u00a0 a3b1 \u00a0 - \u00a0 a1b3, \u00a0 \u00a0 a1b2 \u00a0 - \u00a0 a2b1) \n* '''The scalar triple product''' \u00a0 \u00a0 \u00a0 (a scalar quantity)\n:::: A \u2022 (B x C) \n* '''The vector triple product''' \u00a0 \u00a0 \u00a0 (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 \u2022 b\n# Compute and display: a x b\n# Compute and display: a \u2022 (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* \u00a0 A starting page on Wolfram MathWorld is \u00a0 {{Wolfram|Vector|Multiplication}}.\n* \u00a0 Wikipedia \u00a0 dot product. \n* \u00a0 Wikipedia \u00a0 cross product. \n* \u00a0 Wikipedia \u00a0 triple product.\n\n\n;Related tasks:\n* \u00a0 [[Dot product]]\n* \u00a0 [[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": "Vector products", "language": "JavaScript", "task": "A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: \u00a0 (X, Y, Z). \n\nIf you imagine a graph with the \u00a0 '''x''' \u00a0 and \u00a0 '''y''' \u00a0 axis being at right angles to each other and having a third, \u00a0 '''z''' \u00a0 axis coming out of the page, then a triplet of numbers, \u00a0 (X, Y, Z) \u00a0 would represent a point in the region, \u00a0 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''' \u00a0 \u00a0 \u00a0 (a scalar quantity)\n:::: A \u2022 B = a1b1 \u00a0 + \u00a0 a2b2 \u00a0 + \u00a0 a3b3 \n* '''The cross product''' \u00a0 \u00a0 \u00a0 (a vector quantity)\n:::: A x B = (a2b3\u00a0 - \u00a0 a3b2, \u00a0 \u00a0 a3b1 \u00a0 - \u00a0 a1b3, \u00a0 \u00a0 a1b2 \u00a0 - \u00a0 a2b1) \n* '''The scalar triple product''' \u00a0 \u00a0 \u00a0 (a scalar quantity)\n:::: A \u2022 (B x C) \n* '''The vector triple product''' \u00a0 \u00a0 \u00a0 (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 \u2022 b\n# Compute and display: a x b\n# Compute and display: a \u2022 (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* \u00a0 A starting page on Wolfram MathWorld is \u00a0 {{Wolfram|Vector|Multiplication}}.\n* \u00a0 Wikipedia \u00a0 dot product. \n* \u00a0 Wikipedia \u00a0 cross product. \n* \u00a0 Wikipedia \u00a0 triple product.\n\n\n;Related tasks:\n* \u00a0 [[Dot product]]\n* \u00a0 [[Quaternion type]]\n\n", "solution": "function dotProduct() {\n var len = arguments[0] && arguments[0].length;\n var argsLen = arguments.length;\n var i, j = len;\n var prod, sum = 0;\n \n // If no arguments supplied, return undefined\n if (!len) {\n return;\n }\n \n // If all vectors not same length, return undefined\n i = argsLen;\n while (i--) {\n \n if (arguments[i].length != len) {\n return; // return undefined\n }\n }\n \n // Sum terms\n while (j--) {\n i = argsLen;\n prod = 1;\n \n while (i--) {\n prod *= arguments[i][j];\n }\n sum += prod;\n }\n return sum;\n}\n\nfunction crossProduct(a, b) {\n\n // Check lengths\n if (a.length != 3 || b.length != 3) {\n return;\n }\n \n return [a[1]*b[2] - a[2]*b[1],\n a[2]*b[0] - a[0]*b[2],\n a[0]*b[1] - a[1]*b[0]];\n \n}\n\nfunction scalarTripleProduct(a, b, c) {\n return dotProduct(a, crossProduct(b, c));\n}\n\nfunction vectorTripleProduct(a, b, c) {\n return crossProduct(a, crossProduct(b, c));\n}\n\n// Run tests\n(function () {\n var a = [3, 4, 5];\n var b = [4, 3, 5];\n var c = [-5, -12, -13];\n \n alert(\n 'A . B: ' + dotProduct(a, b) +\n '\\n' +\n 'A x B: ' + crossProduct(a, b) +\n '\\n' +\n 'A . (B x C): ' + scalarTripleProduct(a, b, c) +\n '\\n' +\n 'A x (B x C): ' + vectorTripleProduct(a, b, c)\n ); \n}());"} +{"title": "Vector products", "language": "Python", "task": "A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: \u00a0 (X, Y, Z). \n\nIf you imagine a graph with the \u00a0 '''x''' \u00a0 and \u00a0 '''y''' \u00a0 axis being at right angles to each other and having a third, \u00a0 '''z''' \u00a0 axis coming out of the page, then a triplet of numbers, \u00a0 (X, Y, Z) \u00a0 would represent a point in the region, \u00a0 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''' \u00a0 \u00a0 \u00a0 (a scalar quantity)\n:::: A \u2022 B = a1b1 \u00a0 + \u00a0 a2b2 \u00a0 + \u00a0 a3b3 \n* '''The cross product''' \u00a0 \u00a0 \u00a0 (a vector quantity)\n:::: A x B = (a2b3\u00a0 - \u00a0 a3b2, \u00a0 \u00a0 a3b1 \u00a0 - \u00a0 a1b3, \u00a0 \u00a0 a1b2 \u00a0 - \u00a0 a2b1) \n* '''The scalar triple product''' \u00a0 \u00a0 \u00a0 (a scalar quantity)\n:::: A \u2022 (B x C) \n* '''The vector triple product''' \u00a0 \u00a0 \u00a0 (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 \u2022 b\n# Compute and display: a x b\n# Compute and display: a \u2022 (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* \u00a0 A starting page on Wolfram MathWorld is \u00a0 {{Wolfram|Vector|Multiplication}}.\n* \u00a0 Wikipedia \u00a0 dot product. \n* \u00a0 Wikipedia \u00a0 cross product. \n* \u00a0 Wikipedia \u00a0 triple product.\n\n\n;Related tasks:\n* \u00a0 [[Dot product]]\n* \u00a0 [[Quaternion type]]\n\n", "solution": "def crossp(a, b):\n '''Cross product of two 3D vectors'''\n assert len(a) == len(b) == 3, 'For 3D vectors only'\n a1, a2, a3 = a\n b1, b2, b3 = b\n return (a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1)\n \ndef dotp(a,b):\n '''Dot product of two eqi-dimensioned vectors'''\n assert len(a) == len(b), 'Vector sizes must match'\n return sum(aterm * bterm for aterm,bterm in zip(a, b))\n \ndef scalartriplep(a, b, c):\n '''Scalar triple product of three vectors: \"a . (b x c)\"'''\n return dotp(a, crossp(b, c))\n \ndef vectortriplep(a, b, c):\n '''Vector triple product of three vectors: \"a x (b x c)\"'''\n return crossp(a, crossp(b, c))\n \nif __name__ == '__main__':\n a, b, c = (3, 4, 5), (4, 3, 5), (-5, -12, -13)\n print(\"a = %r; b = %r; c = %r\" % (a, b, c))\n print(\"a . b = %r\" % dotp(a,b))\n print(\"a x b = %r\" % (crossp(a,b),))\n print(\"a . (b x c) = %r\" % scalartriplep(a, b, c))\n print(\"a x (b x c) = %r\" % (vectortriplep(a, b, c),))"} +{"title": "Verhoeff algorithm", "language": "C", "task": ";Description\nThe [https://en.wikipedia.org/wiki/Verhoeff_algorithm 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* \u00a0 [[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": "Verhoeff algorithm", "language": "Python", "task": ";Description\nThe [https://en.wikipedia.org/wiki/Verhoeff_algorithm 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* \u00a0 [[Damm algorithm]]\n\n", "solution": "MULTIPLICATION_TABLE = [\n (0, 1, 2, 3, 4, 5, 6, 7, 8, 9),\n (1, 2, 3, 4, 0, 6, 7, 8, 9, 5),\n (2, 3, 4, 0, 1, 7, 8, 9, 5, 6),\n (3, 4, 0, 1, 2, 8, 9, 5, 6, 7),\n (4, 0, 1, 2, 3, 9, 5, 6, 7, 8),\n (5, 9, 8, 7, 6, 0, 4, 3, 2, 1),\n (6, 5, 9, 8, 7, 1, 0, 4, 3, 2),\n (7, 6, 5, 9, 8, 2, 1, 0, 4, 3),\n (8, 7, 6, 5, 9, 3, 2, 1, 0, 4),\n (9, 8, 7, 6, 5, 4, 3, 2, 1, 0),\n]\n\nINV = (0, 4, 3, 2, 1, 5, 6, 7, 8, 9)\n\nPERMUTATION_TABLE = [\n (0, 1, 2, 3, 4, 5, 6, 7, 8, 9),\n (1, 5, 7, 6, 2, 8, 3, 0, 9, 4),\n (5, 8, 0, 3, 7, 9, 6, 1, 4, 2),\n (8, 9, 1, 6, 0, 4, 3, 5, 2, 7),\n (9, 4, 5, 3, 1, 2, 6, 8, 7, 0),\n (4, 2, 8, 6, 5, 7, 3, 9, 0, 1),\n (2, 7, 9, 3, 8, 0, 6, 4, 1, 5),\n (7, 0, 4, 6, 9, 1, 3, 2, 5, 8),\n]\n\ndef verhoeffchecksum(n, validate=True, terse=True, verbose=False):\n \"\"\"\n Calculate the Verhoeff checksum over `n`.\n Terse mode or with single argument: return True if valid (last digit is a correct check digit).\n If checksum mode, return the expected correct checksum digit.\n If validation mode, return True if last digit checks correctly.\n \"\"\"\n if verbose:\n print(f\"\\n{'Validation' if validate else 'Check digit'}\",\\\n f\"calculations for {n}:\\n\\n i n\u1d62 p[i,n\u1d62] c\\n------------------\")\n # transform number list\n c, dig = 0, list(str(n if validate else 10 * n))\n for i, ni in enumerate(dig[::-1]):\n p = PERMUTATION_TABLE[i % 8][int(ni)]\n c = MULTIPLICATION_TABLE[c][p]\n if verbose:\n print(f\"{i:2} {ni} {p} {c}\")\n\n if verbose and not validate:\n print(f\"\\ninv({c}) = {INV[c]}\")\n if not terse:\n print(f\"\\nThe validation for '{n}' is {'correct' if c == 0 else 'incorrect'}.\"\\\n if validate else f\"\\nThe check digit for '{n}' is {INV[c]}.\")\n return c == 0 if validate else INV[c]\n\nif __name__ == '__main__':\n\n for n, va, t, ve in [\n (236, False, False, True), (2363, True, False, True), (2369, True, False, True),\n (12345, False, False, True), (123451, True, False, True), (123459, True, False, True),\n (123456789012, False, False, False), (1234567890120, True, False, False),\n (1234567890129, True, False, False)]:\n verhoeffchecksum(n, va, t, ve)\n"} +{"title": "Video display modes", "language": "Python", "task": "The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.\n", "solution": "import win32api\nimport win32con\nimport pywintypes\ndevmode=pywintypes.DEVMODEType()\ndevmode.PelsWidth=640\ndevmode.PelsHeight=480\ndevmode.Fields=win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT\nwin32api.ChangeDisplaySettings(devmode,0)"} +{"title": "Visualize a tree", "language": "C", "task": "A tree structure \u00a0 (i.e. a rooted, connected acyclic graph) \u00a0 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:::* \u00a0 indented text \u00a0 (\u00e0 la unix tree command)\n:::* \u00a0 nested HTML tables\n:::* \u00a0 hierarchical GUI widgets\n:::* \u00a0 2D \u00a0 or \u00a0 3D \u00a0 images\n:::* \u00a0 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": "Visualize a tree", "language": "JavaScript", "task": "A tree structure \u00a0 (i.e. a rooted, connected acyclic graph) \u00a0 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:::* \u00a0 indented text \u00a0 (\u00e0 la unix tree command)\n:::* \u00a0 nested HTML tables\n:::* \u00a0 hierarchical GUI widgets\n:::* \u00a0 2D \u00a0 or \u00a0 3D \u00a0 images\n:::* \u00a0 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": "(() => {\n 'use strict';\n\n // UTF8 character-drawn tree, with options for compacting vs\n // centering parents, and for pruning out nodeless lines.\n\n const example = `\n \u250c Epsilon\n \u250c\u2500 Beta \u253c\u2500\u2500\u2500 Zeta\n \u2502 \u2514\u2500\u2500\u2500\u2500 Eta\n Alpha \u253c Gamma \u2500\u2500\u2500 Theta\n \u2502 \u250c\u2500\u2500\u2500 Iota\n \u2514 Delta \u253c\u2500\u2500 Kappa\n \u2514\u2500 Lambda`\n\n // drawTree2 :: Bool -> Bool -> Tree String -> String\n const drawTree2 = blnCompact => blnPruned => tree => {\n // Tree design and algorithm inspired by the Haskell snippet at:\n // https://doisinkidney.com/snippets/drawing-trees.html\n const\n // Lefts, Middle, Rights\n lmrFromStrings = xs => {\n const [ls, rs] = Array.from(splitAt(\n Math.floor(xs.length / 2),\n xs\n ));\n return Tuple3(ls, rs[0], rs.slice(1));\n },\n stringsFromLMR = lmr =>\n Array.from(lmr).reduce((a, x) => a.concat(x), []),\n fghOverLMR = (f, g, h) => lmr => {\n const [ls, m, rs] = Array.from(lmr);\n return Tuple3(ls.map(f), g(m), rs.map(h));\n };\n\n const lmrBuild = (f, w) => wsTree => {\n const\n leftPad = n => s => ' '.repeat(n) + s,\n xs = wsTree.nest,\n lng = xs.length,\n [nChars, x] = Array.from(wsTree.root);\n\n // LEAF NODE --------------------------------------\n return 0 === lng ? (\n Tuple3([], '\u2500'.repeat(w - nChars) + x, [])\n\n // NODE WITH SINGLE CHILD -------------------------\n ) : 1 === lng ? (() => {\n const indented = leftPad(1 + w);\n return fghOverLMR(\n indented,\n z => '\u2500'.repeat(w - nChars) + x + '\u2500' + z,\n indented\n )(f(xs[0]));\n\n // NODE WITH CHILDREN -----------------------------\n })() : (() => {\n const\n cFix = x => xs => x + xs,\n treeFix = (l, m, r) => compose(\n stringsFromLMR,\n fghOverLMR(cFix(l), cFix(m), cFix(r))\n ),\n _x = '\u2500'.repeat(w - nChars) + x,\n indented = leftPad(w),\n lmrs = xs.map(f);\n return fghOverLMR(\n indented,\n s => _x + ({\n '\u250c': '\u252c',\n '\u251c': '\u253c',\n '\u2502': '\u2524',\n '\u2514': '\u2534'\n })[s[0]] + s.slice(1),\n indented\n )(lmrFromStrings(\n intercalate(\n blnCompact ? [] : ['\u2502'],\n [treeFix(' ', '\u250c', '\u2502')(lmrs[0])]\n .concat(init(lmrs.slice(1)).map(\n treeFix('\u2502', '\u251c', '\u2502')\n ))\n .concat([treeFix('\u2502', '\u2514', ' ')(\n lmrs[lmrs.length - 1]\n )])\n )\n ));\n })();\n };\n const\n measuredTree = fmapTree(\n v => {\n const s = ' ' + v + ' ';\n return Tuple(s.length, s)\n }, tree\n ),\n levelWidths = init(levels(measuredTree))\n .reduce(\n (a, level) => a.concat(maximum(level.map(fst))),\n []\n ),\n treeLines = stringsFromLMR(\n levelWidths.reduceRight(\n lmrBuild, x => x\n )(measuredTree)\n );\n return unlines(\n blnPruned ? (\n treeLines.filter(\n s => s.split('')\n .some(c => !' \u2502'.includes(c))\n )\n ) : treeLines\n );\n };\n\n // TESTS ----------------------------------------------\n const main = () => {\n\n // tree :: Tree String\n const tree = Node(\n 'Alpha', [\n Node('Beta', [\n Node('Epsilon', []),\n Node('Zeta', []),\n Node('Eta', [])\n ]),\n Node('Gamma', [Node('Theta', [])]),\n Node('Delta', [\n Node('Iota', []),\n Node('Kappa', []),\n Node('Lambda', [])\n ])\n ]);\n\n // tree2 :: Tree Int\n const tree2 = Node(\n 1,\n [\n Node(2, [\n Node(4, []),\n Node(5, [Node(7, [])])\n ]),\n Node(3, [\n Node(6, [\n Node(8, []),\n Node(9, [])\n ])\n ])\n ]\n );\n\n // strTrees :: String\n const strTrees = ([\n 'Compacted (parents not all vertically centered):',\n drawTree2(true)(false)(tree2),\n 'Fully expanded, with vertical centering:',\n drawTree2(false)(false)(tree),\n 'Vertically centered, with nodeless lines pruned out:',\n drawTree2(false)(true)(tree),\n ].join('\\n\\n'));\n\n return (\n console.log(strTrees),\n strTrees\n );\n };\n\n // GENERIC FUNCTIONS ----------------------------------\n\n // Node :: a -> [Tree a] -> Tree a\n const Node = (v, xs) => ({\n type: 'Node',\n root: v, // any type of value (consistent across tree)\n nest: xs || []\n });\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = (a, b) => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // Tuple3 (,,) :: a -> b -> c -> (a, b, c)\n const Tuple3 = (a, b, c) => ({\n type: 'Tuple3',\n '0': a,\n '1': b,\n '2': c,\n length: 3\n });\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (f, g) => x => f(g(x));\n\n // concat :: [[a]] -> [a]\n // concat :: [String] -> String\n const concat = xs =>\n 0 < xs.length ? (() => {\n const unit = 'string' !== typeof xs[0] ? (\n []\n ) : '';\n return unit.concat.apply(unit, xs);\n })() : [];\n\n // fmapTree :: (a -> b) -> Tree a -> Tree b\n const fmapTree = (f, tree) => {\n const go = node => Node(\n f(node.root),\n node.nest.map(go)\n );\n return go(tree);\n };\n\n // fst :: (a, b) -> a\n const fst = tpl => tpl[0];\n\n // identity :: a -> a\n const identity = x => x;\n\n // init :: [a] -> [a]\n const init = xs =>\n 0 < xs.length ? (\n xs.slice(0, -1)\n ) : undefined;\n\n // intercalate :: [a] -> [[a]] -> [a]\n // intercalate :: String -> [String] -> String\n const intercalate = (sep, xs) =>\n 0 < xs.length && 'string' === typeof sep &&\n 'string' === typeof xs[0] ? (\n xs.join(sep)\n ) : concat(intersperse(sep, xs));\n\n // intersperse(0, [1,2,3]) -> [1, 0, 2, 0, 3]\n\n // intersperse :: a -> [a] -> [a]\n // intersperse :: Char -> String -> String\n const intersperse = (sep, xs) => {\n const bln = 'string' === typeof xs;\n return xs.length > 1 ? (\n (bln ? concat : x => x)(\n (bln ? (\n xs.split('')\n ) : xs)\n .slice(1)\n .reduce((a, x) => a.concat([sep, x]), [xs[0]])\n )) : xs;\n };\n\n // iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a]\n const iterateUntil = (p, f, x) => {\n const vs = [x];\n let h = x;\n while (!p(h))(h = f(h), vs.push(h));\n return vs;\n };\n\n // Returns Infinity over objects without finite length.\n // This enables zip and zipWith to choose the shorter\n // argument when one is non-finite, like cycle, repeat etc\n\n // length :: [a] -> Int\n const length = xs =>\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n // levels :: Tree a -> [[a]]\n const levels = tree =>\n iterateUntil(\n xs => 1 > xs.length,\n ys => [].concat(...ys.map(nest)),\n [tree]\n ).map(xs => xs.map(root));\n\n // maximum :: Ord a => [a] -> a\n const maximum = xs =>\n 0 < xs.length ? (\n xs.slice(1).reduce((a, x) => x > a ? x : a, xs[0])\n ) : undefined;\n\n // nest :: Tree a -> [a]\n const nest = tree => tree.nest;\n\n // root :: Tree a -> a\n const root = tree => tree.root;\n\n // splitAt :: Int -> [a] -> ([a], [a])\n const splitAt = (n, xs) =>\n Tuple(xs.slice(0, n), xs.slice(n));\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // MAIN ---\n return main();\n})();"} +{"title": "Visualize a tree", "language": "Python", "task": "A tree structure \u00a0 (i.e. a rooted, connected acyclic graph) \u00a0 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:::* \u00a0 indented text \u00a0 (\u00e0 la unix tree command)\n:::* \u00a0 nested HTML tables\n:::* \u00a0 hierarchical GUI widgets\n:::* \u00a0 2D \u00a0 or \u00a0 3D \u00a0 images\n:::* \u00a0 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": "Python 3.2.3 (default, May 3 2012, 15:54:42) \n[GCC 4.6.3] on linux2\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> help('pprint.pprint')\nHelp on function pprint in pprint:\n\npprint.pprint = pprint(object, stream=None, indent=1, width=80, depth=None)\n Pretty-print a Python object to a stream [default is sys.stdout].\n\n>>> from pprint import pprint\n>>> for tree in [ (1, 2, 3, 4, 5, 6, 7, 8),\n\t (1, (( 2, 3 ), (4, (5, ((6, 7), 8))))),\n\t ((((1, 2), 3), 4), 5, 6, 7, 8) ]:\n\tprint(\"\\nTree %r can be pprint'd as:\" % (tree, ))\n\tpprint(tree, indent=1, width=1)\n\n\t\n\nTree (1, 2, 3, 4, 5, 6, 7, 8) can be pprint'd as:\n(1,\n 2,\n 3,\n 4,\n 5,\n 6,\n 7,\n 8)\n\nTree (1, ((2, 3), (4, (5, ((6, 7), 8))))) can be pprint'd as:\n(1,\n ((2,\n 3),\n (4,\n (5,\n ((6,\n 7),\n 8)))))\n\nTree ((((1, 2), 3), 4), 5, 6, 7, 8) can be pprint'd as:\n((((1,\n 2),\n 3),\n 4),\n 5,\n 6,\n 7,\n 8)\n>>> "} +{"title": "Visualize a tree", "language": "Python 3", "task": "A tree structure \u00a0 (i.e. a rooted, connected acyclic graph) \u00a0 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:::* \u00a0 indented text \u00a0 (\u00e0 la unix tree command)\n:::* \u00a0 nested HTML tables\n:::* \u00a0 hierarchical GUI widgets\n:::* \u00a0 2D \u00a0 or \u00a0 3D \u00a0 images\n:::* \u00a0 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": "'''Textually visualized tree, with vertically-centered parent nodes'''\n\nfrom functools import reduce\nfrom itertools import (chain, takewhile)\n\n'''\n \u250c Epsilon\n \u251c\u2500\u2500\u2500 Zeta\n \u250c\u2500 Beta \u253c\u2500\u2500\u2500\u2500 Eta\n \u2502 \u2502 \u250c\u2500\u2500\u2500\u2500\u2500 Mu\n \u2502 \u2514\u2500\u2500 Theta \u2524\n Alpha \u2524 \u2514\u2500\u2500\u2500\u2500\u2500 Nu\n \u251c Gamma \u2500\u2500\u2500\u2500\u2500\u2500 Xi \u2500 Omicron\n \u2502 \u250c\u2500\u2500\u2500 Iota\n \u2514 Delta \u253c\u2500\u2500 Kappa\n \u2514\u2500 Lambda\n'''\n# Tree style and algorithm inspired by the Haskell snippet at:\n# https://doisinkidney.com/snippets/drawing-trees.html\n\n\n# drawTree2 :: Bool -> Bool -> Tree a -> String\ndef drawTree2(blnCompact):\n '''Monospaced UTF8 left-to-right text tree in a\n compact or expanded format, with any lines\n containing no nodes optionally pruned out.\n '''\n def go(blnPruned, tree):\n # measured :: a -> (Int, String)\n def measured(x):\n '''Value of a tree node\n tupled with string length.\n '''\n s = ' ' + str(x) + ' '\n return len(s), s\n\n # lmrFromStrings :: [String] -> ([String], String, [String])\n def lmrFromStrings(xs):\n '''Lefts, Mid, Rights.'''\n i = len(xs) // 2\n ls, rs = xs[0:i], xs[i:]\n return ls, rs[0], rs[1:]\n\n # stringsFromLMR :: ([String], String, [String]) -> [String]\n def stringsFromLMR(lmr):\n ls, m, rs = lmr\n return ls + [m] + rs\n\n # fghOverLMR\n # :: (String -> String)\n # -> (String -> String)\n # -> (String -> String)\n # -> ([String], String, [String])\n # -> ([String], String, [String])\n def fghOverLMR(f, g, h):\n def go(lmr):\n ls, m, rs = lmr\n return (\n [f(x) for x in ls],\n g(m),\n [h(x) for x in rs]\n )\n return lambda lmr: go(lmr)\n\n # leftPad :: Int -> String -> String\n def leftPad(n):\n return lambda s: (' ' * n) + s\n\n # treeFix :: (Char, Char, Char) -> ([String], String, [String])\n # -> [String]\n def treeFix(l, m, r):\n def cfix(x):\n return lambda xs: x + xs\n return compose(stringsFromLMR)(\n fghOverLMR(cfix(l), cfix(m), cfix(r))\n )\n\n def lmrBuild(w, f):\n def go(wsTree):\n nChars, x = wsTree['root']\n _x = ('\u2500' * (w - nChars)) + x\n xs = wsTree['nest']\n lng = len(xs)\n\n # linked :: String -> String\n def linked(s):\n c = s[0]\n t = s[1:]\n return _x + '\u252c' + t if '\u250c' == c else (\n _x + '\u2524' + t if '\u2502' == c else (\n _x + '\u253c' + t if '\u251c' == c else (\n _x + '\u2534' + t\n )\n )\n )\n\n # LEAF ------------------------------------\n if 0 == lng:\n return ([], _x, [])\n\n # SINGLE CHILD ----------------------------\n elif 1 == lng:\n def lineLinked(z):\n return _x + '\u2500' + z\n rightAligned = leftPad(1 + w)\n return fghOverLMR(\n rightAligned,\n lineLinked,\n rightAligned\n )(f(xs[0]))\n\n # CHILDREN --------------------------------\n else:\n rightAligned = leftPad(w)\n lmrs = [f(x) for x in xs]\n return fghOverLMR(\n rightAligned,\n linked,\n rightAligned\n )(\n lmrFromStrings(\n intercalate([] if blnCompact else ['\u2502'])(\n [treeFix(' ', '\u250c', '\u2502')(lmrs[0])] + [\n treeFix('\u2502', '\u251c', '\u2502')(x) for x\n in lmrs[1:-1]\n ] + [treeFix('\u2502', '\u2514', ' ')(lmrs[-1])]\n )\n )\n )\n return lambda wsTree: go(wsTree)\n\n measuredTree = fmapTree(measured)(tree)\n levelWidths = reduce(\n lambda a, xs: a + [max(x[0] for x in xs)],\n levels(measuredTree),\n []\n )\n treeLines = stringsFromLMR(\n foldr(lmrBuild)(None)(levelWidths)(\n measuredTree\n )\n )\n return [\n s for s in treeLines\n if any(c not in '\u2502 ' for c in s)\n ] if (not blnCompact and blnPruned) else treeLines\n\n return lambda blnPruned: (\n lambda tree: '\\n'.join(go(blnPruned, tree))\n )\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Trees drawn in varying formats'''\n\n # tree1 :: Tree Int\n tree1 = Node(1)([\n Node(2)([\n Node(4)([\n Node(7)([])\n ]),\n Node(5)([])\n ]),\n Node(3)([\n Node(6)([\n Node(8)([]),\n Node(9)([])\n ])\n ])\n ])\n\n # tree :: Tree String\n tree2 = Node('Alpha')([\n Node('Beta')([\n Node('Epsilon')([]),\n Node('Zeta')([]),\n Node('Eta')([]),\n Node('Theta')([\n Node('Mu')([]),\n Node('Nu')([])\n ])\n ]),\n Node('Gamma')([\n Node('Xi')([Node('Omicron')([])])\n ]),\n Node('Delta')([\n Node('Iota')([]),\n Node('Kappa')([]),\n Node('Lambda')([])\n ])\n ])\n\n print(\n '\\n\\n'.join([\n 'Fully compacted (parents not all centered):',\n drawTree2(True)(False)(\n tree1\n ),\n 'Expanded with vertically centered parents:',\n drawTree2(False)(False)(\n tree2\n ),\n 'Centered parents with nodeless lines pruned out:',\n drawTree2(False)(True)(\n tree2\n )\n ])\n )\n\n\n# GENERIC -------------------------------------------------\n\n# Node :: a -> [Tree a] -> Tree a\ndef Node(v):\n '''Contructor for a Tree node which connects a\n value of some kind to a list of zero or\n more child trees.\n '''\n return lambda xs: {'type': 'Tree', 'root': v, 'nest': xs}\n\n\n# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n '''Right to left function composition.'''\n return lambda f: lambda x: g(f(x))\n\n\n# concatMap :: (a -> [b]) -> [a] -> [b]\ndef concatMap(f):\n '''A concatenated list over which a function has been mapped.\n The list monad can be derived by using a function f which\n wraps its output in a list,\n (using an empty list to represent computational failure).\n '''\n return lambda xs: list(\n chain.from_iterable(map(f, xs))\n )\n\n\n# fmapTree :: (a -> b) -> Tree a -> Tree b\ndef fmapTree(f):\n '''A new tree holding the results of\n applying f to each root in\n the existing tree.\n '''\n def go(x):\n return Node(f(x['root']))(\n [go(v) for v in x['nest']]\n )\n return lambda tree: go(tree)\n\n\n# foldr :: (a -> b -> b) -> b -> [a] -> b\ndef foldr(f):\n '''Right to left reduction of a list,\n using the binary operator f, and\n starting with an initial accumulator value.\n '''\n def g(x, a):\n return f(a, x)\n return lambda acc: lambda xs: reduce(\n g, xs[::-1], acc\n )\n\n\n# intercalate :: [a] -> [[a]] -> [a]\n# intercalate :: String -> [String] -> String\ndef intercalate(x):\n '''The concatenation of xs\n interspersed with copies of x.\n '''\n return lambda xs: x.join(xs) if isinstance(x, str) else list(\n chain.from_iterable(\n reduce(lambda a, v: a + [x, v], xs[1:], [xs[0]])\n )\n ) if xs else []\n\n\n# iterate :: (a -> a) -> a -> Gen [a]\ndef iterate(f):\n '''An infinite list of repeated\n applications of f to x.\n '''\n def go(x):\n v = x\n while True:\n yield v\n v = f(v)\n return lambda x: go(x)\n\n\n# levels :: Tree a -> [[a]]\ndef levels(tree):\n '''A list of the nodes at each level of the tree.'''\n return list(\n map_(map_(root))(\n takewhile(\n bool,\n iterate(concatMap(nest))(\n [tree]\n )\n )\n )\n )\n\n\n# map :: (a -> b) -> [a] -> [b]\ndef map_(f):\n '''The list obtained by applying f\n to each element of xs.\n '''\n return lambda xs: list(map(f, xs))\n\n\n# nest :: Tree a -> [Tree a]\ndef nest(t):\n '''Accessor function for children of tree node.'''\n return t['nest'] if 'nest' in t else None\n\n\n# root :: Tree a -> a\ndef root(t):\n '''Accessor function for data of tree node.'''\n return t['root'] if 'root' in t else None\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} +{"title": "Vogel's approximation method", "language": "C", "task": "[http://mcajournal.cbu.edu.tr/articleinpress/articleinpress_955.pdf Vogel's Approximation Method (VAM)] is a technique for finding a good initial feasible solution to an allocation problem.\n\nThe powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them \u201cA\u201d, \u201cB\u201d, \u201cC\u201d, \u201cD\u201d, and \u201cE\u201d. They estimate that:\n* A will require 30 hours of work,\n* B will require 20 hours of work,\n* C will require 70 hours of work,\n* D will require 30 hours of work, and\n* E will require 60 hours of work.\n\nThey have identified 4 contractors willing to do the work, called \u201cW\u201d, \u201cX\u201d, \u201cY\u201d, and \u201cZ\u201d.\n* W has 50 hours available to commit to working,\n* X has 60 hours available,\n* Y has 50 hours available, and\n* Z has 50 hours available.\nThe cost per hour for each contractor for each task is summarized by the following table:\n\n\n A B C D E\nW 16 16 13 22 17\nX 14 14 13 19 15\nY 19 19 20 23 50\nZ 50 12 50 15 11\n\n\nThe task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows:\n\n:Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply\n A B C D E W X Y Z\n1 2 2 0 4 4 3 1 0 1 E-Z(50)\n\n\nDetermine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply).\nAdjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see [http://rosettacode.org/mw/index.php?title=VAM&oldid=167195 here] for the working.\n\nRepeat until all supply and demand is met:\n\n2 2 2 0 3 2 3 1 0 - C-W(50)\n3 5 5 7 4 35 - 1 0 - E-X(10)\n4 5 5 7 4 - - 1 0 - C-X(20)\n5 5 5 - 4 - - 0 0 - A-X(30)\n6 - 19 - 23 - - - 4 - D-Y(30)\n - - - - - - - - - B-Y(20)\n\nFinally calculate the cost of your solution. In the example given it is \u00a33100:\n\n A B C D E\nW 50\nX 30 20 10\nY 20 30\nZ 50\n\n\nThe optimal solution determined by GLPK is \u00a33100:\n\n A B C D E\nW 50\nX 10 20 20 10\nY 20 30\nZ 50\n\n\n;Cf.\n* Transportation problem\n\n", "solution": "#include \n#include \n\n#define TRUE 1\n#define FALSE 0\n#define N_ROWS 4\n#define N_COLS 5\n\ntypedef int bool;\n\nint supply[N_ROWS] = { 50, 60, 50, 50 };\nint demand[N_COLS] = { 30, 20, 70, 30, 60 };\n\nint costs[N_ROWS][N_COLS] = {\n { 16, 16, 13, 22, 17 },\n { 14, 14, 13, 19, 15 },\n { 19, 19, 20, 23, 50 },\n { 50, 12, 50, 15, 11 }\n};\n\nbool row_done[N_ROWS] = { FALSE };\nbool col_done[N_COLS] = { FALSE };\n\nvoid diff(int j, int len, bool is_row, int res[3]) {\n int i, c, min1 = INT_MAX, min2 = min1, min_p = -1;\n for (i = 0; i < len; ++i) {\n if((is_row) ? col_done[i] : row_done[i]) continue;\n c = (is_row) ? costs[j][i] : costs[i][j];\n if (c < min1) {\n min2 = min1;\n min1 = c;\n min_p = i;\n }\n else if (c < min2) min2 = c;\n }\n res[0] = min2 - min1; res[1] = min1; res[2] = min_p;\n}\n\nvoid max_penalty(int len1, int len2, bool is_row, int res[4]) {\n int i, pc = -1, pm = -1, mc = -1, md = INT_MIN;\n int res2[3];\n\n for (i = 0; i < len1; ++i) {\n if((is_row) ? row_done[i] : col_done[i]) continue;\n diff(i, len2, is_row, res2);\n if (res2[0] > md) {\n md = res2[0]; /* max diff */\n pm = i; /* pos of max diff */\n mc = res2[1]; /* min cost */\n pc = res2[2]; /* pos of min cost */\n }\n }\n\n if (is_row) {\n res[0] = pm; res[1] = pc;\n }\n else {\n res[0] = pc; res[1] = pm;\n }\n res[2] = mc; res[3] = md;\n}\n\nvoid next_cell(int res[4]) {\n int i, res1[4], res2[4];\n max_penalty(N_ROWS, N_COLS, TRUE, res1);\n max_penalty(N_COLS, N_ROWS, FALSE, res2);\n\n if (res1[3] == res2[3]) {\n if (res1[2] < res2[2])\n for (i = 0; i < 4; ++i) res[i] = res1[i];\n else\n for (i = 0; i < 4; ++i) res[i] = res2[i];\n return;\n }\n if (res1[3] > res2[3])\n for (i = 0; i < 4; ++i) res[i] = res2[i];\n else\n for (i = 0; i < 4; ++i) res[i] = res1[i];\n}\n\nint main() {\n int i, j, r, c, q, supply_left = 0, total_cost = 0, cell[4];\n int results[N_ROWS][N_COLS] = { 0 };\n\n for (i = 0; i < N_ROWS; ++i) supply_left += supply[i];\n while (supply_left > 0) {\n next_cell(cell);\n r = cell[0];\n c = cell[1];\n q = (demand[c] <= supply[r]) ? demand[c] : supply[r];\n demand[c] -= q;\n if (!demand[c]) col_done[c] = TRUE;\n supply[r] -= q;\n if (!supply[r]) row_done[r] = TRUE;\n results[r][c] = q;\n supply_left -= q;\n total_cost += q * costs[r][c];\n }\n\n printf(\" A B C D E\\n\");\n for (i = 0; i < N_ROWS; ++i) {\n printf(\"%c\", 'W' + i);\n for (j = 0; j < N_COLS; ++j) printf(\" %2d\", results[i][j]);\n printf(\"\\n\");\n }\n printf(\"\\nTotal cost = %d\\n\", total_cost);\n return 0;\n}"} +{"title": "Vogel's approximation method", "language": "Python", "task": "[http://mcajournal.cbu.edu.tr/articleinpress/articleinpress_955.pdf Vogel's Approximation Method (VAM)] is a technique for finding a good initial feasible solution to an allocation problem.\n\nThe powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them \u201cA\u201d, \u201cB\u201d, \u201cC\u201d, \u201cD\u201d, and \u201cE\u201d. They estimate that:\n* A will require 30 hours of work,\n* B will require 20 hours of work,\n* C will require 70 hours of work,\n* D will require 30 hours of work, and\n* E will require 60 hours of work.\n\nThey have identified 4 contractors willing to do the work, called \u201cW\u201d, \u201cX\u201d, \u201cY\u201d, and \u201cZ\u201d.\n* W has 50 hours available to commit to working,\n* X has 60 hours available,\n* Y has 50 hours available, and\n* Z has 50 hours available.\nThe cost per hour for each contractor for each task is summarized by the following table:\n\n\n A B C D E\nW 16 16 13 22 17\nX 14 14 13 19 15\nY 19 19 20 23 50\nZ 50 12 50 15 11\n\n\nThe task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows:\n\n:Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply\n A B C D E W X Y Z\n1 2 2 0 4 4 3 1 0 1 E-Z(50)\n\n\nDetermine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply).\nAdjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see [http://rosettacode.org/mw/index.php?title=VAM&oldid=167195 here] for the working.\n\nRepeat until all supply and demand is met:\n\n2 2 2 0 3 2 3 1 0 - C-W(50)\n3 5 5 7 4 35 - 1 0 - E-X(10)\n4 5 5 7 4 - - 1 0 - C-X(20)\n5 5 5 - 4 - - 0 0 - A-X(30)\n6 - 19 - 23 - - - 4 - D-Y(30)\n - - - - - - - - - B-Y(20)\n\nFinally calculate the cost of your solution. In the example given it is \u00a33100:\n\n A B C D E\nW 50\nX 30 20 10\nY 20 30\nZ 50\n\n\nThe optimal solution determined by GLPK is \u00a33100:\n\n A B C D E\nW 50\nX 10 20 20 10\nY 20 30\nZ 50\n\n\n;Cf.\n* Transportation problem\n\n", "solution": "from collections import defaultdict\n\ncosts = {'W': {'A': 16, 'B': 16, 'C': 13, 'D': 22, 'E': 17},\n 'X': {'A': 14, 'B': 14, 'C': 13, 'D': 19, 'E': 15},\n 'Y': {'A': 19, 'B': 19, 'C': 20, 'D': 23, 'E': 50},\n 'Z': {'A': 50, 'B': 12, 'C': 50, 'D': 15, 'E': 11}}\ndemand = {'A': 30, 'B': 20, 'C': 70, 'D': 30, 'E': 60}\ncols = sorted(demand.iterkeys())\nsupply = {'W': 50, 'X': 60, 'Y': 50, 'Z': 50}\nres = dict((k, defaultdict(int)) for k in costs)\ng = {}\nfor x in supply:\n g[x] = sorted(costs[x].iterkeys(), key=lambda g: costs[x][g])\nfor x in demand:\n g[x] = sorted(costs.iterkeys(), key=lambda g: costs[g][x])\n\nwhile g:\n d = {}\n for x in demand:\n d[x] = (costs[g[x][1]][x] - costs[g[x][0]][x]) if len(g[x]) > 1 else costs[g[x][0]][x]\n s = {}\n for x in supply:\n s[x] = (costs[x][g[x][1]] - costs[x][g[x][0]]) if len(g[x]) > 1 else costs[x][g[x][0]]\n f = max(d, key=lambda n: d[n])\n t = max(s, key=lambda n: s[n])\n t, f = (f, g[f][0]) if d[f] > s[t] else (g[t][0], t)\n v = min(supply[f], demand[t])\n res[f][t] += v\n demand[t] -= v\n if demand[t] == 0:\n for k, n in supply.iteritems():\n if n != 0:\n g[k].remove(t)\n del g[t]\n del demand[t]\n supply[f] -= v\n if supply[f] == 0:\n for k, n in demand.iteritems():\n if n != 0:\n g[k].remove(f)\n del g[f]\n del supply[f]\n\nfor n in cols:\n print \"\\t\", n,\nprint\ncost = 0\nfor g in sorted(costs):\n print g, \"\\t\",\n for n in cols:\n y = res[g][n]\n if y != 0:\n print y,\n cost += y * costs[g][n]\n print \"\\t\",\n print\nprint \"\\n\\nTotal Cost = \", cost"} +{"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": "Voronoi diagram", "language": "JavaScript", "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": "===Version #1.===\nThe obvious route to this in JavaScript would be to use Mike Bostock's D3.js library.\n\nThere are various examples of Voronoi tesselations,\n\nsome dynamic:\n\nhttps://bl.ocks.org/mbostock/d1d81455dc21e10f742f\n\nsome interactive:\n\nhttps://bl.ocks.org/mbostock/4060366\n\nand all with source code, at https://bl.ocks.org/mbostock\n\n===Version #2.===\nI would agree: using D3.js library can be very helpful. But having stable and compact algorithm in Python (Sidef) made it possible to develop looking the same Voronoi diagram in \"pure\" JavaScript.\nA few custom helper functions simplified code, and they can be used for any other applications.\n"} +{"title": "Voronoi diagram", "language": "Chrome", "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": "\n\nVoronoi diagram\n\n\nPlease input number of sites: \n\u00a0\u00a0\n Metric: \n\nEuclidean\nManhattan\nMinkovski\n\u00a0\n \u00a0\u00a0\n Voronoi diagram\n\n\n\n"} +{"title": "Voronoi diagram", "language": "Python", "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": "from PIL import Image\nimport random\nimport math\n\ndef generate_voronoi_diagram(width, height, num_cells):\n\timage = Image.new(\"RGB\", (width, height))\n\tputpixel = image.putpixel\n\timgx, imgy = image.size\n\tnx = []\n\tny = []\n\tnr = []\n\tng = []\n\tnb = []\n\tfor i in range(num_cells):\n\t\tnx.append(random.randrange(imgx))\n\t\tny.append(random.randrange(imgy))\n\t\tnr.append(random.randrange(256))\n\t\tng.append(random.randrange(256))\n\t\tnb.append(random.randrange(256))\n\tfor y in range(imgy):\n\t\tfor x in range(imgx):\n\t\t\tdmin = math.hypot(imgx-1, imgy-1)\n\t\t\tj = -1\n\t\t\tfor i in range(num_cells):\n\t\t\t\td = math.hypot(nx[i]-x, ny[i]-y)\n\t\t\t\tif d < dmin:\n\t\t\t\t\tdmin = d\n\t\t\t\t\tj = i\n\t\t\tputpixel((x, y), (nr[j], ng[j], nb[j]))\n\timage.save(\"VoronoiDiagram.png\", \"PNG\")\n image.show()\n\t\ngenerate_voronoi_diagram(500, 500, 25)"} +{"title": "Wagstaff primes", "language": "C", "task": ";Definition\nA ''Wagstaff prime'' is a prime number of the form ''(2^p + 1)/3'' where the exponent ''p'' is an odd prime.\n\n;Example \n(2^5 + 1)/3 = 11 is a Wagstaff prime because both 5 and 11 are primes.\n\n;Task\nFind and show here the first ''10'' Wagstaff primes and their corresponding exponents ''p''.\n\n;Stretch (requires arbitrary precision integers)\nFind and show here the exponents ''p'' corresponding to the next ''14'' Wagstaff primes (not the primes themselves) and any more that you have the patience for. \n\nWhen testing for primality, you may use a method which determines that a large number is probably prime with reasonable certainty.\n\n;Note\nIt can be shown (see talk page) that ''(2^p + 1)/3'' is always integral if ''p'' is odd. So there's no need to check for that prior to checking for primality.\n\n;References\n\n* Wikipedia - Wagstaff prime\n* OEIS:A000979 - Wagstaff primes\n\n", "solution": "#include \n#include \n#include \n\nint main() {\n const int limit = 29;\n int count = 0;\n char tmp[40];\n mpz_t p, w;\n mpz_init_set_ui(p, 1);\n mpz_init(w);\n while (count < limit) {\n mpz_nextprime(p, p);\n mpz_set_ui(w, 1);\n unsigned long ulp = mpz_get_ui(p);\n mpz_mul_2exp(w, w, ulp);\n mpz_add_ui(w, w, 1);\n mpz_tdiv_q_ui(w, w, 3);\n if (mpz_probab_prime_p(w, 15) > 0) {\n ++count;\n char *ws = mpz_get_str(NULL, 10, w);\n size_t le = strlen(ws);\n if (le < 34) {\n strcpy(tmp, ws);\n } else {\n strncpy(tmp, ws, 15);\n strcpy(tmp + 15, \"...\");\n strncpy(tmp + 18, ws + le - 15, 16);\n }\n printf(\"%5lu: %s\", ulp, tmp);\n if (le >=34) printf( \" (%ld digits)\", le);\n printf(\"\\n\");\n }\n }\n return 0;\n}"} +{"title": "Wagstaff primes", "language": "Python", "task": ";Definition\nA ''Wagstaff prime'' is a prime number of the form ''(2^p + 1)/3'' where the exponent ''p'' is an odd prime.\n\n;Example \n(2^5 + 1)/3 = 11 is a Wagstaff prime because both 5 and 11 are primes.\n\n;Task\nFind and show here the first ''10'' Wagstaff primes and their corresponding exponents ''p''.\n\n;Stretch (requires arbitrary precision integers)\nFind and show here the exponents ''p'' corresponding to the next ''14'' Wagstaff primes (not the primes themselves) and any more that you have the patience for. \n\nWhen testing for primality, you may use a method which determines that a large number is probably prime with reasonable certainty.\n\n;Note\nIt can be shown (see talk page) that ''(2^p + 1)/3'' is always integral if ''p'' is odd. So there's no need to check for that prior to checking for primality.\n\n;References\n\n* Wikipedia - Wagstaff prime\n* OEIS:A000979 - Wagstaff primes\n\n", "solution": "\"\"\" Rosetta code Wagstaff_primes task \"\"\"\n\nfrom sympy import isprime\n\ndef wagstaff(N):\n \"\"\" find first N Wagstaff primes \"\"\"\n pri, wcount = 1, 0\n while wcount < N:\n pri += 2\n if isprime(pri):\n wag = (2**pri + 1) // 3\n if isprime(wag):\n wcount += 1\n print(f'{wcount: 3}: {pri: 5} => ', \n f'{wag:,}' if wcount < 11 else f'[{len(str(wag))} digit number]')\n\n\nwagstaff(24)\n"} +{"title": "War card game", "language": "Python", "task": "[[Category:Cards]] \n[[Category:Games]]\n\nWar Card Game\n\nSimulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional.\n\nReferences:\n\n:* Bicycle card company: [https://bicyclecards.com/how-to-play/war War game site]\n\n:* Wikipedia: War (card game)\n\nRelated tasks:\n* [[Playing cards]]\n* [[Card shuffles]]\n* [[Deal cards for FreeCell]]\n* [[Poker hand_analyser]]\n* [[Go Fish]]\n\n\n", "solution": "\"\"\" https://bicyclecards.com/how-to-play/war/ \"\"\"\n\nfrom numpy.random import shuffle\n\nSUITS = ['\u2663', '\u2666', '\u2665', '\u2660']\nFACES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']\nDECK = [f + s for f in FACES for s in SUITS]\nCARD_TO_RANK = dict((DECK[i], (i + 3) // 4) for i in range(len(DECK)))\n\n\nclass WarCardGame:\n \"\"\" card game War \"\"\"\n def __init__(self):\n deck = DECK.copy()\n shuffle(deck)\n self.deck1, self.deck2 = deck[:26], deck[26:]\n self.pending = []\n\n def turn(self):\n \"\"\" one turn, may recurse on tie \"\"\"\n if len(self.deck1) == 0 or len(self.deck2) == 0:\n return self.gameover()\n\n card1, card2 = self.deck1.pop(0), self.deck2.pop(0)\n rank1, rank2 = CARD_TO_RANK[card1], CARD_TO_RANK[card2]\n print(\"{:10}{:10}\".format(card1, card2), end='')\n if rank1 > rank2:\n print('Player 1 takes the cards.')\n self.deck1.extend([card1, card2])\n self.deck1.extend(self.pending)\n self.pending = []\n elif rank1 < rank2:\n print('Player 2 takes the cards.')\n self.deck2.extend([card2, card1])\n self.deck2.extend(self.pending)\n self.pending = []\n else: # rank1 == rank2\n print('Tie!')\n if len(self.deck1) == 0 or len(self.deck2) == 0:\n return self.gameover()\n\n card3, card4 = self.deck1.pop(0), self.deck2.pop(0)\n self.pending.extend([card1, card2, card3, card4])\n print(\"{:10}{:10}\".format(\"?\", \"?\"), 'Cards are face down.', sep='')\n return self.turn()\n\n return True\n\n def gameover(self):\n \"\"\" game over who won message \"\"\"\n if len(self.deck2) == 0:\n if len(self.deck1) == 0:\n print('\\nGame ends as a tie.')\n else:\n print('\\nPlayer 1 wins the game.')\n else:\n print('\\nPlayer 2 wins the game.')\n\n return False\n\n\nif __name__ == '__main__':\n WG = WarCardGame()\n while WG.turn():\n continue\n"} +{"title": "Water collected between towers", "language": "C", "task": ";Task:\nIn 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 \u2588\u2588 9 \u2588\u2588 \n8 \u2588\u2588 8 \u2588\u2588 \n7 \u2588\u2588 \u2588\u2588 7 \u2588\u2588\u2248\u2248\u2248\u2248\u2248\u2248\u2248\u2248\u2588\u2588 \n6 \u2588\u2588 \u2588\u2588 \u2588\u2588 6 \u2588\u2588\u2248\u2248\u2588\u2588\u2248\u2248\u2248\u2248\u2588\u2588 \n5 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588\u2588\u2588 5 \u2588\u2588\u2248\u2248\u2588\u2588\u2248\u2248\u2588\u2588\u2248\u2248\u2588\u2588\u2588\u2588 \n4 \u2588\u2588 \u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 4 \u2588\u2588\u2248\u2248\u2588\u2588\u2248\u2248\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \n3 \u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 3 \u2588\u2588\u2588\u2588\u2588\u2588\u2248\u2248\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \n2 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588 2 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2248\u2248\u2588\u2588\n1 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 1 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\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* [https://youtu.be/ftcIcn8AmSY?t=536 Four Solutions to a Trivial Problem] \u2013 a Google Tech Talk by Guy Steele\n* [http://stackoverflow.com/questions/24414700/amazon-water-collected-between-towers/ Water collected between towers] on Stack Overflow, from which the example above is taken)\n* [https://gist.github.com/paf31/9d84ecf6a6a9b69cdb597a390f25764d An interesting Haskell solution], using the Tardis monad, by [https://gist.github.com/paf31 Phil Freeman] in a [https://gist.github.com/paf31/9d84ecf6a6a9b69cdb597a390f25764d Github gist].\n\n\n\n", "solution": "\n#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\nOutput :\n\nC:\\rosettaCode>waterTowers.exe 1 5 3 7 2\nWater collected : 2\nC:\\rosettaCode>waterTowers.exe 5 3 7 2 6 4 5 9 1 2\nWater collected : 14\nC:\\rosettaCode>waterTowers.exe 2 6 3 5 2 8 1 4 2 2 5 3 5 7 4 1\nWater collected : 35\nC:\\rosettaCode>waterTowers.exe 5 5 5 5\nWater collected : 0\nC:\\rosettaCode>waterTowers.exe 8 7 7 6\nWater collected : 0\nC:\\rosettaCode>waterTowers.exe 6 7 10 7 6\nWater collected : 0\n\n"} +{"title": "Water collected between towers", "language": "JavaScript", "task": ";Task:\nIn 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 \u2588\u2588 9 \u2588\u2588 \n8 \u2588\u2588 8 \u2588\u2588 \n7 \u2588\u2588 \u2588\u2588 7 \u2588\u2588\u2248\u2248\u2248\u2248\u2248\u2248\u2248\u2248\u2588\u2588 \n6 \u2588\u2588 \u2588\u2588 \u2588\u2588 6 \u2588\u2588\u2248\u2248\u2588\u2588\u2248\u2248\u2248\u2248\u2588\u2588 \n5 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588\u2588\u2588 5 \u2588\u2588\u2248\u2248\u2588\u2588\u2248\u2248\u2588\u2588\u2248\u2248\u2588\u2588\u2588\u2588 \n4 \u2588\u2588 \u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 4 \u2588\u2588\u2248\u2248\u2588\u2588\u2248\u2248\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \n3 \u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 3 \u2588\u2588\u2588\u2588\u2588\u2588\u2248\u2248\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \n2 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588 2 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2248\u2248\u2588\u2588\n1 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 1 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\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* [https://youtu.be/ftcIcn8AmSY?t=536 Four Solutions to a Trivial Problem] \u2013 a Google Tech Talk by Guy Steele\n* [http://stackoverflow.com/questions/24414700/amazon-water-collected-between-towers/ Water collected between towers] on Stack Overflow, from which the example above is taken)\n* [https://gist.github.com/paf31/9d84ecf6a6a9b69cdb597a390f25764d An interesting Haskell solution], using the Tardis monad, by [https://gist.github.com/paf31 Phil Freeman] in a [https://gist.github.com/paf31/9d84ecf6a6a9b69cdb597a390f25764d Github gist].\n\n\n\n", "solution": "(function () {\n 'use strict';\n\n // waterCollected :: [Int] -> Int\n var waterCollected = function (xs) {\n return sum( // water above each bar\n zipWith(function (a, b) {\n return a - b; // difference between water level and bar\n },\n zipWith(min, // lower of two flanking walls\n scanl1(max, xs), // highest walls to left\n scanr1(max, xs) // highest walls to right\n ), \n xs // tops of bars\n )\n .filter(function (x) {\n return x > 0; // only bars with water above them\n })\n );\n };\n\n // GENERIC FUNCTIONS ----------------------------------------\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n var zipWith = function (f, xs, ys) {\n var ny = ys.length;\n return (xs.length <= ny ? xs : xs.slice(0, ny))\n .map(function (x, i) {\n return f(x, ys[i]);\n });\n };\n\n // scanl1 is a variant of scanl that has no starting value argument\n // scanl1 :: (a -> a -> a) -> [a] -> [a]\n var scanl1 = function (f, xs) {\n return xs.length > 0 ? scanl(f, xs[0], xs.slice(1)) : [];\n };\n\n // scanr1 is a variant of scanr that has no starting value argument\n // scanr1 :: (a -> a -> a) -> [a] -> [a]\n var scanr1 = function (f, xs) {\n return xs.length > 0 ? scanr(f, xs.slice(-1)[0], xs.slice(0, -1)) : [];\n };\n\n // scanl :: (b -> a -> b) -> b -> [a] -> [b]\n var scanl = function (f, startValue, xs) {\n var lst = [startValue];\n return xs.reduce(function (a, x) {\n var v = f(a, x);\n return lst.push(v), v;\n }, startValue), lst;\n };\n\n // scanr :: (b -> a -> b) -> b -> [a] -> [b]\n var scanr = function (f, startValue, xs) {\n var lst = [startValue];\n return xs.reduceRight(function (a, x) {\n var v = f(a, x);\n return lst.push(v), v;\n }, startValue), lst.reverse();\n };\n\n // sum :: (Num a) => [a] -> a\n var sum = function (xs) {\n return xs.reduce(function (a, x) {\n return a + x;\n }, 0);\n };\n\n // max :: Ord a => a -> a -> a\n var max = function (a, b) {\n return a > b ? a : b;\n };\n\n // min :: Ord a => a -> a -> a\n var min = function (a, b) {\n return b < a ? b : a;\n };\n\n // TEST ---------------------------------------------------\n return [\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 ].map(waterCollected);\n\n //--> [2, 14, 35, 0, 0, 0, 0]\n})();"} +{"title": "Water collected between towers", "language": "Python", "task": ";Task:\nIn 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 \u2588\u2588 9 \u2588\u2588 \n8 \u2588\u2588 8 \u2588\u2588 \n7 \u2588\u2588 \u2588\u2588 7 \u2588\u2588\u2248\u2248\u2248\u2248\u2248\u2248\u2248\u2248\u2588\u2588 \n6 \u2588\u2588 \u2588\u2588 \u2588\u2588 6 \u2588\u2588\u2248\u2248\u2588\u2588\u2248\u2248\u2248\u2248\u2588\u2588 \n5 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588\u2588\u2588 5 \u2588\u2588\u2248\u2248\u2588\u2588\u2248\u2248\u2588\u2588\u2248\u2248\u2588\u2588\u2588\u2588 \n4 \u2588\u2588 \u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 4 \u2588\u2588\u2248\u2248\u2588\u2588\u2248\u2248\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \n3 \u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 3 \u2588\u2588\u2588\u2588\u2588\u2588\u2248\u2248\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \n2 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588 2 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2248\u2248\u2588\u2588\n1 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 1 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\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* [https://youtu.be/ftcIcn8AmSY?t=536 Four Solutions to a Trivial Problem] \u2013 a Google Tech Talk by Guy Steele\n* [http://stackoverflow.com/questions/24414700/amazon-water-collected-between-towers/ Water collected between towers] on Stack Overflow, from which the example above is taken)\n* [https://gist.github.com/paf31/9d84ecf6a6a9b69cdb597a390f25764d An interesting Haskell solution], using the Tardis monad, by [https://gist.github.com/paf31 Phil Freeman] in a [https://gist.github.com/paf31/9d84ecf6a6a9b69cdb597a390f25764d Github gist].\n\n\n\n", "solution": "def water_collected(tower):\n N = len(tower)\n highest_left = [0] + [max(tower[:n]) for n in range(1,N)]\n highest_right = [max(tower[n:N]) for n in range(1,N)] + [0]\n water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0)\n for n in range(N)]\n print(\"highest_left: \", highest_left)\n print(\"highest_right: \", highest_right)\n print(\"water_level: \", water_level)\n print(\"tower_level: \", tower)\n print(\"total_water: \", sum(water_level))\n print(\"\")\n return sum(water_level)\n\ntowers = [[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[water_collected(tower) for tower in towers]"} +{"title": "Weird numbers", "language": "C", "task": "In number theory, a perfect either).\n\nIn other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is ''abundant''), but no subset of those divisors sums to the number itself (the number is not ''semiperfect'').\n\nFor example:\n\n* '''12''' is ''not'' a weird number.\n** It is abundant; its proper divisors '''1, 2, 3, 4, 6''' sum to '''16''' (which ''is'' > 12),\n** but it ''is'' semiperfect, e.g.: \u00a0 \u00a0 '''6 + 4 + 2 == 12'''.\n* '''70''' ''is'' a weird number.\n** It is abundant; its proper divisors '''1, 2, 5, 7, 10, 14, 35''' sum to '''74''' (which ''is'' > 70),\n** and there is no subset of proper divisors that sum to '''70'''.\n\n\n;Task:\nFind and display, here on this page, the first '''25''' weird numbers.\n\n\n;Related tasks:\n:* Abundant, deficient and perfect number classifications\n:* Proper divisors\n\n\n;See also:\n:* OEIS: A006037 weird numbers\n:* Wikipedia: weird number\n:* [http://mathworld.wolfram.com/WeirdNumber.html MathWorld: weird number]\n\n", "solution": "#include \"stdio.h\"\n#include \"stdlib.h\"\n#include \"stdbool.h\"\n#include \"string.h\"\n\nstruct int_a {\n int *ptr;\n size_t size;\n};\n\nstruct int_a divisors(int n) {\n int *divs, *divs2, *out;\n int i, j, c1 = 0, c2 = 0;\n struct int_a array;\n\n divs = malloc(n * sizeof(int) / 2);\n divs2 = malloc(n * sizeof(int) / 2);\n divs[c1++] = 1;\n\n for (i = 2; i * i <= n; i++) {\n if (n % i == 0) {\n j = n / i;\n divs[c1++] = i;\n if (i != j) {\n divs2[c2++] = j;\n }\n }\n }\n\n out = malloc((c1 + c2) * sizeof(int));\n for (int i = 0; i < c2; i++) {\n out[i] = divs2[i];\n }\n for (int i = 0; i < c1; i++) {\n out[c2 + i] = divs[c1 - i - 1];\n }\n array.ptr = out;\n array.size = c1 + c2;\n\n free(divs);\n free(divs2);\n return array;\n}\n\nbool abundant(int n, struct int_a divs) {\n int sum = 0;\n int i;\n for (i = 0; i < divs.size; i++) {\n sum += divs.ptr[i];\n }\n return sum > n;\n}\n\nbool semiperfect(int n, struct int_a divs) {\n if (divs.size > 0) {\n int h = *divs.ptr;\n int *t = divs.ptr + 1;\n\n struct int_a ta;\n ta.ptr = t;\n ta.size = divs.size - 1;\n\n if (n < h) {\n return semiperfect(n, ta);\n } else {\n return n == h\n || semiperfect(n - h, ta)\n || semiperfect(n, ta);\n }\n } else {\n return false;\n }\n}\n\nbool *sieve(int limit) {\n bool *w = calloc(limit, sizeof(bool));\n struct int_a divs;\n int i, j;\n\n for (i = 2; i < limit; i += 2) {\n if (w[i]) continue;\n divs = divisors(i);\n if (!abundant(i, divs)) {\n w[i] = true;\n } else if (semiperfect(i, divs)) {\n for (j = i; j < limit; j += i) {\n w[j] = true;\n }\n }\n }\n\n free(divs.ptr);\n return w;\n}\n\nint main() {\n bool *w = sieve(17000);\n int count = 0;\n int max = 25;\n int n;\n\n printf(\"The first 25 weird numbers:\\n\");\n for (n = 2; count < max; n += 2) {\n if (!w[n]) {\n printf(\"%d \", n);\n count++;\n }\n }\n printf(\"\\n\");\n\n free(w);\n return 0;\n}"} +{"title": "Weird numbers", "language": "JavaScript", "task": "In number theory, a perfect either).\n\nIn other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is ''abundant''), but no subset of those divisors sums to the number itself (the number is not ''semiperfect'').\n\nFor example:\n\n* '''12''' is ''not'' a weird number.\n** It is abundant; its proper divisors '''1, 2, 3, 4, 6''' sum to '''16''' (which ''is'' > 12),\n** but it ''is'' semiperfect, e.g.: \u00a0 \u00a0 '''6 + 4 + 2 == 12'''.\n* '''70''' ''is'' a weird number.\n** It is abundant; its proper divisors '''1, 2, 5, 7, 10, 14, 35''' sum to '''74''' (which ''is'' > 70),\n** and there is no subset of proper divisors that sum to '''70'''.\n\n\n;Task:\nFind and display, here on this page, the first '''25''' weird numbers.\n\n\n;Related tasks:\n:* Abundant, deficient and perfect number classifications\n:* Proper divisors\n\n\n;See also:\n:* OEIS: A006037 weird numbers\n:* Wikipedia: weird number\n:* [http://mathworld.wolfram.com/WeirdNumber.html MathWorld: weird number]\n\n", "solution": "(() => {\n 'use strict';\n\n // main :: IO ()\n const main = () =>\n take(25, weirds());\n\n\n // weirds :: Gen [Int]\n function* weirds() {\n let\n x = 1,\n i = 1;\n while (true) {\n x = until(isWeird, succ, x)\n console.log(i.toString() + ' -> ' + x)\n yield x;\n x = 1 + x;\n i = 1 + i;\n }\n }\n\n\n // isWeird :: Int -> Bool\n const isWeird = n => {\n const\n ds = descProperDivisors(n),\n d = sum(ds) - n;\n return 0 < d && !hasSum(d, ds)\n };\n\n // hasSum :: Int -> [Int] -> Bool\n const hasSum = (n, xs) => {\n const go = (n, xs) =>\n 0 < xs.length ? (() => {\n const\n h = xs[0],\n t = xs.slice(1);\n return n < h ? (\n go(n, t)\n ) : (\n n == h || hasSum(n - h, t) || hasSum(n, t)\n );\n })() : false;\n return go(n, xs);\n };\n\n\n // descProperDivisors :: Int -> [Int]\n const descProperDivisors = n => {\n const\n rRoot = Math.sqrt(n),\n intRoot = Math.floor(rRoot),\n blnPerfect = rRoot === intRoot,\n lows = enumFromThenTo(intRoot, intRoot - 1, 1)\n .filter(x => (n % x) === 0);\n return (\n reverse(lows)\n .slice(1)\n .map(x => n / x)\n ).concat((blnPerfect ? tail : id)(lows))\n };\n\n\n // GENERIC FUNCTIONS ----------------------------\n\n\n // enumFromThenTo :: Int -> Int -> Int -> [Int]\n const enumFromThenTo = (x1, x2, y) => {\n const d = x2 - x1;\n return Array.from({\n length: Math.floor(y - x2) / d + 2\n }, (_, i) => x1 + (d * i));\n };\n\n // id :: a -> a\n const id = x => x;\n\n // reverse :: [a] -> [a]\n const reverse = xs =>\n 'string' !== typeof xs ? (\n xs.slice(0).reverse()\n ) : xs.split('').reverse().join('');\n\n // succ :: Enum a => a -> a\n const succ = x => 1 + x;\n\n // sum :: [Num] -> Num\n const sum = xs => xs.reduce((a, x) => a + x, 0);\n\n // tail :: [a] -> [a]\n const tail = xs => 0 < xs.length ? xs.slice(1) : [];\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = (n, xs) =>\n 'GeneratorFunction' !== xs.constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // until :: (a -> Bool) -> (a -> a) -> a -> a\n const until = (p, f, x) => {\n let v = x;\n while (!p(v)) v = f(v);\n return v;\n };\n\n // MAIN ---\n return main();\n})();"} +{"title": "Weird numbers", "language": "Python", "task": "In number theory, a perfect either).\n\nIn other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is ''abundant''), but no subset of those divisors sums to the number itself (the number is not ''semiperfect'').\n\nFor example:\n\n* '''12''' is ''not'' a weird number.\n** It is abundant; its proper divisors '''1, 2, 3, 4, 6''' sum to '''16''' (which ''is'' > 12),\n** but it ''is'' semiperfect, e.g.: \u00a0 \u00a0 '''6 + 4 + 2 == 12'''.\n* '''70''' ''is'' a weird number.\n** It is abundant; its proper divisors '''1, 2, 5, 7, 10, 14, 35''' sum to '''74''' (which ''is'' > 70),\n** and there is no subset of proper divisors that sum to '''70'''.\n\n\n;Task:\nFind and display, here on this page, the first '''25''' weird numbers.\n\n\n;Related tasks:\n:* Abundant, deficient and perfect number classifications\n:* Proper divisors\n\n\n;See also:\n:* OEIS: A006037 weird numbers\n:* Wikipedia: weird number\n:* [http://mathworld.wolfram.com/WeirdNumber.html MathWorld: weird number]\n\n", "solution": "\n===Functional===\nThe first 50 seem to take c. 300 ms\n"} +{"title": "Weird numbers", "language": "Python 3", "task": "In number theory, a perfect either).\n\nIn other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is ''abundant''), but no subset of those divisors sums to the number itself (the number is not ''semiperfect'').\n\nFor example:\n\n* '''12''' is ''not'' a weird number.\n** It is abundant; its proper divisors '''1, 2, 3, 4, 6''' sum to '''16''' (which ''is'' > 12),\n** but it ''is'' semiperfect, e.g.: \u00a0 \u00a0 '''6 + 4 + 2 == 12'''.\n* '''70''' ''is'' a weird number.\n** It is abundant; its proper divisors '''1, 2, 5, 7, 10, 14, 35''' sum to '''74''' (which ''is'' > 70),\n** and there is no subset of proper divisors that sum to '''70'''.\n\n\n;Task:\nFind and display, here on this page, the first '''25''' weird numbers.\n\n\n;Related tasks:\n:* Abundant, deficient and perfect number classifications\n:* Proper divisors\n\n\n;See also:\n:* OEIS: A006037 weird numbers\n:* Wikipedia: weird number\n:* [http://mathworld.wolfram.com/WeirdNumber.html MathWorld: weird number]\n\n", "solution": "'''Weird numbers'''\n\nfrom itertools import chain, count, islice, repeat\nfrom functools import reduce\nfrom math import sqrt\nfrom time import time\n\n\n# weirds :: Gen [Int]\ndef weirds():\n '''Non-finite stream of weird numbers.\n (Abundant, but not semi-perfect)\n OEIS: A006037\n '''\n def go(n):\n ds = descPropDivs(n)\n d = sum(ds) - n\n return [n] if 0 < d and not hasSum(d, ds) else []\n return concatMap(go)(count(1))\n\n\n# hasSum :: Int -> [Int] -> Bool\ndef hasSum(n, xs):\n '''Does any subset of xs sum to n ?\n (Assuming xs to be sorted in descending\n order of magnitude)'''\n def go(n, xs):\n if xs:\n h, t = xs[0], xs[1:]\n if n < h: # Head too big. Forget it. Tail ?\n return go(n, t)\n else:\n # The head IS the target ?\n # Or the tail contains a sum for the\n # DIFFERENCE between the head and the target ?\n # Or the tail contains some OTHER sum for the target ?\n return n == h or go(n - h, t) or go(n, t)\n else:\n return False\n return go(n, xs)\n\n\n# descPropDivs :: Int -> [Int]\ndef descPropDivs(n):\n '''Descending positive divisors of n,\n excluding n itself.'''\n root = sqrt(n)\n intRoot = int(root)\n blnSqr = root == intRoot\n lows = [x for x in range(1, 1 + intRoot) if 0 == n % x]\n return [\n n // x for x in (\n lows[1:-1] if blnSqr else lows[1:]\n )\n ] + list(reversed(lows))\n\n\n# --------------------------TEST---------------------------\n\n# main :: IO ()\ndef main():\n '''Test'''\n\n start = time()\n n = 50\n xs = take(n)(weirds())\n\n print(\n (tabulated('First ' + str(n) + ' weird numbers:\\n')(\n lambda i: str(1 + i)\n )(str)(5)(\n index(xs)\n )(range(0, n)))\n )\n print(\n '\\nApprox computation time: ' +\n str(int(1000 * (time() - start))) + ' ms'\n )\n\n\n# -------------------------GENERIC-------------------------\n\n# chunksOf :: Int -> [a] -> [[a]]\ndef chunksOf(n):\n '''A series of lists of length n,\n subdividing the contents of xs.\n Where the length of xs is not evenly divible,\n the final list will be shorter than n.'''\n return lambda xs: reduce(\n lambda a, i: a + [xs[i:n + i]],\n range(0, len(xs), n), []\n ) if 0 < n else []\n\n\n# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n '''Right to left function composition.'''\n return lambda f: lambda x: g(f(x))\n\n\n# concatMap :: (a -> [b]) -> [a] -> [b]\ndef concatMap(f):\n '''A concatenated list or string over which a function f\n has been mapped.\n The list monad can be derived by using an (a -> [b])\n function which wraps its output in a list (using an\n empty list to represent computational failure).\n '''\n return lambda xs: chain.from_iterable(map(f, xs))\n\n\n# index (!!) :: [a] -> Int -> a\ndef index(xs):\n '''Item at given (zero-based) index.'''\n return lambda n: None if 0 > n else (\n xs[n] if (\n hasattr(xs, \"__getitem__\")\n ) else next(islice(xs, n, None))\n )\n\n\n# paddedMatrix :: a -> [[a]] -> [[a]]\ndef paddedMatrix(v):\n ''''A list of rows padded to equal length\n (where needed) with instances of the value v.'''\n def go(rows):\n return paddedRows(\n len(max(rows, key=len))\n )(v)(rows)\n return lambda rows: go(rows) if rows else []\n\n\n# paddedRows :: Int -> a -> [[a]] -[[a]]\ndef paddedRows(n):\n '''A list of rows padded (but never truncated)\n to length n with copies of value v.'''\n def go(v, xs):\n def pad(x):\n d = n - len(x)\n return (x + list(repeat(v, d))) if 0 < d else x\n return list(map(pad, xs))\n return lambda v: lambda xs: go(v, xs) if xs else []\n\n\n# showColumns :: Int -> [String] -> String\ndef showColumns(n):\n '''A column-wrapped string\n derived from a list of rows.'''\n def go(xs):\n def fit(col):\n w = len(max(col, key=len))\n\n def pad(x):\n return x.ljust(4 + w, ' ')\n return ''.join(map(pad, col))\n\n q, r = divmod(len(xs), n)\n return unlines(map(\n fit,\n transpose(paddedMatrix('')(\n chunksOf(q + int(bool(r)))(\n xs\n )\n ))\n ))\n return lambda xs: go(xs)\n\n\n# succ :: Enum a => a -> a\ndef succ(x):\n '''The successor of a value. For numeric types, (1 +).'''\n return 1 + x if isinstance(x, int) else (\n chr(1 + ord(x))\n )\n\n\n# tabulated :: String -> (a -> String) ->\n# (b -> String) ->\n# Int ->\n# (a -> b) -> [a] -> String\ndef tabulated(s):\n '''Heading -> x display function -> fx display function ->\n number of columns -> f -> value list -> tabular string.'''\n def go(xShow, fxShow, intCols, f, xs):\n w = max(map(compose(len)(xShow), xs))\n return s + '\\n' + showColumns(intCols)([\n xShow(x).rjust(w, ' ') + ' -> ' + fxShow(f(x)) for x in xs\n ])\n return lambda xShow: lambda fxShow: lambda nCols: (\n lambda f: lambda xs: go(\n xShow, fxShow, nCols, f, xs\n )\n )\n\n\n# take :: Int -> [a] -> [a]\n# take :: Int -> String -> String\ndef take(n):\n '''The prefix of xs of length n,\n or xs itself if n > length xs.'''\n return lambda xs: (\n xs[0:n]\n if isinstance(xs, list)\n else list(islice(xs, n))\n )\n\n\n# transpose :: Matrix a -> Matrix a\ndef transpose(m):\n '''The rows and columns of the argument transposed.\n (The matrix containers and rows can be lists or tuples).'''\n if m:\n inner = type(m[0])\n z = zip(*m)\n return (type(m))(\n map(inner, z) if tuple != inner else z\n )\n else:\n return m\n\n\n# unlines :: [String] -> String\ndef unlines(xs):\n '''A single string derived by the intercalation\n of a list of strings with the newline character.'''\n return '\\n'.join(xs)\n\n\n# until :: (a -> Bool) -> (a -> a) -> a -> a\ndef until(p):\n '''The result of repeatedly applying f until p holds.\n The initial seed value is x.'''\n def go(f, x):\n v = x\n while not p(v):\n v = f(v)\n return v\n return lambda f: lambda x: go(f, x)\n\n\n# MAIN ----------------------------------------------------\nif __name__ == '__main__':\n main()"} +{"title": "Word frequency", "language": "C", "task": "[[Category:Text processing]]\n\n;Task:\nGiven a text file and an integer \u00a0 '''n''', \u00a0 print/display the \u00a0 '''n''' \u00a0 most\ncommon words in the file \u00a0 (and the number of their occurrences) \u00a0 in decreasing frequency.\n\n\nFor the purposes of this task:\n* \u00a0 A word is a sequence of one or more contiguous letters.\n* \u00a0 You are free to define what a \u00a0 ''letter'' \u00a0 is. \n* \u00a0 Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.\n* \u00a0 You may treat a compound word like \u00a0 '''well-dressed''' \u00a0 as either one word or two. \n* \u00a0 The word \u00a0 '''it's''' \u00a0 could also be one or two words as you see fit. \n* \u00a0 You may also choose not to support non US-ASCII characters. \n* \u00a0 Assume words will not span multiple lines.\n* \u00a0 Don't worry about normalization of word spelling differences. \n* \u00a0 Treat \u00a0 '''color''' \u00a0 and \u00a0 '''colour''' \u00a0 as two distinct words.\n* \u00a0 Uppercase letters are considered equivalent to their lowercase counterparts.\n* \u00a0 Words of equal frequency can be listed in any order.\n* \u00a0 Feel free to explicitly state the thoughts behind the program decisions.\n\n\nShow example output using [http://www.gutenberg.org/files/135/135-0.txt Les Mis\u00e9rables from Project Gutenberg] as the text file input and display the top \u00a0 '''10''' \u00a0 most used words.\n\n\n;History:\nThis task was originally taken from programming pearls from [https://doi.org/10.1145/5948.315654 Communications of the ACM June 1986 Volume 29 Number 6]\nwhere this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,\ndemonstrating solving the problem in a 6 line Unix shell script (provided as an example below).\n\n\n;References:\n*[http://franklinchen.com/blog/2011/12/08/revisiting-knuth-and-mcilroys-word-count-programs/ McIlroy's program]\n\n\n\n\n", "solution": "#include \n#include \n#include \n\ntypedef struct word_count_tag {\n const char* word;\n size_t count;\n} word_count;\n\nint compare_word_count(const void* p1, const void* p2) {\n const word_count* w1 = p1;\n const word_count* w2 = p2;\n if (w1->count > w2->count)\n return -1;\n if (w1->count < w2->count)\n return 1;\n return 0;\n}\n\nbool get_top_words(const char* filename, size_t count) {\n GError* error = NULL;\n GMappedFile* mapped_file = g_mapped_file_new(filename, FALSE, &error);\n if (mapped_file == NULL) {\n fprintf(stderr, \"%s\\n\", error->message);\n g_error_free(error);\n return false;\n }\n const char* text = g_mapped_file_get_contents(mapped_file);\n if (text == NULL) {\n fprintf(stderr, \"File %s is empty\\n\", filename);\n g_mapped_file_unref(mapped_file);\n return false;\n }\n gsize file_size = g_mapped_file_get_length(mapped_file);\n // Store word counts in a hash table\n GHashTable* ht = g_hash_table_new_full(g_str_hash, g_str_equal,\n g_free, g_free);\n GRegex* regex = g_regex_new(\"\\\\w+\", 0, 0, NULL);\n GMatchInfo* match_info;\n g_regex_match_full(regex, text, file_size, 0, 0, &match_info, NULL);\n while (g_match_info_matches(match_info)) {\n char* word = g_match_info_fetch(match_info, 0);\n char* lower = g_utf8_strdown(word, -1);\n g_free(word);\n size_t* count = g_hash_table_lookup(ht, lower);\n if (count != NULL) {\n ++*count;\n g_free(lower);\n } else {\n count = g_new(size_t, 1);\n *count = 1;\n g_hash_table_insert(ht, lower, count);\n }\n g_match_info_next(match_info, NULL);\n }\n g_match_info_free(match_info);\n g_regex_unref(regex);\n g_mapped_file_unref(mapped_file);\n\n // Sort words in decreasing order of frequency\n size_t size = g_hash_table_size(ht);\n word_count* words = g_new(word_count, size);\n GHashTableIter iter;\n gpointer key, value;\n g_hash_table_iter_init(&iter, ht);\n for (size_t i = 0; g_hash_table_iter_next(&iter, &key, &value); ++i) {\n words[i].word = key;\n words[i].count = *(size_t*)value;\n }\n qsort(words, size, sizeof(word_count), compare_word_count);\n\n // Print the most common words\n if (count > size)\n count = size;\n printf(\"Top %lu words\\n\", count);\n printf(\"Rank\\tCount\\tWord\\n\");\n for (size_t i = 0; i < count; ++i)\n printf(\"%lu\\t%lu\\t%s\\n\", i + 1, words[i].count, words[i].word);\n g_free(words);\n g_hash_table_destroy(ht);\n return true;\n}\n\nint main(int argc, char** argv) {\n if (argc != 2) {\n fprintf(stderr, \"usage: %s file\\n\", argv[0]);\n return EXIT_FAILURE;\n }\n if (!get_top_words(argv[1], 10))\n return EXIT_FAILURE;\n return EXIT_SUCCESS;\n}"} +{"title": "Word frequency", "language": "Python", "task": "[[Category:Text processing]]\n\n;Task:\nGiven a text file and an integer \u00a0 '''n''', \u00a0 print/display the \u00a0 '''n''' \u00a0 most\ncommon words in the file \u00a0 (and the number of their occurrences) \u00a0 in decreasing frequency.\n\n\nFor the purposes of this task:\n* \u00a0 A word is a sequence of one or more contiguous letters.\n* \u00a0 You are free to define what a \u00a0 ''letter'' \u00a0 is. \n* \u00a0 Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.\n* \u00a0 You may treat a compound word like \u00a0 '''well-dressed''' \u00a0 as either one word or two. \n* \u00a0 The word \u00a0 '''it's''' \u00a0 could also be one or two words as you see fit. \n* \u00a0 You may also choose not to support non US-ASCII characters. \n* \u00a0 Assume words will not span multiple lines.\n* \u00a0 Don't worry about normalization of word spelling differences. \n* \u00a0 Treat \u00a0 '''color''' \u00a0 and \u00a0 '''colour''' \u00a0 as two distinct words.\n* \u00a0 Uppercase letters are considered equivalent to their lowercase counterparts.\n* \u00a0 Words of equal frequency can be listed in any order.\n* \u00a0 Feel free to explicitly state the thoughts behind the program decisions.\n\n\nShow example output using [http://www.gutenberg.org/files/135/135-0.txt Les Mis\u00e9rables from Project Gutenberg] as the text file input and display the top \u00a0 '''10''' \u00a0 most used words.\n\n\n;History:\nThis task was originally taken from programming pearls from [https://doi.org/10.1145/5948.315654 Communications of the ACM June 1986 Volume 29 Number 6]\nwhere this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,\ndemonstrating solving the problem in a 6 line Unix shell script (provided as an example below).\n\n\n;References:\n*[http://franklinchen.com/blog/2011/12/08/revisiting-knuth-and-mcilroys-word-count-programs/ McIlroy's program]\n\n\n\n\n", "solution": "import collections\nimport re\nimport string\nimport sys\n\ndef main():\n counter = collections.Counter(re.findall(r\"\\w+\",open(sys.argv[1]).read().lower()))\n print counter.most_common(int(sys.argv[2]))\n\nif __name__ == \"__main__\":\n main()"} +{"title": "Word search", "language": "Python 3.x", "task": "A word search puzzle typically consists of a grid of letters in which words are hidden.\n\nThere are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards.\n\nThe words may overlap but are not allowed to zigzag, or wrap around.\n\n;Task \nCreate a 10 by 10 word search and fill it using words from the [http://www.puzzlers.org/pub/wordlists/unixdict.txt unixdict]. Use only words that are longer than 2, and contain no non-alphabetic characters.\n\nThe cells not used by the hidden words should contain the message: ''Rosetta Code'', read from left to right, top to bottom. These letters should be somewhat evenly distributed over the grid, not clumped together. The message should be in upper case, the hidden words in lower case. All cells should either contain letters from the hidden words or from the message. \n\nPack a minimum of 25 words into the grid.\n\nPrint the resulting grid and the solutions.\n\n;Example\n\n\n 0 1 2 3 4 5 6 7 8 9\n\n0 n a y r y R e l m f \n1 y O r e t s g n a g \n2 t n e d i S k y h E \n3 n o t n c p c w t T \n4 a l s u u n T m a x \n5 r o k p a r i s h h \n6 a A c f p a e a c C \n7 u b u t t t O l u n \n8 g y h w a D h p m u \n9 m i r p E h o g a n \n\nparish (3,5)(8,5) gangster (9,1)(2,1)\npaucity (4,6)(4,0) guaranty (0,8)(0,1)\nprim (3,9)(0,9) huckster (2,8)(2,1)\nplasm (7,8)(7,4) fancy (3,6)(7,2)\nhogan (5,9)(9,9) nolo (1,2)(1,5)\nunder (3,4)(3,0) chatham (8,6)(8,0)\nate (4,8)(6,6) nun (9,7)(9,9)\nbutt (1,7)(4,7) hawk (9,5)(6,2)\nwhy (3,8)(1,8) ryan (3,0)(0,0)\nfay (9,0)(7,2) much (8,8)(8,5)\ntar (5,7)(5,5) elm (6,0)(8,0)\nmax (7,4)(9,4) pup (5,3)(3,5)\nmph (8,8)(6,8)\n\n\n", "solution": "\nimport re\nfrom random import shuffle, randint\n\ndirs = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]]\nn_rows = 10\nn_cols = 10\ngrid_size = n_rows * n_cols\nmin_words = 25\n\n\nclass Grid:\n def __init__(self):\n self.num_attempts = 0\n self.cells = [['' for _ in range(n_cols)] for _ in range(n_rows)]\n self.solutions = []\n\n\ndef read_words(filename):\n max_len = max(n_rows, n_cols)\n\n words = []\n with open(filename, \"r\") as file:\n for line in file:\n s = line.strip().lower()\n if re.match(r'^[a-z]{3,' + re.escape(str(max_len)) + r'}$', s) is not None:\n words.append(s)\n\n return words\n\n\ndef place_message(grid, msg):\n msg = re.sub(r'[^A-Z]', \"\", msg.upper())\n\n message_len = len(msg)\n if 0 < message_len < grid_size:\n gap_size = grid_size // message_len\n\n for i in range(0, message_len):\n pos = i * gap_size + randint(0, gap_size)\n grid.cells[pos // n_cols][pos % n_cols] = msg[i]\n\n return message_len\n\n return 0\n\n\ndef try_location(grid, word, direction, pos):\n r = pos // n_cols\n c = pos % n_cols\n length = len(word)\n\n # check bounds\n if (dirs[direction][0] == 1 and (length + c) > n_cols) or \\\n (dirs[direction][0] == -1 and (length - 1) > c) or \\\n (dirs[direction][1] == 1 and (length + r) > n_rows) or \\\n (dirs[direction][1] == -1 and (length - 1) > r):\n return 0\n\n rr = r\n cc = c\n i = 0\n overlaps = 0\n\n # check cells\n while i < length:\n if grid.cells[rr][cc] != '' and grid.cells[rr][cc] != word[i]:\n return 0\n cc += dirs[direction][0]\n rr += dirs[direction][1]\n i += 1\n\n rr = r\n cc = c\n i = 0\n # place\n while i < length:\n if grid.cells[rr][cc] == word[i]:\n overlaps += 1\n else:\n grid.cells[rr][cc] = word[i]\n\n if i < length - 1:\n cc += dirs[direction][0]\n rr += dirs[direction][1]\n\n i += 1\n\n letters_placed = length - overlaps\n if letters_placed > 0:\n grid.solutions.append(\"{0:<10} ({1},{2})({3},{4})\".format(word, c, r, cc, rr))\n\n return letters_placed\n\n\ndef try_place_word(grid, word):\n rand_dir = randint(0, len(dirs))\n rand_pos = randint(0, grid_size)\n\n for direction in range(0, len(dirs)):\n direction = (direction + rand_dir) % len(dirs)\n\n for pos in range(0, grid_size):\n pos = (pos + rand_pos) % grid_size\n\n letters_placed = try_location(grid, word, direction, pos)\n if letters_placed > 0:\n return letters_placed\n\n return 0\n\n\ndef create_word_search(words):\n grid = None\n num_attempts = 0\n\n while num_attempts < 100:\n num_attempts += 1\n shuffle(words)\n\n grid = Grid()\n message_len = place_message(grid, \"Rosetta Code\")\n target = grid_size - message_len\n\n cells_filled = 0\n for word in words:\n cells_filled += try_place_word(grid, word)\n if cells_filled == target:\n if len(grid.solutions) >= min_words:\n grid.num_attempts = num_attempts\n return grid\n else:\n break # grid is full but we didn't pack enough words, start over\n\n return grid\n\n\ndef print_result(grid):\n if grid is None or grid.num_attempts == 0:\n print(\"No grid to display\")\n return\n\n size = len(grid.solutions)\n\n print(\"Attempts: {0}\".format(grid.num_attempts))\n print(\"Number of words: {0}\".format(size))\n\n print(\"\\n 0 1 2 3 4 5 6 7 8 9\\n\")\n for r in range(0, n_rows):\n print(\"{0} \".format(r), end='')\n for c in range(0, n_cols):\n print(\" %c \" % grid.cells[r][c], end='')\n print()\n print()\n\n for i in range(0, size - 1, 2):\n print(\"{0} {1}\".format(grid.solutions[i], grid.solutions[i+1]))\n\n if size % 2 == 1:\n print(grid.solutions[size - 1])\n\n\nif __name__ == \"__main__\":\n print_result(create_word_search(read_words(\"unixdict.txt\")))\n"} +{"title": "Word wrap", "language": "C", "task": "[[Category:Text processing]]\n\nEven today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. \n\n\n;Basic task:\nThe basic task is to wrap a paragraph of text in a simple way in your language. \n\nIf there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the [http://en.wikipedia.org/wiki/Word_wrap#Minimum_length minimum length greedy algorithm from Wikipedia.]\n\nShow your routine working on a sample of text at two different wrap columns.\n\n\n;Extra credit:\nWrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm. \nIf your language provides this, you get easy extra credit, \nbut you ''must reference documentation'' indicating that the algorithm \nis something better than a simple minimum length algorithm.\n\nIf you have both basic and extra credit solutions, show an example where \nthe two algorithms give different results.\n\n\n\n", "solution": "#include \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": "Word wrap", "language": "JavaScript", "task": "[[Category:Text processing]]\n\nEven today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. \n\n\n;Basic task:\nThe basic task is to wrap a paragraph of text in a simple way in your language. \n\nIf there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the [http://en.wikipedia.org/wiki/Word_wrap#Minimum_length minimum length greedy algorithm from Wikipedia.]\n\nShow your routine working on a sample of text at two different wrap columns.\n\n\n;Extra credit:\nWrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm. \nIf your language provides this, you get easy extra credit, \nbut you ''must reference documentation'' indicating that the algorithm \nis something better than a simple minimum length algorithm.\n\nIf you have both basic and extra credit solutions, show an example where \nthe two algorithms give different results.\n\n\n\n", "solution": "\nfunction wrap (text, limit) {\n if (text.length > limit) {\n // find the last space within limit\n var edge = text.slice(0, limit).lastIndexOf(' ');\n if (edge > 0) {\n var line = text.slice(0, edge);\n var remainder = text.slice(edge + 1);\n return line + '\\n' + wrap(remainder, limit);\n }\n }\n return text;\n}\n"} +{"title": "Word wrap", "language": "Python", "task": "[[Category:Text processing]]\n\nEven today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. \n\n\n;Basic task:\nThe basic task is to wrap a paragraph of text in a simple way in your language. \n\nIf there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the [http://en.wikipedia.org/wiki/Word_wrap#Minimum_length minimum length greedy algorithm from Wikipedia.]\n\nShow your routine working on a sample of text at two different wrap columns.\n\n\n;Extra credit:\nWrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm. \nIf your language provides this, you get easy extra credit, \nbut you ''must reference documentation'' indicating that the algorithm \nis something better than a simple minimum length algorithm.\n\nIf you have both basic and extra credit solutions, show an example where \nthe two algorithms give different results.\n\n\n\n", "solution": ">>> import textwrap\n>>> help(textwrap.fill)\nHelp on function fill in module textwrap:\n\nfill(text, width=70, **kwargs)\n Fill a single paragraph of text, returning a new string.\n \n Reformat the single paragraph in 'text' to fit in lines of no more\n than 'width' columns, and return a new string containing the entire\n wrapped paragraph. As with wrap(), tabs are expanded and other\n whitespace characters converted to space. See TextWrapper class for\n available keyword args to customize wrapping behaviour.\n\n>>> txt = '''\\\nReformat the single paragraph in 'text' to fit in lines of no more\nthan 'width' columns, and return a new string containing the entire\nwrapped paragraph. As with wrap(), tabs are expanded and other\nwhitespace characters converted to space. See TextWrapper class for\navailable keyword args to customize wrapping behaviour.'''\n>>> print(textwrap.fill(txt, width=75))\nReformat the single paragraph in 'text' to fit in lines of no more than\n'width' columns, and return a new string containing the entire wrapped\nparagraph. As with wrap(), tabs are expanded and other whitespace\ncharacters converted to space. See TextWrapper class for available keyword\nargs to customize wrapping behaviour.\n>>> print(textwrap.fill(txt, width=45))\nReformat the single paragraph in 'text' to\nfit in lines of no more than 'width' columns,\nand return a new string containing the entire\nwrapped paragraph. As with wrap(), tabs are\nexpanded and other whitespace characters\nconverted to space. See TextWrapper class\nfor available keyword args to customize\nwrapping behaviour.\n>>> print(textwrap.fill(txt, width=85))\nReformat the single paragraph in 'text' to fit in lines of no more than 'width'\ncolumns, and return a new string containing the entire wrapped paragraph. As with\nwrap(), tabs are expanded and other whitespace characters converted to space. See\nTextWrapper class for available keyword args to customize wrapping behaviour.\n>>> "} +{"title": "World Cup group stage", "language": "C", "task": "It's World Cup season (or at least it was when this page was created)! \n\nThe World Cup is an international football/soccer tournament that happens every 4 years. \u00a0 Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games. \u00a0 Once a team has qualified they are put into a group with 3 other teams. \n\nFor the first part of the World Cup tournament the teams play in \"group stage\" games where each of the four teams in a group plays all three other teams once. \u00a0 The results of these games determine which teams will move on to the \"knockout stage\" which is a standard single-elimination tournament. \u00a0 The two teams from each group with the most standings points move on to the knockout stage. \n\nEach game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team. \n:::* \u00a0 A win is worth three points.\n:::* \u00a0 A draw/tie is worth one point. \n:::* \u00a0 A loss is worth zero points.\n\n\n;Task:\n:* \u00a0 Generate all possible outcome combinations for the six group stage games. \u00a0 With three possible outcomes for each game there should be 36 = 729 of them. \n:* \u00a0 Calculate the standings points for each team with each combination of outcomes. \n:* \u00a0 Show a histogram (graphical, \u00a0 ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes.\n\n\nDon't worry about tiebreakers as they can get complicated. \u00a0 We are basically looking to answer the question \"if a team gets x standings points, where can they expect to end up in the group standings?\".\n\n''Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three. \u00a0 Oddly enough, there is no way to get 8 points at all.''\n\n", "solution": "#include \n#include \n#include \n#include \n\n// to supply to qsort\nint compare(const void *a, const void *b) {\n int int_a = *((int *)a);\n int int_b = *((int *)b);\n return (int_a > int_b) - (int_a < int_b);\n}\n\nchar results[7];\nbool next_result() {\n char *ptr = results + 5;\n int num = 0;\n size_t i;\n\n // check if the space has been examined\n if (strcmp(results, \"222222\") == 0) {\n return false;\n }\n\n // translate the base 3 string back to a base 10 integer\n for (i = 0; results[i] != 0; i++) {\n int d = results[i] - '0';\n num = 3 * num + d;\n }\n\n // to the next value to process\n num++;\n\n // write the base 3 string (fixed width)\n while (num > 0) {\n int rem = num % 3;\n num /= 3;\n *ptr-- = rem + '0';\n }\n // zero fill the remainder\n while (ptr > results) {\n *ptr-- = '0';\n }\n\n return true;\n}\n\nchar *games[6] = { \"12\", \"13\", \"14\", \"23\", \"24\", \"34\" };\nchar *places[4] = { \"1st\", \"2nd\", \"3rd\", \"4th\" };\nint main() {\n int points[4][10];\n size_t i, j;\n\n strcpy(results, \"000000\");\n for (i = 0; i < 4; i++) {\n for (j = 0; j < 10; j++) {\n points[i][j] = 0;\n }\n }\n\n do {\n int records[] = { 0, 0, 0, 0 };\n\n for (i = 0; i < 6; i++) {\n switch (results[i]) {\n case '2':\n records[games[i][0] - '1'] += 3;\n break;\n case '1':\n records[games[i][0] - '1']++;\n records[games[i][1] - '1']++;\n break;\n case '0':\n records[games[i][1] - '1'] += 3;\n break;\n default:\n break;\n }\n }\n\n qsort(records, 4, sizeof(int), compare);\n for (i = 0; i < 4; i++) {\n points[i][records[i]]++;\n }\n } while (next_result());\n\n printf(\"POINTS 0 1 2 3 4 5 6 7 8 9\\n\");\n printf(\"-----------------------------------------------------------\\n\");\n for (i = 0; i < 4; i++) {\n printf(\"%s place\", places[i]);\n for (j = 0; j < 10; j++) {\n printf(\"%5d\", points[3 - i][j]);\n }\n printf(\"\\n\");\n }\n\n return 0;\n}"} +{"title": "World Cup group stage", "language": "Python", "task": "It's World Cup season (or at least it was when this page was created)! \n\nThe World Cup is an international football/soccer tournament that happens every 4 years. \u00a0 Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games. \u00a0 Once a team has qualified they are put into a group with 3 other teams. \n\nFor the first part of the World Cup tournament the teams play in \"group stage\" games where each of the four teams in a group plays all three other teams once. \u00a0 The results of these games determine which teams will move on to the \"knockout stage\" which is a standard single-elimination tournament. \u00a0 The two teams from each group with the most standings points move on to the knockout stage. \n\nEach game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team. \n:::* \u00a0 A win is worth three points.\n:::* \u00a0 A draw/tie is worth one point. \n:::* \u00a0 A loss is worth zero points.\n\n\n;Task:\n:* \u00a0 Generate all possible outcome combinations for the six group stage games. \u00a0 With three possible outcomes for each game there should be 36 = 729 of them. \n:* \u00a0 Calculate the standings points for each team with each combination of outcomes. \n:* \u00a0 Show a histogram (graphical, \u00a0 ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes.\n\n\nDon't worry about tiebreakers as they can get complicated. \u00a0 We are basically looking to answer the question \"if a team gets x standings points, where can they expect to end up in the group standings?\".\n\n''Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three. \u00a0 Oddly enough, there is no way to get 8 points at all.''\n\n", "solution": "from itertools import product, combinations, izip\n\nscoring = [0, 1, 3]\nhisto = [[0] * 10 for _ in xrange(4)]\n\nfor results in product(range(3), repeat=6):\n s = [0] * 4\n for r, g in izip(results, combinations(range(4), 2)):\n s[g[0]] += scoring[r]\n s[g[1]] += scoring[2 - r]\n\n for h, v in izip(histo, sorted(s)):\n h[v] += 1\n\nfor x in reversed(histo):\n print x"} +{"title": "Write float arrays to a text file", "language": "C", "task": ";Task:\nWrite 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 float arrays to a text file", "language": "Python 2.6", "task": ";Task:\nWrite 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": ">>> import math\n>>> x = [1, 2, 3, 1e11]\n>>> y = map(math.sqrt, x)\n>>> y\n[1.0, 1.4142135623730951, 1.7320508075688772, 316227.76601683791]\n>>> writedat(\"sqrt.dat\", x, y)\n>>> # check \n...\n>>> for line in open('sqrt.dat'):\n... print line,\n...\n1 1\n2 1.4142\n3 1.7321\n1e+011 3.1623e+005"} +{"title": "Write float arrays to a text file", "language": "Python 3", "task": ";Task:\nWrite 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": "def writedat(filename, x, y, xprecision=3, yprecision=5):\n with open(filename,'w') as f:\n for a, b in zip(x, y):\n print(\"%.*g\\t%.*g\" % (xprecision, a, yprecision, b), file=f)\n #or, using the new-style formatting:\n #print(\"{1:.{0}g}\\t{3:.{2}g}\".format(xprecision, a, yprecision, b), file=f)"} +{"title": "Write language name in 3D ASCII", "language": "C", "task": ";Task:\nWrite/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 language name in 3D ASCII", "language": "Python", "task": ";Task:\nWrite/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": "py = '''\\\n #### # # ##### # # ### # #\n # # # # # # # # # ## #\n #### # # ##### # # # # #\n # # # # # # # # ##\n # # # # # ### # #'''\n\nlines = py.replace('#', '<<<').replace(' ','X') \\\n .replace('X', ' ').replace('\\n', ' Y') \\\n .replace('< ', '<>').split('Y')\n\nfor i, l in enumerate(lines): \n print(' ' * (len(lines) - i) + l)"} +{"title": "Write to Windows event log", "language": "C", "task": ";Task:\nWrite script status to the Windows Event Log\n\n", "solution": "\n#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": "Write to Windows event log", "language": "Python", "task": ";Task:\nWrite script status to the Windows Event Log\n\n", "solution": "import win32api\nimport win32con\nimport win32evtlog\nimport win32security\nimport win32evtlogutil\n\nph = win32api.GetCurrentProcess()\nth = win32security.OpenProcessToken(ph, win32con.TOKEN_READ)\nmy_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0]\n\napplicationName = \"My Application\"\neventID = 1\ncategory = 5\t# Shell\nmyType = win32evtlog.EVENTLOG_WARNING_TYPE\ndescr = [\"A warning\", \"An even more dire warning\"]\ndata = \"Application\\0Data\".encode(\"ascii\")\n\nwin32evtlogutil.ReportEvent(applicationName, eventID, eventCategory=category, \n\teventType=myType, strings=descr, data=data, sid=my_sid)"} +{"title": "Yellowstone sequence", "language": "C", "task": "[[Category:Prime Numbers]]\n\nThe '''Yellowstone sequence''', also called the '''Yellowstone permutation''', is defined as:\n\nFor n <= 3,\n\n a(n) = n\n\nFor n >= 4,\n\n a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and \n is not relatively prime to a(n-2).\n\n\nThe sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence.\n\n\n;Example:\na(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2).\n\n\n;Task\n: Find and show as output the first \u00a0'''30'''\u00a0 Yellowstone numbers.\n\n\n;Extra\n: Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers.\n\n\n;Related tasks:\n:* \u00a0 [https://rosettacode.org/wiki/Greatest_common_divisor Greatest common divisor].\n:* \u00a0 [https://rosettacode.org/wiki/Plot_coordinate_pairs Plot coordinate pairs].\n\n\n;See also:\n:* \u00a0 The OEIS entry: \u00a0 [https://oeis.org/A098550 A098550 The Yellowstone permutation].\n:* \u00a0 Applegate et al, 2015: The Yellowstone Permutation [https://arxiv.org/abs/1501.01669].\n\n", "solution": "#include \n#include \n#include \n\ntypedef struct lnode_t {\n struct lnode_t *prev;\n struct lnode_t *next;\n int v;\n} Lnode;\n\nLnode *make_list_node(int v) {\n Lnode *node = malloc(sizeof(Lnode));\n if (node == NULL) {\n return NULL;\n }\n node->v = v;\n node->prev = NULL;\n node->next = NULL;\n return node;\n}\n\nvoid free_lnode(Lnode *node) {\n if (node == NULL) {\n return;\n }\n\n node->v = 0;\n node->prev = NULL;\n free_lnode(node->next);\n node->next = NULL;\n}\n\ntypedef struct list_t {\n Lnode *front;\n Lnode *back;\n size_t len;\n} List;\n\nList *make_list() {\n List *list = malloc(sizeof(List));\n if (list == NULL) {\n return NULL;\n }\n list->front = NULL;\n list->back = NULL;\n list->len = 0;\n return list;\n}\n\nvoid free_list(List *list) {\n if (list == NULL) {\n return;\n }\n list->len = 0;\n list->back = NULL;\n free_lnode(list->front);\n list->front = NULL;\n}\n\nvoid list_insert(List *list, int v) {\n Lnode *node;\n\n if (list == NULL) {\n return;\n }\n\n node = make_list_node(v);\n if (list->front == NULL) {\n list->front = node;\n list->back = node;\n list->len = 1;\n } else {\n node->prev = list->back;\n list->back->next = node;\n list->back = node;\n list->len++;\n }\n}\n\nvoid list_print(List *list) {\n Lnode *it;\n\n if (list == NULL) {\n return;\n }\n\n for (it = list->front; it != NULL; it = it->next) {\n printf(\"%d \", it->v);\n }\n}\n\nint list_get(List *list, int idx) {\n Lnode *it = NULL;\n\n if (list != NULL && list->front != NULL) {\n int i;\n if (idx < 0) {\n it = list->back;\n i = -1;\n while (it != NULL && i > idx) {\n it = it->prev;\n i--;\n }\n } else {\n it = list->front;\n i = 0;\n while (it != NULL && i < idx) {\n it = it->next;\n i++;\n }\n }\n }\n\n if (it == NULL) {\n return INT_MIN;\n }\n return it->v;\n}\n\n///////////////////////////////////////\n\ntypedef struct mnode_t {\n int k;\n bool v;\n struct mnode_t *next;\n} Mnode;\n\nMnode *make_map_node(int k, bool v) {\n Mnode *node = malloc(sizeof(Mnode));\n if (node == NULL) {\n return node;\n }\n node->k = k;\n node->v = v;\n node->next = NULL;\n return node;\n}\n\nvoid free_mnode(Mnode *node) {\n if (node == NULL) {\n return;\n }\n node->k = 0;\n node->v = false;\n free_mnode(node->next);\n node->next = NULL;\n}\n\ntypedef struct map_t {\n Mnode *front;\n} Map;\n\nMap *make_map() {\n Map *map = malloc(sizeof(Map));\n if (map == NULL) {\n return NULL;\n }\n map->front = NULL;\n return map;\n}\n\nvoid free_map(Map *map) {\n if (map == NULL) {\n return;\n }\n free_mnode(map->front);\n map->front = NULL;\n}\n\nvoid map_insert(Map *map, int k, bool v) {\n if (map == NULL) {\n return;\n }\n if (map->front == NULL) {\n map->front = make_map_node(k, v);\n } else {\n Mnode *it = map->front;\n while (it->next != NULL) {\n it = it->next;\n }\n it->next = make_map_node(k, v);\n }\n}\n\nbool map_get(Map *map, int k) {\n if (map != NULL) {\n Mnode *it = map->front;\n while (it != NULL && it->k != k) {\n it = it->next;\n }\n if (it != NULL) {\n return it->v;\n }\n }\n return false;\n}\n\n///////////////////////////////////////\n\nint gcd(int u, int v) {\n if (u < 0) u = -u;\n if (v < 0) v = -v;\n if (v) {\n while ((u %= v) && (v %= u));\n }\n return u + v;\n}\n\nList *yellow(size_t n) {\n List *a;\n Map *b;\n int i;\n\n a = make_list();\n list_insert(a, 1);\n list_insert(a, 2);\n list_insert(a, 3);\n\n b = make_map();\n map_insert(b, 1, true);\n map_insert(b, 2, true);\n map_insert(b, 3, true);\n\n i = 4;\n\n while (n > a->len) {\n if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) {\n list_insert(a, i);\n map_insert(b, i, true);\n i = 4;\n }\n i++;\n }\n\n free_map(b);\n return a;\n}\n\nint main() {\n List *a = yellow(30);\n list_print(a);\n free_list(a);\n putc('\\n', stdout);\n return 0;\n}"} +{"title": "Yellowstone sequence", "language": "ES6", "task": "[[Category:Prime Numbers]]\n\nThe '''Yellowstone sequence''', also called the '''Yellowstone permutation''', is defined as:\n\nFor n <= 3,\n\n a(n) = n\n\nFor n >= 4,\n\n a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and \n is not relatively prime to a(n-2).\n\n\nThe sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence.\n\n\n;Example:\na(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2).\n\n\n;Task\n: Find and show as output the first \u00a0'''30'''\u00a0 Yellowstone numbers.\n\n\n;Extra\n: Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers.\n\n\n;Related tasks:\n:* \u00a0 [https://rosettacode.org/wiki/Greatest_common_divisor Greatest common divisor].\n:* \u00a0 [https://rosettacode.org/wiki/Plot_coordinate_pairs Plot coordinate pairs].\n\n\n;See also:\n:* \u00a0 The OEIS entry: \u00a0 [https://oeis.org/A098550 A098550 The Yellowstone permutation].\n:* \u00a0 Applegate et al, 2015: The Yellowstone Permutation [https://arxiv.org/abs/1501.01669].\n\n", "solution": "(() => {\n 'use strict';\n\n // yellowstone :: Generator [Int]\n function* yellowstone() {\n // A non finite stream of terms in the\n // Yellowstone permutation of the natural numbers.\n // OEIS A098550\n const nextWindow = ([p2, p1, rest]) => {\n const [rp2, rp1] = [p2, p1].map(\n relativelyPrime\n );\n const go = xxs => {\n const [x, xs] = Array.from(\n uncons(xxs).Just\n );\n return rp1(x) && !rp2(x) ? (\n Tuple(x)(xs)\n ) : secondArrow(cons(x))(\n go(xs)\n );\n };\n return [p1, ...Array.from(go(rest))];\n };\n const A098550 = fmapGen(x => x[1])(\n iterate(nextWindow)(\n [2, 3, enumFrom(4)]\n )\n );\n yield 1\n yield 2\n while (true)(\n yield A098550.next().value\n )\n };\n\n\n // relativelyPrime :: Int -> Int -> Bool\n const relativelyPrime = a =>\n // True if a is relatively prime to b.\n b => 1 === gcd(a)(b);\n\n\n // ------------------------TEST------------------------\n const main = () => console.log(\n take(30)(\n yellowstone()\n )\n );\n\n\n // -----------------GENERIC FUNCTIONS------------------\n\n // Just :: a -> Maybe a\n const Just = x => ({\n type: 'Maybe',\n Nothing: false,\n Just: x\n });\n\n // Nothing :: Maybe a\n const Nothing = () => ({\n type: 'Maybe',\n Nothing: true,\n });\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = a =>\n b => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // abs :: Num -> Num\n const abs =\n // Absolute value of a given number - without the sign.\n Math.abs;\n\n // cons :: a -> [a] -> [a]\n const cons = x =>\n xs => Array.isArray(xs) ? (\n [x].concat(xs)\n ) : 'GeneratorFunction' !== xs\n .constructor.constructor.name ? (\n x + xs\n ) : ( // cons(x)(Generator)\n function*() {\n yield x;\n let nxt = xs.next()\n while (!nxt.done) {\n yield nxt.value;\n nxt = xs.next();\n }\n }\n )();\n\n // enumFrom :: Enum a => a -> [a]\n function* enumFrom(x) {\n // A non-finite succession of enumerable\n // values, starting with the value x.\n let v = x;\n while (true) {\n yield v;\n v = 1 + v;\n }\n }\n\n // fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]\n const fmapGen = f =>\n function*(gen) {\n let v = take(1)(gen);\n while (0 < v.length) {\n yield(f(v[0]))\n v = take(1)(gen)\n }\n };\n\n // gcd :: Int -> Int -> Int\n const gcd = x => y => {\n const\n _gcd = (a, b) => (0 === b ? a : _gcd(b, a % b)),\n abs = Math.abs;\n return _gcd(abs(x), abs(y));\n };\n\n // iterate :: (a -> a) -> a -> Gen [a]\n const iterate = f =>\n function*(x) {\n let v = x;\n while (true) {\n yield(v);\n v = f(v);\n }\n };\n\n // length :: [a] -> Int\n const length = xs =>\n // Returns Infinity over objects without finite\n // length. This enables zip and zipWith to choose\n // the shorter argument when one is non-finite,\n // like cycle, repeat etc\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n // secondArrow :: (a -> b) -> ((c, a) -> (c, b))\n const secondArrow = f => xy =>\n // A function over a simple value lifted\n // to a function over a tuple.\n // f (a, b) -> (a, f(b))\n Tuple(xy[0])(\n f(xy[1])\n );\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n =>\n // The first n elements of a list,\n // string of characters, or stream.\n xs => 'GeneratorFunction' !== xs\n .constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // uncons :: [a] -> Maybe (a, [a])\n const uncons = xs => {\n // Just a tuple of the head of xs and its tail,\n // Or Nothing if xs is an empty list.\n const lng = length(xs);\n return (0 < lng) ? (\n Infinity > lng ? (\n Just(Tuple(xs[0])(xs.slice(1))) // Finite list\n ) : (() => {\n const nxt = take(1)(xs);\n return 0 < nxt.length ? (\n Just(Tuple(nxt[0])(xs))\n ) : Nothing();\n })() // Lazy generator\n ) : Nothing();\n };\n\n // MAIN ---\n return main();\n})();"} +{"title": "Yellowstone sequence", "language": "Python 3.7", "task": "[[Category:Prime Numbers]]\n\nThe '''Yellowstone sequence''', also called the '''Yellowstone permutation''', is defined as:\n\nFor n <= 3,\n\n a(n) = n\n\nFor n >= 4,\n\n a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and \n is not relatively prime to a(n-2).\n\n\nThe sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence.\n\n\n;Example:\na(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2).\n\n\n;Task\n: Find and show as output the first \u00a0'''30'''\u00a0 Yellowstone numbers.\n\n\n;Extra\n: Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers.\n\n\n;Related tasks:\n:* \u00a0 [https://rosettacode.org/wiki/Greatest_common_divisor Greatest common divisor].\n:* \u00a0 [https://rosettacode.org/wiki/Plot_coordinate_pairs Plot coordinate pairs].\n\n\n;See also:\n:* \u00a0 The OEIS entry: \u00a0 [https://oeis.org/A098550 A098550 The Yellowstone permutation].\n:* \u00a0 Applegate et al, 2015: The Yellowstone Permutation [https://arxiv.org/abs/1501.01669].\n\n", "solution": "'''Yellowstone permutation OEIS A098550'''\n\nfrom itertools import chain, count, islice\nfrom operator import itemgetter\nfrom math import gcd\n\nfrom matplotlib import pyplot\n\n\n# yellowstone :: [Int]\ndef yellowstone():\n '''A non-finite stream of terms from\n the Yellowstone permutation.\n OEIS A098550.\n '''\n # relativelyPrime :: Int -> Int -> Bool\n def relativelyPrime(a):\n return lambda b: 1 == gcd(a, b)\n\n # nextWindow :: (Int, Int, [Int]) -> (Int, Int, [Int])\n def nextWindow(triple):\n p2, p1, rest = triple\n [rp2, rp1] = map(relativelyPrime, [p2, p1])\n\n # match :: [Int] -> (Int, [Int])\n def match(xxs):\n x, xs = uncons(xxs)['Just']\n return (x, xs) if rp1(x) and not rp2(x) else (\n second(cons(x))(\n match(xs)\n )\n )\n n, residue = match(rest)\n return (p1, n, residue)\n\n return chain(\n range(1, 3),\n map(\n itemgetter(1),\n iterate(nextWindow)(\n (2, 3, count(4))\n )\n )\n )\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Terms of the Yellowstone permutation.'''\n\n print(showList(\n take(30)(yellowstone())\n ))\n pyplot.plot(\n take(100)(yellowstone())\n )\n pyplot.xlabel(main.__doc__)\n pyplot.show()\n\n\n# GENERIC -------------------------------------------------\n\n# Just :: a -> Maybe a\ndef Just(x):\n '''Constructor for an inhabited Maybe (option type) value.\n Wrapper containing the result of a computation.\n '''\n return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n# Nothing :: Maybe a\ndef Nothing():\n '''Constructor for an empty Maybe (option type) value.\n Empty wrapper returned where a computation is not possible.\n '''\n return {'type': 'Maybe', 'Nothing': True}\n\n\n# cons :: a -> [a] -> [a]\ndef cons(x):\n '''Construction of a list from x as head,\n and xs as tail.\n '''\n return lambda xs: [x] + xs if (\n isinstance(xs, list)\n ) else x + xs if (\n isinstance(xs, str)\n ) else chain([x], xs)\n\n\n# iterate :: (a -> a) -> a -> Gen [a]\ndef iterate(f):\n '''An infinite list of repeated\n applications of f to x.\n '''\n def go(x):\n v = x\n while True:\n yield v\n v = f(v)\n return go\n\n\n# second :: (a -> b) -> ((c, a) -> (c, b))\ndef second(f):\n '''A simple function lifted to a function over a tuple,\n with f applied only to the second of two values.\n '''\n return lambda xy: (xy[0], f(xy[1]))\n\n\n# showList :: [a] -> String\ndef showList(xs):\n '''Stringification of a list.'''\n return '[' + ','.join(repr(x) for x in xs) + ']'\n\n\n# take :: Int -> [a] -> [a]\n# take :: Int -> String -> String\ndef take(n):\n '''The prefix of xs of length n,\n or xs itself if n > length xs.\n '''\n return lambda xs: (\n xs[0:n]\n if isinstance(xs, (list, tuple))\n else list(islice(xs, n))\n )\n\n\n# uncons :: [a] -> Maybe (a, [a])\ndef uncons(xs):\n '''The deconstruction of a non-empty list\n (or generator stream) into two parts:\n a head value, and the remaining values.\n '''\n if isinstance(xs, list):\n return Just((xs[0], xs[1:])) if xs else Nothing()\n else:\n nxt = take(1)(xs)\n return Just((nxt[0], xs)) if nxt else Nothing()\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} +{"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* \u00a0 [http://oeis.org/A014417 OEIS A014417] \u00a0 for the the sequence of required results.\n* \u00a0 [http://www.youtube.com/watch?v=kQZmZRE0cQY&list=UUoxcjq-8xIDTYp3uz647V5A&index=3&feature=plcp Brown's Criterion - Numberphile]\n\n\n;Related task:\n* \u00a0 [[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": "Zeckendorf number representation", "language": "JavaScript", "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* \u00a0 [http://oeis.org/A014417 OEIS A014417] \u00a0 for the the sequence of required results.\n* \u00a0 [http://www.youtube.com/watch?v=kQZmZRE0cQY&list=UUoxcjq-8xIDTYp3uz647V5A&index=3&feature=plcp Brown's Criterion - Numberphile]\n\n\n;Related task:\n* \u00a0 [[Fibonacci sequence]]\n\n", "solution": "(() => {\n 'use strict';\n\n const main = () =>\n unlines(\n map(n => concat(zeckendorf(n)),\n enumFromTo(0, 20)\n )\n );\n\n // zeckendorf :: Int -> String\n const zeckendorf = n => {\n const go = (n, x) =>\n n < x ? (\n Tuple(n, '0')\n ) : Tuple(n - x, '1')\n return 0 < n ? (\n snd(mapAccumL(\n go, n,\n reverse(fibUntil(n))\n ))\n ) : ['0'];\n };\n\n // fibUntil :: Int -> [Int]\n const fibUntil = n =>\n cons(1, takeWhile(x => n >= x,\n map(snd, iterateUntil(\n tpl => n <= fst(tpl),\n tpl => {\n const x = snd(tpl);\n return Tuple(x, x + fst(tpl));\n },\n Tuple(1, 2)\n ))));\n\n // GENERIC FUNCTIONS ----------------------------\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = (a, b) => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // concat :: [[a]] -> [a]\n // concat :: [String] -> String\n const concat = xs =>\n 0 < xs.length ? (() => {\n const unit = 'string' !== typeof xs[0] ? (\n []\n ) : '';\n return unit.concat.apply(unit, xs);\n })() : [];\n\n // cons :: a -> [a] -> [a]\n const cons = (x, xs) =>\n Array.isArray(xs) ? (\n [x].concat(xs)\n ) : (x + xs);\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = (m, n) =>\n m <= n ? iterateUntil(\n x => n <= x,\n x => 1 + x,\n m\n ) : [];\n\n // fst :: (a, b) -> a\n const fst = tpl => tpl[0];\n\n // iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a]\n const iterateUntil = (p, f, x) => {\n const vs = [x];\n let h = x;\n while (!p(h))(h = f(h), vs.push(h));\n return vs;\n };\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) => xs.map(f);\n\n // 'The mapAccumL function behaves like a combination of map and foldl;\n // it applies a function to each element of a list, passing an accumulating\n // parameter from left to right, and returning a final value of this\n // accumulator together with the new list.' (See Hoogle)\n\n // mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])\n const mapAccumL = (f, acc, xs) =>\n xs.reduce((a, x, i) => {\n const pair = f(a[0], x, i);\n return Tuple(pair[0], a[1].concat(pair[1]));\n }, Tuple(acc, []));\n\n // reverse :: [a] -> [a]\n const reverse = xs =>\n 'string' !== typeof xs ? (\n xs.slice(0).reverse()\n ) : xs.split('').reverse().join('');\n\n // snd :: (a, b) -> b\n const snd = tpl => tpl[1];\n\n // tail :: [a] -> [a]\n const tail = xs => 0 < xs.length ? xs.slice(1) : [];\n\n // takeWhile :: (a -> Bool) -> [a] -> [a]\n // takeWhile :: (Char -> Bool) -> String -> String\n const takeWhile = (p, xs) => {\n const lng = xs.length;\n return 0 < lng ? xs.slice(\n 0,\n until(\n i => i === lng || !p(xs[i]),\n i => 1 + i,\n 0\n )\n ) : [];\n };\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // until :: (a -> Bool) -> (a -> a) -> a -> a\n const until = (p, f, x) => {\n let v = x;\n while (!p(v)) v = f(v);\n return v;\n };\n\n // MAIN ---\n return main();\n})();"} +{"title": "Zeckendorf number representation", "language": "Python", "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* \u00a0 [http://oeis.org/A014417 OEIS A014417] \u00a0 for the the sequence of required results.\n* \u00a0 [http://www.youtube.com/watch?v=kQZmZRE0cQY&list=UUoxcjq-8xIDTYp3uz647V5A&index=3&feature=plcp Brown's Criterion - Numberphile]\n\n\n;Related task:\n* \u00a0 [[Fibonacci sequence]]\n\n", "solution": "def fib():\n memo = [1, 2]\n while True:\n memo.append(sum(memo))\n yield memo.pop(0)\n\ndef sequence_down_from_n(n, seq_generator):\n seq = []\n for s in seq_generator():\n seq.append(s)\n if s >= n: break\n return seq[::-1]\n\ndef zeckendorf(n):\n if n == 0: return [0]\n seq = sequence_down_from_n(n, fib)\n digits, nleft = [], n\n for s in seq:\n if s <= nleft:\n digits.append(1)\n nleft -= s\n else:\n digits.append(0)\n assert nleft == 0, 'Check all of n is accounted for'\n assert sum(x*y for x,y in zip(digits, seq)) == n, 'Assert digits are correct'\n while digits[0] == 0:\n # Remove any zeroes padding L.H.S.\n digits.pop(0)\n return digits\n\nn = 20\nprint('Fibonacci digit multipliers: %r' % sequence_down_from_n(n, fib))\nfor i in range(n + 1):\n print('%3i: %8s' % (i, ''.join(str(d) for d in zeckendorf(i))))"} +{"title": "Zero to the zero power", "language": "C99", "task": "[[Category:Simple]]\nSome computer programming languages are not exactly consistent \u00a0 (with other computer programming languages) \u00a0 \nwhen \u00a0 ''raising zero to the zeroth power'': \u00a0 \u00a0 00\n\n\n;Task:\nShow the results of raising \u00a0 zero \u00a0 to the \u00a0 zeroth \u00a0 power.\n\n\nIf your computer language objects to \u00a0 \u00a0 '''0**0''' \u00a0 \u00a0 or \u00a0 \u00a0 '''0^0''' \u00a0 \u00a0 at compile time, \u00a0 you may also try something like:\n x = 0\n y = 0\n z = x**y\n say 'z=' z\n\n\n'''Show the result here.'''\nAnd of course use any symbols or notation that is supported in your computer programming language for exponentiation. \n\n\n;See also:\n* The Wiki entry: Zero to the power of zero. \n* The Wiki entry: Zero to the power of zero: History.\n* The MathWorld\u2122 entry: [http://mathworld.wolfram.com/ExponentLaws.html exponent laws].\n** Also, in the above MathWorld\u2122 entry, see formula ('''9'''): x^0=1.\n* The OEIS entry: [https://oeis.org/wiki/The_special_case_of_zero_to_the_zeroth_power The special case of zero to the zeroth power]\n\n", "solution": "#include \n#include \n#include \n\nint main()\n{\n\tprintf(\"0 ^ 0 = %f\\n\", pow(0,0));\n double complex c = cpow(0,0);\n\tprintf(\"0+0i ^ 0+0i = %f+%fi\\n\", creal(c), cimag(c));\n\treturn 0;\n}"} +{"title": "Zero to the zero power", "language": "Python", "task": "[[Category:Simple]]\nSome computer programming languages are not exactly consistent \u00a0 (with other computer programming languages) \u00a0 \nwhen \u00a0 ''raising zero to the zeroth power'': \u00a0 \u00a0 00\n\n\n;Task:\nShow the results of raising \u00a0 zero \u00a0 to the \u00a0 zeroth \u00a0 power.\n\n\nIf your computer language objects to \u00a0 \u00a0 '''0**0''' \u00a0 \u00a0 or \u00a0 \u00a0 '''0^0''' \u00a0 \u00a0 at compile time, \u00a0 you may also try something like:\n x = 0\n y = 0\n z = x**y\n say 'z=' z\n\n\n'''Show the result here.'''\nAnd of course use any symbols or notation that is supported in your computer programming language for exponentiation. \n\n\n;See also:\n* The Wiki entry: Zero to the power of zero. \n* The Wiki entry: Zero to the power of zero: History.\n* The MathWorld\u2122 entry: [http://mathworld.wolfram.com/ExponentLaws.html exponent laws].\n** Also, in the above MathWorld\u2122 entry, see formula ('''9'''): x^0=1.\n* The OEIS entry: [https://oeis.org/wiki/The_special_case_of_zero_to_the_zeroth_power The special case of zero to the zeroth power]\n\n", "solution": "from decimal import Decimal\nfrom fractions import Fraction\nfrom itertools import product\n\nzeroes = [0, 0.0, 0j, Decimal(0), Fraction(0, 1), -0.0, -0.0j, Decimal(-0.0)]\nfor i, j in product(zeroes, repeat=2):\n try:\n ans = i**j\n except:\n ans = ''\n print(f'{i!r:>15} ** {j!r:<15} = {ans!r}')"} +{"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 \u00a0 P9 \u00a0 \u00a0 P2 \u00a0 \u00a0 P3 \u00a0 \n \u00a0 P8 \u00a0 \u00a0 P1 \u00a0 \u00a0 P4 \u00a0 \n \u00a0 P7 \u00a0 \u00a0 P6 \u00a0 \u00a0 P5 \u00a0 \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* [http://nayefreza.wordpress.com/2013/05/11/zhang-suen-thinning-algorithm-java-implementation/ 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": "\n#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\n\nContents of input file : zhImage.txt\n\n10 32\n0 1\n00000000000000000000000000000000\n01111111110000000111111110000000\n01110001111000001111001111000000\n01110000111000001110000111000000\n01110001111000001110000000000000\n01111111110000001110000000000000\n01110111100000001110000111000000\n01110011110011101111001111011100\n01110001111011100111111110011100\n00000000000000000000000000000000\n\n\nConsole interaction :\n\nEnter full path of input image file : zhImage.txt\nEnter full path of output image file : out.txt\n\nPrinting original image :\n\n00000000000000000000000000000000\n01111111110000000111111110000000\n01110001111000001111001111000000\n01110000111000001110000111000000\n01110001111000001110000000000000\n01111111110000001110000000000000\n01110111100000001110000111000000\n01110011110011101111001111011100\n01110001111011100111111110011100\n00000000000000000000000000000000\n\n\nPrinting image after applying Zhang Suen Thinning Algorithm :\n\n\n00000000000000000000000000000000\n00111111100000000011111100000000\n00100000100000000110000000000000\n01000000100000000100000000000000\n01000000100000001000000000000000\n01111110100000001000000000000000\n00000001000000000100000000000000\n00000000100001000110000110001000\n00000000010000000001111000000000\n00000000000000000000000000000000\n\nImage also written to : out.txt\n\n\nContents of out.txt :\n\n00000000000000000000000000000000\n00111111100000000011111100000000\n00100000100000000110000000000000\n01000000100000000100000000000000\n01000000100000001000000000000000\n01111110100000001000000000000000\n00000001000000000100000000000000\n00000000100001000110000110001000\n00000000010000000001111000000000\n00000000000000000000000000000000\n\n"} +{"title": "Zhang-Suen thinning algorithm", "language": "JavaScript", "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 \u00a0 P9 \u00a0 \u00a0 P2 \u00a0 \u00a0 P3 \u00a0 \n \u00a0 P8 \u00a0 \u00a0 P1 \u00a0 \u00a0 P4 \u00a0 \n \u00a0 P7 \u00a0 \u00a0 P6 \u00a0 \u00a0 P5 \u00a0 \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* [http://nayefreza.wordpress.com/2013/05/11/zhang-suen-thinning-algorithm-java-implementation/ 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": "function Point(x, y) {\n this.x = x;\n this.y = y;\n}\nvar ZhangSuen = (function () {\n function ZhangSuen() {\n }\n ZhangSuen.image = \n [\" \",\n \" ################# ############# \",\n \" ################## ################ \",\n \" ################### ################## \",\n \" ######## ####### ################### \",\n \" ###### ####### ####### ###### \",\n \" ###### ####### ####### \",\n \" ################# ####### \",\n \" ################ ####### \",\n \" ################# ####### \",\n \" ###### ####### ####### \",\n \" ###### ####### ####### \",\n \" ###### ####### ####### ###### \",\n \" ######## ####### ################### \",\n \" ######## ####### ###### ################## ###### \",\n \" ######## ####### ###### ################ ###### \",\n \" ######## ####### ###### ############# ###### \",\n \" \"];\n\n ZhangSuen.nbrs = [[0, -1], [1, -1], [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1]];\n\n ZhangSuen.nbrGroups = [[[0, 2, 4], [2, 4, 6]], [[0, 2, 6], [0, 4, 6]]];\n\n ZhangSuen.toWhite = new Array();\n ;\n ZhangSuen.main = function (args) {\n ZhangSuen.grid = new Array(ZhangSuen.image.length);\n for (var r = 0; r < ZhangSuen.image.length; r++)\n ZhangSuen.grid[r] = (ZhangSuen.image[r]).split('');\n ZhangSuen.thinImage();\n };\n ZhangSuen.thinImage = function () {\n var firstStep = false;\n var hasChanged;\n do {\n hasChanged = false;\n firstStep = !firstStep;\n for (var r = 1; r < ZhangSuen.grid.length - 1; r++) {\n for (var c = 1; c < ZhangSuen.grid[0].length - 1; c++) {\n if (ZhangSuen.grid[r][c] !== '#')\n continue;\n var nn = ZhangSuen.numNeighbors(r, c);\n if (nn < 2 || nn > 6)\n continue;\n if (ZhangSuen.numTransitions(r, c) !== 1)\n continue;\n if (!ZhangSuen.atLeastOneIsWhite(r, c, firstStep ? 0 : 1))\n continue;\n ZhangSuen.toWhite.push(new Point(c, r));\n hasChanged = true;\n }\n }\n for (let i = 0; i < ZhangSuen.toWhite.length; i++) {\n var p = ZhangSuen.toWhite[i];\n ZhangSuen.grid[p.y][p.x] = ' ';\n }\n ZhangSuen.toWhite = new Array();\n } while ((firstStep || hasChanged));\n ZhangSuen.printResult();\n };\n ZhangSuen.numNeighbors = function (r, c) {\n var count = 0;\n for (var i = 0; i < ZhangSuen.nbrs.length - 1; i++)\n if (ZhangSuen.grid[r + ZhangSuen.nbrs[i][1]][c + ZhangSuen.nbrs[i][0]] === '#')\n count++;\n return count;\n };\n ZhangSuen.numTransitions = function (r, c) {\n var count = 0;\n for (var i = 0; i < ZhangSuen.nbrs.length - 1; i++)\n if (ZhangSuen.grid[r + ZhangSuen.nbrs[i][1]][c + ZhangSuen.nbrs[i][0]] === ' ') {\n if (ZhangSuen.grid[r + ZhangSuen.nbrs[i + 1][1]][c + ZhangSuen.nbrs[i + 1][0]] === '#')\n count++;\n }\n return count;\n };\n ZhangSuen.atLeastOneIsWhite = function (r, c, step) {\n var count = 0;\n var group = ZhangSuen.nbrGroups[step];\n for (var i = 0; i < 2; i++)\n for (var j = 0; j < group[i].length; j++) {\n var nbr = ZhangSuen.nbrs[group[i][j]];\n if (ZhangSuen.grid[r + nbr[1]][c + nbr[0]] === ' ') {\n count++;\n break;\n }\n }\n return count > 1;\n };\n ZhangSuen.printResult = function () {\n for (var i = 0; i < ZhangSuen.grid.length; i++) {\n var row = ZhangSuen.grid[i];\n console.log(row.join(''));\n }\n };\n return ZhangSuen;\n}());\nZhangSuen.main(null);"} +{"title": "Zhang-Suen thinning algorithm", "language": "Python", "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 \u00a0 P9 \u00a0 \u00a0 P2 \u00a0 \u00a0 P3 \u00a0 \n \u00a0 P8 \u00a0 \u00a0 P1 \u00a0 \u00a0 P4 \u00a0 \n \u00a0 P7 \u00a0 \u00a0 P6 \u00a0 \u00a0 P5 \u00a0 \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* [http://nayefreza.wordpress.com/2013/05/11/zhang-suen-thinning-algorithm-java-implementation/ 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": "# -*- coding: utf-8 -*-\n\n# Example from [http://nayefreza.wordpress.com/2013/05/11/zhang-suen-thinning-algorithm-java-implementation/ this blog post].\nbeforeTxt = '''\\\n1100111\n1100111\n1100111\n1100111\n1100110\n1100110\n1100110\n1100110\n1100110\n1100110\n1100110\n1100110\n1111110\n0000000\\\n'''\n\n# Thanks to [http://www.network-science.de/ascii/ this site] and vim for these next two examples\nsmallrc01 = '''\\\n00000000000000000000000000000000\n01111111110000000111111110000000\n01110001111000001111001111000000\n01110000111000001110000111000000\n01110001111000001110000000000000\n01111111110000001110000000000000\n01110111100000001110000111000000\n01110011110011101111001111011100\n01110001111011100111111110011100\n00000000000000000000000000000000\\\n'''\n\nrc01 = '''\\\n00000000000000000000000000000000000000000000000000000000000\n01111111111111111100000000000000000001111111111111000000000\n01111111111111111110000000000000001111111111111111000000000\n01111111111111111111000000000000111111111111111111000000000\n01111111100000111111100000000001111111111111111111000000000\n00011111100000111111100000000011111110000000111111000000000\n00011111100000111111100000000111111100000000000000000000000\n00011111111111111111000000000111111100000000000000000000000\n00011111111111111110000000000111111100000000000000000000000\n00011111111111111111000000000111111100000000000000000000000\n00011111100000111111100000000111111100000000000000000000000\n00011111100000111111100000000111111100000000000000000000000\n00011111100000111111100000000011111110000000111111000000000\n01111111100000111111100000000001111111111111111111000000000\n01111111100000111111101111110000111111111111111111011111100\n01111111100000111111101111110000001111111111111111011111100\n01111111100000111111101111110000000001111111111111011111100\n00000000000000000000000000000000000000000000000000000000000\\\n'''\n\ndef intarray(binstring):\n '''Change a 2D matrix of 01 chars into a list of lists of ints'''\n return [[1 if ch == '1' else 0 for ch in line] \n for line in binstring.strip().split()]\n\ndef chararray(intmatrix):\n '''Change a 2d list of lists of 1/0 ints into lines of 1/0 chars'''\n return '\\n'.join(''.join(str(p) for p in row) for row in intmatrix)\n\ndef toTxt(intmatrix):\n '''Change a 2d list of lists of 1/0 ints into lines of '#' and '.' chars'''\n return '\\n'.join(''.join(('#' if p else '.') for p in row) for row in intmatrix)\n\ndef neighbours(x, y, image):\n '''Return 8-neighbours of point p1 of picture, in order'''\n i = image\n x1, y1, x_1, y_1 = x+1, y-1, x-1, y+1\n #print ((x,y))\n return [i[y1][x], i[y1][x1], i[y][x1], i[y_1][x1], # P2,P3,P4,P5\n i[y_1][x], i[y_1][x_1], i[y][x_1], i[y1][x_1]] # P6,P7,P8,P9\n\ndef transitions(neighbours):\n n = neighbours + neighbours[0:1] # P2, ... P9, P2\n return sum((n1, n2) == (0, 1) for n1, n2 in zip(n, n[1:]))\n\ndef zhangSuen(image):\n changing1 = changing2 = [(-1, -1)]\n while changing1 or changing2:\n # Step 1\n changing1 = []\n for y in range(1, len(image) - 1):\n for x in range(1, len(image[0]) - 1):\n P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)\n if (image[y][x] == 1 and # (Condition 0)\n P4 * P6 * P8 == 0 and # Condition 4\n P2 * P4 * P6 == 0 and # Condition 3\n transitions(n) == 1 and # Condition 2\n 2 <= sum(n) <= 6): # Condition 1\n changing1.append((x,y))\n for x, y in changing1: image[y][x] = 0\n # Step 2\n changing2 = []\n for y in range(1, len(image) - 1):\n for x in range(1, len(image[0]) - 1):\n P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)\n if (image[y][x] == 1 and # (Condition 0)\n P2 * P6 * P8 == 0 and # Condition 4\n P2 * P4 * P8 == 0 and # Condition 3\n transitions(n) == 1 and # Condition 2\n 2 <= sum(n) <= 6): # Condition 1\n changing2.append((x,y))\n for x, y in changing2: image[y][x] = 0\n #print changing1\n #print changing2\n return image\n \n\nif __name__ == '__main__':\n for picture in (beforeTxt, smallrc01, rc01):\n image = intarray(picture)\n print('\\nFrom:\\n%s' % toTxt(image))\n after = zhangSuen(image)\n print('\\nTo thinned:\\n%s' % toTxt(after))"}