diff --git "a/solutions-2023-06-17.jsonl" "b/solutions-2023-06-17.jsonl" deleted file mode 100644--- "a/solutions-2023-06-17.jsonl" +++ /dev/null @@ -1,1656 +0,0 @@ -{"title": "100 doors", "language": "C", "task": "There are 100 doors in a row that are all initially closed. \n\nYou make 100 passes by the doors. \n\nThe first time through, visit every door and ''toggle'' the door (if the door is closed, open it; if it is open, close it). \n\nThe second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it. \n\nThe third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.\n\n\n;Task:\nAnswer the question: what state are the doors in after the last pass? Which are open, which are closed?\n\n\n'''Alternate:''' \nAs noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.\n\nOpening only those doors is an optimization that may also be expressed; \nhowever, as should be obvious, this defeats the intent of comparing implementations across programming languages.\n\n", "solution": "#include \n\n#define NUM_DOORS 100\n\nint main(int argc, char *argv[])\n{\n int is_open[NUM_DOORS] = { 0 } ;\n int * doorptr, * doorlimit = is_open + NUM_DOORS ;\n int pass ;\n\n /* do the N passes, go backwards because the order is not important */\n for ( pass= NUM_DOORS ; ( pass ) ; -- pass ) {\n for ( doorptr= is_open + ( pass-1 ); ( doorptr < doorlimit ) ; doorptr += pass ) {\n ( * doorptr ) ^= 1 ;\n }\n }\n\n /* output results */\n for ( doorptr= is_open ; ( doorptr != doorlimit ) ; ++ doorptr ) {\n printf(\"door #%lld is %s\\n\", ( doorptr - is_open ) + 1, ( * doorptr ) ? \"open\" : \"closed\" ) ;\n }\n}"} -{"title": "100 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 ''toggle'' the door (if the door is closed, open it; if it is open, close it). \n\nThe second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it. \n\nThe third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.\n\n\n;Task:\nAnswer the question: what state are the doors in after the last pass? Which are open, which are closed?\n\n\n'''Alternate:''' \nAs noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.\n\nOpening only those doors is an optimization that may also be expressed; \nhowever, as should be obvious, this defeats the intent of comparing implementations across programming languages.\n\n", "solution": "(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": "JavaScript Node.js 16.13.0 (LTS)", "task": "There are 100 doors in a row that are all initially closed. \n\nYou make 100 passes by the doors. \n\nThe first time through, visit every door and ''toggle'' the door (if the door is closed, open it; if it is open, close it). \n\nThe second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it. \n\nThe third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.\n\n\n;Task:\nAnswer the question: what state are the doors in after the last pass? Which are open, which are closed?\n\n\n'''Alternate:''' \nAs noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.\n\nOpening only those doors is an optimization that may also be expressed; \nhowever, as should be obvious, this defeats the intent of comparing implementations across programming languages.\n\n", "solution": "\"use strict\";\n\n// Doors can be open or closed.\nconst open = \"O\";\nconst closed = \"C\";\n\n// There are 100 doors in a row that are all initially closed.\nconst doorsCount = 100;\nconst doors = [];\nfor (let i = 0; i < doorsCount; doors[i] = closed, i++);\n\n// You make 100 passes by the doors, visiting every door and toggle the door (if\n// the door is closed, open it; if it is open, close it), according to the rules\n// of the task.\nfor (let pass = 1; pass <= doorsCount; pass++)\n for (let i = pass - 1; i < doorsCount; i += pass)\n doors[i] = doors[i] == open ? closed : open;\n\n// Answer the question: what state are the doors in after the last pass?\ndoors.forEach((v, i) =>\n console.log(`Doors ${i + 1} are ${v == open ? 'opened' : 'closed'}.`));\n\n// Which are open, which are closed?\nlet openKeyList = [];\nlet closedKeyList = [];\nfor (let door of doors.entries())\n if (door[1] == open)\n openKeyList.push(door[0] + 1);\n else\n closedKeyList.push(door[0] + 1);\nconsole.log(\"These are open doors: \" + openKeyList.join(\", \") + \".\");\nconsole.log(\"These are closed doors: \" + closedKeyList.join(\", \") + \".\");\n\n// Assert:\nconst expected = [];\nfor (let i = 1; i * i <= doorsCount; expected.push(i * i), i++);\nif (openKeyList.every((v, i) => v === expected[i]))\n console.log(\"The task is solved.\")\nelse\n throw \"These aren't the doors you're looking for.\";"} -{"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 ''toggle'' the door (if the door is closed, open it; if it is open, close it). \n\nThe second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it. \n\nThe third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.\n\n\n;Task:\nAnswer the question: what state are the doors in after the last pass? Which are open, which are closed?\n\n\n'''Alternate:''' \nAs noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.\n\nOpening only those doors is an optimization that may also be expressed; \nhowever, as should be obvious, this defeats the intent of comparing implementations across programming languages.\n\n", "solution": "doors = [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 ''toggle'' the door (if the door is closed, open it; if it is open, close it). \n\nThe second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it. \n\nThe third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.\n\n\n;Task:\nAnswer the question: what state are the doors in after the last pass? Which are open, which are closed?\n\n\n'''Alternate:''' \nAs noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.\n\nOpening only those doors is an optimization that may also be expressed; \nhowever, as should be obvious, this defeats the intent of comparing implementations across programming languages.\n\n", "solution": "for 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# The unbelievable solution to the 100 prisoner puzzle standupmaths (Video).\n# [[wp:100 prisoners problem]]\n# 100 Prisoners Escape Puzzle DataGenetics.\n# Random permutation statistics#One hundred prisoners on Wikipedia.\n\n", "solution": "#include\n#include\n#include\n#include\n\n#define LIBERTY false\n#define DEATH true\n\ntypedef struct{\n\tint cardNum;\n\tbool hasBeenOpened;\n}drawer;\n\ndrawer *drawerSet;\n\nvoid initialize(int prisoners){\n\tint i,j,card;\n\tbool unique;\n\n\tdrawerSet = ((drawer*)malloc(prisoners * sizeof(drawer))) -1;\n\n\tcard = rand()%prisoners + 1;\n\tdrawerSet[1] = (drawer){.cardNum = card, .hasBeenOpened = false};\n\n\tfor(i=1 + 1;i \",argv[0]);\n\n\tprisoners = atoi(argv[1]);\n\tchances = atoi(argv[2]);\n\ttrials = strtoull(argv[3],&end,10);\n\n\tsrand(time(NULL));\n\n\tprintf(\"Running random trials...\");\n\tfor(i=0;i // for rand\n#include // for random_shuffle\n#include // for output\n\nusing namespace std;\n\nclass cupboard {\npublic:\n cupboard() {\n for (int i = 0; i < 100; i++)\n drawers[i] = i;\n random_shuffle(drawers, drawers + 100);\n }\n\n bool playRandom();\n bool playOptimal();\n\nprivate:\n int drawers[100];\n};\n\nbool cupboard::playRandom() {\n bool openedDrawers[100] = { 0 };\n for (int prisonerNum = 0; prisonerNum < 100; prisonerNum++) { // loops through prisoners numbered 0 through 99\n bool prisonerSuccess = false;\n for (int i = 0; i < 100 / 2; i++) { // loops through 50 draws for each prisoner\n int drawerNum = rand() % 100;\n if (!openedDrawers[drawerNum]) {\n openedDrawers[drawerNum] = true;\n break;\n }\n if (drawers[drawerNum] == prisonerNum) {\n prisonerSuccess = true;\n break;\n }\n }\n if (!prisonerSuccess)\n return false;\n }\n return true;\n}\n\nbool cupboard::playOptimal() {\n for (int prisonerNum = 0; prisonerNum < 100; prisonerNum++) {\n bool prisonerSuccess = false;\n int checkDrawerNum = prisonerNum;\n for (int i = 0; i < 100 / 2; i++) {\n if (drawers[checkDrawerNum] == prisonerNum) {\n prisonerSuccess = true;\n break;\n } else\n checkDrawerNum = drawers[checkDrawerNum];\n }\n if (!prisonerSuccess)\n return false;\n }\n return true;\n}\n\ndouble simulate(char strategy) {\n int numberOfSuccesses = 0;\n for (int i = 0; i < 10000; i++) {\n cupboard d;\n if ((strategy == 'R' && d.playRandom()) || (strategy == 'O' && d.playOptimal())) // will run playRandom or playOptimal but not both because of short-circuit evaluation\n numberOfSuccesses++;\n }\n\n return numberOfSuccesses * 100.0 / 10000;\n}\n\nint main() {\n cout << \"Random strategy: \" << simulate('R') << \" %\" << endl;\n cout << \"Optimal strategy: \" << simulate('O') << \" %\" << endl;\n system(\"PAUSE\"); // for Windows\n return 0;\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# The unbelievable solution to the 100 prisoner puzzle standupmaths (Video).\n# [[wp:100 prisoners problem]]\n# 100 Prisoners Escape Puzzle DataGenetics.\n# Random permutation statistics#One hundred prisoners on Wikipedia.\n\n", "solution": "\"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# The unbelievable solution to the 100 prisoner puzzle standupmaths (Video).\n# [[wp:100 prisoners problem]]\n# 100 Prisoners Escape Puzzle DataGenetics.\n# Random permutation statistics#One hundred prisoners on Wikipedia.\n\n", "solution": "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": "100 prisoners", "language": "Python 3.7", "task": "The Problem:\n* 100 prisoners are individually numbered 1 to 100\n* A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside.\n* Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start.\n* Prisoners start outside the room\n:* They can decide some strategy before any enter the room.\n:* Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer.\n:* A prisoner can open no more than 50 drawers.\n:* A prisoner tries to find his own number.\n:* A prisoner finding his own number is then held apart from the others.\n* If '''all''' 100 prisoners find their own numbers then they will all be pardoned. If ''any'' don't then ''all'' sentences stand. \n\n\n;The task:\n# Simulate several thousand instances of the game where the prisoners randomly open drawers\n# Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of:\n:* First opening the drawer whose outside number is his prisoner number.\n:* If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum).\n\n\nShow and compare the computed probabilities of success for the two strategies, here, on this page.\n\n\n;References:\n# The unbelievable solution to the 100 prisoner puzzle standupmaths (Video).\n# [[wp:100 prisoners problem]]\n# 100 Prisoners Escape Puzzle DataGenetics.\n# Random permutation statistics#One hundred prisoners on Wikipedia.\n\n", "solution": "'''100 Prisoners'''\n\nfrom random import randint, sample\n\n\n# allChainedPathsAreShort :: Int -> IO (0|1)\ndef allChainedPathsAreShort(n):\n '''1 if none of the index-chasing cycles in a shuffled\n sample of [1..n] cards are longer than half the\n sample size. Otherwise, 0.\n '''\n limit = n // 2\n xs = range(1, 1 + n)\n shuffled = sample(xs, k=n)\n\n # A cycle of boxes, drawn from a shuffled\n # sample, which includes the given target.\n def cycleIncluding(target):\n boxChain = [target]\n v = shuffled[target - 1]\n while v != target:\n boxChain.append(v)\n v = shuffled[v - 1]\n return boxChain\n\n # Nothing if the target list is empty, or if the cycle which contains the\n # first target is larger than half the sample size.\n # Otherwise, just a cycle of enchained boxes containing the first target\n # in the list, tupled with the residue of any remaining targets which\n # fall outside that cycle.\n def boxCycle(targets):\n if targets:\n boxChain = cycleIncluding(targets[0])\n return Just((\n difference(targets[1:])(boxChain),\n boxChain\n )) if limit >= len(boxChain) else Nothing()\n else:\n return Nothing()\n\n # No cycles longer than half of total box count ?\n return int(n == sum(map(len, unfoldr(boxCycle)(xs))))\n\n\n# randomTrialResult :: RandomIO (0|1) -> Int -> (0|1)\ndef randomTrialResult(coin):\n '''1 if every one of the prisoners finds their ticket\n in an arbitrary half of the sample. Otherwise 0.\n '''\n return lambda n: int(all(\n coin(x) for x in range(1, 1 + n)\n ))\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Two sampling techniques constrasted with 100 drawers\n and 100 prisoners, over 100,000 trial runs.\n '''\n halfOfDrawers = randomRInt(0)(1)\n\n def optimalDrawerSampling(x):\n return allChainedPathsAreShort(x)\n\n def randomDrawerSampling(x):\n return randomTrialResult(halfOfDrawers)(x)\n\n # kSamplesWithNBoxes :: Int -> Int -> String\n def kSamplesWithNBoxes(k):\n tests = range(1, 1 + k)\n return lambda n: '\\n\\n' + fTable(\n str(k) + ' tests of optimal vs random drawer-sampling ' +\n 'with ' + str(n) + ' boxes: \\n'\n )(fName)(lambda r: '{:.2%}'.format(r))(\n lambda f: sum(f(n) for x in tests) / k\n )([\n optimalDrawerSampling,\n randomDrawerSampling,\n ])\n\n print(kSamplesWithNBoxes(10000)(10))\n\n print(kSamplesWithNBoxes(10000)(100))\n\n print(kSamplesWithNBoxes(100000)(100))\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# fname :: (a -> b) -> String\ndef fName(f):\n '''Name bound to the given function.'''\n return f.__name__\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# difference :: Eq a => [a] -> [a] -> [a]\ndef difference(xs):\n '''All elements of xs, except any also found in ys.'''\n return lambda ys: list(set(xs) - set(ys))\n\n\n# randomRInt :: Int -> Int -> IO () -> Int\ndef randomRInt(m):\n '''The return value of randomRInt is itself\n a function. The returned function, whenever\n called, yields a a new pseudo-random integer\n in the range [m..n].\n '''\n return lambda n: lambda _: randint(m, n)\n\n\n# unfoldr(lambda x: Just((x, x - 1)) if 0 != x else Nothing())(10)\n# -> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]\n# unfoldr :: (b -> Maybe (a, b)) -> b -> [a]\ndef unfoldr(f):\n '''Dual to reduce or foldr.\n Where catamorphism reduces a list to a summary value,\n the anamorphic unfoldr builds a list from a seed value.\n As long as f returns Just(a, b), a is prepended 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 xr = v, v\n xs = []\n while True:\n mb = f(xr[0])\n if mb.get('Nothing'):\n return xs\n else:\n xr = mb.get('Just')\n xs.append(xr[1])\n return xs\n return lambda x: go(x)\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} -{"title": "15 puzzle game", "language": "C", "task": "Implement the Fifteen Puzzle Game.\n\n\nThe '''15-puzzle''' is also known as: \n:::* '''Fifteen Puzzle'''\n:::* '''Gem Puzzle'''\n:::* '''Boss Puzzle'''\n:::* '''Game of Fifteen'''\n:::* '''Mystic Square'''\n:::* '''14-15 Puzzle'''\n:::* and some others.\n\n\n;Related Tasks:\n:* 15 Puzzle Solver\n:* [[16 Puzzle Game]]\n\n", "solution": "/*\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"} -{"title": "15 puzzle game", "language": "C++", "task": "Implement the Fifteen Puzzle Game.\n\n\nThe '''15-puzzle''' is also known as: \n:::* '''Fifteen Puzzle'''\n:::* '''Gem Puzzle'''\n:::* '''Boss Puzzle'''\n:::* '''Game of Fifteen'''\n:::* '''Mystic Square'''\n:::* '''14-15 Puzzle'''\n:::* and some others.\n\n\n;Related Tasks:\n:* 15 Puzzle Solver\n:* [[16 Puzzle Game]]\n\n", "solution": "#include \n#include \n#include \n#include \n#include \nclass p15 {\npublic :\n void play() {\n bool p = true;\n std::string a;\n while( p ) {\n createBrd();\n while( !isDone() ) { drawBrd();getMove(); }\n drawBrd();\n std::cout << \"\\n\\nCongratulations!\\nPlay again (Y/N)?\";\n std::cin >> a; if( a != \"Y\" && a != \"y\" ) break;\n }\n }\nprivate:\n void createBrd() {\n int i = 1; std::vector v;\n for( ; i < 16; i++ ) { brd[i - 1] = i; }\n brd[15] = 0; x = y = 3;\n for( i = 0; i < 1000; i++ ) {\n getCandidates( v );\n move( v[rand() % v.size()] );\n v.clear();\n }\n }\n void move( int d ) {\n int t = x + y * 4;\n switch( d ) {\n case 1: y--; break;\n case 2: x++; break;\n case 4: y++; break;\n case 8: x--;\n }\n brd[t] = brd[x + y * 4];\n brd[x + y * 4] = 0;\n }\n void getCandidates( std::vector& v ) {\n if( x < 3 ) v.push_back( 2 ); if( x > 0 ) v.push_back( 8 );\n if( y < 3 ) v.push_back( 4 ); if( y > 0 ) v.push_back( 1 );\n }\n void drawBrd() {\n int r; std::cout << \"\\n\\n\";\n for( int y = 0; y < 4; y++ ) {\n std::cout << \"+----+----+----+----+\\n\";\n for( int x = 0; x < 4; x++ ) {\n r = brd[x + y * 4];\n std::cout << \"| \";\n if( r < 10 ) std::cout << \" \";\n if( !r ) std::cout << \" \";\n else std::cout << r << \" \";\n }\n std::cout << \"|\\n\";\n }\n std::cout << \"+----+----+----+----+\\n\";\n }\n void getMove() {\n std::vector v; getCandidates( v );\n std::vector p; getTiles( p, v ); unsigned int i;\n while( true ) {\n std::cout << \"\\nPossible moves: \";\n for( i = 0; i < p.size(); i++ ) std::cout << p[i] << \" \";\n int z; std::cin >> z;\n for( i = 0; i < p.size(); i++ )\n if( z == p[i] ) { move( v[i] ); return; }\n }\n }\n void getTiles( std::vector& p, std::vector& v ) {\n for( unsigned int t = 0; t < v.size(); t++ ) {\n int xx = x, yy = y;\n switch( v[t] ) {\n case 1: yy--; break;\n case 2: xx++; break;\n case 4: yy++; break;\n case 8: xx--;\n }\n p.push_back( brd[xx + yy * 4] );\n }\n }\n bool isDone() {\n for( int i = 0; i < 15; i++ ) {\n if( brd[i] != i + 1 ) return false;\n }\n return true;\n }\n int brd[16], x, y;\n};\nint main( int argc, char* argv[] ) {\n srand( ( unsigned )time( 0 ) );\n p15 p; p.play(); return 0;\n}\n"} -{"title": "15 puzzle game", "language": "Python 3.X", "task": "Implement the Fifteen Puzzle Game.\n\n\nThe '''15-puzzle''' is also known as: \n:::* '''Fifteen Puzzle'''\n:::* '''Gem Puzzle'''\n:::* '''Boss Puzzle'''\n:::* '''Game of Fifteen'''\n:::* '''Mystic Square'''\n:::* '''14-15 Puzzle'''\n:::* and some others.\n\n\n;Related Tasks:\n:* 15 Puzzle Solver\n:* [[16 Puzzle Game]]\n\n", "solution": "''' 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 total''.\n\nThe game is won by the player whose chosen number causes the ''running total''\nto reach ''exactly'' '''21'''.\n\nThe ''running total'' starts at zero. \nOne player will be the computer.\n \nPlayers alternate supplying a number to be added to the ''running total''. \n\n\n;Task:\nWrite a computer program that will:\n::* do the prompting (or provide a button menu), \n::* check for errors and display appropriate error messages, \n::* do the additions (add a chosen number to the ''running total''), \n::* display the ''running total'', \n::* provide a mechanism for the player to quit/exit/halt/stop/close the program,\n::* issue a notification when there is a winner, and\n::* determine who goes first (maybe a random or user choice, or can be specified when the game begins). \n\n", "solution": "/**\n * Game 21 - an example in C language for Rosseta Code.\n *\n * A simple game program whose rules are described below\n * - see DESCRIPTION string.\n *\n * This program should be compatible with C89 and up.\n */\n\n\n/*\n * Turn off MS Visual Studio panic warnings which disable to use old gold\n * library functions like printf, scanf etc. This definition should be harmless\n * for non-MS compilers.\n */\n#define _CRT_SECURE_NO_WARNINGS\n\n#include \n#include \n#include \n\n/*\n * Define bool, true and false as needed. The stdbool.h is a standard header\n * in C99, therefore for older compilers we need DIY booleans. BTW, there is\n * no __STDC__VERSION__ predefined macro in MS Visual C, therefore we need\n * check also _MSC_VER.\n */\n#if __STDC_VERSION__ >= 199901L || _MSC_VER >= 1800\n#include \n#else\n#define bool int\n#define true 1\n#define false 0\n#endif\n\n#define GOAL 21\n#define NUMBER_OF_PLAYERS 2\n#define MIN_MOVE 1\n#define MAX_MOVE 3\n#define BUFFER_SIZE 256\n\n#define _(STRING) STRING\n\n\n/*\n * Spaces are meaningful: on some systems they can be visible.\n */\nstatic char DESCRIPTION[] = \n \"21 Game \\n\"\n \" \\n\"\n \"21 is a two player game, the game is played by choosing a number \\n\"\n \"(1, 2, or 3) to be added to the running total. The game is won by\\n\"\n \"the player whose chosen number causes the running total to reach \\n\"\n \"exactly 21. The running total starts at zero. \\n\\n\";\n\nstatic int total;\n\n\nvoid update(char* player, int move)\n{\n printf(\"%8s: %d = %d + %d\\n\\n\", player, total + move, total, move);\n total += move;\n if (total == GOAL)\n printf(_(\"The winner is %s.\\n\\n\"), player);\n}\n\n\nint ai()\n{\n/*\n * There is a winning strategy for the first player. The second player can win\n * then and only then the frist player does not use the winning strategy.\n * \n * The winning strategy may be defined as best move for the given running total.\n * The running total is a number from 0 to GOAL. Therefore, for given GOAL, best\n * moves may be precomputed (and stored in a lookup table). Actually (when legal\n * moves are 1 or 2 or 3) the table may be truncated to four first elements.\n */\n#if GOAL < 32 && MIN_MOVE == 1 && MAX_MOVE == 3\n static const int precomputed[] = { 1, 1, 3, 2, 1, 1, 3, 2, 1, 1, 3, 2, 1, 1,\n 3, 2, 1, 1, 3, 2, 1, 1, 3, 2, 1, 1, 3, 2, 1, 1, 3 };\n update(_(\"ai\"), precomputed[total]);\n#elif MIN_MOVE == 1 && MAX_MOVE == 3\n static const int precomputed[] = { 1, 1, 3, 2};\n update(_(\"ai\"), precomputed[total % (MAX_MOVE + 1)]);\n#else\n int i;\n int move = 1;\n for (i = MIN_MOVE; i <= MAX_MOVE; i++)\n if ((total + i - 1) % (MAX_MOVE + 1) == 0)\n move = i;\n for (i = MIN_MOVE; i <= MAX_MOVE; i++)\n if (total + i == GOAL)\n move = i;\n update(_(\"ai\"), move);\n#endif\n}\n\n\nvoid human(void)\n{\n char buffer[BUFFER_SIZE];\n int move;\n \n while ( printf(_(\"enter your move to play (or enter 0 to exit game): \")),\n fgets(buffer, BUFFER_SIZE, stdin), \n sscanf(buffer, \"%d\", &move) != 1 ||\n (move && (move < MIN_MOVE || move > MAX_MOVE || total+move > GOAL)))\n puts(_(\"\\nYour answer is not a valid choice.\\n\"));\n putchar('\\n');\n if (!move) exit(EXIT_SUCCESS);\n update(_(\"human\"), move);\n}\n\n\nint main(int argc, char* argv[])\n{\n srand(time(NULL));\n puts(_(DESCRIPTION));\n while (true)\n {\n puts(_(\"\\n---- NEW GAME ----\\n\"));\n puts(_(\"\\nThe running total is currently zero.\\n\"));\n total = 0;\n\n if (rand() % NUMBER_OF_PLAYERS)\n {\n puts(_(\"The first move is AI move.\\n\"));\n ai();\n }\n else\n puts(_(\"The first move is human move.\\n\"));\n\n while (total < GOAL)\n {\n human();\n ai();\n }\n }\n}"} -{"title": "21 game", "language": "C++", "task": "'''21''' is a two player game, the game is played by choosing \na number ('''1''', '''2''', or '''3''') to be added to the ''running total''.\n\nThe game is won by the player whose chosen number causes the ''running total''\nto reach ''exactly'' '''21'''.\n\nThe ''running total'' starts at zero. \nOne player will be the computer.\n \nPlayers alternate supplying a number to be added to the ''running total''. \n\n\n;Task:\nWrite a computer program that will:\n::* do the prompting (or provide a button menu), \n::* check for errors and display appropriate error messages, \n::* do the additions (add a chosen number to the ''running total''), \n::* display the ''running total'', \n::* provide a mechanism for the player to quit/exit/halt/stop/close the program,\n::* issue a notification when there is a winner, and\n::* determine who goes first (maybe a random or user choice, or can be specified when the game begins). \n\n", "solution": "/**\n * Game 21 - an example in C++ language for Rosseta Code.\n *\n * This version is an example of MVP architecture. The user input, as well as\n * the AI opponent, is handled by separate passive subclasses of abstract class\n * named Controller. It can be noticed that the architecture support OCP,\n * for an example the AI module can be \"easily\" replaced by another AI etc.\n *\n * BTW, it would be better to place each class in its own file. But it would\n * be less convinient for Rosseta Code, where \"one solution\" mean \"one file\".\n */\n\n#include \n#include \n#include \n#include \n#include \n\n\nusing namespace std;\n\n#define _(STR) STR\n\n\nclass Model\n{\nprotected:\n\n int oldTotal;\n int newTotal;\n int lastMove;\n\npublic:\n\n static const int GOAL = 21;\n static const int NUMBER_OF_PLAYERS = 2;\n\n Model()\n {\n newTotal = 0;\n oldTotal = 0;\n lastMove = 0;\n }\n\n void update(int move)\n {\n oldTotal = newTotal;\n newTotal = oldTotal + move;\n lastMove = move;\n }\n\n int getOldTotal()\n {\n return oldTotal;\n }\n\n int getNewTotal()\n {\n return newTotal;\n }\n\n int getLastMove()\n {\n return lastMove;\n }\n\n bool isEndGame()\n {\n return newTotal == GOAL;\n }\n};\n\n\nclass View\n{\npublic:\n\n void update(string comment, Model* model)\n {\n cout << setw(8) << comment << \": \"\n << model->getNewTotal()\n << \" = \"\n << model->getOldTotal()\n << \" + \"\n << model->getLastMove() << endl\n << endl;\n }\n\n void newGame(string player)\n {\n cout << _(\"----NEW GAME----\") << endl\n << endl\n << _(\"The running total is currently zero.\") << endl\n << endl\n << _(\"The first move is \") << player << _(\" move.\") << endl\n << endl;\n }\n\n void endGame(string name)\n {\n cout << endl << _(\"The winner is \") << name << _(\".\") << endl\n << endl\n << endl;\n }\n};\n\n\nclass Controller\n{\npublic:\n\n virtual string getName() = 0;\n virtual int getMove(Model* model) = 0;\n};\n\n\nclass AI : public Controller\n{\npublic:\n\n string getName()\n {\n return _(\"AI\");\n }\n\n int getMove(Model* model)\n {\n int n = model->getNewTotal();\n for (int i = 1; i <= 3; i++)\n if (n + i == Model::GOAL)\n return i;\n for (int i = 1; i <= 3; i++)\n if ((n + i - 1) % 4 == 0)\n return i;\n return 1 + rand() % 3;\n }\n};\n\n\nclass Human : public Controller\n{\npublic:\n\n string getName()\n {\n return _(\"human\");\n }\n\n int getMove(Model* model)\n {\n int n = model->getNewTotal();\n int value;\n while (true) {\n if (n == Model::GOAL - 1)\n cout << _(\"enter 1 to play (or enter 0 to exit game): \");\n else if (n == Model::GOAL - 2)\n cout << _(\"enter 1 or 2 to play (or enter 0 to exit game): \");\n else\n cout << _(\"enter 1 or 2 or 3 to play (or enter 0 to exit game): \");\n cin >> value;\n if (!cin.fail()) {\n if (value == 0)\n exit(0);\n else if (value >= 1 && value <= 3 && n + value <= Model::GOAL)\n {\n cout << endl;\n return value;\n }\n }\n cout << _(\"Your answer is not a valid choice.\") << endl;\n cin.clear();\n cin.ignore((streamsize)numeric_limits::max, '\\n');\n }\n }\n};\n\n\nclass Presenter\n{\nprotected:\n\n Model* model;\n View* view;\n Controller** controllers;\n\npublic:\n\n Presenter(Model* model, View* view, Controller** controllers)\n {\n this->model = model;\n this->view = view;\n this->controllers = controllers;\n }\n\n void run()\n {\n int player = rand() % Model::NUMBER_OF_PLAYERS;\n view->newGame(controllers[player]->getName());\n\n while (true)\n {\n Controller* controller = controllers[player];\n model->update(controller->getMove(model));\n view->update(controller->getName(), model);\n if (model->isEndGame())\n {\n view->endGame(controllers[player]->getName());\n break;\n }\n player = (player + 1) % Model::NUMBER_OF_PLAYERS;\n }\n }\n};\n\n\nint main(int argc, char* argv)\n{\n srand(time(NULL));\n\n while (true)\n {\n Model* model = new Model();\n View* view = new View();\n Controller* controllers[Model::NUMBER_OF_PLAYERS];\n controllers[0] = new Human();\n for (int i = 1; i < Model::NUMBER_OF_PLAYERS; i++)\n controllers[i] = new AI();\n Presenter* presenter = new Presenter(model, view, controllers);\n\n presenter->run();\n\n delete model;\n delete view;\n delete controllers[0];\n delete controllers[1];\n delete presenter;\n }\n return EXIT_SUCCESS; // dead code\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 total''.\n\nThe game is won by the player whose chosen number causes the ''running total''\nto reach ''exactly'' '''21'''.\n\nThe ''running total'' starts at zero. \nOne player will be the computer.\n \nPlayers alternate supplying a number to be added to the ''running total''. \n\n\n;Task:\nWrite a computer program that will:\n::* do the prompting (or provide a button menu), \n::* check for errors and display appropriate error messages, \n::* do the additions (add a chosen number to the ''running total''), \n::* display the ''running total'', \n::* provide a mechanism for the player to quit/exit/halt/stop/close the program,\n::* issue a notification when there is a winner, and\n::* determine who goes first (maybe a random or user choice, or can be specified when the game begins). \n\n", "solution": "from 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": "The 24 Game tests one's mental arithmetic. \n\n\n;Task\nWrite a program that displays four digits, each from 1 --> 9 (inclusive) with repetitions allowed.\n\nThe program should prompt for the player to enter an arithmetic expression using ''just'' those, and ''all'' of those four digits, used exactly ''once'' each. The program should ''check'' then evaluate the expression. \n\nThe goal is for the player to enter an expression that (numerically) evaluates to '''24'''.\n* Only the following operators/functions are allowed: multiplication, division, addition, subtraction\n* Division should use floating point or rational arithmetic, etc, to preserve remainders.\n* Brackets are allowed, if using an infix expression evaluator.\n* Forming multiple digit numbers from the supplied digits is ''disallowed''. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).\n* The order of the digits when given does not have to be preserved.\n\n\n;Notes\n* The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.\n* The task is not for the program to generate the expression, or test whether an expression is even possible.\n\n\n;Related tasks\n* [[24 game/Solve]]\n\n\n;Reference\n* The 24 Game on h2g2.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n \njmp_buf ctx;\nconst char *msg;\n \nenum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV };\n \ntypedef struct expr_t *expr, expr_t;\nstruct expr_t {\n\tint op, val, used;\n\texpr left, right;\n};\n \n#define N_DIGITS 4\nexpr_t digits[N_DIGITS];\n \nvoid gen_digits()\n{\n\tint i;\n\tfor (i = 0; i < N_DIGITS; i++)\n\t\tdigits[i].val = 1 + rand() % 9;\n}\n \n#define MAX_INPUT 64\nchar str[MAX_INPUT];\nint pos;\n \n#define POOL_SIZE 8\nexpr_t pool[POOL_SIZE];\nint pool_ptr;\n \nvoid reset()\n{\n\tint i;\n\tmsg = 0;\n\tpool_ptr = pos = 0;\n\tfor (i = 0; i < POOL_SIZE; i++) {\n\t\tpool[i].op = OP_NONE;\n\t\tpool[i].left = pool[i].right = 0;\n\t}\n\tfor (i = 0; i < N_DIGITS; i++)\n\t\tdigits[i].used = 0;\n}\n \n/* longish jumpish back to input cycle */\nvoid bail(const char *s)\n{\n\tmsg = s;\n\tlongjmp(ctx, 1);\n}\n \nexpr new_expr()\n{\n\tif (pool_ptr < POOL_SIZE)\n\t\treturn pool + pool_ptr++;\n\treturn 0;\n}\n \n/* check next input char */\nint next_tok()\n{\n\twhile (isspace(str[pos])) pos++;\n\treturn str[pos];\n}\n \n/* move input pointer forward */\nint take()\n{\n\tif (str[pos] != '\\0') return ++pos;\n\treturn 0;\n}\n \n/* BNF(ish)\nexpr = term { (\"+\")|(\"-\") term }\nterm = fact { (\"*\")|(\"/\") expr }\nfact =\tnumber\n\t| '(' expr ')'\n*/\n \nexpr get_fact();\nexpr get_term();\nexpr get_expr();\n \nexpr get_expr()\n{\n\tint c;\n\texpr l, r, ret;\n\tif (!(ret = get_term())) bail(\"Expected term\");\n\twhile ((c = next_tok()) == '+' || c == '-') {\n\t\tif (!take()) bail(\"Unexpected end of input\");\n\t\tif (!(r = get_term())) bail(\"Expected term\");\n \n\t\tl = ret;\n\t\tret = new_expr();\n\t\tret->op = (c == '+') ? OP_ADD : OP_SUB;\n\t\tret->left = l;\n\t\tret->right = r;\n\t}\n\treturn ret;\n}\n \nexpr get_term()\n{\n\tint c;\n\texpr l, r, ret;\n\tret = get_fact();\n\twhile((c = next_tok()) == '*' || c == '/') {\n\t\tif (!take()) bail(\"Unexpected end of input\");\n \n\t\tr = get_fact();\n\t\tl = ret;\n\t\tret = new_expr();\n\t\tret->op = (c == '*') ? OP_MUL : OP_DIV;\n\t\tret->left = l;\n\t\tret->right = r;\n\t}\n\treturn ret;\n}\n \nexpr get_digit()\n{\n\tint i, c = next_tok();\n\texpr ret;\n\tif (c >= '0' && c <= '9') {\n\t\ttake();\n\t\tret = new_expr();\n\t\tret->op = OP_NUM;\n\t\tret->val = c - '0';\n\t\tfor (i = 0; i < N_DIGITS; i++)\n\t\t\tif (digits[i].val == ret->val && !digits[i].used) {\n\t\t\t\tdigits[i].used = 1;\n\t\t\t\treturn ret;\n\t\t\t}\n\t\tbail(\"Invalid digit\");\n\t}\n\treturn 0;\n}\n \nexpr get_fact()\n{\n\tint c;\n\texpr l = get_digit();\n\tif (l) return l;\n\tif ((c = next_tok()) == '(') {\n\t\ttake();\n\t\tl = get_expr();\n\t\tif (next_tok() != ')') bail(\"Unbalanced parens\");\n\t\ttake();\n\t\treturn l;\n\t}\n\treturn 0;\n}\n \nexpr parse()\n{\n\tint i;\n\texpr ret = get_expr();\n\tif (next_tok() != '\\0')\n\t\tbail(\"Trailing garbage\");\n\tfor (i = 0; i < N_DIGITS; i++)\n\t\tif (!digits[i].used)\n\t\t\tbail(\"Not all digits are used\");\n\treturn ret;\n}\n \ntypedef struct frac_t frac_t, *frac;\nstruct frac_t { int denom, num; };\n \nint gcd(int m, int n)\n{\n\tint t;\n\twhile (m) {\n\t\tt = m; m = n % m; n = t;\n\t}\n\treturn n;\n}\n \n/* evaluate expression tree. result in fraction form */\nvoid eval_tree(expr e, frac res)\n{\n\tfrac_t l, r;\n\tint t;\n\tif (e->op == OP_NUM) {\n\t\tres->num = e->val;\n\t\tres->denom = 1;\n\t\treturn;\n\t}\n \n\teval_tree(e->left, &l);\n\teval_tree(e->right, &r);\n \n\tswitch(e->op) {\n\tcase OP_ADD:\n\t\tres->num = l.num * r.denom + l.denom * r.num;\n\t\tres->denom = l.denom * r.denom;\n\t\tbreak;\n\tcase OP_SUB:\n\t\tres->num = l.num * r.denom - l.denom * r.num;\n\t\tres->denom = l.denom * r.denom;\n\t\tbreak;\n\tcase OP_MUL:\n\t\tres->num = l.num * r.num;\n\t\tres->denom = l.denom * r.denom;\n\t\tbreak;\n\tcase OP_DIV:\n\t\tres->num = l.num * r.denom;\n\t\tres->denom = l.denom * r.num;\n\t\tbreak;\n\t}\n\tif ((t = gcd(res->denom, res->num))) {\n\t\tres->denom /= t;\n\t\tres->num /= t;\n\t}\n}\n \nvoid get_input()\n{\n\tint i;\nreinput:\n\treset();\n\tprintf(\"\\nAvailable digits are:\");\n\tfor (i = 0; i < N_DIGITS; i++) \n\t\tprintf(\" %d\", digits[i].val);\n\tprintf(\". Type an expression and I'll check it for you, or make new numbers.\\n\"\n\t\t\"Your choice? [Expr/n/q] \");\n \n\twhile (1) {\n\t\tfor (i = 0; i < MAX_INPUT; i++) str[i] = '\\n';\n\t\tfgets(str, MAX_INPUT, stdin);\n\t\tif (*str == '\\0') goto reinput;\n\t\tif (str[MAX_INPUT - 1] != '\\n')\n\t\t\tbail(\"string too long\");\n \n\t\tfor (i = 0; i < MAX_INPUT; i++)\n\t\t\tif (str[i] == '\\n') str[i] = '\\0';\n\t\tif (str[0] == 'q') {\n\t\t\tprintf(\"Bye\\n\");\n\t\t\texit(0);\n\t\t}\n\t\tif (str[0] == 'n') {\n\t\t\tgen_digits();\n\t\t\tgoto reinput;\n\t\t}\n\t\treturn;\n\t}\n}\n \nint main()\n{\n\tfrac_t f;\n\tsrand(time(0));\n \n\tgen_digits();\n\twhile(1) {\n\t\tget_input();\n\t\tsetjmp(ctx); /* if parse error, jump back here with err msg set */\n\t\tif (msg) {\n\t\t\t/* after error jump; announce, reset, redo */\n\t\t\tprintf(\"%s at '%.*s'\\n\", msg, pos, str);\n\t\t\tcontinue;\n\t\t}\n \n\t\teval_tree(parse(), &f);\n \n\t\tif (f.denom == 0) bail(\"Divide by zero\");\n\t\tif (f.denom == 1 && f.num == 24)\n\t\t\tprintf(\"You got 24. Very good.\\n\");\n\t\telse {\n\t\t\tif (f.denom == 1)\n\t\t\t\tprintf(\"Eval to: %d, \", f.num);\n\t\t\telse\n\t\t\t\tprintf(\"Eval to: %d/%d, \", f.num, f.denom);\n\t\t\tprintf(\"no good. Try again.\\n\");\n\t\t}\n\t}\n\treturn 0;\n}"} -{"title": "24 game", "language": "C++11", "task": "The 24 Game tests one's mental arithmetic. \n\n\n;Task\nWrite a program that displays four digits, each from 1 --> 9 (inclusive) with repetitions allowed.\n\nThe program should prompt for the player to enter an arithmetic expression using ''just'' those, and ''all'' of those four digits, used exactly ''once'' each. The program should ''check'' then evaluate the expression. \n\nThe goal is for the player to enter an expression that (numerically) evaluates to '''24'''.\n* Only the following operators/functions are allowed: multiplication, division, addition, subtraction\n* Division should use floating point or rational arithmetic, etc, to preserve remainders.\n* Brackets are allowed, if using an infix expression evaluator.\n* Forming multiple digit numbers from the supplied digits is ''disallowed''. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).\n* The order of the digits when given does not have to be preserved.\n\n\n;Notes\n* The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.\n* The task is not for the program to generate the expression, or test whether an expression is even possible.\n\n\n;Related tasks\n* [[24 game/Solve]]\n\n\n;Reference\n* The 24 Game on h2g2.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\nclass RPNParse\n{\npublic:\n stack stk;\n multiset digits;\n\n void op(function f)\n {\n if(stk.size() < 2)\n throw \"Improperly written expression\";\n int b = stk.top(); stk.pop();\n int a = stk.top(); stk.pop();\n stk.push(f(a, b));\n }\n\n void parse(char c)\n {\n if(c >= '0' && c <= '9')\n {\n stk.push(c - '0');\n digits.insert(c - '0');\n }\n else if(c == '+')\n op([](double a, double b) {return a+b;});\n else if(c == '-')\n op([](double a, double b) {return a-b;});\n else if(c == '*')\n op([](double a, double b) {return a*b;});\n else if(c == '/')\n op([](double a, double b) {return a/b;});\n }\n\n void parse(string s)\n {\n for(int i = 0; i < s.size(); ++i)\n parse(s[i]);\n }\n\n double getResult()\n {\n if(stk.size() != 1)\n throw \"Improperly written expression\";\n return stk.top();\n }\n};\n\nint main()\n{\n random_device seed;\n mt19937 engine(seed());\n uniform_int_distribution<> distribution(1, 9);\n auto rnd = bind(distribution, engine);\n\n multiset digits;\n cout << \"Make 24 with the digits: \";\n for(int i = 0; i < 4; ++i)\n {\n int n = rnd();\n cout << \" \" << n;\n digits.insert(n);\n }\n cout << endl;\n\n RPNParse parser;\n\n try\n {\n string input;\n getline(cin, input);\n parser.parse(input);\n\n if(digits != parser.digits)\n cout << \"Error: Not using the given digits\" << endl;\n else\n {\n double r = parser.getResult();\n cout << \"Result: \" << r << endl;\n\n if(r > 23.999 && r < 24.001)\n cout << \"Good job!\" << endl;\n else\n cout << \"Try again.\" << endl;\n }\n }\n catch(char* e)\n {\n cout << \"Error: \" << e << endl;\n }\n return 0;\n}"} -{"title": "24 game", "language": "JavaScript", "task": "The 24 Game tests one's mental arithmetic. \n\n\n;Task\nWrite a program that displays four digits, each from 1 --> 9 (inclusive) with repetitions allowed.\n\nThe program should prompt for the player to enter an arithmetic expression using ''just'' those, and ''all'' of those four digits, used exactly ''once'' each. The program should ''check'' then evaluate the expression. \n\nThe goal is for the player to enter an expression that (numerically) evaluates to '''24'''.\n* Only the following operators/functions are allowed: multiplication, division, addition, subtraction\n* Division should use floating point or rational arithmetic, etc, to preserve remainders.\n* Brackets are allowed, if using an infix expression evaluator.\n* Forming multiple digit numbers from the supplied digits is ''disallowed''. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).\n* The order of the digits when given does not have to be preserved.\n\n\n;Notes\n* The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.\n* The task is not for the program to generate the expression, or test whether an expression is even possible.\n\n\n;Related tasks\n* [[24 game/Solve]]\n\n\n;Reference\n* The 24 Game on h2g2.\n\n", "solution": "function 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": "The 24 Game tests one's mental arithmetic. \n\n\n;Task\nWrite a program that displays four digits, each from 1 --> 9 (inclusive) with repetitions allowed.\n\nThe program should prompt for the player to enter an arithmetic expression using ''just'' those, and ''all'' of those four digits, used exactly ''once'' each. The program should ''check'' then evaluate the expression. \n\nThe goal is for the player to enter an expression that (numerically) evaluates to '''24'''.\n* Only the following operators/functions are allowed: multiplication, division, addition, subtraction\n* Division should use floating point or rational arithmetic, etc, to preserve remainders.\n* Brackets are allowed, if using an infix expression evaluator.\n* Forming multiple digit numbers from the supplied digits is ''disallowed''. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).\n* The order of the digits when given does not have to be preserved.\n\n\n;Notes\n* The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.\n* The task is not for the program to generate the expression, or test whether an expression is even possible.\n\n\n;Related tasks\n* [[24 game/Solve]]\n\n\n;Reference\n* The 24 Game on h2g2.\n\n", "solution": "'''\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": "Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the [[24 game]].\n\nShow examples of solutions generated by the program.\n\n\n;Related task:\n* [[Arithmetic Evaluator]]\n\n", "solution": "#include \n\ntypedef struct {int val, op, left, right;} Node;\n\nNode nodes[10000];\nint iNodes;\n\nint b;\nfloat eval(Node x){\n if (x.op != -1){\n float l = eval(nodes[x.left]), r = eval(nodes[x.right]);\n switch(x.op){\n case 0: return l+r;\n case 1: return l-r;\n case 2: return r-l;\n case 3: return l*r;\n case 4: return r?l/r:(b=1,0);\n case 5: return l?r/l:(b=1,0);\n }\n }\n else return x.val*1.;\n}\n\nvoid show(Node x){\n if (x.op != -1){\n printf(\"(\");\n switch(x.op){\n case 0: show(nodes[x.left]); printf(\" + \"); show(nodes[x.right]); break;\n case 1: show(nodes[x.left]); printf(\" - \"); show(nodes[x.right]); break;\n case 2: show(nodes[x.right]); printf(\" - \"); show(nodes[x.left]); break;\n case 3: show(nodes[x.left]); printf(\" * \"); show(nodes[x.right]); break;\n case 4: show(nodes[x.left]); printf(\" / \"); show(nodes[x.right]); break;\n case 5: show(nodes[x.right]); printf(\" / \"); show(nodes[x.left]); break;\n }\n printf(\")\");\n }\n else printf(\"%d\", x.val);\n}\n\nint float_fix(float x){ return x < 0.00001 && x > -0.00001; }\n\nvoid solutions(int a[], int n, float t, int s){\n if (s == n){\n b = 0;\n float e = eval(nodes[0]); \n \n if (!b && float_fix(e-t)){\n show(nodes[0]);\n printf(\"\\n\");\n }\n }\n else{\n nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1};\n \n for (int op = 0; op < 6; op++){ \n int k = iNodes-1;\n for (int i = 0; i < k; i++){\n nodes[iNodes++] = nodes[i];\n nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2};\n solutions(a, n, t, s+1);\n nodes[i] = nodes[--iNodes];\n }\n }\n \n iNodes--;\n }\n};\n\nint main(){\n // define problem\n\n int a[4] = {8, 3, 8, 3};\n float t = 24;\n\n // print all solutions\n\n nodes[0] = (typeof(Node)){a[0],-1,-1,-1};\n iNodes = 1;\n\n solutions(a, sizeof(a)/sizeof(int), t, 1);\n\n return 0;\n}"} -{"title": "24 game/Solve", "language": "JavaScript", "task": "Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the [[24 game]].\n\nShow examples of solutions generated by the program.\n\n\n;Related task:\n* [[Arithmetic Evaluator]]\n\n", "solution": "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": "Replace '''a, b, c, d, e, f,''' and\n '''g ''' with the decimal\ndigits LOW ---> HIGH\nsuch that the sum of the letters inside of each of the four large squares add up to\nthe same sum.\n\n\n +--------------+ +--------------+\n | | | |\n | a | | e |\n | | | |\n | +---+------+---+ +---+---------+\n | | | | | | | |\n | | b | | d | | f | |\n | | | | | | | |\n | | | | | | | |\n +----------+---+ +---+------+---+ |\n | c | | g |\n | | | |\n | | | |\n +--------------+ +-------------+\n\n\nShow all output here.\n\n\n:* Show all solutions for each letter being unique with\n LOW=1 HIGH=7\n:* Show all solutions for each letter being unique with\n LOW=3 HIGH=9\n:* Show only the ''number'' of solutions when each letter can be non-unique\n LOW=0 HIGH=9\n\n\n;Related task:\n* [[Solve the no connection puzzle]]\n\n", "solution": "#include \n\n#define TRUE 1\n#define FALSE 0\n\nint a,b,c,d,e,f,g;\nint lo,hi,unique,show;\nint solutions;\n\nvoid\nbf()\n{\n for (f = lo;f <= hi; f++)\n if ((!unique) ||\n ((f != a) && (f != c) && (f != d) && (f != g) && (f != e)))\n {\n b = e + f - c;\n if ((b >= lo) && (b <= hi) &&\n ((!unique) || ((b != a) && (b != c) &&\n (b != d) && (b != g) && (b != e) && (b != f))))\n {\n solutions++;\n if (show)\n printf(\"%d %d %d %d %d %d %d\\n\",a,b,c,d,e,f,g);\n }\n }\n}\n\n\nvoid\nge()\n{\n for (e = lo;e <= hi; e++)\n if ((!unique) || ((e != a) && (e != c) && (e != d)))\n {\n g = d + e;\n if ((g >= lo) && (g <= hi) &&\n ((!unique) || ((g != a) && (g != c) &&\n (g != d) && (g != e))))\n bf();\n }\n}\n\nvoid\nacd()\n{\n for (c = lo;c <= hi; c++)\n for (d = lo;d <= hi; d++)\n if ((!unique) || (c != d))\n {\n a = c + d;\n if ((a >= lo) && (a <= hi) &&\n ((!unique) || ((c != 0) && (d != 0))))\n ge();\n }\n}\n\n\nvoid\nfoursquares(int plo,int phi, int punique,int pshow)\n{\n lo = plo;\n hi = phi;\n unique = punique;\n show = pshow;\n solutions = 0;\n\n printf(\"\\n\");\n\n acd();\n\n if (unique)\n printf(\"\\n%d unique solutions in %d to %d\\n\",solutions,lo,hi);\n else\n printf(\"\\n%d non-unique solutions in %d to %d\\n\",solutions,lo,hi);\n}\n\nmain()\n{\n foursquares(1,7,TRUE,TRUE);\n foursquares(3,9,TRUE,TRUE);\n foursquares(0,9,FALSE,FALSE);\n}\n"} -{"title": "4-rings or 4-squares puzzle", "language": "C++", "task": "Replace '''a, b, c, d, e, f,''' and\n '''g ''' with the decimal\ndigits LOW ---> HIGH\nsuch that the sum of the letters inside of each of the four large squares add up to\nthe same sum.\n\n\n +--------------+ +--------------+\n | | | |\n | a | | e |\n | | | |\n | +---+------+---+ +---+---------+\n | | | | | | | |\n | | b | | d | | f | |\n | | | | | | | |\n | | | | | | | |\n +----------+---+ +---+------+---+ |\n | c | | g |\n | | | |\n | | | |\n +--------------+ +-------------+\n\n\nShow all output here.\n\n\n:* Show all solutions for each letter being unique with\n LOW=1 HIGH=7\n:* Show all solutions for each letter being unique with\n LOW=3 HIGH=9\n:* Show only the ''number'' of solutions when each letter can be non-unique\n LOW=0 HIGH=9\n\n\n;Related task:\n* [[Solve the no connection puzzle]]\n\n", "solution": "//C++14/17\n#include //std::for_each\n#include //std::cout\n#include //std::iota\n#include //std::vector, save solutions\n#include //std::list, for fast erase\n\nusing std::begin, std::end, std::for_each;\n\n//Generates all the valid solutions for the problem in the specified range [from, to)\nstd::list> combinations(int from, int to)\n{\n if (from > to)\n return {}; //Return nothing if limits are invalid\n\n auto pool = std::vector(to - from);//Here we'll save our values\n std::iota(begin(pool), end(pool), from);//Populates pool\n\n auto solutions = std::list>{}; //List for the solutions\n\n //Brute-force calculation of valid values...\n for (auto a : pool)\n for (auto b : pool)\n for (auto c : pool)\n for (auto d : pool)\n for (auto e : pool)\n for (auto f : pool)\n for (auto g : pool)\n if ( a == c + d\n && b + c == e + f\n && d + e == g )\n solutions.push_back({a, b, c, d, e, f, g});\n return solutions;\n}\n\n//Filter the list generated from \"combinations\" and return only lists with no repetitions\nstd::list> filter_unique(int from, int to)\n{\n //Helper lambda to check repetitions:\n //If the count is > 1 for an element, there must be a repetition inside the range\n auto has_non_unique_values = [](const auto & range, auto target)\n {\n return std::count( begin(range), end(range), target) > 1;\n };\n\n //Generates all the solutions...\n auto results = combinations(from, to);\n\n //For each solution, find duplicates inside\n for (auto subrange = cbegin(results); subrange != cend(results); ++subrange)\n {\n bool repetition = false;\n\n //If some element is repeated, repetition becomes true \n for (auto x : *subrange)\n repetition |= has_non_unique_values(*subrange, x);\n\n if (repetition) //If repetition is true, remove the current subrange from the list\n {\n results.erase(subrange); //Deletes subrange from solutions\n --subrange; //Rewind to the last subrange analysed\n }\n }\n\n return results; //Finally return remaining results\n}\n\ntemplate //Template for the sake of simplicity\ninline void print_range(const Container & c)\n{\n for (const auto & subrange : c)\n {\n std::cout << \"[\";\n for (auto elem : subrange)\n std::cout << elem << ' ';\n std::cout << \"\\b]\\n\";\n }\n}\n\n\nint main()\n{\n std::cout << \"Unique-numbers combinations in range 1-7:\\n\";\n auto solution1 = filter_unique(1, 8);\n print_range(solution1);\n std::cout << \"\\nUnique-numbers combinations in range 3-9:\\n\";\n auto solution2 = filter_unique(3,10);\n print_range(solution2);\n std::cout << \"\\nNumber of combinations in range 0-9: \" \n << combinations(0, 10).size() << \".\" << std::endl;\n\n return 0;\n}\n"} -{"title": "4-rings or 4-squares puzzle", "language": "JavaScript from Haskell", "task": "Replace '''a, b, c, d, e, f,''' and\n '''g ''' with the decimal\ndigits LOW ---> HIGH\nsuch that the sum of the letters inside of each of the four large squares add up to\nthe same sum.\n\n\n +--------------+ +--------------+\n | | | |\n | a | | e |\n | | | |\n | +---+------+---+ +---+---------+\n | | | | | | | |\n | | b | | d | | f | |\n | | | | | | | |\n | | | | | | | |\n +----------+---+ +---+------+---+ |\n | c | | g |\n | | | |\n | | | |\n +--------------+ +-------------+\n\n\nShow all output here.\n\n\n:* Show all solutions for each letter being unique with\n LOW=1 HIGH=7\n:* Show all solutions for each letter being unique with\n LOW=3 HIGH=9\n:* Show only the ''number'' of solutions when each letter can be non-unique\n LOW=0 HIGH=9\n\n\n;Related task:\n* [[Solve the no connection puzzle]]\n\n", "solution": "(() => {\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": "Replace '''a, b, c, d, e, f,''' and\n '''g ''' with the decimal\ndigits LOW ---> HIGH\nsuch that the sum of the letters inside of each of the four large squares add up to\nthe same sum.\n\n\n +--------------+ +--------------+\n | | | |\n | a | | e |\n | | | |\n | +---+------+---+ +---+---------+\n | | | | | | | |\n | | b | | d | | f | |\n | | | | | | | |\n | | | | | | | |\n +----------+---+ +---+------+---+ |\n | c | | g |\n | | | |\n | | | |\n +--------------+ +-------------+\n\n\nShow all output here.\n\n\n:* Show all solutions for each letter being unique with\n LOW=1 HIGH=7\n:* Show all solutions for each letter being unique with\n LOW=3 HIGH=9\n:* Show only the ''number'' of solutions when each letter can be non-unique\n LOW=0 HIGH=9\n\n\n;Related task:\n* [[Solve the no connection puzzle]]\n\n", "solution": "def 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": "Replace '''a, b, c, d, e, f,''' and\n '''g ''' with the decimal\ndigits LOW ---> HIGH\nsuch that the sum of the letters inside of each of the four large squares add up to\nthe same sum.\n\n\n +--------------+ +--------------+\n | | | |\n | a | | e |\n | | | |\n | +---+------+---+ +---+---------+\n | | | | | | | |\n | | b | | d | | f | |\n | | | | | | | |\n | | | | | | | |\n +----------+---+ +---+------+---+ |\n | c | | g |\n | | | |\n | | | |\n +--------------+ +-------------+\n\n\nShow all output here.\n\n\n:* Show all solutions for each letter being unique with\n LOW=1 HIGH=7\n:* Show all solutions for each letter being unique with\n LOW=3 HIGH=9\n:* Show only the ''number'' of solutions when each letter can be non-unique\n LOW=0 HIGH=9\n\n\n;Related task:\n* [[Solve the no connection puzzle]]\n\n", "solution": "'''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": "JavaScript", "task": "Display the complete lyrics for the song: '''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 '''0''' (zero).\n\nGrammatical support for ''1 bottle of beer'' 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* http://99-bottles-of-beer.net/\n* [[:Category:99_Bottles_of_Beer]]\n* [[:Category:Programming language families]]\n* 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": "Display the complete lyrics for the song: '''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 '''0''' (zero).\n\nGrammatical support for ''1 bottle of beer'' 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* http://99-bottles-of-beer.net/\n* [[:Category:99_Bottles_of_Beer]]\n* [[:Category:Programming language families]]\n* Wikipedia 99 bottles of beer\n\n", "solution": "\"\"\"\nExcercise of style. An overkill for the task :-D\n\n1. OOP, with abstract class and implementation with much common magic methods\n2. you can customize:\n a. the initial number\n b. the name of the item and its plural\n c. the string to display when there's no more items\n d. the normal action\n e. the final action\n f. the template used, for foreign languages\n3. strofas of the song are created with multiprocessing\n4. when you launch it as a script, you can specify an optional parameter for \n the number of initial items\n\"\"\"\n\nfrom string import Template\nfrom abc import ABC, abstractmethod\nfrom multiprocessing.pool import Pool as ProcPool\nfrom functools import partial\nimport sys\n\nclass Song(ABC):\n @abstractmethod\n def sing(self):\n \"\"\"\n it must return the song as a text-like object\n \"\"\"\n \n pass\n\nclass MuchItemsSomewhere(Song):\n eq_attrs = (\n \"initial_number\", \n \"zero_items\", \n \"action1\", \n \"action2\", \n \"item\", \n \"items\", \n \"strofa_tpl\"\n )\n \n hash_attrs = eq_attrs\n repr_attrs = eq_attrs\n \n __slots__ = eq_attrs + (\"_repr\", \"_hash\")\n \n def __init__(\n self, \n items = \"bottles of beer\", \n item = \"bottle of beer\",\n where = \"on the wall\",\n initial_number = None,\n zero_items = \"No more\",\n action1 = \"Take one down, pass it around\",\n action2 = \"Go to the store, buy some more\",\n template = None,\n ):\n initial_number_true = 99 if initial_number is None else initial_number\n \n try:\n is_initial_number_int = (initial_number_true % 1) == 0\n except Exception:\n is_initial_number_int = False\n \n if not is_initial_number_int:\n raise ValueError(\"`initial_number` parameter must be None or a int-like object\")\n \n if initial_number_true < 0:\n raise ValueError(\"`initial_number` parameter must be >=0\")\n \n \n true_tpl = template or \"\"\"\\\n$i $items1 $where\n$i $items1\n$action\n$j $items2 $where\"\"\"\n \n strofa_tpl_tmp = Template(true_tpl)\n strofa_tpl = Template(strofa_tpl_tmp.safe_substitute(where=where))\n \n self.zero_items = zero_items\n self.action1 = action1\n self.action2 = action2\n self.initial_number = initial_number_true\n self.item = item\n self.items = items\n self.strofa_tpl = strofa_tpl\n self._hash = None\n self._repr = None\n \n def strofa(self, number):\n zero_items = self.zero_items\n item = self.item\n items = self.items\n \n if number == 0:\n i = zero_items\n action = self.action2\n j = self.initial_number\n else:\n i = number\n action = self.action1\n j = i - 1\n \n if i == 1:\n items1 = item\n j = zero_items\n else:\n items1 = items\n \n if j == 1:\n items2 = item\n else:\n items2 = items\n \n return self.strofa_tpl.substitute(\n i = i, \n j = j, \n action = action, \n items1 = items1, \n items2 = items2\n )\n \n def sing(self):\n with ProcPool() as proc_pool:\n strofa = self.strofa\n initial_number = self.initial_number\n args = range(initial_number, -1, -1)\n return \"\\n\\n\".join(proc_pool.map(strofa, args))\n \n def __copy__(self, *args, **kwargs):\n return self\n \n def __deepcopy__(self, *args, **kwargs):\n return self\n \n def __eq__(self, other, *args, **kwargs):\n if self is other:\n return True\n \n getmyattr = partial(getattr, self)\n getotherattr = partial(getattr, other)\n eq_attrs = self.eq_attrs\n \n for attr in eq_attrs:\n val = getmyattr(attr)\n \n try:\n val2 = getotherattr(attr)\n except Exception:\n return False\n \n if attr == \"strofa_tpl\":\n val_true = val.safe_substitute()\n val2_true = val.safe_substitute()\n else:\n val_true = val\n val2_true = val\n \n if val_true != val2_true:\n return False\n \n return True\n \n def __hash__(self, *args, **kwargs):\n _hash = self._hash\n \n if _hash is None:\n getmyattr = partial(getattr, self)\n attrs = self.hash_attrs\n hash_true = self._hash = hash(tuple(map(getmyattr, attrs)))\n else:\n hash_true = _hash\n \n return hash_true\n \n def __repr__(self, *args, **kwargs):\n _repr = self._repr\n \n if _repr is None:\n repr_attrs = self.repr_attrs\n getmyattr = partial(getattr, self)\n \n attrs = []\n \n for attr in repr_attrs:\n val = getmyattr(attr)\n \n if attr == \"strofa_tpl\":\n val_true = val.safe_substitute()\n else:\n val_true = val\n \n attrs.append(f\"{attr}={repr(val_true)}\")\n \n repr_true = self._repr = f\"{self.__class__.__name__}({', '.join(attrs)})\"\n else:\n repr_true = _repr\n \n return repr_true\n\ndef muchBeersOnTheWall(num):\n song = MuchItemsSomewhere(initial_number=num)\n \n return song.sing()\n\ndef balladOfProgrammer(num):\n \"\"\"\n Prints\n \"99 Subtle Bugs in Production\"\n or\n \"The Ballad of Programmer\"\n \"\"\"\n \n song = MuchItemsSomewhere(\n initial_number = num,\n items = \"subtle bugs\",\n item = \"subtle bug\",\n where = \"in Production\",\n action1 = \"Debug and catch, commit a patch\",\n action2 = \"Release the fixes, wait for some tickets\",\n zero_items = \"Zarro\",\n )\n\n return song.sing()\n\ndef main(num):\n print(f\"### {num} Bottles of Beers on the Wall ###\")\n print()\n print(muchBeersOnTheWall(num))\n print()\n print()\n print('### \"The Ballad of Programmer\", by Marco Sulla')\n print()\n print(balladOfProgrammer(num))\n\nif __name__ == \"__main__\":\n # Ok, argparse is **really** too much\n argv = sys.argv\n \n if len(argv) == 1:\n num = None\n elif len(argv) == 2:\n try:\n num = int(argv[1])\n except Exception:\n raise ValueError(\n f\"{__file__} parameter must be an integer, or can be omitted\"\n )\n else:\n raise RuntimeError(f\"{__file__} takes one parameter at max\")\n \n main(num)\n\n__all__ = (Song.__name__, MuchItemsSomewhere.__name__, muchBeersOnTheWall.__name__, balladOfProgrammer.__name__)\n"} -{"title": "99 bottles of beer", "language": "Python 3", "task": "Display the complete lyrics for the song: '''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 '''0''' (zero).\n\nGrammatical support for ''1 bottle of beer'' 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* http://99-bottles-of-beer.net/\n* [[:Category:99_Bottles_of_Beer]]\n* [[:Category:Programming language families]]\n* 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": "Display the complete lyrics for the song: '''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 '''0''' (zero).\n\nGrammatical support for ''1 bottle of beer'' 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* http://99-bottles-of-beer.net/\n* [[:Category:99_Bottles_of_Beer]]\n* [[:Category:Programming language families]]\n* 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 \"name\":\n:The integer 1 has 1 name \"1\".\n:The integer 2 has 2 names \"1+1\", and \"2\".\n:The integer 3 has 3 names \"1+1+1\", \"2+1\", and \"3\".\n:The integer 4 has 5 names \"1+1+1+1\", \"2+1+1\", \"2+2\", \"3+1\", \"4\".\n:The integer 5 has 7 names \"1+1+1+1+1\", \"2+1+1+1\", \"2+2+1\", \"3+1+1\", \"3+2\", \"4+1\", \"5\".\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 n corresponds to integer n, and each column C in row m from left to right corresponds to the number of names beginning with C.\n\nA function G(n) should return the sum of the n-th row. \n\nDemonstrate this function by displaying: G(23), G(123), G(1234), and G(12345). \n\nOptionally note that the sum of the n-th row P(n) is the integer partition function. \n\nDemonstrate this is equivalent to G(n) by displaying: P(23), P(123), P(1234), and P(12345).\n\n\n;Extra credit\n\nIf your environment is able, plot P(n) against n for n=1\\ldots 999.\n\n;Related tasks\n* [[Partition function P]]\n\n", "solution": "// Calculate hypotenuse n of OTT assuming only nothingness, unity, and hyp[n-1] if n>1\n// Nigel Galloway, May 6th., 2013\n#include \nint N{123456};\nmpz_class hyp[N-3];\nconst mpz_class G(const int n,const int g){return g>n?0:(g==1 or n-g<2)?1:hyp[n-g-2];};\nvoid G_hyp(const int n){for(int i=0;i max_ns:\n break\n p = partitions(i)\n if i in ns:\n print \"%6d: %s\" % (i, p)\n\nmain()"} -{"title": "A+B", "language": "C", "task": "'''A+B''' --- a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.\n\n\n;Task:\nGiven two integers, '''A''' and '''B'''. \n\nTheir sum needs to be calculated.\n\n\n;Input data:\nTwo integers are written in the input stream, separated by space(s):\n: (-1000 \\le A,B \\le +1000)\n\n\n;Output data:\nThe required output is one integer: the sum of '''A''' and '''B'''.\n\n\n;Example:\n::{|class=\"standard\"\n ! input \n ! output \n |-\n | 2 2 \n | 4 \n |-\n | 3 2 \n | 5 \n |}\n\n", "solution": "// Input file: input.txt\n// Output file: output.txt\n#include \nint main()\n{\n freopen(\"input.txt\", \"rt\", stdin);\n freopen(\"output.txt\", \"wt\", stdout);\n int a, b;\n scanf(\"%d%d\", &a, &b);\n printf(\"%d\\n\", a + b);\n return 0;\n}"} -{"title": "A+B", "language": "C++", "task": "'''A+B''' --- a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.\n\n\n;Task:\nGiven two integers, '''A''' and '''B'''. \n\nTheir sum needs to be calculated.\n\n\n;Input data:\nTwo integers are written in the input stream, separated by space(s):\n: (-1000 \\le A,B \\le +1000)\n\n\n;Output data:\nThe required output is one integer: the sum of '''A''' and '''B'''.\n\n\n;Example:\n::{|class=\"standard\"\n ! input \n ! output \n |-\n | 2 2 \n | 4 \n |-\n | 3 2 \n | 5 \n |}\n\n", "solution": "// Input file: input.txt\n// Output file: output.txt\n#include \nusing namespace std;\nint main()\n{\n ifstream in(\"input.txt\");\n ofstream out(\"output.txt\");\n int a, b;\n in >> a >> b;\n out << a + b << endl;\n return 0;\n}"} -{"title": "A+B", "language": "JavaScript", "task": "'''A+B''' --- a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.\n\n\n;Task:\nGiven two integers, '''A''' and '''B'''. \n\nTheir sum needs to be calculated.\n\n\n;Input data:\nTwo integers are written in the input stream, separated by space(s):\n: (-1000 \\le A,B \\le +1000)\n\n\n;Output data:\nThe required output is one integer: the sum of '''A''' and '''B'''.\n\n\n;Example:\n::{|class=\"standard\"\n ! input \n ! output \n |-\n | 2 2 \n | 4 \n |-\n | 3 2 \n | 5 \n |}\n\n", "solution": "\n\n
\n
\n\n\n"} -{"title": "A+B", "language": "Python", "task": "'''A+B''' --- a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.\n\n\n;Task:\nGiven two integers, '''A''' and '''B'''. \n\nTheir sum needs to be calculated.\n\n\n;Input data:\nTwo integers are written in the input stream, separated by space(s):\n: (-1000 \\le A,B \\le +1000)\n\n\n;Output data:\nThe required output is one integer: the sum of '''A''' and '''B'''.\n\n\n;Example:\n::{|class=\"standard\"\n ! input \n ! output \n |-\n | 2 2 \n | 4 \n |-\n | 3 2 \n | 5 \n |}\n\n", "solution": "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 (maybe like the ones you had when you were a kid). \n\nThere are twenty blocks with two letters on each block. \n\nA complete alphabet is guaranteed amongst all sides of the blocks. \n\nThe sample collection of blocks: \n (B O)\n (X K)\n (D Q)\n (C P)\n (N A)\n (G T)\n (R E)\n (T G)\n (Q D)\n (F S)\n (J W)\n (H U)\n (V I)\n (A N)\n (O B)\n (E R)\n (F S)\n (L Y)\n (P C)\n (Z M)\n\n\n;Task:\nWrite a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks. \n\n\nThe rules are simple:\n::# Once a letter on a block is used that block cannot be used again\n::# The function should be case-insensitive\n::# Show the output on this page for the following 7 words in the following example\n\n\n;Example:\n >>> can_make_word(\"A\")\n True\n >>> can_make_word(\"BARK\")\n True\n >>> can_make_word(\"BOOK\")\n False\n >>> can_make_word(\"TREAT\")\n True\n >>> can_make_word(\"COMMON\")\n False\n >>> can_make_word(\"SQUAD\")\n True\n >>> can_make_word(\"CONFUSE\")\n True\n\n", "solution": "#include \n#include \n\nint can_make_words(char **b, char *word)\n{\n\tint i, ret = 0, c = toupper(*word);\n\n#define SWAP(a, b) if (a != b) { char * tmp = a; a = b; b = tmp; }\n\n\tif (!c) return 1;\n\tif (!b[0]) return 0;\n\n\tfor (i = 0; b[i] && !ret; i++) {\n\t\tif (b[i][0] != c && b[i][1] != c) continue;\n\t\tSWAP(b[i], b[0]);\n\t\tret = can_make_words(b + 1, word + 1);\n\t\tSWAP(b[i], b[0]);\n\t}\n\n\treturn ret;\n}\n\nint main(void)\n{\n\tchar* blocks[] = {\n\t\t\"BO\", \"XK\", \"DQ\", \"CP\", \"NA\", \n\t\t\"GT\", \"RE\", \"TG\", \"QD\", \"FS\", \n\t\t\"JW\", \"HU\", \"VI\", \"AN\", \"OB\", \n\t\t\"ER\", \"FS\", \"LY\", \"PC\", \"ZM\",\n\t\t0 };\n\n\tchar *words[] = {\n\t\t\"\", \"A\", \"BARK\", \"BOOK\", \"TREAT\", \"COMMON\", \"SQUAD\", \"Confuse\", 0\n\t};\n\n\tchar **w;\n\tfor (w = words; *w; w++)\n\t\tprintf(\"%s\\t%d\\n\", *w, can_make_words(blocks, *w));\n\n\treturn 0;\n}"} -{"title": "ABC problem", "language": "C++11", "task": "You are given a collection of ABC blocks (maybe like the ones you had when you were a kid). \n\nThere are twenty blocks with two letters on each block. \n\nA complete alphabet is guaranteed amongst all sides of the blocks. \n\nThe sample collection of blocks: \n (B O)\n (X K)\n (D Q)\n (C P)\n (N A)\n (G T)\n (R E)\n (T G)\n (Q D)\n (F S)\n (J W)\n (H U)\n (V I)\n (A N)\n (O B)\n (E R)\n (F S)\n (L Y)\n (P C)\n (Z M)\n\n\n;Task:\nWrite a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks. \n\n\nThe rules are simple:\n::# Once a letter on a block is used that block cannot be used again\n::# The function should be case-insensitive\n::# Show the output on this page for the following 7 words in the following example\n\n\n;Example:\n >>> can_make_word(\"A\")\n True\n >>> can_make_word(\"BARK\")\n True\n >>> can_make_word(\"BOOK\")\n False\n >>> can_make_word(\"TREAT\")\n True\n >>> can_make_word(\"COMMON\")\n False\n >>> can_make_word(\"SQUAD\")\n True\n >>> can_make_word(\"CONFUSE\")\n True\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\ntypedef std::pair item_t;\ntypedef std::vector list_t;\n\nbool can_make_word(const std::string& w, const list_t& vals) {\n std::set used;\n while (used.size() < w.size()) {\n const char c = toupper(w[used.size()]);\n uint32_t x = used.size();\n for (uint32_t i = 0, ii = vals.size(); i < ii; ++i) {\n if (used.find(i) == used.end()) {\n if (toupper(vals[i].first) == c || toupper(vals[i].second) == c) {\n used.insert(i);\n break;\n }\n }\n }\n if (x == used.size()) break;\n }\n return used.size() == w.size();\n}\n\nint main() {\n list_t vals{ {'B','O'}, {'X','K'}, {'D','Q'}, {'C','P'}, {'N','A'}, {'G','T'}, {'R','E'}, {'T','G'}, {'Q','D'}, {'F','S'}, {'J','W'}, {'H','U'}, {'V','I'}, {'A','N'}, {'O','B'}, {'E','R'}, {'F','S'}, {'L','Y'}, {'P','C'}, {'Z','M'} };\n std::vector words{\"A\",\"BARK\",\"BOOK\",\"TREAT\",\"COMMON\",\"SQUAD\",\"CONFUSE\"};\n for (const std::string& w : words) {\n std::cout << w << \": \" << std::boolalpha << can_make_word(w,vals) << \".\\n\";\n }\n}"} -{"title": "ABC problem", "language": "JavaScript", "task": "You are given a collection of ABC blocks (maybe like the ones you had when you were a kid). \n\nThere are twenty blocks with two letters on each block. \n\nA complete alphabet is guaranteed amongst all sides of the blocks. \n\nThe sample collection of blocks: \n (B O)\n (X K)\n (D Q)\n (C P)\n (N A)\n (G T)\n (R E)\n (T G)\n (Q D)\n (F S)\n (J W)\n (H U)\n (V I)\n (A N)\n (O B)\n (E R)\n (F S)\n (L Y)\n (P C)\n (Z M)\n\n\n;Task:\nWrite a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks. \n\n\nThe rules are simple:\n::# Once a letter on a block is used that block cannot be used again\n::# The function should be case-insensitive\n::# Show the output on this page for the following 7 words in the following example\n\n\n;Example:\n >>> can_make_word(\"A\")\n True\n >>> can_make_word(\"BARK\")\n True\n >>> can_make_word(\"BOOK\")\n False\n >>> can_make_word(\"TREAT\")\n True\n >>> can_make_word(\"COMMON\")\n False\n >>> can_make_word(\"SQUAD\")\n True\n >>> can_make_word(\"CONFUSE\")\n True\n\n", "solution": "(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');"} -{"title": "ABC problem", "language": "JavaScript from Haskell", "task": "You are given a collection of ABC blocks (maybe like the ones you had when you were a kid). \n\nThere are twenty blocks with two letters on each block. \n\nA complete alphabet is guaranteed amongst all sides of the blocks. \n\nThe sample collection of blocks: \n (B O)\n (X K)\n (D Q)\n (C P)\n (N A)\n (G T)\n (R E)\n (T G)\n (Q D)\n (F S)\n (J W)\n (H U)\n (V I)\n (A N)\n (O B)\n (E R)\n (F S)\n (L Y)\n (P C)\n (Z M)\n\n\n;Task:\nWrite a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks. \n\n\nThe rules are simple:\n::# Once a letter on a block is used that block cannot be used again\n::# The function should be case-insensitive\n::# Show the output on this page for the following 7 words in the following example\n\n\n;Example:\n >>> can_make_word(\"A\")\n True\n >>> can_make_word(\"BARK\")\n True\n >>> can_make_word(\"BOOK\")\n False\n >>> can_make_word(\"TREAT\")\n True\n >>> can_make_word(\"COMMON\")\n False\n >>> can_make_word(\"SQUAD\")\n True\n >>> can_make_word(\"CONFUSE\")\n True\n\n", "solution": "(() => {\n \"use strict\";\n\n // ------------------- ABC BLOCKS --------------------\n\n // spellWith :: [(Char, Char)] -> [Char] -> [[(Char, Char)]]\n const spellWith = blocks =>\n wordChars => !Boolean(wordChars.length) ? [\n []\n ] : (() => {\n const [x, ...xs] = wordChars;\n\n return blocks.flatMap(\n b => b.includes(x) ? (\n spellWith(\n deleteBy(\n p => q => (p[0] === q[0]) && (\n p[1] === q[1]\n )\n )(b)(blocks)\n )(xs)\n .flatMap(bs => [b, ...bs])\n ) : []\n );\n })();\n\n\n // ---------------------- TEST -----------------------\n const main = () => {\n const blocks = (\n \"BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM\"\n ).split(\" \");\n\n return [\n \"\", \"A\", \"BARK\", \"BoOK\", \"TrEAT\",\n \"COmMoN\", \"SQUAD\", \"conFUsE\"\n ]\n .map(\n x => JSON.stringify([\n x, !Boolean(\n spellWith(blocks)(\n [...x.toLocaleUpperCase()]\n )\n .length\n )\n ])\n )\n .join(\"\\n\");\n };\n\n // ---------------- GENERIC FUNCTIONS ----------------\n\n // deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a]\n const deleteBy = fEq =>\n x => {\n const go = xs => Boolean(xs.length) ? (\n fEq(x)(xs[0]) ? (\n xs.slice(1)\n ) : [xs[0], ...go(xs.slice(1))]\n ) : [];\n\n return go;\n };\n\n // MAIN ---\n return main();\n})();"} -{"title": "ABC problem", "language": "Python", "task": "You are given a collection of ABC blocks (maybe like the ones you had when you were a kid). \n\nThere are twenty blocks with two letters on each block. \n\nA complete alphabet is guaranteed amongst all sides of the blocks. \n\nThe sample collection of blocks: \n (B O)\n (X K)\n (D Q)\n (C P)\n (N A)\n (G T)\n (R E)\n (T G)\n (Q D)\n (F S)\n (J W)\n (H U)\n (V I)\n (A N)\n (O B)\n (E R)\n (F S)\n (L Y)\n (P C)\n (Z M)\n\n\n;Task:\nWrite a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks. \n\n\nThe rules are simple:\n::# Once a letter on a block is used that block cannot be used again\n::# The function should be case-insensitive\n::# Show the output on this page for the following 7 words in the following example\n\n\n;Example:\n >>> can_make_word(\"A\")\n True\n >>> can_make_word(\"BARK\")\n True\n >>> can_make_word(\"BOOK\")\n False\n >>> can_make_word(\"TREAT\")\n True\n >>> can_make_word(\"COMMON\")\n False\n >>> can_make_word(\"SQUAD\")\n True\n >>> can_make_word(\"CONFUSE\")\n True\n\n", "solution": "'''\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": "#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": "C++", "task": "Given the RFC 1035 message diagram from Section 4.1.1 (Header section format) as a string:\nhttp://www.ietf.org/rfc/rfc1035.txt\n\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ID |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n |QR| Opcode |AA|TC|RD|RA| Z | RCODE |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | QDCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ANCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | NSCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ARCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n\nWhere (every column of the table is 1 bit):\n\n ID is 16 bits\n QR = Query (0) or Response (1)\n Opcode = Four bits defining kind of query:\n 0: a standard query (QUERY)\n 1: an inverse query (IQUERY)\n 2: a server status request (STATUS)\n 3-15: reserved for future use\n AA = Authoritative Answer bit\n TC = Truncation bit\n RD = Recursion Desired bit\n RA = Recursion Available bit\n Z = Reserved\n RCODE = Response code\n QC = Question Count\n ANC = Answer Count\n AUC = Authority Count\n ADC = Additional Count\n\nWrite a function, member function, class or template that accepts a similar multi-line string as input to define a data structure or something else able to decode or store a header with that specified bit structure.\n\nIf your language has macros, introspection, code generation, or powerful enough templates, then accept such string at compile-time to define the header data structure statically.\n\nSuch \"Header\" function or template should accept a table with 8, 16, 32 or 64 columns, and any number of rows. For simplicity the only allowed symbols to define the table are + - | (plus, minus, pipe), and whitespace. Lines of the input string composed just of whitespace should be ignored. Leading and trailing whitespace in the input string should be ignored, as well as before and after each table row. The box for each bit of the diagram takes four chars \"+--+\". The code should perform a little of validation of the input string, but for brevity a full validation is not required.\n\nBonus: perform a thoroughly validation of the input string.\n\n", "solution": "#include \n#include \n#include \n\nusing namespace std;\n\nstruct FieldDetails {string_view Name; int NumBits;};\n\n// parses the ASCII diagram and returns the field name, bit sizes, and the\n// total byte size\ntemplate consteval auto ParseDiagram()\n{ \n // trim the ASCII diagram text\n constexpr string_view rawArt(T);\n constexpr auto firstBar = rawArt.find(\"|\");\n constexpr auto lastBar = rawArt.find_last_of(\"|\");\n constexpr auto art = rawArt.substr(firstBar, lastBar - firstBar);\n static_assert(firstBar < lastBar, \"ASCII Table has no fields\");\n \n // make an array for all of the fields\n constexpr auto numFields = \n count(rawArt.begin(), rawArt.end(), '|') -\n count(rawArt.begin(), rawArt.end(), '\\n') / 2; \n array fields;\n \n // parse the diagram\n bool isValidDiagram = true;\n int startDiagramIndex = 0;\n int totalBits = 0;\n for(int i = 0; i < numFields; )\n {\n auto beginningBar = art.find(\"|\", startDiagramIndex);\n auto endingBar = art.find(\"|\", beginningBar + 1);\n auto field = art.substr(beginningBar + 1, endingBar - beginningBar - 1);\n if(field.find(\"-\") == field.npos) \n {\n int numBits = (field.size() + 1) / 3;\n auto nameStart = field.find_first_not_of(\" \");\n auto nameEnd = field.find_last_not_of(\" \");\n if (nameStart > nameEnd || nameStart == string_view::npos) \n {\n // the table cannot be parsed\n isValidDiagram = false;\n field = \"\"sv;\n }\n else\n {\n field = field.substr(nameStart, 1 + nameEnd - nameStart);\n }\n fields[i++] = FieldDetails {field, numBits};\n totalBits += numBits;\n }\n startDiagramIndex = endingBar;\n }\n \n int numRawBytes = isValidDiagram ? (totalBits - 1) / 8 + 1 : 0;\n return make_pair(fields, numRawBytes);\n}\n\n// encode the values of the fields into a raw data array\ntemplate auto Encode(auto inputValues)\n{\n constexpr auto parsedDiagram = ParseDiagram();\n static_assert(parsedDiagram.second > 0, \"Invalid ASCII talble\");\n array data;\n\n int startBit = 0;\n int i = 0;\n for(auto value : inputValues)\n {\n const auto &field = parsedDiagram.first[i++];\n int remainingValueBits = field.NumBits;\n while(remainingValueBits > 0)\n {\n // pack the bits from an input field into the data array\n auto [fieldStartByte, fieldStartBit] = div(startBit, 8);\n int unusedBits = 8 - fieldStartBit;\n int numBitsToEncode = min({unusedBits, 8, field.NumBits});\n int divisor = 1 << (remainingValueBits - numBitsToEncode);\n unsigned char bitsToEncode = value / divisor;\n data[fieldStartByte] <<= numBitsToEncode;\n data[fieldStartByte] |= bitsToEncode;\n value %= divisor;\n startBit += numBitsToEncode;\n remainingValueBits -= numBitsToEncode;\n }\n }\n \n return data;\n}\n\n// decode the raw data into the format of the ASCII diagram\ntemplate void Decode(auto data)\n{\n cout << \"Name Bit Pattern\\n\";\n cout << \"======= ================\\n\";\n constexpr auto parsedDiagram = ParseDiagram();\n static_assert(parsedDiagram.second > 0, \"Invalid ASCII talble\");\n\n int startBit = 0;\n for(const auto& field : parsedDiagram.first)\n {\n // unpack the bits from the data into a single field\n auto [fieldStartByte, fieldStartBit] = div(startBit, 8);\n unsigned char firstByte = data[fieldStartByte];\n firstByte <<= fieldStartBit;\n firstByte >>= fieldStartBit;\n int64_t value = firstByte;\n auto endBit = startBit + field.NumBits;\n auto [fieldEndByte, fieldEndBit] = div(endBit, 8);\n fieldEndByte = min(fieldEndByte, (int)(ssize(data) - 1));\n for(int index = fieldStartByte + 1; index <= fieldEndByte; index++)\n {\n value <<= 8;\n value += data[index];\n }\n value >>= fieldEndBit;\n startBit = endBit;\n \n cout << field.Name << \n string_view(\" \", (7 - field.Name.size())) << \" \" << \n string_view(bitset<64>(value).to_string()).substr(64 - field.NumBits, 64) << \"\\n\";\n }\n \n}\n\nint main(void) \n{\n static constexpr char art[] = R\"(\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 // using the table above, encode the data below\n auto rawData = Encode (initializer_list {\n 30791,\n 0, 15, 0, 1, 1, 1, 3, 15,\n 21654,\n 57646,\n 7153,\n 27044\n });\n \n cout << \"Raw encoded data in hex:\\n\";\n for (auto v : rawData) printf(\"%.2X\", v);\n cout << \"\\n\\n\";\n \n cout << \"Decoded raw data:\\n\";\n Decode(rawData);\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": "\"\"\"\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": "C++ from D", "task": "{{wikipedia|AVL tree}}\n\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 m-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": "#include \n#include \n\n/* AVL node */\ntemplate \nclass AVLnode {\npublic:\n T key;\n int balance;\n AVLnode *left, *right, *parent;\n\n AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p),\n left(NULL), right(NULL) {}\n\n ~AVLnode() {\n delete left;\n delete right;\n }\n};\n\n/* AVL tree */\ntemplate \nclass AVLtree {\npublic:\n AVLtree(void);\n ~AVLtree(void);\n bool insert(T key);\n void deleteKey(const T key);\n void printBalance();\n\nprivate:\n AVLnode *root;\n\n AVLnode* rotateLeft ( AVLnode *a );\n AVLnode* rotateRight ( AVLnode *a );\n AVLnode* rotateLeftThenRight ( AVLnode *n );\n AVLnode* rotateRightThenLeft ( AVLnode *n );\n void rebalance ( AVLnode *n );\n int height ( AVLnode *n );\n void setBalance ( AVLnode *n );\n void printBalance ( AVLnode *n );\n};\n\n/* AVL class definition */\ntemplate \nvoid AVLtree::rebalance(AVLnode *n) {\n setBalance(n);\n\n if (n->balance == -2) {\n if (height(n->left->left) >= height(n->left->right))\n n = rotateRight(n);\n else\n n = rotateLeftThenRight(n);\n }\n else if (n->balance == 2) {\n if (height(n->right->right) >= height(n->right->left))\n n = rotateLeft(n);\n else\n n = rotateRightThenLeft(n);\n }\n\n if (n->parent != NULL) {\n rebalance(n->parent);\n }\n else {\n root = n;\n }\n}\n\ntemplate \nAVLnode* AVLtree::rotateLeft(AVLnode *a) {\n AVLnode *b = a->right;\n b->parent = a->parent;\n a->right = b->left;\n\n if (a->right != NULL)\n a->right->parent = a;\n\n b->left = a;\n a->parent = b;\n\n if (b->parent != NULL) {\n if (b->parent->right == a) {\n b->parent->right = b;\n }\n else {\n b->parent->left = b;\n }\n }\n\n setBalance(a);\n setBalance(b);\n return b;\n}\n\ntemplate \nAVLnode* AVLtree::rotateRight(AVLnode *a) {\n AVLnode *b = a->left;\n b->parent = a->parent;\n a->left = b->right;\n\n if (a->left != NULL)\n a->left->parent = a;\n\n b->right = a;\n a->parent = b;\n\n if (b->parent != NULL) {\n if (b->parent->right == a) {\n b->parent->right = b;\n }\n else {\n b->parent->left = b;\n }\n }\n\n setBalance(a);\n setBalance(b);\n return b;\n}\n\ntemplate \nAVLnode* AVLtree::rotateLeftThenRight(AVLnode *n) {\n n->left = rotateLeft(n->left);\n return rotateRight(n);\n}\n\ntemplate \nAVLnode* AVLtree::rotateRightThenLeft(AVLnode *n) {\n n->right = rotateRight(n->right);\n return rotateLeft(n);\n}\n\ntemplate \nint AVLtree::height(AVLnode *n) {\n if (n == NULL)\n return -1;\n return 1 + std::max(height(n->left), height(n->right));\n}\n\ntemplate \nvoid AVLtree::setBalance(AVLnode *n) {\n n->balance = height(n->right) - height(n->left);\n}\n\ntemplate \nvoid AVLtree::printBalance(AVLnode *n) {\n if (n != NULL) {\n printBalance(n->left);\n std::cout << n->balance << \" \";\n printBalance(n->right);\n }\n}\n\ntemplate \nAVLtree::AVLtree(void) : root(NULL) {}\n\ntemplate \nAVLtree::~AVLtree(void) {\n delete root;\n}\n\ntemplate \nbool AVLtree::insert(T key) {\n if (root == NULL) {\n root = new AVLnode(key, NULL);\n }\n else {\n AVLnode\n *n = root,\n *parent;\n\n while (true) {\n if (n->key == key)\n return false;\n\n parent = n;\n\n bool goLeft = n->key > key;\n n = goLeft ? n->left : n->right;\n\n if (n == NULL) {\n if (goLeft) {\n parent->left = new AVLnode(key, parent);\n }\n else {\n parent->right = new AVLnode(key, parent);\n }\n\n rebalance(parent);\n break;\n }\n }\n }\n\n return true;\n}\n\ntemplate \nvoid AVLtree::deleteKey(const T delKey) {\n if (root == NULL)\n return;\n\n AVLnode\n *n = root,\n *parent = root,\n *delNode = NULL,\n *child = root;\n\n while (child != NULL) {\n parent = n;\n n = child;\n child = delKey >= n->key ? n->right : n->left;\n if (delKey == n->key)\n delNode = n;\n }\n\n if (delNode != NULL) {\n delNode->key = n->key;\n\n child = n->left != NULL ? n->left : n->right;\n\n if (root->key == delKey) {\n root = child;\n }\n else {\n if (parent->left == n) {\n parent->left = child;\n }\n else {\n parent->right = child;\n }\n\n rebalance(parent);\n }\n }\n}\n\ntemplate \nvoid AVLtree::printBalance() {\n printBalance(root);\n std::cout << std::endl;\n}\n\nint main(void)\n{\n AVLtree t;\n\n std::cout << \"Inserting integer values 1 to 10\" << std::endl;\n for (int i = 1; i <= 10; ++i)\n t.insert(i);\n\n std::cout << \"Printing balance: \";\n t.printBalance();\n}\n"} -{"title": "AVL tree", "language": "Python", "task": "{{wikipedia|AVL tree}}\n\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 m-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": "# 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++ from C#", "task": "The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an\neasy way to add flexibility when specifying or using commands, sub-commands, options, etc.\n\n\n\nIt would make a list of words easier to maintain (as words are added, changed, and/or deleted) 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 (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_djele E_hene E_marte E_merkure E_enjte E_premte E_shtune\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 miercoles xueves vienres sabadu\nBazar_gUnU Birinci_gUn Ckinci_gUn UcUncU_gUn DOrdUncU_gUn Bes,inci_gUn Altonco_gUn\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 Mekredi Jedi Vandredi Samdi\nnedjelja ponedjeljak utorak srijeda cxetvrtak petak subota\nnede^le ponde^li utery str^eda c^tvrtek patek 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 ^Jaudo Vendredo Sabato\npUhapaev esmaspaev teisipaev kolmapaev neljapaev reede laupaev\n\nDiu_prima Diu_sequima Diu_tritima Diu_quartima Diu_quintima Diu_sextima Diu_sabbata\nsunnudagur manadagur tysdaguy mikudagur hosdagur 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 Mercores Joves Venres Sabado\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\npopule po`akahi po`alua po`akolu po`aha po`alima po`aono\nYom_rishon Yom_sheni Yom_shlishi Yom_revi'i Yom_chamishi Yom_shishi Shabat\nravivara somavar mangalavar budhavara brahaspativar shukravara shanivar\nvasarnap hetfo kedd szerda csutortok pentek szombat\nSunnudagur Manudagur +ridjudagur Midvikudagar Fimmtudagur FOstudagur Laugardagur\nsundio lundio mardio merkurdio jovdio venerdio saturdio\nMinggu Senin Selasa Rabu Kamis Jumat Sabtu\nDominica Lunedi Martedi Mercuridi Jovedi Venerdi Sabbato\nDe_Domhnaigh De_Luain De_Mairt De_Ceadaoin De_ardaoin De_hAoine De_Sathairn\ndomenica lunedi martedi mercoledi giovedi venerdi 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_Lunae 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-_ri xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu\nJedoonee Jelune Jemayrt Jecrean Jardaim Jeheiney Jesam\nJabot Manre Juje Wonje Taije Balaire Jarere\ngeminrongo minomishi martes mierkoles misheushi bernashi mishabaro\nAhad Isnin Selasa Rabu Khamis Jumaat Sabtu\nsphndag mandag tirsdag onsdag torsdag fredag lphrdag\nlo_dimenge lo_diluns lo_dimarc lo_dimercres lo_dijous lo_divendres lo_dissabte\ndjadomingo djaluna djamars djarason djaweps djabierna djasabra\nNiedziela Poniedzial/ek Wtorek S,roda Czwartek Pia,tek Sobota\nDomingo segunda-feire terca-feire quarta-feire quinta-feire sexta-feira sabado\nDomingo Lunes martes Miercoles Jueves Viernes Sabado\nDuminica Luni Mart'i Miercuri Joi Vineri Sambata\nvoskresenie ponedelnik vtornik sreda chetverg pyatnitsa subbota\nSunday Di-luain Di-mairt 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 miercoles jueves viernes sabado\nsonde mundey tude-wroko dride-wroko fode-wroko freyda Saturday\nJumapili Jumatatu Jumanne Jumatano Alhamisi Ijumaa Jumamosi\nsondag mandag tisdag onsdag torsdag fredag lordag\nLinggo Lunes Martes Miyerkoles Huwebes Biyernes Sabado\nLe-pai-jit Pai-it Pai-ji Pai-san Pai-si Pai-gO. Pai-lak\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 Car,samba Per,sembe Cuma Cumartesi\nnedilya ponedilok vivtorok sereda chetver pyatnytsya subota\nChu?_Nha.t Thu*_Hai Thu*_Ba Thu*_Tu* Thu*_Na'm Thu*_Sau Thu*_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_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni\nBazar_gUnU Bazar_aertaesi Caers,aenbae_axs,amo Caers,aenbae_gUnU CUmae_axs,amo CUmae_gUnU CUmae_Senbae\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 Sabado\nDies_Solis Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Sabbatum\nxing-_qi-_tian xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu\ndjadomingu djaluna djamars djarason djaweps djabierne djasabra\nKillachau Atichau Quoyllurchau Illapachau Chaskachau Kuychichau Intichau\n\n''Caveat: 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::* each line has a list of days-of-the-week for a language, separated by at least one blank\n::* the words on each line happen to be in order, from Sunday --> Saturday\n::* most lines have words in mixed case and some have all manner of accented words and other characters\n::* some words were translated to the nearest character that was available to ''code page'' '''437'''\n::* the characters in the words are not restricted except that they may not have imbedded blanks\n::* for this example, the use of an underscore ('''_''') was used to indicate a blank in a word\n\n\n;Task:\n::* The list of words (days of the week) needn't be verified/validated.\n::* Write a function to find the (numeric) minimum length abbreviation for each line that would make abbreviations unique.\n::* A blank line (or a null line) should return a null string.\n::* Process and show the output for at least the first '''five''' lines of the file.\n::* Show all output here.\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstd::vector split(const std::string& str, char delimiter) {\n std::vector tokens;\n std::string token;\n std::istringstream tokenStream(str);\n while (std::getline(tokenStream, token, delimiter)) {\n tokens.push_back(token);\n }\n return tokens;\n}\n\nint main() {\n using namespace std;\n string line;\n int i = 0;\n\n ifstream in(\"days_of_week.txt\");\n if (in.is_open()) {\n while (getline(in, line)) {\n i++;\n if (line.empty()) {\n continue;\n }\n\n auto days = split(line, ' ');\n if (days.size() != 7) {\n throw std::runtime_error(\"There aren't 7 days in line \" + i);\n }\n\n map temp;\n for (auto& day : days) {\n if (temp.find(day) != temp.end()) {\n cerr << \" \u221e \" << line << '\\n';\n continue;\n }\n temp[day] = 1;\n }\n\n int len = 1;\n while (true) {\n temp.clear();\n for (auto& day : days) {\n string key = day.substr(0, len);\n if (temp.find(key) != temp.end()) {\n break;\n }\n temp[key] = 1;\n }\n if (temp.size() == 7) {\n cout << setw(2) << len << \" \" << line << '\\n';\n break;\n }\n len++;\n }\n }\n }\n\n return 0;\n}"} -{"title": "Abbreviations, automatic", "language": "JavaScript", "task": "The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an\neasy way to add flexibility when specifying or using commands, sub-commands, options, etc.\n\n\n\nIt would make a list of words easier to maintain (as words are added, changed, and/or deleted) 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 (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_djele E_hene E_marte E_merkure E_enjte E_premte E_shtune\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 miercoles xueves vienres sabadu\nBazar_gUnU Birinci_gUn Ckinci_gUn UcUncU_gUn DOrdUncU_gUn Bes,inci_gUn Altonco_gUn\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 Mekredi Jedi Vandredi Samdi\nnedjelja ponedjeljak utorak srijeda cxetvrtak petak subota\nnede^le ponde^li utery str^eda c^tvrtek patek 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 ^Jaudo Vendredo Sabato\npUhapaev esmaspaev teisipaev kolmapaev neljapaev reede laupaev\n\nDiu_prima Diu_sequima Diu_tritima Diu_quartima Diu_quintima Diu_sextima Diu_sabbata\nsunnudagur manadagur tysdaguy mikudagur hosdagur 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 Mercores Joves Venres Sabado\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\npopule po`akahi po`alua po`akolu po`aha po`alima po`aono\nYom_rishon Yom_sheni Yom_shlishi Yom_revi'i Yom_chamishi Yom_shishi Shabat\nravivara somavar mangalavar budhavara brahaspativar shukravara shanivar\nvasarnap hetfo kedd szerda csutortok pentek szombat\nSunnudagur Manudagur +ridjudagur Midvikudagar Fimmtudagur FOstudagur Laugardagur\nsundio lundio mardio merkurdio jovdio venerdio saturdio\nMinggu Senin Selasa Rabu Kamis Jumat Sabtu\nDominica Lunedi Martedi Mercuridi Jovedi Venerdi Sabbato\nDe_Domhnaigh De_Luain De_Mairt De_Ceadaoin De_ardaoin De_hAoine De_Sathairn\ndomenica lunedi martedi mercoledi giovedi venerdi 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_Lunae 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-_ri xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu\nJedoonee Jelune Jemayrt Jecrean Jardaim Jeheiney Jesam\nJabot Manre Juje Wonje Taije Balaire Jarere\ngeminrongo minomishi martes mierkoles misheushi bernashi mishabaro\nAhad Isnin Selasa Rabu Khamis Jumaat Sabtu\nsphndag mandag tirsdag onsdag torsdag fredag lphrdag\nlo_dimenge lo_diluns lo_dimarc lo_dimercres lo_dijous lo_divendres lo_dissabte\ndjadomingo djaluna djamars djarason djaweps djabierna djasabra\nNiedziela Poniedzial/ek Wtorek S,roda Czwartek Pia,tek Sobota\nDomingo segunda-feire terca-feire quarta-feire quinta-feire sexta-feira sabado\nDomingo Lunes martes Miercoles Jueves Viernes Sabado\nDuminica Luni Mart'i Miercuri Joi Vineri Sambata\nvoskresenie ponedelnik vtornik sreda chetverg pyatnitsa subbota\nSunday Di-luain Di-mairt 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 miercoles jueves viernes sabado\nsonde mundey tude-wroko dride-wroko fode-wroko freyda Saturday\nJumapili Jumatatu Jumanne Jumatano Alhamisi Ijumaa Jumamosi\nsondag mandag tisdag onsdag torsdag fredag lordag\nLinggo Lunes Martes Miyerkoles Huwebes Biyernes Sabado\nLe-pai-jit Pai-it Pai-ji Pai-san Pai-si Pai-gO. Pai-lak\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 Car,samba Per,sembe Cuma Cumartesi\nnedilya ponedilok vivtorok sereda chetver pyatnytsya subota\nChu?_Nha.t Thu*_Hai Thu*_Ba Thu*_Tu* Thu*_Na'm Thu*_Sau Thu*_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_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni\nBazar_gUnU Bazar_aertaesi Caers,aenbae_axs,amo Caers,aenbae_gUnU CUmae_axs,amo CUmae_gUnU CUmae_Senbae\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 Sabado\nDies_Solis Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Sabbatum\nxing-_qi-_tian xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu\ndjadomingu djaluna djamars djarason djaweps djabierne djasabra\nKillachau Atichau Quoyllurchau Illapachau Chaskachau Kuychichau Intichau\n\n''Caveat: 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::* each line has a list of days-of-the-week for a language, separated by at least one blank\n::* the words on each line happen to be in order, from Sunday --> Saturday\n::* most lines have words in mixed case and some have all manner of accented words and other characters\n::* some words were translated to the nearest character that was available to ''code page'' '''437'''\n::* the characters in the words are not restricted except that they may not have imbedded blanks\n::* for this example, the use of an underscore ('''_''') was used to indicate a blank in a word\n\n\n;Task:\n::* The list of words (days of the week) needn't be verified/validated.\n::* Write a function to find the (numeric) minimum length abbreviation for each line that would make abbreviations unique.\n::* A blank line (or a null line) should return a null string.\n::* Process and show the output for at least the first '''five''' lines of the file.\n::* Show all output here.\n\n\n", "solution": "Array.prototype.hasDoubles = function() {\n let arr = this.slice();\n while (arr.length > 1) {\n let cur = arr.shift();\n if (arr.includes(cur)) return true;\n }\n return false;\n}\n\nfunction getMinAbbrLen(arr) {\n if (arr.length <= 1) return '';\n let testArr = [],\n len = 0, i;\n do {\n len++;\n for (i = 0; i < arr.length; i++)\n testArr[i] = arr[i].substr(0, len);\n } while (testArr.hasDoubles());\n return len;\n}\n\n// testing\nfor (let x = 0; x < list.length; x++) {\n let days = list[x].split(' '),\n l = getMinAbbrLen(days);\n for (let y = 0; y < days.length; y++)\n days[y] = days[y].substring(0, l);\n document.write(`

(${l}): ${days.join('. ')}.

`);\n}\n"} -{"title": "Abbreviations, automatic", "language": "Python from Kotlin", "task": "The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an\neasy way to add flexibility when specifying or using commands, sub-commands, options, etc.\n\n\n\nIt would make a list of words easier to maintain (as words are added, changed, and/or deleted) 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 (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_djele E_hene E_marte E_merkure E_enjte E_premte E_shtune\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 miercoles xueves vienres sabadu\nBazar_gUnU Birinci_gUn Ckinci_gUn UcUncU_gUn DOrdUncU_gUn Bes,inci_gUn Altonco_gUn\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 Mekredi Jedi Vandredi Samdi\nnedjelja ponedjeljak utorak srijeda cxetvrtak petak subota\nnede^le ponde^li utery str^eda c^tvrtek patek 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 ^Jaudo Vendredo Sabato\npUhapaev esmaspaev teisipaev kolmapaev neljapaev reede laupaev\n\nDiu_prima Diu_sequima Diu_tritima Diu_quartima Diu_quintima Diu_sextima Diu_sabbata\nsunnudagur manadagur tysdaguy mikudagur hosdagur 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 Mercores Joves Venres Sabado\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\npopule po`akahi po`alua po`akolu po`aha po`alima po`aono\nYom_rishon Yom_sheni Yom_shlishi Yom_revi'i Yom_chamishi Yom_shishi Shabat\nravivara somavar mangalavar budhavara brahaspativar shukravara shanivar\nvasarnap hetfo kedd szerda csutortok pentek szombat\nSunnudagur Manudagur +ridjudagur Midvikudagar Fimmtudagur FOstudagur Laugardagur\nsundio lundio mardio merkurdio jovdio venerdio saturdio\nMinggu Senin Selasa Rabu Kamis Jumat Sabtu\nDominica Lunedi Martedi Mercuridi Jovedi Venerdi Sabbato\nDe_Domhnaigh De_Luain De_Mairt De_Ceadaoin De_ardaoin De_hAoine De_Sathairn\ndomenica lunedi martedi mercoledi giovedi venerdi 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_Lunae 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-_ri xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu\nJedoonee Jelune Jemayrt Jecrean Jardaim Jeheiney Jesam\nJabot Manre Juje Wonje Taije Balaire Jarere\ngeminrongo minomishi martes mierkoles misheushi bernashi mishabaro\nAhad Isnin Selasa Rabu Khamis Jumaat Sabtu\nsphndag mandag tirsdag onsdag torsdag fredag lphrdag\nlo_dimenge lo_diluns lo_dimarc lo_dimercres lo_dijous lo_divendres lo_dissabte\ndjadomingo djaluna djamars djarason djaweps djabierna djasabra\nNiedziela Poniedzial/ek Wtorek S,roda Czwartek Pia,tek Sobota\nDomingo segunda-feire terca-feire quarta-feire quinta-feire sexta-feira sabado\nDomingo Lunes martes Miercoles Jueves Viernes Sabado\nDuminica Luni Mart'i Miercuri Joi Vineri Sambata\nvoskresenie ponedelnik vtornik sreda chetverg pyatnitsa subbota\nSunday Di-luain Di-mairt 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 miercoles jueves viernes sabado\nsonde mundey tude-wroko dride-wroko fode-wroko freyda Saturday\nJumapili Jumatatu Jumanne Jumatano Alhamisi Ijumaa Jumamosi\nsondag mandag tisdag onsdag torsdag fredag lordag\nLinggo Lunes Martes Miyerkoles Huwebes Biyernes Sabado\nLe-pai-jit Pai-it Pai-ji Pai-san Pai-si Pai-gO. Pai-lak\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 Car,samba Per,sembe Cuma Cumartesi\nnedilya ponedilok vivtorok sereda chetver pyatnytsya subota\nChu?_Nha.t Thu*_Hai Thu*_Ba Thu*_Tu* Thu*_Na'm Thu*_Sau Thu*_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_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni\nBazar_gUnU Bazar_aertaesi Caers,aenbae_axs,amo Caers,aenbae_gUnU CUmae_axs,amo CUmae_gUnU CUmae_Senbae\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 Sabado\nDies_Solis Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Sabbatum\nxing-_qi-_tian xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu\ndjadomingu djaluna djamars djarason djaweps djabierne djasabra\nKillachau Atichau Quoyllurchau Illapachau Chaskachau Kuychichau Intichau\n\n''Caveat: 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::* each line has a list of days-of-the-week for a language, separated by at least one blank\n::* the words on each line happen to be in order, from Sunday --> Saturday\n::* most lines have words in mixed case and some have all manner of accented words and other characters\n::* some words were translated to the nearest character that was available to ''code page'' '''437'''\n::* the characters in the words are not restricted except that they may not have imbedded blanks\n::* for this example, the use of an underscore ('''_''') was used to indicate a blank in a word\n\n\n;Task:\n::* The list of words (days of the week) needn't be verified/validated.\n::* Write a function to find the (numeric) minimum length abbreviation for each line that would make abbreviations unique.\n::* A blank line (or a null line) should return a null string.\n::* Process and show the output for at least the first '''five''' lines of the file.\n::* Show all output here.\n\n\n", "solution": "def shortest_abbreviation_length(line, list_size):\n words = line.split()\n word_count = len(words)\n # Can't give true answer with unexpected number of entries\n if word_count != list_size:\n raise ValueError(f'Not enough entries, expected {list_size} found {word_count}')\n\n # Find the small slice length that gives list_size unique values\n abbreviation_length = 1\n abbreviations = set()\n while(True):\n abbreviations = {word[:abbreviation_length] for word in words}\n if len(abbreviations) == list_size:\n return abbreviation_length\n abbreviation_length += 1\n abbreviations.clear()\n\ndef automatic_abbreviations(filename, words_per_line):\n with open(filename) as file:\n for line in file:\n line = line.rstrip()\n if len(line) > 0:\n length = shortest_abbreviation_length(line, words_per_line)\n print(f'{length:2} {line}')\n else:\n print()\n\nautomatic_abbreviations('daysOfWeek.txt', 7)"} -{"title": "Abbreviations, automatic", "language": "Python 3", "task": "The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an\neasy way to add flexibility when specifying or using commands, sub-commands, options, etc.\n\n\n\nIt would make a list of words easier to maintain (as words are added, changed, and/or deleted) 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 (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_djele E_hene E_marte E_merkure E_enjte E_premte E_shtune\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 miercoles xueves vienres sabadu\nBazar_gUnU Birinci_gUn Ckinci_gUn UcUncU_gUn DOrdUncU_gUn Bes,inci_gUn Altonco_gUn\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 Mekredi Jedi Vandredi Samdi\nnedjelja ponedjeljak utorak srijeda cxetvrtak petak subota\nnede^le ponde^li utery str^eda c^tvrtek patek 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 ^Jaudo Vendredo Sabato\npUhapaev esmaspaev teisipaev kolmapaev neljapaev reede laupaev\n\nDiu_prima Diu_sequima Diu_tritima Diu_quartima Diu_quintima Diu_sextima Diu_sabbata\nsunnudagur manadagur tysdaguy mikudagur hosdagur 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 Mercores Joves Venres Sabado\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\npopule po`akahi po`alua po`akolu po`aha po`alima po`aono\nYom_rishon Yom_sheni Yom_shlishi Yom_revi'i Yom_chamishi Yom_shishi Shabat\nravivara somavar mangalavar budhavara brahaspativar shukravara shanivar\nvasarnap hetfo kedd szerda csutortok pentek szombat\nSunnudagur Manudagur +ridjudagur Midvikudagar Fimmtudagur FOstudagur Laugardagur\nsundio lundio mardio merkurdio jovdio venerdio saturdio\nMinggu Senin Selasa Rabu Kamis Jumat Sabtu\nDominica Lunedi Martedi Mercuridi Jovedi Venerdi Sabbato\nDe_Domhnaigh De_Luain De_Mairt De_Ceadaoin De_ardaoin De_hAoine De_Sathairn\ndomenica lunedi martedi mercoledi giovedi venerdi 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_Lunae 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-_ri xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu\nJedoonee Jelune Jemayrt Jecrean Jardaim Jeheiney Jesam\nJabot Manre Juje Wonje Taije Balaire Jarere\ngeminrongo minomishi martes mierkoles misheushi bernashi mishabaro\nAhad Isnin Selasa Rabu Khamis Jumaat Sabtu\nsphndag mandag tirsdag onsdag torsdag fredag lphrdag\nlo_dimenge lo_diluns lo_dimarc lo_dimercres lo_dijous lo_divendres lo_dissabte\ndjadomingo djaluna djamars djarason djaweps djabierna djasabra\nNiedziela Poniedzial/ek Wtorek S,roda Czwartek Pia,tek Sobota\nDomingo segunda-feire terca-feire quarta-feire quinta-feire sexta-feira sabado\nDomingo Lunes martes Miercoles Jueves Viernes Sabado\nDuminica Luni Mart'i Miercuri Joi Vineri Sambata\nvoskresenie ponedelnik vtornik sreda chetverg pyatnitsa subbota\nSunday Di-luain Di-mairt 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 miercoles jueves viernes sabado\nsonde mundey tude-wroko dride-wroko fode-wroko freyda Saturday\nJumapili Jumatatu Jumanne Jumatano Alhamisi Ijumaa Jumamosi\nsondag mandag tisdag onsdag torsdag fredag lordag\nLinggo Lunes Martes Miyerkoles Huwebes Biyernes Sabado\nLe-pai-jit Pai-it Pai-ji Pai-san Pai-si Pai-gO. Pai-lak\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 Car,samba Per,sembe Cuma Cumartesi\nnedilya ponedilok vivtorok sereda chetver pyatnytsya subota\nChu?_Nha.t Thu*_Hai Thu*_Ba Thu*_Tu* Thu*_Na'm Thu*_Sau Thu*_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_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni\nBazar_gUnU Bazar_aertaesi Caers,aenbae_axs,amo Caers,aenbae_gUnU CUmae_axs,amo CUmae_gUnU CUmae_Senbae\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 Sabado\nDies_Solis Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Sabbatum\nxing-_qi-_tian xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu\ndjadomingu djaluna djamars djarason djaweps djabierne djasabra\nKillachau Atichau Quoyllurchau Illapachau Chaskachau Kuychichau Intichau\n\n''Caveat: 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::* each line has a list of days-of-the-week for a language, separated by at least one blank\n::* the words on each line happen to be in order, from Sunday --> Saturday\n::* most lines have words in mixed case and some have all manner of accented words and other characters\n::* some words were translated to the nearest character that was available to ''code page'' '''437'''\n::* the characters in the words are not restricted except that they may not have imbedded blanks\n::* for this example, the use of an underscore ('''_''') was used to indicate a blank in a word\n\n\n;Task:\n::* The list of words (days of the week) needn't be verified/validated.\n::* Write a function to find the (numeric) minimum length abbreviation for each line that would make abbreviations unique.\n::* A blank line (or a null line) should return a null string.\n::* Process and show the output for at least the first '''five''' lines of the file.\n::* Show all output here.\n\n\n", "solution": "'''Automatic abbreviations'''\n\nfrom itertools import (accumulate, chain)\nfrom os.path import expanduser\n\n\n# abbrevLen :: [String] -> Int\ndef abbrevLen(xs):\n '''The minimum length of prefix required to obtain\n a unique abbreviation for each string in xs.'''\n n = len(xs)\n\n return next(\n len(a[0]) for a in map(\n compose(nub)(map_(concat)),\n transpose(list(map(inits, xs)))\n ) if n == len(a)\n )\n\n\n# TEST ----------------------------------------------------\ndef main():\n '''Test'''\n\n xs = map_(strip)(\n lines(readFile('weekDayNames.txt'))\n )\n for i, n in enumerate(map(compose(abbrevLen)(words), xs)):\n print(n, ' ', xs[i])\n\n\n# GENERIC -------------------------------------------------\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# concat :: [String] -> String\ndef concat(xs):\n '''The concatenation of a list of strings.'''\n return ''.join(xs)\n\n\n# inits :: [a] -> [[a]]\ndef inits(xs):\n '''all initial segments of xs, shortest first.'''\n return list(scanl(lambda a, x: a + [x])(\n []\n )(list(xs)))\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 return s.splitlines()\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 return lambda xs: list(map(f, xs))\n\n\n# nub :: [a] -> [a]\ndef nub(xs):\n '''A list containing the same elements as xs,\n without duplicates, in the order of their\n first occurrence.'''\n return list(dict.fromkeys(xs))\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 with open(expanduser(fp), 'r', encoding='utf-8') as f:\n return f.read()\n\n\n# scanl :: (b -> a -> b) -> b -> [a] -> [b]\ndef scanl(f):\n '''scanl is like reduce, but returns a succession of\n intermediate values, building from the left.'''\n return lambda a: lambda xs: (\n accumulate(chain([a], xs), f)\n )\n\n\n# strip :: String -> String\ndef strip(s):\n '''A copy of s without any leading or trailling\n white space.'''\n return s.strip()\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# words :: String -> [String]\ndef words(s):\n '''A list of words delimited by characters\n representing white space.'''\n return s.split()\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} -{"title": "Abbreviations, easy", "language": "C", "task": "This task is an easier (to code) variant of the Rosetta Code task: [[Abbreviations, simple]].\n\n\nFor this task, the following ''command table'' will be used:\n Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\n COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\n MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\n READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\n RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up\n\n\n\n\nNotes concerning the above ''command table'':\n::* it can be thought of as one long literal string (with blanks at end-of-lines)\n::* it may have superfluous blanks\n::* it may be in any case (lower/upper/mixed)\n::* the order of the words in the ''command table'' must be preserved as shown\n::* the user input(s) may be in any case (upper/lower/mixed)\n::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)\n::* A valid abbreviation is a word that has:\n:::* at least the minimum length of the number of capital letters of the word in the ''command table''\n:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''\n:::* a length not longer than the word in the ''command table''\n::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTer'''\n::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTer'''\n::::* The number of capital letters in '''ALTer''' indicates that any abbreviation for '''ALTer''' must be at least three letters\n::::* Any word longer than five characters can't be an abbreviation for '''ALTer'''\n::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''Overlay'''\n::* if there isn't any lowercase letters in the word in the ''command table'', then there isn't an abbreviation permitted\n\n\n\n;Task:\n::* The command table needn't be verified/validated.\n::* Write a function to validate if the user \"words\" (given as input) are valid (in the ''command table'').\n::* If the word is valid, then return the full uppercase version of that \"word\".\n::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).\n::* A blank input (or a null input) should return a null string.\n::* Show all output here.\n\n\n;An example test case to be used for this task:\nFor a user string of:\n riG rePEAT copies put mo rest types fup. 6 poweRin\nthe computer program should return the string:\n RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nconst char* command_table =\n \"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy \"\n \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n \"Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO \"\n \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT \"\n \"READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT \"\n \"RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n char* cmd;\n size_t length;\n size_t min_len;\n struct command_tag* next;\n} command_t;\n\n// str is assumed to be all uppercase\nbool command_match(const command_t* command, const char* str) {\n size_t olen = strlen(str);\n return olen >= command->min_len && olen <= command->length\n && strncmp(str, command->cmd, olen) == 0;\n}\n\n// convert string to uppercase\nchar* uppercase(char* str, size_t n) {\n for (size_t i = 0; i < n; ++i)\n str[i] = toupper((unsigned char)str[i]);\n return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n size_t len = 0;\n while (len < n && isupper((unsigned char)str[len]))\n ++len;\n return len;\n}\n\nvoid fatal(const char* message) {\n fprintf(stderr, \"%s\\n\", message);\n exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n void* ptr = malloc(n);\n if (ptr == NULL)\n fatal(\"Out of memory\");\n return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n void* ptr = realloc(p, n);\n if (ptr == NULL)\n fatal(\"Out of memory\");\n return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n size_t size = 0;\n size_t capacity = 16;\n char** words = xmalloc(capacity * sizeof(char*));\n size_t len = strlen(str);\n for (size_t begin = 0; begin < len; ) {\n size_t i = begin;\n for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n begin = i;\n for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n size_t word_len = i - begin;\n if (word_len == 0)\n break;\n char* word = xmalloc(word_len + 1);\n memcpy(word, str + begin, word_len);\n word[word_len] = 0;\n begin += word_len;\n if (capacity == size) {\n capacity *= 2;\n words = xrealloc(words, capacity * sizeof(char*));\n }\n words[size++] = word;\n }\n *count = size;\n return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n command_t* cmd = NULL;\n size_t count = 0;\n char** words = split_into_words(table, &count);\n for (size_t i = 0; i < count; ++i) {\n char* word = words[i];\n command_t* new_cmd = xmalloc(sizeof(command_t));\n size_t word_len = strlen(word);\n new_cmd->length = word_len;\n new_cmd->min_len = get_min_length(word, word_len);\n new_cmd->cmd = uppercase(word, word_len);\n new_cmd->next = cmd;\n cmd = new_cmd;\n }\n free(words);\n return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n while (cmd != NULL) {\n command_t* next = cmd->next;\n free(cmd->cmd);\n free(cmd);\n cmd = next;\n }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n if (command_match(cmd, word))\n return cmd;\n }\n return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n printf(\" input: %s\\n\", input);\n printf(\"output:\");\n size_t count = 0;\n char** words = split_into_words(input, &count);\n for (size_t i = 0; i < count; ++i) {\n char* word = words[i];\n uppercase(word, strlen(word));\n const command_t* cmd_ptr = find_command(commands, word);\n printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n free(word);\n }\n free(words);\n printf(\"\\n\");\n}\n\nint main() {\n command_t* commands = make_command_list(command_table);\n const char* input = \"riG rePEAT copies put mo rest types fup. 6 poweRin\";\n test(commands, input);\n free_command_list(commands);\n return 0;\n}"} -{"title": "Abbreviations, easy", "language": "C++", "task": "This task is an easier (to code) variant of the Rosetta Code task: [[Abbreviations, simple]].\n\n\nFor this task, the following ''command table'' will be used:\n Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\n COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\n MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\n READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\n RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up\n\n\n\n\nNotes concerning the above ''command table'':\n::* it can be thought of as one long literal string (with blanks at end-of-lines)\n::* it may have superfluous blanks\n::* it may be in any case (lower/upper/mixed)\n::* the order of the words in the ''command table'' must be preserved as shown\n::* the user input(s) may be in any case (upper/lower/mixed)\n::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)\n::* A valid abbreviation is a word that has:\n:::* at least the minimum length of the number of capital letters of the word in the ''command table''\n:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''\n:::* a length not longer than the word in the ''command table''\n::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTer'''\n::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTer'''\n::::* The number of capital letters in '''ALTer''' indicates that any abbreviation for '''ALTer''' must be at least three letters\n::::* Any word longer than five characters can't be an abbreviation for '''ALTer'''\n::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''Overlay'''\n::* if there isn't any lowercase letters in the word in the ''command table'', then there isn't an abbreviation permitted\n\n\n\n;Task:\n::* The command table needn't be verified/validated.\n::* Write a function to validate if the user \"words\" (given as input) are valid (in the ''command table'').\n::* If the word is valid, then return the full uppercase version of that \"word\".\n::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).\n::* A blank input (or a null input) should return a null string.\n::* Show all output here.\n\n\n;An example test case to be used for this task:\nFor a user string of:\n riG rePEAT copies put mo rest types fup. 6 poweRin\nthe computer program should return the string:\n RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n\nconst char* command_table =\n \"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy \"\n \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n \"Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO \"\n \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT \"\n \"READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT \"\n \"RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up\";\n\nclass command {\npublic:\n command(const std::string&, size_t);\n const std::string& cmd() const { return cmd_; }\n size_t min_length() const { return min_len_; }\n bool match(const std::string&) const;\nprivate:\n std::string cmd_;\n size_t min_len_;\n};\n\n// cmd is assumed to be all uppercase\ncommand::command(const std::string& cmd, size_t min_len)\n : cmd_(cmd), min_len_(min_len) {}\n\n// str is assumed to be all uppercase\nbool command::match(const std::string& str) const {\n size_t olen = str.length();\n return olen >= min_len_ && olen <= cmd_.length()\n && cmd_.compare(0, olen, str) == 0;\n}\n\n// convert string to uppercase\nvoid uppercase(std::string& str) {\n std::transform(str.begin(), str.end(), str.begin(),\n [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nsize_t get_min_length(const std::string& str) {\n size_t len = 0, n = str.length();\n while (len < n && std::isupper(static_cast(str[len])))\n ++len;\n return len;\n}\n\nclass command_list {\npublic:\n explicit command_list(const char*);\n const command* find_command(const std::string&) const;\nprivate:\n std::vector commands_;\n};\n\ncommand_list::command_list(const char* table) {\n std::vector commands;\n std::istringstream is(table);\n std::string word;\n while (is >> word) {\n // count leading uppercase characters\n size_t len = get_min_length(word);\n // then convert to uppercase\n uppercase(word);\n commands_.push_back(command(word, len));\n }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n auto iter = std::find_if(commands_.begin(), commands_.end(),\n [&word](const command& cmd) { return cmd.match(word); });\n return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n std::string output;\n std::istringstream is(input);\n std::string word;\n while (is >> word) {\n if (!output.empty())\n output += ' ';\n uppercase(word);\n const command* cmd_ptr = commands.find_command(word);\n if (cmd_ptr)\n output += cmd_ptr->cmd();\n else\n output += \"*error*\";\n }\n return output;\n}\n\nint main() {\n command_list commands(command_table);\n std::string input(\"riG rePEAT copies put mo rest types fup. 6 poweRin\");\n std::string output(test(commands, input));\n std::cout << \" input: \" << input << '\\n';\n std::cout << \"output: \" << output << '\\n';\n return 0;\n}"} -{"title": "Abbreviations, easy", "language": "JavaScript", "task": "This task is an easier (to code) variant of the Rosetta Code task: [[Abbreviations, simple]].\n\n\nFor this task, the following ''command table'' will be used:\n Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\n COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\n MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\n READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\n RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up\n\n\n\n\nNotes concerning the above ''command table'':\n::* it can be thought of as one long literal string (with blanks at end-of-lines)\n::* it may have superfluous blanks\n::* it may be in any case (lower/upper/mixed)\n::* the order of the words in the ''command table'' must be preserved as shown\n::* the user input(s) may be in any case (upper/lower/mixed)\n::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)\n::* A valid abbreviation is a word that has:\n:::* at least the minimum length of the number of capital letters of the word in the ''command table''\n:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''\n:::* a length not longer than the word in the ''command table''\n::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTer'''\n::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTer'''\n::::* The number of capital letters in '''ALTer''' indicates that any abbreviation for '''ALTer''' must be at least three letters\n::::* Any word longer than five characters can't be an abbreviation for '''ALTer'''\n::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''Overlay'''\n::* if there isn't any lowercase letters in the word in the ''command table'', then there isn't an abbreviation permitted\n\n\n\n;Task:\n::* The command table needn't be verified/validated.\n::* Write a function to validate if the user \"words\" (given as input) are valid (in the ''command table'').\n::* If the word is valid, then return the full uppercase version of that \"word\".\n::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).\n::* A blank input (or a null input) should return a null string.\n::* Show all output here.\n\n\n;An example test case to be used for this task:\nFor a user string of:\n riG rePEAT copies put mo rest types fup. 6 poweRin\nthe computer program should return the string:\n RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\n\n\n", "solution": "var abr=`Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\n COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\n MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\n READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\n RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up`\n .split(/\\W+/).map(_=>_.trim())\nfunction escapeRegex(string) {\n return string.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&');\n}\nvar input = prompt();\nconsole.log(input.length==0?null:input.trim().split(/\\s+/)\n .map(\n (s=>abr.filter(\n a=>(new RegExp('^'+escapeRegex(s),'i'))\n .test(a)&&s.length>=a.match(/^[A-Z]+/)[0].length\n\t\t\t\t )[0])\n\t\t\t\t)\n .map(_=>typeof _==\"undefined\"?\"*error*\":_).join(' ')\n\t\t\t)\n\n"} -{"title": "Abbreviations, easy", "language": "Python 3.6", "task": "This task is an easier (to code) variant of the Rosetta Code task: [[Abbreviations, simple]].\n\n\nFor this task, the following ''command table'' will be used:\n Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\n COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\n MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\n READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\n RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up\n\n\n\n\nNotes concerning the above ''command table'':\n::* it can be thought of as one long literal string (with blanks at end-of-lines)\n::* it may have superfluous blanks\n::* it may be in any case (lower/upper/mixed)\n::* the order of the words in the ''command table'' must be preserved as shown\n::* the user input(s) may be in any case (upper/lower/mixed)\n::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)\n::* A valid abbreviation is a word that has:\n:::* at least the minimum length of the number of capital letters of the word in the ''command table''\n:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''\n:::* a length not longer than the word in the ''command table''\n::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTer'''\n::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTer'''\n::::* The number of capital letters in '''ALTer''' indicates that any abbreviation for '''ALTer''' must be at least three letters\n::::* Any word longer than five characters can't be an abbreviation for '''ALTer'''\n::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''Overlay'''\n::* if there isn't any lowercase letters in the word in the ''command table'', then there isn't an abbreviation permitted\n\n\n\n;Task:\n::* The command table needn't be verified/validated.\n::* Write a function to validate if the user \"words\" (given as input) are valid (in the ''command table'').\n::* If the word is valid, then return the full uppercase version of that \"word\".\n::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).\n::* A blank input (or a null input) should return a null string.\n::* Show all output here.\n\n\n;An example test case to be used for this task:\nFor a user string of:\n riG rePEAT copies put mo rest types fup. 6 poweRin\nthe computer program should return the string:\n RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\n\n\n", "solution": "command_table_text = \\\n\"\"\"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\nCOUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\nNFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\nJoin SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\nMErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\nREAD RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\nRIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up\"\"\"\n\nuser_words = \"riG rePEAT copies put mo rest types fup. 6 poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n \"\"\" find the minimal abbreviation length for each word by counting capital letters.\n a word that does not have capital letters gets it's full length as the minimum.\n \"\"\"\n command_table = dict()\n for word in command_table_text.split():\n abbr_len = sum(1 for c in word if c.isupper())\n if abbr_len == 0:\n abbr_len = len(word)\n command_table[word] = abbr_len\n return command_table\n\ndef find_abbreviations(command_table):\n \"\"\" for each command insert all possible abbreviations\"\"\"\n abbreviations = dict()\n for command, min_abbr_len in command_table.items():\n for l in range(min_abbr_len, len(command)+1):\n abbr = command[:l].lower()\n abbreviations[abbr] = command.upper()\n return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n user_words = [word.lower() for word in user_string.split()]\n commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)"} -{"title": "Abbreviations, simple", "language": "C", "task": "The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an \neasy way to add flexibility when specifying or using commands, sub-commands, options, etc.\n\n\n\nFor this task, the following ''command table'' will be used:\n add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3\n compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate\n 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2\n forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load\n locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2\n msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3\n refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left\n 2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1\n\n\n\n\nNotes concerning the above ''command table'':\n::* it can be thought of as one long literal string (with blanks at end-of-lines)\n::* it may have superfluous blanks\n::* it may be in any case (lower/upper/mixed)\n::* the order of the words in the ''command table'' must be preserved as shown\n::* the user input(s) may be in any case (upper/lower/mixed)\n::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)\n::* a command is followed by an optional number, which indicates the minimum abbreviation\n::* A valid abbreviation is a word that has:\n:::* at least the minimum length of the word's minimum number in the ''command table''\n:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''\n:::* a length not longer than the word in the ''command table''\n::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTER 3'''\n::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTER 3'''\n::::* The '''3''' indicates that any abbreviation for '''ALTER''' must be at least three characters\n::::* Any word longer than five characters can't be an abbreviation for '''ALTER'''\n::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''overlay 1'''\n::* if there isn't a number after the command, then there isn't an abbreviation permitted\n\n\n\n;Task:\n::* The command table needn't be verified/validated.\n::* Write a function to validate if the user \"words\" (given as input) are valid (in the ''command table'').\n::* If the word is valid, then return the full uppercase version of that \"word\".\n::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).\n::* A blank input (or a null input) should return a null string.\n::* Show all output here.\n\n\n;An example test case to be used for this task:\nFor a user string of:\n riG rePEAT copies put mo rest types fup. 6 poweRin\nthe computer program should return the string:\n RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nconst char* command_table =\n \"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 \"\n \"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate \"\n \"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n \"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load \"\n \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 \"\n \"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 \"\n \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n \"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1\";\n\ntypedef struct command_tag {\n char* cmd;\n size_t length;\n size_t min_len;\n struct command_tag* next;\n} command_t;\n\n// str is assumed to be all uppercase\nbool command_match(const command_t* command, const char* str) {\n size_t olen = strlen(str);\n return olen >= command->min_len && olen <= command->length\n && strncmp(str, command->cmd, olen) == 0;\n}\n\n// convert string to uppercase\nchar* uppercase(char* str, size_t n) {\n for (size_t i = 0; i < n; ++i)\n str[i] = toupper((unsigned char)str[i]);\n return str;\n}\n\nvoid fatal(const char* message) {\n fprintf(stderr, \"%s\\n\", message);\n exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n void* ptr = malloc(n);\n if (ptr == NULL)\n fatal(\"Out of memory\");\n return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n void* ptr = realloc(p, n);\n if (ptr == NULL)\n fatal(\"Out of memory\");\n return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n size_t size = 0;\n size_t capacity = 16;\n char** words = xmalloc(capacity * sizeof(char*));\n size_t len = strlen(str);\n for (size_t begin = 0; begin < len; ) {\n size_t i = begin;\n for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n begin = i;\n for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n size_t word_len = i - begin;\n if (word_len == 0)\n break;\n char* word = xmalloc(word_len + 1);\n memcpy(word, str + begin, word_len);\n word[word_len] = 0;\n begin += word_len;\n if (capacity == size) {\n capacity *= 2;\n words = xrealloc(words, capacity * sizeof(char*));\n }\n words[size++] = word;\n }\n *count = size;\n return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n command_t* cmd = NULL;\n size_t count = 0;\n char** words = split_into_words(table, &count);\n for (size_t i = 0; i < count; ++i) {\n char* word = words[i];\n command_t* new_cmd = xmalloc(sizeof(command_t));\n size_t word_len = strlen(word);\n new_cmd->length = word_len;\n new_cmd->min_len = word_len;\n new_cmd->cmd = uppercase(word, word_len);\n if (i + 1 < count) {\n char* eptr = 0;\n unsigned long min_len = strtoul(words[i + 1], &eptr, 10);\n if (min_len > 0 && *eptr == 0) {\n free(words[i + 1]);\n new_cmd->min_len = min_len;\n ++i;\n }\n }\n new_cmd->next = cmd;\n cmd = new_cmd;\n }\n free(words);\n return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n while (cmd != NULL) {\n command_t* next = cmd->next;\n free(cmd->cmd);\n free(cmd);\n cmd = next;\n }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n if (command_match(cmd, word))\n return cmd;\n }\n return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n printf(\" input: %s\\n\", input);\n printf(\"output:\");\n size_t count = 0;\n char** words = split_into_words(input, &count);\n for (size_t i = 0; i < count; ++i) {\n char* word = words[i];\n uppercase(word, strlen(word));\n const command_t* cmd_ptr = find_command(commands, word);\n printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n free(word);\n }\n free(words);\n printf(\"\\n\");\n}\n\nint main() {\n command_t* commands = make_command_list(command_table);\n const char* input = \"riG rePEAT copies put mo rest types fup. 6 poweRin\";\n test(commands, input);\n free_command_list(commands);\n return 0;\n}"} -{"title": "Abbreviations, simple", "language": "C++", "task": "The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an \neasy way to add flexibility when specifying or using commands, sub-commands, options, etc.\n\n\n\nFor this task, the following ''command table'' will be used:\n add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3\n compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate\n 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2\n forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load\n locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2\n msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3\n refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left\n 2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1\n\n\n\n\nNotes concerning the above ''command table'':\n::* it can be thought of as one long literal string (with blanks at end-of-lines)\n::* it may have superfluous blanks\n::* it may be in any case (lower/upper/mixed)\n::* the order of the words in the ''command table'' must be preserved as shown\n::* the user input(s) may be in any case (upper/lower/mixed)\n::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)\n::* a command is followed by an optional number, which indicates the minimum abbreviation\n::* A valid abbreviation is a word that has:\n:::* at least the minimum length of the word's minimum number in the ''command table''\n:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''\n:::* a length not longer than the word in the ''command table''\n::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTER 3'''\n::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTER 3'''\n::::* The '''3''' indicates that any abbreviation for '''ALTER''' must be at least three characters\n::::* Any word longer than five characters can't be an abbreviation for '''ALTER'''\n::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''overlay 1'''\n::* if there isn't a number after the command, then there isn't an abbreviation permitted\n\n\n\n;Task:\n::* The command table needn't be verified/validated.\n::* Write a function to validate if the user \"words\" (given as input) are valid (in the ''command table'').\n::* If the word is valid, then return the full uppercase version of that \"word\".\n::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).\n::* A blank input (or a null input) should return a null string.\n::* Show all output here.\n\n\n;An example test case to be used for this task:\nFor a user string of:\n riG rePEAT copies put mo rest types fup. 6 poweRin\nthe computer program should return the string:\n RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n\nconst char* command_table =\n \"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 \"\n \"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate \"\n \"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n \"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load \"\n \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 \"\n \"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 \"\n \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n \"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1\";\n\nclass command {\npublic:\n command(const std::string&, size_t);\n const std::string& cmd() const { return cmd_; }\n size_t min_length() const { return min_len_; }\n bool match(const std::string&) const;\nprivate:\n std::string cmd_;\n size_t min_len_;\n};\n\n// cmd is assumed to be all uppercase\ncommand::command(const std::string& cmd, size_t min_len)\n : cmd_(cmd), min_len_(min_len) {}\n\n// str is assumed to be all uppercase\nbool command::match(const std::string& str) const {\n size_t olen = str.length();\n return olen >= min_len_ && olen <= cmd_.length()\n && cmd_.compare(0, olen, str) == 0;\n}\n\nbool parse_integer(const std::string& word, int& value) {\n try {\n size_t pos;\n int i = std::stoi(word, &pos, 10);\n if (pos < word.length())\n return false;\n value = i;\n return true;\n } catch (const std::exception& ex) {\n return false;\n }\n}\n\n// convert string to uppercase\nvoid uppercase(std::string& str) {\n std::transform(str.begin(), str.end(), str.begin(),\n [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nclass command_list {\npublic:\n explicit command_list(const char*);\n const command* find_command(const std::string&) const;\nprivate:\n std::vector commands_;\n};\n\ncommand_list::command_list(const char* table) {\n std::istringstream is(table);\n std::string word;\n std::vector words;\n while (is >> word) {\n uppercase(word);\n words.push_back(word);\n }\n for (size_t i = 0, n = words.size(); i < n; ++i) {\n word = words[i];\n // if there's an integer following this word, it specifies the minimum\n // length for the command, otherwise the minimum length is the length\n // of the command string\n int len = word.length();\n if (i + 1 < n && parse_integer(words[i + 1], len))\n ++i;\n commands_.push_back(command(word, len));\n }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n auto iter = std::find_if(commands_.begin(), commands_.end(),\n [&word](const command& cmd) { return cmd.match(word); });\n return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n std::string output;\n std::istringstream is(input);\n std::string word;\n while (is >> word) {\n if (!output.empty())\n output += ' ';\n uppercase(word);\n const command* cmd_ptr = commands.find_command(word);\n if (cmd_ptr)\n output += cmd_ptr->cmd();\n else\n output += \"*error*\";\n }\n return output;\n}\n\nint main() {\n command_list commands(command_table);\n std::string input(\"riG rePEAT copies put mo rest types fup. 6 poweRin\");\n std::string output(test(commands, input));\n std::cout << \" input: \" << input << '\\n';\n std::cout << \"output: \" << output << '\\n';\n return 0;\n}"} -{"title": "Abbreviations, simple", "language": "JavaScript from Python", "task": "The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an \neasy way to add flexibility when specifying or using commands, sub-commands, options, etc.\n\n\n\nFor this task, the following ''command table'' will be used:\n add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3\n compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate\n 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2\n forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load\n locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2\n msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3\n refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left\n 2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1\n\n\n\n\nNotes concerning the above ''command table'':\n::* it can be thought of as one long literal string (with blanks at end-of-lines)\n::* it may have superfluous blanks\n::* it may be in any case (lower/upper/mixed)\n::* the order of the words in the ''command table'' must be preserved as shown\n::* the user input(s) may be in any case (upper/lower/mixed)\n::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)\n::* a command is followed by an optional number, which indicates the minimum abbreviation\n::* A valid abbreviation is a word that has:\n:::* at least the minimum length of the word's minimum number in the ''command table''\n:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''\n:::* a length not longer than the word in the ''command table''\n::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTER 3'''\n::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTER 3'''\n::::* The '''3''' indicates that any abbreviation for '''ALTER''' must be at least three characters\n::::* Any word longer than five characters can't be an abbreviation for '''ALTER'''\n::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''overlay 1'''\n::* if there isn't a number after the command, then there isn't an abbreviation permitted\n\n\n\n;Task:\n::* The command table needn't be verified/validated.\n::* Write a function to validate if the user \"words\" (given as input) are valid (in the ''command table'').\n::* If the word is valid, then return the full uppercase version of that \"word\".\n::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).\n::* A blank input (or a null input) should return a null string.\n::* Show all output here.\n\n\n;An example test case to be used for this task:\nFor a user string of:\n riG rePEAT copies put mo rest types fup. 6 poweRin\nthe computer program should return the string:\n RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\n\n\n", "solution": "(() => {\n 'use strict';\n\n // withExpansions :: [(String, Int)] -> String -> String\n const withExpansions = tbl => s =>\n unwords(map(expanded(tbl), words(s)));\n\n // expanded :: [(String, Int)] -> String -> String\n const expanded = tbl => s => {\n const\n lng = s.length,\n u = toUpper(s),\n p = wn => {\n const [w, n] = Array.from(wn);\n return lng >= n && isPrefixOf(u, w);\n }\n return maybe(\n '*error*',\n fst,\n 0 < lng ? (\n find(p, tbl)\n ) : Just(Tuple([], 0))\n );\n };\n\n // cmdsFromString :: String -> [(String, Int)]\n const cmdsFromString = s =>\n fst(foldr(\n (w, a) => {\n const [xs, n] = Array.from(a);\n return isDigit(head(w)) ? (\n Tuple(xs, parseInt(w, 10))\n ) : Tuple(\n [Tuple(toUpper(w), n)].concat(xs),\n 0\n );\n },\n Tuple([], 0),\n words(s)\n ));\n\n // TEST -----------------------------------------------\n const main = () => {\n\n // table :: [(String, Int)]\n const table = cmdsFromString(\n `add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1\n Schange Cinsert 2 Clast 3 compress 4 copy 2 count 3 Coverlay 3\n cursor 3 delete 3 Cdelete 2 down 1 duplicate 3 xEdit 1 expand 3\n extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2\n forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1\n split 2 spltJOIN load locate 1 Clocate 2 lowerCase 3 upperCase 3\n Lprefix 2 macro merge 2 modify 3 move 2 msg next 1 overlay 1\n parse preserve 4 purge 3 put putD query 1 quit read recover 3\n refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4\n rgtLEFT right 2 left 2 save set shift 2 si sort sos stack 3\n status 4 top transfer 3 type 1 up 1`\n );\n\n return fTable(\n 'Abbreviation tests:\\n',\n s => \"'\" + s + \"'\",\n s => \"\\n\\t'\" + s + \"'\",\n withExpansions(table),\n [\n 'riG rePEAT copies put mo rest types fup. 6 poweRin',\n ''\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 // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (f, g) => x => f(g(x));\n\n // find :: (a -> Bool) -> [a] -> Maybe a\n const find = (p, xs) => {\n for (let i = 0, lng = xs.length; i < lng; i++) {\n if (p(xs[i])) return Just(xs[i]);\n }\n return Nothing();\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 // 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 // foldr :: (a -> b -> b) -> b -> [a] -> b\n const foldr = (f, a, xs) => xs.reduceRight(flip(f), a);\n\n // fst :: (a, b) -> a\n const fst = tpl => tpl[0];\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 = map(xShow, xs),\n w = maximum(map(length, ys)),\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 // head :: [a] -> a\n const head = xs => xs.length ? xs[0] : undefined;\n\n // isDigit :: Char -> Bool\n const isDigit = c => {\n const n = ord(c);\n return 48 <= n && 57 >= n;\n };\n\n // isPrefixOf takes two lists or strings and returns\n // true iff the first is a prefix of the second.\n\n // isPrefixOf :: [a] -> [a] -> Bool\n // isPrefixOf :: String -> String -> Bool\n const isPrefixOf = (xs, ys) => {\n const go = (xs, ys) => {\n const intX = xs.length;\n return 0 < intX ? (\n ys.length >= intX ? xs[0] === ys[0] && go(\n xs.slice(1), ys.slice(1)\n ) : false\n ) : true;\n };\n return 'string' !== typeof xs ? (\n go(xs, ys)\n ) : ys.startsWith(xs);\n };\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 // 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 // maybe :: b -> (a -> b) -> Maybe a -> b\n const maybe = (v, f, m) =>\n m.Nothing ? v : f(m.Just);\n\n // ord :: Char -> Int\n const ord = c => c.codePointAt(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 // toUpper :: String -> String\n const toUpper = s => s.toLocaleUpperCase();\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 // words :: String -> [String]\n const words = s => s.split(/\\s+/);\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": "Abbreviations, simple", "language": "Python 3.6", "task": "The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an \neasy way to add flexibility when specifying or using commands, sub-commands, options, etc.\n\n\n\nFor this task, the following ''command table'' will be used:\n add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3\n compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate\n 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2\n forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load\n locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2\n msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3\n refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left\n 2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1\n\n\n\n\nNotes concerning the above ''command table'':\n::* it can be thought of as one long literal string (with blanks at end-of-lines)\n::* it may have superfluous blanks\n::* it may be in any case (lower/upper/mixed)\n::* the order of the words in the ''command table'' must be preserved as shown\n::* the user input(s) may be in any case (upper/lower/mixed)\n::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)\n::* a command is followed by an optional number, which indicates the minimum abbreviation\n::* A valid abbreviation is a word that has:\n:::* at least the minimum length of the word's minimum number in the ''command table''\n:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''\n:::* a length not longer than the word in the ''command table''\n::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTER 3'''\n::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTER 3'''\n::::* The '''3''' indicates that any abbreviation for '''ALTER''' must be at least three characters\n::::* Any word longer than five characters can't be an abbreviation for '''ALTER'''\n::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''overlay 1'''\n::* if there isn't a number after the command, then there isn't an abbreviation permitted\n\n\n\n;Task:\n::* The command table needn't be verified/validated.\n::* Write a function to validate if the user \"words\" (given as input) are valid (in the ''command table'').\n::* If the word is valid, then return the full uppercase version of that \"word\".\n::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).\n::* A blank input (or a null input) should return a null string.\n::* Show all output here.\n\n\n;An example test case to be used for this task:\nFor a user string of:\n riG rePEAT copies put mo rest types fup. 6 poweRin\nthe computer program should return the string:\n RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\n\n\n", "solution": "command_table_text = \"\"\"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3\n compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate\n 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2\n forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load\n locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2\n msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3\n refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left\n 2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1\"\"\"\n\nuser_words = \"riG rePEAT copies put mo rest types fup. 6 poweRin\"\n\n\ndef find_abbreviations_length(command_table_text):\n \"\"\" find the minimal abbreviation length for each word.\n a word that does not have minimum abbreviation length specified\n gets it's full lengths as the minimum.\n \"\"\"\n command_table = dict()\n input_iter = iter(command_table_text.split())\n\n word = None\n try:\n while True:\n if word is None:\n word = next(input_iter)\n abbr_len = next(input_iter, len(word))\n try:\n command_table[word] = int(abbr_len)\n word = None\n except ValueError:\n command_table[word] = len(word)\n word = abbr_len\n except StopIteration:\n pass\n return command_table\n\n\ndef find_abbreviations(command_table):\n \"\"\" for each command insert all possible abbreviations\"\"\"\n abbreviations = dict()\n for command, min_abbr_len in command_table.items():\n for l in range(min_abbr_len, len(command)+1):\n abbr = command[:l].lower()\n abbreviations[abbr] = command.upper()\n return abbreviations\n\n\ndef parse_user_string(user_string, abbreviations):\n user_words = [word.lower() for word in user_string.split()]\n commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n return \" \".join(commands)\n\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n"} -{"title": "Abbreviations, simple", "language": "Python 3.7", "task": "The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an \neasy way to add flexibility when specifying or using commands, sub-commands, options, etc.\n\n\n\nFor this task, the following ''command table'' will be used:\n add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3\n compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate\n 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2\n forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load\n locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2\n msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3\n refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left\n 2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1\n\n\n\n\nNotes concerning the above ''command table'':\n::* it can be thought of as one long literal string (with blanks at end-of-lines)\n::* it may have superfluous blanks\n::* it may be in any case (lower/upper/mixed)\n::* the order of the words in the ''command table'' must be preserved as shown\n::* the user input(s) may be in any case (upper/lower/mixed)\n::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)\n::* a command is followed by an optional number, which indicates the minimum abbreviation\n::* A valid abbreviation is a word that has:\n:::* at least the minimum length of the word's minimum number in the ''command table''\n:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''\n:::* a length not longer than the word in the ''command table''\n::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTER 3'''\n::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTER 3'''\n::::* The '''3''' indicates that any abbreviation for '''ALTER''' must be at least three characters\n::::* Any word longer than five characters can't be an abbreviation for '''ALTER'''\n::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''overlay 1'''\n::* if there isn't a number after the command, then there isn't an abbreviation permitted\n\n\n\n;Task:\n::* The command table needn't be verified/validated.\n::* Write a function to validate if the user \"words\" (given as input) are valid (in the ''command table'').\n::* If the word is valid, then return the full uppercase version of that \"word\".\n::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).\n::* A blank input (or a null input) should return a null string.\n::* Show all output here.\n\n\n;An example test case to be used for this task:\nFor a user string of:\n riG rePEAT copies put mo rest types fup. 6 poweRin\nthe computer program should return the string:\n RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\n\n\n", "solution": "'''Simple abbreviations'''\n\nfrom functools import reduce\nimport re\n\n\n# withExpansions :: [(String, Int)] -> String -> String\ndef withExpansions(table):\n '''A string in which all words are either\n expanded (if they match abbreviations in\n a supplied table), or replaced with an\n '*error*' string.\n '''\n return lambda s: unwords(map(\n expanded(table), words(s)\n ))\n\n\n# expanded :: [(String, Int)] -> String -> String\ndef expanded(table):\n '''An abbreviation (or error string) for\n a given word, based on a table of full\n strings and minimum abbreviation lengths.\n '''\n def expansion(k):\n u = k.upper()\n lng = len(k)\n\n def p(wn):\n w, n = wn\n return w.startswith(u) and lng >= n\n return find(p)(table) if k else Just(('', 0))\n\n return lambda s: maybe('*error*')(fst)(expansion(s))\n\n\n# cmdsFromString :: String -> [(String, Int)]\ndef cmdsFromString(s):\n '''A simple rule-base consisting of a\n list of tuples [(\n upper case expansion string,\n minimum character count of abbreviation\n )],\n obtained by a parse of single input string.\n '''\n def go(a, x):\n xs, n = a\n return (xs, int(x)) if x.isdigit() else (\n ([(x.upper(), n)] + xs, 0)\n )\n return fst(reduce(\n go,\n reversed(re.split(r'\\s+', s)),\n ([], 0)\n ))\n\n\n# TEST -------------------------------------------------\ndef main():\n '''Tests of abbreviation expansions'''\n\n # table :: [(String, Int)]\n table = cmdsFromString(\n '''add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1\n Schange Cinsert 2 Clast 3 compress 4 copy 2 count 3 Coverlay 3\n cursor 3 delete 3 Cdelete 2 down 1 duplicate 3 xEdit 1 expand 3\n extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2\n forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1\n split 2 spltJOIN load locate 1 Clocate 2 lowerCase 3 upperCase 3\n Lprefix 2 macro merge 2 modify 3 move 2 msg next 1 overlay 1\n parse preserve 4 purge 3 put putD query 1 quit read recover 3\n refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4\n rgtLEFT right 2 left 2 save set shift 2 si sort sos stack 3\n status 4 top transfer 3 type 1 up 1'''\n )\n\n # tests :: [String]\n tests = [\n 'riG rePEAT copies put mo rest types fup. 6 poweRin',\n ''\n ]\n\n print(\n fTable(__doc__ + ':\\n')(lambda s: \"'\" + s + \"'\")(\n lambda s: \"\\n\\t'\" + s + \"'\"\n )(withExpansions(table))(tests)\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# 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# 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 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# fst :: (a, b) -> a\ndef fst(tpl):\n '''First member of a pair.'''\n return tpl[0]\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 ->\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# 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 return lambda f: lambda m: v if m.get('Nothing') else (\n f(m.get('Just'))\n )\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\n# words :: String -> [String]\ndef words(s):\n '''A list of words delimited by characters\n representing white space.'''\n return re.split(r'\\s+', s)\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} -{"title": "Abelian sandpile model", "language": "C", "task": "{{wikipedia|Abelian sandpile model}}\nImplement the '''Abelian sandpile model''' also known as '''Bak-Tang-Wiesenfeld model'''. Its history, mathematical definition and properties can be found under its wikipedia article.\n\nThe task requires the creation of a 2D grid of arbitrary size on which \"piles of sand\" can be placed. Any \"pile\" that has 4 or more sand particles on it ''collapses'', resulting in '''four particles being subtracted from the pile''' and '''distributed among its neighbors.'''\n\nIt is recommended to display the output in some kind of image format, as terminal emulators are usually too small to display images larger than a few dozen characters tall. As an example of how to accomplish this, see the Bitmap/Write a PPM file task.\nExamples up to 2^30, wow!\njavascript running on web\n'''Examples:'''\n\n\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 1 0 0\n0 0 4 0 0 -> 0 1 0 1 0\n0 0 0 0 0 0 0 1 0 0\n0 0 0 0 0 0 0 0 0 0\n\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 1 0 0\n0 0 6 0 0 -> 0 1 2 1 0\n0 0 0 0 0 0 0 1 0 0\n0 0 0 0 0 0 0 0 0 0\n\n0 0 0 0 0 0 0 1 0 0\n0 0 0 0 0 0 2 1 2 0\n0 0 16 0 0 -> 1 1 0 1 1\n0 0 0 0 0 0 2 1 2 0\n0 0 0 0 0 0 0 1 0 0\n\n", "solution": "#include\n#include\n#include\n\nint main(int argc, char** argv)\n{\n\tint i,j,sandPileEdge, centerPileHeight, processAgain = 1,top,down,left,right;\t\n\tint** sandPile;\n\tchar* fileName;\n\tstatic unsigned char colour[3];\n\n\tif(argc!=3){\n\t\tprintf(\"Usage: %s
\",argv[0]);\n\t\treturn 0;\n\t}\n\n\tsandPileEdge = atoi(argv[1]);\n\tcenterPileHeight = atoi(argv[2]);\n\n\tif(sandPileEdge<=0 || centerPileHeight<=0){\n\t\tprintf(\"Sand pile and center pile dimensions must be positive integers.\");\n\t\treturn 0;\n\t}\n\n\tsandPile = (int**)malloc(sandPileEdge * sizeof(int*));\n\n\tfor(i=0;i=4){\t\t\t\t\n\t\t\t\t\tif(i-1>=0){\n\t\t\t\t\t\ttop = 1;\n\t\t\t\t\t\tsandPile[i-1][j]+=1;\n\t\t\t\t\t\tif(sandPile[i-1][j]>=4)\n\t\t\t\t\t\t\tprocessAgain = 1;\n\t\t\t\t\t}\n\t\t\t\t\tif(i+1=4)\n\t\t\t\t\t\t\tprocessAgain = 1;\n\t\t\t\t\t}\n\t\t\t\t\tif(j-1>=0){\n\t\t\t\t\t\tleft = 1;\n\t\t\t\t\t\tsandPile[i][j-1]+=1;\n\t\t\t\t\t\tif(sandPile[i][j-1]>=4)\n\t\t\t\t\t\t\tprocessAgain = 1;\n\t\t\t\t\t}\n\t\t\t\t\tif(j+1=4)\n\t\t\t\t\t\t\tprocessAgain = 1;\n\t\t\t\t\t}\n\t\t\t\tsandPile[i][j] -= (top + down + left + right);\n\t\t\t\tif(sandPile[i][j]>=4)\n\t\t\t\t\tprocessAgain = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprintf(\"Final sand pile : \\n\\n\");\n\n\tfor(i=0;i 0 1 0 1 0\n0 0 0 0 0 0 0 1 0 0\n0 0 0 0 0 0 0 0 0 0\n\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 1 0 0\n0 0 6 0 0 -> 0 1 2 1 0\n0 0 0 0 0 0 0 1 0 0\n0 0 0 0 0 0 0 0 0 0\n\n0 0 0 0 0 0 0 1 0 0\n0 0 0 0 0 0 2 1 2 0\n0 0 16 0 0 -> 1 1 0 1 1\n0 0 0 0 0 0 2 1 2 0\n0 0 0 0 0 0 0 1 0 0\n\n", "solution": "import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef iterate(grid):\n changed = False\n for ii, arr in enumerate(grid):\n for jj, val in enumerate(arr):\n if val > 3:\n grid[ii, jj] -= 4\n if ii > 0:\n grid[ii - 1, jj] += 1\n if ii < len(grid)-1:\n grid[ii + 1, jj] += 1\n if jj > 0:\n grid[ii, jj - 1] += 1\n if jj < len(grid)-1:\n grid[ii, jj + 1] += 1\n changed = True\n return grid, changed\n\n\ndef simulate(grid):\n while True:\n grid, changed = iterate(grid)\n if not changed:\n return grid\n\n\nif __name__ == '__main__':\n start_grid = np.zeros((10, 10))\n start_grid[4:5, 4:5] = 64\n final_grid = simulate(start_grid.copy())\n plt.figure()\n plt.gray()\n plt.imshow(start_grid)\n plt.figure()\n plt.gray()\n plt.imshow(final_grid)"} -{"title": "Abelian sandpile model/Identity", "language": "C++", "task": "Our sandpiles are based on a 3 by 3 rectangular grid giving nine areas that \ncontain a number from 0 to 3 inclusive. (The numbers are said to represent \ngrains of sand in each area of the sandpile).\n\nE.g. s1 =\n \n 1 2 0\n 2 1 1\n 0 1 3\n\n\nand s2 =\n\n 2 1 3\n 1 0 1\n 0 1 0\n \n\nAddition on sandpiles is done by adding numbers in corresponding grid areas,\nso for the above:\n\n 1 2 0 2 1 3 3 3 3\n s1 + s2 = 2 1 1 + 1 0 1 = 3 1 2\n 0 1 3 0 1 0 0 2 3\n\n\nIf the addition would result in more than 3 \"grains of sand\" in any area then \nthose areas cause the whole sandpile to become \"unstable\" and the sandpile \nareas are \"toppled\" in an \"avalanche\" until the \"stable\" result is obtained.\n\nAny unstable area (with a number >= 4), is \"toppled\" by loosing one grain of \nsand to each of its four horizontal or vertical neighbours. Grains are lost \nat the edge of the grid, but otherwise increase the number in neighbouring \ncells by one, whilst decreasing the count in the toppled cell by four in each \ntoppling.\n\nA toppling may give an adjacent area more than four grains of sand leading to\na chain of topplings called an \"avalanche\".\nE.g.\n \n 4 3 3 0 4 3 1 0 4 1 1 0 2 1 0\n 3 1 2 ==> 4 1 2 ==> 4 2 2 ==> 4 2 3 ==> 0 3 3\n 0 2 3 0 2 3 0 2 3 0 2 3 1 2 3\n\n\nThe final result is the stable sandpile on the right. \n\n'''Note:''' The order in which cells are toppled does not affect the final result.\n\n;Task:\n* Create a class or datastructure and functions to represent and operate on sandpiles. \n* Confirm the result of the avalanche of topplings shown above\n* Confirm that s1 + s2 == s2 + s1 # Show the stable results\n* If s3 is the sandpile with number 3 in every grid area, and s3_id is the following sandpile:\n\n 2 1 2 \n 1 0 1 \n 2 1 2\n\n\n* Show that s3 + s3_id == s3\n* Show that s3_id + s3_id == s3_id\n\n\nShow confirming output here, with your examples.\n\n\n;References:\n* https://www.youtube.com/watch?v=1MtEUErz7Gg\n* https://en.wikipedia.org/wiki/Abelian_sandpile_model\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nconstexpr size_t sp_rows = 3;\nconstexpr size_t sp_columns = 3;\nconstexpr size_t sp_cells = sp_rows * sp_columns;\nconstexpr int sp_limit = 4;\n\nclass abelian_sandpile {\n friend std::ostream& operator<<(std::ostream&, const abelian_sandpile&);\n\npublic:\n abelian_sandpile();\n explicit abelian_sandpile(std::initializer_list init);\n void stabilize();\n bool is_stable() const;\n void topple();\n abelian_sandpile& operator+=(const abelian_sandpile&);\n bool operator==(const abelian_sandpile&);\n\nprivate:\n int& cell_value(size_t row, size_t column) {\n return cells_[cell_index(row, column)];\n }\n static size_t cell_index(size_t row, size_t column) {\n return row * sp_columns + column;\n }\n static size_t row_index(size_t cell_index) {\n return cell_index/sp_columns;\n }\n static size_t column_index(size_t cell_index) {\n return cell_index % sp_columns;\n }\n\n std::array cells_;\n};\n\nabelian_sandpile::abelian_sandpile() {\n cells_.fill(0);\n}\n\nabelian_sandpile::abelian_sandpile(std::initializer_list init) {\n assert(init.size() == sp_cells);\n std::copy(init.begin(), init.end(), cells_.begin());\n}\n\nabelian_sandpile& abelian_sandpile::operator+=(const abelian_sandpile& other) {\n for (size_t i = 0; i < sp_cells; ++i)\n cells_[i] += other.cells_[i];\n stabilize();\n return *this;\n}\n\nbool abelian_sandpile::operator==(const abelian_sandpile& other) {\n return cells_ == other.cells_;\n}\n\nbool abelian_sandpile::is_stable() const {\n return std::none_of(cells_.begin(), cells_.end(),\n [](int a) { return a >= sp_limit; });\n}\n\nvoid abelian_sandpile::topple() {\n for (size_t i = 0; i < sp_cells; ++i) {\n if (cells_[i] >= sp_limit) {\n cells_[i] -= sp_limit;\n size_t row = row_index(i);\n size_t column = column_index(i);\n if (row > 0)\n ++cell_value(row - 1, column);\n if (row + 1 < sp_rows)\n ++cell_value(row + 1, column);\n if (column > 0)\n ++cell_value(row, column - 1);\n if (column + 1 < sp_columns)\n ++cell_value(row, column + 1);\n break;\n }\n }\n}\n\nvoid abelian_sandpile::stabilize() {\n while (!is_stable())\n topple();\n}\n\nabelian_sandpile operator+(const abelian_sandpile& a, const abelian_sandpile& b) {\n abelian_sandpile c(a);\n c += b;\n return c;\n}\n\nstd::ostream& operator<<(std::ostream& out, const abelian_sandpile& as) {\n for (size_t i = 0; i < sp_cells; ++i) {\n if (i > 0)\n out << (as.column_index(i) == 0 ? '\\n' : ' ');\n out << as.cells_[i];\n }\n return out << '\\n';\n}\n\nint main() {\n std::cout << std::boolalpha;\n\n std::cout << \"Avalanche:\\n\";\n abelian_sandpile sp{4,3,3, 3,1,2, 0,2,3};\n while (!sp.is_stable()) {\n std::cout << sp << \"stable? \" << sp.is_stable() << \"\\n\\n\";\n sp.topple();\n }\n std::cout << sp << \"stable? \" << sp.is_stable() << \"\\n\\n\";\n\n std::cout << \"Commutativity:\\n\";\n abelian_sandpile s1{1,2,0, 2,1,1, 0,1,3};\n abelian_sandpile s2{2,1,3, 1,0,1, 0,1,0};\n abelian_sandpile sum1(s1 + s2);\n abelian_sandpile sum2(s2 + s1);\n std::cout << \"s1 + s2 equals s2 + s1? \" << (sum1 == sum2) << \"\\n\\n\";\n std::cout << \"s1 + s2 = \\n\" << sum1;\n std::cout << \"\\ns2 + s1 = \\n\" << sum2;\n std::cout << '\\n';\n\n std::cout << \"Identity:\\n\";\n abelian_sandpile s3{3,3,3, 3,3,3, 3,3,3};\n abelian_sandpile s3_id{2,1,2, 1,0,1, 2,1,2};\n abelian_sandpile sum3(s3 + s3_id);\n abelian_sandpile sum4(s3_id + s3_id);\n std::cout << \"s3 + s3_id equals s3? \" << (sum3 == s3) << '\\n';\n std::cout << \"s3_id + s3_id equals s3_id? \" << (sum4 == s3_id) << \"\\n\\n\";\n std::cout << \"s3 + s3_id = \\n\" << sum3;\n std::cout << \"\\ns3_id + s3_id = \\n\" << sum4;\n\n return 0;\n}"} -{"title": "Abelian sandpile model/Identity", "language": "Python", "task": "Our sandpiles are based on a 3 by 3 rectangular grid giving nine areas that \ncontain a number from 0 to 3 inclusive. (The numbers are said to represent \ngrains of sand in each area of the sandpile).\n\nE.g. s1 =\n \n 1 2 0\n 2 1 1\n 0 1 3\n\n\nand s2 =\n\n 2 1 3\n 1 0 1\n 0 1 0\n \n\nAddition on sandpiles is done by adding numbers in corresponding grid areas,\nso for the above:\n\n 1 2 0 2 1 3 3 3 3\n s1 + s2 = 2 1 1 + 1 0 1 = 3 1 2\n 0 1 3 0 1 0 0 2 3\n\n\nIf the addition would result in more than 3 \"grains of sand\" in any area then \nthose areas cause the whole sandpile to become \"unstable\" and the sandpile \nareas are \"toppled\" in an \"avalanche\" until the \"stable\" result is obtained.\n\nAny unstable area (with a number >= 4), is \"toppled\" by loosing one grain of \nsand to each of its four horizontal or vertical neighbours. Grains are lost \nat the edge of the grid, but otherwise increase the number in neighbouring \ncells by one, whilst decreasing the count in the toppled cell by four in each \ntoppling.\n\nA toppling may give an adjacent area more than four grains of sand leading to\na chain of topplings called an \"avalanche\".\nE.g.\n \n 4 3 3 0 4 3 1 0 4 1 1 0 2 1 0\n 3 1 2 ==> 4 1 2 ==> 4 2 2 ==> 4 2 3 ==> 0 3 3\n 0 2 3 0 2 3 0 2 3 0 2 3 1 2 3\n\n\nThe final result is the stable sandpile on the right. \n\n'''Note:''' The order in which cells are toppled does not affect the final result.\n\n;Task:\n* Create a class or datastructure and functions to represent and operate on sandpiles. \n* Confirm the result of the avalanche of topplings shown above\n* Confirm that s1 + s2 == s2 + s1 # Show the stable results\n* If s3 is the sandpile with number 3 in every grid area, and s3_id is the following sandpile:\n\n 2 1 2 \n 1 0 1 \n 2 1 2\n\n\n* Show that s3 + s3_id == s3\n* Show that s3_id + s3_id == s3_id\n\n\nShow confirming output here, with your examples.\n\n\n;References:\n* https://www.youtube.com/watch?v=1MtEUErz7Gg\n* https://en.wikipedia.org/wiki/Abelian_sandpile_model\n\n", "solution": "'''Abelian Sandpile \u2013 Identity'''\n\nfrom operator import add, eq\n\n\n# -------------------------- TEST --------------------------\n# main :: IO ()\ndef main():\n '''Tests of cascades and additions'''\n s0 = [[4, 3, 3], [3, 1, 2], [0, 2, 3]]\n s1 = [[1, 2, 0], [2, 1, 1], [0, 1, 3]]\n s2 = [[2, 1, 3], [1, 0, 1], [0, 1, 0]]\n s3 = [[3, 3, 3], [3, 3, 3], [3, 3, 3]]\n s3_id = [[2, 1, 2], [1, 0, 1], [2, 1, 2]]\n\n series = list(cascadeSeries(s0))\n for expr in [\n 'Cascade:',\n showSandPiles(\n [(' ', series[0])] + [\n (':', xs) for xs in series[1:]\n ]\n ),\n '',\n f's1 + s2 == s2 + s1 -> {addSand(s1)(s2) == addSand(s2)(s1)}',\n showSandPiles([\n (' ', s1),\n ('+', s2),\n ('=', addSand(s1)(s2))\n ]),\n '',\n showSandPiles([\n (' ', s2),\n ('+', s1),\n ('=', addSand(s2)(s1))\n ]),\n '',\n f's3 + s3_id == s3 -> {addSand(s3)(s3_id) == s3}',\n showSandPiles([\n (' ', s3),\n ('+', s3_id),\n ('=', addSand(s3)(s3_id))\n ]),\n '',\n f's3_id + s3_id == s3_id -> {addSand(s3_id)(s3_id) == s3_id}',\n showSandPiles([\n (' ', s3_id),\n ('+', s3_id),\n ('=', addSand(s3_id)(s3_id))\n ]),\n\n ]:\n print(expr)\n\n\n# ----------------------- SANDPILES ------------------------\n\n# addSand :: [[Int]] -> [[Int]] -> [[Int]]\ndef addSand(xs):\n '''The stabilised sum of two sandpiles.\n '''\n def go(ys):\n return cascadeSeries(\n chunksOf(len(xs))(\n map(\n add,\n concat(xs),\n concat(ys)\n )\n )\n )[-1]\n return go\n\n\n# cascadeSeries :: [[Int]] -> [[[Int]]]\ndef cascadeSeries(rows):\n '''The sequence of states from a given\n sand pile to a stable condition.\n '''\n xs = list(rows)\n w = len(xs)\n return [\n list(chunksOf(w)(x)) for x\n in convergence(eq)(\n iterate(nextState(w))(\n concat(xs)\n )\n )\n ]\n\n\n# convergence :: (a -> a -> Bool) -> [a] -> [a]\ndef convergence(p):\n '''All items of xs to the point where the binary\n p returns True over two successive values.\n '''\n def go(xs):\n def conv(prev, ys):\n y = next(ys)\n return [prev] + (\n [] if p(prev, y) else conv(y, ys)\n )\n return conv(next(xs), xs)\n return go\n\n\n# nextState Int -> Int -> [Int] -> [Int]\ndef nextState(w):\n '''The next state of a (potentially unstable)\n flattened sand-pile matrix of row length w.\n '''\n def go(xs):\n def tumble(i):\n neighbours = indexNeighbours(w)(i)\n return [\n 1 + k if j in neighbours else (\n k - (1 + w) if j == i else k\n ) for (j, k) in enumerate(xs)\n ]\n return maybe(xs)(tumble)(\n findIndex(lambda x: w < x)(xs)\n )\n return go\n\n\n# indexNeighbours :: Int -> Int -> [Int]\ndef indexNeighbours(w):\n '''Indices vertically and horizontally adjoining the\n given index in a flattened matrix of dimension w.\n '''\n def go(i):\n lastCol = w - 1\n iSqr = (w * w)\n col = i % w\n return [\n j for j in [i - w, i + w]\n if -1 < j < iSqr\n ] + ([i - 1] if 0 != col else []) + (\n [1 + i] if lastCol != col else []\n )\n return go\n\n\n# ------------------------ DISPLAY -------------------------\n\n# showSandPiles :: [(String, [[Int]])] -> String\ndef showSandPiles(pairs):\n '''Indented multi-line representation\n of a sequence of matrices, delimited\n by preceding operators or indents.\n '''\n return '\\n'.join([\n ' '.join([' '.join(map(str, seq)) for seq in tpl])\n for tpl in zip(*[\n zip(\n *[list(str(pfx).center(len(rows)))]\n + list(zip(*rows))\n )\n for (pfx, rows) in pairs\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 divible, the final list will be shorter than n.\n '''\n def go(xs):\n ys = list(xs)\n return (\n ys[i:n + i] for i in range(0, len(ys), n)\n ) if 0 < n else None\n return go\n\n\n# concat :: [[a]] -> [a]\ndef concat(xs):\n '''The concatenation of all\n elements in a list.\n '''\n return [x for lst in xs for x in lst]\n\n\n# findIndex :: (a -> Bool) -> [a] -> Maybe Int\ndef findIndex(p):\n '''Just the first index at which an\n element in xs matches p,\n or Nothing if no elements match.\n '''\n def go(xs):\n return next(\n (i for (i, x) in enumerate(xs) if p(x)),\n None\n )\n return go\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# maybe :: b -> (a -> b) -> Maybe a -> b\ndef maybe(v):\n '''Either the default value v, if x is None,\n or the application of f to x.\n '''\n def go(f):\n def g(x):\n return v if None is x else f(x)\n return g\n return go\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} -{"title": "Abundant odd numbers", "language": "C", "task": "An Abundant number is a number '''n''' for which the ''sum of divisors'' '''s(n) > 2n''',\nor, equivalently, the ''sum of proper divisors'' (or aliquot sum) '''s(n) > n'''.\n\n\n;E.G.:\n'''12''' is abundant, it has the proper divisors '''1,2,3,4 & 6''' which sum to '''16''' ( > '''12''' or '''n'''); \n or alternately, has the sigma sum of '''1,2,3,4,6 & 12''' which sum to '''28''' ( > '''24''' or '''2n''').\n\n\nAbundant numbers are common, though '''even''' abundant numbers seem to be much more common than '''odd''' abundant numbers. \n\nTo make things more interesting, this task is specifically about finding ''odd abundant numbers''.\n\n\n;Task\n*Find and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum.\n*Find and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum.\n*Find and display here: the first abundant odd number greater than one billion (109) and either its proper divisor sum or sigma sum.\n\n\n;References:\n:* OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n)\n:* American Journal of Mathematics, Vol. 35, No. 4 (Oct., 1913), pp. 413-422 - Finiteness of the Odd Perfect and Primitive Abundant Numbers with n Distinct Prime Factors (LE Dickson)\n\n", "solution": "#include \n#include \n\n// The following function is for odd numbers ONLY\n// Please use \"for (unsigned i = 2, j; i*i <= n; i ++)\" for even and odd numbers\nunsigned sum_proper_divisors(const unsigned n) {\n unsigned sum = 1;\n for (unsigned i = 3, j; i < sqrt(n)+1; i += 2) if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);\n return sum;\n}\n\nint main(int argc, char const *argv[]) {\n unsigned n, c;\n for (n = 1, c = 0; c < 25; n += 2) if (n < sum_proper_divisors(n)) printf(\"%u: %u\\n\", ++c, n);\n\n for ( ; c < 1000; n += 2) if (n < sum_proper_divisors(n)) c ++;\n printf(\"\\nThe one thousandth abundant odd number is: %u\\n\", n);\n\n for (n = 1000000001 ;; n += 2) if (n < sum_proper_divisors(n)) break;\n printf(\"The first abundant odd number above one billion is: %u\\n\", n);\n \n return 0;\n}"} -{"title": "Abundant odd numbers", "language": "C++ from Go", "task": "An Abundant number is a number '''n''' for which the ''sum of divisors'' '''s(n) > 2n''',\nor, equivalently, the ''sum of proper divisors'' (or aliquot sum) '''s(n) > n'''.\n\n\n;E.G.:\n'''12''' is abundant, it has the proper divisors '''1,2,3,4 & 6''' which sum to '''16''' ( > '''12''' or '''n'''); \n or alternately, has the sigma sum of '''1,2,3,4,6 & 12''' which sum to '''28''' ( > '''24''' or '''2n''').\n\n\nAbundant numbers are common, though '''even''' abundant numbers seem to be much more common than '''odd''' abundant numbers. \n\nTo make things more interesting, this task is specifically about finding ''odd abundant numbers''.\n\n\n;Task\n*Find and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum.\n*Find and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum.\n*Find and display here: the first abundant odd number greater than one billion (109) and either its proper divisor sum or sigma sum.\n\n\n;References:\n:* OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n)\n:* American Journal of Mathematics, Vol. 35, No. 4 (Oct., 1913), pp. 413-422 - Finiteness of the Odd Perfect and Primitive Abundant Numbers with n Distinct Prime Factors (LE Dickson)\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nstd::vector divisors(int n) {\n std::vector divs{ 1 };\n std::vector divs2;\n\n for (int i = 2; i*i <= n; i++) {\n if (n%i == 0) {\n int j = n / i;\n divs.push_back(i);\n if (i != j) {\n divs2.push_back(j);\n }\n }\n }\n std::copy(divs2.crbegin(), divs2.crend(), std::back_inserter(divs));\n\n return divs;\n}\n\nint sum(const std::vector& divs) {\n return std::accumulate(divs.cbegin(), divs.cend(), 0);\n}\n\nstd::string sumStr(const std::vector& divs) {\n auto it = divs.cbegin();\n auto end = divs.cend();\n std::stringstream ss;\n\n if (it != end) {\n ss << *it;\n it = std::next(it);\n }\n while (it != end) {\n ss << \" + \" << *it;\n it = std::next(it);\n }\n\n return ss.str();\n}\n\nint abundantOdd(int searchFrom, int countFrom, int countTo, bool printOne) {\n int count = countFrom;\n int n = searchFrom;\n for (; count < countTo; n += 2) {\n auto divs = divisors(n);\n int tot = sum(divs);\n if (tot > n) {\n count++;\n if (printOne && count < countTo) {\n continue;\n }\n auto s = sumStr(divs);\n if (printOne) {\n printf(\"%d < %s = %d\\n\", n, s.c_str(), tot);\n } else {\n printf(\"%2d. %5d < %s = %d\\n\", count, n, s.c_str(), tot);\n }\n }\n }\n return n;\n}\n\nint main() {\n using namespace std;\n\n const int max = 25;\n cout << \"The first \" << max << \" abundant odd numbers are:\\n\";\n int n = abundantOdd(1, 0, 25, false);\n\n cout << \"\\nThe one thousandth abundant odd number is:\\n\";\n abundantOdd(n, 25, 1000, true);\n\n cout << \"\\nThe first abundant odd number above one billion is:\\n\";\n abundantOdd(1e9 + 1, 0, 1, true);\n\n return 0;\n}"} -{"title": "Abundant odd numbers", "language": "JavaScript from Python", "task": "An Abundant number is a number '''n''' for which the ''sum of divisors'' '''s(n) > 2n''',\nor, equivalently, the ''sum of proper divisors'' (or aliquot sum) '''s(n) > n'''.\n\n\n;E.G.:\n'''12''' is abundant, it has the proper divisors '''1,2,3,4 & 6''' which sum to '''16''' ( > '''12''' or '''n'''); \n or alternately, has the sigma sum of '''1,2,3,4,6 & 12''' which sum to '''28''' ( > '''24''' or '''2n''').\n\n\nAbundant numbers are common, though '''even''' abundant numbers seem to be much more common than '''odd''' abundant numbers. \n\nTo make things more interesting, this task is specifically about finding ''odd abundant numbers''.\n\n\n;Task\n*Find and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum.\n*Find and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum.\n*Find and display here: the first abundant odd number greater than one billion (109) and either its proper divisor sum or sigma sum.\n\n\n;References:\n:* OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n)\n:* American Journal of Mathematics, Vol. 35, No. 4 (Oct., 1913), pp. 413-422 - Finiteness of the Odd Perfect and Primitive Abundant Numbers with n Distinct Prime Factors (LE Dickson)\n\n", "solution": "(() => {\n 'use strict';\n const main = () => {\n\n // abundantTuple :: Int -> [(Int, Int)]\n const abundantTuple = n => {\n // Either a list containing the tuple of N\n // and its divisor sum (if n is abundant),\n // or otherwise an empty list.\n const x = divisorSum(n);\n return n < x ? ([\n Tuple(n)(x)\n ]) : [];\n };\n\n // divisorSum :: Int -> Int\n const divisorSum = n => {\n // Sum of the divisors of n.\n const\n floatRoot = Math.sqrt(n),\n intRoot = Math.floor(floatRoot),\n lows = filter(x => 0 === n % x)(\n enumFromTo(1)(intRoot)\n );\n return sum(lows.concat(map(quot(n))(\n intRoot === floatRoot ? (\n lows.slice(1, -1)\n ) : lows.slice(1)\n )));\n };\n\n // TEST ---------------------------------------\n console.log(\n 'First 25 abundant odd numbers, with their divisor sums:'\n )\n console.log(unlines(map(showTuple)(\n take(25)(\n concatMapGen(abundantTuple)(\n enumFromThen(1)(3)\n )\n )\n )));\n console.log(\n '\\n\\n1000th abundant odd number, with its divisor sum:'\n )\n console.log(showTuple(\n take(1)(drop(999)(\n concatMapGen(abundantTuple)(\n enumFromThen(1)(3)\n )\n ))[0]\n ))\n console.log(\n '\\n\\nFirst abundant odd number above 10^9, with divisor sum:'\n )\n const billion = Math.pow(10, 9);\n console.log(showTuple(\n take(1)(\n concatMapGen(abundantTuple)(\n enumFromThen(1 + billion)(3 + billion)\n )\n )[0]\n ))\n };\n\n\n // GENERAL REUSABLE 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 // concatMapGen :: (a -> [b]) -> Gen [a] -> Gen [b]\n const concatMapGen = f =>\n function*(xs) {\n let\n x = xs.next(),\n v = undefined;\n while (!x.done) {\n v = f(x.value);\n if (0 < v.length) {\n yield v[0];\n }\n x = xs.next();\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 // dropAround :: (a -> Bool) -> [a] -> [a]\n // dropAround :: (Char -> Bool) -> String -> String\n const dropAround = p => xs => dropWhile(p)(\n dropWhileEnd(p)(xs)\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 // dropWhileEnd :: (a -> Bool) -> [a] -> [a]\n // dropWhileEnd :: (Char -> Bool) -> String -> String\n const dropWhileEnd = p => xs => {\n let i = xs.length;\n while (i-- && p(xs[i])) {}\n return xs.slice(0, i + 1);\n };\n\n // enumFromThen :: Int -> Int -> Gen [Int]\n const enumFromThen = x =>\n // A non-finite stream of integers,\n // starting with x and y, and continuing\n // with the same interval.\n function*(y) {\n const d = y - x;\n let v = y + d;\n yield x;\n yield y;\n while (true) {\n yield v;\n v = d + v;\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 // filter :: (a -> Bool) -> [a] -> [a]\n const filter = f => xs => xs.filter(f);\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 // quot :: Int -> Int -> Int\n const quot = n => m => Math.floor(n / m);\n\n // show :: a -> String\n const show = JSON.stringify;\n\n // showTuple :: Tuple -> String\n const showTuple = tpl =>\n '(' + enumFromTo(0)(tpl.length - 1)\n .map(x => unQuoted(show(tpl[x])))\n .join(',') + ')';\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 // 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 // unQuoted :: String -> String\n const unQuoted = s =>\n dropAround(x => 34 === x.codePointAt(0))(\n s\n );\n\n // MAIN ---\n return main();\n})();"} -{"title": "Abundant odd numbers", "language": "Python from Visual Basic .NET", "task": "An Abundant number is a number '''n''' for which the ''sum of divisors'' '''s(n) > 2n''',\nor, equivalently, the ''sum of proper divisors'' (or aliquot sum) '''s(n) > n'''.\n\n\n;E.G.:\n'''12''' is abundant, it has the proper divisors '''1,2,3,4 & 6''' which sum to '''16''' ( > '''12''' or '''n'''); \n or alternately, has the sigma sum of '''1,2,3,4,6 & 12''' which sum to '''28''' ( > '''24''' or '''2n''').\n\n\nAbundant numbers are common, though '''even''' abundant numbers seem to be much more common than '''odd''' abundant numbers. \n\nTo make things more interesting, this task is specifically about finding ''odd abundant numbers''.\n\n\n;Task\n*Find and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum.\n*Find and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum.\n*Find and display here: the first abundant odd number greater than one billion (109) and either its proper divisor sum or sigma sum.\n\n\n;References:\n:* OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n)\n:* American Journal of Mathematics, Vol. 35, No. 4 (Oct., 1913), pp. 413-422 - Finiteness of the Odd Perfect and Primitive Abundant Numbers with n Distinct Prime Factors (LE Dickson)\n\n", "solution": "#!/usr/bin/python\n# Abundant odd numbers - Python\n\noddNumber = 1\naCount = 0\ndSum = 0\n \nfrom math import sqrt\n \ndef divisorSum(n):\n sum = 1\n i = int(sqrt(n)+1)\n \n for d in range (2, i):\n if n % d == 0:\n sum += d\n otherD = n // d\n if otherD != d:\n sum += otherD\n return sum\n \nprint (\"The first 25 abundant odd numbers:\")\nwhile aCount < 25:\n dSum = divisorSum(oddNumber )\n if dSum > oddNumber :\n aCount += 1\n print(\"{0:5} proper divisor sum: {1}\". format(oddNumber ,dSum ))\n oddNumber += 2\n \nwhile aCount < 1000:\n dSum = divisorSum(oddNumber )\n if dSum > oddNumber :\n aCount += 1\n oddNumber += 2\nprint (\"\\n1000th abundant odd number:\")\nprint (\" \",(oddNumber - 2),\" proper divisor sum: \",dSum)\n \noddNumber = 1000000001\nfound = False\nwhile not found :\n dSum = divisorSum(oddNumber )\n if dSum > oddNumber :\n found = True\n print (\"\\nFirst abundant odd number > 1 000 000 000:\")\n print (\" \",oddNumber,\" proper divisor sum: \",dSum)\n oddNumber += 2"} -{"title": "Accumulator factory", "language": "C", "task": "{{requires|Mutable State}}\n\nA problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).\n\n\n;Rules:\nThe detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text'').\n:Before you submit an example, make sure the function\n\n:# Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).Although these exact function and parameter names need not be used\n:# Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) ''(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)''\n:# Generates functions that return the sum of every number ever passed to them, not just the most recent. ''(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)''\n:# Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. ''(Follow your language's conventions here.)''\n:# Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. ''(No global variables or other such things.)''\n: E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'':\n:: x = foo(1); \nx(5); \nfoo(3);\nprint x(2.3);\n: It should print 8.3. ''(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)''\n\n\n;Task:\nCreate a function that implements the described rules. \n\n\nIt need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.\n\nWhere it is not possible to hold exactly to the constraints above, describe the deviations.\n\n", "solution": "#include \n//~ Take a number n and return a function that takes a number i\n#define ACCUMULATOR(name,n) __typeof__(n) name (__typeof__(n) i) { \\\n static __typeof__(n) _n=n; LOGIC; }\n//~ have it return n incremented by the accumulation of i\n#define LOGIC return _n+=i\nACCUMULATOR(x,1.0)\nACCUMULATOR(y,3)\nACCUMULATOR(z,'a')\n#undef LOGIC\nint main (void) {\n printf (\"%f\\n\", x(5)); /* 6.000000 */\n printf (\"%f\\n\", x(2.3)); /* 8.300000 */\n printf (\"%i\\n\", y(5.0)); /* 8 */\n printf (\"%i\\n\", y(3.3)); /* 11 */\n printf (\"%c\\n\", z(5)); /* f */\n return 0;\n}"} -{"title": "Accumulator factory", "language": "C++", "task": "{{requires|Mutable State}}\n\nA problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).\n\n\n;Rules:\nThe detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text'').\n:Before you submit an example, make sure the function\n\n:# Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).Although these exact function and parameter names need not be used\n:# Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) ''(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)''\n:# Generates functions that return the sum of every number ever passed to them, not just the most recent. ''(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)''\n:# Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. ''(Follow your language's conventions here.)''\n:# Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. ''(No global variables or other such things.)''\n: E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'':\n:: x = foo(1); \nx(5); \nfoo(3);\nprint x(2.3);\n: It should print 8.3. ''(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)''\n\n\n;Task:\nCreate a function that implements the described rules. \n\n\nIt need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.\n\nWhere it is not possible to hold exactly to the constraints above, describe the deviations.\n\n", "solution": "#include \n\nclass Acc\n{\npublic:\n Acc(int init)\n : _type(intType)\n , _intVal(init)\n {}\n\n Acc(float init)\n : _type(floatType)\n , _floatVal(init)\n {}\n\n int operator()(int x)\n {\n if( _type == intType )\n {\n _intVal += x;\n return _intVal;\n }\n else\n {\n _floatVal += x;\n return static_cast(_floatVal);\n }\n }\n\n float operator()(float x)\n {\n if( _type == intType )\n {\n _floatVal = _intVal + x;\n _type = floatType;\n return _floatVal;\n }\n else\n {\n _floatVal += x;\n return _floatVal;\n }\n }\nprivate:\n enum {floatType, intType} _type;\n float _floatVal;\n int _intVal;\n};\n\nint main()\n{\n Acc a(1);\n a(5);\n Acc(3);\n std::cout << a(2.3f);\n return 0;\n}"} -{"title": "Accumulator factory", "language": "C++11", "task": "{{requires|Mutable State}}\n\nA problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).\n\n\n;Rules:\nThe detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text'').\n:Before you submit an example, make sure the function\n\n:# Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).Although these exact function and parameter names need not be used\n:# Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) ''(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)''\n:# Generates functions that return the sum of every number ever passed to them, not just the most recent. ''(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)''\n:# Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. ''(Follow your language's conventions here.)''\n:# Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. ''(No global variables or other such things.)''\n: E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'':\n:: x = foo(1); \nx(5); \nfoo(3);\nprint x(2.3);\n: It should print 8.3. ''(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)''\n\n\n;Task:\nCreate a function that implements the described rules. \n\n\nIt need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.\n\nWhere it is not possible to hold exactly to the constraints above, describe the deviations.\n\n", "solution": "// still inside struct Accumulator_\n\t// various operator() implementations provide a de facto multimethod\n\tAccumulator_& operator()(int more)\n\t{\n\t\tif (auto i = CoerceInt(*val_))\n\t\t\tSet(+i + more);\n\t\telse if (auto d = CoerceDouble(*val_))\n\t\t\tSet(+d + more);\n\t\telse\n\t\t\tTHROW(\"Accumulate(int) failed\");\n\t\treturn *this;\n\t}\n\tAccumulator_& operator()(double more)\n\t{\n\t\tif (auto d = CoerceDouble(*val_))\n\t\t\tSet(+d + more);\n\t\telse\n\t\t\tTHROW(\"Accumulate(double) failed\");\n\t\treturn *this;\n\t}\n\tAccumulator_& operator()(const String_& more)\n\t{\n\t\tif (auto s = CoerceString(*val_))\n\t\t\tSet(+s + more);\n\t\telse\n\t\t\tTHROW(\"Accumulate(string) failed\");\n\t\treturn *this;\n\t}\n};\n"} -{"title": "Accumulator factory", "language": "JavaScript", "task": "{{requires|Mutable State}}\n\nA problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).\n\n\n;Rules:\nThe detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text'').\n:Before you submit an example, make sure the function\n\n:# Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).Although these exact function and parameter names need not be used\n:# Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) ''(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)''\n:# Generates functions that return the sum of every number ever passed to them, not just the most recent. ''(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)''\n:# Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. ''(Follow your language's conventions here.)''\n:# Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. ''(No global variables or other such things.)''\n: E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'':\n:: x = foo(1); \nx(5); \nfoo(3);\nprint x(2.3);\n: It should print 8.3. ''(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)''\n\n\n;Task:\nCreate a function that implements the described rules. \n\n\nIt need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.\n\nWhere it is not possible to hold exactly to the constraints above, describe the deviations.\n\n", "solution": "function accumulator(sum) {\n return function(n) {\n return sum += n;\n }\n}\nvar x = accumulator(1);\nx(5);\nconsole.log(accumulator(3).toString() + '
');\nconsole.log(x(2.3));"} -{"title": "Accumulator factory", "language": "Python 2.x/3.x", "task": "{{requires|Mutable State}}\n\nA problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).\n\n\n;Rules:\nThe detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text'').\n:Before you submit an example, make sure the function\n\n:# Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).Although these exact function and parameter names need not be used\n:# Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) ''(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)''\n:# Generates functions that return the sum of every number ever passed to them, not just the most recent. ''(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)''\n:# Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. ''(Follow your language's conventions here.)''\n:# Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. ''(No global variables or other such things.)''\n: E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'':\n:: x = foo(1); \nx(5); \nfoo(3);\nprint x(2.3);\n: It should print 8.3. ''(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)''\n\n\n;Task:\nCreate a function that implements the described rules. \n\n\nIt need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.\n\nWhere it is not possible to hold exactly to the constraints above, describe the deviations.\n\n", "solution": ">>> def accumulator(sum):\n def f(n):\n f.sum += n\n return f.sum\n f.sum = sum\n return f\n\n>>> x = accumulator(1)\n>>> x(5)\n6\n>>> x(2.3)\n8.3000000000000007\n>>> x = accumulator(1)\n>>> x(5)\n6\n>>> x(2.3)\n8.3000000000000007\n>>> x2 = accumulator(3)\n>>> x2(5)\n8\n>>> x2(3.3)\n11.300000000000001\n>>> x(0)\n8.3000000000000007\n>>> x2(0)\n11.300000000000001"} -{"title": "Accumulator factory", "language": "Python 3.x", "task": "{{requires|Mutable State}}\n\nA problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).\n\n\n;Rules:\nThe detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text'').\n:Before you submit an example, make sure the function\n\n:# Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).Although these exact function and parameter names need not be used\n:# Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) ''(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)''\n:# Generates functions that return the sum of every number ever passed to them, not just the most recent. ''(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)''\n:# Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. ''(Follow your language's conventions here.)''\n:# Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. ''(No global variables or other such things.)''\n: E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'':\n:: x = foo(1); \nx(5); \nfoo(3);\nprint x(2.3);\n: It should print 8.3. ''(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)''\n\n\n;Task:\nCreate a function that implements the described rules. \n\n\nIt need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.\n\nWhere it is not possible to hold exactly to the constraints above, describe the deviations.\n\n", "solution": "def accumulator(sum):\n def f(n):\n nonlocal sum\n sum += n\n return sum\n return f\n\nx = accumulator(1)\nx(5)\nprint(accumulator(3))\nprint(x(2.3))"} -{"title": "Accumulator factory", "language": "Python 2.5+", "task": "{{requires|Mutable State}}\n\nA problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).\n\n\n;Rules:\nThe detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text'').\n:Before you submit an example, make sure the function\n\n:# Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).Although these exact function and parameter names need not be used\n:# Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) ''(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)''\n:# Generates functions that return the sum of every number ever passed to them, not just the most recent. ''(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)''\n:# Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. ''(Follow your language's conventions here.)''\n:# Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. ''(No global variables or other such things.)''\n: E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'':\n:: x = foo(1); \nx(5); \nfoo(3);\nprint x(2.3);\n: It should print 8.3. ''(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)''\n\n\n;Task:\nCreate a function that implements the described rules. \n\n\nIt need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.\n\nWhere it is not possible to hold exactly to the constraints above, describe the deviations.\n\n", "solution": "def accumulator(sum):\n while True:\n sum += yield sum\n\nx = accumulator(1)\nx.send(None)\nx.send(5)\nprint(accumulator(3))\nprint(x.send(2.3))"} -{"title": "Achilles numbers", "language": "Python", "task": "{{Wikipedia|Achilles number}}\n\n\nAn '''Achilles number''' is a number that is powerful but imperfect. ''Named after Achilles, a hero of the Trojan war, who was also powerful but imperfect.''\n\n\nA positive integer '''n''' is a powerful number if, for every prime factor '''p''' of '''n''', '''p2''' is also a divisor.\n\nIn other words, every prime factor appears at least squared in the factorization.\n\nAll '''Achilles numbers''' are powerful. However, not all powerful numbers are '''Achilles numbers''': only those that cannot be represented as '''mk''', where '''m''' and '''k''' are positive integers greater than '''1'''.\n\n\nA '''''strong'' Achilles number''' is an '''Achilles number''' whose '''Euler totient ()''' is also an '''Achilles number'''.\n\n\n\n;E.G.\n\n'''108''' is a powerful number. Its prime factorization is '''22 x 33''', and thus its prime factors are '''2''' and '''3'''. Both '''22 = 4''' and '''32 = 9''' are divisors of '''108'''. However, '''108''' cannot be represented as '''mk''', where '''m''' and '''k''' are positive integers greater than '''1''', so '''108''' is an '''Achilles number'''.\n\n'''360''' is ''not'' an '''Achilles number''' because it is not powerful. One of its prime factors is '''5''' but '''360''' is not divisible by '''52 = 25'''.\n\nFinally, '''784''' is ''not'' an '''Achilles number'''. It is a powerful number, because not only are '''2''' and '''7''' its only prime factors, but also '''22 = 4''' and '''72 = 49''' are divisors of it. Nonetheless, it is a perfect power; its square root is an even integer, so it is ''not'' an '''Achilles number'''.\n\n\n'''500 = 22 x 53''' is a '''''strong'' Achilles number''' as its Euler totient, '''(500)''', is '''200 = 23 x 52''' which is ''also'' an '''Achilles number'''.\n\n\n\n;Task\n\n* Find and show the first 50 '''Achilles numbers'''.\n* Find and show at least the first 20 '''''strong'' Achilles numbers'''.\n* For at least 2 through 5, show the count of '''Achilles numbers''' with that many digits.\n\n\n;See also\n\n;* Wikipedia: Achilles number\n;* OEIS:A052486 - Achilles numbers - powerful but imperfect numbers\n;* OEIS:A194085 - Strong Achilles numbers: Achilles numbers m such that phi(m) is also an Achilles number\n;* Related task: Powerful numbers\n;* Related task: Totient function\n\n\n", "solution": "from math import gcd\nfrom sympy import factorint\n \ndef is_Achilles(n):\n p = factorint(n).values()\n return all(i > 1 for i in p) and gcd(*p) == 1\n\ndef is_strong_Achilles(n):\n return is_Achilles(n) and is_Achilles(totient(n))\n \ndef test_strong_Achilles(nachilles, nstrongachilles):\n # task 1\n print('First', nachilles, 'Achilles numbers:')\n n, found = 0, 0\n while found < nachilles:\n if is_Achilles(n):\n found += 1\n print(f'{n: 8,}', end='\\n' if found % 10 == 0 else '')\n n += 1\n\n # task 2\n print('\\nFirst', nstrongachilles, 'strong Achilles numbers:')\n n, found = 0, 0\n while found < nstrongachilles:\n if is_strong_Achilles(n):\n found += 1\n print(f'{n: 9,}', end='\\n' if found % 10 == 0 else '')\n n += 1\n\n # task 3\n print('\\nCount of Achilles numbers for various intervals:')\n intervals = [[10, 99], [100, 999], [1000, 9999], [10000, 99999], [100000, 999999]]\n for interval in intervals:\n print(f'{interval}:', sum(is_Achilles(i) for i in range(*interval)))\n\n\ntest_strong_Achilles(50, 100)\n"} -{"title": "Aliquot sequence classifications", "language": "C", "task": "An aliquot sequence of a positive integer K is defined recursively as the first member\nbeing K and subsequent members being the sum of the [[Proper divisors]] of the previous term.\n\n:* If the terms eventually reach 0 then the series for K is said to '''terminate'''.\n\n:There are several classifications for non termination:\n:* If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called '''perfect'''.\n:* If the third term ''would'' be repeating K then the sequence repeats with period 2 and K is called '''amicable'''.\n:* If the Nth term ''would'' be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called '''sociable'''.\n:Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...\n:* Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called '''aspiring'''.\n:* K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called '''cyclic'''.\n\n:And finally:\n:* Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called '''non-terminating'''. For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating '''16''' terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328. \n\n\n;Task:\n# Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.\n# Use it to display the classification and sequences of the numbers one to ten inclusive.\n# Use it to show the classification and sequences of the following integers, in order:\n:: 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.\n\nShow all output on this page.\n\n\n;Related tasks:\n* [[Abundant, deficient and perfect number classifications]]. (Classifications from only the first two members of the whole sequence).\n* [[Proper divisors]]\n* [[Amicable pairs]]\n\n", "solution": "#include\n#include\n#include\n\nunsigned long long raiseTo(unsigned long long base, unsigned long long power){\n unsigned long long result = 1,i;\n for (i=0; i 1)\n\t\t\tprod *= ((raiseTo(i,count + 1) - 1)/(i-1));\n\t}\n\t\n\tif(n>2)\n\t\tprod *= (n+1);\n\n\treturn prod - temp;\n}\n\nvoid printSeries(unsigned long long* arr,int size,char* type){\n\tint i;\n\t\n\tprintf(\"\\nInteger : %llu, Type : %s, Series : \",arr[0],type);\n\t\n\tfor(i=0;i\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],'.')!=NULL)\n\t\t\tprocessFile(argV[1]);\n\t\telse\n\t\t\taliquotClassifier(strtoull(argV[1],(char**)NULL,10));\n\t}\n\treturn 0;\n}\n"} -{"title": "Aliquot sequence classifications", "language": "C++", "task": "An aliquot sequence of a positive integer K is defined recursively as the first member\nbeing K and subsequent members being the sum of the [[Proper divisors]] of the previous term.\n\n:* If the terms eventually reach 0 then the series for K is said to '''terminate'''.\n\n:There are several classifications for non termination:\n:* If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called '''perfect'''.\n:* If the third term ''would'' be repeating K then the sequence repeats with period 2 and K is called '''amicable'''.\n:* If the Nth term ''would'' be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called '''sociable'''.\n:Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...\n:* Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called '''aspiring'''.\n:* K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called '''cyclic'''.\n\n:And finally:\n:* Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called '''non-terminating'''. For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating '''16''' terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328. \n\n\n;Task:\n# Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.\n# Use it to display the classification and sequences of the numbers one to ten inclusive.\n# Use it to show the classification and sequences of the following integers, in order:\n:: 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.\n\nShow all output on this page.\n\n\n;Related tasks:\n* [[Abundant, deficient and perfect number classifications]]. (Classifications from only the first two members of the whole sequence).\n* [[Proper divisors]]\n* [[Amicable pairs]]\n\n", "solution": "#include \n#include \n#include \n\nusing integer = uint64_t;\n\n// See https://en.wikipedia.org/wiki/Divisor_function\ninteger divisor_sum(integer n) {\n integer total = 1, power = 2;\n // Deal with powers of 2 first\n for (; n % 2 == 0; power *= 2, n /= 2)\n total += power;\n // Odd prime factors up to the square root\n for (integer p = 3; p * p <= n; p += 2) {\n integer sum = 1;\n for (power = p; n % p == 0; power *= p, n /= p)\n sum += power;\n total *= sum;\n }\n // If n > 1 then it's prime\n if (n > 1)\n total *= n + 1;\n return total;\n}\n\n// See https://en.wikipedia.org/wiki/Aliquot_sequence\nvoid classify_aliquot_sequence(integer n) {\n constexpr int limit = 16;\n integer terms[limit];\n terms[0] = n;\n std::string classification(\"non-terminating\");\n int length = 1;\n for (int i = 1; i < limit; ++i) {\n ++length;\n terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];\n if (terms[i] == n) {\n classification =\n (i == 1 ? \"perfect\" : (i == 2 ? \"amicable\" : \"sociable\"));\n break;\n }\n int j = 1;\n for (; j < i; ++j) {\n if (terms[i] == terms[i - j])\n break;\n }\n if (j < i) {\n classification = (j == 1 ? \"aspiring\" : \"cyclic\");\n break;\n }\n if (terms[i] == 0) {\n classification = \"terminating\";\n break;\n }\n }\n std::cout << n << \": \" << classification << \", sequence: \" << terms[0];\n for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)\n std::cout << ' ' << terms[i];\n std::cout << '\\n';\n}\n\nint main() {\n for (integer i = 1; i <= 10; ++i)\n classify_aliquot_sequence(i);\n for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,\n 1064, 1488})\n classify_aliquot_sequence(i);\n classify_aliquot_sequence(15355717786080);\n classify_aliquot_sequence(153557177860800);\n return 0;\n}"} -{"title": "Aliquot sequence classifications", "language": "Python", "task": "An aliquot sequence of a positive integer K is defined recursively as the first member\nbeing K and subsequent members being the sum of the [[Proper divisors]] of the previous term.\n\n:* If the terms eventually reach 0 then the series for K is said to '''terminate'''.\n\n:There are several classifications for non termination:\n:* If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called '''perfect'''.\n:* If the third term ''would'' be repeating K then the sequence repeats with period 2 and K is called '''amicable'''.\n:* If the Nth term ''would'' be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called '''sociable'''.\n:Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...\n:* Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called '''aspiring'''.\n:* K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called '''cyclic'''.\n\n:And finally:\n:* Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called '''non-terminating'''. For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating '''16''' terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328. \n\n\n;Task:\n# Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.\n# Use it to display the classification and sequences of the numbers one to ten inclusive.\n# Use it to show the classification and sequences of the following integers, in order:\n:: 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.\n\nShow all output on this page.\n\n\n;Related tasks:\n* [[Abundant, deficient and perfect number classifications]]. (Classifications from only the first two members of the whole sequence).\n* [[Proper divisors]]\n* [[Amicable pairs]]\n\n", "solution": "from proper_divisors import proper_divs\nfrom functools import lru_cache\n\n\n@lru_cache()\ndef pdsum(n): \n return sum(proper_divs(n))\n \n \ndef aliquot(n, maxlen=16, maxterm=2**47):\n if n == 0:\n return 'terminating', [0]\n s, slen, new = [n], 1, n\n while slen <= maxlen and new < maxterm:\n new = pdsum(s[-1])\n if new in s:\n if s[0] == new:\n if slen == 1:\n return 'perfect', s\n elif slen == 2:\n return 'amicable', s\n else:\n return 'sociable of length %i' % slen, s\n elif s[-1] == new:\n return 'aspiring', s\n else:\n return 'cyclic back to %i' % new, s\n elif new == 0:\n return 'terminating', s + [0]\n else:\n s.append(new)\n slen += 1\n else:\n return 'non-terminating', s\n \nif __name__ == '__main__':\n for n in range(1, 11): \n print('%s: %r' % aliquot(n))\n print()\n for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]: \n print('%s: %r' % aliquot(n))"} -{"title": "Almkvist-Giullera formula for pi", "language": "Python", "task": "The Almkvist-Giullera formula for calculating 1/p2 is based on the Calabi-Yau\ndifferential equations of order 4 and 5, which were originally used to describe certain manifolds\nin string theory. \n\n\nThe formula is:\n::::: 1/p2 = (25/3) 0 ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1\n\n\nThis formula can be used to calculate the constant p-2, and thus to calculate p.\n\nNote that, because the product of all terms but the power of 1000 can be calculated as an integer,\nthe terms in the series can be separated into a large integer term:\n\n::::: (25) (6n)! (532n2 + 126n + 9) / (3(n!)6) (***)\n\nmultiplied by a negative integer power of 10:\n\n::::: 10-(6n + 3) \n\n\n;Task:\n:* Print the integer portions (the starred formula, which is without the power of 1000 divisor) of the first 10 terms of the series.\n:* Use the complete formula to calculate and print p to 70 decimal digits of precision.\n\n\n;Reference:\n:* Gert Almkvist and Jesus Guillera, Ramanujan-like series for 1/p2 and string theory, Experimental Mathematics, 21 (2012), page 2, formula 1.\n\n", "solution": "import mpmath as mp\n\nwith mp.workdps(72):\n\n def integer_term(n):\n p = 532 * n * n + 126 * n + 9\n return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)\n\n def exponent_term(n):\n return -(mp.mpf(\"6.0\") * n + 3)\n\n def nthterm(n):\n return integer_term(n) * mp.mpf(\"10.0\")**exponent_term(n)\n\n\n for n in range(10):\n print(\"Term \", n, ' ', int(integer_term(n)))\n\n\n def almkvist_guillera(floatprecision):\n summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')\n for n in range(100000000):\n nextadd = summed + nthterm(n)\n if abs(nextadd - summed) < 10.0**(-floatprecision):\n break\n\n summed = nextadd\n\n return nextadd\n\n\n print('\\n\u03c0 to 70 digits is ', end='')\n mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)\n print('mpmath \u03c0 is ', end='')\n mp.nprint(mp.pi, 71)\n"} -{"title": "Amb", "language": "C", "task": "Define and give an example of the Amb operator.\n\nThe Amb operator (short for \"ambiguous\") expresses nondeterminism. This doesn't refer to randomness (as in \"nondeterministic universe\") but is closely related to the term as it is used in automata theory (\"non-deterministic finite automaton\").\n\nThe Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.\n\nProblems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent. \n\nEssentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other \"parallel universes\" somehow go away. Amb called with no arguments fails.\n\nFor simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.\n\nA pseudo-code program which satisfies this constraint might look like:\n\nlet x = Amb(1, 2, 3)\nlet y = Amb(7, 6, 4, 5)\nAmb(x * y = 8)\nprint x, y\n\nThe output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.\n\nAlternatively, failure could be represented using strictly Amb():\n\nunless x * y = 8 do Amb()\n\nOr else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:\n\nlet x = Ambsel(1, 2, 3)\nlet y = Ambsel(4, 5, 6)\nAmbassert(x * y = 8)\nprint x, y\n\nwhere Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.\n\nThe task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:\n\n#\"the\" \"that\" \"a\"\n#\"frog\" \"elephant\" \"thing\"\n#\"walked\" \"treaded\" \"grows\"\n#\"slowly\" \"quickly\"\n\nThe constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.\n\nThe only successful sentence is \"that thing grows slowly\"; other combinations do not satisfy the constraint and thus fail.\n\nThe goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.\n\n", "solution": "typedef const char * amb_t;\n\namb_t amb(size_t argc, ...)\n{\n amb_t *choices;\n va_list ap;\n int i;\n \n if(argc) {\n choices = malloc(argc*sizeof(amb_t));\n va_start(ap, argc);\n i = 0;\n do { choices[i] = va_arg(ap, amb_t); } while(++i < argc);\n va_end(ap);\n \n i = 0;\n do { TRY(choices[i]); } while(++i < argc);\n free(choices);\n }\n \n FAIL;\n}\n\nint joins(const char *left, const char *right) { return left[strlen(left)-1] == right[0]; }\n\nint _main() {\n const char *w1,*w2,*w3,*w4;\n \n w1 = amb(3, \"the\", \"that\", \"a\");\n w2 = amb(3, \"frog\", \"elephant\", \"thing\");\n w3 = amb(3, \"walked\", \"treaded\", \"grows\");\n w4 = amb(2, \"slowly\", \"quickly\");\n \n if(!joins(w1, w2)) amb(0);\n if(!joins(w2, w3)) amb(0);\n if(!joins(w3, w4)) amb(0);\n \n printf(\"%s %s %s %s\\n\", w1, w2, w3, w4);\n \n return EXIT_SUCCESS;\n}"} -{"title": "Amb", "language": "C++", "task": "Define and give an example of the Amb operator.\n\nThe Amb operator (short for \"ambiguous\") expresses nondeterminism. This doesn't refer to randomness (as in \"nondeterministic universe\") but is closely related to the term as it is used in automata theory (\"non-deterministic finite automaton\").\n\nThe Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.\n\nProblems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent. \n\nEssentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other \"parallel universes\" somehow go away. Amb called with no arguments fails.\n\nFor simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.\n\nA pseudo-code program which satisfies this constraint might look like:\n\nlet x = Amb(1, 2, 3)\nlet y = Amb(7, 6, 4, 5)\nAmb(x * y = 8)\nprint x, y\n\nThe output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.\n\nAlternatively, failure could be represented using strictly Amb():\n\nunless x * y = 8 do Amb()\n\nOr else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:\n\nlet x = Ambsel(1, 2, 3)\nlet y = Ambsel(4, 5, 6)\nAmbassert(x * y = 8)\nprint x, y\n\nwhere Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.\n\nThe task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:\n\n#\"the\" \"that\" \"a\"\n#\"frog\" \"elephant\" \"thing\"\n#\"walked\" \"treaded\" \"grows\"\n#\"slowly\" \"quickly\"\n\nThe constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.\n\nThe only successful sentence is \"that thing grows slowly\"; other combinations do not satisfy the constraint and thus fail.\n\nThe goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.\n\n", "solution": "#include \n#include \n#include \n#include \n\nusing namespace std;\nnamespace hana = boost::hana;\n\n// Define the Amb function. The first parameter is the constraint to be\n// enforced followed by the potential values.\nconstexpr auto Amb(auto constraint, auto&& ...params)\n{\n // create the set of all possible solutions\n auto possibleSolutions = hana::cartesian_product(hana::tuple(params...));\n\n // find one that matches the constraint\n auto foldOperation = [constraint](auto a, auto b)\n {\n bool meetsConstraint = constraint(a);\n return meetsConstraint ? a : b;\n };\n\n return hana::fold_right(possibleSolutions, foldOperation);\n}\n\nvoid AlgebraExample()\n{\n // use a tuple to hold the possible values of each variable\n constexpr hana::tuple x{1, 2, 3};\n constexpr hana::tuple y{7, 6, 4, 5};\n\n // the constraint enforcing x * y == 8\n constexpr auto constraint = [](auto t)\n {\n return t[hana::size_c<0>] * t[hana::size_c<1>] == 8;\n };\n\n // find the solution using the Amb function\n auto result = Amb(constraint, x, y);\n\n cout << \"\\nx = \" << hana::experimental::print(x);\n cout << \"\\ny = \" << hana::experimental::print(y);\n cout << \"\\nx * y == 8: \" << hana::experimental::print(result);\n}\n\nvoid StringExample()\n{\n // the word lists to choose from\n constexpr hana::tuple words1 {\"the\"sv, \"that\"sv, \"a\"sv};\n constexpr hana::tuple words2 {\"frog\"sv, \"elephant\"sv, \"thing\"sv};\n constexpr hana::tuple words3 {\"walked\"sv, \"treaded\"sv, \"grows\"sv};\n constexpr hana::tuple words4 {\"slowly\"sv, \"quickly\"sv};\n\n // the constraint that the first letter of a word is the same as the last\n // letter of the previous word\n constexpr auto constraint = [](const auto t)\n {\n auto adjacent = hana::zip(hana::drop_back(t), hana::drop_front(t));\n return hana::all_of(adjacent, [](auto t)\n {\n return t[hana::size_c<0>].back() == t[hana::size_c<1>].front();\n });\n };\n\n\n // find the solution using the Amb function\n auto wordResult = Amb(constraint, words1, words2, words3, words4);\n\n cout << \"\\n\\nWords 1: \" << hana::experimental::print(words1);\n cout << \"\\nWords 2: \" << hana::experimental::print(words2);\n cout << \"\\nWords 3: \" << hana::experimental::print(words3);\n cout << \"\\nWords 4: \" << hana::experimental::print(words4);\n cout << \"\\nSolution: \" << hana::experimental::print(wordResult) << \"\\n\";\n}\n\nint main()\n{\n AlgebraExample();\n StringExample();\n}\n"} -{"title": "Amb", "language": "JavaScript", "task": "Define and give an example of the Amb operator.\n\nThe Amb operator (short for \"ambiguous\") expresses nondeterminism. This doesn't refer to randomness (as in \"nondeterministic universe\") but is closely related to the term as it is used in automata theory (\"non-deterministic finite automaton\").\n\nThe Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.\n\nProblems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent. \n\nEssentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other \"parallel universes\" somehow go away. Amb called with no arguments fails.\n\nFor simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.\n\nA pseudo-code program which satisfies this constraint might look like:\n\nlet x = Amb(1, 2, 3)\nlet y = Amb(7, 6, 4, 5)\nAmb(x * y = 8)\nprint x, y\n\nThe output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.\n\nAlternatively, failure could be represented using strictly Amb():\n\nunless x * y = 8 do Amb()\n\nOr else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:\n\nlet x = Ambsel(1, 2, 3)\nlet y = Ambsel(4, 5, 6)\nAmbassert(x * y = 8)\nprint x, y\n\nwhere Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.\n\nThe task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:\n\n#\"the\" \"that\" \"a\"\n#\"frog\" \"elephant\" \"thing\"\n#\"walked\" \"treaded\" \"grows\"\n#\"slowly\" \"quickly\"\n\nThe constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.\n\nThe only successful sentence is \"that thing grows slowly\"; other combinations do not satisfy the constraint and thus fail.\n\nThe goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.\n\n", "solution": "function ambRun(func) {\n var choices = [];\n var index;\n\n function amb(values) {\n if (values.length == 0) {\n fail();\n }\n if (index == choices.length) {\n choices.push({i: 0,\n count: values.length});\n }\n var choice = choices[index++];\n return values[choice.i];\n }\n\n function fail() { throw fail; }\n\n while (true) {\n try {\n index = 0;\n return func(amb, fail);\n } catch (e) {\n if (e != fail) {\n throw e;\n }\n var choice;\n while ((choice = choices.pop()) && ++choice.i == choice.count) {}\n if (choice == undefined) {\n return undefined;\n }\n choices.push(choice);\n }\n }\n}\n\nambRun(function(amb, fail) {\n function linked(s1, s2) {\n return s1.slice(-1) == s2.slice(0, 1);\n }\n\n var w1 = amb([\"the\", \"that\", \"a\"]);\n var w2 = amb([\"frog\", \"elephant\", \"thing\"]);\n if (!linked(w1, w2)) fail();\n\n var w3 = amb([\"walked\", \"treaded\", \"grows\"]);\n if (!linked(w2, w3)) fail();\n\n var w4 = amb([\"slowly\", \"quickly\"]);\n if (!linked(w3, w4)) fail();\n\n return [w1, w2, w3, w4].join(' ');\n}); // \"that thing grows slowly\""} -{"title": "Amb", "language": "Python", "task": "Define and give an example of the Amb operator.\n\nThe Amb operator (short for \"ambiguous\") expresses nondeterminism. This doesn't refer to randomness (as in \"nondeterministic universe\") but is closely related to the term as it is used in automata theory (\"non-deterministic finite automaton\").\n\nThe Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.\n\nProblems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent. \n\nEssentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other \"parallel universes\" somehow go away. Amb called with no arguments fails.\n\nFor simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.\n\nA pseudo-code program which satisfies this constraint might look like:\n\nlet x = Amb(1, 2, 3)\nlet y = Amb(7, 6, 4, 5)\nAmb(x * y = 8)\nprint x, y\n\nThe output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.\n\nAlternatively, failure could be represented using strictly Amb():\n\nunless x * y = 8 do Amb()\n\nOr else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:\n\nlet x = Ambsel(1, 2, 3)\nlet y = Ambsel(4, 5, 6)\nAmbassert(x * y = 8)\nprint x, y\n\nwhere Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.\n\nThe task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:\n\n#\"the\" \"that\" \"a\"\n#\"frog\" \"elephant\" \"thing\"\n#\"walked\" \"treaded\" \"grows\"\n#\"slowly\" \"quickly\"\n\nThe constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.\n\nThe only successful sentence is \"that thing grows slowly\"; other combinations do not satisfy the constraint and thus fail.\n\nThe goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.\n\n", "solution": "import itertools as _itertools\n \nclass Amb(object):\n def __init__(self):\n self._names2values = {} # set of values for each global name\n self._func = None # Boolean constraint function\n self._valueiterator = None # itertools.product of names values\n self._funcargnames = None # Constraint parameter names\n \n def __call__(self, arg=None):\n if hasattr(arg, '__code__'): \n ##\n ## Called with a constraint function. \n ##\n globls = arg.__globals__ if hasattr(arg, '__globals__') else arg.func_globals\n # Names used in constraint\n argv = arg.__code__.co_varnames[:arg.__code__.co_argcount]\n for name in argv:\n if name not in self._names2values:\n assert name in globls, \\\n \"Global name %s not found in function globals\" % name\n self._names2values[name] = globls[name]\n # Gather the range of values of all names used in the constraint\n valuesets = [self._names2values[name] for name in argv]\n self._valueiterator = _itertools.product(*valuesets)\n self._func = arg\n self._funcargnames = argv\n return self\n elif arg is not None:\n ##\n ## Assume called with an iterable set of values\n ##\n arg = frozenset(arg)\n return arg\n else:\n ##\n ## blank call tries to return next solution\n ##\n return self._nextinsearch()\n \n def _nextinsearch(self):\n arg = self._func\n globls = arg.__globals__\n argv = self._funcargnames\n found = False\n for values in self._valueiterator:\n if arg(*values):\n # Set globals.\n found = True\n for n, v in zip(argv, values):\n globls[n] = v\n break\n if not found: raise StopIteration\n return values\n \n def __iter__(self):\n return self\n \n def __next__(self):\n return self()\n next = __next__ # Python 2\n \nif __name__ == '__main__':\n if True:\n amb = Amb()\n \n print(\"\\nSmall Pythagorean triples problem:\")\n x = amb(range(1,11))\n y = amb(range(1,11))\n z = amb(range(1,11))\n \n for _dummy in amb( lambda x, y, z: x*x + y*y == z*z ):\n print ('%s %s %s' % (x, y, z))\n \n \n if True:\n amb = Amb()\n \n print(\"\\nRosetta Code Amb problem:\")\n w1 = amb([\"the\", \"that\", \"a\"])\n w2 = amb([\"frog\", \"elephant\", \"thing\"])\n w3 = amb([\"walked\", \"treaded\", \"grows\"])\n w4 = amb([\"slowly\", \"quickly\"])\n \n for _dummy in amb( lambda w1, w2, w3, w4: \\\n w1[-1] == w2[0] and \\\n w2[-1] == w3[0] and \\\n w3[-1] == w4[0] ):\n print ('%s %s %s %s' % (w1, w2, w3, w4))\n \n if True:\n amb = Amb()\n \n print(\"\\nAmb problem from \"\n \"http://www.randomhacks.net/articles/2005/10/11/amb-operator:\")\n x = amb([1, 2, 3])\n y = amb([4, 5, 6])\n \n for _dummy in amb( lambda x, y: x * y != 8 ):\n print ('%s %s' % (x, y))"} -{"title": "Amb", "language": "Python from Haskell", "task": "Define and give an example of the Amb operator.\n\nThe Amb operator (short for \"ambiguous\") expresses nondeterminism. This doesn't refer to randomness (as in \"nondeterministic universe\") but is closely related to the term as it is used in automata theory (\"non-deterministic finite automaton\").\n\nThe Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.\n\nProblems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent. \n\nEssentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other \"parallel universes\" somehow go away. Amb called with no arguments fails.\n\nFor simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.\n\nA pseudo-code program which satisfies this constraint might look like:\n\nlet x = Amb(1, 2, 3)\nlet y = Amb(7, 6, 4, 5)\nAmb(x * y = 8)\nprint x, y\n\nThe output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.\n\nAlternatively, failure could be represented using strictly Amb():\n\nunless x * y = 8 do Amb()\n\nOr else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:\n\nlet x = Ambsel(1, 2, 3)\nlet y = Ambsel(4, 5, 6)\nAmbassert(x * y = 8)\nprint x, y\n\nwhere Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.\n\nThe task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:\n\n#\"the\" \"that\" \"a\"\n#\"frog\" \"elephant\" \"thing\"\n#\"walked\" \"treaded\" \"grows\"\n#\"slowly\" \"quickly\"\n\nThe constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.\n\nThe only successful sentence is \"that thing grows slowly\"; other combinations do not satisfy the constraint and thus fail.\n\nThe goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.\n\n", "solution": "# joins :: String -> String -> Bool\ndef joins(a, b):\n return a[-1] == b[0]\n\n\nprint (\n [\n ' '.join([w1, w2, w3, w4])\n for w1 in ['the', 'that', 'a']\n for w2 in ['frog', 'elephant', 'thing']\n for w3 in ['walked', 'treaded', 'grows']\n for w4 in ['slowly', 'quickly']\n if joins(w1, w2) and joins(w2, w3) and joins(w3, w4)\n ]\n)"} -{"title": "Anagrams/Deranged anagrams", "language": "C", "task": "Two or more words are said to be anagrams if they have the same characters, but in a different order. \n\nBy analogy with derangements we define a ''deranged anagram'' as two words with the same characters, but in which the same character does ''not'' appear in the same position in both words.\n\n;Task\n\nUse the word list at unixdict to find and display the longest deranged anagram. \n\n\n;Related\n* [[Permutations/Derangements]]\n* Best shuffle\n\n{{Related tasks/Word plays}}\n\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n// Letter lookup by frequency. This is to reduce word insertion time.\nconst char *freq = \"zqxjkvbpygfwmucldrhsnioate\";\nint char_to_idx[128];\n\n// Trie structure of sorts\nstruct word {\n\tconst char *w;\n\tstruct word *next;\n};\n\nunion node {\n\tunion node *down[10];\n\tstruct word *list[10];\n};\n\nint deranged(const char *s1, const char *s2)\n{\n\tint i;\n\tfor (i = 0; s1[i]; i++)\n\t\tif (s1[i] == s2[i]) return 0;\n\treturn 1;\n}\n\nint count_letters(const char *s, unsigned char *c)\n{\n\tint i, len;\n\tmemset(c, 0, 26);\n\tfor (len = i = 0; s[i]; i++) {\n\t\tif (s[i] < 'a' || s[i] > 'z')\n\t\t\treturn 0;\n\t\tlen++, c[char_to_idx[(unsigned char)s[i]]]++;\n\t}\n\treturn len;\n}\n\nconst char * insert(union node *root, const char *s, unsigned char *cnt)\n{\n\tint i;\n\tunion node *n;\n\tstruct word *v, *w = 0;\n\n\tfor (i = 0; i < 25; i++, root = n) {\n\t\tif (!(n = root->down[cnt[i]]))\n\t\t\troot->down[cnt[i]] = n = calloc(1, sizeof(union node));\n\t}\n\n\tw = malloc(sizeof(struct word));\n\tw->w = s;\n\tw->next = root->list[cnt[25]];\n\troot->list[cnt[25]] = w;\n\n\tfor (v = w->next; v; v = v->next) {\n\t\tif (deranged(w->w, v->w))\n\t\t\treturn v->w;\n\t}\n\treturn 0;\n}\n\nint main(int c, char **v)\n{\n\tint i, j = 0;\n\tchar *words;\n\tstruct stat st;\n\n\tint fd = open(c < 2 ? \"unixdict.txt\" : v[1], O_RDONLY);\n\tif (fstat(fd, &st) < 0) return 1;\n\n\twords = malloc(st.st_size);\n\tread(fd, words, st.st_size);\n\tclose(fd);\n\n\tunion node root = {{0}};\n\tunsigned char cnt[26];\n\tint best_len = 0;\n\tconst char *b1, *b2;\n\n\tfor (i = 0; freq[i]; i++)\n\t\tchar_to_idx[(unsigned char)freq[i]] = i;\n\n\t/* count words, change newline to null */\n\tfor (i = j = 0; i < st.st_size; i++) {\n\t\tif (words[i] != '\\n') continue;\n\t\twords[i] = '\\0';\n\n\t\tif (i - j > best_len) {\n\t\t\tcount_letters(words + j, cnt);\n\t\t\tconst char *match = insert(&root, words + j, cnt);\n\n\t\t\tif (match) {\n\t\t\t\tbest_len = i - j;\n\t\t\t\tb1 = words + j;\n\t\t\t\tb2 = match;\n\t\t\t}\n\t\t}\n\n\t\tj = ++i;\n\t}\n\n\tif (best_len) printf(\"longest derangement: %s %s\\n\", b1, b2);\n\n\treturn 0;\n}"} -{"title": "Anagrams/Deranged anagrams", "language": "C++", "task": "Two or more words are said to be anagrams if they have the same characters, but in a different order. \n\nBy analogy with derangements we define a ''deranged anagram'' as two words with the same characters, but in which the same character does ''not'' appear in the same position in both words.\n\n;Task\n\nUse the word list at unixdict to find and display the longest deranged anagram. \n\n\n;Related\n* [[Permutations/Derangements]]\n* Best shuffle\n\n{{Related tasks/Word plays}}\n\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nbool is_deranged(const std::string& left, const std::string& right)\n{\n return (left.size() == right.size()) &&\n (std::inner_product(left.begin(), left.end(), right.begin(), 0, std::plus(), std::equal_to()) == 0);\n}\n\nint main()\n{\n std::ifstream input(\"unixdict.txt\");\n if (!input) {\n std::cerr << \"can't open input file\\n\";\n return EXIT_FAILURE;\n }\n\n typedef std::set WordList;\n typedef std::map AnagraMap;\n AnagraMap anagrams;\n\n std::pair result;\n size_t longest = 0;\n\n for (std::string value; input >> value; /**/) {\n std::string key(value);\n std::sort(key.begin(), key.end());\n\n if (longest < value.length()) { // is it a long candidate?\n if (0 < anagrams.count(key)) { // is it an anagram?\n for (const auto& prior : anagrams[key]) {\n if (is_deranged(prior, value)) { // are they deranged?\n result = std::make_pair(prior, value);\n longest = value.length();\n }\n }\n }\n }\n anagrams[key].insert(value);\n }\n\n std::cout << result.first << ' ' << result.second << '\\n';\n return EXIT_SUCCESS;\n}"} -{"title": "Anagrams/Deranged anagrams", "language": "JavaScript", "task": "Two or more words are said to be anagrams if they have the same characters, but in a different order. \n\nBy analogy with derangements we define a ''deranged anagram'' as two words with the same characters, but in which the same character does ''not'' appear in the same position in both words.\n\n;Task\n\nUse the word list at unixdict to find and display the longest deranged anagram. \n\n\n;Related\n* [[Permutations/Derangements]]\n* Best shuffle\n\n{{Related tasks/Word plays}}\n\n\n\n", "solution": "#!/usr/bin/env js\n\nfunction main() {\n var wordList = read('unixdict.txt').split(/\\s+/);\n var anagrams = findAnagrams(wordList);\n var derangedAnagrams = findDerangedAnagrams(anagrams);\n var longestPair = findLongestDerangedPair(derangedAnagrams);\n print(longestPair.join(' '));\n \n}\n\nfunction findLongestDerangedPair(danas) {\n var longestLen = danas[0][0].length;\n var longestPair = danas[0];\n for (var i in danas) {\n if (danas[i][0].length > longestLen) {\n longestLen = danas[i][0].length;\n longestPair = danas[i];\n }\n }\n return longestPair;\n}\n\nfunction findDerangedAnagrams(anagrams) {\n var deranged = [];\n \n function isDeranged(w1, w2) {\n for (var c = 0; c < w1.length; c++) {\n if (w1[c] == w2[c]) {\n return false;\n }\n }\n return true;\n }\n\n function findDeranged(anas) {\n for (var a = 0; a < anas.length; a++) {\n for (var b = a + 1; b < anas.length; b++) {\n if (isDeranged(anas[a], anas[b])) {\n deranged.push([anas[a], anas[b]]);\n } \n }\n }\n }\n \n for (var a in anagrams) {\n var anas = anagrams[a];\n findDeranged(anas);\n }\n \n return deranged;\n}\n \nfunction findAnagrams(wordList) {\n var anagrams = {};\n\n for (var wordNum in wordList) {\n var word = wordList[wordNum];\n var key = word.split('').sort().join('');\n if (!(key in anagrams)) {\n anagrams[key] = [];\n }\n anagrams[key].push(word);\n }\n\n for (var a in anagrams) {\n if (anagrams[a].length < 2) {\n delete(anagrams[a]);\n }\n }\n\n return anagrams;\n}\n\nmain();"} -{"title": "Anagrams/Deranged anagrams", "language": "Python", "task": "Two or more words are said to be anagrams if they have the same characters, but in a different order. \n\nBy analogy with derangements we define a ''deranged anagram'' as two words with the same characters, but in which the same character does ''not'' appear in the same position in both words.\n\n;Task\n\nUse the word list at unixdict to find and display the longest deranged anagram. \n\n\n;Related\n* [[Permutations/Derangements]]\n* Best shuffle\n\n{{Related tasks/Word plays}}\n\n\n\n", "solution": "import urllib.request\nfrom collections import defaultdict\nfrom itertools import combinations\n\ndef getwords(url='http://www.puzzlers.org/pub/wordlists/unixdict.txt'):\n return list(set(urllib.request.urlopen(url).read().decode().split()))\n\ndef find_anagrams(words):\n anagram = defaultdict(list) # map sorted chars to anagrams\n for word in words:\n anagram[tuple(sorted(word))].append( word )\n return dict((key, words) for key, words in anagram.items()\n if len(words) > 1)\n\ndef is_deranged(words):\n 'returns pairs of words that have no character in the same position'\n return [ (word1, word2)\n for word1,word2 in combinations(words, 2)\n if all(ch1 != ch2 for ch1, ch2 in zip(word1, word2)) ]\n\ndef largest_deranged_ana(anagrams):\n ordered_anagrams = sorted(anagrams.items(),\n key=lambda x:(-len(x[0]), x[0]))\n for _, words in ordered_anagrams:\n deranged_pairs = is_deranged(words)\n if deranged_pairs:\n return deranged_pairs\n return []\n\nif __name__ == '__main__':\n words = getwords('http://www.puzzlers.org/pub/wordlists/unixdict.txt')\n print(\"Word count:\", len(words))\n\n anagrams = find_anagrams(words)\n print(\"Anagram count:\", len(anagrams),\"\\n\")\n\n print(\"Longest anagrams with no characters in the same position:\")\n print(' ' + '\\n '.join(', '.join(pairs)\n for pairs in largest_deranged_ana(anagrams)))"} -{"title": "Angle difference between two bearings", "language": "C", "task": "Finding the angle between two bearings is often confusing.[https://stackoverflow.com/questions/16180595/find-the-angle-between-two-bearings]\n\n\n;Task:\nFind the angle which is the result of the subtraction '''b2 - b1''', where '''b1''' and '''b2''' are the bearings. \n\nInput bearings are expressed in the range '''-180''' to '''+180''' degrees. \nThe result is also expressed in the range '''-180''' to '''+180''' degrees. \n\n\nCompute the angle for the following pairs:\n* 20 degrees ('''b1''') and 45 degrees ('''b2''')\n* -45 and 45\n* -85 and 90\n* -95 and 90\n* -45 and 125\n* -45 and 145\n* 29.4803 and -88.6381\n* -78.3251 and -159.036\n\n\n;Optional extra: \nAllow the input bearings to be any (finite) value. \n\n\n;Test cases:\n* -70099.74233810938 and 29840.67437876723\n* -165313.6666297357 and 33693.9894517456\n* 1174.8380510598456 and -154146.66490124757\n* 60175.77306795546 and 42213.07192354373\n\n", "solution": "#include\n#include\n#include\n\nvoid processFile(char* name){\n\t\n\tint i,records;\n\tdouble diff,b1,b2;\n\tFILE* fp = fopen(name,\"r\");\n\t\n\tfscanf(fp,\"%d\\n\",&records);\n\t\n\tfor(i=0;i=180)?diff-360:diff));\t\n\t}\n\t\n\tfclose(fp);\n}\n\nint main(int argC,char* argV[])\n{\n\tdouble diff;\n\t\n\tif(argC < 2)\n\t\tprintf(\"Usage : %s \",argV[0]);\n\telse if(argC == 2)\n\t\tprocessFile(argV[1]);\n\telse{\n\t\tdiff = fmod(atof(argV[2])-atof(argV[1]),360.0);\n\t\tprintf(\"Difference between b2(%s) and b1(%s) is %lf\",argV[2],argV[1],(diff<-180)?diff+360:((diff>=180)?diff-360:diff));\n\t}\n\n\treturn 0;\n}\n"} -{"title": "Angle difference between two bearings", "language": "C++", "task": "Finding the angle between two bearings is often confusing.[https://stackoverflow.com/questions/16180595/find-the-angle-between-two-bearings]\n\n\n;Task:\nFind the angle which is the result of the subtraction '''b2 - b1''', where '''b1''' and '''b2''' are the bearings. \n\nInput bearings are expressed in the range '''-180''' to '''+180''' degrees. \nThe result is also expressed in the range '''-180''' to '''+180''' degrees. \n\n\nCompute the angle for the following pairs:\n* 20 degrees ('''b1''') and 45 degrees ('''b2''')\n* -45 and 45\n* -85 and 90\n* -95 and 90\n* -45 and 125\n* -45 and 145\n* 29.4803 and -88.6381\n* -78.3251 and -159.036\n\n\n;Optional extra: \nAllow the input bearings to be any (finite) value. \n\n\n;Test cases:\n* -70099.74233810938 and 29840.67437876723\n* -165313.6666297357 and 33693.9894517456\n* 1174.8380510598456 and -154146.66490124757\n* 60175.77306795546 and 42213.07192354373\n\n", "solution": "#include \n#include \nusing namespace std;\n\ndouble getDifference(double b1, double b2) {\n\tdouble r = fmod(b2 - b1, 360.0);\n\tif (r < -180.0)\n\t\tr += 360.0;\n\tif (r >= 180.0)\n\t\tr -= 360.0;\n\treturn r;\n}\n\nint main()\n{\n\tcout << \"Input in -180 to +180 range\" << endl;\n\tcout << getDifference(20.0, 45.0) << endl;\n\tcout << getDifference(-45.0, 45.0) << endl;\n\tcout << getDifference(-85.0, 90.0) << endl;\n\tcout << getDifference(-95.0, 90.0) << endl;\n\tcout << getDifference(-45.0, 125.0) << endl;\n\tcout << getDifference(-45.0, 145.0) << endl;\n\tcout << getDifference(-45.0, 125.0) << endl;\n\tcout << getDifference(-45.0, 145.0) << endl;\n\tcout << getDifference(29.4803, -88.6381) << endl;\n\tcout << getDifference(-78.3251, -159.036) << endl;\n\t\n\tcout << \"Input in wider range\" << endl;\n\tcout << getDifference(-70099.74233810938, 29840.67437876723) << endl;\n\tcout << getDifference(-165313.6666297357, 33693.9894517456) << endl;\n\tcout << getDifference(1174.8380510598456, -154146.66490124757) << endl;\n\tcout << getDifference(60175.77306795546, 42213.07192354373) << endl;\n\n\treturn 0;\n}"} -{"title": "Angle difference between two bearings", "language": "Python from C++", "task": "Finding the angle between two bearings is often confusing.[https://stackoverflow.com/questions/16180595/find-the-angle-between-two-bearings]\n\n\n;Task:\nFind the angle which is the result of the subtraction '''b2 - b1''', where '''b1''' and '''b2''' are the bearings. \n\nInput bearings are expressed in the range '''-180''' to '''+180''' degrees. \nThe result is also expressed in the range '''-180''' to '''+180''' degrees. \n\n\nCompute the angle for the following pairs:\n* 20 degrees ('''b1''') and 45 degrees ('''b2''')\n* -45 and 45\n* -85 and 90\n* -95 and 90\n* -45 and 125\n* -45 and 145\n* 29.4803 and -88.6381\n* -78.3251 and -159.036\n\n\n;Optional extra: \nAllow the input bearings to be any (finite) value. \n\n\n;Test cases:\n* -70099.74233810938 and 29840.67437876723\n* -165313.6666297357 and 33693.9894517456\n* 1174.8380510598456 and -154146.66490124757\n* 60175.77306795546 and 42213.07192354373\n\n", "solution": "from __future__ import print_function\n \ndef getDifference(b1, b2):\n\tr = (b2 - b1) % 360.0\n\t# Python modulus has same sign as divisor, which is positive here,\n\t# so no need to consider negative case\n\tif r >= 180.0:\n\t\tr -= 360.0\n\treturn r\n \nif __name__ == \"__main__\":\n\tprint (\"Input in -180 to +180 range\")\n\tprint (getDifference(20.0, 45.0))\n\tprint (getDifference(-45.0, 45.0))\n\tprint (getDifference(-85.0, 90.0))\n\tprint (getDifference(-95.0, 90.0))\n\tprint (getDifference(-45.0, 125.0))\n\tprint (getDifference(-45.0, 145.0))\n\tprint (getDifference(-45.0, 125.0))\n\tprint (getDifference(-45.0, 145.0))\n\tprint (getDifference(29.4803, -88.6381))\n\tprint (getDifference(-78.3251, -159.036))\n \n\tprint (\"Input in wider range\")\n\tprint (getDifference(-70099.74233810938, 29840.67437876723))\n\tprint (getDifference(-165313.6666297357, 33693.9894517456))\n\tprint (getDifference(1174.8380510598456, -154146.66490124757))\n\tprint (getDifference(60175.77306795546, 42213.07192354373))"} -{"title": "Angle difference between two bearings", "language": "Python 3.7", "task": "Finding the angle between two bearings is often confusing.[https://stackoverflow.com/questions/16180595/find-the-angle-between-two-bearings]\n\n\n;Task:\nFind the angle which is the result of the subtraction '''b2 - b1''', where '''b1''' and '''b2''' are the bearings. \n\nInput bearings are expressed in the range '''-180''' to '''+180''' degrees. \nThe result is also expressed in the range '''-180''' to '''+180''' degrees. \n\n\nCompute the angle for the following pairs:\n* 20 degrees ('''b1''') and 45 degrees ('''b2''')\n* -45 and 45\n* -85 and 90\n* -95 and 90\n* -45 and 125\n* -45 and 145\n* 29.4803 and -88.6381\n* -78.3251 and -159.036\n\n\n;Optional extra: \nAllow the input bearings to be any (finite) value. \n\n\n;Test cases:\n* -70099.74233810938 and 29840.67437876723\n* -165313.6666297357 and 33693.9894517456\n* 1174.8380510598456 and -154146.66490124757\n* 60175.77306795546 and 42213.07192354373\n\n", "solution": "'''Difference between two bearings'''\n\nfrom math import (acos, cos, pi, sin)\n\n\n# bearingDelta :: Radians -> Radians -> Radians\ndef bearingDelta(ar):\n '''Difference between two bearings,\n expressed in radians.'''\n def go(br):\n [(ax, ay), (bx, by)] = [\n (sin(x), cos(x)) for x in [ar, br]\n ]\n # cross-product > 0 ?\n sign = +1 if 0 < ((ay * bx) - (by * ax)) else -1\n # sign * dot-product\n return sign * acos((ax * bx) + (ay * by))\n return lambda br: go(br)\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Test and display'''\n\n # showMap :: Degrees -> Degrees -> String\n def showMap(da, db):\n return unwords(\n str(x).rjust(n) for n, x in\n [\n (22, str(da) + ' +'),\n (24, str(db) + ' -> '),\n (7, round(\n degrees(\n bearingDelta\n (radians(da))\n (radians(db))\n ), 2)\n )\n ]\n )\n\n print(__doc__ + ':')\n print(\n unlines(showMap(a, b) for a, b in [\n (20, 45),\n (-45, 45),\n (-85, 90),\n (-95, 90),\n (-45, 125),\n (-45, 145),\n (-70099.74233810938, 29840.67437876723),\n (-165313.6666297357, 33693.9894517456),\n (1174.8380510598456, -154146.66490124757),\n (60175.77306795546, 42213.07192354373)\n ]))\n\n\n# GENERIC ----------------------------------------------\n\n\n# radians :: Float x => Degrees x -> Radians x\ndef radians(x):\n '''Radians derived from degrees.'''\n return pi * x / 180\n\n\n# degrees :: Float x => Radians x -> Degrees x\ndef degrees(x):\n '''Degrees derived from radians.'''\n return 180 * x / pi\n\n\n# unlines :: [String] -> String\ndef unlines(xs):\n '''A single newline-delimited string derived\n from a list of strings.'''\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": "Angle difference between two bearings", "language": "Python 3.6", "task": "Finding the angle between two bearings is often confusing.[https://stackoverflow.com/questions/16180595/find-the-angle-between-two-bearings]\n\n\n;Task:\nFind the angle which is the result of the subtraction '''b2 - b1''', where '''b1''' and '''b2''' are the bearings. \n\nInput bearings are expressed in the range '''-180''' to '''+180''' degrees. \nThe result is also expressed in the range '''-180''' to '''+180''' degrees. \n\n\nCompute the angle for the following pairs:\n* 20 degrees ('''b1''') and 45 degrees ('''b2''')\n* -45 and 45\n* -85 and 90\n* -95 and 90\n* -45 and 125\n* -45 and 145\n* 29.4803 and -88.6381\n* -78.3251 and -159.036\n\n\n;Optional extra: \nAllow the input bearings to be any (finite) value. \n\n\n;Test cases:\n* -70099.74233810938 and 29840.67437876723\n* -165313.6666297357 and 33693.9894517456\n* 1174.8380510598456 and -154146.66490124757\n* 60175.77306795546 and 42213.07192354373\n\n", "solution": "\"\"\"\nDifference between two bearings\n\"\"\"\n\ndef delta_bearing(b1 , b2):\n\treturn ((b2-b1+540)%360)-180\n\ndataSet = [[20, 45], [-45, 45], [-85, 90], [-95, 90], [-45, 125], [-45, 145], \\\n\t[29.4803, -88.6381], [-78.3251, -159.036], \\\n\t[-70099.74233810938, 29840.67437876723], \\\n\t[-165313.6666297357, 33693.9894517456], \\\n\t[1174.8380510598456, -154146.66490124757], \\\n\t[60175.77306795546, 42213.07192354373]]\n\nprint('.{:-^19}.{:-^19}.{:-^9}.' .format(\" b1 \", \" b2 \", \" \u0394 b \" ))\nfor \u0394 in dataSet: \n\tprint('|{: > 19}|{: > 19}|{: > 9.4f}|' .format(\u0394[0], \u0394[1],delta_bearing(\u0394[0],\u0394[1])))"} -{"title": "Anti-primes", "language": "C++ from C", "task": "The anti-primes \n(or highly composite numbers, sequence A002182 in the OEIS) \nare the natural numbers with more factors than any smaller than itself.\n\n\n;Task:\nGenerate and show here, the first twenty anti-primes.\n\n\n;Related tasks:\n:* [[Factors of an integer]]\n:* [[Sieve of Eratosthenes]]\n\n", "solution": "#include \n\nint countDivisors(int n) {\n if (n < 2) return 1;\n int count = 2; // 1 and n\n for (int i = 2; i <= n/2; ++i) {\n if (n%i == 0) ++count;\n }\n return count;\n}\n\nint main() {\n int maxDiv = 0, count = 0;\n std::cout << \"The first 20 anti-primes are:\" << std::endl;\n for (int n = 1; count < 20; ++n) {\n int d = countDivisors(n);\n if (d > maxDiv) {\n std::cout << n << \" \";\n maxDiv = d;\n count++;\n }\n }\n std::cout << std::endl;\n return 0;\n}"} -{"title": "Anti-primes", "language": "Python", "task": "The anti-primes \n(or highly composite numbers, sequence A002182 in the OEIS) \nare the natural numbers with more factors than any smaller than itself.\n\n\n;Task:\nGenerate and show here, the first twenty anti-primes.\n\n\n;Related tasks:\n:* [[Factors of an integer]]\n:* [[Sieve of Eratosthenes]]\n\n", "solution": "from itertools import chain, count, cycle, islice, accumulate\n \ndef factors(n):\n def prime_powers(n):\n for c in accumulate(chain([2, 1, 2], cycle([2,4]))):\n if c*c > n: break\n if n%c: continue\n d,p = (), c\n while not n%c:\n n,p,d = n//c, p*c, d+(p,)\n yield d\n if n > 1: yield n,\n \n r = [1]\n for e in prime_powers(n):\n r += [a*b for a in r for b in e]\n return r\n \ndef antiprimes():\n mx = 0\n yield 1\n for c in count(2,2):\n if c >= 58: break\n ln = len(factors(c))\n if ln > mx:\n yield c\n mx = ln\n for c in count(60,30):\n ln = len(factors(c))\n if ln > mx:\n yield c\n mx = ln \n\nif __name__ == '__main__':\n print(*islice(antiprimes(), 40)))"} -{"title": "Apply a digital filter (direct form II transposed)", "language": "C", "task": "Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the \"direct form II transposed\" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [https://ccrma.stanford.edu/~jos/fp/Transposed_Direct_Forms.html]\n\n;Task:\n\nFilter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667]\n\nThe signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]\n\n;See also:\n[Wikipedia on Butterworth filters]\n\n\n", "solution": "#include\n#include\n#include\n\n#define MAX_LEN 1000\n\ntypedef struct{\n\tfloat* values;\n\tint size;\n}vector;\n\nvector extractVector(char* str){\n\tvector coeff;\n\tint i=0,count = 1;\n\tchar* token;\n\t\n\twhile(str[i]!=00){\n\t\tif(str[i++]==' ')\n\t\t\tcount++;\n\t}\n\t\n\tcoeff.values = (float*)malloc(count*sizeof(float));\n\tcoeff.size = count;\n\t\n\ttoken = strtok(str,\" \");\n\t\n\ti = 0;\n\t\n\twhile(token!=NULL){\n\t\tcoeff.values[i++] = atof(token);\n\t\ttoken = strtok(NULL,\" \");\n\t}\n\t\n\treturn coeff;\n}\n\nvector processSignalFile(char* fileName){\n\tint i,j;\n\tfloat sum;\n\tchar str[MAX_LEN];\n\tvector coeff1,coeff2,signal,filteredSignal;\n\t\n\tFILE* fp = fopen(fileName,\"r\");\n\t\n\tfgets(str,MAX_LEN,fp);\n\tcoeff1 = extractVector(str);\n\t\n\tfgets(str,MAX_LEN,fp);\n\tcoeff2 = extractVector(str);\n\t\n\tfgets(str,MAX_LEN,fp);\n\tsignal = extractVector(str);\n\n fclose(fp);\n\t\n\tfilteredSignal.values = (float*)calloc(signal.size,sizeof(float));\n\tfilteredSignal.size = signal.size;\n\t\n\tfor(i=0;i=0)\n\t\t\t\tsum += coeff2.values[j]*signal.values[i-j];\n\t\t}\n\t\t\n\t\tfor(j=0;j=0)\n\t\t\t\tsum -= coeff1.values[j]*filteredSignal.values[i-j];\n\t\t}\n\t\t\n\t\tsum /= coeff1.values[0];\n\t\tfilteredSignal.values[i] = sum;\n\t}\n\t\n\treturn filteredSignal;\n}\n\nvoid printVector(vector v, char* outputFile){\n\tint i;\n\t\n\tif(outputFile==NULL){\n\t\tprintf(\"[\");\n\t\tfor(i=0;i3)\n\t\tprintf(\"Usage : %s \",argV[0]);\n\telse{\n\t\tif(argC!=2){\n\t\t\tstr = (char*)malloc((strlen(argV[2]) + strlen(str) + 1)*sizeof(char));\n\t\t\tstrcpy(str,\"written to \");\n\t\t}\n\t\tprintf(\"Filtered signal %s\",(argC==2)?\"is:\\n\":strcat(str,argV[2]));\n\t\tprintVector(processSignalFile(argV[1]),argV[2]);\n\t}\n\treturn 0;\n}\n"} -{"title": "Apply a digital filter (direct form II transposed)", "language": "C++", "task": "Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the \"direct form II transposed\" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [https://ccrma.stanford.edu/~jos/fp/Transposed_Direct_Forms.html]\n\n;Task:\n\nFilter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667]\n\nThe signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]\n\n;See also:\n[Wikipedia on Butterworth filters]\n\n\n", "solution": "#include \n#include \nusing namespace std;\n\nvoid Filter(const vector &b, const vector &a, const vector &in, vector &out)\n{\n\n\tout.resize(0);\n\tout.resize(in.size());\n\n\tfor(int i=0; i < in.size(); i++)\n\t{\n\t\tfloat tmp = 0.;\n\t\tint j=0;\n\t\tout[i] = 0.f;\n\t\tfor(j=0; j < b.size(); j++)\n\t\t{\n\t\t\tif(i - j < 0) continue;\n\t\t\ttmp += b[j] * in[i-j];\n\t\t}\n\n\t\tfor(j=1; j < a.size(); j++)\n\t\t{\n\t\t\tif(i - j < 0) continue;\n\t\t\ttmp -= a[j]*out[i-j];\n\t\t}\n\t\t\n\t\ttmp /= a[0];\n\t\tout[i] = tmp;\n\t}\n}\n\nint main()\n{\n\tvector sig = {-0.917843918645,0.141984778794,1.20536903482,0.190286794412,-0.662370894973,-1.00700480494,\\\n\t\t-0.404707073677,0.800482325044,0.743500089861,1.01090520172,0.741527555207,\\\n\t\t0.277841675195,0.400833448236,-0.2085993586,-0.172842103641,-0.134316096293,\\\n\t\t0.0259303398477,0.490105989562,0.549391221511,0.9047198589};\n\n\t//Constants for a Butterworth filter (order 3, low pass)\n\tvector a = {1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17};\n\tvector b = {0.16666667, 0.5, 0.5, 0.16666667};\n\t\n\tvector result;\n\tFilter(b, a, sig, result);\n\n\tfor(size_t i=0;i\n#include \n#include \n\nbool approxEquals(double a, double b, double e) {\n return fabs(a - b) < e;\n}\n\nvoid test(double a, double b) {\n constexpr double epsilon = 1e-18;\n std::cout << std::setprecision(21) << a;\n std::cout << \", \";\n std::cout << std::setprecision(21) << b;\n std::cout << \" => \";\n std::cout << approxEquals(a, b, epsilon) << '\\n';\n}\n\nint main() {\n test(100000000000000.01, 100000000000000.011);\n test(100.01, 100.011);\n test(10000000000000.001 / 10000.0, 1000000000.0000001000);\n test(0.001, 0.0010000001);\n test(0.000000000000000000000101, 0.0);\n test(sqrt(2.0) * sqrt(2.0), 2.0);\n test(-sqrt(2.0) * sqrt(2.0), -2.0);\n test(3.14159265358979323846, 3.14159265358979324);\n return 0;\n}"} -{"title": "Approximate equality", "language": "Python", "task": "Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the\ndifference in floating point calculations between different language implementations becomes significant. \n\nFor example, a difference between '''32''' bit and '''64''' bit floating point calculations may appear by \nabout the 8th significant digit in base 10 arithmetic.\n\n\n;Task:\nCreate a function which returns true if two floating point numbers are approximately equal. \n\n\nThe function should allow for differences in the magnitude of numbers, so that, for example, \n'''100000000000000.01''' may be approximately equal to '''100000000000000.011''', \neven though '''100.01''' is not approximately equal to '''100.011'''.\n\nIf the language has such a feature in its standard library, this may be used instead of a custom function.\n\nShow the function results with comparisons on the following pairs of values:\n:# 100000000000000.01, 100000000000000.011 (note: should return ''true'')\n:# 100.01, 100.011 (note: should return ''false'')\n:# 10000000000000.001 / 10000.0, 1000000000.0000001000\n:# 0.001, 0.0010000001\n:# 0.000000000000000000000101, 0.0\n:# sqrt(2) * sqrt(2), 2.0\n:# -sqrt(2) * sqrt(2), -2.0\n:# 3.14159265358979323846, 3.14159265358979324\n\nAnswers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.\n\n\n__TOC__\n\n", "solution": "from numpy import sqrt\nfrom math import isclose\n\ntestvalues = [[100000000000000.01, 100000000000000.011],\n [100.01, 100.011],\n [10000000000000.001 / 10000.0, 1000000000.0000001000],\n [0.001, 0.0010000001],\n [0.000000000000000000000101, 0.0],\n [sqrt(2) * sqrt(2), 2.0],\n [-sqrt(2) * sqrt(2), -2.0],\n [3.14159265358979323846, 3.14159265358979324]]\n\nfor (x, y) in testvalues:\n maybenot = \"is\" if isclose(x, y) else \"is NOT\"\n print(x, maybenot, \"approximately equal to \", y)\n\n"} -{"title": "Archimedean spiral", "language": "C", "task": "The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. \n\n\nAn Archimedean spiral can be described by the equation:\n\n:\\, r=a+b\\theta\n\nwith real numbers ''a'' and ''b''.\n\n\n;Task\nDraw an Archimedean spiral.\n\n", "solution": "#include\n#include\n#include\n\n#define pi M_PI\n\nint main(){\n\tdouble a,b,cycles,incr,i;\n\t\n\tint steps,x=500,y=500;\n\t\n\tprintf(\"Enter the parameters a and b : \");\n\tscanf(\"%lf%lf\",&a,&b);\n\t\n\tprintf(\"Enter cycles : \");\n\tscanf(\"%lf\",&cycles);\n\t\n\tprintf(\"Enter divisional steps : \");\n\tscanf(\"%d\",&steps);\n\t\n\tincr = 1.0/steps;\n\t\n\tinitwindow(1000,1000,\"Archimedean Spiral\");\n\t\n\tfor(i=0;i<=cycles*pi;i+=incr){\n\t\tputpixel(x + (a + b*i)*cos(i),x + (a + b*i)*sin(i),15);\n\t}\n\t\n\tgetch();\n\t\n\tclosegraph();\t\n}\n"} -{"title": "Archimedean spiral", "language": "C++", "task": "The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. \n\n\nAn Archimedean spiral can be described by the equation:\n\n:\\, r=a+b\\theta\n\nwith real numbers ''a'' and ''b''.\n\n\n;Task\nDraw an Archimedean spiral.\n\n", "solution": "#include \n#include \n#include \n \nconst int BMP_SIZE = 600;\n \nclass myBitmap {\npublic:\n myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n ~myBitmap() {\n DeleteObject( pen ); DeleteObject( brush );\n DeleteDC( hdc ); DeleteObject( bmp );\n }\n bool create( int w, int h ) {\n BITMAPINFO bi;\n ZeroMemory( &bi, sizeof( bi ) );\n bi.bmiHeader.biSize = sizeof( bi.bmiHeader );\n bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n bi.bmiHeader.biCompression = BI_RGB;\n bi.bmiHeader.biPlanes = 1;\n bi.bmiHeader.biWidth = w;\n bi.bmiHeader.biHeight = -h;\n HDC dc = GetDC( GetConsoleWindow() );\n bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n if( !bmp ) return false;\n hdc = CreateCompatibleDC( dc );\n SelectObject( hdc, bmp );\n ReleaseDC( GetConsoleWindow(), dc );\n width = w; height = h;\n return true;\n }\n void clear( BYTE clr = 0 ) {\n memset( pBits, clr, width * height * sizeof( DWORD ) );\n }\n void setBrushColor( DWORD bClr ) {\n if( brush ) DeleteObject( brush );\n brush = CreateSolidBrush( bClr );\n SelectObject( hdc, brush );\n }\n void setPenColor( DWORD c ) {\n clr = c; createPen();\n }\n void setPenWidth( int w ) {\n wid = w; createPen();\n }\n void saveBitmap( std::string path ) {\n BITMAPFILEHEADER fileheader;\n BITMAPINFO infoheader;\n BITMAP bitmap;\n DWORD wb;\n GetObject( bmp, sizeof( bitmap ), &bitmap );\n DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n infoheader.bmiHeader.biCompression = BI_RGB;\n infoheader.bmiHeader.biPlanes = 1;\n infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n fileheader.bfType = 0x4D42;\n fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n FILE_ATTRIBUTE_NORMAL, NULL );\n WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n CloseHandle( file );\n delete [] dwpBits;\n }\n HDC getDC() const { return hdc; }\n int getWidth() const { return width; }\n int getHeight() const { return height; }\nprivate:\n void createPen() {\n if( pen ) DeleteObject( pen );\n pen = CreatePen( PS_SOLID, wid, clr );\n SelectObject( hdc, pen );\n }\n HBITMAP bmp; HDC hdc;\n HPEN pen; HBRUSH brush;\n void *pBits; int width, height, wid;\n DWORD clr;\n};\nclass spiral {\npublic:\n spiral() {\n bmp.create( BMP_SIZE, BMP_SIZE );\n }\n void draw( int c, int s ) {\n double a = .2, b = .3, r, x, y;\n int w = BMP_SIZE >> 1;\n HDC dc = bmp.getDC();\n for( double d = 0; d < c * 6.28318530718; d += .002 ) {\n r = a + b * d; x = r * cos( d ); y = r * sin( d );\n SetPixel( dc, ( int )( s * x + w ), ( int )( s * y + w ), 255 );\n }\n // saves the bitmap\n bmp.saveBitmap( \"./spiral.bmp\" );\n }\nprivate:\n myBitmap bmp;\n};\nint main(int argc, char* argv[]) {\n spiral s; s.draw( 16, 8 ); return 0;\n}\n"} -{"title": "Archimedean spiral", "language": "Python", "task": "The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. \n\n\nAn Archimedean spiral can be described by the equation:\n\n:\\, r=a+b\\theta\n\nwith real numbers ''a'' and ''b''.\n\n\n;Task\nDraw an Archimedean spiral.\n\n", "solution": "from turtle import *\nfrom math import *\ncolor(\"blue\")\ndown()\nfor i in range(200):\n t = i / 20 * pi\n x = (1 + 5 * t) * cos(t)\n y = (1 + 5 * t) * sin(t)\n goto(x, y)\nup()\ndone()"} -{"title": "Arena storage pool", "language": "C", "task": "Dynamically allocated objects take their memory from a [[heap]]. \n\nThe memory for an object is provided by an '''allocator''' which maintains the storage pool used for the [[heap]].\n\nOften a call to allocator is denoted as\nP := new T\nwhere '''T''' is the type of an allocated object, and '''P''' is a [[reference]] to the object.\n\nThe storage pool chosen by the allocator can be determined by either:\n* the object type '''T'''\n* the type of pointer '''P'''\n\n\nIn the former case objects can be allocated only in one storage pool. \n\nIn the latter case objects of the type can be allocated in any storage pool or on the [[stack]].\n\n\n;Task:\nThe task is to show how allocators and user-defined storage pools are supported by the language. \n\nIn particular:\n# define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.\n# allocate some objects (e.g., integers) in the pool.\n\n\nExplain what controls the storage pool choice in the language.\n\n", "solution": "#include \n#include \n#include \n\n// VERY rudimentary C memory management independent of C library's malloc.\n\n// Linked list (yes, this is inefficient)\nstruct __ALLOCC_ENTRY__\n{\n void * allocatedAddr;\n size_t size;\n struct __ALLOCC_ENTRY__ * next;\n};\ntypedef struct __ALLOCC_ENTRY__ __ALLOCC_ENTRY__;\n\n// Keeps track of allocated memory and metadata\n__ALLOCC_ENTRY__ * __ALLOCC_ROOT__ = NULL;\n__ALLOCC_ENTRY__ * __ALLOCC_TAIL__ = NULL;\n\n// Add new metadata to the table\nvoid _add_mem_entry(void * location, size_t size)\n{\n \n __ALLOCC_ENTRY__ * newEntry = (__ALLOCC_ENTRY__ *) mmap(NULL, sizeof(__ALLOCC_ENTRY__), PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);\n \n if (__ALLOCC_TAIL__ != NULL)\n {\n __ALLOCC_TAIL__ -> next = newEntry;\n __ALLOCC_TAIL__ = __ALLOCC_TAIL__ -> next;\n }\n else\n {\n // Create new table\n __ALLOCC_ROOT__ = newEntry;\n __ALLOCC_TAIL__ = newEntry;\n }\n \n __ALLOCC_ENTRY__ * tail = __ALLOCC_TAIL__;\n tail -> allocatedAddr = location;\n tail -> size = size;\n tail -> next = NULL;\n __ALLOCC_TAIL__ = tail;\n}\n\n// Remove metadata from the table given pointer\nsize_t _remove_mem_entry(void * location)\n{\n __ALLOCC_ENTRY__ * curNode = __ALLOCC_ROOT__;\n \n // Nothing to do\n if (curNode == NULL)\n {\n return 0;\n }\n \n // First entry matches\n if (curNode -> allocatedAddr == location)\n {\n __ALLOCC_ROOT__ = curNode -> next;\n size_t chunkSize = curNode -> size;\n \n // No nodes left\n if (__ALLOCC_ROOT__ == NULL)\n {\n __ALLOCC_TAIL__ = NULL;\n }\n munmap(curNode, sizeof(__ALLOCC_ENTRY__));\n \n return chunkSize;\n }\n \n // If next node is null, remove it\n while (curNode -> next != NULL)\n {\n __ALLOCC_ENTRY__ * nextNode = curNode -> next;\n \n if (nextNode -> allocatedAddr == location)\n {\n size_t chunkSize = nextNode -> size;\n \n if(curNode -> next == __ALLOCC_TAIL__)\n {\n __ALLOCC_TAIL__ = curNode;\n }\n curNode -> next = nextNode -> next;\n munmap(nextNode, sizeof(__ALLOCC_ENTRY__));\n \n return chunkSize;\n }\n \n curNode = nextNode;\n }\n \n // Nothing was found\n return 0;\n}\n\n// Allocate a block of memory with size\n// When customMalloc an already mapped location, causes undefined behavior\nvoid * customMalloc(size_t size)\n{\n // Now we can use 0 as our error state\n if (size == 0)\n {\n return NULL;\n }\n \n void * mapped = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);\n \n // Store metadata\n _add_mem_entry(mapped, size);\n \n return mapped;\n}\n\n// Free a block of memory that has been customMalloc'ed\nvoid customFree(void * addr)\n{\n size_t size = _remove_mem_entry(addr);\n \n munmap(addr, size);\n}\n\nint main(int argc, char const *argv[])\n{\n int *p1 = customMalloc(4*sizeof(int)); // allocates enough for an array of 4 int\n int *p2 = customMalloc(sizeof(int[4])); // same, naming the type directly\n int *p3 = customMalloc(4*sizeof *p3); // same, without repeating the type name\n \n if(p1) {\n for(int n=0; n<4; ++n) // populate the array\n p1[n] = n*n;\n for(int n=0; n<4; ++n) // print it back out\n printf(\"p1[%d] == %d\\n\", n, p1[n]);\n }\n \n customFree(p1);\n customFree(p2);\n customFree(p3);\n \n return 0;\n}"} -{"title": "Arena storage pool", "language": "C++", "task": "Dynamically allocated objects take their memory from a [[heap]]. \n\nThe memory for an object is provided by an '''allocator''' which maintains the storage pool used for the [[heap]].\n\nOften a call to allocator is denoted as\nP := new T\nwhere '''T''' is the type of an allocated object, and '''P''' is a [[reference]] to the object.\n\nThe storage pool chosen by the allocator can be determined by either:\n* the object type '''T'''\n* the type of pointer '''P'''\n\n\nIn the former case objects can be allocated only in one storage pool. \n\nIn the latter case objects of the type can be allocated in any storage pool or on the [[stack]].\n\n\n;Task:\nThe task is to show how allocators and user-defined storage pools are supported by the language. \n\nIn particular:\n# define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.\n# allocate some objects (e.g., integers) in the pool.\n\n\nExplain what controls the storage pool choice in the language.\n\n", "solution": "#include \n#include \n#include \n\n// This class basically provides a global stack of pools; it is not thread-safe, and pools must be destructed in reverse order of construction\n// (you definitely want something better in production use :-))\nclass Pool\n{\npublic:\n Pool(std::size_type sz);\n ~Pool();\n static Pool& current() { return *cur; }\n void* allocate(std::size_type sz, std::size_t alignment);\nprivate:\n char* memory; // char* instead of void* enables pointer arithmetic\n char* free;\n char* end;\n Pool* prev;\n static Pool* cur;\n\n // prohibit copying\n Pool(Pool const&); // not implemented\n Pool& operator=(Pool const&); // not implemented\n};\n\nPool* pool::cur = 0;\n\nPool::Pool(std::size_type size):\n memory(static_cast(::operator new(size))),\n free(memory),\n end(memory + size))\n{\n prev = cur;\n cur = this;\n}\n\nPool::~Pool()\n{\n ::operator delete(memory);\n cur = prev;\n}\n\nvoid* Pool::allocate(std::size_t size, std::size_t alignment)\n{\n char* start = free;\n\n // align the pointer\n std::size_t extra = (start - memory) % aligment;\n if (extra != 0)\n {\n extra = alignment - extra;\n }\n\n // test if we can still allocate that much memory\n if (end - free < size + extra)\n throw std::bad_alloc();\n\n // the free memory now starts after the newly allocated object\n free = start + size + extra;\n return start;\n}\n\n// this is just a simple C-like struct, except that it uses a specific allocation/deallocation function.\nstruct X\n{\n int member;\n void* operator new(std::size_t);\n void operator delete(void*) {} // don't deallocate memory for single objects\n};\n\nvoid* X::operator new(std::size_t size)\n{\n // unfortunately C++ doesn't offer a portable way to find out alignment\n // however, using the size as alignment is always safe (although usually wasteful)\n return Pool::current().allocate(size, size);\n}\n\n// Example program\nint main()\n{\n Pool my_pool(3*sizeof(X));\n X* p1 = new X; // uses the allocator function defined above\n X* p2 = new X;\n X* p3 = new X;\n delete p3; // doesn't really deallocate the memory because operator delete has an empty body\n\n try\n {\n X* p4 = new X; // should fail\n assert(false);\n }\n catch(...)\n {\n }\n\n X* p5 = new X[10]; // uses global array allocation routine because we didn't provide operator new[] and operator delete[]\n delete[] p5; // global array deallocation\n\n Pool* my_second_pool(1000); // a large pool\n X* p6 = new X; // allocate a new object from that pool\n X* p7 = new X;\n delete my_second_pool // also deallocates the memory for p6 and p7\n\n} // Here my_pool goes out of scope, deallocating the memory for p1, p2 and p3"} -{"title": "Arena storage pool", "language": "Python", "task": "Dynamically allocated objects take their memory from a [[heap]]. \n\nThe memory for an object is provided by an '''allocator''' which maintains the storage pool used for the [[heap]].\n\nOften a call to allocator is denoted as\nP := new T\nwhere '''T''' is the type of an allocated object, and '''P''' is a [[reference]] to the object.\n\nThe storage pool chosen by the allocator can be determined by either:\n* the object type '''T'''\n* the type of pointer '''P'''\n\n\nIn the former case objects can be allocated only in one storage pool. \n\nIn the latter case objects of the type can be allocated in any storage pool or on the [[stack]].\n\n\n;Task:\nThe task is to show how allocators and user-defined storage pools are supported by the language. \n\nIn particular:\n# define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.\n# allocate some objects (e.g., integers) in the pool.\n\n\nExplain what controls the storage pool choice in the language.\n\n", "solution": "In Python:\n* Everything is an object.\n* Objects are dynamically allocated.\n* Unused objects are garbage collected.\n\nWhere objects appear from, or disappear to, is treated as an implementation detail.\n\nStatements, such as assignments, class and function definitions, and import statements can create objects and assign names to them which can be seen as assigning a reference to objects. Objects can also be referred to from other objects e.g. in collections such as lists.
\nWhen names go out of scope, or objects are explicitly destroyed, references to objects are diminished. Python's implementation keeps track of references to objects and marks objects that have no remaining references so that they become candidates for '[[wp:Garbage collection (computer science)|garbage collection]]' at a later time.\n\n"} -{"title": "Arithmetic-geometric mean", "language": "C", "task": "{{wikipedia|Arithmetic-geometric mean}}\n\n\n;Task:\nWrite a function to compute the arithmetic-geometric mean of two numbers.\n\n\nThe arithmetic-geometric mean of two numbers can be (usefully) denoted as \\mathrm{agm}(a,g), and is equal to the limit of the sequence:\n: a_0 = a; \\qquad g_0 = g\n: a_{n+1} = \\tfrac{1}{2}(a_n + g_n); \\quad g_{n+1} = \\sqrt{a_n g_n}.\nSince the limit of a_n-g_n tends (rapidly) to zero with iterations, this is an efficient method.\n\nDemonstrate the function by calculating:\n:\\mathrm{agm}(1,1/\\sqrt{2})\n \n\n;Also see:\n* mathworld.wolfram.com/Arithmetic-Geometric Mean\n\n", "solution": "/*Arithmetic Geometric Mean of 1 and 1/sqrt(2)\n\n Nigel_Galloway\n February 7th., 2012.\n*/\n\n#include \"gmp.h\"\n\nvoid agm (const mpf_t in1, const mpf_t in2, mpf_t out1, mpf_t out2) {\n\tmpf_add (out1, in1, in2);\n\tmpf_div_ui (out1, out1, 2);\n\tmpf_mul (out2, in1, in2);\n\tmpf_sqrt (out2, out2);\n}\n\nint main (void) {\n\tmpf_set_default_prec (65568);\n\tmpf_t x0, y0, resA, resB;\n\n\tmpf_init_set_ui (y0, 1);\n\tmpf_init_set_d (x0, 0.5);\n\tmpf_sqrt (x0, x0);\n\tmpf_init (resA);\n\tmpf_init (resB);\n\n\tfor(int i=0; i<7; i++){\n\t\tagm(x0, y0, resA, resB);\n\t\tagm(resA, resB, x0, y0);\n\t}\n\tgmp_printf (\"%.20000Ff\\n\", x0);\n\tgmp_printf (\"%.20000Ff\\n\\n\", y0);\n\n\treturn 0;\n}"} -{"title": "Arithmetic-geometric mean", "language": "C++", "task": "{{wikipedia|Arithmetic-geometric mean}}\n\n\n;Task:\nWrite a function to compute the arithmetic-geometric mean of two numbers.\n\n\nThe arithmetic-geometric mean of two numbers can be (usefully) denoted as \\mathrm{agm}(a,g), and is equal to the limit of the sequence:\n: a_0 = a; \\qquad g_0 = g\n: a_{n+1} = \\tfrac{1}{2}(a_n + g_n); \\quad g_{n+1} = \\sqrt{a_n g_n}.\nSince the limit of a_n-g_n tends (rapidly) to zero with iterations, this is an efficient method.\n\nDemonstrate the function by calculating:\n:\\mathrm{agm}(1,1/\\sqrt{2})\n \n\n;Also see:\n* mathworld.wolfram.com/Arithmetic-Geometric Mean\n\n", "solution": "#include\nusing namespace std;\n#define _cin\tios_base::sync_with_stdio(0);\tcin.tie(0);\n#define rep(a, b)\tfor(ll i =a;i<=b;++i)\n\ndouble agm(double a, double g)\t\t//ARITHMETIC GEOMETRIC MEAN\n{\tdouble epsilon = 1.0E-16,a1,g1;\n\tif(a*g<0.0)\n\t{\tcout<<\"Couldn't find arithmetic-geometric mean of these numbers\\n\";\n\t\texit(1);\n\t}\n\twhile(fabs(a-g)>epsilon)\n\t{\ta1 = (a+g)/2.0;\n\t\tg1 = sqrt(a*g);\n\t\ta = a1;\n\t\tg = g1;\n\t}\n\treturn a;\n}\n\nint main()\n{\t_cin; //fast input-output\n\tdouble x, y;\n\tcout<<\"Enter X and Y: \";\t//Enter two numbers\n\tcin>>x>>y;\n\tcout<<\"\\nThe Arithmetic-Geometric Mean of \"< {\n 'use strict';\n\n // ARITHMETIC-GEOMETRIC MEAN\n\n // agm :: Num a => a -> a -> a\n let agm = (a, g) => {\n let abs = Math.abs,\n sqrt = Math.sqrt;\n\n return until(\n m => abs(m.an - m.gn) < tolerance,\n m => {\n return {\n an: (m.an + m.gn) / 2,\n gn: sqrt(m.an * m.gn)\n };\n }, {\n an: (a + g) / 2,\n gn: sqrt(a * g)\n }\n )\n .an;\n },\n\n // GENERIC\n\n // until :: (a -> Bool) -> (a -> a) -> a -> a\n until = (p, f, x) => {\n let v = x;\n while (!p(v)) v = f(v);\n return v;\n };\n\n\n // TEST\n\n let tolerance = 0.000001;\n\n\n return agm(1, 1 / Math.sqrt(2));\n\n})();"} -{"title": "Arithmetic-geometric mean", "language": "Python", "task": "{{wikipedia|Arithmetic-geometric mean}}\n\n\n;Task:\nWrite a function to compute the arithmetic-geometric mean of two numbers.\n\n\nThe arithmetic-geometric mean of two numbers can be (usefully) denoted as \\mathrm{agm}(a,g), and is equal to the limit of the sequence:\n: a_0 = a; \\qquad g_0 = g\n: a_{n+1} = \\tfrac{1}{2}(a_n + g_n); \\quad g_{n+1} = \\sqrt{a_n g_n}.\nSince the limit of a_n-g_n tends (rapidly) to zero with iterations, this is an efficient method.\n\nDemonstrate the function by calculating:\n:\\mathrm{agm}(1,1/\\sqrt{2})\n \n\n;Also see:\n* mathworld.wolfram.com/Arithmetic-Geometric Mean\n\n", "solution": "from math import sqrt\n\ndef agm(a0, g0, tolerance=1e-10):\n \"\"\"\n Calculating the arithmetic-geometric mean of two numbers a0, g0.\n\n tolerance the tolerance for the converged \n value of the arithmetic-geometric mean\n (default value = 1e-10)\n \"\"\"\n an, gn = (a0 + g0) / 2.0, sqrt(a0 * g0)\n while abs(an - gn) > tolerance:\n an, gn = (an + gn) / 2.0, sqrt(an * gn)\n return an\n\nprint agm(1, 1 / sqrt(2))"} -{"title": "Arithmetic-geometric mean/Calculate Pi", "language": "C", "task": "Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate \\pi.\n\nWith the same notations used in [[Arithmetic-geometric mean]], we can summarize the paper by writing:\n\n\\pi =\n\\frac{4\\; \\mathrm{agm}(1, 1/\\sqrt{2})^2}\n{1 - \\sum\\limits_{n=1}^{\\infty} 2^{n+1}(a_n^2-g_n^2)}\n\n\nThis allows you to make the approximation, for any large '''N''':\n\n\\pi \\approx\n\\frac{4\\; a_N^2}\n{1 - \\sum\\limits_{k=1}^N 2^{k+1}(a_k^2-g_k^2)}\n\n\nThe purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of \\pi.\n\n", "solution": "See [[Talk:Arithmetic-geometric mean]]\n\n"} -{"title": "Arithmetic-geometric mean/Calculate Pi", "language": "Python from Ruby", "task": "Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate \\pi.\n\nWith the same notations used in [[Arithmetic-geometric mean]], we can summarize the paper by writing:\n\n\\pi =\n\\frac{4\\; \\mathrm{agm}(1, 1/\\sqrt{2})^2}\n{1 - \\sum\\limits_{n=1}^{\\infty} 2^{n+1}(a_n^2-g_n^2)}\n\n\nThis allows you to make the approximation, for any large '''N''':\n\n\\pi \\approx\n\\frac{4\\; a_N^2}\n{1 - \\sum\\limits_{k=1}^N 2^{k+1}(a_k^2-g_k^2)}\n\n\nThe purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of \\pi.\n\n", "solution": "from decimal import *\n\nD = Decimal\ngetcontext().prec = 100\na = n = D(1)\ng, z, half = 1 / D(2).sqrt(), D(0.25), D(0.5)\nfor i in range(18):\n x = [(a + g) * half, (a * g).sqrt()]\n var = x[0] - a\n z -= var * var * n\n n += n\n a, g = x \nprint(a * a / z)"} -{"title": "Arithmetic derivative", "language": "Python", "task": "The '''arithmetic derivative''' of an integer (more specifically, the\n'''Lagarias arithmetic derivative''') is a function defined for integers, based on prime\nfactorization, by analogy with the product rule for the derivative of a function that is\nused in mathematical analysis. Accordingly, for natural numbers n, the arithmetic \nderivative D(n) is defined as follows:\n\n;*D(0) = D(1) = 0.\n;*D(p) = 1 for any prime p.\n;*D(mn) = D(m)n + mD(n) for any m,n N. (Leibniz rule for derivatives).\n\nAdditionally, for negative integers the arithmetic derivative may be defined as -D(-n) (n < 0).\n\n; Examples\n\nD(2) = 1 and D(3) = 1 (both are prime) so if mn = 2 * 3, D(6) = (1)(3) + (1)(2) = 5.\n\nD(9) = D(3)(3) + D(3)(3) = 6\n\nD(27) = D(3)*9 + D(9)*3 = 9 + 18 = 27\n\nD(30) = D(5)(6) + D(6)(5) = 6 + 5 * 5 = 31.\n\n; Task\n\nFind and show the arithmetic derivatives for -99 through 100.\n\n; Stretch task\n\nFind (the arithmetic derivative of 10^m) then divided by 7, where m is from 1 to 20.\n\n; See also\n\n;* OEIS:A003415 - a(n) = n' = arithmetic derivative of n.\n;*Wikipedia: Arithmetic Derivative\n\n\n", "solution": "from sympy.ntheory import factorint\n\ndef D(n):\n if n < 0:\n return -D(-n)\n elif n < 2:\n return 0\n else:\n fdict = factorint(n)\n if len(fdict) == 1 and 1 in fdict: # is prime\n return 1\n return sum([n * e // p for p, e in fdict.items()])\n\nfor n in range(-99, 101):\n print('{:5}'.format(D(n)), end='\\n' if n % 10 == 0 else '')\n\nprint()\nfor m in range(1, 21):\n print('(D for 10**{}) divided by 7 is {}'.format(m, D(10 ** m) // 7))\n\n"} -{"title": "Arithmetic evaluation", "language": "JavaScript", "task": "Create a program which parses and evaluates arithmetic expressions.\n;Requirements:\n* An abstract-syntax tree (AST) for the expression must be created from parsing the input. \n* The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) \n* The expression will be a string or list of symbols like \"(1+3)*7\". \n* The four symbols + - * / must be supported as binary operators with conventional precedence rules. \n* Precedence-control parentheses must also be supported.\n\n\n;Note:\nFor those who don't remember, mathematical precedence is as follows:\n* Parentheses\n* Multiplication/Division (left to right)\n* Addition/Subtraction (left to right)\n\n\n;C.f: \n* [[24 game Player]].\n* [[Parsing/RPN calculator algorithm]].\n* [[Parsing/RPN to infix conversion]].\n\n", "solution": "function evalArithmeticExp(s) {\n s = s.replace(/\\s/g,'').replace(/^\\+/,'');\n var rePara = /\\([^\\(\\)]*\\)/;\n var exp = s.match(rePara);\n\n while (exp = s.match(rePara)) {\n s = s.replace(exp[0], evalExp(exp[0]));\n }\n return evalExp(s);\n \n function evalExp(s) {\n s = s.replace(/[\\(\\)]/g,'');\n var reMD = /\\d+\\.?\\d*\\s*[\\*\\/]\\s*[+-]?\\d+\\.?\\d*/;\n var reM = /\\*/;\n var reAS = /-?\\d+\\.?\\d*\\s*[\\+-]\\s*[+-]?\\d+\\.?\\d*/;\n var reA = /\\d\\+/;\n var exp;\n\n while (exp = s.match(reMD)) {\n s = exp[0].match(reM)? s.replace(exp[0], multiply(exp[0])) : s.replace(exp[0], divide(exp[0]));\n }\n \n while (exp = s.match(reAS)) {\n s = exp[0].match(reA)? s.replace(exp[0], add(exp[0])) : s.replace(exp[0], subtract(exp[0]));\n }\n \n return '' + s;\n\n function multiply(s, b) {\n b = s.split('*');\n return b[0] * b[1];\n }\n \n function divide(s, b) {\n b = s.split('/');\n return b[0] / b[1];\n }\n \n function add(s, b) {\n s = s.replace(/^\\+/,'').replace(/\\++/,'+');\n b = s.split('+');\n return Number(b[0]) + Number(b[1]);\n }\n \n function subtract(s, b) {\n s = s.replace(/\\+-|-\\+/g,'-');\n\n if (s.match(/--/)) {\n return add(s.replace(/--/,'+'));\n }\n b = s.split('-');\n return b.length == 3? -1 * b[1] - b[2] : b[0] - b[1];\n }\n }\n}"} -{"title": "Arithmetic evaluation", "language": "Python", "task": "Create a program which parses and evaluates arithmetic expressions.\n;Requirements:\n* An abstract-syntax tree (AST) for the expression must be created from parsing the input. \n* The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) \n* The expression will be a string or list of symbols like \"(1+3)*7\". \n* The four symbols + - * / must be supported as binary operators with conventional precedence rules. \n* Precedence-control parentheses must also be supported.\n\n\n;Note:\nFor those who don't remember, mathematical precedence is as follows:\n* Parentheses\n* Multiplication/Division (left to right)\n* Addition/Subtraction (left to right)\n\n\n;C.f: \n* [[24 game Player]].\n* [[Parsing/RPN calculator algorithm]].\n* [[Parsing/RPN to infix conversion]].\n\n", "solution": "import operator\n\nclass AstNode(object):\n def __init__( self, opr, left, right ):\n self.opr = opr\n self.l = left\n self.r = right\n\n def eval(self):\n return self.opr(self.l.eval(), self.r.eval())\n\nclass LeafNode(object):\n def __init__( self, valStrg ):\n self.v = int(valStrg)\n\n def eval(self):\n return self.v\n\nclass Yaccer(object):\n def __init__(self):\n self.operstak = []\n self.nodestak =[]\n self.__dict__.update(self.state1)\n\n def v1( self, valStrg ):\n # Value String\n self.nodestak.append( LeafNode(valStrg))\n self.__dict__.update(self.state2)\n #print 'push', valStrg\n\n def o2( self, operchar ):\n # Operator character or open paren in state1\n def openParen(a,b):\n return 0\t\t# function should not be called\n\n opDict= { '+': ( operator.add, 2, 2 ),\n '-': (operator.sub, 2, 2 ),\n '*': (operator.mul, 3, 3 ),\n '/': (operator.div, 3, 3 ),\n '^': ( pow, 4, 5 ), # right associative exponentiation for grins\n '(': ( openParen, 0, 8 )\n }\n operPrecidence = opDict[operchar][2]\n self.redeuce(operPrecidence)\n\n self.operstak.append(opDict[operchar])\n self.__dict__.update(self.state1)\n # print 'pushop', operchar\n\n def syntaxErr(self, char ):\n # Open Parenthesis \n print 'parse error - near operator \"%s\"' %char\n\n def pc2( self,operchar ):\n # Close Parenthesis\n # reduce node until matching open paren found \n self.redeuce( 1 )\n if len(self.operstak)>0:\n self.operstak.pop()\t\t# pop off open parenthesis\n else:\n print 'Error - no open parenthesis matches close parens.'\n self.__dict__.update(self.state2)\n\n def end(self):\n self.redeuce(0)\n return self.nodestak.pop()\n\n def redeuce(self, precidence):\n while len(self.operstak)>0:\n tailOper = self.operstak[-1]\n if tailOper[1] < precidence: break\n\n tailOper = self.operstak.pop()\n vrgt = self.nodestak.pop()\n vlft= self.nodestak.pop()\n self.nodestak.append( AstNode(tailOper[0], vlft, vrgt))\n # print 'reduce'\n\n state1 = { 'v': v1, 'o':syntaxErr, 'po':o2, 'pc':syntaxErr }\n state2 = { 'v': syntaxErr, 'o':o2, 'po':syntaxErr, 'pc':pc2 }\n\n\ndef Lex( exprssn, p ):\n bgn = None\n cp = -1\n for c in exprssn:\n cp += 1\n if c in '+-/*^()': # throw in exponentiation (^)for grins\n if bgn is not None:\n p.v(p, exprssn[bgn:cp])\n bgn = None\n if c=='(': p.po(p, c)\n elif c==')':p.pc(p, c)\n else: p.o(p, c)\n elif c in ' \\t':\n if bgn is not None:\n p.v(p, exprssn[bgn:cp])\n bgn = None\n elif c in '0123456789':\n if bgn is None:\n bgn = cp\n else:\n print 'Invalid character in expression'\n if bgn is not None:\n p.v(p, exprssn[bgn:cp])\n bgn = None\n \n if bgn is not None:\n p.v(p, exprssn[bgn:cp+1])\n bgn = None\n return p.end()\n\n\nexpr = raw_input(\"Expression:\")\nastTree = Lex( expr, Yaccer())\nprint expr, '=',astTree.eval()"} -{"title": "Arithmetic numbers", "language": "C", "task": "Definition\nA positive integer '''n''' is an arithmetic number if the average of its positive divisors is also an integer.\n\nClearly all odd primes '''p''' must be arithmetic numbers because their only divisors are '''1''' and '''p''' whose sum is even and hence their average must be an integer. However, the prime number '''2''' is not an arithmetic number because the average of its divisors is 1.5.\n\n;Example\n30 is an arithmetic number because its 7 divisors are: [1, 2, 3, 5, 6, 10, 15, 30], their sum is 72 and average 9 which is an integer. \n\n;Task\nCalculate and show here:\n\n1. The first 100 arithmetic numbers.\n\n2. The '''x'''th arithmetic number where '''x''' = 1,000 and '''x''' = 10,000.\n\n3. How many of the first '''x''' arithmetic numbers are composite.\n\nNote that, technically, the arithmetic number '''1''' is neither prime nor composite.\n\n;Stretch\nCarry out the same exercise in 2. and 3. above for '''x''' = 100,000 and '''x''' = 1,000,000.\n\n;References\n\n* Wikipedia: Arithmetic number\n* OEIS:A003601 - Numbers n such that the average of the divisors of n is an integer\n\n", "solution": "#include \n\nvoid divisor_count_and_sum(unsigned int n, unsigned int* pcount,\n unsigned int* psum) {\n unsigned int divisor_count = 1;\n unsigned int divisor_sum = 1;\n unsigned int power = 2;\n for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n ++divisor_count;\n divisor_sum += power;\n }\n for (unsigned int p = 3; p * p <= n; p += 2) {\n unsigned int count = 1, sum = 1;\n for (power = p; n % p == 0; power *= p, n /= p) {\n ++count;\n sum += power;\n }\n divisor_count *= count;\n divisor_sum *= sum;\n }\n if (n > 1) {\n divisor_count *= 2;\n divisor_sum *= n + 1;\n }\n *pcount = divisor_count;\n *psum = divisor_sum;\n}\n\nint main() {\n unsigned int arithmetic_count = 0;\n unsigned int composite_count = 0;\n\n for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) {\n unsigned int divisor_count;\n unsigned int divisor_sum;\n divisor_count_and_sum(n, &divisor_count, &divisor_sum);\n if (divisor_sum % divisor_count != 0)\n continue;\n ++arithmetic_count;\n if (divisor_count > 2)\n ++composite_count;\n if (arithmetic_count <= 100) {\n printf(\"%3u \", n);\n if (arithmetic_count % 10 == 0)\n printf(\"\\n\");\n }\n if (arithmetic_count == 1000 || arithmetic_count == 10000 ||\n arithmetic_count == 100000 || arithmetic_count == 1000000) {\n printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n,\n composite_count);\n }\n }\n return 0;\n}"} -{"title": "Arithmetic numbers", "language": "C++", "task": "Definition\nA positive integer '''n''' is an arithmetic number if the average of its positive divisors is also an integer.\n\nClearly all odd primes '''p''' must be arithmetic numbers because their only divisors are '''1''' and '''p''' whose sum is even and hence their average must be an integer. However, the prime number '''2''' is not an arithmetic number because the average of its divisors is 1.5.\n\n;Example\n30 is an arithmetic number because its 7 divisors are: [1, 2, 3, 5, 6, 10, 15, 30], their sum is 72 and average 9 which is an integer. \n\n;Task\nCalculate and show here:\n\n1. The first 100 arithmetic numbers.\n\n2. The '''x'''th arithmetic number where '''x''' = 1,000 and '''x''' = 10,000.\n\n3. How many of the first '''x''' arithmetic numbers are composite.\n\nNote that, technically, the arithmetic number '''1''' is neither prime nor composite.\n\n;Stretch\nCarry out the same exercise in 2. and 3. above for '''x''' = 100,000 and '''x''' = 1,000,000.\n\n;References\n\n* Wikipedia: Arithmetic number\n* OEIS:A003601 - Numbers n such that the average of the divisors of n is an integer\n\n", "solution": "#include \n\nvoid divisor_count_and_sum(unsigned int n,\n\t\t\t unsigned int& divisor_count,\n\t\t\t unsigned int& divisor_sum)\n{\n divisor_count = 0;\n divisor_sum = 0;\n for (unsigned int i = 1;; i++)\n {\n unsigned int j = n / i;\n if (j < i)\n break;\n if (i * j != n)\n continue;\n divisor_sum += i;\n divisor_count += 1;\n if (i != j)\n {\n divisor_sum += j;\n divisor_count += 1;\n }\n }\n}\n\nint main()\n{\n unsigned int arithmetic_count = 0;\n unsigned int composite_count = 0;\n\n for (unsigned int n = 1; arithmetic_count <= 1000000; n++)\n {\n unsigned int divisor_count;\n unsigned int divisor_sum;\n divisor_count_and_sum(n, divisor_count, divisor_sum);\n unsigned int mean = divisor_sum / divisor_count;\n if (mean * divisor_count != divisor_sum)\n continue;\n arithmetic_count++;\n if (divisor_count > 2)\n composite_count++;\n if (arithmetic_count <= 100)\n {\n // would prefer to use and in C++20\n std::printf(\"%3u \", n);\n if (arithmetic_count % 10 == 0)\n\tstd::printf(\"\\n\");\n }\n if ((arithmetic_count == 1000) || (arithmetic_count == 10000) ||\n\t(arithmetic_count == 100000) || (arithmetic_count == 1000000))\n {\n std::printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n std::printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n, composite_count);\n }\n }\n return 0;\n}"} -{"title": "Arithmetic numbers", "language": "Python", "task": "Definition\nA positive integer '''n''' is an arithmetic number if the average of its positive divisors is also an integer.\n\nClearly all odd primes '''p''' must be arithmetic numbers because their only divisors are '''1''' and '''p''' whose sum is even and hence their average must be an integer. However, the prime number '''2''' is not an arithmetic number because the average of its divisors is 1.5.\n\n;Example\n30 is an arithmetic number because its 7 divisors are: [1, 2, 3, 5, 6, 10, 15, 30], their sum is 72 and average 9 which is an integer. \n\n;Task\nCalculate and show here:\n\n1. The first 100 arithmetic numbers.\n\n2. The '''x'''th arithmetic number where '''x''' = 1,000 and '''x''' = 10,000.\n\n3. How many of the first '''x''' arithmetic numbers are composite.\n\nNote that, technically, the arithmetic number '''1''' is neither prime nor composite.\n\n;Stretch\nCarry out the same exercise in 2. and 3. above for '''x''' = 100,000 and '''x''' = 1,000,000.\n\n;References\n\n* Wikipedia: Arithmetic number\n* OEIS:A003601 - Numbers n such that the average of the divisors of n is an integer\n\n", "solution": "def factors(n: int):\n f = set([1, n])\n i = 2\n while True:\n j = n // i\n if j < i:\n break\n if i * j == n:\n f.add(i)\n f.add(j)\n i += 1\n return f\n\narithmetic_count = 0\ncomposite_count = 0\nn = 1\nwhile arithmetic_count <= 1000000:\n f = factors(n)\n if (sum(f)/len(f)).is_integer():\n arithmetic_count += 1\n if len(f) > 2:\n composite_count += 1\n if arithmetic_count <= 100:\n print(f'{n:3d} ', end='')\n if arithmetic_count % 10 == 0:\n print()\n if arithmetic_count in (1000, 10000, 100000, 1000000):\n print(f'\\n{arithmetic_count}th arithmetic number is {n}')\n print(f'Number of composite arithmetic numbers <= {n}: {composite_count}')\n n += 1"} -{"title": "Array length", "language": "C", "task": "Determine the amount of elements in an array.\n\n\nAs an example use an array holding the strings 'apple' and 'orange'.\n\n\n\n", "solution": "#define _CRT_SECURE_NO_WARNINGS // turn off panic warnings\n#define _CRT_NONSTDC_NO_WARNINGS // enable old-gold POSIX names in MSVS\n\n#include \n#include \n#include \n#include \n#include \n\n\nstruct StringArray\n{\n size_t sizeOfArray;\n size_t numberOfElements;\n char** elements;\n};\ntypedef struct StringArray* StringArray;\n\nStringArray StringArray_new(size_t size)\n{\n StringArray this = calloc(1, sizeof(struct StringArray));\n if (this)\n {\n this->elements = calloc(size, sizeof(int));\n if (this->elements)\n this->sizeOfArray = size;\n else\n {\n free(this);\n this = NULL;\n }\n }\n return this;\n}\n\nvoid StringArray_delete(StringArray* ptr_to_this)\n{\n assert(ptr_to_this != NULL);\n StringArray this = (*ptr_to_this);\n if (this)\n {\n for (size_t i = 0; i < this->sizeOfArray; i++)\n free(this->elements[i]);\n free(this->elements);\n free(this);\n this = NULL;\n }\n}\n\nvoid StringArray_add(StringArray this, ...)\n{\n char* s;\n va_list args;\n va_start(args, this);\n while (this->numberOfElements < this->sizeOfArray && (s = va_arg(args, char*)))\n this->elements[this->numberOfElements++] = strdup(s);\n va_end(args);\n}\n\n\nint main(int argc, char* argv[])\n{\n StringArray a = StringArray_new(10);\n StringArray_add(a, \"apple\", \"orange\", NULL);\n\n printf(\n \"There are %d elements in an array with a capacity of %d elements:\\n\\n\",\n a->numberOfElements, a->sizeOfArray);\n\n for (size_t i = 0; i < a->numberOfElements; i++)\n printf(\" the element %d is the string \\\"%s\\\"\\n\", i, a->elements[i]);\n\n StringArray_delete(&a);\n\n return EXIT_SUCCESS;\n}"} -{"title": "Array length", "language": "C++", "task": "Determine the amount of elements in an array.\n\n\nAs an example use an array holding the strings 'apple' and 'orange'.\n\n\n\n", "solution": "std::vector fruitV({ \"apples\", \"oranges\" });\n std::list fruitL({ \"apples\", \"oranges\" });\n std::deque fruitD({ \"apples\", \"oranges\" });\n std::cout << fruitV.size() << fruitL.size() << fruitD.size() << std::endl;"} -{"title": "Array length", "language": "JavaScript", "task": "Determine the amount of elements in an array.\n\n\nAs an example use an array holding the strings 'apple' and 'orange'.\n\n\n\n", "solution": "function last(list, defaultValue) {\n return list.length ?list[list.length-1] :defaultValue;\n}"} -{"title": "Ascending primes", "language": "C++ from C", "task": "Generate and show all primes with strictly ascending decimal digits.\n\nAside: Try solving without peeking at existing solutions. I had a weird idea for generating\na prime sieve faster, which needless to say didn't pan out. The solution may be p(r)etty trivial\nbut generating them quickly is at least mildly interesting.\nTip: filtering all 7,027,260 primes below 123,456,789 probably won't kill you, but there is\nat least one significantly better and much faster way, needing a mere 511 odd/prime tests.\n\n\n;See also\n;* OEIS:A052015 - Primes with distinct digits in ascending order\n\n\n;Related:\n*[[Primes with digits in nondecreasing order]] (infinite series allowing duplicate digits, whereas this isn't and doesn't)\n*[[Pandigital prime]] (whereas this is the smallest, with gaps in the used digits being permitted)\n\n\n", "solution": "/*\n * Ascending primes\n *\n * Generate and show all primes with strictly ascending decimal digits.\n *\n *\n * Solution\n *\n * We only consider positive numbers in the range 1 to 123456789. We would\n * get 7027260 primes, because there are so many primes smaller than 123456789\n * (see also Wolfram Alpha).On the other hand, there are only 511 distinct\n * nonzero positive integers having their digits arranged in ascending order.\n * Therefore, it is better to start with numbers that have properly arranged\n * digitsand then check if they are prime numbers.The method of generating\n * a sequence of such numbers is not indifferent.We want this sequence to be\n * monotonically increasing, because then additional sorting of results will\n * be unnecessary. It turns out that by using a queue we can easily get the\n * desired effect. Additionally, the algorithm then does not use recursion\n * (although the program probably does not have to comply with the MISRA\n * standard). The problem to be solved is the queue size, the a priori\n * assumption that 1000 is good enough, but a bit magical.\n */\n\n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n\nqueue suspected;\nvector primes;\n\n\nbool isPrime(unsigned n)\n{\n if (n == 2)\n {\n return true;\n }\n if (n == 1 || n % 2 == 0)\n {\n return false;\n }\n unsigned root = sqrt(n);\n for (unsigned k = 3; k <= root; k += 2)\n {\n if (n % k == 0)\n {\n return false;\n }\n }\n return true;\n}\n\n\nint main(int argc, char argv[])\n{\n for (unsigned k = 1; k <= 9; k++)\n {\n suspected.push(k);\n }\n\n while (!suspected.empty())\n {\n int n = suspected.front();\n suspected.pop();\n\n if (isPrime(n))\n {\n primes.push_back(n);\n }\n\n // The value of n % 10 gives the least significient digit of n\n //\n for (unsigned k = n % 10 + 1; k <= 9; k++)\n {\n suspected.push(n * 10 + k);\n }\n }\n\n copy(primes.begin(), primes.end(), ostream_iterator(cout, \" \"));\n\n return EXIT_SUCCESS;\n}"} -{"title": "Ascending primes", "language": "JavaScript from Java", "task": "Generate and show all primes with strictly ascending decimal digits.\n\nAside: Try solving without peeking at existing solutions. I had a weird idea for generating\na prime sieve faster, which needless to say didn't pan out. The solution may be p(r)etty trivial\nbut generating them quickly is at least mildly interesting.\nTip: filtering all 7,027,260 primes below 123,456,789 probably won't kill you, but there is\nat least one significantly better and much faster way, needing a mere 511 odd/prime tests.\n\n\n;See also\n;* OEIS:A052015 - Primes with distinct digits in ascending order\n\n\n;Related:\n*[[Primes with digits in nondecreasing order]] (infinite series allowing duplicate digits, whereas this isn't and doesn't)\n*[[Pandigital prime]] (whereas this is the smallest, with gaps in the used digits being permitted)\n\n\n", "solution": "\n\n\n \n\n \n\n\n"} -{"title": "Ascending primes", "language": "Python", "task": "Generate and show all primes with strictly ascending decimal digits.\n\nAside: Try solving without peeking at existing solutions. I had a weird idea for generating\na prime sieve faster, which needless to say didn't pan out. The solution may be p(r)etty trivial\nbut generating them quickly is at least mildly interesting.\nTip: filtering all 7,027,260 primes below 123,456,789 probably won't kill you, but there is\nat least one significantly better and much faster way, needing a mere 511 odd/prime tests.\n\n\n;See also\n;* OEIS:A052015 - Primes with distinct digits in ascending order\n\n\n;Related:\n*[[Primes with digits in nondecreasing order]] (infinite series allowing duplicate digits, whereas this isn't and doesn't)\n*[[Pandigital prime]] (whereas this is the smallest, with gaps in the used digits being permitted)\n\n\n", "solution": "from sympy import isprime\n\ndef ascending(x=0):\n for y in range(x*10 + (x%10) + 1, x*10 + 10):\n yield from ascending(y)\n yield(y)\n\nprint(sorted(x for x in ascending() if isprime(x)))"} -{"title": "Ascending primes", "language": "Python from Pascal", "task": "Generate and show all primes with strictly ascending decimal digits.\n\nAside: Try solving without peeking at existing solutions. I had a weird idea for generating\na prime sieve faster, which needless to say didn't pan out. The solution may be p(r)etty trivial\nbut generating them quickly is at least mildly interesting.\nTip: filtering all 7,027,260 primes below 123,456,789 probably won't kill you, but there is\nat least one significantly better and much faster way, needing a mere 511 odd/prime tests.\n\n\n;See also\n;* OEIS:A052015 - Primes with distinct digits in ascending order\n\n\n;Related:\n*[[Primes with digits in nondecreasing order]] (infinite series allowing duplicate digits, whereas this isn't and doesn't)\n*[[Pandigital prime]] (whereas this is the smallest, with gaps in the used digits being permitted)\n\n\n", "solution": "def isprime(n):\n if n == 2: return True\n if n == 1 or n % 2 == 0: return False\n root1 = int(n**0.5) + 1;\n for k in range(3, root1, 2):\n if n % k == 0: return False\n return True\n\nqueue = [k for k in range(1, 10)]\nprimes = []\n\nwhile queue:\n n = queue.pop(0)\n if isprime(n):\n primes.append(n)\n queue.extend(n * 10 + k for k in range(n % 10 + 1, 10))\n\nprint(primes)"} -{"title": "Associative array/Merging", "language": "C++", "task": "Define two associative arrays, where one represents the following \"base\" data:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"name\" || \"Rocket Skates\"\n|-\n| \"price\" || 12.75\n|-\n| \"color\" || \"yellow\"\n|}\n\nAnd the other represents \"update\" data:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"price\" || 15.25\n|-\n| \"color\" || \"red\"\n|-\n| \"year\" || 1974\n|}\n\nMerge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"name\" || \"Rocket Skates\"\n|-\n| \"price\" || 15.25\n|-\n| \"color\" || \"red\"\n|-\n| \"year\" || 1974\n|}\n\n", "solution": "#include \n#include \n#include \n\ntemplate\nmap_type merge(const map_type& original, const map_type& update) {\n map_type result(update);\n result.insert(original.begin(), original.end());\n return result;\n}\n\nint main() {\n typedef std::map map;\n map original{\n {\"name\", \"Rocket Skates\"},\n {\"price\", \"12.75\"},\n {\"color\", \"yellow\"}\n };\n map update{\n {\"price\", \"15.25\"},\n {\"color\", \"red\"},\n {\"year\", \"1974\"}\n };\n map merged(merge(original, update));\n for (auto&& i : merged)\n std::cout << \"key: \" << i.first << \", value: \" << i.second << '\\n';\n return 0;\n}"} -{"title": "Associative array/Merging", "language": "JavaScript", "task": "Define two associative arrays, where one represents the following \"base\" data:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"name\" || \"Rocket Skates\"\n|-\n| \"price\" || 12.75\n|-\n| \"color\" || \"yellow\"\n|}\n\nAnd the other represents \"update\" data:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"price\" || 15.25\n|-\n| \"color\" || \"red\"\n|-\n| \"year\" || 1974\n|}\n\nMerge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"name\" || \"Rocket Skates\"\n|-\n| \"price\" || 15.25\n|-\n| \"color\" || \"red\"\n|-\n| \"year\" || 1974\n|}\n\n", "solution": "(() => {\n 'use strict';\n\n console.log(JSON.stringify(\n Object.assign({}, // Fresh dictionary.\n { // Base.\n \"name\": \"Rocket Skates\",\n \"price\": 12.75,\n \"color\": \"yellow\"\n }, { // Update.\n \"price\": 15.25,\n \"color\": \"red\",\n \"year\": 1974\n }\n ), \n null, 2\n ))\n})();"} -{"title": "Associative array/Merging", "language": "Python", "task": "Define two associative arrays, where one represents the following \"base\" data:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"name\" || \"Rocket Skates\"\n|-\n| \"price\" || 12.75\n|-\n| \"color\" || \"yellow\"\n|}\n\nAnd the other represents \"update\" data:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"price\" || 15.25\n|-\n| \"color\" || \"red\"\n|-\n| \"year\" || 1974\n|}\n\nMerge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"name\" || \"Rocket Skates\"\n|-\n| \"price\" || 15.25\n|-\n| \"color\" || \"red\"\n|-\n| \"year\" || 1974\n|}\n\n", "solution": "As of Python 3.5, this can be solved with the dictionary unpacking operator.\n"} -{"title": "Associative array/Merging", "language": "Python 3.5+", "task": "Define two associative arrays, where one represents the following \"base\" data:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"name\" || \"Rocket Skates\"\n|-\n| \"price\" || 12.75\n|-\n| \"color\" || \"yellow\"\n|}\n\nAnd the other represents \"update\" data:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"price\" || 15.25\n|-\n| \"color\" || \"red\"\n|-\n| \"year\" || 1974\n|}\n\nMerge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"name\" || \"Rocket Skates\"\n|-\n| \"price\" || 15.25\n|-\n| \"color\" || \"red\"\n|-\n| \"year\" || 1974\n|}\n\n", "solution": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)"} -{"title": "Attractive numbers", "language": "C++ from C", "task": "A number is an ''attractive number'' if the number of its prime factors (whether distinct or not) is also prime.\n\n\n;Example:\nThe number '''20''', whose prime decomposition is '''2 x 2 x 5''', is an ''attractive number'' because the number of its prime factors ('''3''') is also prime.\n\n\n;Task:\nShow sequence items up to '''120'''.\n\n\n;Reference:\n:* The OEIS entry: A063989: Numbers with a prime number of prime divisors.\n\n", "solution": "#include \n#include \n\n#define MAX 120\n\nusing namespace std;\n\nbool is_prime(int n) { \n if (n < 2) return false;\n if (!(n % 2)) return n == 2;\n if (!(n % 3)) return n == 3;\n int d = 5;\n while (d *d <= n) {\n if (!(n % d)) return false;\n d += 2;\n if (!(n % d)) return false;\n d += 4;\n }\n return true;\n}\n\nint count_prime_factors(int n) { \n if (n == 1) return 0;\n if (is_prime(n)) return 1;\n int count = 0, f = 2;\n while (true) {\n if (!(n % f)) {\n count++;\n n /= f;\n if (n == 1) return count;\n if (is_prime(n)) f = n;\n } \n else if (f >= 3) f += 2;\n else f = 3;\n }\n}\n\nint main() {\n cout << \"The attractive numbers up to and including \" << MAX << \" are:\" << endl;\n for (int i = 1, count = 0; i <= MAX; ++i) {\n int n = count_prime_factors(i);\n if (is_prime(n)) {\n cout << setw(4) << i;\n if (!(++count % 20)) cout << endl;\n }\n }\n cout << endl;\n return 0;\n}"} -{"title": "Attractive numbers", "language": "JavaScript", "task": "A number is an ''attractive number'' if the number of its prime factors (whether distinct or not) is also prime.\n\n\n;Example:\nThe number '''20''', whose prime decomposition is '''2 x 2 x 5''', is an ''attractive number'' because the number of its prime factors ('''3''') is also prime.\n\n\n;Task:\nShow sequence items up to '''120'''.\n\n\n;Reference:\n:* The OEIS entry: A063989: Numbers with a prime number of prime divisors.\n\n", "solution": "(() => {\n 'use strict';\n\n // attractiveNumbers :: () -> Gen [Int]\n const attractiveNumbers = () =>\n // An infinite series of attractive numbers.\n filter(\n compose(isPrime, length, primeFactors)\n )(enumFrom(1));\n\n\n // ----------------------- TEST -----------------------\n // main :: IO ()\n const main = () =>\n showCols(10)(\n takeWhile(ge(120))(\n attractiveNumbers()\n )\n );\n\n\n // ---------------------- PRIMES ----------------------\n\n // isPrime :: Int -> Bool\n const isPrime = n => {\n // True if n is prime.\n if (2 === n || 3 === n) {\n return true\n }\n if (2 > n || 0 === n % 2) {\n return false\n }\n if (9 > n) {\n return true\n }\n if (0 === n % 3) {\n return false\n }\n return !enumFromThenTo(5)(11)(\n 1 + Math.floor(Math.pow(n, 0.5))\n ).some(x => 0 === n % x || 0 === n % (2 + x));\n };\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 ? (\n 2\n ) : 3,\n 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\n // ---------------- GENERIC FUNCTIONS -----------------\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\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\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\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\n // filter :: (a -> Bool) -> Gen [a] -> [a]\n const filter = p => xs => {\n function* go() {\n let x = xs.next();\n while (!x.done) {\n let v = x.value;\n if (p(v)) {\n yield v\n }\n x = xs.next();\n }\n }\n return go(xs);\n };\n\n\n // ge :: Ord a => a -> a -> Bool\n const ge = x =>\n // True if x >= y\n y => x >= y;\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 // last :: [a] -> a\n const last = xs =>\n // The last item of a list.\n 0 < xs.length ? xs.slice(-1)[0] : undefined;\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\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 => (\n Array.isArray(xs) ? (\n xs\n ) : xs.split('')\n ).map(f);\n\n\n // showCols :: Int -> [a] -> String\n const showCols = w => xs => {\n const\n ys = xs.map(str),\n mx = last(ys).length;\n return unlines(chunksOf(w)(ys).map(\n row => row.map(justifyRight(mx)(' ')).join(' ')\n ))\n };\n\n\n // str :: a -> String\n const str = x =>\n x.toString();\n\n\n // takeWhile :: (a -> Bool) -> Gen [a] -> [a]\n const takeWhile = 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\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 // 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": "Attractive numbers", "language": "Python 2.7.12", "task": "A number is an ''attractive number'' if the number of its prime factors (whether distinct or not) is also prime.\n\n\n;Example:\nThe number '''20''', whose prime decomposition is '''2 x 2 x 5''', is an ''attractive number'' because the number of its prime factors ('''3''') is also prime.\n\n\n;Task:\nShow sequence items up to '''120'''.\n\n\n;Reference:\n:* The OEIS entry: A063989: Numbers with a prime number of prime divisors.\n\n", "solution": "from sympy import sieve # library for primes\n\ndef get_pfct(n): \n\ti = 2; factors = []\n\twhile i * i <= n:\n\t\tif n % i:\n\t\t\ti += 1\n\t\telse:\n\t\t\tn //= i\n\t\t\tfactors.append(i)\n\tif n > 1:\n\t\tfactors.append(n)\n\treturn len(factors) \n\nsieve.extend(110) # first 110 primes...\nprimes=sieve._list\n\npool=[]\n\nfor each in xrange(0,121):\n\tpool.append(get_pfct(each))\n\nfor i,each in enumerate(pool):\n\tif each in primes:\n\t\tprint i,"} -{"title": "Attractive numbers", "language": "Python 3.7", "task": "A number is an ''attractive number'' if the number of its prime factors (whether distinct or not) is also prime.\n\n\n;Example:\nThe number '''20''', whose prime decomposition is '''2 x 2 x 5''', is an ''attractive number'' because the number of its prime factors ('''3''') is also prime.\n\n\n;Task:\nShow sequence items up to '''120'''.\n\n\n;Reference:\n:* The OEIS entry: A063989: Numbers with a prime number of prime divisors.\n\n", "solution": "'''Attractive numbers'''\n\nfrom itertools import chain, count, takewhile\nfrom functools import reduce\n\n\n# attractiveNumbers :: () -> [Int]\ndef attractiveNumbers():\n '''A non-finite stream of attractive numbers.\n (OEIS A063989)\n '''\n return filter(\n compose(\n isPrime,\n len,\n primeDecomposition\n ),\n count(1)\n )\n\n\n# TEST ----------------------------------------------------\ndef main():\n '''Attractive numbers drawn from the range [1..120]'''\n for row in chunksOf(15)(list(\n takewhile(\n lambda x: 120 >= x,\n attractiveNumbers()\n )\n )):\n print(' '.join(map(\n compose(justifyRight(3)(' '), str),\n row\n )))\n\n\n# GENERAL FUNCTIONS ---------------------------------------\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 divible, the final list will be shorter than n.\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 :: ((a -> a), ...) -> (a -> a)\ndef compose(*fs):\n '''Composition, from right to left,\n of a series of functions.\n '''\n return lambda x: reduce(\n lambda a, f: f(a),\n fs[::-1], x\n )\n\n\n# We only need light implementations\n# of prime functions here:\n\n# primeDecomposition :: Int -> [Int]\ndef primeDecomposition(n):\n '''List of integers representing the\n prime decomposition of n.\n '''\n def go(n, p):\n return [p] + go(n // p, p) if (\n 0 == n % p\n ) else []\n return list(chain.from_iterable(map(\n lambda p: go(n, p) if isPrime(p) else [],\n range(2, 1 + n)\n )))\n\n\n# isPrime :: Int -> Bool\ndef isPrime(n):\n '''True if n is prime.'''\n if n in (2, 3):\n return True\n if 2 > n or 0 == n % 2:\n return False\n if 9 > n:\n return True\n if 0 == n % 3:\n return False\n\n return not any(map(\n lambda x: 0 == n % x or 0 == n % (2 + x),\n range(5, 1 + int(n ** 0.5), 6)\n ))\n\n\n# justifyRight :: Int -> Char -> String -> String\ndef justifyRight(n):\n '''A string padded at left to length n,\n using the padding character c.\n '''\n return lambda c: lambda s: s.rjust(n, c)\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} -{"title": "Average loop length", "language": "C", "task": "Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence.\n\n\n;Task:\nWrite a program or a script that estimates, for each N, the average length until the first such repetition.\n\nAlso calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one.\n\n\nThis problem comes from the end of Donald Knuth's Christmas tree lecture 2011.\n\nExample of expected output:\n\n N average analytical (error)\n=== ========= ============ =========\n 1 1.0000 1.0000 ( 0.00%)\n 2 1.4992 1.5000 ( 0.05%)\n 3 1.8784 1.8889 ( 0.56%)\n 4 2.2316 2.2188 ( 0.58%)\n 5 2.4982 2.5104 ( 0.49%)\n 6 2.7897 2.7747 ( 0.54%)\n 7 3.0153 3.0181 ( 0.09%)\n 8 3.2429 3.2450 ( 0.07%)\n 9 3.4536 3.4583 ( 0.14%)\n 10 3.6649 3.6602 ( 0.13%)\n 11 3.8091 3.8524 ( 1.12%)\n 12 3.9986 4.0361 ( 0.93%)\n 13 4.2074 4.2123 ( 0.12%)\n 14 4.3711 4.3820 ( 0.25%)\n 15 4.5275 4.5458 ( 0.40%)\n 16 4.6755 4.7043 ( 0.61%)\n 17 4.8877 4.8579 ( 0.61%)\n 18 4.9951 5.0071 ( 0.24%)\n 19 5.1312 5.1522 ( 0.41%)\n 20 5.2699 5.2936 ( 0.45%)\n\n", "solution": "#include \n#include \n#include \n#include \n\n#define MAX_N 20\n#define TIMES 1000000\n\ndouble factorial(int n) {\n\tdouble f = 1;\n\tint i;\n\tfor (i = 1; i <= n; i++) f *= i;\n\treturn f;\n}\n\ndouble expected(int n) {\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 1; i <= n; i++)\n\t\tsum += factorial(n) / pow(n, i) / factorial(n - i);\n\treturn sum;\n}\n\nint randint(int n) {\n\tint r, rmax = RAND_MAX / n * n;\n\twhile ((r = rand()) >= rmax);\n\treturn r / (RAND_MAX / n);\n}\n\nint test(int n, int times) {\n\tint i, count = 0;\n\tfor (i = 0; i < times; i++) {\n\t\tint x = 1, bits = 0;\n\t\twhile (!(bits & x)) {\n\t\t\tcount++;\n\t\t\tbits |= x;\n\t\t\tx = 1 << randint(n);\n\t\t}\n\t}\n\treturn count;\n}\n\nint main(void) {\n\tsrand(time(0));\n\tputs(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n\tint n;\n\tfor (n = 1; n <= MAX_N; n++) {\n\t\tint cnt = test(n, TIMES);\n\t\tdouble avg = (double)cnt / TIMES;\n\t\tdouble theory = expected(n);\n\t\tdouble diff = (avg / theory - 1) * 100;\n\t\tprintf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, avg, theory, diff);\n\t}\n\treturn 0;\n}"} -{"title": "Average loop length", "language": "C++", "task": "Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence.\n\n\n;Task:\nWrite a program or a script that estimates, for each N, the average length until the first such repetition.\n\nAlso calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one.\n\n\nThis problem comes from the end of Donald Knuth's Christmas tree lecture 2011.\n\nExample of expected output:\n\n N average analytical (error)\n=== ========= ============ =========\n 1 1.0000 1.0000 ( 0.00%)\n 2 1.4992 1.5000 ( 0.05%)\n 3 1.8784 1.8889 ( 0.56%)\n 4 2.2316 2.2188 ( 0.58%)\n 5 2.4982 2.5104 ( 0.49%)\n 6 2.7897 2.7747 ( 0.54%)\n 7 3.0153 3.0181 ( 0.09%)\n 8 3.2429 3.2450 ( 0.07%)\n 9 3.4536 3.4583 ( 0.14%)\n 10 3.6649 3.6602 ( 0.13%)\n 11 3.8091 3.8524 ( 1.12%)\n 12 3.9986 4.0361 ( 0.93%)\n 13 4.2074 4.2123 ( 0.12%)\n 14 4.3711 4.3820 ( 0.25%)\n 15 4.5275 4.5458 ( 0.40%)\n 16 4.6755 4.7043 ( 0.61%)\n 17 4.8877 4.8579 ( 0.61%)\n 18 4.9951 5.0071 ( 0.24%)\n 19 5.1312 5.1522 ( 0.41%)\n 20 5.2699 5.2936 ( 0.45%)\n\n", "solution": "#include \n#include \n#include \n#include \n\n#define MAX_N 20\n#define TIMES 1000000\n\n/**\n * Used to generate a uniform random distribution\n */\nstatic std::random_device rd; //Will be used to obtain a seed for the random number engine\nstatic std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()\nstatic std::uniform_int_distribution<> dis;\n\nint randint(int n) {\n int r, rmax = RAND_MAX / n * n;\n dis=std::uniform_int_distribution(0,rmax) ;\n r = dis(gen);\n return r / (RAND_MAX / n);\n}\n\nunsigned long long factorial(size_t n) {\n //Factorial using dynamic programming to memoize the values.\n static std::vectorfactorials{1,1,2};\n\tfor (;factorials.size() <= n;)\n\t factorials.push_back(((unsigned long long) factorials.back())*factorials.size());\n\treturn factorials[n];\n}\n\nlong double expected(size_t n) {\n long double sum = 0;\n for (size_t i = 1; i <= n; i++)\n sum += factorial(n) / pow(n, i) / factorial(n - i);\n return sum;\n}\n\nint test(int n, int times) {\n int i, count = 0;\n for (i = 0; i < times; i++) {\n unsigned int x = 1, bits = 0;\n while (!(bits & x)) {\n count++;\n bits |= x;\n x = static_cast(1 << randint(n));\n }\n }\n return count;\n}\n\nint main() {\n puts(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n int n;\n for (n = 1; n <= MAX_N; n++) {\n int cnt = test(n, TIMES);\n long double avg = (double)cnt / TIMES;\n long double theory = expected(static_cast(n));\n long double diff = (avg / theory - 1) * 100;\n printf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, static_cast(avg), static_cast(theory), static_cast(diff));\n }\n return 0;\n}\n"} -{"title": "Average loop length", "language": "Python from C", "task": "Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence.\n\n\n;Task:\nWrite a program or a script that estimates, for each N, the average length until the first such repetition.\n\nAlso calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one.\n\n\nThis problem comes from the end of Donald Knuth's Christmas tree lecture 2011.\n\nExample of expected output:\n\n N average analytical (error)\n=== ========= ============ =========\n 1 1.0000 1.0000 ( 0.00%)\n 2 1.4992 1.5000 ( 0.05%)\n 3 1.8784 1.8889 ( 0.56%)\n 4 2.2316 2.2188 ( 0.58%)\n 5 2.4982 2.5104 ( 0.49%)\n 6 2.7897 2.7747 ( 0.54%)\n 7 3.0153 3.0181 ( 0.09%)\n 8 3.2429 3.2450 ( 0.07%)\n 9 3.4536 3.4583 ( 0.14%)\n 10 3.6649 3.6602 ( 0.13%)\n 11 3.8091 3.8524 ( 1.12%)\n 12 3.9986 4.0361 ( 0.93%)\n 13 4.2074 4.2123 ( 0.12%)\n 14 4.3711 4.3820 ( 0.25%)\n 15 4.5275 4.5458 ( 0.40%)\n 16 4.6755 4.7043 ( 0.61%)\n 17 4.8877 4.8579 ( 0.61%)\n 18 4.9951 5.0071 ( 0.24%)\n 19 5.1312 5.1522 ( 0.41%)\n 20 5.2699 5.2936 ( 0.45%)\n\n", "solution": "from __future__ import division # Only necessary for Python 2.X\nfrom math import factorial\nfrom random import randrange\n\nMAX_N = 20\nTIMES = 1000000\n\ndef analytical(n):\n\treturn sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))\n\ndef test(n, times):\n count = 0\n for i in range(times):\n x, bits = 1, 0\n while not (bits & x):\n count += 1\n bits |= x\n x = 1 << randrange(n)\n return count / times\n\nif __name__ == '__main__':\n print(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\")\n for n in range(1, MAX_N+1):\n avg = test(n, TIMES)\n theory = analytical(n)\n diff = (avg / theory - 1) * 100\n print(\"%2d %8.4f %8.4f %6.3f%%\" % (n, avg, theory, diff))"} -{"title": "Averages/Mean angle", "language": "C", "task": "{{Related tasks/Statistical measures}}\n\n\n", "solution": "#include\n#include\n\ndouble\nmeanAngle (double *angles, int size)\n{\n double y_part = 0, x_part = 0;\n int i;\n\n for (i = 0; i < size; i++)\n {\n x_part += cos (angles[i] * M_PI / 180);\n y_part += sin (angles[i] * M_PI / 180);\n }\n\n return atan2 (y_part / size, x_part / size) * 180 / M_PI;\n}\n\nint\nmain ()\n{\n double angleSet1[] = { 350, 10 };\n double angleSet2[] = { 90, 180, 270, 360};\n double angleSet3[] = { 10, 20, 30};\n\n printf (\"\\nMean Angle for 1st set : %lf degrees\", meanAngle (angleSet1, 2));\n printf (\"\\nMean Angle for 2nd set : %lf degrees\", meanAngle (angleSet2, 4));\n printf (\"\\nMean Angle for 3rd set : %lf degrees\\n\", meanAngle (angleSet3, 3));\n return 0;\n}"} -{"title": "Averages/Mean angle", "language": "C++ from C#", "task": "{{Related tasks/Statistical measures}}\n\n\n", "solution": "#include \n#include \n#include \n\n#define _USE_MATH_DEFINES\n#include \n\ntemplate\ndouble meanAngle(const C& c) {\n auto it = std::cbegin(c);\n auto end = std::cend(c);\n\n double x = 0.0;\n double y = 0.0;\n double len = 0.0;\n while (it != end) {\n x += cos(*it * M_PI / 180);\n y += sin(*it * M_PI / 180);\n len++;\n\n it = std::next(it);\n }\n\n return atan2(y, x) * 180 / M_PI;\n}\n\nvoid printMean(std::initializer_list init) {\n std::cout << std::fixed << std::setprecision(3) << meanAngle(init) << '\\n';\n}\n\nint main() {\n printMean({ 350, 10 });\n printMean({ 90, 180, 270, 360 });\n printMean({ 10, 20, 30 });\n\n return 0;\n}"} -{"title": "Averages/Mean angle", "language": "JavaScript", "task": "{{Related tasks/Statistical measures}}\n\n\n", "solution": "function sum(a) {\n var s = 0;\n for (var i = 0; i < a.length; i++) s += a[i];\n return s;\n} \n\nfunction degToRad(a) {\n return Math.PI / 180 * a;\n}\n\nfunction meanAngleDeg(a) {\n return 180 / Math.PI * Math.atan2(\n sum(a.map(degToRad).map(Math.sin)) / a.length,\n sum(a.map(degToRad).map(Math.cos)) / a.length\n );\n}\n\nvar a = [350, 10], b = [90, 180, 270, 360], c = [10, 20, 30];\nconsole.log(meanAngleDeg(a));\nconsole.log(meanAngleDeg(b));\nconsole.log(meanAngleDeg(c));"} -{"title": "Averages/Mean angle", "language": "Python 2.6+", "task": "{{Related tasks/Statistical measures}}\n\n\n", "solution": ">>> from cmath import rect, phase\n>>> from math import radians, degrees\n>>> def mean_angle(deg):\n... return degrees(phase(sum(rect(1, radians(d)) for d in deg)/len(deg)))\n... \n>>> for angles in [[350, 10], [90, 180, 270, 360], [10, 20, 30]]:\n... print('The mean angle of', angles, 'is:', round(mean_angle(angles), 12), 'degrees')\n... \nThe mean angle of [350, 10] is: -0.0 degrees\nThe mean angle of [90, 180, 270, 360] is: -90.0 degrees\nThe mean angle of [10, 20, 30] is: 20.0 degrees\n>>> "} -{"title": "Averages/Pythagorean means", "language": "C", "task": "{{Related tasks/Statistical measures}}\n\n\n", "solution": "#include \n#include // atoi()\n#include // pow()\n\nint main(int argc, char* argv[])\n{\n int i, count=0;\n double f, sum=0.0, prod=1.0, resum=0.0;\n\n for (i=1; i\n#include \n#include \n#include \n#include \n\ndouble toInverse ( int i ) {\n return 1.0 / i ;\n}\n\nint main( ) {\n std::vector numbers ;\n for ( int i = 1 ; i < 11 ; i++ ) \n numbers.push_back( i ) ;\n double arithmetic_mean = std::accumulate( numbers.begin( ) , numbers.end( ) , 0 ) / 10.0 ;\n double geometric_mean =\n pow( std::accumulate( numbers.begin( ) , numbers.end( ) , 1 , std::multiplies( ) ), 0.1 ) ;\n std::vector inverses ;\n inverses.resize( numbers.size( ) ) ;\n std::transform( numbers.begin( ) , numbers.end( ) , inverses.begin( ) , toInverse ) ; \n double harmonic_mean = 10 / std::accumulate( inverses.begin( ) , inverses.end( ) , 0.0 ); //initial value of accumulate must be a double!\n std::cout << \"The arithmetic mean is \" << arithmetic_mean << \" , the geometric mean \" \n << geometric_mean << \" and the harmonic mean \" << harmonic_mean << \" !\\n\" ;\n return 0 ;\n}"} -{"title": "Averages/Pythagorean means", "language": "JavaScript", "task": "{{Related tasks/Statistical measures}}\n\n\n", "solution": "(function () {\n 'use strict';\n\n // arithmetic_mean :: [Number] -> Number\n function arithmetic_mean(ns) {\n return (\n ns.reduce( // sum\n function (sum, n) {\n return (sum + n);\n },\n 0\n ) / ns.length\n );\n }\n\n // geometric_mean :: [Number] -> Number\n function geometric_mean(ns) {\n return Math.pow(\n ns.reduce( // product\n function (product, n) {\n return (product * n);\n },\n 1\n ),\n 1 / ns.length\n );\n }\n\n // harmonic_mean :: [Number] -> Number\n function harmonic_mean(ns) {\n return (\n ns.length / ns.reduce( // sum of inverses\n function (invSum, n) {\n return (invSum + (1 / n));\n },\n 0\n )\n );\n }\n\n var values = [arithmetic_mean, geometric_mean, harmonic_mean]\n .map(function (f) {\n return f([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);\n }),\n mean = {\n Arithmetic: values[0], // arithmetic\n Geometric: values[1], // geometric\n Harmonic: values[2] // harmonic\n }\n\n return JSON.stringify({\n values: mean,\n test: \"is A >= G >= H ? \" +\n (\n mean.Arithmetic >= mean.Geometric &&\n mean.Geometric >= mean.Harmonic ? \"yes\" : \"no\"\n )\n }, null, 2);\n\n})();\n"} -{"title": "Averages/Pythagorean means", "language": "Python 3", "task": "{{Related tasks/Statistical measures}}\n\n\n", "solution": "from operator import mul\nfrom functools import reduce\n\n\ndef amean(num):\n return sum(num) / len(num)\n\n\ndef gmean(num):\n return reduce(mul, num, 1)**(1 / len(num))\n\n\ndef hmean(num):\n return len(num) / sum(1 / n for n in num)\n\n\nnumbers = range(1, 11) # 1..10\na, g, h = amean(numbers), gmean(numbers), hmean(numbers)\nprint(a, g, h)\nassert a >= g >= h"} -{"title": "Averages/Root mean square", "language": "C", "task": "Task\n\nCompute the Root mean square of the numbers 1..10.\n\n\nThe ''root mean square'' is also known by its initials RMS (or rms), and as the '''quadratic mean'''.\n\nThe RMS is calculated as the mean of the squares of the numbers, square-rooted:\n\n\n::: x_{\\mathrm{rms}} = \\sqrt {{{x_1}^2 + {x_2}^2 + \\cdots + {x_n}^2} \\over n}. \n\n\n;See also\n\n{{Related tasks/Statistical measures}}\n\n\n", "solution": "#include \n#include \n\ndouble rms(double *v, int n)\n{\n int i;\n double sum = 0.0;\n for(i = 0; i < n; i++)\n sum += v[i] * v[i];\n return sqrt(sum / n);\n}\n\nint main(void)\n{\n double v[] = {1., 2., 3., 4., 5., 6., 7., 8., 9., 10.};\n printf(\"%f\\n\", rms(v, sizeof(v)/sizeof(double)));\n return 0;\n}"} -{"title": "Averages/Root mean square", "language": "C++", "task": "Task\n\nCompute the Root mean square of the numbers 1..10.\n\n\nThe ''root mean square'' is also known by its initials RMS (or rms), and as the '''quadratic mean'''.\n\nThe RMS is calculated as the mean of the squares of the numbers, square-rooted:\n\n\n::: x_{\\mathrm{rms}} = \\sqrt {{{x_1}^2 + {x_2}^2 + \\cdots + {x_n}^2} \\over n}. \n\n\n;See also\n\n{{Related tasks/Statistical measures}}\n\n\n", "solution": "#include \n#include \n#include \n#include \n\nint main( ) {\n std::vector numbers ;\n for ( int i = 1 ; i < 11 ; i++ )\n numbers.push_back( i ) ;\n double meansquare = sqrt( ( std::inner_product( numbers.begin(), numbers.end(), numbers.begin(), 0 ) ) / static_cast( numbers.size() ) );\n std::cout << \"The quadratic mean of the numbers 1 .. \" << numbers.size() << \" is \" << meansquare << \" !\\n\" ;\n return 0 ;\n}"} -{"title": "Averages/Root mean square", "language": "Python 3", "task": "Task\n\nCompute the Root mean square of the numbers 1..10.\n\n\nThe ''root mean square'' is also known by its initials RMS (or rms), and as the '''quadratic mean'''.\n\nThe RMS is calculated as the mean of the squares of the numbers, square-rooted:\n\n\n::: x_{\\mathrm{rms}} = \\sqrt {{{x_1}^2 + {x_2}^2 + \\cdots + {x_n}^2} \\over n}. \n\n\n;See also\n\n{{Related tasks/Statistical measures}}\n\n\n", "solution": "from functools import (reduce)\nfrom math import (sqrt)\n\n\n# rootMeanSquare :: [Num] -> Float\ndef rootMeanSquare(xs):\n return sqrt(reduce(lambda a, x: a + x * x, xs, 0) / len(xs))\n\n\nprint(\n rootMeanSquare([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\n)"} -{"title": "Babbage problem", "language": "C", "task": "Charles Babbage\nCharles Babbage's analytical engine.\n\nCharles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:\n{{quote\n | What is the smallest positive integer whose square ends in the digits 269,696?\n | Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.\n}}\nHe thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.\n\n\n;Task\n\nThe task is to find out if Babbage had the right answer -- and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand. \nAs Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.\n\nFor these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].\n\n\n;Motivation\n\nThe aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.\n\n", "solution": "// This code is the implementation of Babbage Problem\n\n#include \n#include \n#include \n \nint main() {\n\tint current = 0, \t//the current number \n\t square;\t\t//the square of the current number\n\n\t//the strategy of take the rest of division by 1e06 is\n\t//to take the a number how 6 last digits are 269696\n\twhile (((square=current*current) % 1000000 != 269696) && (square+INT_MAX)\n\t printf(\"Condition not satisfied before INT_MAX reached.\");\n\telse\t\t \n\t printf (\"The smallest number whose square ends in 269696 is %d\\n\", current);\n\t \n //the end\n\treturn 0 ;\n}\n"} -{"title": "Babbage problem", "language": "C++", "task": "Charles Babbage\nCharles Babbage's analytical engine.\n\nCharles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:\n{{quote\n | What is the smallest positive integer whose square ends in the digits 269,696?\n | Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.\n}}\nHe thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.\n\n\n;Task\n\nThe task is to find out if Babbage had the right answer -- and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand. \nAs Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.\n\nFor these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].\n\n\n;Motivation\n\nThe aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.\n\n", "solution": "#include \n\nint main( ) {\n int current = 0 ;\n while ( ( current * current ) % 1000000 != 269696 ) \n current++ ;\n std::cout << \"The square of \" << current << \" is \" << (current * current) << \" !\\n\" ;\n return 0 ;\n}"} -{"title": "Babbage problem", "language": "JavaScript", "task": "Charles Babbage\nCharles Babbage's analytical engine.\n\nCharles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:\n{{quote\n | What is the smallest positive integer whose square ends in the digits 269,696?\n | Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.\n}}\nHe thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.\n\n\n;Task\n\nThe task is to find out if Babbage had the right answer -- and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand. \nAs Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.\n\nFor these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].\n\n\n;Motivation\n\nThe aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.\n\n", "solution": "// Every line starting with a double slash will be ignored by the processing machine,\n// just like these two.\n//\n// Since the square root of 269,696 is approximately 519, we create a variable named \"n\"\n// and give it this value.\n n = 519\n\n// The while-condition is in parentheses\n// * is for multiplication\n// % is for modulo operation\n// != is for \"not equal\"\n while ( ((n * n) % 1000000) != 269696 )\n n = n + 1\n\n// n is incremented until the while-condition is met, so n should finally be the\n// smallest positive integer whose square ends in the digits 269,696. To see n, we\n// need to send it to the monitoring device (named console).\n console.log(n)\n"} -{"title": "Babbage problem", "language": "Python", "task": "Charles Babbage\nCharles Babbage's analytical engine.\n\nCharles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:\n{{quote\n | What is the smallest positive integer whose square ends in the digits 269,696?\n | Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.\n}}\nHe thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.\n\n\n;Task\n\nThe task is to find out if Babbage had the right answer -- and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand. \nAs Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.\n\nFor these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].\n\n\n;Motivation\n\nThe aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.\n\n", "solution": "# Lines that start by # are a comments:\n# they will be ignored by the machine\n\nn=0 # n is a variable and its value is 0\n\n# we will increase its value by one until\n# its square ends in 269,696\n\nwhile n**2 % 1000000 != 269696:\n\n # n**2 -> n squared\n # % -> 'modulo' or remainder after division\n # != -> not equal to\n \n n += 1 # += -> increase by a certain number\n\nprint(n) # prints n\n"} -{"title": "Babbage problem", "language": "Python 3.7", "task": "Charles Babbage\nCharles Babbage's analytical engine.\n\nCharles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:\n{{quote\n | What is the smallest positive integer whose square ends in the digits 269,696?\n | Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.\n}}\nHe thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.\n\n\n;Task\n\nThe task is to find out if Babbage had the right answer -- and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand. \nAs Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.\n\nFor these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].\n\n\n;Motivation\n\nThe aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.\n\n", "solution": "'''Babbage problem'''\n\nfrom math import (floor, sqrt)\nfrom itertools import (islice)\n\n\n# squaresWithSuffix :: Int -> Gen [Int]\ndef squaresWithSuffix(n):\n '''Non finite stream of squares with a given suffix.'''\n stem = 10 ** len(str(n))\n i = 0\n while True:\n i = until(lambda x: isPerfectSquare(n + (stem * x)))(\n succ\n )(i)\n yield n + (stem * i)\n i = succ(i)\n\n\n# isPerfectSquare :: Int -> Bool\ndef isPerfectSquare(n):\n '''True if n is a perfect square.'''\n r = sqrt(n)\n return r == floor(r)\n\n\n# TEST ----------------------------------------------------\n\n# main :: IO ()\ndef main():\n '''Smallest positive integers whose squares end in the digits 269,696'''\n print(\n fTable(main.__doc__ + ':\\n')(\n lambda n: str(int(sqrt(n))) + '^2'\n )(repr)(identity)(\n take(10)(squaresWithSuffix(269696))\n )\n )\n\n\n# GENERIC -------------------------------------------------\n\n# identity :: a -> a\ndef identity(x):\n '''The identity function.'''\n return x\n\n\n# succ :: Enum a => a -> a\ndef succ(x):\n '''The successor of a value.\n For numeric types, (1 +).\n '''\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 '''\n return lambda xs: (\n xs[0:n]\n if isinstance(xs, (list, tuple))\n else list(islice(xs, n))\n )\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, 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# FORMATTING ----------------------------------------------\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": "Babylonian spiral", "language": "Python", "task": "The '''Babylonian spiral''' is a sequence of points in the plane that are created so as to\ncontinuously minimally increase in vector length and minimally bend in vector direction,\nwhile always moving from point to point on strictly integral coordinates. Of the two criteria\nof length and angle, the length has priority.\n\n; Examples\n\nP(1) and P(2) are defined to be at (x = 0, y = 0) and (x = 0, y = 1). The first vector is\nfrom P(1) to P(2). It is vertical and of length 1. Note that the square of that length is 1.\n\nNext in sequence is the vector from P(2) to P(3). This should be the smallest distance to a\npoint with integral (x, y) which is longer than the last vector (that is, 1). It should also bend clockwise\nmore than zero radians, but otherwise to the least degree.\n\nThe point chosen for P(3) that fits criteria is (x = 1, y = 2). Note the length of the vector\nfrom P(2) to P(3) is 2, which squared is 2. The lengths of the vectors thus determined can be given by a sorted\nlist of possible sums of two integer squares, including 0 as a square.\n\n; Task\n\nFind and show the first 40 (x, y) coordinates of the Babylonian spiral.\n\n; Stretch task\n\nShow in your program how to calculate and plot the first 10000 points in the sequence. Your result\nshould look similar to the graph shown at the OEIS: [[File:From_oies_A@97346_A297347_plot2a.png]]\n\n; See also\n\n;* OEIS:A256111 - squared distance to the origin of the n-th vertex on a Babylonian Spiral.\n;* OEIS:A297346 - List of successive x-coordinates in the Babylonian Spiral.\n;* OEIS:A297347 - List of successive y-coordinates in the Babylonian Spiral.\n\n\n\n", "solution": "\"\"\" Rosetta Code task rosettacode.org/wiki/Babylonian_spiral \"\"\"\n\nfrom itertools import accumulate\nfrom math import isqrt, atan2, tau\nfrom matplotlib.pyplot import axis, plot, show\n\n\nsquare_cache = []\n\ndef babylonian_spiral(nsteps):\n \"\"\"\n Get the points for each step along a Babylonia spiral of `nsteps` steps.\n Origin is at (0, 0) with first step one unit in the positive direction along\n the vertical (y) axis. The other points are selected to have integer x and y\n coordinates, progressively concatenating the next longest vector with integer\n x and y coordinates on the grid. The direction change of the new vector is\n chosen to be nonzero and clockwise in a direction that minimizes the change\n in direction from the previous vector.\n \n See also: oeis.org/A256111, oeis.org/A297346, oeis.org/A297347\n \"\"\"\n if len(square_cache) <= nsteps:\n square_cache.extend([x * x for x in range(len(square_cache), nsteps)])\n xydeltas = [(0, 0), (0, 1)]\n \u03b4squared = 1\n for _ in range(nsteps - 2):\n x, y = xydeltas[-1]\n \u03b8 = atan2(y, x)\n candidates = []\n while not candidates:\n \u03b4squared += 1\n for i, a in enumerate(square_cache):\n if a > \u03b4squared // 2:\n break\n for j in range(isqrt(\u03b4squared) + 1, 0, -1):\n b = square_cache[j]\n if a + b < \u03b4squared:\n break\n if a + b == \u03b4squared:\n candidates.extend([(i, j), (-i, j), (i, -j), (-i, -j), (j, i), (-j, i),\n (j, -i), (-j, -i)])\n\n p = min(candidates, key=lambda d: (\u03b8 - atan2(d[1], d[0])) % tau)\n xydeltas.append(p)\n\n return list(accumulate(xydeltas, lambda a, b: (a[0] + b[0], a[1] + b[1])))\n\n\npoints10000 = babylonian_spiral(10000)\nprint(\"The first 40 Babylonian spiral points are:\")\nfor i, p in enumerate(points10000[:40]):\n print(str(p).ljust(10), end = '\\n' if (i + 1) % 10 == 0 else '')\n\n# stretch portion of task\nplot(*zip(*points10000), color=\"navy\", linewidth=0.2)\naxis('scaled')\nshow()\n"} -{"title": "Balanced brackets", "language": "C", "task": "'''Task''': \n* Generate a string with '''N''' opening brackets '''[''' and with '''N''' closing brackets ''']''', in some arbitrary order. \n* Determine whether the generated string is ''balanced''; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.\n\n\n\n;Examples:\n (empty) OK\n [] OK \n [][] OK \n [[][]] OK \n ][ NOT OK\n ][][ NOT OK\n []][[] NOT OK\n\n", "solution": "#include\n#include\n#include\n\nint isBal(const char*s,int l){\n signed c=0;\n while(l--)\n\tif(s[l]==']') ++c;\n\telse if(s[l]=='[') if(--c<0) break;\n return !c;\n}\n\nvoid shuffle(char*s,int h){\n int x,t,i=h;\n while(i--){\n\tt=s[x=rand()%h];\n\ts[x]=s[i];\n\ts[i]=t;\n }\n}\n\nvoid genSeq(char*s,int n){\n if(n){\n\tmemset(s,'[',n);\n\tmemset(s+n,']',n);\n\tshuffle(s,n*2);\n }\n s[n*2]=0;\n}\n\nvoid doSeq(int n){\n char s[64];\n const char *o=\"False\";\n genSeq(s,n);\n if(isBal(s,n*2)) o=\"True\";\n printf(\"'%s': %s\\n\",s,o);\n}\n\nint main(){\n int n=0;\n while(n<9) doSeq(n++);\n return 0;\n}"} -{"title": "Balanced brackets", "language": "C++", "task": "'''Task''': \n* Generate a string with '''N''' opening brackets '''[''' and with '''N''' closing brackets ''']''', in some arbitrary order. \n* Determine whether the generated string is ''balanced''; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.\n\n\n\n;Examples:\n (empty) OK\n [] OK \n [][] OK \n [[][]] OK \n ][ NOT OK\n ][][ NOT OK\n []][[] NOT OK\n\n", "solution": "#include \n#include \n#include \n\nstd::string generate(int n, char left = '[', char right = ']')\n{\n std::string str(std::string(n, left) + std::string(n, right));\n std::random_shuffle(str.begin(), str.end());\n return str;\n}\n\nbool balanced(const std::string &str, char left = '[', char right = ']')\n{\n int count = 0;\n for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)\n {\n if (*it == left)\n count++;\n else if (*it == right)\n if (--count < 0) return false;\n }\n return count == 0;\n}\n\nint main()\n{\n srand(time(NULL)); // seed rng\n for (int i = 0; i < 9; ++i)\n {\n std::string s(generate(i));\n std::cout << (balanced(s) ? \" ok: \" : \"bad: \") << s << \"\\n\";\n }\n}"} -{"title": "Balanced brackets", "language": "JavaScript", "task": "'''Task''': \n* Generate a string with '''N''' opening brackets '''[''' and with '''N''' closing brackets ''']''', in some arbitrary order. \n* Determine whether the generated string is ''balanced''; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.\n\n\n\n;Examples:\n (empty) OK\n [] OK \n [][] OK \n [[][]] OK \n ][ NOT OK\n ][][ NOT OK\n []][[] NOT OK\n\n", "solution": "function shuffle(str) {\n var a = str.split(''), b, c = a.length, d\n while (c) b = Math.random() * c-- | 0, d = a[c], a[c] = a[b], a[b] = d\n return a.join('')\n}\n\nfunction isBalanced(str) {\n var a = str, b\n do { b = a, a = a.replace(/\\[\\]/g, '') } while (a != b)\n return !a\n}\n\nvar M = 20\nwhile (M-- > 0) {\n var N = Math.random() * 10 | 0, bs = shuffle('['.repeat(N) + ']'.repeat(N))\n console.log('\"' + bs + '\" is ' + (isBalanced(bs) ? '' : 'un') + 'balanced')\n}"} -{"title": "Balanced brackets", "language": "Python", "task": "'''Task''': \n* Generate a string with '''N''' opening brackets '''[''' and with '''N''' closing brackets ''']''', in some arbitrary order. \n* Determine whether the generated string is ''balanced''; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.\n\n\n\n;Examples:\n (empty) OK\n [] OK \n [][] OK \n [[][]] OK \n ][ NOT OK\n ][][ NOT OK\n []][[] NOT OK\n\n", "solution": ">>> def gen(N):\n... txt = ['[', ']'] * N\n... random.shuffle( txt )\n... return ''.join(txt)\n... \n>>> def balanced(txt):\n... braced = 0\n... for ch in txt:\n... if ch == '[': braced += 1\n... if ch == ']':\n... braced -= 1\n... if braced < 0: return False\n... return braced == 0\n... \n>>> for txt in (gen(N) for N in range(10)):\n... print (\"%-22r is%s balanced\" % (txt, '' if balanced(txt) else ' not'))\n... \n'' is balanced\n'[]' is balanced\n'[][]' is balanced\n'][[[]]' is not balanced\n'[]][[][]' is not balanced\n'[][[][]]][' is not balanced\n'][]][][[]][[' is not balanced\n'[[]]]]][]][[[[' is not balanced\n'[[[[]][]]][[][]]' is balanced\n'][[][[]]][]]][[[[]' is not balanced"} -{"title": "Balanced brackets", "language": "Python 3.2", "task": "'''Task''': \n* Generate a string with '''N''' opening brackets '''[''' and with '''N''' closing brackets ''']''', in some arbitrary order. \n* Determine whether the generated string is ''balanced''; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.\n\n\n\n;Examples:\n (empty) OK\n [] OK \n [][] OK \n [[][]] OK \n ][ NOT OK\n ][][ NOT OK\n []][[] NOT OK\n\n", "solution": ">>> from itertools import accumulate\n>>> from random import shuffle\n>>> def gen(n):\n... txt = list('[]' * n)\n... shuffle(txt)\n... return ''.join(txt)\n...\n>>> def balanced(txt):\n... brackets = ({'[': 1, ']': -1}.get(ch, 0) for ch in txt)\n... return all(x>=0 for x in accumulate(brackets))\n...\n>>> for txt in (gen(N) for N in range(10)):\n... print (\"%-22r is%s balanced\" % (txt, '' if balanced(txt) else ' not'))\n...\n'' is balanced\n'][' is not balanced\n'[]][' is not balanced\n']][[[]' is not balanced\n'][[][][]' is not balanced\n'[[[][][]]]' is balanced\n'][[[][][]][]' is not balanced\n'][]][][[]][[][' is not balanced\n'][[]]][][[]][[[]' is not balanced\n'][[][[]]]][[[]][][' is not balanced"} -{"title": "Balanced ternary", "language": "C++", "task": "Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or -1. \n\n\n;Examples:\nDecimal 11 = 32 + 31 - 30, thus it can be written as \"++-\"\n\nDecimal 6 = 32 - 31 + 0 x 30, thus it can be written as \"+-0\"\n\n\n;Task:\nImplement balanced ternary representation of integers with the following:\n# Support arbitrarily large integers, both positive and negative;\n# Provide ways to convert to and from text strings, using digits '+', '-' and '0' (unless you are already using strings to represent balanced ternary; but see requirement 5).\n# Provide ways to convert to and from native integer type (unless, improbably, your platform's native integer type ''is'' balanced ternary). If your native integers can't support arbitrary length, overflows during conversion must be indicated.\n# Provide ways to perform addition, negation and multiplication directly on balanced ternary integers; do ''not'' convert to native integers first.\n# Make your implementation efficient, with a reasonable definition of \"efficient\" (and with a reasonable definition of \"reasonable\").\n\n\n'''Test case''' With balanced ternaries ''a'' from string \"+-0++0+\", ''b'' from native integer -436, ''c'' \"+-++-\":\n* write out ''a'', ''b'' and ''c'' in decimal notation;\n* calculate ''a'' x (''b'' - ''c''), write out the result in both ternary and decimal notations.\n\n\n'''Note:''' The pages floating point balanced ternary.\n\n", "solution": "#include \n#include \n#include \nusing namespace std;\n\nclass BalancedTernary {\nprotected:\n\t// Store the value as a reversed string of +, 0 and - characters\n\tstring value;\n\n\t// Helper function to change a balanced ternary character to an integer\n\tint charToInt(char c) const {\n\t\tif (c == '0')\n\t\t\treturn 0;\n\t\treturn 44 - c;\n\t}\n\n\t// Helper function to negate a string of ternary characters\n\tstring negate(string s) const {\n\t\tfor (int i = 0; i < s.length(); ++i) {\n\t\t\tif (s[i] == '+')\n\t\t\t\ts[i] = '-';\n\t\t\telse if (s[i] == '-')\n\t\t\t\ts[i] = '+';\n\t\t}\n\t\treturn s;\n\t}\n\npublic:\n\t// Default constructor\n\tBalancedTernary() {\n\t\tvalue = \"0\";\n\t}\n\n\t// Construct from a string\n\tBalancedTernary(string s) {\n\t\tvalue = string(s.rbegin(), s.rend());\n\t}\n\n\t// Construct from an integer\n\tBalancedTernary(long long n) {\n\t\tif (n == 0) {\n\t\t\tvalue = \"0\";\n\t\t\treturn;\n\t\t}\n\n\t\tbool neg = n < 0;\n\t\tif (neg) \n\t\t\tn = -n;\n\n\t\tvalue = \"\";\n\t\twhile (n != 0) {\n\t\t\tint r = n % 3;\n\t\t\tif (r == 0)\n\t\t\t\tvalue += \"0\";\n\t\t\telse if (r == 1)\n\t\t\t\tvalue += \"+\";\n\t\t\telse {\n\t\t\t\tvalue += \"-\";\n\t\t\t\t++n;\n\t\t\t}\n\n\t\t\tn /= 3;\n\t\t}\n\n\t\tif (neg)\n\t\t\tvalue = negate(value);\n\t}\n\n\t// Copy constructor\n\tBalancedTernary(const BalancedTernary &n) {\n\t\tvalue = n.value;\n\t}\n\n\t// Addition operators\n\tBalancedTernary operator+(BalancedTernary n) const {\n\t\tn += *this;\n\t\treturn n;\n\t}\n\n\tBalancedTernary& operator+=(const BalancedTernary &n) {\n\t\tstatic char *add = \"0+-0+-0\";\n\t\tstatic char *carry = \"--000++\";\n\n\t\tint lastNonZero = 0;\n\t\tchar c = '0';\n\t\tfor (int i = 0; i < value.length() || i < n.value.length(); ++i) {\n\t\t\tchar a = i < value.length() ? value[i] : '0';\n\t\t\tchar b = i < n.value.length() ? n.value[i] : '0';\n\n\t\t\tint sum = charToInt(a) + charToInt(b) + charToInt(c) + 3;\n\t\t\tc = carry[sum];\n\n\t\t\tif (i < value.length())\n\t\t\t\tvalue[i] = add[sum];\n\t\t\telse\n\t\t\t\tvalue += add[sum];\n\n\t\t\tif (add[sum] != '0')\n\t\t\t\tlastNonZero = i;\n\t\t}\n\n\t\tif (c != '0')\n\t\t\tvalue += c;\n\t\telse\n\t\t\tvalue = value.substr(0, lastNonZero + 1); // Chop off leading zeroes\n\n\t\treturn *this;\n\t}\n\n\t// Negation operator\n\tBalancedTernary operator-() const {\n\t\tBalancedTernary result;\n\t\tresult.value = negate(value);\n\t\treturn result;\n\t}\n\n\t// Subtraction operators\n\tBalancedTernary operator-(const BalancedTernary &n) const {\n\t\treturn operator+(-n);\n\t}\n\n\tBalancedTernary& operator-=(const BalancedTernary &n) {\n\t\treturn operator+=(-n);\n\t}\n\n\t// Multiplication operators\n\tBalancedTernary operator*(BalancedTernary n) const {\n\t\tn *= *this;\n\t\treturn n;\n\t}\n\n\tBalancedTernary& operator*=(const BalancedTernary &n) {\n\t\tBalancedTernary pos = *this;\n\t\tBalancedTernary neg = -pos; // Storing an extra copy to avoid negating repeatedly\n\t\tvalue = \"0\";\n\n\t\tfor (int i = 0; i < n.value.length(); ++i) {\n\t\t\tif (n.value[i] == '+')\n\t\t\t\toperator+=(pos);\n\t\t\telse if (n.value[i] == '-')\n\t\t\t\toperator+=(neg);\n\t\t\tpos.value = '0' + pos.value;\n\t\t\tneg.value = '0' + neg.value;\n\t\t}\n\n\t\treturn *this;\n\t}\n\n\t// Stream output operator\n\tfriend ostream& operator<<(ostream &out, const BalancedTernary &n) {\n\t\tout << n.toString();\n\t\treturn out;\n\t}\n\n\t// Convert to string\n\tstring toString() const {\n\t\treturn string(value.rbegin(), value.rend());\n\t}\n\n\t// Convert to integer\n\tlong long toInt() const {\n\t\tlong long result = 0;\n\t\tfor (long long i = 0, pow = 1; i < value.length(); ++i, pow *= 3)\n\t\t\tresult += pow * charToInt(value[i]);\n\t\treturn result;\n\t}\n\n\t// Convert to integer if possible\n\tbool tryInt(long long &out) const {\n\t\tlong long result = 0;\n\t\tbool ok = true;\n\n\t\tfor (long long i = 0, pow = 1; i < value.length() && ok; ++i, pow *= 3) {\n\t\t\tif (value[i] == '+') {\n\t\t\t\tok &= LLONG_MAX - pow >= result; // Clear ok if the result overflows\n\t\t\t\tresult += pow;\n\t\t\t} else if (value[i] == '-') {\n\t\t\t\tok &= LLONG_MIN + pow <= result; // Clear ok if the result overflows\n\t\t\t\tresult -= pow;\n\t\t\t}\n\t\t}\n\n\t\tif (ok)\n\t\t\tout = result;\n\t\treturn ok;\n\t}\n};\n\nint main() {\n\tBalancedTernary a(\"+-0++0+\");\n\tBalancedTernary b(-436);\n\tBalancedTernary c(\"+-++-\");\n\n\tcout << \"a = \" << a << \" = \" << a.toInt() << endl;\n\tcout << \"b = \" << b << \" = \" << b.toInt() << endl;\n\tcout << \"c = \" << c << \" = \" << c.toInt() << endl;\n\n\tBalancedTernary d = a * (b - c);\n\n\tcout << \"a * (b - c) = \" << d << \" = \" << d.toInt() << endl;\n\n\tBalancedTernary e(\"+++++++++++++++++++++++++++++++++++++++++\");\n\n\tlong long n;\n\tif (e.tryInt(n))\n\t\tcout << \"e = \" << e << \" = \" << n << endl;\n\telse\n\t\tcout << \"e = \" << e << \" is too big to fit in a long long\" << endl;\n\n\treturn 0;\n}\n"} -{"title": "Balanced ternary", "language": "Python from Common Lisp", "task": "Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or -1. \n\n\n;Examples:\nDecimal 11 = 32 + 31 - 30, thus it can be written as \"++-\"\n\nDecimal 6 = 32 - 31 + 0 x 30, thus it can be written as \"+-0\"\n\n\n;Task:\nImplement balanced ternary representation of integers with the following:\n# Support arbitrarily large integers, both positive and negative;\n# Provide ways to convert to and from text strings, using digits '+', '-' and '0' (unless you are already using strings to represent balanced ternary; but see requirement 5).\n# Provide ways to convert to and from native integer type (unless, improbably, your platform's native integer type ''is'' balanced ternary). If your native integers can't support arbitrary length, overflows during conversion must be indicated.\n# Provide ways to perform addition, negation and multiplication directly on balanced ternary integers; do ''not'' convert to native integers first.\n# Make your implementation efficient, with a reasonable definition of \"efficient\" (and with a reasonable definition of \"reasonable\").\n\n\n'''Test case''' With balanced ternaries ''a'' from string \"+-0++0+\", ''b'' from native integer -436, ''c'' \"+-++-\":\n* write out ''a'', ''b'' and ''c'' in decimal notation;\n* calculate ''a'' x (''b'' - ''c''), write out the result in both ternary and decimal notations.\n\n\n'''Note:''' The pages floating point balanced ternary.\n\n", "solution": "class BalancedTernary:\n # Represented as a list of 0, 1 or -1s, with least significant digit first.\n\n str2dig = {'+': 1, '-': -1, '0': 0} # immutable\n dig2str = {1: '+', -1: '-', 0: '0'} # immutable\n table = ((0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)) # immutable\n\n def __init__(self, inp):\n if isinstance(inp, str):\n self.digits = [BalancedTernary.str2dig[c] for c in reversed(inp)]\n elif isinstance(inp, int):\n self.digits = self._int2ternary(inp)\n elif isinstance(inp, BalancedTernary):\n self.digits = list(inp.digits)\n elif isinstance(inp, list):\n if all(d in (0, 1, -1) for d in inp):\n self.digits = list(inp)\n else:\n raise ValueError(\"BalancedTernary: Wrong input digits.\")\n else:\n raise TypeError(\"BalancedTernary: Wrong constructor input.\")\n\n @staticmethod\n def _int2ternary(n):\n if n == 0: return []\n if (n % 3) == 0: return [0] + BalancedTernary._int2ternary(n // 3)\n if (n % 3) == 1: return [1] + BalancedTernary._int2ternary(n // 3)\n if (n % 3) == 2: return [-1] + BalancedTernary._int2ternary((n + 1) // 3)\n\n def to_int(self):\n return reduce(lambda y,x: x + 3 * y, reversed(self.digits), 0)\n\n def __repr__(self):\n if not self.digits: return \"0\"\n return \"\".join(BalancedTernary.dig2str[d] for d in reversed(self.digits))\n\n @staticmethod\n def _neg(digs):\n return [-d for d in digs]\n\n def __neg__(self):\n return BalancedTernary(BalancedTernary._neg(self.digits))\n\n @staticmethod\n def _add(a, b, c=0):\n if not (a and b):\n if c == 0:\n return a or b\n else:\n return BalancedTernary._add([c], a or b)\n else:\n (d, c) = BalancedTernary.table[3 + (a[0] if a else 0) + (b[0] if b else 0) + c]\n res = BalancedTernary._add(a[1:], b[1:], c)\n # trim leading zeros\n if res or d != 0:\n return [d] + res\n else:\n return res\n\n def __add__(self, b):\n return BalancedTernary(BalancedTernary._add(self.digits, b.digits))\n\n def __sub__(self, b):\n return self + (-b)\n\n @staticmethod\n def _mul(a, b):\n if not (a and b):\n return []\n else:\n if a[0] == -1: x = BalancedTernary._neg(b)\n elif a[0] == 0: x = []\n elif a[0] == 1: x = b\n else: assert False\n y = [0] + BalancedTernary._mul(a[1:], b)\n return BalancedTernary._add(x, y)\n\n def __mul__(self, b):\n return BalancedTernary(BalancedTernary._mul(self.digits, b.digits))\n\n\ndef main():\n a = BalancedTernary(\"+-0++0+\")\n print \"a:\", a.to_int(), a\n\n b = BalancedTernary(-436)\n print \"b:\", b.to_int(), b\n\n c = BalancedTernary(\"+-++-\")\n print \"c:\", c.to_int(), c\n\n r = a * (b - c)\n print \"a * (b - c):\", r.to_int(), r\n\nmain()"} -{"title": "Barnsley fern", "language": "C", "task": "A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).\n\n\n;Task:\nCreate this fractal fern, using the following transformations:\n* f1 (chosen 1% of the time)\n xn + 1 = 0\n yn + 1 = 0.16 yn\n\n* f2 (chosen 85% of the time)\n xn + 1 = 0.85 xn + 0.04 yn\n yn + 1 = -0.04 xn + 0.85 yn + 1.6\n\n* f3 (chosen 7% of the time)\n xn + 1 = 0.2 xn - 0.26 yn\n yn + 1 = 0.23 xn + 0.22 yn + 1.6\n\n* f4 (chosen 7% of the time)\n xn + 1 = -0.15 xn + 0.28 yn\n yn + 1 = 0.26 xn + 0.24 yn + 0.44.\n\nStarting position: x = 0, y = 0\n\n", "solution": "#include\n#include\n#include\n#include\n\nvoid barnsleyFern(int windowWidth, unsigned long iter){\n\t\n\tdouble x0=0,y0=0,x1,y1;\n\tint diceThrow;\n\ttime_t t;\n\tsrand((unsigned)time(&t));\n\t\n\twhile(iter>0){\n\t\tdiceThrow = rand()%100;\n\t\t\n\t\tif(diceThrow==0){\n\t\t\tx1 = 0;\n\t\t\ty1 = 0.16*y0;\n\t\t}\n\t\t\n\t\telse if(diceThrow>=1 && diceThrow<=7){\n\t\t\tx1 = -0.15*x0 + 0.28*y0;\n\t\t\ty1 = 0.26*x0 + 0.24*y0 + 0.44;\n\t\t}\n\t\t\n\t\telse if(diceThrow>=8 && diceThrow<=15){\n\t\t\tx1 = 0.2*x0 - 0.26*y0;\n\t\t\ty1 = 0.23*x0 + 0.22*y0 + 1.6;\n\t\t}\n\t\t\n\t\telse{\n\t\t\tx1 = 0.85*x0 + 0.04*y0;\n\t\t\ty1 = -0.04*x0 + 0.85*y0 + 1.6;\n\t\t}\n\t\t\n\t\tputpixel(30*x1 + windowWidth/2.0,30*y1,GREEN);\n\t\t\n\t\tx0 = x1;\n\t\ty0 = y1;\n\t\t\n\t\titer--;\n\t}\n\n}\n\nint main()\n{\n\tunsigned long num;\n\t\n\tprintf(\"Enter number of iterations : \");\n\tscanf(\"%ld\",&num);\n\t\n\tinitwindow(500,500,\"Barnsley Fern\");\n\t\n\tbarnsleyFern(500,num);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n}\n"} -{"title": "Barnsley fern", "language": "C++", "task": "A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).\n\n\n;Task:\nCreate this fractal fern, using the following transformations:\n* f1 (chosen 1% of the time)\n xn + 1 = 0\n yn + 1 = 0.16 yn\n\n* f2 (chosen 85% of the time)\n xn + 1 = 0.85 xn + 0.04 yn\n yn + 1 = -0.04 xn + 0.85 yn + 1.6\n\n* f3 (chosen 7% of the time)\n xn + 1 = 0.2 xn - 0.26 yn\n yn + 1 = 0.23 xn + 0.22 yn + 1.6\n\n* f4 (chosen 7% of the time)\n xn + 1 = -0.15 xn + 0.28 yn\n yn + 1 = 0.26 xn + 0.24 yn + 0.44.\n\nStarting position: x = 0, y = 0\n\n", "solution": "#include \n#include \n#include \n\nconst int BMP_SIZE = 600, ITERATIONS = static_cast( 15e5 );\n\nclass myBitmap {\npublic:\n myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n ~myBitmap() {\n DeleteObject( pen ); DeleteObject( brush );\n DeleteDC( hdc ); DeleteObject( bmp );\n }\n bool create( int w, int h ) {\n BITMAPINFO bi;\n ZeroMemory( &bi, sizeof( bi ) );\n bi.bmiHeader.biSize = sizeof( bi.bmiHeader );\n bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n bi.bmiHeader.biCompression = BI_RGB;\n bi.bmiHeader.biPlanes = 1;\n bi.bmiHeader.biWidth = w;\n bi.bmiHeader.biHeight = -h;\n HDC dc = GetDC( GetConsoleWindow() );\n bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n if( !bmp ) return false;\n hdc = CreateCompatibleDC( dc );\n SelectObject( hdc, bmp );\n ReleaseDC( GetConsoleWindow(), dc );\n width = w; height = h;\n return true;\n }\n void clear( BYTE clr = 0 ) {\n memset( pBits, clr, width * height * sizeof( DWORD ) );\n }\n void setBrushColor( DWORD bClr ) {\n if( brush ) DeleteObject( brush );\n brush = CreateSolidBrush( bClr );\n SelectObject( hdc, brush );\n }\n void setPenColor( DWORD c ) {\n clr = c; createPen();\n }\n void setPenWidth( int w ) {\n wid = w; createPen();\n }\n void saveBitmap( std::string path ) {\n BITMAPFILEHEADER fileheader;\n BITMAPINFO infoheader;\n BITMAP bitmap;\n DWORD wb;\n GetObject( bmp, sizeof( bitmap ), &bitmap );\n DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n infoheader.bmiHeader.biCompression = BI_RGB;\n infoheader.bmiHeader.biPlanes = 1;\n infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n fileheader.bfType = 0x4D42;\n fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n FILE_ATTRIBUTE_NORMAL, NULL );\n WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n CloseHandle( file );\n delete [] dwpBits;\n }\n HDC getDC() const { return hdc; }\n int getWidth() const { return width; }\n int getHeight() const { return height; }\nprivate:\n void createPen() {\n if( pen ) DeleteObject( pen );\n pen = CreatePen( PS_SOLID, wid, clr );\n SelectObject( hdc, pen );\n }\n HBITMAP bmp; HDC hdc;\n HPEN pen; HBRUSH brush;\n void *pBits; int width, height, wid;\n DWORD clr;\n};\nclass fern {\npublic:\n void draw() {\n bmp.create( BMP_SIZE, BMP_SIZE );\n float x = 0, y = 0; HDC dc = bmp.getDC();\n int hs = BMP_SIZE >> 1;\n for( int f = 0; f < ITERATIONS; f++ ) {\n SetPixel( dc, hs + static_cast( x * 55.f ), \n BMP_SIZE - 15 - static_cast( y * 55.f ), \n RGB( static_cast( rnd() * 80.f ) + 20, \n static_cast( rnd() * 128.f ) + 128, \n static_cast( rnd() * 80.f ) + 30 ) ); \n getXY( x, y );\n }\n bmp.saveBitmap( \"./bf.bmp\" );\n }\nprivate:\n void getXY( float& x, float& y ) {\n float g, xl, yl;\n g = rnd();\n if( g < .01f ) { xl = 0; yl = .16f * y; } \n else if( g < .07f ) {\n xl = .2f * x - .26f * y;\n yl = .23f * x + .22f * y + 1.6f;\n } else if( g < .14f ) {\n xl = -.15f * x + .28f * y;\n yl = .26f * x + .24f * y + .44f;\n } else {\n xl = .85f * x + .04f * y;\n yl = -.04f * x + .85f * y + 1.6f;\n }\n x = xl; y = yl;\n }\n float rnd() {\n return static_cast( rand() ) / static_cast( RAND_MAX );\n }\n myBitmap bmp;\n};\nint main( int argc, char* argv[]) {\n srand( static_cast( time( 0 ) ) );\n fern f; f.draw(); return 0; \n}\n"} -{"title": "Barnsley fern", "language": "JavaScript from PARI/GP", "task": "A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).\n\n\n;Task:\nCreate this fractal fern, using the following transformations:\n* f1 (chosen 1% of the time)\n xn + 1 = 0\n yn + 1 = 0.16 yn\n\n* f2 (chosen 85% of the time)\n xn + 1 = 0.85 xn + 0.04 yn\n yn + 1 = -0.04 xn + 0.85 yn + 1.6\n\n* f3 (chosen 7% of the time)\n xn + 1 = 0.2 xn - 0.26 yn\n yn + 1 = 0.23 xn + 0.22 yn + 1.6\n\n* f4 (chosen 7% of the time)\n xn + 1 = -0.15 xn + 0.28 yn\n yn + 1 = 0.26 xn + 0.24 yn + 0.44.\n\nStarting position: x = 0, y = 0\n\n", "solution": "// Barnsley fern fractal\n//6/17/16 aev\nfunction pBarnsleyFern(canvasId, lim) {\n // DCLs\n var canvas = document.getElementById(canvasId);\n var ctx = canvas.getContext(\"2d\");\n var w = canvas.width;\n var h = canvas.height;\n var x = 0.,\n y = 0.,\n xw = 0.,\n yw = 0.,\n r;\n // Like in PARI/GP: return random number 0..max-1\n function randgp(max) {\n return Math.floor(Math.random() * max)\n }\n // Clean canvas\n ctx.fillStyle = \"white\";\n ctx.fillRect(0, 0, w, h);\n // MAIN LOOP\n for (var i = 0; i < lim; i++) {\n r = randgp(100);\n if (r <= 1) {\n xw = 0;\n yw = 0.16 * y;\n } else if (r <= 8) {\n xw = 0.2 * x - 0.26 * y;\n yw = 0.23 * x + 0.22 * y + 1.6;\n } else if (r <= 15) {\n xw = -0.15 * x + 0.28 * y;\n yw = 0.26 * x + 0.24 * y + 0.44;\n } else {\n xw = 0.85 * x + 0.04 * y;\n yw = -0.04 * x + 0.85 * y + 1.6;\n }\n x = xw;\n y = yw;\n ctx.fillStyle = \"green\";\n ctx.fillRect(x * 50 + 260, -y * 50 + 540, 1, 1);\n } //fend i\n}"} -{"title": "Barnsley fern", "language": "Python", "task": "A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).\n\n\n;Task:\nCreate this fractal fern, using the following transformations:\n* f1 (chosen 1% of the time)\n xn + 1 = 0\n yn + 1 = 0.16 yn\n\n* f2 (chosen 85% of the time)\n xn + 1 = 0.85 xn + 0.04 yn\n yn + 1 = -0.04 xn + 0.85 yn + 1.6\n\n* f3 (chosen 7% of the time)\n xn + 1 = 0.2 xn - 0.26 yn\n yn + 1 = 0.23 xn + 0.22 yn + 1.6\n\n* f4 (chosen 7% of the time)\n xn + 1 = -0.15 xn + 0.28 yn\n yn + 1 = 0.26 xn + 0.24 yn + 0.44.\n\nStarting position: x = 0, y = 0\n\n", "solution": "import random\nfrom PIL import Image\n\n\nclass BarnsleyFern(object):\n def __init__(self, img_width, img_height, paint_color=(0, 150, 0),\n bg_color=(255, 255, 255)):\n self.img_width, self.img_height = img_width, img_height\n self.paint_color = paint_color\n self.x, self.y = 0, 0\n self.age = 0\n\n self.fern = Image.new('RGB', (img_width, img_height), bg_color)\n self.pix = self.fern.load()\n self.pix[self.scale(0, 0)] = paint_color\n\n def scale(self, x, y):\n h = (x + 2.182)*(self.img_width - 1)/4.8378\n k = (9.9983 - y)*(self.img_height - 1)/9.9983\n return h, k\n\n def transform(self, x, y):\n rand = random.uniform(0, 100)\n if rand < 1:\n return 0, 0.16*y\n elif 1 <= rand < 86:\n return 0.85*x + 0.04*y, -0.04*x + 0.85*y + 1.6\n elif 86 <= rand < 93:\n return 0.2*x - 0.26*y, 0.23*x + 0.22*y + 1.6\n else:\n return -0.15*x + 0.28*y, 0.26*x + 0.24*y + 0.44\n\n def iterate(self, iterations):\n for _ in range(iterations):\n self.x, self.y = self.transform(self.x, self.y)\n self.pix[self.scale(self.x, self.y)] = self.paint_color\n self.age += iterations\n\nfern = BarnsleyFern(500, 500)\nfern.iterate(1000000)\nfern.fern.show()\n"} -{"title": "Base64 decode data", "language": "C++14", "task": "See [[Base64 encode data]]. \n\nNow write a program that takes the output of the [[Base64 encode data]] task as input and regenerate the original file. \n\nWhen working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.\n\n", "solution": "#include \n#include \n#include \n#include \n\ntypedef unsigned char ubyte;\nconst auto BASE64 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\nstd::vector encode(const std::vector& source) {\n auto it = source.cbegin();\n auto end = source.cend();\n\n std::vector sink;\n while (it != end) {\n auto b1 = *it++;\n int acc;\n\n sink.push_back(BASE64[b1 >> 2]); // first output (first six bits from b1)\n\n acc = (b1 & 0x3) << 4; // last two bits from b1\n if (it != end) {\n auto b2 = *it++;\n acc |= (b2 >> 4); // first four bits from b2\n\n sink.push_back(BASE64[acc]); // second output\n\n acc = (b2 & 0xF) << 2; // last four bits from b2\n if (it != end) {\n auto b3 = *it++;\n acc |= (b3 >> 6); // first two bits from b3\n\n sink.push_back(BASE64[acc]); // third output\n sink.push_back(BASE64[b3 & 0x3F]); // fouth output (final six bits from b3)\n } else {\n sink.push_back(BASE64[acc]); // third output\n sink.push_back('='); // fourth output (1 byte padding)\n }\n } else {\n sink.push_back(BASE64[acc]); // second output\n sink.push_back('='); // third output (first padding byte)\n sink.push_back('='); // fourth output (second padding byte)\n }\n }\n return sink;\n}\n\nint findIndex(ubyte val) {\n if ('A' <= val && val <= 'Z') {\n return val - 'A';\n }\n if ('a' <= val && val <= 'z') {\n return val - 'a' + 26;\n }\n if ('0' <= val && val <= '9') {\n return val - '0' + 52;\n }\n if ('+' == val) {\n return 62;\n }\n if ('/' == val) {\n return 63;\n }\n return -1;\n}\n\nstd::vector decode(const std::vector& source) {\n if (source.size() % 4 != 0) {\n throw new std::runtime_error(\"Error in size to the decode method\");\n }\n\n auto it = source.cbegin();\n auto end = source.cend();\n\n std::vector sink;\n while (it != end) {\n auto b1 = *it++;\n auto b2 = *it++;\n auto b3 = *it++; // might be first padding byte\n auto b4 = *it++; // might be first or second padding byte\n\n auto i1 = findIndex(b1);\n auto i2 = findIndex(b2);\n auto acc = i1 << 2; // six bits came from the first byte\n acc |= i2 >> 4; // two bits came from the first byte\n\n sink.push_back(acc); // output the first byte\n\n if (b3 != '=') {\n auto i3 = findIndex(b3);\n\n acc = (i2 & 0xF) << 4; // four bits came from the second byte\n acc |= i3 >> 2; // four bits came from the second byte\n\n sink.push_back(acc); // output the second byte\n\n if (b4 != '=') {\n auto i4 = findIndex(b4);\n\n acc = (i3 & 0x3) << 6; // two bits came from the third byte\n acc |= i4; // six bits came from the third byte\n\n sink.push_back(acc); // output the third byte\n }\n }\n }\n return sink;\n}\n\nint main() {\n using namespace std;\n\n string data = \"VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLVBhdWwgUi5FaHJsaWNo\";\n vector datav{ begin(data), end(data) };\n cout << data << \"\\n\\n\" << decode(datav).data() << endl;\n\n return 0;\n}"} -{"title": "Base64 decode data", "language": "JavaScript", "task": "See [[Base64 encode data]]. \n\nNow write a program that takes the output of the [[Base64 encode data]] task as input and regenerate the original file. \n\nWhen working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.\n\n", "solution": "// define base64 data; in this case the data is the string: \"Hello, world!\"\nconst base64 = Buffer.from('SGVsbG8sIHdvcmxkIQ==', 'base64');\n// .toString() is a built-in method.\nconsole.log(base64.toString());"} -{"title": "Base64 decode data", "language": "Python", "task": "See [[Base64 encode data]]. \n\nNow write a program that takes the output of the [[Base64 encode data]] task as input and regenerate the original file. \n\nWhen working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.\n\n", "solution": "import base64\ndata = 'VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g='\nprint(base64.b64decode(data).decode('utf-8'))\n"} -{"title": "Bell numbers", "language": "Python 2.7", "task": "Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly '''n''' elements. Each element of the sequence '''Bn''' is the number of partitions of a set of size '''n''' where order of the elements and order of the partitions are non-significant. E.G.: '''{a b}''' is the same as '''{b a}''' and '''{a} {b}''' is the same as '''{b} {a}'''.\n\n\n;So:\n\n:'''B0 = 1''' trivially. There is only one way to partition a set with zero elements. '''{ }'''\n\n:'''B1 = 1''' There is only one way to partition a set with one element. '''{a}'''\n\n:'''B2 = 2''' Two elements may be partitioned in two ways. '''{a} {b}, {a b}'''\n\n:'''B3 = 5''' Three elements may be partitioned in five ways '''{a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}'''\n\n: and so on.\n\n\nA simple way to find the Bell numbers is construct a '''Bell triangle''', also known as an '''Aitken's array''' or '''Peirce triangle''', and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.\n\n\n;Task:\n\nWrite a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the '''first 15''' and (if your language supports big Integers) '''50th''' elements of the sequence. \n\nIf you ''do'' use the Bell triangle method to generate the numbers, also show the '''first ten rows''' of the Bell triangle.\n\n\n;See also:\n\n:* '''OEIS:A000110 Bell or exponential numbers'''\n:* '''OEIS:A011971 Aitken's array'''\n\n", "solution": "def bellTriangle(n):\n tri = [None] * n\n for i in xrange(n):\n tri[i] = [0] * i\n tri[1][0] = 1\n for i in xrange(2, n):\n tri[i][0] = tri[i - 1][i - 2]\n for j in xrange(1, i):\n tri[i][j] = tri[i][j - 1] + tri[i - 1][j - 1]\n return tri\n\ndef main():\n bt = bellTriangle(51)\n print \"First fifteen and fiftieth Bell numbers:\"\n for i in xrange(1, 16):\n print \"%2d: %d\" % (i, bt[i][0])\n print \"50:\", bt[50][0]\n print\n print \"The first ten rows of Bell's triangle:\"\n for i in xrange(1, 11):\n print bt[i]\n\nmain()"} -{"title": "Bell numbers", "language": "Python 3.7", "task": "Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly '''n''' elements. Each element of the sequence '''Bn''' is the number of partitions of a set of size '''n''' where order of the elements and order of the partitions are non-significant. E.G.: '''{a b}''' is the same as '''{b a}''' and '''{a} {b}''' is the same as '''{b} {a}'''.\n\n\n;So:\n\n:'''B0 = 1''' trivially. There is only one way to partition a set with zero elements. '''{ }'''\n\n:'''B1 = 1''' There is only one way to partition a set with one element. '''{a}'''\n\n:'''B2 = 2''' Two elements may be partitioned in two ways. '''{a} {b}, {a b}'''\n\n:'''B3 = 5''' Three elements may be partitioned in five ways '''{a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}'''\n\n: and so on.\n\n\nA simple way to find the Bell numbers is construct a '''Bell triangle''', also known as an '''Aitken's array''' or '''Peirce triangle''', and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.\n\n\n;Task:\n\nWrite a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the '''first 15''' and (if your language supports big Integers) '''50th''' elements of the sequence. \n\nIf you ''do'' use the Bell triangle method to generate the numbers, also show the '''first ten rows''' of the Bell triangle.\n\n\n;See also:\n\n:* '''OEIS:A000110 Bell or exponential numbers'''\n:* '''OEIS:A011971 Aitken's array'''\n\n", "solution": "'''Bell numbers'''\n\nfrom itertools import accumulate, chain, islice\nfrom operator import add, itemgetter\nfrom functools import reduce\n\n\n# bellNumbers :: [Int]\ndef bellNumbers():\n '''Bell or exponential numbers.\n A000110\n '''\n return map(itemgetter(0), bellTriangle())\n\n\n# bellTriangle :: [[Int]]\ndef bellTriangle():\n '''Bell triangle.'''\n return map(\n itemgetter(1),\n iterate(\n compose(\n bimap(last)(identity),\n list, uncurry(scanl(add))\n )\n )((1, [1]))\n )\n\n\n# ------------------------- TEST --------------------------\n# main :: IO ()\ndef main():\n '''Tests'''\n showIndex = compose(repr, succ, itemgetter(0))\n showValue = compose(repr, itemgetter(1))\n print(\n fTable(\n 'First fifteen Bell numbers:'\n )(showIndex)(showValue)(identity)(list(\n enumerate(take(15)(bellNumbers()))\n ))\n )\n\n print('\\nFiftieth Bell number:')\n bells = bellNumbers()\n drop(49)(bells)\n print(\n next(bells)\n )\n\n print(\n fTable(\n \"\\nFirst 10 rows of Bell's triangle:\"\n )(showIndex)(showValue)(identity)(list(\n enumerate(take(10)(bellTriangle()))\n ))\n )\n\n\n# ------------------------ GENERIC ------------------------\n\n# bimap :: (a -> b) -> (c -> d) -> (a, c) -> (b, d)\ndef 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 '''\n def go(g):\n def gox(x):\n return (f(x), g(x))\n return gox\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# 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 '''\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 go\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 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, ' ') + ' -> ' + fxShow(f(x))\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# identity :: a -> a\ndef identity(x):\n '''The identity function.'''\n return x\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# last :: [a] -> a\ndef last(xs):\n '''The last element of a non-empty list.'''\n return xs[-1]\n\n\n# scanl :: (b -> a -> b) -> b -> [a] -> [b]\ndef scanl(f):\n '''scanl is like reduce, but returns a succession of\n intermediate values, building from the left.\n '''\n def go(a):\n def g(xs):\n return accumulate(chain([a], xs), f)\n return g\n return go\n\n\n# succ :: Enum a => a -> a\ndef succ(x):\n '''The successor of a value.\n For numeric types, (1 +).\n '''\n return 1 + x\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 def go(xs):\n return (\n xs[0:n]\n if isinstance(xs, (list, tuple))\n else list(islice(xs, n))\n )\n return go\n\n\n# uncurry :: (a -> b -> c) -> ((a, b) -> c)\ndef uncurry(f):\n '''A function over a tuple,\n derived from a curried function.\n '''\n def go(tpl):\n return f(tpl[0])(tpl[1])\n return go\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} -{"title": "Benford's law", "language": "C", "task": "{{Wikipedia|Benford's_law}}\n\n\n'''Benford's law''', also called the '''first-digit law''', refers to the frequency distribution of digits in many (but not all) real-life sources of data. \n\nIn this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. \n\nBenford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.\n\nThis result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.\n\nA set of numbers is said to satisfy Benford's law if the leading digit d (d \\in \\{1, \\ldots, 9\\}) occurs with probability\n\n:::: P(d) = \\log_{10}(d+1)-\\log_{10}(d) = \\log_{10}\\left(1+\\frac{1}{d}\\right)\n\nFor this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).\n\nUse the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. \n\nYou can generate them or load them from a file; whichever is easiest. \n\nDisplay your actual vs expected distribution.\n\n\n''For extra credit:'' Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.\n\n\n;See also:\n* numberphile.com.\n* A starting page on Wolfram Mathworld is {{Wolfram|Benfords|Law}}.\n\n", "solution": "#include \n#include \n#include \n\nfloat *benford_distribution(void)\n{\n static float prob[9];\n for (int i = 1; i < 10; i++)\n prob[i - 1] = log10f(1 + 1.0 / i);\n\n return prob;\n}\n\nfloat *get_actual_distribution(char *fn)\n{\n FILE *input = fopen(fn, \"r\");\n if (!input)\n {\n perror(\"Can't open file\");\n exit(EXIT_FAILURE);\n }\n\n int tally[9] = { 0 };\n char c;\n int total = 0;\n while ((c = getc(input)) != EOF)\n {\n /* get the first nonzero digit on the current line */\n while (c < '1' || c > '9')\n c = getc(input);\n\n tally[c - '1']++;\n total++;\n\n /* discard rest of line */\n while ((c = getc(input)) != '\\n' && c != EOF)\n ;\n }\n fclose(input);\n \n static float freq[9];\n for (int i = 0; i < 9; i++)\n freq[i] = tally[i] / (float) total;\n\n return freq;\n}\n\nint main(int argc, char **argv)\n{\n if (argc != 2)\n {\n printf(\"Usage: benford \\n\");\n return EXIT_FAILURE;\n }\n\n float *actual = get_actual_distribution(argv[1]);\n float *expected = benford_distribution(); \n\n puts(\"digit\\tactual\\texpected\");\n for (int i = 0; i < 9; i++)\n printf(\"%d\\t%.3f\\t%.3f\\n\", i + 1, actual[i], expected[i]);\n\n return EXIT_SUCCESS;\n}"} -{"title": "Benford's law", "language": "C++", "task": "{{Wikipedia|Benford's_law}}\n\n\n'''Benford's law''', also called the '''first-digit law''', refers to the frequency distribution of digits in many (but not all) real-life sources of data. \n\nIn this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. \n\nBenford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.\n\nThis result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.\n\nA set of numbers is said to satisfy Benford's law if the leading digit d (d \\in \\{1, \\ldots, 9\\}) occurs with probability\n\n:::: P(d) = \\log_{10}(d+1)-\\log_{10}(d) = \\log_{10}\\left(1+\\frac{1}{d}\\right)\n\nFor this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).\n\nUse the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. \n\nYou can generate them or load them from a file; whichever is easiest. \n\nDisplay your actual vs expected distribution.\n\n\n''For extra credit:'' Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.\n\n\n;See also:\n* numberphile.com.\n* A starting page on Wolfram Mathworld is {{Wolfram|Benfords|Law}}.\n\n", "solution": "//to cope with the big numbers , I used the Class Library for Numbers( CLN ) \n//if used prepackaged you can compile writing \"g++ -std=c++11 -lcln yourprogram.cpp -o yourprogram\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace cln ;\n\nclass NextNum {\npublic :\n NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }\n cl_I operator( )( ) {\n cl_I result = first + second ;\n first = second ;\n second = result ;\n return result ;\n }\nprivate :\n cl_I first ;\n cl_I second ;\n} ;\n\nvoid findFrequencies( const std::vector & fibos , std::map &numberfrequencies ) {\n for ( cl_I bignumber : fibos ) {\n std::ostringstream os ;\n fprintdecimal ( os , bignumber ) ;//from header file cln/integer_io.h\n int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;\n auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;\n if ( ! result.second ) \n\t numberfrequencies[ firstdigit ]++ ;\n }\n}\n\nint main( ) {\n std::vector fibonaccis( 1000 ) ;\n fibonaccis[ 0 ] = 0 ;\n fibonaccis[ 1 ] = 1 ;\n cl_I a = 0 ;\n cl_I b = 1 ;\n //since a and b are passed as references to the generator's constructor\n //they are constantly changed !\n std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;\n std::cout << std::endl ;\n std::map frequencies ;\n findFrequencies( fibonaccis , frequencies ) ;\n std::cout << \" found expected\\n\" ;\n for ( int i = 1 ; i < 10 ; i++ ) {\n double found = static_cast( frequencies[ i ] ) / 1000 ;\n double expected = std::log10( 1 + 1 / static_cast( i )) ;\n std::cout << i << \" :\" << std::setw( 16 ) << std::right << found * 100 << \" %\" ;\n std::cout.precision( 3 ) ;\n std::cout << std::setw( 26 ) << std::right << expected * 100 << \" %\\n\" ;\n }\n return 0 ;\n}\n"} -{"title": "Benford's law", "language": "JavaScript", "task": "{{Wikipedia|Benford's_law}}\n\n\n'''Benford's law''', also called the '''first-digit law''', refers to the frequency distribution of digits in many (but not all) real-life sources of data. \n\nIn this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. \n\nBenford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.\n\nThis result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.\n\nA set of numbers is said to satisfy Benford's law if the leading digit d (d \\in \\{1, \\ldots, 9\\}) occurs with probability\n\n:::: P(d) = \\log_{10}(d+1)-\\log_{10}(d) = \\log_{10}\\left(1+\\frac{1}{d}\\right)\n\nFor this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).\n\nUse the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. \n\nYou can generate them or load them from a file; whichever is easiest. \n\nDisplay your actual vs expected distribution.\n\n\n''For extra credit:'' Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.\n\n\n;See also:\n* numberphile.com.\n* A starting page on Wolfram Mathworld is {{Wolfram|Benfords|Law}}.\n\n", "solution": "const fibseries = n => [...Array(n)]\n .reduce(\n (fib, _, i) => i < 2 ? (\n fib\n ) : fib.concat(fib[i - 1] + fib[i - 2]),\n [1, 1]\n );\n\nconst benford = array => [1, 2, 3, 4, 5, 6, 7, 8, 9]\n .map(val => [val, array\n .reduce(\n (sum, item) => sum + (\n `${item}` [0] === `${val}`\n ),\n 0\n ) / array.length, Math.log10(1 + 1 / val)\n ]);\n\nconsole.log(benford(fibseries(1000)))"} -{"title": "Benford's law", "language": "Python", "task": "{{Wikipedia|Benford's_law}}\n\n\n'''Benford's law''', also called the '''first-digit law''', refers to the frequency distribution of digits in many (but not all) real-life sources of data. \n\nIn this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. \n\nBenford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.\n\nThis result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.\n\nA set of numbers is said to satisfy Benford's law if the leading digit d (d \\in \\{1, \\ldots, 9\\}) occurs with probability\n\n:::: P(d) = \\log_{10}(d+1)-\\log_{10}(d) = \\log_{10}\\left(1+\\frac{1}{d}\\right)\n\nFor this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).\n\nUse the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. \n\nYou can generate them or load them from a file; whichever is easiest. \n\nDisplay your actual vs expected distribution.\n\n\n''For extra credit:'' Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.\n\n\n;See also:\n* numberphile.com.\n* A starting page on Wolfram Mathworld is {{Wolfram|Benfords|Law}}.\n\n", "solution": "from __future__ import division\nfrom itertools import islice, count\nfrom collections import Counter\nfrom math import log10\nfrom random import randint\n\nexpected = [log10(1+1/d) for d in range(1,10)]\n\ndef fib():\n a,b = 1,1\n while True:\n yield a\n a,b = b,a+b\n\n# powers of 3 as a test sequence\ndef power_of_threes():\n return (3**k for k in count(0))\n\ndef heads(s):\n for a in s: yield int(str(a)[0])\n\ndef show_dist(title, s):\n c = Counter(s)\n size = sum(c.values())\n res = [c[d]/size for d in range(1,10)]\n\n print(\"\\n%s Benfords deviation\" % title)\n for r, e in zip(res, expected):\n print(\"%5.1f%% %5.1f%% %5.1f%%\" % (r*100., e*100., abs(r - e)*100.))\n\ndef rand1000():\n while True: yield randint(1,9999)\n\nif __name__ == '__main__':\n show_dist(\"fibbed\", islice(heads(fib()), 1000))\n show_dist(\"threes\", islice(heads(power_of_threes()), 1000))\n\n # just to show that not all kind-of-random sets behave like that\n show_dist(\"random\", islice(heads(rand1000()), 10000))"} -{"title": "Best shuffle", "language": "C", "task": "Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. \n\nA shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative.\n\nDisplay the result as follows: \n\n original string, shuffled string, (score) \n\nThe score gives the number of positions whose character value did ''not'' change. \n\n\n;Example:\n tree, eetr, (0)\n\n\n;Test cases:\n abracadabra\n seesaw\n elk\n grrrrrr\n up\n a\n\n\n;Related tasks\n* [[Anagrams/Deranged anagrams]]\n* [[Permutations/Derangements]]\n\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\n#define DEBUG\n\nvoid best_shuffle(const char* txt, char* result) {\n const size_t len = strlen(txt);\n if (len == 0)\n return;\n\n#ifdef DEBUG\n // txt and result must have the same length\n assert(len == strlen(result));\n#endif\n\n // how many of each character?\n size_t counts[UCHAR_MAX];\n memset(counts, '\\0', UCHAR_MAX * sizeof(int));\n size_t fmax = 0;\n for (size_t i = 0; i < len; i++) {\n counts[(unsigned char)txt[i]]++;\n const size_t fnew = counts[(unsigned char)txt[i]];\n if (fmax < fnew)\n fmax = fnew;\n }\n assert(fmax > 0 && fmax <= len);\n\n // all character positions, grouped by character\n size_t *ndx1 = malloc(len * sizeof(size_t));\n if (ndx1 == NULL)\n exit(EXIT_FAILURE);\n for (size_t ch = 0, i = 0; ch < UCHAR_MAX; ch++)\n if (counts[ch])\n for (size_t j = 0; j < len; j++)\n if (ch == (unsigned char)txt[j]) {\n ndx1[i] = j;\n i++;\n }\n\n // regroup them for cycles\n size_t *ndx2 = malloc(len * sizeof(size_t));\n if (ndx2 == NULL)\n exit(EXIT_FAILURE);\n for (size_t i = 0, n = 0, m = 0; i < len; i++) {\n ndx2[i] = ndx1[n];\n n += fmax;\n if (n >= len) {\n m++;\n n = m;\n }\n }\n\n // how long can our cyclic groups be?\n const size_t grp = 1 + (len - 1) / fmax;\n assert(grp > 0 && grp <= len);\n\n // how many of them are full length?\n const size_t lng = 1 + (len - 1) % fmax;\n assert(lng > 0 && lng <= len);\n\n // rotate each group\n for (size_t i = 0, j = 0; i < fmax; i++) {\n const size_t first = ndx2[j];\n const size_t glen = grp - (i < lng ? 0 : 1);\n for (size_t k = 1; k < glen; k++)\n ndx1[j + k - 1] = ndx2[j + k];\n ndx1[j + glen - 1] = first;\n j += glen;\n }\n\n // result is original permuted according to our cyclic groups\n result[len] = '\\0';\n for (size_t i = 0; i < len; i++)\n result[ndx2[i]] = txt[ndx1[i]];\n\n free(ndx1);\n free(ndx2);\n}\n\nvoid display(const char* txt1, const char* txt2) {\n const size_t len = strlen(txt1);\n assert(len == strlen(txt2));\n int score = 0;\n for (size_t i = 0; i < len; i++)\n if (txt1[i] == txt2[i])\n score++;\n (void)printf(\"%s, %s, (%u)\\n\", txt1, txt2, score);\n}\n\nint main() {\n const char* data[] = {\"abracadabra\", \"seesaw\", \"elk\", \"grrrrrr\",\n \"up\", \"a\", \"aabbbbaa\", \"\", \"xxxxx\"};\n const size_t data_len = sizeof(data) / sizeof(data[0]);\n for (size_t i = 0; i < data_len; i++) {\n const size_t shuf_len = strlen(data[i]) + 1;\n char shuf[shuf_len];\n\n#ifdef DEBUG\n memset(shuf, 0xFF, sizeof shuf);\n shuf[shuf_len - 1] = '\\0';\n#endif\n\n best_shuffle(data[i], shuf);\n display(data[i], shuf);\n }\n\n return EXIT_SUCCESS;\n}"} -{"title": "Best shuffle", "language": "C++ from Java", "task": "Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. \n\nA shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative.\n\nDisplay the result as follows: \n\n original string, shuffled string, (score) \n\nThe score gives the number of positions whose character value did ''not'' change. \n\n\n;Example:\n tree, eetr, (0)\n\n\n;Test cases:\n abracadabra\n seesaw\n elk\n grrrrrr\n up\n a\n\n\n;Related tasks\n* [[Anagrams/Deranged anagrams]]\n* [[Permutations/Derangements]]\n\n\n\n", "solution": "#include \n#include \n#include \n\nusing namespace std;\n\ntemplate \nclass BestShuffle {\npublic:\n BestShuffle() : rd(), g(rd()) {}\n\n S operator()(const S& s1) {\n S s2 = s1;\n shuffle(s2.begin(), s2.end(), g);\n for (unsigned i = 0; i < s2.length(); i++)\n if (s2[i] == s1[i])\n for (unsigned j = 0; j < s2.length(); j++)\n if (s2[i] != s2[j] && s2[i] != s1[j] && s2[j] != s1[i]) {\n swap(s2[i], s2[j]);\n break;\n }\n ostringstream os;\n os << s1 << endl << s2 << \" [\" << count(s2, s1) << ']';\n return os.str();\n }\n\nprivate:\n static int count(const S& s1, const S& s2) {\n auto count = 0;\n for (unsigned i = 0; i < s1.length(); i++)\n if (s1[i] == s2[i])\n count++;\n return count;\n }\n\n random_device rd;\n mt19937 g;\n};\n\nint main(int argc, char* arguments[]) {\n BestShuffle> bs;\n for (auto i = 1; i < argc; i++)\n cout << bs(basic_string(arguments[i])) << endl;\n return 0;\n}"} -{"title": "Best shuffle", "language": "JavaScript", "task": "Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. \n\nA shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative.\n\nDisplay the result as follows: \n\n original string, shuffled string, (score) \n\nThe score gives the number of positions whose character value did ''not'' change. \n\n\n;Example:\n tree, eetr, (0)\n\n\n;Test cases:\n abracadabra\n seesaw\n elk\n grrrrrr\n up\n a\n\n\n;Related tasks\n* [[Anagrams/Deranged anagrams]]\n* [[Permutations/Derangements]]\n\n\n\n", "solution": "function raze(a) { // like .join('') except producing an array instead of a string\n var r= [];\n for (var j= 0; j rankb:\n best = c\n rankb = rankc\n\n # Add character to list. Remove it from supply.\n r.append(best)\n count[best] -= 1\n if count[best] >= 0: del count[best]\n\n # If the final letter became stuck (as \"ababcd\" became \"bacabd\",\n # and the final \"d\" became stuck), then fix it.\n i = len(s) - 1\n if r[i] == s[i]:\n for j in range(i):\n if r[i] != s[j] and r[j] != s[i]:\n r[i], r[j] = r[j], r[i]\n break\n\n # Convert list to string. PEP 8, \"Style Guide for Python Code\",\n # suggests that ''.join() is faster than + when concatenating\n # many strings. See http://www.python.org/dev/peps/pep-0008/\n r = ''.join(r)\n\n score = sum(x == y for x, y in zip(r, s))\n\n return (r, score)\n\nfor s in \"abracadabra\", \"seesaw\", \"elk\", \"grrrrrr\", \"up\", \"a\":\n shuffled, score = best_shuffle(s)\n print(\"%s, %s, (%d)\" % (s, shuffled, score))"} -{"title": "Bin given limits", "language": "C", "task": "You are given a list of n ascending, unique numbers which are to form limits\nfor n+1 bins which count how many of a large set of input numbers fall in the\nrange of each bin.\n\n(Assuming zero-based indexing)\n\n bin[0] counts how many inputs are < limit[0]\n bin[1] counts how many inputs are >= limit[0] and < limit[1]\n ..''\n bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1]\n bin[n] counts how many inputs are >= limit[n-1]\n\n;Task:\nThe task is to create a function that given the ascending limits and a stream/\nlist of numbers, will return the bins; together with another function that\ngiven the same list of limits and the binning will ''print the limit of each bin\ntogether with the count of items that fell in the range''.\n\nAssume the numbers to bin are too large to practically sort.\n\n;Task examples:\nPart 1: Bin using the following limits the given input data\n\n limits = [23, 37, 43, 53, 67, 83]\n data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n\nPart 2: Bin using the following limits the given input data\n\n limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,\n 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,\n 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]\n\nShow output here, on this page.\n", "solution": "#include \n#include \n\nsize_t upper_bound(const int* array, size_t n, int value) {\n size_t start = 0;\n while (n > 0) {\n size_t step = n / 2;\n size_t index = start + step;\n if (value >= array[index]) {\n start = index + 1;\n n -= step + 1;\n } else {\n n = step;\n }\n }\n return start;\n}\n\nint* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {\n int* result = calloc(nlimits + 1, sizeof(int));\n if (result == NULL)\n return NULL;\n for (size_t i = 0; i < ndata; ++i)\n ++result[upper_bound(limits, nlimits, data[i])];\n return result;\n}\n\nvoid print_bins(const int* limits, size_t n, const int* bins) {\n if (n == 0)\n return;\n printf(\" < %3d: %2d\\n\", limits[0], bins[0]);\n for (size_t i = 1; i < n; ++i)\n printf(\">= %3d and < %3d: %2d\\n\", limits[i - 1], limits[i], bins[i]);\n printf(\">= %3d : %2d\\n\", limits[n - 1], bins[n]);\n}\n\nint main() {\n const int limits1[] = {23, 37, 43, 53, 67, 83};\n const int data1[] = {95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57,\n 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,\n 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98,\n 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n printf(\"Example 1:\\n\");\n size_t n = sizeof(limits1) / sizeof(int);\n int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));\n if (b == NULL) {\n fprintf(stderr, \"Out of memory\\n\");\n return EXIT_FAILURE;\n }\n print_bins(limits1, n, b);\n free(b);\n\n const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};\n const int data2[] = {\n 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,\n 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,\n 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,\n 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,\n 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,\n 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,\n 101, 684, 727, 749};\n\n printf(\"\\nExample 2:\\n\");\n n = sizeof(limits2) / sizeof(int);\n b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));\n if (b == NULL) {\n fprintf(stderr, \"Out of memory\\n\");\n return EXIT_FAILURE;\n }\n print_bins(limits2, n, b);\n free(b);\n\n return EXIT_SUCCESS;\n}"} -{"title": "Bin given limits", "language": "C++", "task": "You are given a list of n ascending, unique numbers which are to form limits\nfor n+1 bins which count how many of a large set of input numbers fall in the\nrange of each bin.\n\n(Assuming zero-based indexing)\n\n bin[0] counts how many inputs are < limit[0]\n bin[1] counts how many inputs are >= limit[0] and < limit[1]\n ..''\n bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1]\n bin[n] counts how many inputs are >= limit[n-1]\n\n;Task:\nThe task is to create a function that given the ascending limits and a stream/\nlist of numbers, will return the bins; together with another function that\ngiven the same list of limits and the binning will ''print the limit of each bin\ntogether with the count of items that fell in the range''.\n\nAssume the numbers to bin are too large to practically sort.\n\n;Task examples:\nPart 1: Bin using the following limits the given input data\n\n limits = [23, 37, 43, 53, 67, 83]\n data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n\nPart 2: Bin using the following limits the given input data\n\n limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,\n 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,\n 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]\n\nShow output here, on this page.\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nstd::vector bins(const std::vector& limits,\n const std::vector& data) {\n std::vector result(limits.size() + 1, 0);\n for (int n : data) {\n auto i = std::upper_bound(limits.begin(), limits.end(), n);\n ++result[i - limits.begin()];\n }\n return result;\n}\n\nvoid print_bins(const std::vector& limits, const std::vector& bins) {\n size_t n = limits.size();\n if (n == 0)\n return;\n assert(n + 1 == bins.size());\n std::cout << \" < \" << std::setw(3) << limits[0] << \": \"\n << std::setw(2) << bins[0] << '\\n';\n for (size_t i = 1; i < n; ++i)\n std::cout << \">= \" << std::setw(3) << limits[i - 1] << \" and < \"\n << std::setw(3) << limits[i] << \": \" << std::setw(2)\n << bins[i] << '\\n';\n std::cout << \">= \" << std::setw(3) << limits[n - 1] << \" : \"\n << std::setw(2) << bins[n] << '\\n';\n}\n\nint main() {\n const std::vector limits1{23, 37, 43, 53, 67, 83};\n const std::vector data1{\n 95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65,\n 17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19,\n 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n std::cout << \"Example 1:\\n\";\n print_bins(limits1, bins(limits1, data1));\n\n const std::vector limits2{14, 18, 249, 312, 389,\n 392, 513, 591, 634, 720};\n const std::vector data2{\n 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,\n 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,\n 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,\n 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,\n 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,\n 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,\n 101, 684, 727, 749};\n\n std::cout << \"\\nExample 2:\\n\";\n print_bins(limits2, bins(limits2, data2));\n}"} -{"title": "Bin given limits", "language": "Python", "task": "You are given a list of n ascending, unique numbers which are to form limits\nfor n+1 bins which count how many of a large set of input numbers fall in the\nrange of each bin.\n\n(Assuming zero-based indexing)\n\n bin[0] counts how many inputs are < limit[0]\n bin[1] counts how many inputs are >= limit[0] and < limit[1]\n ..''\n bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1]\n bin[n] counts how many inputs are >= limit[n-1]\n\n;Task:\nThe task is to create a function that given the ascending limits and a stream/\nlist of numbers, will return the bins; together with another function that\ngiven the same list of limits and the binning will ''print the limit of each bin\ntogether with the count of items that fell in the range''.\n\nAssume the numbers to bin are too large to practically sort.\n\n;Task examples:\nPart 1: Bin using the following limits the given input data\n\n limits = [23, 37, 43, 53, 67, 83]\n data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n\nPart 2: Bin using the following limits the given input data\n\n limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,\n 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,\n 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]\n\nShow output here, on this page.\n", "solution": "from bisect import bisect_right\n\ndef bin_it(limits: list, data: list) -> list:\n \"Bin data according to (ascending) limits.\"\n bins = [0] * (len(limits) + 1) # adds under/over range bins too\n for d in data:\n bins[bisect_right(limits, d)] += 1\n return bins\n\ndef bin_print(limits: list, bins: list) -> list:\n print(f\" < {limits[0]:3} := {bins[0]:3}\")\n for lo, hi, count in zip(limits, limits[1:], bins[1:]):\n print(f\">= {lo:3} .. < {hi:3} := {count:3}\")\n print(f\">= {limits[-1]:3} := {bins[-1]:3}\")\n\n\nif __name__ == \"__main__\":\n print(\"RC FIRST EXAMPLE\\n\")\n limits = [23, 37, 43, 53, 67, 83]\n data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n bins = bin_it(limits, data)\n bin_print(limits, bins)\n\n print(\"\\nRC SECOND EXAMPLE\\n\")\n limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,\n 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,\n 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]\n bins = bin_it(limits, data)\n bin_print(limits, bins)"} -{"title": "Bioinformatics/Global alignment", "language": "Python from Go", "task": "Global alignment is designed to search for highly similar regions in two or more DNA sequences, where the\nsequences appear in the same order and orientation, fitting the sequences in as pieces in a puzzle.\n\nCurrent DNA sequencers find the sequence for multiple small segments of DNA which have mostly randomly formed by splitting a much larger DNA molecule into shorter segments. When re-assembling such segments of DNA sequences into a larger sequence to form, for example, the DNA coding for the relevant gene, the overlaps between multiple shorter sequences are commonly used to decide how the longer sequence is to be assembled. For example, \"AAGATGGA\", GGAGCGCATC\", and \"ATCGCAATAAGGA\" can be assembled into the sequence \"AAGATGGAGCGCATCGCAATAAGGA\" by noting that \"GGA\" is at the tail of the first string and head of the second string and \"ATC\" likewise is at the tail\nof the second and head of the third string.\n\nWhen looking for the best global alignment in the output strings produced by DNA sequences, there are\ntypically a large number of such overlaps among a large number of sequences. In such a case, the ordering\nthat results in the shortest common superstring is generrally preferred.\n\nFinding such a supersequence is an NP-hard problem, and many algorithms have been proposed to\nshorten calculations, especially when many very long sequences are matched.\n\nThe shortest common superstring as used in bioinfomatics here differs from the string task\n[[Shortest_common_supersequence]]. In that task, a supersequence\nmay have other characters interposed as long as the characters of each subsequence appear in order,\nso that (abcbdab, abdcaba) -> abdcabdab. In this task, (abcbdab, abdcaba) -> abcbdabdcaba.\n\n\n;Task:\n:* Given N non-identical strings of characters A, C, G, and T representing N DNA sequences, find the shortest DNA sequence containing all N sequences.\n\n:* Handle cases where two sequences are identical or one sequence is entirely contained in another.\n\n:* Print the resulting sequence along with its size (its base count) and a count of each base in the sequence.\n\n:* Find the shortest common superstring for the following four examples:\n: \n (\"TA\", \"AAG\", \"TA\", \"GAA\", \"TA\")\n\n (\"CATTAGGG\", \"ATTAG\", \"GGG\", \"TA\")\n\n (\"AAGAUGGA\", \"GGAGCGCAUC\", \"AUCGCAAUAAGGA\")\n\n (\"ATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTAT\",\n \"GGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGT\",\n \"CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\",\n \"TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n \"AACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\",\n \"GCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTC\",\n \"CGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCT\",\n \"TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGC\",\n \"GATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATT\",\n \"TTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n \"CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\",\n \"TCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGA\")\n\n;Related tasks:\n:* Bioinformatics base count.\n:* Bioinformatics sequence mutation.\n\n", "solution": "import os\n\nfrom collections import Counter\nfrom functools import reduce\nfrom itertools import permutations\n\nBASES = (\"A\", \"C\", \"G\", \"T\")\n\n\ndef deduplicate(sequences):\n \"\"\"Return the set of sequences with those that are a substring\n of others removed too.\"\"\"\n sequences = set(sequences)\n duplicates = set()\n\n for s, t in permutations(sequences, 2):\n if s != t and s in t:\n duplicates.add(s)\n\n return sequences - duplicates\n\n\ndef smash(s, t):\n \"\"\"Return `s` concatenated with `t`. The longest suffix of `s`\n that matches a prefix of `t` will be removed.\"\"\"\n for i in range(len(s)):\n if t.startswith(s[i:]):\n return s[:i] + t\n return s + t\n\n\ndef shortest_superstring(sequences):\n \"\"\"Return the shortest superstring covering all sequences. If\n there are multiple shortest superstrings, an arbitrary\n superstring is returned.\"\"\"\n sequences = deduplicate(sequences)\n shortest = \"\".join(sequences)\n\n for perm in permutations(sequences):\n superstring = reduce(smash, perm)\n if len(superstring) < len(shortest):\n shortest = superstring\n\n return shortest\n\n\ndef shortest_superstrings(sequences):\n \"\"\"Return a list of all shortest superstrings that cover\n `sequences`.\"\"\"\n sequences = deduplicate(sequences)\n\n shortest = set([\"\".join(sequences)])\n shortest_length = sum(len(s) for s in sequences)\n\n for perm in permutations(sequences):\n superstring = reduce(smash, perm)\n superstring_length = len(superstring)\n if superstring_length < shortest_length:\n shortest.clear()\n shortest.add(superstring)\n shortest_length = superstring_length\n elif superstring_length == shortest_length:\n shortest.add(superstring)\n\n return shortest\n\n\ndef print_report(sequence):\n \"\"\"Writes a report to stdout for the given DNA sequence.\"\"\"\n buf = [f\"Nucleotide counts for {sequence}:\\n\"]\n\n counts = Counter(sequence)\n for base in BASES:\n buf.append(f\"{base:>10}{counts.get(base, 0):>12}\")\n\n other = sum(v for k, v in counts.items() if k not in BASES)\n buf.append(f\"{'Other':>10}{other:>12}\")\n\n buf.append(\" \" * 5 + \"_\" * 17)\n buf.append(f\"{'Total length':>17}{sum(counts.values()):>5}\")\n\n print(os.linesep.join(buf), \"\\n\")\n\n\nif __name__ == \"__main__\":\n test_cases = [\n (\"TA\", \"AAG\", \"TA\", \"GAA\", \"TA\"),\n (\"CATTAGGG\", \"ATTAG\", \"GGG\", \"TA\"),\n (\"AAGAUGGA\", \"GGAGCGCAUC\", \"AUCGCAAUAAGGA\"),\n (\n \"ATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTAT\",\n \"GGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGT\",\n \"CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\",\n \"TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n \"AACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\",\n \"GCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTC\",\n \"CGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCT\",\n \"TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGC\",\n \"GATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATT\",\n \"TTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n \"CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\",\n \"TCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGA\",\n ),\n ]\n\n for case in test_cases:\n for superstring in shortest_superstrings(case):\n print_report(superstring)\n\n # or ..\n #\n # for case in test_cases:\n # print_report(shortest_superstring(case))\n #\n # .. if you don't want all possible shortest superstrings.\n"} -{"title": "Bioinformatics/Sequence mutation", "language": "C", "task": "Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:\n# Choosing a random base position in the sequence.\n# Mutate the sequence by doing one of either:\n## '''S'''wap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base)\n## '''D'''elete the chosen base at the position.\n## '''I'''nsert another base randomly chosen from A,C, G, or T into the sequence at that position.\n# Randomly generate a test DNA sequence of at least 200 bases\n# \"Pretty print\" the sequence and a count of its size, and the count of each base in the sequence\n# Mutate the sequence ten times.\n# \"Pretty print\" the sequence after all mutations, and a count of its size, and the count of each base in the sequence.\n\n;Extra credit:\n* Give more information on the individual mutations applied.\n* Allow mutations to be weighted and/or chosen.\n", "solution": "#include\n#include\n#include\n\ntypedef struct genome{\n char base;\n struct genome *next;\n}genome;\n\ntypedef struct{\n char mutation;\n int position;\n}genomeChange;\n\ntypedef struct{\n int adenineCount,thymineCount,cytosineCount,guanineCount;\n}baseCounts;\n\ngenome *strand;\nbaseCounts baseData;\nint genomeLength = 100, lineLength = 50;\n\nint numDigits(int num){\n int len = 1;\n\n while(num>10){\n num /= 10;\n len++;\n }\n return len;\n}\n\nvoid generateStrand(){\n\n int baseChoice = rand()%4, i;\n genome *strandIterator, *newStrand;\n\n baseData.adenineCount = 0;\n baseData.thymineCount = 0;\n baseData.cytosineCount = 0;\n baseData.guanineCount = 0;\n \n strand = (genome*)malloc(sizeof(genome));\n strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n strand->next = NULL;\n\n strandIterator = strand;\n\n for(i=1;ibase = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n newStrand->next = NULL;\n\n strandIterator->next = newStrand;\n strandIterator = newStrand;\n }\n}\n\ngenomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){\n int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight);\n \n genomeChange mutationCommand;\n\n mutationCommand.mutation = mutationChoice=swapWeight && mutationChoicebase);\n strandIterator = strandIterator->next;\n }\n len += lineLength;\n }\n\n while(strandIterator!=NULL){\n printf(\"%c\",strandIterator->base);\n strandIterator = strandIterator->next;\n }\n\n printf(\"\\n\\nBase Counts\\n-----------\");\n\n printf(\"\\n%*c%3s%*d\",width,'A',\":\",width,baseData.adenineCount);\n printf(\"\\n%*c%3s%*d\",width,'T',\":\",width,baseData.thymineCount);\n printf(\"\\n%*c%3s%*d\",width,'C',\":\",width,baseData.cytosineCount);\n printf(\"\\n%*c%3s%*d\",width,'G',\":\",width,baseData.guanineCount);\n\t\n\tprintf(\"\\n\\nTotal:%*d\",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount);\n\n printf(\"\\n\");\n}\n\nvoid mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){\n int i,j,width,baseChoice;\n genomeChange newMutation;\n genome *strandIterator, *strandFollower, *newStrand;\n\n for(i=0;inext;\n }\n \n if(newMutation.mutation=='S'){\n if(strandIterator->base=='A'){\n strandIterator->base='T';\n printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n }\n else if(strandIterator->base=='A'){\n strandIterator->base='T';\n printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n }\n else if(strandIterator->base=='C'){\n strandIterator->base='G';\n printf(\"\\nSwapping C at position : %*d with G\",width,newMutation.position);\n }\n else{\n strandIterator->base='C';\n printf(\"\\nSwapping G at position : %*d with C\",width,newMutation.position);\n }\n }\n\n else if(newMutation.mutation=='I'){\n baseChoice = rand()%4;\n\n newStrand = (genome*)malloc(sizeof(genome));\n newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n printf(\"\\nInserting %c at position : %*d\",newStrand->base,width,newMutation.position);\n baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n newStrand->next = strandIterator;\n strandFollower->next = newStrand;\n genomeLength++;\n }\n\n else{\n strandFollower->next = strandIterator->next;\n strandIterator->next = NULL;\n printf(\"\\nDeleting %c at position : %*d\",strandIterator->base,width,newMutation.position);\n free(strandIterator);\n genomeLength--;\n }\n }\n}\n\nint main(int argc,char* argv[])\n{\n int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10;\n\n if(argc==1||argc>6){\n printf(\"Usage : %s \\n\",argv[0]);\n return 0;\n }\n\n switch(argc){\n case 2: genomeLength = atoi(argv[1]);\n break;\n case 3: genomeLength = atoi(argv[1]);\n numMutations = atoi(argv[2]);\n break;\n case 4: genomeLength = atoi(argv[1]);\n numMutations = atoi(argv[2]);\n swapWeight = atoi(argv[3]);\n break; \n case 5: genomeLength = atoi(argv[1]);\n numMutations = atoi(argv[2]);\n swapWeight = atoi(argv[3]);\n insertWeight = atoi(argv[4]);\n break; \n case 6: genomeLength = atoi(argv[1]);\n numMutations = atoi(argv[2]);\n swapWeight = atoi(argv[3]);\n insertWeight = atoi(argv[4]);\n deleteWeight = atoi(argv[5]);\n break; \n };\n\n srand(time(NULL));\n generateStrand();\n\t\n\tprintf(\"\\nOriginal:\");\n printGenome();\n mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight);\n \n\tprintf(\"\\n\\nMutated:\");\n\tprintGenome();\n\n return 0;\n}\n"} -{"title": "Bioinformatics/Sequence mutation", "language": "C++", "task": "Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:\n# Choosing a random base position in the sequence.\n# Mutate the sequence by doing one of either:\n## '''S'''wap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base)\n## '''D'''elete the chosen base at the position.\n## '''I'''nsert another base randomly chosen from A,C, G, or T into the sequence at that position.\n# Randomly generate a test DNA sequence of at least 200 bases\n# \"Pretty print\" the sequence and a count of its size, and the count of each base in the sequence\n# Mutate the sequence ten times.\n# \"Pretty print\" the sequence after all mutations, and a count of its size, and the count of each base in the sequence.\n\n;Extra credit:\n* Give more information on the individual mutations applied.\n* Allow mutations to be weighted and/or chosen.\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nclass sequence_generator {\npublic:\n sequence_generator();\n std::string generate_sequence(size_t length);\n void mutate_sequence(std::string&);\n static void print_sequence(std::ostream&, const std::string&);\n enum class operation { change, erase, insert };\n void set_weight(operation, unsigned int);\nprivate:\n char get_random_base() {\n return bases_[base_dist_(engine_)];\n }\n operation get_random_operation();\n static const std::array bases_;\n std::mt19937 engine_;\n std::uniform_int_distribution base_dist_;\n std::array operation_weight_;\n unsigned int total_weight_;\n};\n\nconst std::array sequence_generator::bases_{ 'A', 'C', 'G', 'T' };\n\nsequence_generator::sequence_generator() : engine_(std::random_device()()),\n base_dist_(0, bases_.size() - 1),\n total_weight_(operation_weight_.size()) {\n operation_weight_.fill(1);\n}\n\nsequence_generator::operation sequence_generator::get_random_operation() {\n std::uniform_int_distribution op_dist(0, total_weight_ - 1);\n unsigned int n = op_dist(engine_), op = 0, weight = 0;\n for (; op < operation_weight_.size(); ++op) {\n weight += operation_weight_[op];\n if (n < weight)\n break;\n }\n return static_cast(op);\n}\n\nvoid sequence_generator::set_weight(operation op, unsigned int weight) {\n total_weight_ -= operation_weight_[static_cast(op)];\n operation_weight_[static_cast(op)] = weight;\n total_weight_ += weight;\n}\n\nstd::string sequence_generator::generate_sequence(size_t length) {\n std::string sequence;\n sequence.reserve(length);\n for (size_t i = 0; i < length; ++i)\n sequence += get_random_base();\n return sequence;\n}\n\nvoid sequence_generator::mutate_sequence(std::string& sequence) {\n std::uniform_int_distribution dist(0, sequence.length() - 1);\n size_t pos = dist(engine_);\n char b;\n switch (get_random_operation()) {\n case operation::change:\n b = get_random_base();\n std::cout << \"Change base at position \" << pos << \" from \"\n << sequence[pos] << \" to \" << b << '\\n';\n sequence[pos] = b;\n break;\n case operation::erase:\n std::cout << \"Erase base \" << sequence[pos] << \" at position \"\n << pos << '\\n';\n sequence.erase(pos, 1);\n break;\n case operation::insert:\n b = get_random_base();\n std::cout << \"Insert base \" << b << \" at position \"\n << pos << '\\n';\n sequence.insert(pos, 1, b);\n break;\n }\n}\n\nvoid sequence_generator::print_sequence(std::ostream& out, const std::string& sequence) {\n constexpr size_t base_count = bases_.size();\n std::array count = { 0 };\n for (size_t i = 0, n = sequence.length(); i < n; ++i) {\n if (i % 50 == 0) {\n if (i != 0)\n out << '\\n';\n out << std::setw(3) << i << \": \";\n }\n out << sequence[i];\n for (size_t j = 0; j < base_count; ++j) {\n if (bases_[j] == sequence[i]) {\n ++count[j];\n break;\n }\n }\n }\n out << '\\n';\n out << \"Base counts:\\n\";\n size_t total = 0;\n for (size_t j = 0; j < base_count; ++j) {\n total += count[j];\n out << bases_[j] << \": \" << count[j] << \", \";\n }\n out << \"Total: \" << total << '\\n';\n}\n\nint main() {\n sequence_generator gen;\n gen.set_weight(sequence_generator::operation::change, 2);\n std::string sequence = gen.generate_sequence(250);\n std::cout << \"Initial sequence:\\n\";\n sequence_generator::print_sequence(std::cout, sequence);\n constexpr int count = 10;\n for (int i = 0; i < count; ++i)\n gen.mutate_sequence(sequence);\n std::cout << \"After \" << count << \" mutations:\\n\";\n sequence_generator::print_sequence(std::cout, sequence);\n return 0;\n}"} -{"title": "Bioinformatics/Sequence mutation", "language": "JavaScript", "task": "Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:\n# Choosing a random base position in the sequence.\n# Mutate the sequence by doing one of either:\n## '''S'''wap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base)\n## '''D'''elete the chosen base at the position.\n## '''I'''nsert another base randomly chosen from A,C, G, or T into the sequence at that position.\n# Randomly generate a test DNA sequence of at least 200 bases\n# \"Pretty print\" the sequence and a count of its size, and the count of each base in the sequence\n# Mutate the sequence ten times.\n# \"Pretty print\" the sequence after all mutations, and a count of its size, and the count of each base in the sequence.\n\n;Extra credit:\n* Give more information on the individual mutations applied.\n* Allow mutations to be weighted and/or chosen.\n", "solution": "// Basic set-up\nconst numBases = 250\nconst numMutations = 30\nconst bases = ['A', 'C', 'G', 'T'];\n\n// Utility functions\n/**\n * Return a shallow copy of an array\n * @param {Array<*>} arr\n * @returns {*[]}\n */\nconst copy = arr => [...arr];\n\n/**\n * Get a random int up to but excluding the the given number\n * @param {number} max\n * @returns {number}\n */\nconst randTo = max => (Math.random() * max) | 0;\n\n/**\n * Given an array return a random element and the index of that element from\n * the array.\n * @param {Array<*>} arr\n * @returns {[*[], number]}\n */\nconst randSelect = arr => {\n const at = randTo(arr.length);\n return [arr[at], at];\n};\n\n/**\n * Given a number or string, return a left padded string\n * @param {string|number} v\n * @returns {string}\n */\nconst pad = v => ('' + v).padStart(4, ' ');\n\n/**\n * Count the number of elements that match the given value in an array\n * @param {Array} arr\n * @returns {function(string): number}\n */\nconst filterCount = arr => s => arr.filter(e => e === s).length;\n\n/**\n * Utility logging function\n * @param {string|number} v\n * @param {string|number} n\n */\nconst print = (v, n) => console.log(`${pad(v)}:\\t${n}`)\n\n/**\n * Utility function to randomly select a new base, and an index in the given\n * sequence.\n * @param {Array} seq\n * @param {Array} bases\n * @returns {[string, string, number]}\n */\nconst getVars = (seq, bases) => {\n const [newBase, _] = randSelect(bases);\n const [extBase, randPos] = randSelect(seq);\n return [newBase, extBase, randPos];\n};\n\n// Bias the operations\n/**\n * Given a map of function to ratio, return an array of those functions\n * appearing ratio number of times in the array.\n * @param weightMap\n * @returns {Array}\n */\nconst weightedOps = weightMap => {\n return [...weightMap.entries()].reduce((p, [op, weight]) =>\n [...p, ...(Array(weight).fill(op))], []);\n};\n\n// Pretty Print functions\nconst prettyPrint = seq => {\n let idx = 0;\n const rem = seq.reduce((p, c) => {\n const s = p + c;\n if (s.length === 50) {\n print(idx, s);\n idx = idx + 50;\n return '';\n }\n return s;\n }, '');\n if (rem !== '') {\n print(idx, rem);\n }\n}\n\nconst printBases = seq => {\n const filterSeq = filterCount(seq);\n let tot = 0;\n [...bases].forEach(e => {\n const cnt = filterSeq(e);\n print(e, cnt);\n tot = tot + cnt;\n })\n print('\u03a3', tot);\n}\n\n// Mutation definitions\nconst swap = ([hist, seq]) => {\n const arr = copy(seq);\n const [newBase, extBase, randPos] = getVars(arr, bases);\n arr.splice(randPos, 1, newBase);\n return [[...hist, `Swapped ${extBase} for ${newBase} at ${randPos}`], arr];\n};\n\nconst del = ([hist, seq]) => {\n const arr = copy(seq);\n const [newBase, extBase, randPos] = getVars(arr, bases);\n arr.splice(randPos, 1);\n return [[...hist, `Deleted ${extBase} at ${randPos}`], arr];\n}\n\nconst insert = ([hist, seq]) => {\n const arr = copy(seq);\n const [newBase, extBase, randPos] = getVars(arr, bases);\n arr.splice(randPos, 0, newBase);\n return [[...hist, `Inserted ${newBase} at ${randPos}`], arr];\n}\n\n// Create the starting sequence\nconst seq = Array(numBases).fill(undefined).map(\n () => randSelect(bases)[0]);\n\n// Create a weighted set of mutations\nconst weightMap = new Map()\n .set(swap, 1)\n .set(del, 1)\n .set(insert, 1);\nconst operations = weightedOps(weightMap);\nconst mutations = Array(numMutations).fill(undefined).map(\n () => randSelect(operations)[0]);\n\n// Mutate the sequence\nconst [hist, mut] = mutations.reduce((p, c) => c(p), [[], seq]);\n\nconsole.log('ORIGINAL SEQUENCE:')\nprettyPrint(seq);\n\nconsole.log('\\nBASE COUNTS:')\nprintBases(seq);\n\nconsole.log('\\nMUTATION LOG:')\nhist.forEach((e, i) => console.log(`${i}:\\t${e}`));\n\nconsole.log('\\nMUTATED SEQUENCE:')\nprettyPrint(mut);\n\nconsole.log('\\nMUTATED BASE COUNTS:')\nprintBases(mut);\n"} -{"title": "Bioinformatics/Sequence mutation", "language": "Python", "task": "Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:\n# Choosing a random base position in the sequence.\n# Mutate the sequence by doing one of either:\n## '''S'''wap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base)\n## '''D'''elete the chosen base at the position.\n## '''I'''nsert another base randomly chosen from A,C, G, or T into the sequence at that position.\n# Randomly generate a test DNA sequence of at least 200 bases\n# \"Pretty print\" the sequence and a count of its size, and the count of each base in the sequence\n# Mutate the sequence ten times.\n# \"Pretty print\" the sequence after all mutations, and a count of its size, and the count of each base in the sequence.\n\n;Extra credit:\n* Give more information on the individual mutations applied.\n* Allow mutations to be weighted and/or chosen.\n", "solution": "import random\nfrom collections import Counter\n\ndef basecount(dna):\n return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n for i, part in enumerate(seq_split(dna, n)):\n print(f\"{i*n:>5}: {part}\")\n print(\"\\n BASECOUNT:\")\n tot = 0\n for base, count in basecount(dna):\n print(f\" {base:>3}: {count}\")\n tot += count\n base, count = 'TOT', tot\n print(f\" {base:>3}= {count}\")\n\ndef seq_mutate(dna, count=1, kinds=\"IDSSSS\", choice=\"ATCG\" ):\n mutation = []\n k2txt = dict(I='Insert', D='Delete', S='Substitute')\n for _ in range(count):\n kind = random.choice(kinds)\n index = random.randint(0, len(dna))\n if kind == 'I': # Insert\n dna = dna[:index] + random.choice(choice) + dna[index:]\n elif kind == 'D' and dna: # Delete\n dna = dna[:index] + dna[index+1:]\n elif kind == 'S' and dna: # Substitute\n dna = dna[:index] + random.choice(choice) + dna[index+1:]\n mutation.append((k2txt[kind], index))\n return dna, mutation\n\nif __name__ == '__main__':\n length = 250\n print(\"SEQUENCE:\")\n sequence = ''.join(random.choices('ACGT', weights=(1, 0.8, .9, 1.1), k=length))\n seq_pp(sequence)\n print(\"\\n\\nMUTATIONS:\")\n mseq, m = seq_mutate(sequence, 10)\n for kind, index in m:\n print(f\" {kind:>10} @{index}\")\n print()\n seq_pp(mseq)"} -{"title": "Bioinformatics/base count", "language": "C", "task": "Given this string representing ordered DNA bases:\n\nCGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\nCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\nAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\nGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\nCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\nTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\nTTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\nCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\nTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\nGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\n\n\n\n;Task:\n:* \"Pretty print\" the sequence followed by a summary of the counts of each of the bases: ('''A''', '''C''', '''G''', and '''T''') in the sequence \n:* print the total count of each base in the string.\n\n\n\n", "solution": "#include\n#include\n#include\n\ntypedef struct genome{\n char* strand;\n int length;\n struct genome* next;\n}genome;\n\ngenome* genomeData;\nint totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0;\n\nint numDigits(int num){\n int len = 1;\n\n while(num>10){\n num = num/10;\n len++;\n }\n\n return len;\n}\n\nvoid buildGenome(char str[100]){\n int len = strlen(str),i;\n genome *genomeIterator, *newGenome; \n\n totalLength += len;\n\n for(i=0;istrand = (char*)malloc(len*sizeof(char));\n strcpy(genomeData->strand,str);\n genomeData->length = len;\n\n genomeData->next = NULL;\n }\n\n else{\n genomeIterator = genomeData;\n\n while(genomeIterator->next!=NULL)\n genomeIterator = genomeIterator->next;\n\n newGenome = (genome*)malloc(sizeof(genome));\n\n newGenome->strand = (char*)malloc(len*sizeof(char));\n strcpy(newGenome->strand,str);\n newGenome->length = len;\n\n newGenome->next = NULL;\n genomeIterator->next = newGenome;\n }\n}\n\nvoid printGenome(){\n genome* genomeIterator = genomeData;\n\n int width = numDigits(totalLength), len = 0;\n\n printf(\"Sequence:\\n\");\n\n while(genomeIterator!=NULL){\n printf(\"\\n%*d%3s%3s\",width+1,len,\":\",genomeIterator->strand);\n len += genomeIterator->length;\n\n genomeIterator = genomeIterator->next;\n }\n\n printf(\"\\n\\nBase Count\\n----------\\n\\n\");\n\n printf(\"%3c%3s%*d\\n\",'A',\":\",width+1,Adenine);\n printf(\"%3c%3s%*d\\n\",'T',\":\",width+1,Thymine);\n printf(\"%3c%3s%*d\\n\",'C',\":\",width+1,Cytosine);\n printf(\"%3c%3s%*d\\n\",'G',\":\",width+1,Guanine);\n printf(\"\\n%3s%*d\\n\",\"Total:\",width+1,Adenine + Thymine + Cytosine + Guanine);\n\n free(genomeData);\n}\n\nint main(int argc,char** argv)\n{\n char str[100];\n int counter = 0, len;\n \n if(argc!=2){\n printf(\"Usage : %s \\n\",argv[0]);\n return 0;\n }\n\n FILE *fp = fopen(argv[1],\"r\");\n\n while(fscanf(fp,\"%s\",str)!=EOF)\n buildGenome(str);\n fclose(fp);\n\n printGenome();\n\n return 0;\n}\n"} -{"title": "Bioinformatics/base count", "language": "C++", "task": "Given this string representing ordered DNA bases:\n\nCGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\nCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\nAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\nGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\nCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\nTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\nTTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\nCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\nTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\nGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\n\n\n\n;Task:\n:* \"Pretty print\" the sequence followed by a summary of the counts of each of the bases: ('''A''', '''C''', '''G''', and '''T''') in the sequence \n:* print the total count of each base in the string.\n\n\n\n", "solution": "#include \n#include \n#include \n#include \n\nconst std::string DEFAULT_DNA = \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\"\n \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\"\n \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\"\n \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\"\n \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\"\n \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\"\n \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\"\n \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\"\n \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\"\n \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\";\n\nclass DnaBase {\npublic:\n DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {\n // Map each character to a counter\n for (auto elm : dna) {\n if (count.find(elm) == count.end())\n count[elm] = 0;\n ++count[elm];\n }\n }\n\n void viewGenome() {\n std::cout << \"Sequence:\" << std::endl;\n std::cout << std::endl;\n int limit = genome.size() / displayWidth;\n if (genome.size() % displayWidth != 0)\n ++limit;\n\n for (int i = 0; i < limit; ++i) {\n int beginPos = i * displayWidth;\n std::cout << std::setw(4) << beginPos << \" :\" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;\n }\n std::cout << std::endl;\n std::cout << \"Base Count\" << std::endl;\n std::cout << \"----------\" << std::endl;\n std::cout << std::endl;\n int total = 0;\n for (auto elm : count) {\n std::cout << std::setw(4) << elm.first << \" : \" << elm.second << std::endl;\n total += elm.second;\n }\n std::cout << std::endl;\n std::cout << \"Total: \" << total << std::endl;\n }\n\nprivate:\n std::string genome;\n std::map count;\n int displayWidth;\n};\n\nint main(void) {\n auto d = new DnaBase();\n d->viewGenome();\n delete d;\n return 0;\n}"} -{"title": "Bioinformatics/base count", "language": "JavaScript", "task": "Given this string representing ordered DNA bases:\n\nCGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\nCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\nAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\nGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\nCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\nTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\nTTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\nCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\nTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\nGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\n\n\n\n;Task:\n:* \"Pretty print\" the sequence followed by a summary of the counts of each of the bases: ('''A''', '''C''', '''G''', and '''T''') in the sequence \n:* print the total count of each base in the string.\n\n\n\n", "solution": "const rowLength = 50;\n\nconst bases = ['A', 'C', 'G', 'T'];\n\n// Create the starting sequence\nconst seq = `CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\nCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\nAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\nGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\nCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\nTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\nTTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\nCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\nTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\nGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT`\n .split('')\n .filter(e => bases.includes(e))\n\n/**\n * Convert the given array into an array of smaller arrays each with the length\n * given by n.\n * @param {number} n\n * @returns {function(!Array<*>): !Array>}\n */\nconst chunk = n => a => a.reduce(\n (p, c, i) => (!(i % n)) ? p.push([c]) && p : p[p.length - 1].push(c) && p,\n []);\nconst toRows = chunk(rowLength);\n\n/**\n * Given a number, return function that takes a string and left pads it to n\n * @param {number} n\n * @returns {function(string): string}\n */\nconst padTo = n => v => ('' + v).padStart(n, ' ');\nconst pad = padTo(5);\n\n/**\n * Count the number of elements that match the given value in an array\n * @param {Array} arr\n * @returns {function(string): number}\n */\nconst countIn = arr => s => arr.filter(e => e === s).length;\n\n/**\n * Utility logging function\n * @param {string|number} v\n * @param {string|number} n\n */\nconst print = (v, n) => console.log(`${pad(v)}:\\t${n}`)\n\nconst prettyPrint = seq => {\n const chunks = toRows(seq);\n console.log('SEQUENCE:')\n chunks.forEach((e, i) => print(i * rowLength, e.join('')))\n}\n\nconst printBases = (seq, bases) => {\n const filterSeq = countIn(seq);\n const counts = bases.map(filterSeq);\n console.log('\\nBASE COUNTS:')\n counts.forEach((e, i) => print(bases[i], e));\n print('Total', counts.reduce((p,c) => p + c, 0));\n}\n\nprettyPrint(seq);\nprintBases(seq, bases);\n"} -{"title": "Bioinformatics/base count", "language": "Python", "task": "Given this string representing ordered DNA bases:\n\nCGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\nCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\nAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\nGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\nCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\nTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\nTTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\nCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\nTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\nGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\n\n\n\n;Task:\n:* \"Pretty print\" the sequence followed by a summary of the counts of each of the bases: ('''A''', '''C''', '''G''', and '''T''') in the sequence \n:* print the total count of each base in the string.\n\n\n\n", "solution": "from collections import Counter\n\ndef basecount(dna):\n return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n for i, part in enumerate(seq_split(dna, n)):\n print(f\"{i*n:>5}: {part}\")\n print(\"\\n BASECOUNT:\")\n tot = 0\n for base, count in basecount(dna):\n print(f\" {base:>3}: {count}\")\n tot += count\n base, count = 'TOT', tot\n print(f\" {base:>3}= {count}\")\n \nif __name__ == '__main__':\n print(\"SEQUENCE:\")\n sequence = '''\\\nCGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\\\nCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\\\nAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\\\nGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\\\nCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\\\nTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\\\nTTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\\\nCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\\\nTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\\\nGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT'''\n seq_pp(sequence)\n"} -{"title": "Bioinformatics/base count", "language": "Python 3.10.5 ", "task": "Given this string representing ordered DNA bases:\n\nCGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\nCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\nAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\nGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\nCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\nTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\nTTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\nCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\nTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\nGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\n\n\n\n;Task:\n:* \"Pretty print\" the sequence followed by a summary of the counts of each of the bases: ('''A''', '''C''', '''G''', and '''T''') in the sequence \n:* print the total count of each base in the string.\n\n\n\n", "solution": "\"\"\"\n\tPython 3.10.5 (main, Jun 6 2022, 18:49:26) [GCC 12.1.0] on linux\n\n\tCreated on Wed 2022/08/17 11:19:31\n\t\n\"\"\"\n\n\ndef main ():\n\n\tdef DispCount () :\n\n\t return f'\\n\\nBases :\\n\\n' + f''.join ( [ f'{i} =\\t{D [ i ]:4d}\\n' for i in sorted ( BoI ) ] )\n\n\n\tS =\t'CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG' \\\n\t\t'AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT' \\\n\t\t'CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA' \\\n\t\t'TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG' \\\n\t\t'TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT'\n\n\tAll = set( S ) \n\t\n\tBoI = set ( [ \"A\",\"C\",\"G\",\"T\" ] )\n\t\n\tother = All - BoI\n\t\n\tD = { k : S.count ( k ) for k in All }\n\t\n\tprint ( 'Sequence:\\n\\n')\n\n\tprint ( ''.join ( [ f'{k:4d} : {S [ k: k + 50 ]}\\n' for k in range ( 0, len ( S ), 50 ) ] ) )\n\n\tprint ( f'{DispCount ()} \\n------------')\n\n\tprint ( '' if ( other == set () ) else f'Other\\t{sum ( [ D [ k ] for k in sorted ( other ) ] ):4d}\\n\\n' )\n\n\tprint ( f'\u03a3 = \\t {sum ( [ D [ k ] for k in sorted ( All ) ] ) } \\n============\\n')\n\t\n\tpass\n\n\ndef test ():\n\n\tpass\n\n\n## START\n\nLIVE = True\n\nif ( __name__ == '__main__' ) :\n\n\tmain () if LIVE else test ()\n\n\n"} -{"title": "Bioinformatics/base count", "language": "Python 3.7", "task": "Given this string representing ordered DNA bases:\n\nCGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\nCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\nAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\nGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\nCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\nTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\nTTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\nCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\nTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\nGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\n\n\n\n;Task:\n:* \"Pretty print\" the sequence followed by a summary of the counts of each of the bases: ('''A''', '''C''', '''G''', and '''T''') in the sequence \n:* print the total count of each base in the string.\n\n\n\n", "solution": "'''Bioinformatics \u2013 base count'''\n\nfrom itertools import count\nfrom functools import reduce\n\n\n# genBankFormatWithBaseCounts :: String -> String\ndef genBankFormatWithBaseCounts(sequence):\n '''DNA Sequence displayed in a subset of the GenBank format.\n See example at foot of:\n https://www.genomatix.de/online_help/help/sequence_formats.html\n '''\n ks, totals = zip(*baseCounts(sequence))\n ns = list(map(str, totals))\n w = 2 + max(map(len, ns))\n\n return '\\n'.join([\n 'DEFINITION len=' + str(sum(totals)),\n 'BASE COUNT ' + ''.join(\n n.rjust(w) + ' ' + k.lower() for (k, n)\n in zip(ks, ns)\n ),\n 'ORIGIN'\n ] + [\n str(i).rjust(9) + ' ' + k for i, k\n in zip(\n count(1, 60),\n [\n ' '.join(row) for row in\n chunksOf(6)(chunksOf(10)(sequence))\n ]\n )\n ] + ['//'])\n\n\n# baseCounts :: String -> Zip [(String, Int)]\ndef baseCounts(baseString):\n '''Sums for each base type in the given sequence string, with\n a fifth sum for any characters not drawn from {A, C, G, T}.'''\n bases = {\n 'A': 0,\n 'C': 1,\n 'G': 2,\n 'T': 3\n }\n return zip(\n list(bases.keys()) + ['Other'],\n foldl(\n lambda a: compose(\n nthArrow(succ)(a),\n flip(curry(bases.get))(4)\n )\n )((0, 0, 0, 0, 0))(baseString)\n )\n\n\n# -------------------------- TEST --------------------------\n# main :: IO ()\ndef main():\n '''Base counts and sequence displayed in GenBank format\n '''\n print(\n genBankFormatWithBaseCounts('''\\\nCGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\\\nCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\\\nAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\\\nGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\\\nCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\\\nTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\\\nTTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\\\nCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\\\nTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\\\nGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT''')\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 divible, the final list will be shorter than n.\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 :: ((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# curry :: ((a, b) -> c) -> a -> b -> c\ndef curry(f):\n '''A curried function derived\n from an uncurried function.\n '''\n return lambda x: lambda y: f(x, y)\n\n\n# flip :: (a -> b -> c) -> b -> a -> c\ndef flip(f):\n '''The (curried or uncurried) function f with its\n arguments reversed.\n '''\n return lambda a: lambda b: f(b)(a)\n\n\n# foldl :: (a -> b -> a) -> a -> [b] -> a\ndef foldl(f):\n '''Left to right reduction of a list,\n using the binary operator f, and\n starting with an initial value a.\n '''\n def go(acc, xs):\n return reduce(lambda a, x: f(a)(x), xs, acc)\n return lambda acc: lambda xs: go(acc, xs)\n\n\n# nthArrow :: (a -> b) -> Tuple -> Int -> Tuple\ndef nthArrow(f):\n '''A simple function lifted to one which applies\n to a tuple, transforming only its nth value.\n '''\n def go(v, n):\n return v if n > len(v) else [\n x if n != i else f(x)\n for i, x in enumerate(v)\n ]\n return lambda tpl: lambda n: tuple(go(tpl, n))\n\n\n# succ :: Enum a => a -> a\ndef succ(x):\n '''The successor of a value.\n For numeric types, (1 +).\n '''\n return 1 + x\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} -{"title": "Biorhythms", "language": "Python", "task": "For a while in the late 70s, the pseudoscience of biorhythms was popular enough to rival astrology, with kiosks in malls that would give you your weekly printout. It was also a popular entry in \"Things to Do with your Pocket Calculator\" lists. You can read up on the history at Wikipedia, but the main takeaway is that unlike astrology, the math behind biorhythms is dead simple.\n\nIt's based on the number of days since your birth. The premise is that three cycles of unspecified provenance govern certain aspects of everyone's lives - specifically, how they're feeling physically, emotionally, and mentally. The best part is that not only do these cycles somehow have the same respective lengths for all humans of any age, gender, weight, genetic background, etc, but those lengths are an exact number of days. And the pattern is in each case a perfect sine curve. Absolutely miraculous!\n\nTo compute your biorhythmic profile for a given day, the first thing you need is the number of days between that day and your birth, so the answers in [[Days between dates]] are probably a good starting point. (Strictly speaking, the biorhythms start at 0 at the moment of your birth, so if you know time of day you can narrow things down further, but in general these operate at whole-day granularity.) Then take the residue of that day count modulo each of the the cycle lengths to calculate where the day falls on each of the three sinusoidal journeys. \n\nThe three cycles and their lengths are as follows:\n:::{| class=\"wikitable\"\n! Cycle \n! Length\n|- \n|Physical \n| 23 days\n|- \n|Emotional \n| 28 days\n|- \n|Mental \n| 33 days\n|}\n\nThe first half of each cycle is in \"plus\" territory, with a peak at the quarter-way point; the second half in \"minus\" territory, with a valley at the three-quarters mark. You can calculate a specific value between -1 and +1 for the ''k''th day of an ''n''-day cycle by computing '''sin( 2p''k'' / ''n'' )'''. The days where a cycle crosses the axis in either direction are called \"critical\" days, although with a cycle value of 0 they're also said to be the most neutral, which seems contradictory.\n\nThe task: write a subroutine, function, or program that will, given a birthdate and a target date, output the three biorhythmic values for the day. You may optionally include a text description of the position and the trend (e.g. \"up and rising\", \"peak\", \"up but falling\", \"critical\", \"down and falling\", \"valley\", \"down but rising\"), an indication of the date on which the next notable event (peak, valley, or crossing) falls, or even a graph of the cycles around the target date. Demonstrate the functionality for dates of your choice.\n\nExample run of my Raku implementation:\nraku br.raku 1943-03-09 1972-07-11\n", "solution": "\"\"\"\n\nPython implementation of\n\nhttp://rosettacode.org/wiki/Biorhythms\n\n\"\"\"\n\nfrom datetime import date, timedelta\nfrom math import floor, sin, pi\n\ndef biorhythms(birthdate,targetdate):\n \"\"\"\n Print out biorhythm data for targetdate assuming you were\n born on birthdate.\n \n birthdate and targetdata are strings in this format:\n \n YYYY-MM-DD e.g. 1964-12-26\n \"\"\"\n \n # print dates\n \n print(\"Born: \"+birthdate+\" Target: \"+targetdate) \n \n # convert to date types - Python 3.7 or later\n \n birthdate = date.fromisoformat(birthdate)\n targetdate = date.fromisoformat(targetdate)\n \n # days between\n \n days = (targetdate - birthdate).days\n \n print(\"Day: \"+str(days))\n \n # cycle logic - mostly from Julia example\n \n cycle_labels = [\"Physical\", \"Emotional\", \"Mental\"]\n cycle_lengths = [23, 28, 33]\n quadrants = [(\"up and rising\", \"peak\"), (\"up but falling\", \"transition\"),\n (\"down and falling\", \"valley\"), (\"down but rising\", \"transition\")]\n \n for i in range(3):\n label = cycle_labels[i]\n length = cycle_lengths[i]\n position = days % length\n quadrant = int(floor((4 * position) / length))\n percentage = int(round(100 * sin(2 * pi * position / length),0))\n transition_date = targetdate + timedelta(days=floor((quadrant + 1)/4 * length) - position)\n trend, next = quadrants[quadrant]\n \n if percentage > 95:\n description = \"peak\"\n elif percentage < -95:\n description = \"valley\"\n elif abs(percentage) < 5:\n description = \"critical transition\"\n else:\n description = str(percentage)+\"% (\"+trend+\", next \"+next+\" \"+str(transition_date)+\")\"\n print(label+\" day \"+str(position)+\": \"+description)\n \n \nbiorhythms(\"1943-03-09\",\"1972-07-11\")\n"} -{"title": "Bitcoin/address validation", "language": "C", "task": "Write a program that takes a bitcoin address as argument, \nand checks whether or not this address is valid.\n\nA bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters:\n:::* 0 zero\n:::* O uppercase oh\n:::* I uppercase eye\n:::* l lowercase ell\n\n\nWith this encoding, a bitcoin address encodes 25 bytes:\n* the first byte is the version number, which will be zero for this task ;\n* the next twenty bytes are a [[RIPEMD-160]] digest, but you don't have to know that for this task: you can consider them a pure arbitrary data ;\n* the last four bytes are a checksum check. They are the first four bytes of a double [[SHA-256]] digest of the previous 21 bytes.\n\n\nTo check the bitcoin address, you must read the first twenty-one bytes, compute the checksum, and check that it corresponds to the last four bytes.\n\nThe program can either return a boolean value or throw an exception when not valid.\n\nYou can use a digest library for [[SHA-256]].\n\n\n;Example of a bitcoin address:\n\n 1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i\n\n\nIt doesn't belong to anyone and is part of the test suite of the bitcoin software. \nYou can change a few characters in this string and check that it'll fail the test.\n\n", "solution": "#include \n#include \n#include \n\nconst char *coin_err;\n#define bail(s) { coin_err = s; return 0; }\n\nint unbase58(const char *s, unsigned char *out) {\n\tstatic const char *tmpl = \"123456789\"\n\t\t\"ABCDEFGHJKLMNPQRSTUVWXYZ\"\n\t\t\"abcdefghijkmnopqrstuvwxyz\";\n\tint i, j, c;\n\tconst char *p;\n\n\tmemset(out, 0, 25);\n\tfor (i = 0; s[i]; i++) {\n\t\tif (!(p = strchr(tmpl, s[i])))\n\t\t\tbail(\"bad char\");\n\n\t\tc = p - tmpl;\n\t\tfor (j = 25; j--; ) {\n\t\t\tc += 58 * out[j];\n\t\t\tout[j] = c % 256;\n\t\t\tc /= 256;\n\t\t}\n\n\t\tif (c) bail(\"address too long\");\n\t}\n\n\treturn 1;\n}\n\nint valid(const char *s) {\n\tunsigned char dec[32], d1[SHA256_DIGEST_LENGTH], d2[SHA256_DIGEST_LENGTH];\n\n\tcoin_err = \"\";\n\tif (!unbase58(s, dec)) return 0;\n\n\tSHA256(SHA256(dec, 21, d1), SHA256_DIGEST_LENGTH, d2);\n\n\tif (memcmp(dec + 21, d2, 4))\n\t\tbail(\"bad digest\");\n\n\treturn 1;\n}\n\nint main (void) {\n\tconst char *s[] = {\n\t\t\"1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9\",\n\t\t\"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i\",\n\t\t\"1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nJ9\",\n\t\t\"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62I\",\n\t\t0 };\n\tint i;\n\tfor (i = 0; s[i]; i++) {\n\t\tint status = valid(s[i]);\n\t\tprintf(\"%s: %s\\n\", s[i], status ? \"Ok\" : coin_err);\n\t}\n\n\treturn 0;\n}"} -{"title": "Bitcoin/address validation", "language": "Python", "task": "Write a program that takes a bitcoin address as argument, \nand checks whether or not this address is valid.\n\nA bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters:\n:::* 0 zero\n:::* O uppercase oh\n:::* I uppercase eye\n:::* l lowercase ell\n\n\nWith this encoding, a bitcoin address encodes 25 bytes:\n* the first byte is the version number, which will be zero for this task ;\n* the next twenty bytes are a [[RIPEMD-160]] digest, but you don't have to know that for this task: you can consider them a pure arbitrary data ;\n* the last four bytes are a checksum check. They are the first four bytes of a double [[SHA-256]] digest of the previous 21 bytes.\n\n\nTo check the bitcoin address, you must read the first twenty-one bytes, compute the checksum, and check that it corresponds to the last four bytes.\n\nThe program can either return a boolean value or throw an exception when not valid.\n\nYou can use a digest library for [[SHA-256]].\n\n\n;Example of a bitcoin address:\n\n 1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i\n\n\nIt doesn't belong to anyone and is part of the test suite of the bitcoin software. \nYou can change a few characters in this string and check that it'll fail the test.\n\n", "solution": "from hashlib import sha256\n\ndigits58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n\ndef decode_base58(bc, length):\n n = 0\n for char in bc:\n n = n * 58 + digits58.index(char)\n return n.to_bytes(length, 'big')\ndef check_bc(bc):\n try:\n bcbytes = decode_base58(bc, 25)\n return bcbytes[-4:] == sha256(sha256(bcbytes[:-4]).digest()).digest()[:4]\n except Exception:\n return False\n\nprint(check_bc('1AGNa15ZQXAZUgFiqJ3i7Z2DPU2J6hW62i'))\nprint(check_bc(\"17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j\"))"} -{"title": "Bitcoin/public point to address", "language": "C", "task": "elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion.\n\nThe encoding steps are:\n* take the X and Y coordinates of the given public point, and concatenate them in order to have a 64 byte-longed string ;\n* add one byte prefix equal to 4 (it is a convention for this way of encoding a public point) ;\n* compute the [[SHA-256]] of this string ;\n* compute the [[RIPEMD-160]] of this SHA-256 digest ;\n* compute the checksum of the concatenation of the version number digit (a single zero byte) and this RIPEMD-160 digest, as described in [[bitcoin/address validation]] ;\n* Base-58 encode (see below) the concatenation of the version number (zero in this case), the ripemd digest and the checksum\n\nThe base-58 encoding is based on an alphabet of alphanumeric characters (numbers, upper case and lower case, in that order) but without the four characters 0, O, l and I.\n\nHere is an example public point:\nX = 0x50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352\nY = 0x2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6\n\nThe corresponding address should be:\n16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM\n\nNb. The leading '1' is not significant as 1 is zero in base-58. It is however often added to the bitcoin address for various reasons. There can actually be several of them. You can ignore this and output an address without the leading 1.\n\n''Extra credit:'' add a verification procedure about the public point, making sure it belongs to the secp256k1 elliptic curve\n", "solution": "#include \n#include \n#include \n#include \n#include \n\n#define COIN_VER 0\nconst char *coin_err;\n\ntypedef unsigned char byte;\n\nint is_hex(const char *s) {\n\tint i;\n\tfor (i = 0; i < 64; i++)\n\t\tif (!isxdigit(s[i])) return 0;\n\treturn 1;\n}\n\nvoid str_to_byte(const char *src, byte *dst, int n) {\n\twhile (n--) sscanf(src + n * 2, \"%2hhx\", dst + n);\n}\n\nchar* base58(byte *s, char *out) {\n\tstatic const char *tmpl = \"123456789\"\n\t\t\"ABCDEFGHJKLMNPQRSTUVWXYZ\"\n\t\t\"abcdefghijkmnopqrstuvwxyz\";\n\tstatic char buf[40];\n\n\tint c, i, n;\n\tif (!out) out = buf;\n\n\tout[n = 34] = 0;\n\twhile (n--) {\n\t\tfor (c = i = 0; i < 25; i++) {\n\t\t\tc = c * 256 + s[i];\n\t\t\ts[i] = c / 58;\n\t\t\tc %= 58;\n\t\t}\n\t\tout[n] = tmpl[c];\n\t}\n\n\tfor (n = 0; out[n] == '1'; n++);\n\tmemmove(out, out + n, 34 - n);\n\n\treturn out;\n}\n\nchar *coin_encode(const char *x, const char *y, char *out) {\n\tbyte s[65];\n\tbyte rmd[5 + RIPEMD160_DIGEST_LENGTH];\n\n\tif (!is_hex(x) || !(is_hex(y))) {\n\t\tcoin_err = \"bad public point string\";\n\t\treturn 0;\n\t}\n\n\ts[0] = 4;\n\tstr_to_byte(x, s + 1, 32);\n\tstr_to_byte(y, s + 33, 32);\n\n\trmd[0] = COIN_VER;\n\tRIPEMD160(SHA256(s, 65, 0), SHA256_DIGEST_LENGTH, rmd + 1);\n\n\tmemcpy(rmd + 21, SHA256(SHA256(rmd, 21, 0), SHA256_DIGEST_LENGTH, 0), 4);\n\n\treturn base58(rmd, out);\n}\n\nint main(void) {\n\tputs(coin_encode(\n\t\t\"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352\",\n\t\t\"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6\",\n\t\t0));\n\treturn 0;\n}"} -{"title": "Bitcoin/public point to address", "language": "Python", "task": "elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion.\n\nThe encoding steps are:\n* take the X and Y coordinates of the given public point, and concatenate them in order to have a 64 byte-longed string ;\n* add one byte prefix equal to 4 (it is a convention for this way of encoding a public point) ;\n* compute the [[SHA-256]] of this string ;\n* compute the [[RIPEMD-160]] of this SHA-256 digest ;\n* compute the checksum of the concatenation of the version number digit (a single zero byte) and this RIPEMD-160 digest, as described in [[bitcoin/address validation]] ;\n* Base-58 encode (see below) the concatenation of the version number (zero in this case), the ripemd digest and the checksum\n\nThe base-58 encoding is based on an alphabet of alphanumeric characters (numbers, upper case and lower case, in that order) but without the four characters 0, O, l and I.\n\nHere is an example public point:\nX = 0x50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352\nY = 0x2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6\n\nThe corresponding address should be:\n16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM\n\nNb. The leading '1' is not significant as 1 is zero in base-58. It is however often added to the bitcoin address for various reasons. There can actually be several of them. You can ignore this and output an address without the leading 1.\n\n''Extra credit:'' add a verification procedure about the public point, making sure it belongs to the secp256k1 elliptic curve\n", "solution": "#!/usr/bin/env python3\n\nimport binascii\nimport functools\nimport hashlib\n\ndigits58 = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n\ndef b58(n):\n return b58(n//58) + digits58[n%58:n%58+1] if n else b''\n\ndef public_point_to_address(x, y):\n c = b'\\x04' + binascii.unhexlify(x) + binascii.unhexlify(y)\n r = hashlib.new('ripemd160')\n r.update(hashlib.sha256(c).digest())\n c = b'\\x00' + r.digest()\n d = hashlib.sha256(hashlib.sha256(c).digest()).digest()\n return b58(functools.reduce(lambda n, b: n<<8|b, c + d[:4]))\n\nif __name__ == '__main__':\n print(public_point_to_address(\n b'50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352',\n b'2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6'))"} -{"title": "Bitwise IO", "language": "C", "task": "The aim of this task is to write functions (or create a class if yourlanguage is Object Oriented and you prefer) for reading and writing sequences of\nbits, most significant bit first. While the output of a asciiprint \"STRING\" is the ASCII byte sequence\n\"S\", \"T\", \"R\", \"I\", \"N\", \"G\", the output of a \"print\" of the bits sequence\n0101011101010 (13 bits) must be 0101011101010; real I/O is performed always\n''quantized'' by byte (avoiding endianness issues and relying on underlying\nbuffering for performance), therefore you must obtain as output the bytes\n0101 0111 0101 0'''000''' (bold bits are padding bits), i.e. in hexadecimal 57 50.\n\nAs test, you can implement a '''rough''' (e.g. don't care about error handling or\nother issues) compression/decompression program for ASCII sequences\nof bytes, i.e. bytes for which the most significant bit is always unused, so that you can write\nseven bits instead of eight (each 8 bytes of input, we write 7 bytes of output).\n\nThese bit oriented I/O functions can be used to implement compressors and\ndecompressors; e.g. Dynamic and Static Huffman encodings use variable length\nbits sequences, while LZW (see [[LZW compression]]) use fixed or variable ''words''\nnine (or more) bits long.\n\n* Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed.\n* Errors handling is not mandatory\n\n", "solution": "#include \n#include \n#include \n#include \n\ntypedef uint8_t byte;\ntypedef struct {\n FILE *fp;\n uint32_t accu;\n int bits;\n} bit_io_t, *bit_filter;\n\nbit_filter b_attach(FILE *f)\n{\n bit_filter b = malloc(sizeof(bit_io_t));\n b->bits = b->accu = 0;\n b->fp = f;\n return b;\n}\n\nvoid b_write(byte *buf, size_t n_bits, size_t shift, bit_filter bf)\n{\n uint32_t accu = bf->accu;\n int bits = bf->bits;\n\n buf += shift / 8;\n shift %= 8;\n\n while (n_bits || bits >= 8) {\n while (bits >= 8) {\n bits -= 8;\n fputc(accu >> bits, bf->fp);\n accu &= (1 << bits) - 1;\n }\n while (bits < 8 && n_bits) {\n accu = (accu << 1) | (((128 >> shift) & *buf) >> (7 - shift));\n --n_bits;\n bits++;\n if (++shift == 8) {\n shift = 0;\n buf++;\n }\n }\n }\n bf->accu = accu;\n bf->bits = bits;\n}\n\nsize_t b_read(byte *buf, size_t n_bits, size_t shift, bit_filter bf)\n{\n uint32_t accu = bf->accu;\n int bits = bf->bits;\n int mask, i = 0;\n\n buf += shift / 8;\n shift %= 8;\n\n while (n_bits) {\n while (bits && n_bits) {\n mask = 128 >> shift;\n if (accu & (1 << (bits - 1))) *buf |= mask;\n else *buf &= ~mask;\n\n n_bits--;\n bits--;\n\n if (++shift >= 8) {\n shift = 0;\n buf++;\n }\n }\n if (!n_bits) break;\n accu = (accu << 8) | fgetc(bf->fp);\n bits += 8;\n }\n bf->accu = accu;\n bf->bits = bits;\n\n return i;\n}\n\nvoid b_detach(bit_filter bf)\n{\n if (bf->bits) {\n bf->accu <<= 8 - bf->bits;\n fputc(bf->accu, bf->fp);\n }\n free(bf);\n}\n\nint main()\n{\n unsigned char s[] = \"abcdefghijk\";\n unsigned char s2[11] = {0};\n int i;\n\n FILE *f = fopen(\"test.bin\", \"wb\");\n bit_filter b = b_attach(f);\n /* for each byte in s, write 7 bits skipping 1 */\n for (i = 0; i < 10; i++) b_write(s + i, 7, 1, b);\n b_detach(b);\n fclose(f);\n\n /* read 7 bits and expand to each byte of s2 skipping 1 bit */\n f = fopen(\"test.bin\", \"rb\");\n b = b_attach(f);\n for (i = 0; i < 10; i++) b_read(s2 + i, 7, 1, b);\n b_detach(b);\n fclose(f);\n\n printf(\"%10s\\n\", s2); /* should be the same first 10 bytes as in s */\n\n return 0;\n}"} -{"title": "Bitwise IO", "language": "Python", "task": "The aim of this task is to write functions (or create a class if yourlanguage is Object Oriented and you prefer) for reading and writing sequences of\nbits, most significant bit first. While the output of a asciiprint \"STRING\" is the ASCII byte sequence\n\"S\", \"T\", \"R\", \"I\", \"N\", \"G\", the output of a \"print\" of the bits sequence\n0101011101010 (13 bits) must be 0101011101010; real I/O is performed always\n''quantized'' by byte (avoiding endianness issues and relying on underlying\nbuffering for performance), therefore you must obtain as output the bytes\n0101 0111 0101 0'''000''' (bold bits are padding bits), i.e. in hexadecimal 57 50.\n\nAs test, you can implement a '''rough''' (e.g. don't care about error handling or\nother issues) compression/decompression program for ASCII sequences\nof bytes, i.e. bytes for which the most significant bit is always unused, so that you can write\nseven bits instead of eight (each 8 bytes of input, we write 7 bytes of output).\n\nThese bit oriented I/O functions can be used to implement compressors and\ndecompressors; e.g. Dynamic and Static Huffman encodings use variable length\nbits sequences, while LZW (see [[LZW compression]]) use fixed or variable ''words''\nnine (or more) bits long.\n\n* Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed.\n* Errors handling is not mandatory\n\n", "solution": "class BitWriter(object):\n def __init__(self, f):\n self.accumulator = 0\n self.bcount = 0\n self.out = f\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.flush()\n\n def __del__(self):\n try:\n self.flush()\n except ValueError: # I/O operation on closed file.\n pass\n\n def _writebit(self, bit):\n if self.bcount == 8:\n self.flush()\n if bit > 0:\n self.accumulator |= 1 << 7-self.bcount\n self.bcount += 1\n\n def writebits(self, bits, n):\n while n > 0:\n self._writebit(bits & 1 << n-1)\n n -= 1\n\n def flush(self):\n self.out.write(bytearray([self.accumulator]))\n self.accumulator = 0\n self.bcount = 0\n\n\nclass BitReader(object):\n def __init__(self, f):\n self.input = f\n self.accumulator = 0\n self.bcount = 0\n self.read = 0\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n pass\n\n def _readbit(self):\n if not self.bcount:\n a = self.input.read(1)\n if a:\n self.accumulator = ord(a)\n self.bcount = 8\n self.read = len(a)\n rv = (self.accumulator & (1 << self.bcount-1)) >> self.bcount-1\n self.bcount -= 1\n return rv\n\n def readbits(self, n):\n v = 0\n while n > 0:\n v = (v << 1) | self._readbit()\n n -= 1\n return v\n\nif __name__ == '__main__':\n import os\n import sys\n # Determine this module's name from it's file name and import it.\n module_name = os.path.splitext(os.path.basename(__file__))[0]\n bitio = __import__(module_name)\n\n with open('bitio_test.dat', 'wb') as outfile:\n with bitio.BitWriter(outfile) as writer:\n chars = '12345abcde'\n for ch in chars:\n writer.writebits(ord(ch), 7)\n\n with open('bitio_test.dat', 'rb') as infile:\n with bitio.BitReader(infile) as reader:\n chars = []\n while True:\n x = reader.readbits(7)\n if not reader.read: # End-of-file?\n break\n chars.append(chr(x))\n print(''.join(chars))\n"} -{"title": "Box the compass", "language": "C", "task": "Avast me hearties!\nThere be many a land lubber that knows naught of the pirate ways and gives direction by degree!\nThey know not how to box the compass! \n\n\n;Task description:\n# Create a function that takes a heading in degrees and returns the correct 32-point compass heading.\n# Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:\n:[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).\n\n\n;Notes;\n* The headings and indices can be calculated from this pseudocode:\nfor i in 0..32 inclusive:\n heading = i * 11.25\n case i %3:\n if 1: heading += 5.62; break\n if 2: heading -= 5.62; break\n end\n index = ( i mod 32) + 1\n* The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..\n\n", "solution": "#include \n\nint main()\n{\n int i, j;\n double degrees[] = { 0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5,\n 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88,\n 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12,\n 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5,\n 354.37, 354.38 };\n const char * names = \"North \"\n \"North by east \"\n \"North-northeast \"\n \"Northeast by north \"\n \"Northeast \"\n \"Northeast by east \"\n \"East-northeast \"\n \"East by north \"\n \"East \"\n \"East by south \"\n \"East-southeast \"\n \"Southeast by east \"\n \"Southeast \"\n \"Southeast by south \"\n \"South-southeast \"\n \"South by east \"\n \"South \"\n \"South by west \"\n \"South-southwest \"\n \"Southwest by south \"\n \"Southwest \"\n \"Southwest by west \"\n \"West-southwest \"\n \"West by south \"\n \"West \"\n \"West by north \"\n \"West-northwest \"\n \"Northwest by west \"\n \"Northwest \"\n \"Northwest by north \"\n \"North-northwest \"\n \"North by west \"\n \"North \";\n\n for (i = 0; i < 33; i++) {\n j = .5 + degrees[i] * 32 / 360;\n\n printf(\"%2d %.22s %6.2f\\n\", (j % 32) + 1, names + (j % 32) * 22,\n degrees[i]);\n }\n\n return 0;\n}"} -{"title": "Box the compass", "language": "JavaScript", "task": "Avast me hearties!\nThere be many a land lubber that knows naught of the pirate ways and gives direction by degree!\nThey know not how to box the compass! \n\n\n;Task description:\n# Create a function that takes a heading in degrees and returns the correct 32-point compass heading.\n# Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:\n:[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).\n\n\n;Notes;\n* The headings and indices can be calculated from this pseudocode:\nfor i in 0..32 inclusive:\n heading = i * 11.25\n case i %3:\n if 1: heading += 5.62; break\n if 2: heading -= 5.62; break\n end\n index = ( i mod 32) + 1\n* The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..\n\n", "solution": "(() => {\n 'use strict';\n\n // GENERIC FUNCTIONS\n\n // toTitle :: String -> String\n let toTitle = s => s.length ? (s[0].toUpperCase() + s.slice(1)) : '';\n\n // COMPASS DATA AND FUNCTIONS\n\n // Scale invariant keys for points of the compass\n // (allows us to look up a translation for one scale of compass (32 here)\n // for use in another size of compass (8 or 16 points)\n // (Also semi-serviceable as more or less legible keys without translation)\n\n // compassKeys :: Int -> [String]\n let compassKeys = depth => {\n let urCompass = ['N', 'S', 'N'],\n subdivision = (compass, n) => n <= 1 ? (\n compass\n ) : subdivision( // Borders between N and S engender E and W.\n // other new boxes concatenate their parent keys.\n compass.reduce((a, x, i, xs) => {\n if (i > 0) {\n return (n === depth) ? (\n a.concat([x === 'N' ? 'W' : 'E'], x)\n ) : a.concat([xs[i - 1] + x, x]);\n } else return a.concat(x);\n }, []),\n n - 1\n );\n return subdivision(urCompass, depth)\n .slice(0, -1);\n };\n\n // https://zh.wikipedia.org/wiki/%E7%BD%97%E7%9B%98%E6%96%B9%E4%BD%8D\n let lstLangs = [{\n 'name': 'English',\n expansions: {\n N: 'north',\n S: 'south',\n E: 'east',\n W: 'west',\n b: ' by ',\n '-': '-'\n },\n 'N': 'N',\n 'NNNE': 'NbE',\n 'NNE': 'N-NE',\n 'NNENE': 'NEbN',\n 'NE': 'NE',\n 'NENEE': 'NEbE',\n 'NEE': 'E-NE',\n 'NEEE': 'EbN',\n 'E': 'E',\n 'EEES': 'EbS',\n 'EES': 'E-SE',\n 'EESES': 'SEbE',\n 'ES': 'SE',\n 'ESESS': 'SEbS',\n 'ESS': 'S-SE',\n 'ESSS': 'SbE',\n 'S': 'S',\n 'SSSW': 'SbW',\n 'SSW': 'S-SW',\n 'SSWSW': 'SWbS',\n 'SW': 'SW',\n 'SWSWW': 'SWbW',\n 'SWW': 'W-SW',\n 'SWWW': 'WbS',\n 'W': 'W',\n 'WWWN': 'WbN',\n 'WWN': 'W-NW',\n 'WWNWN': 'NWbW',\n 'WN': 'NW',\n 'WNWNN': 'NWbN',\n 'WNN': 'N-NW',\n 'WNNN': 'NbW'\n }, {\n 'name': 'Chinese',\n 'N': '\u5317',\n 'NNNE': '\u5317\u5fae\u4e1c',\n 'NNE': '\u4e1c\u5317\u504f\u5317',\n 'NNENE': '\u4e1c\u5317\u5fae\u5317',\n 'NE': '\u4e1c\u5317',\n 'NENEE': '\u4e1c\u5317\u5fae\u4e1c',\n 'NEE': '\u4e1c\u5317\u504f\u4e1c',\n 'NEEE': '\u4e1c\u5fae\u5317',\n 'E': '\u4e1c',\n 'EEES': '\u4e1c\u5fae\u5357',\n 'EES': '\u4e1c\u5357\u504f\u4e1c',\n 'EESES': '\u4e1c\u5357\u5fae\u4e1c',\n 'ES': '\u4e1c\u5357',\n 'ESESS': '\u4e1c\u5357\u5fae\u5357',\n 'ESS': '\u4e1c\u5357\u504f\u5357',\n 'ESSS': '\u5357\u5fae\u4e1c',\n 'S': '\u5357',\n 'SSSW': '\u5357\u5fae\u897f',\n 'SSW': '\u897f\u5357\u504f\u5357',\n 'SSWSW': '\u897f\u5357\u5fae\u5357',\n 'SW': '\u897f\u5357',\n 'SWSWW': '\u897f\u5357\u5fae\u897f',\n 'SWW': '\u897f\u5357\u504f\u897f',\n 'SWWW': '\u897f\u5fae\u5357',\n 'W': '\u897f',\n 'WWWN': '\u897f\u5fae\u5317',\n 'WWN': '\u897f\u5317\u504f\u897f',\n 'WWNWN': '\u897f\u5317\u5fae\u897f',\n 'WN': '\u897f\u5317',\n 'WNWNN': '\u897f\u5317\u5fae\u5317',\n 'WNN': '\u897f\u5317\u504f\u5317',\n 'WNNN': '\u5317\u5fae\u897f'\n }];\n\n // pointIndex :: Int -> Num -> Int\n let pointIndex = (power, degrees) => {\n let nBoxes = (power ? Math.pow(2, power) : 32);\n return Math.ceil(\n (degrees + (360 / (nBoxes * 2))) % 360 * nBoxes / 360\n ) || 1;\n };\n\n // pointNames :: Int -> Int -> [String]\n let pointNames = (precision, iBox) => {\n let k = compassKeys(precision)[iBox - 1];\n return lstLangs.map(dctLang => {\n let s = dctLang[k] || k, // fallback to key if no translation\n dctEx = dctLang.expansions;\n\n return dctEx ? toTitle(s.split('')\n .map(c => dctEx[c])\n .join(precision > 5 ? ' ' : ''))\n .replace(/ /g, ' ') : s;\n });\n };\n\n // maximumBy :: (a -> a -> Ordering) -> [a] -> a\n let maximumBy = (f, xs) =>\n xs.reduce((a, x) => a === undefined ? x : (\n f(x, a) > 0 ? x : a\n ), undefined);\n\n // justifyLeft :: Int -> Char -> Text -> Text\n let justifyLeft = (n, cFiller, strText) =>\n n > strText.length ? (\n (strText + replicate(n, cFiller)\n .join(''))\n .substr(0, n)\n ) : strText;\n\n // justifyRight :: Int -> Char -> Text -> Text\n let justifyRight = (n, cFiller, strText) =>\n n > strText.length ? (\n (replicate(n, cFiller)\n .join('') + strText)\n .slice(-n)\n ) : strText;\n\n // replicate :: Int -> a -> [a]\n let 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 // transpose :: [[a]] -> [[a]]\n let transpose = xs =>\n xs[0].map((_, iCol) => xs.map((row) => row[iCol]));\n\n // length :: [a] -> Int\n // length :: Text -> Int\n let length = xs => xs.length;\n\n // compareByLength = (a, a) -> (-1 | 0 | 1)\n let compareByLength = (a, b) => {\n let [na, nb] = [a, b].map(length);\n return na < nb ? -1 : na > nb ? 1 : 0;\n };\n\n // maxLen :: [String] -> Int\n let maxLen = xs => maximumBy(compareByLength, xs)\n .length;\n\n // compassTable :: Int -> [Num] -> Maybe String\n let compassTable = (precision, xs) => {\n if (precision < 1) return undefined;\n else {\n let intPad = 2;\n\n let lstIndex = xs.map(x => pointIndex(precision, x)),\n lstStrIndex = lstIndex.map(x => x.toString()),\n nIndexWidth = maxLen(lstStrIndex),\n colIndex = lstStrIndex.map(\n x => justifyRight(nIndexWidth, ' ', x)\n );\n\n let lstAngles = xs.map(x => x.toFixed(2) + '\u00b0'),\n nAngleWidth = maxLen(lstAngles) + intPad,\n colAngles = lstAngles.map(x => justifyRight(nAngleWidth, ' ', x));\n\n let lstTrans = transpose(\n lstIndex.map(i => pointNames(precision, i))\n ),\n lstTransWidths = lstTrans.map(x => maxLen(x) + 2),\n colsTrans = lstTrans\n .map((lstLang, i) => lstLang\n .map(x => justifyLeft(lstTransWidths[i], ' ', x))\n );\n\n return transpose([colIndex]\n .concat([colAngles], [replicate(lstIndex.length, \" \")])\n .concat(colsTrans))\n .map(x => x.join(''))\n .join('\\n');\n }\n }\n\n // TEST\n let xs = [0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37,\n 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75,\n 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13,\n 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37,\n 354.38\n ];\n\n // If we supply other precisions, like 4 or 6, (2^n -> 16 or 64 boxes)\n // the bearings will be divided amongst smaller or larger numbers of boxes,\n // either using name translations retrieved by the generic hash\n // or using the hash itself (combined with any expansions)\n // to substitute for missing names for very finely divided boxes.\n\n return compassTable(5, xs); // 2^5 -> 32 boxes\n})();"} -{"title": "Box the compass", "language": "Python", "task": "Avast me hearties!\nThere be many a land lubber that knows naught of the pirate ways and gives direction by degree!\nThey know not how to box the compass! \n\n\n;Task description:\n# Create a function that takes a heading in degrees and returns the correct 32-point compass heading.\n# Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:\n:[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).\n\n\n;Notes;\n* The headings and indices can be calculated from this pseudocode:\nfor i in 0..32 inclusive:\n heading = i * 11.25\n case i %3:\n if 1: heading += 5.62; break\n if 2: heading -= 5.62; break\n end\n index = ( i mod 32) + 1\n* The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..\n\n", "solution": "majors = 'north east south west'.split()\nmajors *= 2 # no need for modulo later\nquarter1 = 'N,N by E,N-NE,NE by N,NE,NE by E,E-NE,E by N'.split(',')\nquarter2 = [p.replace('NE','EN') for p in quarter1]\n\ndef degrees2compasspoint(d):\n d = (d % 360) + 360/64\n majorindex, minor = divmod(d, 90.)\n majorindex = int(majorindex)\n minorindex = int( (minor*4) // 45 )\n p1, p2 = majors[majorindex: majorindex+2]\n if p1 in {'north', 'south'}:\n q = quarter1\n else:\n q = quarter2\n return q[minorindex].replace('N', p1).replace('E', p2).capitalize()\n\nif __name__ == '__main__':\n for i in range(33):\n d = i * 11.25\n m = i % 3\n if m == 1: d += 5.62\n elif m == 2: d -= 5.62\n n = i % 32 + 1\n print( '%2i %-18s %7.2f\u00b0' % (n, degrees2compasspoint(d), d) )"} -{"title": "Boyer-Moore string search", "language": "Python", "task": "This algorithm is designed for pattern searching on certain types of devices which are backtracking-unfriendly such as Tape drives and Hard disks.\n\nIt works by first caching a segment of data from storage and match it against the pattern from the highest position backward to the lowest. If the matching fails, it will cache next segment of data and move the start point forward to skip the portion of data which will definitely fail to match. This continues until we successfully match the pattern or the pointer exceeds the data length.\n\nFollow this link for more information about this algorithm.\n\nTo properly test this algorithm, it would be good to search for a string which contains repeated subsequences, such as alfalfa and the text being searched should not only include a match but that match should be preceded by words which partially match, such as alfredo, behalf, calfskin, halfhearted, malfunction or severalfold.\n", "solution": "\"\"\"\nThis version uses ASCII for case-sensitive matching. For Unicode you may want to match in UTF-8\nbytes instead of creating a 0x10FFFF-sized table.\n\"\"\"\n\nfrom typing import List\n\nALPHABET_SIZE = 256\n\ndef alphabet_index(c: str) -> int:\n \"\"\"Return the index of the given ASCII character. \"\"\"\n val = ord(c)\n assert 0 <= val < ALPHABET_SIZE\n return val\n\ndef match_length(S: str, idx1: int, idx2: int) -> int:\n \"\"\"Return the length of the match of the substrings of S beginning at idx1 and idx2.\"\"\"\n if idx1 == idx2:\n return len(S) - idx1\n match_count = 0\n while idx1 < len(S) and idx2 < len(S) and S[idx1] == S[idx2]:\n match_count += 1\n idx1 += 1\n idx2 += 1\n return match_count\n\ndef fundamental_preprocess(S: str) -> List[int]:\n \"\"\"Return Z, the Fundamental Preprocessing of S.\n\n Z[i] is the length of the substring beginning at i which is also a prefix of S.\n This pre-processing is done in O(n) time, where n is the length of S.\n \"\"\"\n if len(S) == 0: # Handles case of empty string\n return []\n if len(S) == 1: # Handles case of single-character string\n return [1]\n z = [0 for x in S]\n z[0] = len(S)\n z[1] = match_length(S, 0, 1)\n for i in range(2, 1 + z[1]): # Optimization from exercise 1-5\n z[i] = z[1] - i + 1\n # Defines lower and upper limits of z-box\n l = 0\n r = 0\n for i in range(2 + z[1], len(S)):\n if i <= r: # i falls within existing z-box\n k = i - l\n b = z[k]\n a = r - i + 1\n if b < a: # b ends within existing z-box\n z[i] = b\n else: # b ends at or after the end of the z-box, we need to do an explicit match to the right of the z-box\n z[i] = a + match_length(S, a, r + 1)\n l = i\n r = i + z[i] - 1\n else: # i does not reside within existing z-box\n z[i] = match_length(S, 0, i)\n if z[i] > 0:\n l = i\n r = i + z[i] - 1\n return z\n\ndef bad_character_table(S: str) -> List[List[int]]:\n \"\"\"\n Generates R for S, which is an array indexed by the position of some character c in the\n ASCII table. At that index in R is an array of length |S|+1, specifying for each\n index i in S (plus the index after S) the next location of character c encountered when\n traversing S from right to left starting at i. This is used for a constant-time lookup\n for the bad character rule in the Boyer-Moore string search algorithm, although it has\n a much larger size than non-constant-time solutions.\n \"\"\"\n if len(S) == 0:\n return [[] for a in range(ALPHABET_SIZE)]\n R = [[-1] for a in range(ALPHABET_SIZE)]\n alpha = [-1 for a in range(ALPHABET_SIZE)]\n for i, c in enumerate(S):\n alpha[alphabet_index(c)] = i\n for j, a in enumerate(alpha):\n R[j].append(a)\n return R\n\ndef good_suffix_table(S: str) -> List[int]:\n \"\"\"\n Generates L for S, an array used in the implementation of the strong good suffix rule.\n L[i] = k, the largest position in S such that S[i:] (the suffix of S starting at i) matches\n a suffix of S[:k] (a substring in S ending at k). Used in Boyer-Moore, L gives an amount to\n shift P relative to T such that no instances of P in T are skipped and a suffix of P[:L[i]]\n matches the substring of T matched by a suffix of P in the previous match attempt.\n Specifically, if the mismatch took place at position i-1 in P, the shift magnitude is given\n by the equation len(P) - L[i]. In the case that L[i] = -1, the full shift table is used.\n Since only proper suffixes matter, L[0] = -1.\n \"\"\"\n L = [-1 for c in S]\n N = fundamental_preprocess(S[::-1]) # S[::-1] reverses S\n N.reverse()\n for j in range(0, len(S) - 1):\n i = len(S) - N[j]\n if i != len(S):\n L[i] = j\n return L\n\ndef full_shift_table(S: str) -> List[int]:\n \"\"\"\n Generates F for S, an array used in a special case of the good suffix rule in the Boyer-Moore\n string search algorithm. F[i] is the length of the longest suffix of S[i:] that is also a\n prefix of S. In the cases it is used, the shift magnitude of the pattern P relative to the\n text T is len(P) - F[i] for a mismatch occurring at i-1.\n \"\"\"\n F = [0 for c in S]\n Z = fundamental_preprocess(S)\n longest = 0\n for i, zv in enumerate(reversed(Z)):\n longest = max(zv, longest) if zv == i + 1 else longest\n F[-i - 1] = longest\n return F\n\ndef string_search(P, T) -> List[int]:\n \"\"\"\n Implementation of the Boyer-Moore string search algorithm. This finds all occurrences of P\n in T, and incorporates numerous ways of pre-processing the pattern to determine the optimal\n amount to shift the string and skip comparisons. In practice it runs in O(m) (and even\n sublinear) time, where m is the length of T. This implementation performs a case-sensitive\n search on ASCII characters. P must be ASCII as well.\n \"\"\"\n if len(P) == 0 or len(T) == 0 or len(T) < len(P):\n return []\n\n matches = []\n\n # Preprocessing\n R = bad_character_table(P)\n L = good_suffix_table(P)\n F = full_shift_table(P)\n\n k = len(P) - 1 # Represents alignment of end of P relative to T\n previous_k = -1 # Represents alignment in previous phase (Galil's rule)\n while k < len(T):\n i = len(P) - 1 # Character to compare in P\n h = k # Character to compare in T\n while i >= 0 and h > previous_k and P[i] == T[h]: # Matches starting from end of P\n i -= 1\n h -= 1\n if i == -1 or h == previous_k: # Match has been found (Galil's rule)\n matches.append(k - len(P) + 1)\n k += len(P) - F[1] if len(P) > 1 else 1\n else: # No match, shift by max of bad character and good suffix rules\n char_shift = i - R[alphabet_index(T[h])][i]\n if i + 1 == len(P): # Mismatch happened on first attempt\n suffix_shift = 1\n elif L[i + 1] == -1: # Matched suffix does not appear anywhere in P\n suffix_shift = len(P) - F[i + 1]\n else: # Matched suffix appears in P\n suffix_shift = len(P) - 1 - L[i + 1]\n shift = max(char_shift, suffix_shift)\n previous_k = k if shift >= i + 1 else previous_k # Galil's rule\n k += shift\n return matches\n\nTEXT1 = 'InhisbookseriesTheArtofComputerProgrammingpublishedbyAddisonWesleyDKnuthusesanimaginarycomputertheMIXanditsassociatedmachinecodeandassemblylanguagestoillustratetheconceptsandalgorithmsastheyarepresented'\nTEXT2 = \"Nearby farms grew a half acre of alfalfa on the dairy's behalf, with bales of all that alfalfa exchanged for milk.\"\nPAT1, PAT2, PAT3 = 'put', 'and', 'alfalfa'\n\nprint(\"Found\", PAT1, \"at:\", string_search(PAT1, TEXT1))\nprint(\"Found\", PAT2, \"at:\", string_search(PAT2, TEXT1))\nprint(\"Found\", PAT3, \"at:\", string_search(PAT3, TEXT2))\n"} -{"title": "Brazilian numbers", "language": "C++ from D", "task": "Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad ''Olimpiada Iberoamericana de Matematica'' in Fortaleza, Brazil.\n\nBrazilian numbers are defined as:\n\nThe set of positive integer numbers where each number '''N''' has at least one natural number '''B''' where '''1 < B < N-1''' where the representation of '''N''' in '''base B''' has all equal digits.\n\n\n;E.G.:\n\n:* '''1, 2 & 3''' can not be Brazilian; there is no base '''B''' that satisfies the condition '''1 < B < N-1'''.\n:* '''4''' is not Brazilian; '''4''' in '''base 2''' is '''100'''. The digits are not all the same.\n:* '''5''' is not Brazilian; '''5''' in '''base 2''' is '''101''', in '''base 3''' is '''12'''. There is no representation where the digits are the same.\n:* '''6''' is not Brazilian; '''6''' in '''base 2''' is '''110''', in '''base 3''' is '''20''', in '''base 4''' is '''12'''. There is no representation where the digits are the same.\n:* '''7''' ''is'' Brazilian; '''7''' in '''base 2''' is '''111'''. There is at least one representation where the digits are all the same.\n:* '''8''' ''is'' Brazilian; '''8''' in '''base 3''' is '''22'''. There is at least one representation where the digits are all the same.\n:* ''and so on...''\n\n\nAll even integers '''2P >= 8''' are Brazilian because '''2P = 2(P-1) + 2''', which is '''22''' in '''base P-1''' when '''P-1 > 2'''. That becomes true when '''P >= 4'''.\nMore common: for all all integers '''R''' and '''S''', where '''R > 1''' and also '''S-1 > R''', then '''R*S''' is Brazilian because '''R*S = R(S-1) + R''', which is '''RR''' in '''base S-1'''\nThe only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3. \nAll prime integers, that are brazilian, can only have the digit '''1'''. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of '''111''' to base Integer(sqrt(prime number)). Must be an odd count of '''1''' to stay odd like primes > 2\n\n;Task:\n\nWrite a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page;\n\n:* the first '''20''' Brazilian numbers;\n:* the first '''20 odd''' Brazilian numbers;\n:* the first '''20 prime''' Brazilian numbers;\n\n\n;See also:\n\n:* '''OEIS:A125134 - Brazilian numbers'''\n:* '''OEIS:A257521 - Odd Brazilian numbers'''\n:* '''OEIS:A085104 - Prime Brazilian numbers'''\n\n", "solution": "#include \n\nbool sameDigits(int n, int b) {\n int f = n % b;\n while ((n /= b) > 0) {\n if (n % b != f) {\n return false;\n }\n }\n return true;\n}\n\nbool isBrazilian(int n) {\n if (n < 7) return false;\n if (n % 2 == 0)return true;\n for (int b = 2; b < n - 1; b++) {\n if (sameDigits(n, b)) {\n return true;\n }\n }\n return false;\n}\n\nbool isPrime(int n) {\n if (n < 2)return false;\n if (n % 2 == 0)return n == 2;\n if (n % 3 == 0)return n == 3;\n int d = 5;\n while (d * d <= n) {\n if (n % d == 0)return false;\n d += 2;\n if (n % d == 0)return false;\n d += 4;\n }\n return true;\n}\n\nint main() {\n for (auto kind : { \"\", \"odd \", \"prime \" }) {\n bool quiet = false;\n int BigLim = 99999;\n int limit = 20;\n std::cout << \"First \" << limit << ' ' << kind << \"Brazillian numbers:\\n\";\n int c = 0;\n int n = 7;\n while (c < BigLim) {\n if (isBrazilian(n)) {\n if (!quiet)std::cout << n << ' ';\n if (++c == limit) {\n std::cout << \"\\n\\n\";\n quiet = true;\n }\n }\n if (quiet && kind != \"\") continue;\n if (kind == \"\") {\n n++;\n }\n else if (kind == \"odd \") {\n n += 2;\n }\n else if (kind == \"prime \") {\n while (true) {\n n += 2;\n if (isPrime(n)) break;\n }\n } else {\n throw new std::runtime_error(\"Unexpected\");\n }\n }\n if (kind == \"\") {\n std::cout << \"The \" << BigLim + 1 << \"th Brazillian number is: \" << n << \"\\n\\n\";\n }\n }\n\n return 0;\n}"} -{"title": "Brazilian numbers", "language": "Python", "task": "Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad ''Olimpiada Iberoamericana de Matematica'' in Fortaleza, Brazil.\n\nBrazilian numbers are defined as:\n\nThe set of positive integer numbers where each number '''N''' has at least one natural number '''B''' where '''1 < B < N-1''' where the representation of '''N''' in '''base B''' has all equal digits.\n\n\n;E.G.:\n\n:* '''1, 2 & 3''' can not be Brazilian; there is no base '''B''' that satisfies the condition '''1 < B < N-1'''.\n:* '''4''' is not Brazilian; '''4''' in '''base 2''' is '''100'''. The digits are not all the same.\n:* '''5''' is not Brazilian; '''5''' in '''base 2''' is '''101''', in '''base 3''' is '''12'''. There is no representation where the digits are the same.\n:* '''6''' is not Brazilian; '''6''' in '''base 2''' is '''110''', in '''base 3''' is '''20''', in '''base 4''' is '''12'''. There is no representation where the digits are the same.\n:* '''7''' ''is'' Brazilian; '''7''' in '''base 2''' is '''111'''. There is at least one representation where the digits are all the same.\n:* '''8''' ''is'' Brazilian; '''8''' in '''base 3''' is '''22'''. There is at least one representation where the digits are all the same.\n:* ''and so on...''\n\n\nAll even integers '''2P >= 8''' are Brazilian because '''2P = 2(P-1) + 2''', which is '''22''' in '''base P-1''' when '''P-1 > 2'''. That becomes true when '''P >= 4'''.\nMore common: for all all integers '''R''' and '''S''', where '''R > 1''' and also '''S-1 > R''', then '''R*S''' is Brazilian because '''R*S = R(S-1) + R''', which is '''RR''' in '''base S-1'''\nThe only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3. \nAll prime integers, that are brazilian, can only have the digit '''1'''. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of '''111''' to base Integer(sqrt(prime number)). Must be an odd count of '''1''' to stay odd like primes > 2\n\n;Task:\n\nWrite a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page;\n\n:* the first '''20''' Brazilian numbers;\n:* the first '''20 odd''' Brazilian numbers;\n:* the first '''20 prime''' Brazilian numbers;\n\n\n;See also:\n\n:* '''OEIS:A125134 - Brazilian numbers'''\n:* '''OEIS:A257521 - Odd Brazilian numbers'''\n:* '''OEIS:A085104 - Prime Brazilian numbers'''\n\n", "solution": "'''Brazilian numbers'''\n\nfrom itertools import count, islice\n\n\n# isBrazil :: Int -> Bool\ndef isBrazil(n):\n '''True if n is a Brazilian number,\n in the sense of OEIS:A125134.\n '''\n return 7 <= n and (\n 0 == n % 2 or any(\n map(monoDigit(n), range(2, n - 1))\n )\n )\n\n\n# monoDigit :: Int -> Int -> Bool\ndef monoDigit(n):\n '''True if all the digits of n,\n in the given base, are the same.\n '''\n def go(base):\n def g(b, n):\n (q, d) = divmod(n, b)\n\n def p(qr):\n return d != qr[1] or 0 == qr[0]\n\n def f(qr):\n return divmod(qr[0], b)\n return d == until(p)(f)(\n (q, d)\n )[1]\n return g(base, n)\n return go\n\n\n# -------------------------- TEST --------------------------\n# main :: IO ()\ndef main():\n '''First 20 members each of:\n OEIS:A125134\n OEIS:A257521\n OEIS:A085104\n '''\n for kxs in ([\n (' ', count(1)),\n (' odd ', count(1, 2)),\n (' prime ', primes())\n ]):\n print(\n 'First 20' + kxs[0] + 'Brazilians:\\n' +\n showList(take(20)(filter(isBrazil, kxs[1]))) + '\\n'\n )\n\n\n# ------------------- GENERIC FUNCTIONS --------------------\n\n# primes :: [Int]\ndef primes():\n ''' Non finite sequence of prime numbers.\n '''\n n = 2\n dct = {}\n while True:\n if n in dct:\n for p in dct[n]:\n dct.setdefault(n + p, []).append(p)\n del dct[n]\n else:\n yield n\n dct[n * n] = [n]\n n = 1 + 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\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 def go(xs):\n return (\n xs[0:n]\n if isinstance(xs, (list, tuple))\n else list(islice(xs, n))\n )\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": "Break OO privacy", "language": "C++", "task": "Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. \nThe intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism. \nThe intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.\n\nNote that cheating on your type system is almost universally regarded \nas unidiomatic at best, and poor programming practice at worst. \nNonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.\n", "solution": "#include \n\nclass CWidget; // Forward-declare that we have a class named CWidget.\n\nclass CFactory\n{\n friend class CWidget;\nprivate:\n unsigned int m_uiCount;\npublic:\n CFactory();\n ~CFactory();\n CWidget* GetWidget();\n};\n\nclass CWidget\n{\nprivate:\n CFactory& m_parent;\n\nprivate:\n CWidget(); // Disallow the default constructor.\n CWidget(const CWidget&); // Disallow the copy constructor\n CWidget& operator=(const CWidget&); // Disallow the assignment operator.\npublic:\n CWidget(CFactory& parent);\n ~CWidget();\n};\n\n// CFactory constructors and destructors. Very simple things.\nCFactory::CFactory() : m_uiCount(0) {}\nCFactory::~CFactory() {}\n\n// CFactory method which creates CWidgets.\nCWidget* CFactory::GetWidget()\n{\n // Create a new CWidget, tell it we're its parent.\n return new CWidget(*this);\n}\n\n// CWidget constructor\nCWidget::CWidget(CFactory& parent) : m_parent(parent)\n{\n ++m_parent.m_uiCount;\n\n std::cout << \"Widget spawning. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nCWidget::~CWidget()\n{\n --m_parent.m_uiCount;\n\n std::cout << \"Widget dieing. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nint main()\n{\n CFactory factory;\n\n CWidget* pWidget1 = factory.GetWidget();\n CWidget* pWidget2 = factory.GetWidget();\n delete pWidget1;\n\n CWidget* pWidget3 = factory.GetWidget();\n delete pWidget3;\n delete pWidget2;\n}"} -{"title": "Break OO privacy", "language": "Python", "task": "Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. \nThe intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism. \nThe intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.\n\nNote that cheating on your type system is almost universally regarded \nas unidiomatic at best, and poor programming practice at worst. \nNonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.\n", "solution": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n File \"\", line 1, in \n mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>> "} -{"title": "Brilliant numbers", "language": "Python", "task": "'''Brilliant numbers''' are a subset of semiprime numbers. Specifically, they are numbers that are the product of exactly two prime numbers '''that both have the same number of digits when expressed in base 10'''.\n\n''Brilliant numbers are useful in cryptography and when testing prime factoring algorithms.''\n \n\n\n;E.G.\n* '''3 x 3''' (9) is a brilliant number. \n* '''2 x 7''' (14) is a brilliant number.\n* '''113 x 691''' (78083) is a brilliant number.\n* '''2 x 31''' (62) is semiprime, but is '''not''' a brilliant number (different number of digits in the two factors).\n\n\n\n;Task\n* Find and display the first 100 brilliant numbers.\n* For the orders of magnitude 1 through 6, find and show the first brilliant number greater than or equal to the order of magnitude, and, its position in the series (or the count of brilliant numbers up to that point).\n\n\n;Stretch\n* Continue for larger orders of magnitude.\n\n\n;See also\n;* Numbers Aplenty - Brilliant numbers\n;* OEIS:A078972 - Brilliant numbers: semiprimes whose prime factors have the same number of decimal digits\n", "solution": "from primesieve.numpy import primes\nfrom math import isqrt\nimport numpy as np\n\nmax_order = 9\nblocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)]\n\ndef smallest_brilliant(lb):\n pos = 1\n root = isqrt(lb)\n\n for blk in blocks:\n n = len(blk)\n if blk[-1]*blk[-1] < lb:\n pos += n*(n + 1)//2\n continue\n\n i = np.searchsorted(blk, root, 'left')\n i += blk[i]*blk[i] < lb\n\n if not i:\n return blk[0]*blk[0], pos\n\n p = blk[:i + 1]\n q = (lb - 1)//p\n idx = np.searchsorted(blk, q, 'right')\n\n sel = idx < n\n p, idx = p[sel], idx[sel]\n q = blk[idx]\n\n sel = q >= p\n p, q, idx = p[sel], q[sel], idx[sel]\n\n pos += np.sum(idx - np.arange(len(idx)))\n return np.min(p*q), pos\n\nres = []\np = 0\nfor i in range(100):\n p, _ = smallest_brilliant(p + 1)\n res.append(p)\n\nprint(f'first 100 are {res}')\n\nfor i in range(max_order*2):\n thresh = 10**i\n p, pos = smallest_brilliant(thresh)\n print(f'Above 10^{i:2d}: {p:20d} at #{pos}')"} -{"title": "Burrows\u2013Wheeler transform", "language": "C++ from C#", "task": "{{Wikipedia|Burrows-Wheeler_transform}}\n\n\nThe Burrows-Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters. \n\nThis is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding. \n\nMore importantly, the transformation is reversible, without needing to store any additional data. \n\nThe BWT is thus a \"free\" method of improving the efficiency of text compression algorithms, costing only some extra computation.\n\n\nSource: Burrows-Wheeler transform\n\n", "solution": "#include \n#include \n#include \n\nconst int STX = 0x02;\nconst int ETX = 0x03;\n\nvoid rotate(std::string &a) {\n char t = a[a.length() - 1];\n for (int i = a.length() - 1; i > 0; i--) {\n a[i] = a[i - 1];\n }\n a[0] = t;\n}\n\nstd::string bwt(const std::string &s) {\n for (char c : s) {\n if (c == STX || c == ETX) {\n throw std::runtime_error(\"Input can't contain STX or ETX\");\n }\n }\n\n std::string ss;\n ss += STX;\n ss += s;\n ss += ETX;\n\n std::vector table;\n for (size_t i = 0; i < ss.length(); i++) {\n table.push_back(ss);\n rotate(ss);\n }\n //table.sort();\n std::sort(table.begin(), table.end());\n\n std::string out;\n for (auto &s : table) {\n out += s[s.length() - 1];\n }\n return out;\n}\n\nstd::string ibwt(const std::string &r) {\n int len = r.length();\n std::vector table(len);\n for (int i = 0; i < len; i++) {\n for (int j = 0; j < len; j++) {\n table[j] = r[j] + table[j];\n }\n std::sort(table.begin(), table.end());\n }\n for (auto &row : table) {\n if (row[row.length() - 1] == ETX) {\n return row.substr(1, row.length() - 2);\n }\n }\n return {};\n}\n\nstd::string makePrintable(const std::string &s) {\n auto ls = s;\n for (auto &c : ls) {\n if (c == STX) {\n c = '^';\n } else if (c == ETX) {\n c = '|';\n }\n }\n return ls;\n}\n\nint main() {\n auto tests = {\n \"banana\",\n \"appellee\",\n \"dogwood\",\n \"TO BE OR NOT TO BE OR WANT TO BE OR NOT?\",\n \"SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES\",\n \"\\u0002ABC\\u0003\"\n };\n\n for (auto &test : tests) {\n std::cout << makePrintable(test) << \"\\n\";\n std::cout << \" --> \";\n\n std::string t;\n try {\n t = bwt(test);\n std::cout << makePrintable(t) << \"\\n\";\n } catch (std::runtime_error &e) {\n std::cout << \"Error \" << e.what() << \"\\n\";\n }\n\n std::string r = ibwt(t);\n std::cout << \" --> \" << r << \"\\n\\n\";\n }\n\n return 0;\n}"} -{"title": "Burrows\u2013Wheeler transform", "language": "Python", "task": "{{Wikipedia|Burrows-Wheeler_transform}}\n\n\nThe Burrows-Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters. \n\nThis is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding. \n\nMore importantly, the transformation is reversible, without needing to store any additional data. \n\nThe BWT is thus a \"free\" method of improving the efficiency of text compression algorithms, costing only some extra computation.\n\n\nSource: Burrows-Wheeler transform\n\n", "solution": "def bwt(s):\n \"\"\"Apply Burrows-Wheeler transform to input string.\"\"\"\n assert \"\\002\" not in s and \"\\003\" not in s, \"Input string cannot contain STX and ETX characters\"\n s = \"\\002\" + s + \"\\003\" # Add start and end of text marker\n table = sorted(s[i:] + s[:i] for i in range(len(s))) # Table of rotations of string\n last_column = [row[-1:] for row in table] # Last characters of each row\n return \"\".join(last_column) # Convert list of characters into string\n\n\ndef ibwt(r):\n \"\"\"Apply inverse Burrows-Wheeler transform.\"\"\"\n table = [\"\"] * len(r) # Make empty table\n for i in range(len(r)):\n table = sorted(r[i] + table[i] for i in range(len(r))) # Add a column of r\n s = [row for row in table if row.endswith(\"\\003\")][0] # Find the correct row (ending in ETX)\n return s.rstrip(\"\\003\").strip(\"\\002\") # Get rid of start and end markers\n"} -{"title": "CSV data manipulation", "language": "C", "task": "CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. \n\nThe CSV format is flexible but somewhat ill-defined. \n\nFor present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.\n\n\n;Task:\nRead a CSV file, change some values and save the changes back to a file.\n\nFor this task we will use the following CSV file:\n\n C1,C2,C3,C4,C5\n 1,5,9,13,17\n 2,6,10,14,18\n 3,7,11,15,19\n 4,8,12,16,20\n\nSuggestions\n\n Show how to add a column, headed 'SUM', of the sums of the rows.\n If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.\n\n\n", "solution": "#define TITLE \"CSV data manipulation\"\n#define URL \"http://rosettacode.org/wiki/CSV_data_manipulation\"\n\n#define _GNU_SOURCE\n#define bool int\n#include \n#include /* malloc...*/\n#include /* strtok...*/\n#include \n#include \n\n\n/**\n * How to read a CSV file ?\n */\n\n\ntypedef struct {\n\tchar * delim;\n\tunsigned int rows;\n\tunsigned int cols;\n\tchar ** table;\n} CSV;\n\n\n/** \n * Utility function to trim whitespaces from left & right of a string\n */\nint trim(char ** str) {\n\tint trimmed;\n\tint n;\n\tint len;\n\t\n\tlen = strlen(*str);\n\tn = len - 1;\n\t/* from right */\n\twhile((n>=0) && isspace((*str)[n])) {\n\t\t(*str)[n] = '\\0'; \n\t\ttrimmed += 1;\n\t\tn--;\n\t}\n\n\t/* from left */\n\tn = 0;\n\twhile((n < len) && (isspace((*str)[0]))) {\n\t\t(*str)[0] = '\\0'; \n\t\t*str = (*str)+1;\n\t\ttrimmed += 1;\n\t\tn++;\n\t}\n\treturn trimmed;\n}\n\n\n/** \n * De-allocate csv structure \n */\nint csv_destroy(CSV * csv) {\n\tif (csv == NULL) { return 0; }\n\tif (csv->table != NULL) { free(csv->table); }\n\tif (csv->delim != NULL) { free(csv->delim); }\n\tfree(csv);\n\treturn 0;\n}\n\n\n/**\n * Allocate memory for a CSV structure \n */\nCSV * csv_create(unsigned int cols, unsigned int rows) {\n\tCSV * csv;\n\t\n\tcsv = malloc(sizeof(CSV));\n\tcsv->rows = rows;\n\tcsv->cols = cols;\n\tcsv->delim = strdup(\",\");\n\n\tcsv->table = malloc(sizeof(char *) * cols * rows);\n\tif (csv->table == NULL) { goto error; }\n\n\tmemset(csv->table, 0, sizeof(char *) * cols * rows);\n\n\treturn csv;\n\nerror:\n\tcsv_destroy(csv);\n\treturn NULL;\n}\n\n\n/**\n * Get value in CSV table at COL, ROW\n */\nchar * csv_get(CSV * csv, unsigned int col, unsigned int row) {\n\tunsigned int idx;\n\tidx = col + (row * csv->cols);\n\treturn csv->table[idx];\n}\n\n\n/**\n * Set value in CSV table at COL, ROW\n */\nint csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) {\n\tunsigned int idx;\n\tidx = col + (row * csv->cols);\n\tcsv->table[idx] = value;\n\treturn 0;\n}\n\nvoid csv_display(CSV * csv) {\n\tint row, col;\n\tchar * content;\n\tif ((csv->rows == 0) || (csv->cols==0)) {\n\t\tprintf(\"[Empty table]\\n\");\n\t\treturn ;\n\t}\n\n\tprintf(\"\\n[Table cols=%d rows=%d]\\n\", csv->cols, csv->rows);\n\tfor (row=0; rowrows; row++) {\n\t\tprintf(\"[|\");\n\t\tfor (col=0; colcols; col++) {\n\t\t\tcontent = csv_get(csv, col, row);\n printf(\"%s\\t|\", content);\n\t\t}\n printf(\"]\\n\");\n\t}\n\tprintf(\"\\n\");\n}\n\n/**\n * Resize CSV table\n */\nint csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) {\n\tunsigned int cur_col, \n\t\t\t\t cur_row, \n\t\t\t\t max_cols,\n\t\t\t\t max_rows;\n\tCSV * new_csv;\n\tchar * content;\n\tbool in_old, in_new;\n\n\t/* Build a new (fake) csv */\n\tnew_csv = csv_create(new_cols, new_rows);\n\tif (new_csv == NULL) { goto error; }\n\n\tnew_csv->rows = new_rows;\n\tnew_csv->cols = new_cols;\n\n\n\tmax_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols;\n\tmax_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows;\n\n\tfor (cur_col=0; cur_colcols) && (cur_row < old_csv->rows);\n\t\t\tin_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows);\n\n\t\t\tif (in_old && in_new) {\n\t\t\t\t/* re-link data */\n\t\t\t\tcontent = csv_get(old_csv, cur_col, cur_row);\n\t\t\t\tcsv_set(new_csv, cur_col, cur_row, content);\n\t\t\t} else if (in_old) {\n\t\t\t\t/* destroy data */\n\t\t\t\tcontent = csv_get(old_csv, cur_col, cur_row);\n\t\t\t\tfree(content);\n\t\t\t} else { /* skip */ }\n\t\t}\n\t}\n\t/* on rows */\t\t\n\tfree(old_csv->table);\n\told_csv->rows = new_rows;\n\told_csv->cols = new_cols;\n\told_csv->table = new_csv->table;\n\tnew_csv->table = NULL;\n\tcsv_destroy(new_csv);\n\n\treturn 0;\n\nerror:\n\tprintf(\"Unable to resize CSV table: error %d - %s\\n\", errno, strerror(errno));\n\treturn -1;\n}\n\n\n/**\n * Open CSV file and load its content into provided CSV structure\n **/\nint csv_open(CSV * csv, char * filename) {\n\tFILE * fp;\n\tunsigned int m_rows;\n\tunsigned int m_cols, cols;\n\tchar line[2048];\n\tchar * lineptr;\n\tchar * token;\n\n\n\tfp = fopen(filename, \"r\");\n\tif (fp == NULL) { goto error; }\n\n\tm_rows = 0;\n\tm_cols = 0;\n\twhile(fgets(line, sizeof(line), fp) != NULL) {\n \t\tm_rows += 1;\n \t\tcols = 0;\n \t\tlineptr = line;\n \t\twhile ((token = strtok(lineptr, csv->delim)) != NULL) {\n \t\t\tlineptr = NULL;\n \t\t\ttrim(&token);\n cols += 1;\n \tif (cols > m_cols) { m_cols = cols; }\n csv_resize(csv, m_cols, m_rows);\n csv_set(csv, cols-1, m_rows-1, strdup(token));\n }\n\t}\n\n\tfclose(fp);\n\tcsv->rows = m_rows;\n\tcsv->cols = m_cols;\n\treturn 0;\n\nerror:\n\tfclose(fp);\n\tprintf(\"Unable to open %s for reading.\", filename);\n\treturn -1;\n}\n\n\n/**\n * Open CSV file and save CSV structure content into it\n **/\nint csv_save(CSV * csv, char * filename) {\n\tFILE * fp;\n\tint row, col;\n\tchar * content;\n\n\tfp = fopen(filename, \"w\");\n\tfor (row=0; rowrows; row++) {\n\t\tfor (col=0; colcols; col++) {\n\t\t\tcontent = csv_get(csv, col, row);\n fprintf(fp, \"%s%s\", content, \n \t\t((col == csv->cols-1) ? \"\" : csv->delim) );\n\t\t}\n fprintf(fp, \"\\n\");\n\t}\n\n\tfclose(fp);\n\treturn 0;\n}\n\n\n/** \n * Test\n */\nint main(int argc, char ** argv) {\n\tCSV * csv;\n\n\tprintf(\"%s\\n%s\\n\\n\",TITLE, URL);\n\n\tcsv = csv_create(0, 0);\n\tcsv_open(csv, \"fixtures/csv-data-manipulation.csv\");\n\tcsv_display(csv);\n\n\tcsv_set(csv, 0, 0, \"Column0\");\n\tcsv_set(csv, 1, 1, \"100\");\n\tcsv_set(csv, 2, 2, \"200\");\n\tcsv_set(csv, 3, 3, \"300\");\n\tcsv_set(csv, 4, 4, \"400\");\n\tcsv_display(csv);\n\n\tcsv_save(csv, \"tmp/csv-data-manipulation.result.csv\");\n\tcsv_destroy(csv);\n\n\treturn 0;\n}\n"} -{"title": "CSV data manipulation", "language": "C++", "task": "CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. \n\nThe CSV format is flexible but somewhat ill-defined. \n\nFor present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.\n\n\n;Task:\nRead a CSV file, change some values and save the changes back to a file.\n\nFor this task we will use the following CSV file:\n\n C1,C2,C3,C4,C5\n 1,5,9,13,17\n 2,6,10,14,18\n 3,7,11,15,19\n 4,8,12,16,20\n\nSuggestions\n\n Show how to add a column, headed 'SUM', of the sums of the rows.\n If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nclass CSV\n{\npublic:\n CSV(void) : m_nCols( 0 ), m_nRows( 0 )\n {}\n\n bool open( const char* filename, char delim = ',' )\n {\n std::ifstream file( filename );\n \n clear();\n if ( file.is_open() )\n {\n open( file, delim );\n return true;\n }\n\n return false;\n }\n\n void open( std::istream& istream, char delim = ',' )\n {\n std::string line;\n\n clear();\n while ( std::getline( istream, line ) )\n {\n unsigned int nCol = 0;\n std::istringstream lineStream(line);\n std::string cell;\n\n while( std::getline( lineStream, cell, delim ) )\n {\n m_oData[std::make_pair( nCol, m_nRows )] = trim( cell );\n nCol++;\n }\n m_nCols = std::max( m_nCols, nCol );\n m_nRows++;\n }\n }\n\n bool save( const char* pFile, char delim = ',' )\n {\n std::ofstream ofile( pFile );\n if ( ofile.is_open() )\n {\n save( ofile );\n return true;\n }\n return false;\n }\n\n void save( std::ostream& ostream, char delim = ',' )\n {\n for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ )\n {\n for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ )\n {\n ostream << trim( m_oData[std::make_pair( nCol, nRow )] );\n if ( (nCol+1) < m_nCols )\n {\n ostream << delim;\n }\n else\n {\n ostream << std::endl;\n }\n }\n }\n }\n\n void clear()\n {\n m_oData.clear();\n m_nRows = m_nCols = 0;\n }\n\n std::string& operator()( unsigned int nCol, unsigned int nRow )\n {\n m_nCols = std::max( m_nCols, nCol+1 );\n m_nRows = std::max( m_nRows, nRow+1 );\n return m_oData[std::make_pair(nCol, nRow)];\n }\n\n inline unsigned int GetRows() { return m_nRows; }\n inline unsigned int GetCols() { return m_nCols; }\n\nprivate:\n // trim string for empty spaces in begining and at the end\n inline std::string &trim(std::string &s) \n {\n \n s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun(std::isspace))));\n s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun(std::isspace))).base(), s.end());\n return s;\n }\n\nprivate:\n std::map, std::string> m_oData;\n\n unsigned int m_nCols;\n unsigned int m_nRows;\n};\n\n\nint main()\n{\n CSV oCSV;\n\n oCSV.open( \"test_in.csv\" );\n oCSV( 0, 0 ) = \"Column0\";\n oCSV( 1, 1 ) = \"100\";\n oCSV( 2, 2 ) = \"200\";\n oCSV( 3, 3 ) = \"300\";\n oCSV( 4, 4 ) = \"400\";\n oCSV.save( \"test_out.csv\" );\n return 0;\n}"} -{"title": "CSV data manipulation", "language": "JavaScript", "task": "CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. \n\nThe CSV format is flexible but somewhat ill-defined. \n\nFor present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.\n\n\n;Task:\nRead a CSV file, change some values and save the changes back to a file.\n\nFor this task we will use the following CSV file:\n\n C1,C2,C3,C4,C5\n 1,5,9,13,17\n 2,6,10,14,18\n 3,7,11,15,19\n 4,8,12,16,20\n\nSuggestions\n\n Show how to add a column, headed 'SUM', of the sums of the rows.\n If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.\n\n\n", "solution": "(function () {\n 'use strict';\n\n // splitRegex :: Regex -> String -> [String]\n function splitRegex(rgx, s) {\n return s.split(rgx);\n }\n\n // lines :: String -> [String]\n function lines(s) {\n return s.split(/[\\r\\n]/);\n }\n\n // unlines :: [String] -> String\n function unlines(xs) {\n return xs.join('\\n');\n }\n\n // macOS JavaScript for Automation version of readFile.\n // Other JS contexts will need a different definition of this function,\n // and some may have no access to the local file system at all.\n\n // readFile :: FilePath -> maybe String\n function readFile(strPath) {\n var error = $(),\n str = ObjC.unwrap(\n $.NSString.stringWithContentsOfFileEncodingError(\n $(strPath)\n .stringByStandardizingPath,\n $.NSUTF8StringEncoding,\n error\n )\n );\n return error.code ? error.localizedDescription : str;\n }\n\n // macOS JavaScript for Automation version of writeFile.\n // Other JS contexts will need a different definition of this function,\n // and some may have no access to the local file system at all.\n\n // writeFile :: FilePath -> String -> IO ()\n function writeFile(strPath, strText) {\n $.NSString.alloc.initWithUTF8String(strText)\n .writeToFileAtomicallyEncodingError(\n $(strPath)\n .stringByStandardizingPath, false,\n $.NSUTF8StringEncoding, null\n );\n }\n\n // EXAMPLE - appending a SUM column\n\n var delimCSV = /,\\s*/g;\n\n var strSummed = unlines(\n lines(readFile('~/csvSample.txt'))\n .map(function (x, i) {\n var xs = x ? splitRegex(delimCSV, x) : [];\n\n return (xs.length ? xs.concat(\n // 'SUM' appended to first line, others summed.\n i > 0 ? xs.reduce(\n function (a, b) {\n return a + parseInt(b, 10);\n }, 0\n ).toString() : 'SUM'\n ) : []).join(',');\n })\n );\n\n return (\n writeFile('~/csvSampleSummed.txt', strSummed),\n strSummed\n );\n\n})();"} -{"title": "CSV data manipulation", "language": "Python", "task": "CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. \n\nThe CSV format is flexible but somewhat ill-defined. \n\nFor present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.\n\n\n;Task:\nRead a CSV file, change some values and save the changes back to a file.\n\nFor this task we will use the following CSV file:\n\n C1,C2,C3,C4,C5\n 1,5,9,13,17\n 2,6,10,14,18\n 3,7,11,15,19\n 4,8,12,16,20\n\nSuggestions\n\n Show how to add a column, headed 'SUM', of the sums of the rows.\n If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.\n\n\n", "solution": "import fileinput\n\nchangerow, changecolumn, changevalue = 2, 4, '\"Spam\"'\n\nwith fileinput.input('csv_data_manipulation.csv', inplace=True) as f:\n for line in f:\n if fileinput.filelineno() == changerow:\n fields = line.rstrip().split(',')\n fields[changecolumn-1] = changevalue\n line = ','.join(fields) + '\\n'\n print(line, end='')"} -{"title": "CSV to HTML translation", "language": "C", "task": "Consider a simplified CSV format where all rows are separated by a newline \nand all columns are separated by commas. \n\nNo commas are allowed as field data, but the data may contain \nother characters and character sequences that would \nnormally be ''escaped'' when converted to HTML\n\n\n;Task:\nCreate a function that takes a string representation of the CSV data\nand returns a text string of an HTML table representing the CSV data. \n\nUse the following data as the CSV text to convert, and show your output.\n: Character,Speech\n: The multitude,The messiah! Show us the messiah!\n: Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!\n: The multitude,Who are you?\n: Brians mother,I'm his mother; that's who!\n: The multitude,Behold his mother! Behold his mother!\n\n\n;Extra credit:\n''Optionally'' allow special formatting for the first row of the table as if it is the tables header row \n(via preferably; CSS if you must).\n\n", "solution": "#include \n\nconst char *input = \n\t\"Character,Speech\\n\"\n\t\"The multitude,The messiah! Show us the messiah!\\n\"\n\t\"Brians mother,Now you listen here! He's not the messiah; \"\n\t\t\"he's a very naughty boy! Now go away!\\n\"\n\t\"The multitude,Who are you?\\n\"\n\t\"Brians mother,I'm his mother; that's who!\\n\"\n\t\"The multitude,Behold his mother! Behold his mother!\";\n\nint main()\n{\n\tconst char *s;\n\tprintf(\"\\n\\n\\n
\");\n\tfor (s = input; *s; s++) {\n\t\tswitch(*s) {\n\t\tcase '\\n': printf(\"
\"); break;\n\t\tcase ',': printf(\"\"); break;\n\t\tcase '<': printf(\"<\"); break;\n\t\tcase '>': printf(\">\"); break;\n\t\tcase '&': printf(\"&\"); break;\n\t\tdefault: putchar(*s);\n\t\t}\n\t}\n\tputs(\"
\");\n\n\treturn 0;\n}"} -{"title": "CSV to HTML translation", "language": "C++", "task": "Consider a simplified CSV format where all rows are separated by a newline \nand all columns are separated by commas. \n\nNo commas are allowed as field data, but the data may contain \nother characters and character sequences that would \nnormally be ''escaped'' when converted to HTML\n\n\n;Task:\nCreate a function that takes a string representation of the CSV data\nand returns a text string of an HTML table representing the CSV data. \n\nUse the following data as the CSV text to convert, and show your output.\n: Character,Speech\n: The multitude,The messiah! Show us the messiah!\n: Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!\n: The multitude,Who are you?\n: Brians mother,I'm his mother; that's who!\n: The multitude,Behold his mother! Behold his mother!\n\n\n;Extra credit:\n''Optionally'' allow special formatting for the first row of the table as if it is the tables header row \n(via preferably; CSS if you must).\n\n", "solution": "#include \n#include \n#include \n\nstd::string csvToHTML( const std::string & ) ;\n\nint main( ) {\n std::string text = \"Character,Speech\\n\" \n \"The multitude,The messiah! Show us the messiah!\\n\" \n\t\t\t \"Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!\\n\" \n\t \"The multitude,Who are you?\\n\" \n\t\t \"Brians mother,I'm his mother; that's who!\\n\" \n\t\t \"The multitude,Behold his mother! Behold his mother!\\n\" ;\n std::cout << csvToHTML( text ) ;\n return 0 ;\n}\n\nstd::string csvToHTML( const std::string & csvtext ) {\n //the order of the regexes and the replacements is decisive!\n std::string regexes[ 5 ] = { \"<\" , \">\" , \"^(.+?)\\\\b\" , \",\" , \"\\n\" } ;\n const char* replacements [ 5 ] = { \"<\" , \">\" , \" $1\" , \"\", \"\\n\" } ; \n boost::regex e1( regexes[ 0 ] ) ; \n std::string tabletext = boost::regex_replace( csvtext , e1 ,\n replacements[ 0 ] , boost::match_default | boost::format_all ) ;\n for ( int i = 1 ; i < 5 ; i++ ) {\n e1.assign( regexes[ i ] ) ;\n tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;\n }\n tabletext = std::string( \"\\n\" ) + tabletext ;\n tabletext.append( \"
\\n\" ) ;\n return tabletext ;\n}"} -{"title": "CSV to HTML translation", "language": "JavaScript", "task": "Consider a simplified CSV format where all rows are separated by a newline \nand all columns are separated by commas. \n\nNo commas are allowed as field data, but the data may contain \nother characters and character sequences that would \nnormally be ''escaped'' when converted to HTML\n\n\n;Task:\nCreate a function that takes a string representation of the CSV data\nand returns a text string of an HTML table representing the CSV data. \n\nUse the following data as the CSV text to convert, and show your output.\n: Character,Speech\n: The multitude,The messiah! Show us the messiah!\n: Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!\n: The multitude,Who are you?\n: Brians mother,I'm his mother; that's who!\n: The multitude,Behold his mother! Behold his mother!\n\n\n;Extra credit:\n''Optionally'' allow special formatting for the first row of the table as if it is the tables header row \n(via preferably; CSS if you must).\n\n", "solution": "var csv = \"Character,Speech\\n\" +\n\t \"The multitude,The messiah! Show us the messiah!\\n\" +\n\t \"Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!\\n\" +\n\t \"The multitude,Who are you?\\n\" +\n\t \"Brians mother,I'm his mother; that's who!\\n\" +\n\t \"The multitude,Behold his mother! Behold his mother!\";\n\nvar lines = csv.replace(/&/g, '&')\n .replace(//g, '>')\n .replace(/\"/g, '"')\n .split(/[\\n\\r]/)\n .map(function(line) { return line.split(',')})\n .map(function(row) {return '\\t\\t' + row[0] + '' + row[1] + '';});\n\nconsole.log('\\n\\t\\n' + lines[0] +\n '\\n\\t\\n\\t\\n' + lines.slice(1).join('\\n') +\n '\\t\\n
');\n\n"} -{"title": "CSV to HTML translation", "language": "Python", "task": "Consider a simplified CSV format where all rows are separated by a newline \nand all columns are separated by commas. \n\nNo commas are allowed as field data, but the data may contain \nother characters and character sequences that would \nnormally be ''escaped'' when converted to HTML\n\n\n;Task:\nCreate a function that takes a string representation of the CSV data\nand returns a text string of an HTML table representing the CSV data. \n\nUse the following data as the CSV text to convert, and show your output.\n: Character,Speech\n: The multitude,The messiah! Show us the messiah!\n: Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!\n: The multitude,Who are you?\n: Brians mother,I'm his mother; that's who!\n: The multitude,Behold his mother! Behold his mother!\n\n\n;Extra credit:\n''Optionally'' allow special formatting for the first row of the table as if it is the tables header row \n(via preferably; CSS if you must).\n\n", "solution": "from csv import DictReader\nfrom xml.etree import ElementTree as ET\n\ndef csv2html_robust(txt, header=True, attr=None):\n # Use DictReader because, despite what the docs say, reader() doesn't\n # return an object with .fieldnames\n # (DictReader expects an iterable that returns lines, so split on \\n)\n reader = DictReader(txt.split('\\n'))\n\n table = ET.Element(\"TABLE\", **attr.get('TABLE', {}))\n thead_tr = ET.SubElement(\n ET.SubElement(table, \"THEAD\", **attr.get('THEAD', {})),\n \"TR\")\n tbody = ET.SubElement(table, \"TBODY\", **attr.get('TBODY', {}))\n\n if header:\n for name in reader.fieldnames:\n ET.SubElement(thead_tr, \"TD\").text = name\n\n for row in reader:\n tr_elem = ET.SubElement(tbody, \"TR\", **attr.get('TR', {}))\n\n # Use reader.fieldnames to query `row` in the correct order.\n # (`row` isn't an OrderedDict prior to Python 3.6)\n for field in reader.fieldnames:\n td_elem = ET.SubElement(tr_elem, \"TD\", **attr.get('TD', {}))\n td_elem.text = row[field]\n\n return ET.tostring(table, method='html')\n\nhtmltxt = csv2html_robust(csvtxt, True, {\n 'TABLE': {'border': \"1\", 'summary': \"csv2html extra program output\"},\n 'THEAD': {'bgcolor': \"yellow\"},\n 'TBODY': {'bgcolor': \"orange\"}\n})\n\nprint(htmltxt.decode('utf8'))"} -{"title": "Calculating the value of e", "language": "C", "task": "Calculate the value of ''e''.\n\n\n(''e'' is also known as ''Euler's number'' and ''Napier's constant''.)\n\n\nSee details: Calculating the value of e\n\n", "solution": "#include \n#include \n\nint main(void)\n{\n double e;\n\n puts(\"The double precision in C give about 15 significant digits.\\n\"\n \"Values below are presented with 16 digits after the decimal point.\\n\");\n\n // The most direct way to compute Euler constant.\n //\n e = exp(1);\n printf(\"Euler constant e = %.16lf\\n\", e);\n\n // The fast and independed method: e = lim (1 + 1/n)**n\n //\n e = 1.0 + 0x1p-26;\n for (int i = 0; i < 26; i++)\n e *= e;\n printf(\"Euler constant e = %.16lf\\n\", e);\n\n // Taylor expansion e = 1 + 1/1 + 1/2 + 1/2/3 + 1/2/3/4 + 1/2/3/4/5 + ...\n // Actually Kahan summation may improve the accuracy, but is not necessary.\n //\n const int N = 1000;\n double a[1000];\n a[0] = 1.0;\n for (int i = 1; i < N; i++)\n {\n a[i] = a[i-1] / i;\n }\n e = 1.;\n for (int i = N - 1; i > 0; i--)\n e += a[i];\n printf(\"Euler constant e = %.16lf\\n\", e);\n\n return 0;\n}"} -{"title": "Calculating the value of e", "language": "C++ from C", "task": "Calculate the value of ''e''.\n\n\n(''e'' is also known as ''Euler's number'' and ''Napier's constant''.)\n\n\nSee details: Calculating the value of e\n\n", "solution": "#include \n#include \n#include \n\nusing namespace std;\n\nint main() {\n const double EPSILON = 1.0e-15;\n unsigned long long fact = 1;\n double e = 2.0, e0;\n int n = 2;\n do {\n e0 = e;\n fact *= n++;\n e += 1.0 / fact;\n }\n while (fabs(e - e0) >= EPSILON);\n cout << \"e = \" << setprecision(16) << e << endl;\n return 0;\n}"} -{"title": "Calculating the value of e", "language": "Python", "task": "Calculate the value of ''e''.\n\n\n(''e'' is also known as ''Euler's number'' and ''Napier's constant''.)\n\n\nSee details: Calculating the value of e\n\n", "solution": "import math\n#Implementation of Brother's formula\ne0 = 0\ne = 2\nn = 0\nfact = 1\nwhile(e-e0 > 1e-15):\n\te0 = e\n\tn += 1\n\tfact *= 2*n*(2*n+1)\n\te += (2.*n+2)/fact\n\nprint \"Computed e = \"+str(e)\nprint \"Real e = \"+str(math.e)\nprint \"Error = \"+str(math.e-e)\nprint \"Number of iterations = \"+str(n)"} -{"title": "Calculating the value of e", "language": "Python 3.7", "task": "Calculate the value of ''e''.\n\n\n(''e'' is also known as ''Euler's number'' and ''Napier's constant''.)\n\n\nSee details: Calculating the value of e\n\n", "solution": "'''Calculating an approximate value for e'''\n\nfrom itertools import (accumulate, chain)\nfrom functools import (reduce)\nfrom operator import (mul)\n\n\n# eApprox :: () -> Float\ndef eApprox():\n '''Approximation to the value of e.'''\n return reduce(\n lambda a, x: a + 1 / x,\n scanl(mul)(1)(\n range(1, 18)\n ),\n 0\n )\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Test'''\n\n print(\n eApprox()\n )\n\n\n# GENERIC ABSTRACTIONS ------------------------------------\n\n# scanl is like reduce, but returns a succession of\n# intermediate values, building from the left.\n# See, for example, under `scan` in the Lists chapter of\n# the language-independent Bird & Wadler 1988.\n\n# scanl :: (b -> a -> b) -> b -> [a] -> [b]\ndef scanl(f):\n '''scanl is like reduce, but returns a succession of\n intermediate values, building from the left.'''\n return lambda a: lambda xs: (\n accumulate(chain([a], xs), f)\n )\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} -{"title": "Calkin-Wilf sequence", "language": "Python", "task": "The '''Calkin-Wilf sequence''' contains every nonnegative rational number exactly once. \n\nIt can be calculated recursively as follows:\n\n {{math|a1}} = {{math|1}} \n {{math|an+1}} = {{math|1/(2an+1-an)}} for n > 1 \n\n\n;Task part 1:\n* Show on this page terms 1 through 20 of the Calkin-Wilf sequence.\n\nTo avoid floating point error, you may want to use a rational number data type.\n\n\nIt is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction. \nIt only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this:\n\n {{math|[a0; a1, a2, ..., an]}} = {{math|[a0; a1, a2 ,..., an-1, 1]}} \n\n\n;Example:\nThe fraction '''9/4''' has odd continued fraction representation {{math|2; 3, 1}}, giving a binary representation of '''100011''', \nwhich means '''9/4''' appears as the '''35th''' term of the sequence.\n\n\n;Task part 2:\n* Find the position of the number '''83116''''''/''''''51639''' in the Calkin-Wilf sequence.\n\n\n;See also:\n* Wikipedia entry: Calkin-Wilf tree\n* [[Continued fraction]]\n* [[Continued fraction/Arithmetic/Construct from rational number]]\n\n", "solution": "from fractions import Fraction\nfrom math import floor\nfrom itertools import islice, groupby\n\n\ndef cw():\n a = Fraction(1)\n while True:\n yield a\n a = 1 / (2 * floor(a) + 1 - a)\n\ndef r2cf(rational):\n num, den = rational.numerator, rational.denominator\n while den:\n num, (digit, den) = den, divmod(num, den)\n yield digit\n\ndef get_term_num(rational):\n ans, dig, pwr = 0, 1, 0\n for n in r2cf(rational):\n for _ in range(n):\n ans |= dig << pwr\n pwr += 1\n dig ^= 1\n return ans\n\n \nif __name__ == '__main__':\n print('TERMS 1..20: ', ', '.join(str(x) for x in islice(cw(), 20)))\n x = Fraction(83116, 51639)\n print(f\"\\n{x} is the {get_term_num(x):_}'th term.\")"} -{"title": "Call a function", "language": "C", "task": "Demonstrate the different syntax and semantics provided for calling a function. \n\n\nThis may include:\n:* Calling a function that requires no arguments\n:* Calling a function with a fixed number of arguments\n:* Calling a function with optional arguments\n:* Calling a function with a variable number of arguments\n:* Calling a function with named arguments\n:* Using a function in statement context\n:* Using a function in first-class context within an expression\n:* Obtaining the return value of a function\n:* Distinguishing built-in functions and user-defined functions\n:* Distinguishing subroutines and functions\n;* Stating whether arguments are passed by value or by reference\n;* Is partial application possible and how\n\n\nThis task is ''not'' about defining functions.\n\n", "solution": "/* function with no argument */\nf();\n\n/* fix number of arguments */\ng(1, 2, 3);\n\n/* Optional arguments: err...\n Feel free to make sense of the following. I can't. */\nint op_arg();\nint main()\n{\n\top_arg(1);\n\top_arg(1, 2);\n\top_arg(1, 2, 3);\n\treturn 0;\n}\nint op_arg(int a, int b)\n{\n\tprintf(\"%d %d %d\\n\", a, b, (&b)[1]);\n\treturn a;\n} /* end of sensible code */\n\n/* Variadic function: how the args list is handled solely depends on the function */\nvoid h(int a, ...)\n{\n\tva_list ap;\n\tva_start(ap);\n\t...\n}\n/* call it as: (if you feed it something it doesn't expect, don't count on it working) */\nh(1, 2, 3, 4, \"abcd\", (void*)0);\n\n/* named arguments: this is only possible through some pre-processor abuse\n*/\nstruct v_args {\n int arg1;\n int arg2;\n char _sentinel;\n};\n\nvoid _v(struct v_args args)\n{\n printf(\"%d, %d\\n\", args.arg1, args.arg2);\n}\n\n#define v(...) _v((struct v_args){__VA_ARGS__})\n\nv(.arg2 = 5, .arg1 = 17); // prints \"17,5\"\n/* NOTE the above implementation gives us optional typesafe optional arguments as well (unspecified arguments are initialized to zero)*/\nv(.arg2=1); // prints \"0,1\"\nv(); // prints \"0,0\"\n\n/* as a first-class object (i.e. function pointer) */\nprintf(\"%p\", f); /* that's the f() above */\n\n/* return value */\ndouble a = asin(1);\n\n/* built-in functions: no such thing. Compiler may interally give special treatment\n to bread-and-butter functions such as memcpy(), but that's not a C built-in per se */\n\n/* subroutines: no such thing. You can goto places, but I doubt that counts. */\n\n/* Scalar values are passed by value by default. However, arrays are passed by reference. */\n/* Pointers *sort of* work like references, though. */"} -{"title": "Call a function", "language": "C++", "task": "Demonstrate the different syntax and semantics provided for calling a function. \n\n\nThis may include:\n:* Calling a function that requires no arguments\n:* Calling a function with a fixed number of arguments\n:* Calling a function with optional arguments\n:* Calling a function with a variable number of arguments\n:* Calling a function with named arguments\n:* Using a function in statement context\n:* Using a function in first-class context within an expression\n:* Obtaining the return value of a function\n:* Distinguishing built-in functions and user-defined functions\n:* Distinguishing subroutines and functions\n;* Stating whether arguments are passed by value or by reference\n;* Is partial application possible and how\n\n\nThis task is ''not'' about defining functions.\n\n", "solution": "#include \nusing namespace std;\n/* passing arguments by reference */\nvoid f(int &y) /* variable is now passed by reference */\n{\ny++;\n}\nint main()\n{\nint x = 0;\ncout<<\"x = \"<\n#include \n#include \n\ntypedef struct cidr_tag {\n uint32_t address;\n unsigned int mask_length;\n} cidr_t;\n\n// Convert a string in CIDR format to an IPv4 address and netmask,\n// if possible. Also performs CIDR canonicalization.\nbool cidr_parse(const char* str, cidr_t* cidr) {\n int a, b, c, d, m;\n if (sscanf(str, \"%d.%d.%d.%d/%d\", &a, &b, &c, &d, &m) != 5)\n return false;\n if (m < 1 || m > 32\n || a < 0 || a > UINT8_MAX\n || b < 0 || b > UINT8_MAX\n || c < 0 || c > UINT8_MAX\n || d < 0 || d > UINT8_MAX)\n return false;\n uint32_t mask = ~((1 << (32 - m)) - 1);\n uint32_t address = (a << 24) + (b << 16) + (c << 8) + d;\n address &= mask;\n cidr->address = address;\n cidr->mask_length = m;\n return true;\n}\n\n// Write a string in CIDR notation into the supplied buffer.\nvoid cidr_format(const cidr_t* cidr, char* str, size_t size) {\n uint32_t address = cidr->address;\n unsigned int d = address & UINT8_MAX;\n address >>= 8;\n unsigned int c = address & UINT8_MAX;\n address >>= 8;\n unsigned int b = address & UINT8_MAX;\n address >>= 8;\n unsigned int a = address & UINT8_MAX;\n snprintf(str, size, \"%u.%u.%u.%u/%u\", a, b, c, d,\n cidr->mask_length);\n}\n\nint main(int argc, char** argv) {\n const char* tests[] = {\n \"87.70.141.1/22\",\n \"36.18.154.103/12\",\n \"62.62.197.11/29\",\n \"67.137.119.181/4\",\n \"161.214.74.21/24\",\n \"184.232.176.184/18\"\n };\n for (int i = 0; i < sizeof(tests)/sizeof(tests[0]); ++i) {\n cidr_t cidr;\n if (cidr_parse(tests[i], &cidr)) {\n char out[32];\n cidr_format(&cidr, out, sizeof(out));\n printf(\"%-18s -> %s\\n\", tests[i], out);\n } else {\n fprintf(stderr, \"%s: invalid CIDR\\n\", tests[i]);\n }\n }\n return 0;\n}"} -{"title": "Canonicalize CIDR", "language": "C++", "task": "Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form. \n\nThat is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.\n\n\n;Example:\nGiven '''87.70.141.1/22''', your code should output '''87.70.140.0/22'''\n\n\n;Explanation:\nAn Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 digit is given in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the network portion of the address, while the rightmost (least-significant) bits determine the host portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion.\n\nIn general, CIDR blocks stand in for the entire set of IP addresses sharing the same network component, so it's common to see access control lists that specify individual IP addresses using /32 to indicate that only the one address is included. Software accepting this notation as input often expects it to be entered in canonical form, in which the host bits are all zeroes. But network admins sometimes skip this step and just enter the address of a specific host on the subnet with the network size, resulting in a non-canonical entry.\n\nThe example address, 87.70.141.1/22, represents binary 0101011101000110100011 / 0100000001, with the / indicating the network/host division. To canonicalize, clear all the bits to the right of the / and convert back to dotted decimal: 0101011101000110100011 / 0000000000 - 87.70.140.0.\n\n\n;More examples for testing\n\n 36.18.154.103/12 - 36.16.0.0/12\n 62.62.197.11/29 - 62.62.197.8/29\n 67.137.119.181/4 - 64.0.0.0/4\n 161.214.74.21/24 - 161.214.74.0/24\n 184.232.176.184/18 - 184.232.128.0/18\n\n\n", "solution": "#include \n#include \n#include \n#include \n\n// Class representing an IPv4 address + netmask length\nclass ipv4_cidr {\npublic:\n ipv4_cidr() {}\n ipv4_cidr(std::uint32_t address, unsigned int mask_length)\n : address_(address), mask_length_(mask_length) {}\n std::uint32_t address() const {\n return address_;\n }\n unsigned int mask_length() const {\n return mask_length_;\n }\n friend std::istream& operator>>(std::istream&, ipv4_cidr&);\nprivate:\n std::uint32_t address_ = 0;\n unsigned int mask_length_ = 0;\n};\n\n// Stream extraction operator, also performs canonicalization\nstd::istream& operator>>(std::istream& in, ipv4_cidr& cidr) {\n int a, b, c, d, m;\n char ch;\n if (!(in >> a >> ch) || a < 0 || a > UINT8_MAX || ch != '.'\n || !(in >> b >> ch) || b < 0 || b > UINT8_MAX || ch != '.'\n || !(in >> c >> ch) || c < 0 || c > UINT8_MAX || ch != '.'\n || !(in >> d >> ch) || d < 0 || d > UINT8_MAX || ch != '/'\n || !(in >> m) || m < 1 || m > 32) {\n in.setstate(std::ios_base::failbit);\n return in;\n }\n uint32_t mask = ~((1 << (32 - m)) - 1);\n uint32_t address = (a << 24) + (b << 16) + (c << 8) + d;\n address &= mask;\n cidr.address_ = address;\n cidr.mask_length_ = m;\n return in;\n}\n\n// Stream insertion operator\nstd::ostream& operator<<(std::ostream& out, const ipv4_cidr& cidr) {\n uint32_t address = cidr.address();\n unsigned int d = address & UINT8_MAX;\n address >>= 8;\n unsigned int c = address & UINT8_MAX;\n address >>= 8;\n unsigned int b = address & UINT8_MAX;\n address >>= 8;\n unsigned int a = address & UINT8_MAX;\n out << a << '.' << b << '.' << c << '.' << d << '/'\n << cidr.mask_length();\n return out;\n}\n\nint main(int argc, char** argv) {\n const char* tests[] = {\n \"87.70.141.1/22\",\n \"36.18.154.103/12\",\n \"62.62.197.11/29\",\n \"67.137.119.181/4\",\n \"161.214.74.21/24\",\n \"184.232.176.184/18\"\n };\n for (auto test : tests) {\n std::istringstream in(test);\n ipv4_cidr cidr;\n if (in >> cidr)\n std::cout << std::setw(18) << std::left << test << \" -> \"\n << cidr << '\\n';\n else\n std::cerr << test << \": invalid CIDR\\n\";\n }\n return 0;\n}"} -{"title": "Canonicalize CIDR", "language": "JavaScript", "task": "Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form. \n\nThat is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.\n\n\n;Example:\nGiven '''87.70.141.1/22''', your code should output '''87.70.140.0/22'''\n\n\n;Explanation:\nAn Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 digit is given in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the network portion of the address, while the rightmost (least-significant) bits determine the host portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion.\n\nIn general, CIDR blocks stand in for the entire set of IP addresses sharing the same network component, so it's common to see access control lists that specify individual IP addresses using /32 to indicate that only the one address is included. Software accepting this notation as input often expects it to be entered in canonical form, in which the host bits are all zeroes. But network admins sometimes skip this step and just enter the address of a specific host on the subnet with the network size, resulting in a non-canonical entry.\n\nThe example address, 87.70.141.1/22, represents binary 0101011101000110100011 / 0100000001, with the / indicating the network/host division. To canonicalize, clear all the bits to the right of the / and convert back to dotted decimal: 0101011101000110100011 / 0000000000 - 87.70.140.0.\n\n\n;More examples for testing\n\n 36.18.154.103/12 - 36.16.0.0/12\n 62.62.197.11/29 - 62.62.197.8/29\n 67.137.119.181/4 - 64.0.0.0/4\n 161.214.74.21/24 - 161.214.74.0/24\n 184.232.176.184/18 - 184.232.128.0/18\n\n\n", "solution": "const canonicalize = s => {\n\n // Prepare a DataView over a 16 Byte Array buffer.\n // Initialised to all zeros.\n const dv = new DataView(new ArrayBuffer(16));\n\n // Get the ip-address and cidr components\n const [ip, cidr] = s.split('/');\n\n // Make sure the cidr component is a usable int, and\n // default to 32 if it does not exist.\n const cidrInt = parseInt(cidr || 32, 10);\n\n // Populate the buffer with uint8 ip address components.\n // Use zero as the default for shorthand pool definitions.\n ip.split('.').forEach(\n (e, i) => dv.setUint8(i, parseInt(e || 0, 10))\n );\n\n // Grab the whole buffer as a uint32\n const ipAsInt = dv.getUint32(0);\n\n // Zero out the lower bits as per the CIDR number.\n const normIpInt = (ipAsInt >> 32 - cidrInt) << 32 - cidrInt;\n\n // Plonk it back into the buffer\n dv.setUint32(0, normIpInt);\n\n // Read each of the uint8 slots in the buffer and join them with a dot.\n const canonIp = [...'0123'].map((e, i) => dv.getUint8(i)).join('.');\n\n // Attach the cidr number to the back of the normalised IP address.\n return [canonIp, cidrInt].join('/');\n }\n\n const test = s => console.log(s, '->', canonicalize(s));\n [\n '255.255.255.255/10',\n '87.70.141.1/22',\n '36.18.154.103/12',\n '62.62.197.11/29',\n '67.137.119.181/4',\n '161.214.74.21/24',\n '184.232.176.184/18',\n '10.207.219.251/32',\n '10.207.219.251',\n '110.200.21/4',\n '10..55/8',\n '10.../8'\n ].forEach(test)"} -{"title": "Canonicalize CIDR", "language": "Python from Perl", "task": "Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form. \n\nThat is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.\n\n\n;Example:\nGiven '''87.70.141.1/22''', your code should output '''87.70.140.0/22'''\n\n\n;Explanation:\nAn Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 digit is given in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the network portion of the address, while the rightmost (least-significant) bits determine the host portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion.\n\nIn general, CIDR blocks stand in for the entire set of IP addresses sharing the same network component, so it's common to see access control lists that specify individual IP addresses using /32 to indicate that only the one address is included. Software accepting this notation as input often expects it to be entered in canonical form, in which the host bits are all zeroes. But network admins sometimes skip this step and just enter the address of a specific host on the subnet with the network size, resulting in a non-canonical entry.\n\nThe example address, 87.70.141.1/22, represents binary 0101011101000110100011 / 0100000001, with the / indicating the network/host division. To canonicalize, clear all the bits to the right of the / and convert back to dotted decimal: 0101011101000110100011 / 0000000000 - 87.70.140.0.\n\n\n;More examples for testing\n\n 36.18.154.103/12 - 36.16.0.0/12\n 62.62.197.11/29 - 62.62.197.8/29\n 67.137.119.181/4 - 64.0.0.0/4\n 161.214.74.21/24 - 161.214.74.0/24\n 184.232.176.184/18 - 184.232.128.0/18\n\n\n", "solution": "#!/usr/bin/env python\n# canonicalize a CIDR block specification:\n# make sure none of the host bits are set\n\nimport sys\nfrom socket import inet_aton, inet_ntoa\nfrom struct import pack, unpack\n\nargs = sys.argv[1:]\nif len(args) == 0:\n args = sys.stdin.readlines()\n\nfor cidr in args:\n # IP in dotted-decimal / bits in network part\n dotted, size_str = cidr.split('/')\n size = int(size_str)\n\n numeric = unpack('!I', inet_aton(dotted))[0] # IP as an integer\n binary = f'{numeric:#034b}' # then as a padded binary string\n prefix = binary[:size + 2] # just the network part\n # (34 and +2 are to account\n # for leading '0b')\n\n canon_binary = prefix + '0' * (32 - size) # replace host part with all zeroes\n canon_numeric = int(canon_binary, 2) # convert back to integer\n canon_dotted = inet_ntoa(pack('!I',\n (canon_numeric))) # and then to dotted-decimal\n print(f'{canon_dotted}/{size}') # output result"} -{"title": "Cantor set", "language": "C++ from D", "task": "Draw a Cantor set.\n\n\nSee details at this Wikipedia webpage: Cantor set\n\n", "solution": "#include \n\nconst int WIDTH = 81;\nconst int HEIGHT = 5;\n\nchar lines[WIDTH*HEIGHT];\n\nvoid cantor(int start, int len, int index) {\n\tint seg = len / 3;\n\tif (seg == 0) return;\n\tfor (int i = index; i < HEIGHT; i++) {\n\t\tfor (int j = start + seg; j < start + seg * 2; j++) {\n\t\t\tint pos = i * WIDTH + j;\n\t\t\tlines[pos] = ' ';\n\t\t}\n\t}\n\tcantor(start, seg, index + 1);\n\tcantor(start + 2 * seg, seg, index + 1);\n}\n\nint main() {\n\t// init\n\tfor (int i = 0; i < WIDTH*HEIGHT; i++) {\n\t\tlines[i] = '*';\n\t}\n\n\t// calculate\n\tcantor(0, WIDTH, 1);\n\n\t// print\n\tfor (int i = 0; i < HEIGHT*WIDTH; i += WIDTH) {\n\t\tprintf(\"%.*s\\n\", WIDTH, lines + i);\n\t}\n\n\treturn 0;\n}"} -{"title": "Cantor set", "language": "JavaScript from Python", "task": "Draw a Cantor set.\n\n\nSee details at this Wikipedia webpage: Cantor set\n\n", "solution": "(() => {\n \"use strict\";\n\n // -------------- CANTOR RATIONAL PAIRS --------------\n\n // cantor :: [(Rational, Rational)] ->\n // [(Rational, Rational)]\n const cantor = xs => {\n const go = ab => {\n const [r1, r2] = Array.from(ab).map(rational);\n const third = ratioDiv(ratioMinus(r2)(r1))(3);\n\n return [\n Tuple(r1)(ratioPlus(r1)(third)),\n Tuple(ratioMinus(r2)(third))(r2)\n ];\n };\n\n return xs.flatMap(go);\n };\n\n\n // ---------------------- TEST -----------------------\n // main :: IO ()\n const main = () => {\n const\n xs = take(4)(\n iterate(cantor)([Tuple(0)(1)])\n );\n\n return [\n `${unlines(xs.map(intervalRatios))}\\n`,\n intervalBars(xs)\n ]\n .join(\"\\n\\n\");\n };\n\n\n // --------------------- DISPLAY ---------------------\n\n // intervalRatios :: [(Rational, Rational)] -> String\n const intervalRatios = xs => {\n const go = ab =>\n Array.from(ab).map(\n compose(showRatio, rational)\n )\n .join(\", \");\n\n return `(${xs.map(go).join(\") (\")})`;\n };\n\n // intervalBars :: [[(Rational, Rational)]] -> String\n const intervalBars = rs => {\n const go = w => xs =>\n snd(mapAccumL(\n a => ab => {\n const [wx, wy] = Array.from(ab).map(\n r => ratioMult(w)(\n rational(r)\n )\n );\n\n return Tuple(wy)(\n replicateString(\n floor(ratioMinus(wx)(a))\n )(\" \") + replicateString(\n floor(ratioMinus(wy)(wx))\n )(\"\u2588\")\n );\n }\n )(0)(xs)).join(\"\");\n const d = maximum(\n last(rs).map(x => fst(x).d)\n );\n\n return unlines(rs.map(\n go(Ratio(d)(1))\n ));\n };\n\n\n // ---------------- GENERIC FUNCTIONS ----------------\n\n // Ratio :: Integral a => a -> a -> Ratio a\n const Ratio = a => b => {\n const go = (x, y) =>\n 0 !== y ? (() => {\n const d = gcd(x)(y);\n\n return {\n type: \"Ratio\",\n // numerator\n \"n\": Math.trunc(x / d),\n // denominator\n \"d\": Math.trunc(y / d)\n };\n })() : undefined;\n\n return go(a * signum(b), abs(b));\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 // 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 // approxRatio :: Float -> Float -> Ratio\n const approxRatio = eps =>\n n => {\n const\n gcde = (e, x, y) => {\n const _gcd = (a, b) =>\n b < e ? (\n a\n ) : _gcd(b, a % b);\n\n return _gcd(Math.abs(x), Math.abs(y));\n },\n c = gcde(Boolean(eps) ? (\n eps\n ) : (1 / 10000), 1, n);\n\n return Ratio(\n Math.floor(n / c)\n )(\n Math.floor(1 / c)\n );\n };\n\n\n // floor :: Num -> Int\n const floor = x => {\n const\n nr = (\n \"Ratio\" !== x.type ? (\n properFraction\n ) : properFracRatio\n )(x),\n n = nr[0];\n\n return 0 > nr[1] ? n - 1 : n;\n };\n\n\n // fst :: (a, b) -> a\n const fst = ab =>\n // First member of a pair.\n ab[0];\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\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 // iterate :: (a -> a) -> a -> Gen [a]\n const iterate = f =>\n // An infinite list of repeated\n // applications of f to x.\n function* (x) {\n let v = x;\n\n while (true) {\n yield v;\n v = f(v);\n }\n };\n\n\n // last :: [a] -> a\n const last = xs =>\n // The last item of a list.\n 0 < xs.length ? (\n xs.slice(-1)[0]\n ) : null;\n\n\n // lcm :: Int -> Int -> Int\n const lcm = x =>\n // The smallest positive integer divisible\n // without remainder by both x and y.\n y => (x === 0 || y === 0) ? (\n 0\n ) : Math.abs(Math.floor(x / gcd(x)(y)) * y);\n\n\n // mapAccumL :: (acc -> x -> (acc, y)) ->\n // acc -> [x] -> (acc, [y])\n const mapAccumL = f =>\n // A tuple of an accumulation and a list\n // obtained by a combined map and fold,\n // with accumulation from left to right.\n acc => xs => [...xs].reduce(\n (a, x) => {\n const ab = f(a[0])(x);\n\n return [ab[0], a[1].concat(ab[1])];\n },\n [acc, []]\n );\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 )(xs);\n\n\n // properFracRatio :: Ratio -> (Int, Ratio)\n const properFracRatio = nd => {\n const [q, r] = Array.from(quotRem(nd.n)(nd.d));\n\n return Tuple(q)(Ratio(r)(nd.d));\n };\n\n\n // properFraction :: Real -> (Int, Real)\n const properFraction = n => {\n const i = Math.floor(n) + (n < 0 ? 1 : 0);\n\n return Tuple(i)(n - i);\n };\n\n\n // quotRem :: Integral a => a -> a -> (a, a)\n const quotRem = m =>\n // The quotient, tupled with the remainder.\n n => Tuple(\n Math.trunc(m / n)\n )(\n m % n\n );\n\n\n // ratioDiv :: Rational -> Rational -> Rational\n const ratioDiv = n1 => n2 => {\n const [r1, r2] = [n1, n2].map(rational);\n\n return Ratio(r1.n * r2.d)(\n r1.d * r2.n\n );\n };\n\n\n // ratioMinus :: Rational -> Rational -> Rational\n const ratioMinus = n1 => n2 => {\n const [r1, r2] = [n1, n2].map(rational);\n const d = lcm(r1.d)(r2.d);\n\n return Ratio(\n (r1.n * (d / r1.d)) - (r2.n * (d / r2.d))\n )(d);\n };\n\n\n // ratioMult :: Rational -> Rational -> Rational\n const ratioMult = n1 => n2 => {\n const [r1, r2] = [n1, n2].map(rational);\n\n return Ratio(r1.n * r2.n)(\n r1.d * r2.d\n );\n };\n\n\n // ratioPlus :: Rational -> Rational -> Rational\n const ratioPlus = n1 =>\n n2 => {\n const [r1, r2] = [n1, n2].map(rational);\n const d = lcm(r1.d)(r2.d);\n\n return Ratio(\n (r1.n * (d / r1.d)) + (\n r2.n * (d / r2.d)\n )\n )(d);\n };\n\n\n // rational :: Num a => a -> Rational\n const rational = x =>\n isNaN(x) ? x : Number.isInteger(x) ? (\n Ratio(x)(1)\n ) : approxRatio(undefined)(x);\n\n\n // replicateString :: Int -> String -> String\n const replicateString = n =>\n s => s.repeat(n);\n\n\n // showRatio :: Ratio -> String\n const showRatio = r =>\n \"Ratio\" !== r.type ? (\n r.toString()\n ) : r.n.toString() + (\n 1 !== r.d ? (\n `/${r.d}`\n ) : \"\"\n );\n\n\n // signum :: Num -> Num\n const signum = n =>\n // | Sign of a number.\n n.constructor(\n 0 > n ? (\n -1\n ) : (\n 0 < n ? 1 : 0\n )\n );\n\n\n // snd :: (a, b) -> b\n const snd = ab =>\n // Second member of a pair.\n ab[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(...Array.from({\n length: n\n }, () => {\n const x = xs.next();\n\n return x.done ? [] : [x.value];\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\n // MAIN ---\n return main();\n})();"} -{"title": "Cantor set", "language": "Python", "task": "Draw a Cantor set.\n\n\nSee details at this Wikipedia webpage: Cantor set\n\n", "solution": "WIDTH = 81\nHEIGHT = 5\n\nlines=[]\ndef cantor(start, len, index):\n seg = len / 3\n if seg == 0:\n return None\n for it in xrange(HEIGHT-index):\n i = index + it\n for jt in xrange(seg):\n j = start + seg + jt\n pos = i * WIDTH + j\n lines[pos] = ' '\n cantor(start, seg, index + 1)\n cantor(start + seg * 2, seg, index + 1)\n return None\n\nlines = ['*'] * (WIDTH*HEIGHT)\ncantor(0, WIDTH, 1)\n\nfor i in xrange(HEIGHT):\n beg = WIDTH * i\n print ''.join(lines[beg : beg+WIDTH])"} -{"title": "Cantor set", "language": "Python 3.7", "task": "Draw a Cantor set.\n\n\nSee details at this Wikipedia webpage: Cantor set\n\n", "solution": "'''A Cantor set generator, and two different\n representations of its output.\n'''\n\nfrom itertools import (islice, chain)\nfrom fractions import Fraction\nfrom functools import (reduce)\n\n\n# ----------------------- CANTOR SET -----------------------\n\n# cantor :: Generator [[(Fraction, Fraction)]]\ndef cantor():\n '''A non-finite stream of successive Cantor\n partitions of the line, in the form of\n lists of fraction pairs.\n '''\n def go(xy):\n (x, y) = xy\n third = Fraction(y - x, 3)\n return [(x, x + third), (y - third, y)]\n\n return iterate(\n concatMap(go)\n )(\n [(0, 1)]\n )\n\n\n# fractionLists :: [(Fraction, Fraction)] -> String\ndef fractionLists(xs):\n '''A fraction pair representation of a\n Cantor-partitioned line.\n '''\n def go(xy):\n return ', '.join(map(showRatio, xy))\n return ' '.join('(' + go(x) + ')' for x in xs)\n\n\n# intervalBars :: [(Fraction, Fraction)] -> String\ndef intervalBars(w):\n '''A block diagram representation of a\n Cantor-partitioned line.\n '''\n def go(xs):\n def show(a, tpl):\n [x, y] = [int(w * r) for r in tpl]\n return (\n y,\n (' ' * (x - a)) + ('\u2588' * (y - x))\n )\n return mapAccumL(show)(0)(xs)\n return lambda xs: ''.join(go(xs)[1])\n\n\n# -------------------------- TEST --------------------------\n# main :: IO ()\ndef main():\n '''Testing the generation of successive\n Cantor subdivisions of the line, and\n displaying them both as lines of fraction\n pairs and as graphic interval bars.\n '''\n xs = list(islice(cantor(), 4))\n w = max(xy[1].denominator for xy in xs[-1])\n print(\n '\\n'.join(map(fractionLists, xs)),\n '\\n'\n )\n print(\n '\\n'.join(map(intervalBars(w), xs))\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 return lambda xs: list(\n chain.from_iterable(map(f, xs))\n )\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# 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# showRatio :: Ratio -> String\ndef showRatio(r):\n '''String representation of the ratio r.'''\n d = r.denominator\n return str(r.numerator) + (\n '/' + str(d) if 1 != d else ''\n )\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} -{"title": "Cartesian product of two or more lists", "language": "C", "task": "Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.\n\nDemonstrate that your function/method correctly returns:\n::{1, 2} x {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}\n\nand, in contrast:\n::{3, 4} x {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}\n\nAlso demonstrate, using your function/method, that the product of an empty list with any other list is empty.\n:: {1, 2} x {} = {}\n:: {} x {1, 2} = {}\n\nFor extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.\n\nUse your n-ary Cartesian product function to show the following products:\n:: {1776, 1789} x {7, 12} x {4, 14, 23} x {0, 1}\n:: {1, 2, 3} x {30} x {500, 100}\n:: {1, 2, 3} x {} x {500, 100}\n\n\n", "solution": "#include\n#include\n#include\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s \",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n"} -{"title": "Cartesian product of two or more lists", "language": "C++", "task": "Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.\n\nDemonstrate that your function/method correctly returns:\n::{1, 2} x {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}\n\nand, in contrast:\n::{3, 4} x {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}\n\nAlso demonstrate, using your function/method, that the product of an empty list with any other list is empty.\n:: {1, 2} x {} = {}\n:: {} x {1, 2} = {}\n\nFor extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.\n\nUse your n-ary Cartesian product function to show the following products:\n:: {1776, 1789} x {7, 12} x {4, 14, 23} x {0, 1}\n:: {1, 2, 3} x {30} x {500, 100}\n:: {1, 2, 3} x {} x {500, 100}\n\n\n", "solution": "#include \n#include \n#include \n\nvoid print(const std::vector>& v) {\n std::cout << \"{ \";\n for (const auto& p : v) {\n std::cout << \"(\";\n for (const auto& e : p) {\n std::cout << e << \" \";\n }\n std::cout << \") \";\n }\n std::cout << \"}\" << std::endl;\n}\n\nauto product(const std::vector>& lists) {\n std::vector> result;\n if (std::find_if(std::begin(lists), std::end(lists), \n [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {\n return result;\n }\n for (auto& e : lists[0]) {\n result.push_back({ e });\n }\n for (size_t i = 1; i < lists.size(); ++i) {\n std::vector> temp;\n for (auto& e : result) {\n for (auto f : lists[i]) {\n auto e_tmp = e;\n e_tmp.push_back(f);\n temp.push_back(e_tmp);\n }\n }\n result = temp;\n }\n return result;\n}\n\nint main() {\n std::vector> prods[] = {\n { { 1, 2 }, { 3, 4 } },\n { { 3, 4 }, { 1, 2} },\n { { 1, 2 }, { } },\n { { }, { 1, 2 } },\n { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },\n { { 1, 2, 3 }, { 30 }, { 500, 100 } },\n { { 1, 2, 3 }, { }, { 500, 100 } }\n };\n for (const auto& p : prods) {\n print(product(p));\n }\n std::cin.ignore();\n std::cin.get();\n return 0;\n}"} -{"title": "Cartesian product of two or more lists", "language": "JavaScript", "task": "Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.\n\nDemonstrate that your function/method correctly returns:\n::{1, 2} x {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}\n\nand, in contrast:\n::{3, 4} x {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}\n\nAlso demonstrate, using your function/method, that the product of an empty list with any other list is empty.\n:: {1, 2} x {} = {}\n:: {} x {1, 2} = {}\n\nFor extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.\n\nUse your n-ary Cartesian product function to show the following products:\n:: {1776, 1789} x {7, 12} x {4, 14, 23} x {0, 1}\n:: {1, 2, 3} x {30} x {500, 100}\n:: {1, 2, 3} x {} x {500, 100}\n\n\n", "solution": "(() => {\n // CARTESIAN PRODUCT OF TWO LISTS ---------------------\n\n // cartProd :: [a] -> [b] -> [[a, b]]\n const cartProd = xs => ys =>\n xs.flatMap(x => ys.map(y => [x, y]))\n\n\n // TEST -----------------------------------------------\n return [\n cartProd([1, 2])([3, 4]),\n cartProd([3, 4])([1, 2]),\n cartProd([1, 2])([]),\n cartProd([])([1, 2]),\n ].map(JSON.stringify).join('\\n');\n})();"} -{"title": "Cartesian product of two or more lists", "language": "Python", "task": "Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.\n\nDemonstrate that your function/method correctly returns:\n::{1, 2} x {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}\n\nand, in contrast:\n::{3, 4} x {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}\n\nAlso demonstrate, using your function/method, that the product of an empty list with any other list is empty.\n:: {1, 2} x {} = {}\n:: {} x {1, 2} = {}\n\nFor extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.\n\nUse your n-ary Cartesian product function to show the following products:\n:: {1776, 1789} x {7, 12} x {4, 14, 23} x {0, 1}\n:: {1, 2, 3} x {30} x {500, 100}\n:: {1, 2, 3} x {} x {500, 100}\n\n\n", "solution": "import itertools\n\ndef cp(lsts):\n return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n from pprint import pprint as pp\n \n for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n ((1776, 1789), (7, 12), (4, 14, 23), (0, 1)),\n ((1, 2, 3), (30,), (500, 100)),\n ((1, 2, 3), (), (500, 100))]:\n print(lists, '=>')\n pp(cp(lists), indent=2)\n"} -{"title": "Casting out nines", "language": "C++", "task": "Task (in three parts):\n\n\n;Part 1\nWrite a procedure (say \\mathit{co9}(x)) which implements Casting Out Nines as described by returning the checksum for x. Demonstrate the procedure using the examples given there, or others you may consider lucky.\n\nNote that this function does nothing more than calculate the least positive residue, modulo 9. Many of the solutions omit Part 1 for this reason. Many languages have a modulo operator, of which this is a trivial application.\n\nWith that understanding, solutions to Part 1, if given, are encouraged to follow the naive pencil-and-paper or mental arithmetic of repeated digit addition understood to be \"casting out nines\", or some approach other than just reducing modulo 9 using a built-in operator. Solutions for part 2 and 3 are not required to make use of the function presented in part 1.\n\n;Part 2\nNotwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:\n: Consider the statement \"318682 is 101558 + 217124 and squared is 101558217124\" (see: [[Kaprekar numbers#Casting Out Nines (fast)]]).\n: note that 318682 has the same checksum as (101558 + 217124);\n: note that 101558217124 has the same checksum as (101558 + 217124) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);\n: note that this implies that for Kaprekar numbers the checksum of k equals the checksum of k^2.\n\nDemonstrate that your procedure can be used to generate or filter a range of numbers with the property \\mathit{co9}(k) = \\mathit{co9}(k^2) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.\n\n;Part 3\nConsidering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:\n: \\mathit{co9}(x) is the residual of x mod 9;\n: the procedure can be extended to bases other than 9.\n\nDemonstrate your algorithm by generating or filtering a range of numbers with the property k%(\\mathit{Base}-1) == (k^2)%(\\mathit{Base}-1) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.\n\n;related tasks\n* [[First perfect square in base N with N unique digits]]\n* [[Kaprekar numbers]]\n\n", "solution": "// Casting Out Nines\n//\n// Nigel Galloway. June 24th., 2012\n//\n#include \nint main() {\n\tint Base = 10;\n\tconst int N = 2;\n\tint c1 = 0;\n\tint c2 = 0;\n\tfor (int k=1; kcastOutNine: ');\n castOutNine()\n document.write('
kaprekar: ');\n kaprekar()\n document.write('

')\n\n function castOutNine() {\n for (var n = s, k = 0, bsm1 = bs - 1; n <= e; n += 1)\n if (n % bsm1 == (n * n) % bsm1) k += 1,\n document.write(toString(n), ' ')\n document.write('
trying ', k, ' numbers instead of ', n = e - s + 1,\n ' numbers saves ', (100 - k / n * 100)\n .toFixed(3), '%')\n }\n\n function kaprekar() {\n for (var n = s; n <= e; n += 1)\n if (isKaprekar(n)) document.write(toString(n), ' ')\n\n function isKaprekar(n) {\n if (n < 1) return false\n if (n == 1) return true\n var s = (n * n)\n .toString(bs)\n for (var i = 1, e = s.length; i < e; i += 1) {\n var a = parseInt(s.substr(0, i), bs)\n var b = parseInt(s.substr(i), bs)\n if (b && a + b == n) return true\n }\n return false\n }\n }\n\n function toString(n) {\n return n.toString(pbs)\n .toUpperCase()\n }\n}\nmain(1, 10 * 10 - 1)\nmain(1, 16 * 16 - 1, 16)\nmain(1, 17 * 17 - 1, 17)\nmain(parseInt('10', 17), parseInt('gg', 17), 17, 17)"} -{"title": "Casting out nines", "language": "JavaScript from Haskell", "task": "Task (in three parts):\n\n\n;Part 1\nWrite a procedure (say \\mathit{co9}(x)) which implements Casting Out Nines as described by returning the checksum for x. Demonstrate the procedure using the examples given there, or others you may consider lucky.\n\nNote that this function does nothing more than calculate the least positive residue, modulo 9. Many of the solutions omit Part 1 for this reason. Many languages have a modulo operator, of which this is a trivial application.\n\nWith that understanding, solutions to Part 1, if given, are encouraged to follow the naive pencil-and-paper or mental arithmetic of repeated digit addition understood to be \"casting out nines\", or some approach other than just reducing modulo 9 using a built-in operator. Solutions for part 2 and 3 are not required to make use of the function presented in part 1.\n\n;Part 2\nNotwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:\n: Consider the statement \"318682 is 101558 + 217124 and squared is 101558217124\" (see: [[Kaprekar numbers#Casting Out Nines (fast)]]).\n: note that 318682 has the same checksum as (101558 + 217124);\n: note that 101558217124 has the same checksum as (101558 + 217124) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);\n: note that this implies that for Kaprekar numbers the checksum of k equals the checksum of k^2.\n\nDemonstrate that your procedure can be used to generate or filter a range of numbers with the property \\mathit{co9}(k) = \\mathit{co9}(k^2) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.\n\n;Part 3\nConsidering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:\n: \\mathit{co9}(x) is the residual of x mod 9;\n: the procedure can be extended to bases other than 9.\n\nDemonstrate your algorithm by generating or filtering a range of numbers with the property k%(\\mathit{Base}-1) == (k^2)%(\\mathit{Base}-1) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.\n\n;related tasks\n* [[First perfect square in base N with N unique digits]]\n* [[Kaprekar numbers]]\n\n", "solution": "(() => {\n 'use strict';\n\n // co9 :: Int -> Int\n const co9 = n =>\n n <= 8 ? n : co9(\n digits(10, n)\n .reduce((a, x) => x !== 9 ? a + x : a, 0)\n );\n\n // GENERIC FUNCTIONS\n\n // digits :: Int -> Int -> [Int]\n const digits = (base, n) => {\n if (n < base) return [n];\n const [q, r] = quotRem(n, base);\n return [r].concat(digits(base, q));\n };\n\n // quotRem :: Integral a => a -> a -> (a, a)\n const quotRem = (m, n) => [Math.floor(m / n), m % 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 // squared :: Num a => a -> a\n const squared = n => Math.pow(n, 2);\n\n // show :: a -> String\n const show = x => JSON.stringify(x, null, 2);\n\n // TESTS\n return show({\n test1: co9(232345), //-> 1\n test2: co9(34234234), //-> 7\n test3: co9(232345 + 34234234) === co9(232345) + co9(34234234), //-> true\n test4: co9(232345 * 34234234) === co9(232345) * co9(34234234), //-> true,\n task2: range(1, 100)\n .filter(n => co9(n) === co9(squared(n))),\n task3: (k => range(1, 100)\n .filter(n => (n % k) === (squared(n) % k)))(16)\n });\n})();"} -{"title": "Casting out nines", "language": "Python", "task": "Task (in three parts):\n\n\n;Part 1\nWrite a procedure (say \\mathit{co9}(x)) which implements Casting Out Nines as described by returning the checksum for x. Demonstrate the procedure using the examples given there, or others you may consider lucky.\n\nNote that this function does nothing more than calculate the least positive residue, modulo 9. Many of the solutions omit Part 1 for this reason. Many languages have a modulo operator, of which this is a trivial application.\n\nWith that understanding, solutions to Part 1, if given, are encouraged to follow the naive pencil-and-paper or mental arithmetic of repeated digit addition understood to be \"casting out nines\", or some approach other than just reducing modulo 9 using a built-in operator. Solutions for part 2 and 3 are not required to make use of the function presented in part 1.\n\n;Part 2\nNotwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:\n: Consider the statement \"318682 is 101558 + 217124 and squared is 101558217124\" (see: [[Kaprekar numbers#Casting Out Nines (fast)]]).\n: note that 318682 has the same checksum as (101558 + 217124);\n: note that 101558217124 has the same checksum as (101558 + 217124) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);\n: note that this implies that for Kaprekar numbers the checksum of k equals the checksum of k^2.\n\nDemonstrate that your procedure can be used to generate or filter a range of numbers with the property \\mathit{co9}(k) = \\mathit{co9}(k^2) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.\n\n;Part 3\nConsidering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:\n: \\mathit{co9}(x) is the residual of x mod 9;\n: the procedure can be extended to bases other than 9.\n\nDemonstrate your algorithm by generating or filtering a range of numbers with the property k%(\\mathit{Base}-1) == (k^2)%(\\mathit{Base}-1) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.\n\n;related tasks\n* [[First perfect square in base N with N unique digits]]\n* [[Kaprekar numbers]]\n\n", "solution": "# Casting out Nines\n#\n# Nigel Galloway: June 27th., 2012,\n#\ndef CastOut(Base=10, Start=1, End=999999):\n ran = [y for y in range(Base-1) if y%(Base-1) == (y*y)%(Base-1)]\n x,y = divmod(Start, Base-1)\n while True:\n for n in ran:\n k = (Base-1)*x + n\n if k < Start:\n continue\n if k > End:\n return\n yield k\n x += 1\n\nfor V in CastOut(Base=16,Start=1,End=255):\n print(V, end=' ')"} -{"title": "Catalan numbers/Pascal's triangle", "language": "C", "task": "Print out the first '''15''' Catalan numbers by extracting them from Pascal's triangle.\n\n\n;See:\n* Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.\n\n* Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.\n* Sequence A000108 on OEIS has a lot of information on Catalan Numbers.\n\n;Related Tasks:\n[[Pascal's triangle]]\n\n", "solution": "//This code implements the print of 15 first Catalan's Numbers\n//Formula used:\n// __n__\n// | | (n + k) / k n>0\n// k=2 \n\n#include \n#include \n\n//the number of Catalan's Numbers to be printed\nconst int N = 15;\n\nint main()\n{\n //loop variables (in registers)\n register int k, n;\n\n //necessarily ull for reach big values\n unsigned long long int num, den;\n\n //the nmmber\n int catalan;\n\n //the first is not calculated for the formula\n printf(\"1 \");\n\n //iterating from 2 to 15\n for (n=2; n<=N; ++n) {\n //initializaing for products\n num = den = 1;\n //applying the formula\n for (k=2; k<=n; ++k) {\n num *= (n+k);\n den *= k;\n catalan = num /den;\n }\n \n //output\n printf(\"%d \", catalan);\n }\n\n //the end\n printf(\"\\n\");\n return 0;\n}\n"} -{"title": "Catalan numbers/Pascal's triangle", "language": "C++", "task": "Print out the first '''15''' Catalan numbers by extracting them from Pascal's triangle.\n\n\n;See:\n* Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.\n\n* Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.\n* Sequence A000108 on OEIS has a lot of information on Catalan Numbers.\n\n;Related Tasks:\n[[Pascal's triangle]]\n\n", "solution": "// Generate Catalan Numbers\n//\n// Nigel Galloway: June 9th., 2012\n//\n#include \nint main() {\n const int N = 15;\n int t[N+2] = {0,1};\n for(int i = 1; i<=N; i++){\n for(int j = i; j>1; j--) t[j] = t[j] + t[j-1];\n t[i+1] = t[i];\n for(int j = i+1; j>1; j--) t[j] = t[j] + t[j-1];\n std::cout << t[i+1] - t[i] << \" \";\n }\n return 0;\n}"} -{"title": "Catalan numbers/Pascal's triangle", "language": "JavaScript from C++", "task": "Print out the first '''15''' Catalan numbers by extracting them from Pascal's triangle.\n\n\n;See:\n* Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.\n\n* Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.\n* Sequence A000108 on OEIS has a lot of information on Catalan Numbers.\n\n;Related Tasks:\n[[Pascal's triangle]]\n\n", "solution": "var n = 15;\nfor (var t = [0, 1], i = 1; i <= n; i++) {\n for (var j = i; j > 1; j--) t[j] += t[j - 1];\n t[i + 1] = t[i];\n for (var j = i + 1; j > 1; j--) t[j] += t[j - 1];\n document.write(i == 1 ? '' : ', ', t[i + 1] - t[i]);\n}"} -{"title": "Catalan numbers/Pascal's triangle", "language": "JavaScript from Haskell", "task": "Print out the first '''15''' Catalan numbers by extracting them from Pascal's triangle.\n\n\n;See:\n* Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.\n\n* Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.\n* Sequence A000108 on OEIS has a lot of information on Catalan Numbers.\n\n;Related Tasks:\n[[Pascal's triangle]]\n\n", "solution": "(() => {\n 'use strict';\n\n // CATALAN\n\n // catalanSeries :: Int -> [Int]\n let catalanSeries = n => {\n let alternate = xs => xs.reduce(\n (a, x, i) => i % 2 === 0 ? a.concat([x]) : a, []\n ),\n diff = xs => xs.length > 1 ? xs[0] - xs[1] : xs[0];\n\n return alternate(pascal(n * 2))\n .map((xs, i) => diff(drop(i, xs)));\n }\n\n // PASCAL\n\n // pascal :: Int -> [[Int]]\n let pascal = n => until(\n m => m.level <= 1,\n m => {\n let nxt = zipWith(\n (a, b) => a + b, [0].concat(m.row), m.row.concat(0)\n );\n return {\n row: nxt,\n triangle: m.triangle.concat([nxt]),\n level: m.level - 1\n }\n }, {\n level: n,\n row: [1],\n triangle: [\n [1]\n ]\n }\n )\n .triangle;\n\n\n // GENERIC FUNCTIONS\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n let zipWith = (f, xs, ys) =>\n xs.length === ys.length ? (\n xs.map((x, i) => f(x, ys[i]))\n ) : undefined;\n\n // until :: (a -> Bool) -> (a -> a) -> a -> a\n let until = (p, f, x) => {\n let v = x;\n while (!p(v)) v = f(v);\n return v;\n }\n\n // drop :: Int -> [a] -> [a]\n let drop = (n, xs) => xs.slice(n);\n\n // tail :: [a] -> [a]\n let tail = xs => xs.length ? xs.slice(1) : undefined;\n\n return tail(catalanSeries(16));\n})();"} -{"title": "Catalan numbers/Pascal's triangle", "language": "Python from C++", "task": "Print out the first '''15''' Catalan numbers by extracting them from Pascal's triangle.\n\n\n;See:\n* Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.\n\n* Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.\n* Sequence A000108 on OEIS has a lot of information on Catalan Numbers.\n\n;Related Tasks:\n[[Pascal's triangle]]\n\n", "solution": ">>> n = 15\n>>> t = [0] * (n + 2)\n>>> t[1] = 1\n>>> for i in range(1, n + 1):\n\tfor j in range(i, 1, -1): t[j] += t[j - 1]\n\tt[i + 1] = t[i]\n\tfor j in range(i + 1, 1, -1): t[j] += t[j - 1]\n\tprint(t[i+1] - t[i], end=' ')\n\n\t\n1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845 \n>>> "} -{"title": "Catalan numbers/Pascal's triangle", "language": "Python 2.7", "task": "Print out the first '''15''' Catalan numbers by extracting them from Pascal's triangle.\n\n\n;See:\n* Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.\n\n* Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.\n* Sequence A000108 on OEIS has a lot of information on Catalan Numbers.\n\n;Related Tasks:\n[[Pascal's triangle]]\n\n", "solution": "def catalan_number(n):\n nm = dm = 1\n for k in range(2, n+1):\n nm, dm = ( nm*(n+k), dm*k )\n return nm/dm\n \nprint [catalan_number(n) for n in range(1, 16)]\n \n[1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845]"} -{"title": "Catalan numbers/Pascal's triangle", "language": "Python 3.7", "task": "Print out the first '''15''' Catalan numbers by extracting them from Pascal's triangle.\n\n\n;See:\n* Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.\n\n* Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.\n* Sequence A000108 on OEIS has a lot of information on Catalan Numbers.\n\n;Related Tasks:\n[[Pascal's triangle]]\n\n", "solution": "'''Catalan numbers from Pascal's triangle'''\n\nfrom itertools import (islice)\nfrom operator import (add)\n\n\n# nCatalans :: Int -> [Int]\ndef nCatalans(n):\n '''The first n Catalan numbers,\n derived from Pascal's triangle.'''\n\n # diff :: [Int] -> Int\n def diff(xs):\n '''Difference between the first two items in the list,\n if its length is more than one.\n Otherwise, the first (only) item in the list.'''\n return (\n xs[0] - (xs[1] if 1 < len(xs) else 0)\n ) if xs else None\n return list(map(\n compose(diff)(uncurry(drop)),\n enumerate(map(fst, take(n)(\n everyOther(\n pascalTriangle()\n )\n )))\n ))\n\n\n# pascalTriangle :: Gen [[Int]]\ndef pascalTriangle():\n '''A non-finite stream of\n Pascal's triangle rows.'''\n return iterate(nextPascal)([1])\n\n\n# nextPascal :: [Int] -> [Int]\ndef nextPascal(xs):\n '''A row of Pascal's triangle\n derived from a preceding row.'''\n return zipWith(add)([0] + xs)(xs + [0])\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''First 16 Catalan numbers.'''\n\n print(\n nCatalans(16)\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# 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):\n return xs[n:]\n else:\n take(n)(xs)\n return xs\n return lambda xs: go(xs)\n\n\n# everyOther :: Gen [a] -> Gen [a]\ndef everyOther(g):\n '''Every other item of a generator stream.'''\n while True:\n yield take(1)(g)\n take(1)(g) # Consumed, not yielded.\n\n\n# fst :: (a, b) -> a\ndef fst(tpl):\n '''First component of a pair.'''\n return tpl[0]\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# 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# uncurry :: (a -> b -> c) -> ((a, b) -> c)\ndef uncurry(f):\n '''A function over a tuple\n derived from a curried function.'''\n return lambda xy: f(xy[0])(\n xy[1]\n )\n\n\n# zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\ndef zipWith(f):\n '''A list constructed by zipping with a\n custom function, rather than with the\n default tuple constructor.'''\n return lambda xs: lambda ys: (\n list(map(f, xs, ys))\n )\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} -{"title": "Catamorphism", "language": "C", "task": "''Reduce'' is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. \n\n\n;Task:\nShow how ''reduce'' (or ''foldl'' or ''foldr'' etc), work (or would be implemented) in your language.\n\n\n;See also:\n* Wikipedia article: Fold\n* Wikipedia article: Catamorphism\n\n", "solution": "#include \n\ntypedef int (*intFn)(int, int);\n\nint reduce(intFn fn, int size, int *elms)\n{\n int i, val = *elms;\n for (i = 1; i < size; ++i)\n val = fn(val, elms[i]);\n return val;\n}\n\nint add(int a, int b) { return a + b; }\nint sub(int a, int b) { return a - b; }\nint mul(int a, int b) { return a * b; }\n\nint main(void)\n{\n int nums[] = {1, 2, 3, 4, 5};\n printf(\"%d\\n\", reduce(add, 5, nums));\n printf(\"%d\\n\", reduce(sub, 5, nums));\n printf(\"%d\\n\", reduce(mul, 5, nums));\n return 0;\n}"} -{"title": "Catamorphism", "language": "C++", "task": "''Reduce'' is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. \n\n\n;Task:\nShow how ''reduce'' (or ''foldl'' or ''foldr'' etc), work (or would be implemented) in your language.\n\n\n;See also:\n* Wikipedia article: Fold\n* Wikipedia article: Catamorphism\n\n", "solution": "#include \n#include \n#include \n#include \n\nint main() {\n\tstd::vector nums = { 1, 2, 3, 4, 5 };\n\tauto nums_added = std::accumulate(std::begin(nums), std::end(nums), 0, std::plus());\n\tauto nums_other = std::accumulate(std::begin(nums), std::end(nums), 0, [](const int& a, const int& b) {\n\t\treturn a + 2 * b;\n\t});\n\tstd::cout << \"nums_added: \" << nums_added << std::endl;\n\tstd::cout << \"nums_other: \" << nums_other << std::endl;\n}"} -{"title": "Catamorphism", "language": "JavaScript", "task": "''Reduce'' is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. \n\n\n;Task:\nShow how ''reduce'' (or ''foldl'' or ''foldr'' etc), work (or would be implemented) in your language.\n\n\n;See also:\n* Wikipedia article: Fold\n* Wikipedia article: Catamorphism\n\n", "solution": "(function (xs) {\n 'use strict';\n\n // foldl :: (b -> a -> b) -> b -> [a] -> b\n function foldl(f, acc, xs) {\n return xs.reduce(f, acc);\n }\n\n // foldr :: (b -> a -> b) -> b -> [a] -> b\n function foldr(f, acc, xs) {\n return xs.reduceRight(f, acc);\n }\n\n // Test folds in both directions\n return [foldl, foldr].map(function (f) {\n return f(function (acc, x) {\n return acc + (x * 2).toString() + ' ';\n }, [], xs);\n });\n\n})([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);"} -{"title": "Catamorphism", "language": "Python", "task": "''Reduce'' is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. \n\n\n;Task:\nShow how ''reduce'' (or ''foldl'' or ''foldr'' etc), work (or would be implemented) in your language.\n\n\n;See also:\n* Wikipedia article: Fold\n* Wikipedia article: Catamorphism\n\n", "solution": ">>> # Python 2.X\n>>> from operator import add\n>>> listoflists = [['the', 'cat'], ['sat', 'on'], ['the', 'mat']]\n>>> help(reduce)\nHelp on built-in function reduce in module __builtin__:\n\nreduce(...)\n reduce(function, sequence[, initial]) -> value\n \n Apply a function of two arguments cumulatively to the items of a sequence,\n from left to right, so as to reduce the sequence to a single value.\n For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n of the sequence in the calculation, and serves as a default when the\n sequence is empty.\n\n>>> reduce(add, listoflists, [])\n['the', 'cat', 'sat', 'on', 'the', 'mat']\n>>> "} -{"title": "Chaocipher", "language": "C++ from C#", "task": "Description:\nThe Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.\n\nThe algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.\n\n\n;Task:\nCode the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.\n\n", "solution": "#include \n\nenum class Mode {\n ENCRYPT,\n DECRYPT,\n};\n\nconst std::string L_ALPHABET = \"HXUCZVAMDSLKPEFJRIGTWOBNYQ\";\nconst std::string R_ALPHABET = \"PTLNBQDEOYSFAVZKGJRIHWXUMC\";\n\nstd::string exec(std::string text, Mode mode, bool showSteps = false) {\n auto left = L_ALPHABET;\n auto right = R_ALPHABET;\n auto eText = new char[text.size() + 1];\n auto temp = new char[27];\n\n memset(eText, 0, text.size() + 1);\n memset(temp, 0, 27);\n\n for (size_t i = 0; i < text.size(); i++) {\n if (showSteps) std::cout << left << ' ' << right << '\\n';\n size_t index;\n if (mode == Mode::ENCRYPT) {\n index = right.find(text[i]);\n eText[i] = left[index];\n } else {\n index = left.find(text[i]);\n eText[i] = right[index];\n }\n if (i == text.size() - 1) break;\n\n // permute left\n\n for (int j = index; j < 26; ++j) temp[j - index] = left[j];\n for (int j = 0; j < index; ++j) temp[26 - index + j] = left[j];\n auto store = temp[1];\n for (int j = 2; j < 14; ++j) temp[j - 1] = temp[j];\n temp[13] = store;\n left = temp;\n\n // permurte right\n\n for (int j = index; j < 26; ++j) temp[j - index] = right[j];\n for (int j = 0; j < index; ++j) temp[26 - index + j] = right[j];\n store = temp[0];\n for (int j = 1; j < 26; ++j) temp[j - 1] = temp[j];\n temp[25] = store;\n store = temp[2];\n for (int j = 3; j < 14; ++j) temp[j - 1] = temp[j];\n temp[13] = store;\n right = temp;\n }\n\n return eText;\n}\n\nint main() {\n auto plainText = \"WELLDONEISBETTERTHANWELLSAID\";\n std::cout << \"The original plaintext is : \" << plainText << \"\\n\\n\";\n std::cout << \"The left and right alphabets after each permutation during encryption are :\\n\";\n auto cipherText = exec(plainText, Mode::ENCRYPT, true);\n std::cout << \"\\nThe ciphertext is : \" << cipherText << '\\n';\n auto plainText2 = exec(cipherText, Mode::DECRYPT);\n std::cout << \"\\nThe recovered plaintext is : \" << plainText2 << '\\n';\n\n return 0;\n}"} -{"title": "Chaocipher", "language": "JavaScript from C", "task": "Description:\nThe Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.\n\nThe algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.\n\n\n;Task:\nCode the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.\n\n", "solution": "const L_ALPHABET = \"HXUCZVAMDSLKPEFJRIGTWOBNYQ\";\nconst R_ALPHABET = \"PTLNBQDEOYSFAVZKGJRIHWXUMC\";\n\nconst ENCRYPT = 0;\nconst DECRYPT = 1;\n\nfunction setCharAt(str, index, chr) {\n if (index > str.length - 1) return str;\n return str.substr(0, index) + chr + str.substr(index + 1);\n}\n\nfunction chao(text, mode, show_steps) {\n var left = L_ALPHABET;\n var right = R_ALPHABET;\n var out = text;\n var temp = \"01234567890123456789012345\";\n var i = 0;\n var index, j, store;\n\n if (show_steps) {\n console.log(\"The left and right alphabets after each permutation during encryption are :\");\n }\n while (i < text.length) {\n if (show_steps) {\n console.log(left + \" \" + right);\n }\n if (mode == ENCRYPT) {\n index = right.indexOf(text[i]);\n out = setCharAt(out, i, left[index]);\n } else {\n index = left.indexOf(text[i]);\n out = setCharAt(out, i, right[index]);\n }\n if (i == text.length - 1) {\n break;\n }\n\n //permute left\n j = index;\n while (j < 26) {\n temp = setCharAt(temp, j - index, left[j])\n j += 1;\n }\n j = 0;\n while (j < index) {\n temp = setCharAt(temp, 26 - index + j, left[j]);\n j += 1;\n }\n store = temp[1];\n j = 2;\n while (j < 14) {\n temp = setCharAt(temp, j - 1, temp[j]);\n j += 1;\n }\n temp = setCharAt(temp, 13, store);\n left = temp;\n\n //permute right\n j = index;\n while (j < 26) {\n temp = setCharAt(temp, j - index, right[j]);\n j += 1;\n }\n j = 0;\n while (j < index) {\n temp = setCharAt(temp, 26 - index + j, right[j]);\n j += 1;\n }\n store = temp[0];\n j = 1;\n while (j < 26) {\n temp = setCharAt(temp, j - 1, temp[j]);\n j += 1;\n }\n temp = setCharAt(temp, 25, store);\n store = temp[2];\n j = 3;\n while (j < 14) {\n temp = setCharAt(temp, j - 1, temp[j]);\n j += 1;\n }\n temp = setCharAt(temp, 13, store);\n right = temp;\n\n i += 1;\n }\n\n return out;\n}\n\nfunction main() {\n var out = document.getElementById(\"content\");\n const plain_text = \"WELLDONEISBETTERTHANWELLSAID\";\n\n out.innerHTML = \"

The original plaintext is : \" + plain_text + \"

\";\n var cipher_text = chao(plain_text, ENCRYPT, true);\n out.innerHTML += \"

The ciphertext is : \" + cipher_text + \"

\";\n var decipher_text = chao(cipher_text, DECRYPT, false);\n out.innerHTML += \"

The recovered plaintext is : \" + decipher_text + \"

\";\n}"} -{"title": "Chaocipher", "language": "Python", "task": "Description:\nThe Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.\n\nThe algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.\n\n\n;Task:\nCode the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.\n\n", "solution": "# Python3 implementation of Chaocipher \n# left wheel = ciphertext wheel\n# right wheel = plaintext wheel\n\ndef main():\n # letters only! makealpha(key) helps generate lalpha/ralpha. \n lalpha = \"HXUCZVAMDSLKPEFJRIGTWOBNYQ\"\n ralpha = \"PTLNBQDEOYSFAVZKGJRIHWXUMC\"\n msg = \"WELLDONEISBETTERTHANWELLSAID\"\n\n print(\"L:\", lalpha)\n print(\"R:\", ralpha)\n print(\"I:\", msg)\n print(\"O:\", do_chao(msg, lalpha, ralpha, 1, 0), \"\\n\")\n \n do_chao(msg, lalpha, ralpha, 1, 1)\n\ndef do_chao(msg, lalpha, ralpha, en=1, show=0):\n msg = correct_case(msg)\n out = \"\" \n if show:\n print(\"=\"*54) \n print(10*\" \" + \"left:\" + 21*\" \" + \"right: \")\n print(\"=\"*54) \n print(lalpha, ralpha, \"\\n\")\n for L in msg:\n if en:\n lalpha, ralpha = rotate_wheels(lalpha, ralpha, L)\n out += lalpha[0]\n else:\n ralpha, lalpha = rotate_wheels(ralpha, lalpha, L)\n out += ralpha[0]\n lalpha, ralpha = scramble_wheels(lalpha, ralpha)\n if show:\n print(lalpha, ralpha) \n return out\n \ndef makealpha(key=\"\"):\n alpha = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n z = set()\n key = [x.upper() for x in (key + alpha[::-1])\n if not (x.upper() in z or z.add(x.upper()))]\n return \"\".join(key)\n\ndef correct_case(string):\n return \"\".join([s.upper() for s in string if s.isalpha()])\n\ndef permu(alp, num):\n alp = alp[:num], alp[num:]\n return \"\".join(alp[::-1])\n\ndef rotate_wheels(lalph, ralph, key):\n newin = ralph.index(key)\n return permu(lalph, newin), permu(ralph, newin) \n\ndef scramble_wheels(lalph, ralph):\n # LEFT = cipher wheel \n # Cycle second[1] through nadir[14] forward\n lalph = list(lalph)\n lalph = \"\".join([*lalph[0],\n *lalph[2:14],\n lalph[1],\n *lalph[14:]])\n \n # RIGHT = plain wheel \n # Send the zenith[0] character to the end[25],\n # cycle third[2] through nadir[14] characters forward\n ralph = list(ralph)\n ralph = \"\".join([*ralph[1:3],\n *ralph[4:15],\n ralph[3],\n *ralph[15:],\n ralph[0]])\n return lalph, ralph\n\nmain()"} -{"title": "Chaocipher", "language": "Python 3.7", "task": "Description:\nThe Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.\n\nThe algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.\n\n\n;Task:\nCode the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.\n\n", "solution": "'''Chaocipher'''\n\nfrom itertools import chain, cycle, islice\n\n\n# chao :: String -> String -> Bool -> String -> String\ndef chao(l):\n '''Chaocipher encoding or decoding for the given\n left and right 'wheels'.\n A ciphertext is returned if the boolean flag\n is True, and a plaintext if the flag is False.\n '''\n def go(l, r, plain, xxs):\n if xxs:\n (src, dst) = (l, r) if plain else (r, l)\n (x, xs) = (xxs[0], xxs[1:])\n\n def chaoProcess(n):\n return [dst[n]] + go(\n shifted(1)(14)(rotated(n, l)),\n compose(shifted(2)(14))(shifted(0)(26))(\n rotated(n, r)\n ),\n plain,\n xs\n )\n\n return maybe('')(chaoProcess)(\n elemIndex(x)(src)\n )\n else:\n return []\n return lambda r: lambda plain: lambda xxs: concat(go(\n l, r, plain, xxs\n ))\n\n\n# rotated :: Int -> [a] -> [a]\ndef rotated(z, s):\n '''Rotation of string s by z characters.'''\n return take(len(s))(\n drop(z)(\n cycle(s)\n )\n )\n\n\n# shifted :: Int -> Int -> [a] -> [a]\ndef shifted(src):\n '''The string s with a set of its characters cyclically\n shifted from a source index to a destination index.\n '''\n def go(dst, s):\n (a, b) = splitAt(dst)(s)\n (x, y) = splitAt(src)(a)\n return concat([x, rotated(1, y), b])\n return lambda dst: lambda s: go(dst, s)\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Print the plain text, followed by\n a corresponding cipher text,\n and a decode of that cipher text.\n '''\n chaoWheels = chao(\n \"HXUCZVAMDSLKPEFJRIGTWOBNYQ\"\n )(\n \"PTLNBQDEOYSFAVZKGJRIHWXUMC\"\n )\n plainText = \"WELLDONEISBETTERTHANWELLSAID\"\n cipherText = chaoWheels(False)(plainText)\n\n print(plainText)\n print(cipherText)\n print(\n chaoWheels(True)(cipherText)\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# 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# concat :: [[a]] -> [a]\n# concat :: [String] -> String\ndef concat(xs):\n '''The concatenation of all the elements\n in a list or iterable.\n '''\n def f(ys):\n zs = list(chain(*ys))\n return ''.join(zs) if isinstance(ys[0], str) else zs\n\n return (\n f(xs) if isinstance(xs, list) else (\n chain.from_iterable(xs)\n )\n ) if xs else []\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 '''\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# elemIndex :: Eq a => a -> [a] -> Maybe Int\ndef elemIndex(x):\n '''Just the index of the first element in xs\n which is equal to x,\n or Nothing if there is no such element.\n '''\n def go(xs):\n try:\n return Just(xs.index(x))\n except ValueError:\n return Nothing()\n return lambda xs: go(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 None is m or m.get('Nothing') else (\n f(m.get('Just'))\n )\n\n\n# splitAt :: Int -> [a] -> ([a], [a])\ndef splitAt(n):\n '''A tuple pairing the prefix of length n\n with the rest of xs.\n '''\n return lambda xs: (xs[0:n], xs[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# MAIN ---\nif __name__ == '__main__':\n main()"} -{"title": "Chaos game", "language": "C", "task": "The Chaos Game is a method of generating the attractor of an iterated function system (IFS). \n\nOne of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.\n\n\n;Task\nPlay the Chaos Game using the corners of an equilateral triangle as the reference points. Add a starting point at random (preferably inside the triangle). Then add the next point halfway between the starting point and one of the reference points. This reference point is chosen at random.\n\nAfter a sufficient number of iterations, the image of a Sierpinski Triangle should emerge.\n\n\n;See also\n* The Game of Chaos\n\n", "solution": "#include\n#include\n#include\n#include\n#include\n\n#define pi M_PI\n\nint main(){\n\t\n\ttime_t t;\n\tdouble side, vertices[3][3],seedX,seedY,windowSide;\n\tint i,iter,choice;\n\t\n\tprintf(\"Enter triangle side length : \");\n\tscanf(\"%lf\",&side);\n\t\n\tprintf(\"Enter number of iterations : \");\n\tscanf(\"%d\",&iter);\n\t\n\twindowSide = 10 + 2*side;\n\n\tinitwindow(windowSide,windowSide,\"Sierpinski Chaos\");\n\t\n\tfor(i=0;i<3;i++){\n\t\tvertices[i][0] = windowSide/2 + side*cos(i*2*pi/3);\n\t\tvertices[i][1] = windowSide/2 + side*sin(i*2*pi/3);\n\t\tputpixel(vertices[i][0],vertices[i][1],15);\n\t}\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tseedX = rand()%(int)(vertices[0][0]/2 + (vertices[1][0] + vertices[2][0])/4);\n\tseedY = rand()%(int)(vertices[0][1]/2 + (vertices[1][1] + vertices[2][1])/4);\n\t\n\tputpixel(seedX,seedY,15);\n\t\n\tfor(i=0;i\n#include \n#include \n#include \n \nconst int BMP_SIZE = 600;\n\nclass myBitmap {\npublic:\n myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n ~myBitmap() {\n DeleteObject( pen ); DeleteObject( brush );\n DeleteDC( hdc ); DeleteObject( bmp );\n }\n bool create( int w, int h ) {\n BITMAPINFO bi;\n ZeroMemory( &bi, sizeof( bi ) );\n bi.bmiHeader.biSize = sizeof( bi.bmiHeader );\n bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n bi.bmiHeader.biCompression = BI_RGB;\n bi.bmiHeader.biPlanes = 1;\n bi.bmiHeader.biWidth = w;\n bi.bmiHeader.biHeight = -h;\n \n HDC dc = GetDC( GetConsoleWindow() );\n bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n if( !bmp ) return false;\n \n hdc = CreateCompatibleDC( dc );\n SelectObject( hdc, bmp );\n ReleaseDC( GetConsoleWindow(), dc );\n \n width = w; height = h;\n return true;\n }\n void clear( BYTE clr = 0 ) {\n memset( pBits, clr, width * height * sizeof( DWORD ) );\n }\n void setBrushColor( DWORD bClr ) {\n if( brush ) DeleteObject( brush );\n brush = CreateSolidBrush( bClr );\n SelectObject( hdc, brush );\n }\n void setPenColor( DWORD c ) {\n clr = c; createPen();\n }\n void setPenWidth( int w ) {\n wid = w; createPen();\n }\n void saveBitmap( std::string path ) {\n BITMAPFILEHEADER fileheader;\n BITMAPINFO infoheader;\n BITMAP bitmap;\n DWORD wb;\n \n GetObject( bmp, sizeof( bitmap ), &bitmap );\n DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n \n ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n \n infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n infoheader.bmiHeader.biCompression = BI_RGB;\n infoheader.bmiHeader.biPlanes = 1;\n infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n \n fileheader.bfType = 0x4D42;\n fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n \n GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n \n HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n CloseHandle( file );\n \n delete [] dwpBits;\n }\n HDC getDC() const { return hdc; }\n int getWidth() const { return width; }\n int getHeight() const { return height; }\nprivate:\n void createPen() {\n if( pen ) DeleteObject( pen );\n pen = CreatePen( PS_SOLID, wid, clr );\n SelectObject( hdc, pen );\n }\n HBITMAP bmp; HDC hdc;\n HPEN pen; HBRUSH brush;\n void *pBits; int width, height, wid;\n DWORD clr;\n};\nclass chaos {\npublic:\n void start() {\n POINT org;\n fillPts(); initialPoint( org ); initColors();\n int cnt = 0, i;\n bmp.create( BMP_SIZE, BMP_SIZE );\n bmp.clear( 255 );\n\n while( cnt++ < 1000000 ) {\n switch( rand() % 6 ) {\n case 0: case 3: i = 0; break;\n case 1: case 5: i = 1; break;\n case 2: case 4: i = 2;\n }\n setPoint( org, myPoints[i], i );\n }\n // --- edit this path --- //\n bmp.saveBitmap( \"F:/st.bmp\" );\n }\nprivate:\n void setPoint( POINT &o, POINT v, int i ) {\n POINT z;\n o.x = ( o.x + v.x ) >> 1; o.y = ( o.y + v.y ) >> 1;\n SetPixel( bmp.getDC(), o.x, o.y, colors[i] );\n }\n void fillPts() {\n int a = BMP_SIZE - 1;\n myPoints[0].x = BMP_SIZE >> 1; myPoints[0].y = 0;\n myPoints[1].x = 0; myPoints[1].y = myPoints[2].x = myPoints[2].y = a;\n }\n void initialPoint( POINT& p ) {\n p.x = ( BMP_SIZE >> 1 ) + rand() % 2 ? rand() % 30 + 10 : -( rand() % 30 + 10 );\n p.y = ( BMP_SIZE >> 1 ) + rand() % 2 ? rand() % 30 + 10 : -( rand() % 30 + 10 );\n }\n void initColors() {\n colors[0] = RGB( 255, 0, 0 );\n colors[1] = RGB( 0, 255, 0 );\n colors[2] = RGB( 0, 0, 255 );\n }\n \n myBitmap bmp;\n POINT myPoints[3];\n COLORREF colors[3];\n};\nint main( int argc, char* argv[] ) {\n srand( ( unsigned )time( 0 ) );\n chaos c; c.start();\n return 0;\n}\n"} -{"title": "Chaos game", "language": "JavaScript", "task": "The Chaos Game is a method of generating the attractor of an iterated function system (IFS). \n\nOne of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.\n\n\n;Task\nPlay the Chaos Game using the corners of an equilateral triangle as the reference points. Add a starting point at random (preferably inside the triangle). Then add the next point halfway between the starting point and one of the reference points. This reference point is chosen at random.\n\nAfter a sufficient number of iterations, the image of a Sierpinski Triangle should emerge.\n\n\n;See also\n* The Game of Chaos\n\n", "solution": "\n\n\n\n\n\nChaos Game\n\n\n\n\n\n

\n\n

\n\n

\n\n

\n\n\n\n\n\n"} -{"title": "Chaos game", "language": "Python", "task": "The Chaos Game is a method of generating the attractor of an iterated function system (IFS). \n\nOne of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.\n\n\n;Task\nPlay the Chaos Game using the corners of an equilateral triangle as the reference points. Add a starting point at random (preferably inside the triangle). Then add the next point halfway between the starting point and one of the reference points. This reference point is chosen at random.\n\nAfter a sufficient number of iterations, the image of a Sierpinski Triangle should emerge.\n\n\n;See also\n* The Game of Chaos\n\n", "solution": "import argparse\nimport random\nimport shapely.geometry as geometry\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\n\ndef main(args):\n # Styles\n plt.style.use(\"ggplot\")\n\n # Creating figure\n fig = plt.figure()\n line, = plt.plot([], [], \".\")\n\n # Limit axes\n plt.xlim(0, 1)\n plt.ylim(0, 1)\n\n # Titles\n title = \"Chaos Game\"\n plt.title(title)\n fig.canvas.set_window_title(title)\n\n # Getting data\n data = get_data(args.frames)\n\n # Creating animation\n line_ani = animation.FuncAnimation(\n fig=fig,\n func=update_line,\n frames=args.frames,\n fargs=(data, line),\n interval=args.interval,\n repeat=False\n )\n\n # To save the animation install ffmpeg and uncomment\n # line_ani.save(\"chaos_game.gif\")\n\n plt.show()\n\n\ndef get_data(n):\n \"\"\"\n Get data to plot\n \"\"\"\n leg = 1\n triangle = get_triangle(leg)\n cur_point = gen_point_within_poly(triangle)\n data = []\n for _ in range(n):\n data.append((cur_point.x, cur_point.y))\n cur_point = next_point(triangle, cur_point)\n return data\n\n\ndef get_triangle(n):\n \"\"\"\n Create right triangle\n \"\"\"\n ax = ay = 0.0\n a = ax, ay\n\n bx = 0.5 * n\n by = 0.75 * (n ** 2)\n b = bx, by\n\n cx = n\n cy = 0.0\n c = cx, cy\n\n triangle = geometry.Polygon([a, b, c])\n return triangle\n\n\ndef gen_point_within_poly(poly):\n \"\"\"\n Generate random point inside given polygon\n \"\"\"\n minx, miny, maxx, maxy = poly.bounds\n while True:\n x = random.uniform(minx, maxx)\n y = random.uniform(miny, maxy)\n point = geometry.Point(x, y)\n if point.within(poly):\n return point\n\n\ndef next_point(poly, point):\n \"\"\"\n Generate next point according to chaos game rules\n \"\"\"\n vertices = poly.boundary.coords[:-1] # Last point is the same as the first one\n random_vertex = geometry.Point(random.choice(vertices))\n line = geometry.linestring.LineString([point, random_vertex])\n return line.centroid\n\n\ndef update_line(num, data, line):\n \"\"\"\n Update line with new points\n \"\"\"\n new_data = zip(*data[:num]) or [(), ()]\n line.set_data(new_data)\n return line,\n\n\nif __name__ == \"__main__\":\n arg_parser = argparse.ArgumentParser(description=\"Chaos Game by Suenweek (c) 2017\")\n arg_parser.add_argument(\"-f\", dest=\"frames\", type=int, default=1000)\n arg_parser.add_argument(\"-i\", dest=\"interval\", type=int, default=10)\n\n main(arg_parser.parse_args())\n\n"} -{"title": "Check Machin-like formulas", "language": "Python", "task": "Machin-like formulas are useful for efficiently computing numerical approximations for \\pi\n\n\n;Task:\nVerify the following Machin-like formulas are correct by calculating the value of '''tan''' (''right hand side)'' for each equation using exact arithmetic and showing they equal '''1''':\n\n: {\\pi\\over4} = \\arctan{1\\over2} + \\arctan{1\\over3} \n: {\\pi\\over4} = 2 \\arctan{1\\over3} + \\arctan{1\\over7}\n: {\\pi\\over4} = 4 \\arctan{1\\over5} - \\arctan{1\\over239}\n: {\\pi\\over4} = 5 \\arctan{1\\over7} + 2 \\arctan{3\\over79}\n: {\\pi\\over4} = 5 \\arctan{29\\over278} + 7 \\arctan{3\\over79}\n: {\\pi\\over4} = \\arctan{1\\over2} + \\arctan{1\\over5} + \\arctan{1\\over8} \n: {\\pi\\over4} = 4 \\arctan{1\\over5} - \\arctan{1\\over70} + \\arctan{1\\over99} \n: {\\pi\\over4} = 5 \\arctan{1\\over7} + 4 \\arctan{1\\over53} + 2 \\arctan{1\\over4443}\n: {\\pi\\over4} = 6 \\arctan{1\\over8} + 2 \\arctan{1\\over57} + \\arctan{1\\over239}\n: {\\pi\\over4} = 8 \\arctan{1\\over10} - \\arctan{1\\over239} - 4 \\arctan{1\\over515}\n: {\\pi\\over4} = 12 \\arctan{1\\over18} + 8 \\arctan{1\\over57} - 5 \\arctan{1\\over239}\n: {\\pi\\over4} = 16 \\arctan{1\\over21} + 3 \\arctan{1\\over239} + 4 \\arctan{3\\over1042}\n: {\\pi\\over4} = 22 \\arctan{1\\over28} + 2 \\arctan{1\\over443} - 5 \\arctan{1\\over1393} - 10 \\arctan{1\\over11018}\n: {\\pi\\over4} = 22 \\arctan{1\\over38} + 17 \\arctan{7\\over601} + 10 \\arctan{7\\over8149}\n: {\\pi\\over4} = 44 \\arctan{1\\over57} + 7 \\arctan{1\\over239} - 12 \\arctan{1\\over682} + 24 \\arctan{1\\over12943}\n: {\\pi\\over4} = 88 \\arctan{1\\over172} + 51 \\arctan{1\\over239} + 32 \\arctan{1\\over682} + 44 \\arctan{1\\over5357} + 68 \\arctan{1\\over12943}\n\nand confirm that the following formula is ''incorrect'' by showing '''tan''' (''right hand side)'' is ''not'' '''1''':\n\n: {\\pi\\over4} = 88 \\arctan{1\\over172} + 51 \\arctan{1\\over239} + 32 \\arctan{1\\over682} + 44 \\arctan{1\\over5357} + 68 \\arctan{1\\over12944}\n\nThese identities are useful in calculating the values:\n: \\tan(a + b) = {\\tan(a) + \\tan(b) \\over 1 - \\tan(a) \\tan(b)}\n\n: \\tan\\left(\\arctan{a \\over b}\\right) = {a \\over b}\n\n: \\tan(-a) = -\\tan(a)\n\nYou can store the equations in any convenient data structure, but for extra credit parse them from human-readable text input.\n\nNote: to formally prove the formula correct, it would have to be shown that ''{-3 pi \\over 4} < right hand side < {5 pi \\over 4}'' due to ''\\tan()'' periodicity.\n\n\n", "solution": "import re\nfrom fractions import Fraction\nfrom pprint import pprint as pp\n\n\nequationtext = '''\\\n pi/4 = arctan(1/2) + arctan(1/3) \n pi/4 = 2*arctan(1/3) + arctan(1/7)\n pi/4 = 4*arctan(1/5) - arctan(1/239)\n pi/4 = 5*arctan(1/7) + 2*arctan(3/79)\n pi/4 = 5*arctan(29/278) + 7*arctan(3/79)\n pi/4 = arctan(1/2) + arctan(1/5) + arctan(1/8) \n pi/4 = 4*arctan(1/5) - arctan(1/70) + arctan(1/99) \n pi/4 = 5*arctan(1/7) + 4*arctan(1/53) + 2*arctan(1/4443)\n pi/4 = 6*arctan(1/8) + 2*arctan(1/57) + arctan(1/239)\n pi/4 = 8*arctan(1/10) - arctan(1/239) - 4*arctan(1/515)\n pi/4 = 12*arctan(1/18) + 8*arctan(1/57) - 5*arctan(1/239)\n pi/4 = 16*arctan(1/21) + 3*arctan(1/239) + 4*arctan(3/1042)\n pi/4 = 22*arctan(1/28) + 2*arctan(1/443) - 5*arctan(1/1393) - 10*arctan(1/11018)\n pi/4 = 22*arctan(1/38) + 17*arctan(7/601) + 10*arctan(7/8149)\n pi/4 = 44*arctan(1/57) + 7*arctan(1/239) - 12*arctan(1/682) + 24*arctan(1/12943)\n pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12943)\n pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12944)\n'''\n\ndef parse_eqn(equationtext=equationtext):\n eqn_re = re.compile(r\"\"\"(?mx)\n (?P ^ \\s* pi/4 \\s* = \\s*)? # LHS of equation\n (?: # RHS\n \\s* (?P [+-])? \\s* \n (?: (?P \\d+) \\s* \\*)? \n \\s* arctan\\( (?P \\d+) / (?P \\d+)\n )\"\"\")\n\n found = eqn_re.findall(equationtext)\n machins, part = [], []\n for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext):\n if lhs and part:\n machins.append(part)\n part = []\n part.append( ( (-1 if sign == '-' else 1) * ( int(mult) if mult else 1),\n Fraction(int(numer), (int(denom) if denom else 1)) ) )\n machins.append(part)\n return machins\n\n\ndef tans(xs):\n xslen = len(xs)\n if xslen == 1:\n return tanEval(*xs[0])\n aa, bb = xs[:xslen//2], xs[xslen//2:]\n a, b = tans(aa), tans(bb)\n return (a + b) / (1 - a * b)\n\ndef tanEval(coef, f):\n if coef == 1:\n return f\n if coef < 0:\n return -tanEval(-coef, f)\n ca = coef // 2\n cb = coef - ca\n a, b = tanEval(ca, f), tanEval(cb, f)\n return (a + b) / (1 - a * b)\n\n\nif __name__ == '__main__':\n machins = parse_eqn()\n #pp(machins, width=160)\n for machin, eqn in zip(machins, equationtext.split('\\n')):\n ans = tans(machin)\n print('%5s: %s' % ( ('OK' if ans == 1 else 'ERROR'), eqn))"} -{"title": "Check input device is a terminal", "language": "C", "task": "Demonstrate how to check whether the input device is a terminal or not.\n\n\n;Related task:\n* [[Check output device is a terminal]]\n\n", "solution": "#include \t//for isatty()\n#include \t//for fileno()\n\nint main(void)\n{\n\tputs(isatty(fileno(stdin))\n\t\t? \"stdin is tty\"\n\t\t: \"stdin is not tty\");\n\treturn 0;\n}"} -{"title": "Check input device is a terminal", "language": "Python", "task": "Demonstrate how to check whether the input device is a terminal or not.\n\n\n;Related task:\n* [[Check output device is a terminal]]\n\n", "solution": "from sys import stdin\nif stdin.isatty():\n print(\"Input comes from tty.\")\nelse:\n print(\"Input doesn't come from tty.\")"} -{"title": "Check output device is a terminal", "language": "C", "task": "Demonstrate how to check whether the output device is a terminal or not.\n\n\n;Related task:\n* [[Check input device is a terminal]]\n\n", "solution": "#include // for isatty()\n#include // for fileno()\n\nint main()\n{\n puts(isatty(fileno(stdout))\n ? \"stdout is tty\"\n : \"stdout is not tty\");\n return 0;\n}"} -{"title": "Check output device is a terminal", "language": "C++ from C", "task": "Demonstrate how to check whether the output device is a terminal or not.\n\n\n;Related task:\n* [[Check input device is a terminal]]\n\n", "solution": "#if _WIN32\n#include \n#define ISATTY _isatty\n#define FILENO _fileno\n#else\n#include \n#define ISATTY isatty\n#define FILENO fileno\n#endif\n\n#include \n\nint main() {\n if (ISATTY(FILENO(stdout))) {\n std::cout << \"stdout is a tty\\n\";\n } else {\n std::cout << \"stdout is not a tty\\n\";\n }\n\n return 0;\n}"} -{"title": "Check output device is a terminal", "language": "Python", "task": "Demonstrate how to check whether the output device is a terminal or not.\n\n\n;Related task:\n* [[Check input device is a terminal]]\n\n", "solution": "from sys import stdout\nif stdout.isatty():\n print 'The output device is a teletype. Or something like a teletype.'\nelse:\n print 'The output device isn\\'t like a teletype.'"} -{"title": "Cheryl's birthday", "language": "C++ from Go", "task": "Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.\n\nCheryl gave them a list of ten possible dates:\n May 15, May 16, May 19\n June 17, June 18\n July 14, July 16\n August 14, August 15, August 17\n\nCheryl then tells Albert the ''month'' of birth, and Bernard the ''day'' (of the month) of birth.\n 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too.\n 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now.\n 3) Albert: Then I also know when Cheryl's birthday is.\n\n\n;Task\nWrite a computer program to deduce, by successive elimination, Cheryl's birthday.\n\n\n;Related task:\n* [[Sum and Product Puzzle]]\n\n\n;References\n* Wikipedia article of the same name.\n* Tuple Relational Calculus\n\n", "solution": "#include \n#include \n#include \nusing namespace std;\n\nconst vector MONTHS = {\n \"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\",\n \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"\n};\n\nstruct Birthday {\n int month, day;\n\n friend ostream &operator<<(ostream &, const Birthday &);\n};\n\nostream &operator<<(ostream &out, const Birthday &birthday) {\n return out << MONTHS[birthday.month - 1] << ' ' << birthday.day;\n}\n\ntemplate \nbool monthUniqueIn(const Birthday &b, const C &container) {\n auto it = cbegin(container);\n auto end = cend(container);\n int count = 0;\n while (it != end) {\n if (it->month == b.month) {\n count++;\n }\n it = next(it);\n }\n return count == 1;\n}\n\ntemplate \nbool dayUniqueIn(const Birthday &b, const C &container) {\n auto it = cbegin(container);\n auto end = cend(container);\n int count = 0;\n while (it != end) {\n if (it->day == b.day) {\n count++;\n }\n it = next(it);\n }\n return count == 1;\n}\n\ntemplate \nbool monthWithUniqueDayIn(const Birthday &b, const C &container) {\n auto it = cbegin(container);\n auto end = cend(container);\n while (it != end) {\n if (it->month == b.month && dayUniqueIn(*it, container)) {\n return true;\n }\n it = next(it);\n }\n return false;\n}\n\nint main() {\n vector choices = {\n {5, 15}, {5, 16}, {5, 19}, {6, 17}, {6, 18},\n {7, 14}, {7, 16}, {8, 14}, {8, 15}, {8, 17},\n };\n\n // Albert knows the month but doesn't know the day.\n // So the month can't be unique within the choices.\n vector filtered;\n for (auto bd : choices) {\n if (!monthUniqueIn(bd, choices)) {\n filtered.push_back(bd);\n }\n }\n\n // Albert also knows that Bernard doesn't know the answer.\n // So the month can't have a unique day.\n vector filtered2;\n for (auto bd : filtered) {\n if (!monthWithUniqueDayIn(bd, filtered)) {\n filtered2.push_back(bd);\n }\n }\n\n // Bernard now knows the answer.\n // So the day must be unique within the remaining choices.\n vector filtered3;\n for (auto bd : filtered2) {\n if (dayUniqueIn(bd, filtered2)) {\n filtered3.push_back(bd);\n }\n }\n\n // Albert now knows the answer too.\n // So the month must be unique within the remaining choices.\n vector filtered4;\n for (auto bd : filtered3) {\n if (monthUniqueIn(bd, filtered3)) {\n filtered4.push_back(bd);\n }\n }\n\n if (filtered4.size() == 1) {\n cout << \"Cheryl's birthday is \" << filtered4[0] << '\\n';\n } else {\n cout << \"Something went wrong!\\n\";\n }\n\n return 0;\n}"} -{"title": "Cheryl's birthday", "language": "JavaScript", "task": "Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.\n\nCheryl gave them a list of ten possible dates:\n May 15, May 16, May 19\n June 17, June 18\n July 14, July 16\n August 14, August 15, August 17\n\nCheryl then tells Albert the ''month'' of birth, and Bernard the ''day'' (of the month) of birth.\n 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too.\n 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now.\n 3) Albert: Then I also know when Cheryl's birthday is.\n\n\n;Task\nWrite a computer program to deduce, by successive elimination, Cheryl's birthday.\n\n\n;Related task:\n* [[Sum and Product Puzzle]]\n\n\n;References\n* Wikipedia article of the same name.\n* Tuple Relational Calculus\n\n", "solution": "(() => {\n 'use strict';\n\n // main :: IO ()\n const main = () => {\n const\n month = fst,\n day = snd;\n showLog(\n map(x => Array.from(x), (\n\n // The month with only one remaining day,\n\n // (A's month contains only one remaining day)\n // (3 :: A \"Then I also know\")\n uniquePairing(month)(\n\n // among the days with unique months,\n\n // (B's day is paired with only one remaining month)\n // (2 :: B \"I know now\")\n uniquePairing(day)(\n\n // excluding months with unique days,\n\n // (A's month is not among those with unique days)\n // (1 :: A \"I know that Bernard does not know\")\n monthsWithUniqueDays(false)(\n\n // from the given month-day pairs:\n\n // (0 :: Cheryl's list)\n map(x => tupleFromList(words(strip(x))),\n splitOn(/,\\s+/,\n `May 15, May 16, May 19,\n June 17, June 18, July 14, July 16,\n Aug 14, Aug 15, Aug 17`\n )\n )\n )\n )\n )\n ))\n );\n };\n\n // monthsWithUniqueDays :: Bool -> [(Month, Day)] -> [(Month, Day)]\n const monthsWithUniqueDays = blnInclude => xs => {\n const months = map(fst, uniquePairing(snd)(xs));\n return filter(\n md => (blnInclude ? id : not)(\n elem(fst(md), months)\n ),\n xs\n );\n };\n\n // uniquePairing :: ((a, a) -> a) ->\n // -> [(Month, Day)] -> [(Month, Day)]\n const uniquePairing = f => xs =>\n bindPairs(xs,\n md => {\n const\n dct = f(md),\n matches = filter(\n k => 1 === length(dct[k]),\n Object.keys(dct)\n );\n return filter(tpl => elem(f(tpl), matches), xs);\n }\n );\n\n // bindPairs :: [(Month, Day)] -> (Dict, Dict) -> [(Month, Day)]\n const bindPairs = (xs, f) => f(\n Tuple(\n dictFromPairs(fst)(snd)(xs),\n dictFromPairs(snd)(fst)(xs)\n )\n );\n\n // dictFromPairs :: ((a, a) -> a) -> ((a, a) -> a) -> [(a, a)] -> Dict\n const dictFromPairs = f => g => xs =>\n foldl((a, tpl) => Object.assign(\n a, {\n [f(tpl)]: (a[f(tpl)] || []).concat(g(tpl).toString())\n }\n ), {}, xs);\n\n\n // GENERIC ABSTRACTIONS -------------------------------\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 // elem :: Eq a => a -> [a] -> Bool\n const elem = (x, xs) => xs.includes(x);\n\n // filter :: (a -> Bool) -> [a] -> [a]\n const filter = (f, xs) => xs.filter(f);\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 // id :: a -> a\n const id = x => x;\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 // not :: Bool -> Bool\n const not = b => !b;\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 // splitOn :: String -> String -> [String]\n const splitOn = (pat, src) =>\n src.split(pat);\n\n // strip :: String -> String\n const strip = s => s.trim();\n\n // tupleFromList :: [a] -> (a, a ...)\n const tupleFromList = xs =>\n TupleN.apply(null, xs);\n\n // TupleN :: a -> b ... -> (a, b ... )\n function TupleN() {\n const\n args = Array.from(arguments),\n lng = args.length;\n return lng > 1 ? Object.assign(\n args.reduce((a, x, i) => Object.assign(a, {\n [i]: x\n }), {\n type: 'Tuple' + (2 < lng ? lng.toString() : ''),\n length: lng\n })\n ) : args[0];\n };\n\n // words :: String -> [String]\n const words = s => s.split(/\\s+/);\n\n // MAIN ---\n return main();\n})();"} -{"title": "Cheryl's birthday", "language": "Python 3", "task": "Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.\n\nCheryl gave them a list of ten possible dates:\n May 15, May 16, May 19\n June 17, June 18\n July 14, July 16\n August 14, August 15, August 17\n\nCheryl then tells Albert the ''month'' of birth, and Bernard the ''day'' (of the month) of birth.\n 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too.\n 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now.\n 3) Albert: Then I also know when Cheryl's birthday is.\n\n\n;Task\nWrite a computer program to deduce, by successive elimination, Cheryl's birthday.\n\n\n;Related task:\n* [[Sum and Product Puzzle]]\n\n\n;References\n* Wikipedia article of the same name.\n* Tuple Relational Calculus\n\n", "solution": "'''Cheryl's Birthday'''\n\nfrom itertools import groupby\nfrom re import split\n\n\n# main :: IO ()\ndef main():\n '''Derivation of the date.'''\n\n month, day = 0, 1\n print(\n # (3 :: A \"Then I also know\")\n # (A's month contains only one remaining day)\n uniquePairing(month)(\n # (2 :: B \"I know now\")\n # (B's day is paired with only one remaining month)\n uniquePairing(day)(\n # (1 :: A \"I know that Bernard does not know\")\n # (A's month is not among those with unique days)\n monthsWithUniqueDays(False)([\n # 0 :: Cheryl's list:\n tuple(x.split()) for x in\n split(\n ', ',\n 'May 15, May 16, May 19, ' +\n 'June 17, June 18, ' +\n 'July 14, July 16, ' +\n 'Aug 14, Aug 15, Aug 17'\n )\n ])\n )\n )\n )\n\n\n# ------------------- QUERY FUNCTIONS --------------------\n\n# monthsWithUniqueDays :: Bool -> [(Month, Day)] -> [(Month, Day)]\ndef monthsWithUniqueDays(blnInclude):\n '''The subset of months with (or without) unique days.\n '''\n def go(xs):\n month, day = 0, 1\n months = [fst(x) for x in uniquePairing(day)(xs)]\n return [\n md for md in xs\n if blnInclude or not (md[month] in months)\n ]\n return go\n\n\n# uniquePairing :: DatePart -> [(Month, Day)] -> [(Month, Day)]\ndef uniquePairing(i):\n '''Subset of months (or days) with a unique intersection.\n '''\n def go(xs):\n def inner(md):\n dct = md[i]\n uniques = [\n k for k in dct.keys()\n if 1 == len(dct[k])\n ]\n return [tpl for tpl in xs if tpl[i] in uniques]\n return inner\n return ap(bindPairs)(go)\n\n\n# bindPairs :: [(Month, Day)] ->\n# ((Dict String [String], Dict String [String])\n# -> [(Month, Day)]) -> [(Month, Day)]\ndef bindPairs(xs):\n '''List monad injection operator for lists\n of (Month, Day) pairs.\n '''\n return lambda f: f(\n (\n dictFromPairs(xs),\n dictFromPairs(\n [(b, a) for (a, b) in xs]\n )\n )\n )\n\n\n# dictFromPairs :: [(Month, Day)] -> Dict Text [Text]\ndef dictFromPairs(xs):\n '''A dictionary derived from a list of\n month day pairs.\n '''\n return {\n k: [snd(x) for x in m] for k, m in groupby(\n sorted(xs, key=fst), key=fst\n )\n }\n\n\n# ----------------------- GENERIC ------------------------\n\n# ap :: (a -> b -> c) -> (a -> b) -> a -> c\ndef ap(f):\n '''Applicative instance for functions.\n '''\n def go(g):\n def fxgx(x):\n return f(x)(\n g(x)\n )\n return fxgx\n return go\n\n\n# fst :: (a, b) -> a\ndef fst(tpl):\n '''First component of a pair.\n '''\n return tpl[0]\n\n\n# snd :: (a, b) -> b\ndef snd(tpl):\n '''Second component of a pair.\n '''\n return tpl[1]\n\n\nif __name__ == '__main__':\n main()"} -{"title": "Chinese remainder theorem", "language": "C", "task": "Suppose n_1, n_2, \\ldots, n_k are positive [[integer]]s that are pairwise co-prime. \n\nThen, for any given sequence of integers a_1, a_2, \\dots, a_k, there exists an integer x solving the following system of simultaneous congruences:\n\n::: \\begin{align}\n x &\\equiv a_1 \\pmod{n_1} \\\\\n x &\\equiv a_2 \\pmod{n_2} \\\\\n &{}\\ \\ \\vdots \\\\\n x &\\equiv a_k \\pmod{n_k}\n\\end{align}\n\nFurthermore, all solutions x of this system are congruent modulo the product, N=n_1n_2\\ldots n_k.\n\n\n;Task:\nWrite a program to solve a system of linear congruences by applying the Chinese Remainder Theorem. \n\nIf the system of equations cannot be solved, your program must somehow indicate this. \n\n(It may throw an exception or return a special false value.) \n\nSince there are infinitely many solutions, the program should return the unique solution s where 0 \\leq s \\leq n_1n_2\\ldots n_k.\n\n\n''Show the functionality of this program'' by printing the result such that the n's are [3,5,7] and the a's are [2,3,2].\n\n\n'''Algorithm''': The following algorithm only applies if the n_i's are pairwise co-prime. \n\nSuppose, as above, that a solution is required for the system of congruences:\n\n::: x \\equiv a_i \\pmod{n_i} \\quad\\mathrm{for}\\; i = 1, \\ldots, k\n\nAgain, to begin, the product N = n_1n_2 \\ldots n_k is defined. \n\nThen a solution x can be found as follows:\n\nFor each i, the integers n_i and N/n_i are co-prime. \n\nUsing the Extended Euclidean algorithm, we can find integers r_i and s_i such that r_i n_i + s_i N/n_i = 1. \n\nThen, one solution to the system of simultaneous congruences is:\n\n::: x = \\sum_{i=1}^k a_i s_i N/n_i\n\nand the minimal solution,\n\n::: x \\pmod{N}.\n\n", "solution": "#include \n\n// returns x where (a * x) % b == 1\nint mul_inv(int a, int b)\n{\n\tint b0 = b, t, q;\n\tint x0 = 0, x1 = 1;\n\tif (b == 1) return 1;\n\twhile (a > 1) {\n\t\tq = a / b;\n\t\tt = b, b = a % b, a = t;\n\t\tt = x0, x0 = x1 - q * x0, x1 = t;\n\t}\n\tif (x1 < 0) x1 += b0;\n\treturn x1;\n}\n\nint chinese_remainder(int *n, int *a, int len)\n{\n\tint p, i, prod = 1, sum = 0;\n\n\tfor (i = 0; i < len; i++) prod *= n[i];\n\n\tfor (i = 0; i < len; i++) {\n\t\tp = prod / n[i];\n\t\tsum += a[i] * mul_inv(p, n[i]) * p;\n\t}\n\n\treturn sum % prod;\n}\n\nint main(void)\n{\n\tint n[] = { 3, 5, 7 };\n\tint a[] = { 2, 3, 2 };\n\n\tprintf(\"%d\\n\", chinese_remainder(n, a, sizeof(n)/sizeof(n[0])));\n\treturn 0;\n}"} -{"title": "Chinese remainder theorem", "language": "C++", "task": "Suppose n_1, n_2, \\ldots, n_k are positive [[integer]]s that are pairwise co-prime. \n\nThen, for any given sequence of integers a_1, a_2, \\dots, a_k, there exists an integer x solving the following system of simultaneous congruences:\n\n::: \\begin{align}\n x &\\equiv a_1 \\pmod{n_1} \\\\\n x &\\equiv a_2 \\pmod{n_2} \\\\\n &{}\\ \\ \\vdots \\\\\n x &\\equiv a_k \\pmod{n_k}\n\\end{align}\n\nFurthermore, all solutions x of this system are congruent modulo the product, N=n_1n_2\\ldots n_k.\n\n\n;Task:\nWrite a program to solve a system of linear congruences by applying the Chinese Remainder Theorem. \n\nIf the system of equations cannot be solved, your program must somehow indicate this. \n\n(It may throw an exception or return a special false value.) \n\nSince there are infinitely many solutions, the program should return the unique solution s where 0 \\leq s \\leq n_1n_2\\ldots n_k.\n\n\n''Show the functionality of this program'' by printing the result such that the n's are [3,5,7] and the a's are [2,3,2].\n\n\n'''Algorithm''': The following algorithm only applies if the n_i's are pairwise co-prime. \n\nSuppose, as above, that a solution is required for the system of congruences:\n\n::: x \\equiv a_i \\pmod{n_i} \\quad\\mathrm{for}\\; i = 1, \\ldots, k\n\nAgain, to begin, the product N = n_1n_2 \\ldots n_k is defined. \n\nThen a solution x can be found as follows:\n\nFor each i, the integers n_i and N/n_i are co-prime. \n\nUsing the Extended Euclidean algorithm, we can find integers r_i and s_i such that r_i n_i + s_i N/n_i = 1. \n\nThen, one solution to the system of simultaneous congruences is:\n\n::: x = \\sum_{i=1}^k a_i s_i N/n_i\n\nand the minimal solution,\n\n::: x \\pmod{N}.\n\n", "solution": "// Requires C++17\n#include \n#include \n#include \n#include \n\ntemplate _Ty mulInv(_Ty a, _Ty b) {\n\t_Ty b0 = b;\n\t_Ty x0 = 0;\n\t_Ty x1 = 1;\n\n\tif (b == 1) {\n\t\treturn 1;\n\t}\n\n\twhile (a > 1) {\n\t\t_Ty q = a / b;\n\t\t_Ty amb = a % b;\n\t\ta = b;\n\t\tb = amb;\n\n\t\t_Ty xqx = x1 - q * x0;\n\t\tx1 = x0;\n\t\tx0 = xqx;\n\t}\n\n\tif (x1 < 0) {\n\t\tx1 += b0;\n\t}\n\n\treturn x1;\n}\n\ntemplate _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {\n\t_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });\n\n\t_Ty sm = 0;\n\tfor (int i = 0; i < n.size(); i++) {\n\t\t_Ty p = prod / n[i];\n\t\tsm += a[i] * mulInv(p, n[i]) * p;\n\t}\n\n\treturn sm % prod;\n}\n\nint main() {\n\tvector n = { 3, 5, 7 };\n\tvector a = { 2, 3, 2 };\n \n\tcout << chineseRemainder(n,a) << endl;\n \n\treturn 0;\n}"} -{"title": "Chinese remainder theorem", "language": "JavaScript", "task": "Suppose n_1, n_2, \\ldots, n_k are positive [[integer]]s that are pairwise co-prime. \n\nThen, for any given sequence of integers a_1, a_2, \\dots, a_k, there exists an integer x solving the following system of simultaneous congruences:\n\n::: \\begin{align}\n x &\\equiv a_1 \\pmod{n_1} \\\\\n x &\\equiv a_2 \\pmod{n_2} \\\\\n &{}\\ \\ \\vdots \\\\\n x &\\equiv a_k \\pmod{n_k}\n\\end{align}\n\nFurthermore, all solutions x of this system are congruent modulo the product, N=n_1n_2\\ldots n_k.\n\n\n;Task:\nWrite a program to solve a system of linear congruences by applying the Chinese Remainder Theorem. \n\nIf the system of equations cannot be solved, your program must somehow indicate this. \n\n(It may throw an exception or return a special false value.) \n\nSince there are infinitely many solutions, the program should return the unique solution s where 0 \\leq s \\leq n_1n_2\\ldots n_k.\n\n\n''Show the functionality of this program'' by printing the result such that the n's are [3,5,7] and the a's are [2,3,2].\n\n\n'''Algorithm''': The following algorithm only applies if the n_i's are pairwise co-prime. \n\nSuppose, as above, that a solution is required for the system of congruences:\n\n::: x \\equiv a_i \\pmod{n_i} \\quad\\mathrm{for}\\; i = 1, \\ldots, k\n\nAgain, to begin, the product N = n_1n_2 \\ldots n_k is defined. \n\nThen a solution x can be found as follows:\n\nFor each i, the integers n_i and N/n_i are co-prime. \n\nUsing the Extended Euclidean algorithm, we can find integers r_i and s_i such that r_i n_i + s_i N/n_i = 1. \n\nThen, one solution to the system of simultaneous congruences is:\n\n::: x = \\sum_{i=1}^k a_i s_i N/n_i\n\nand the minimal solution,\n\n::: x \\pmod{N}.\n\n", "solution": "function crt(num, rem) {\n let sum = 0;\n const prod = num.reduce((a, c) => a * c, 1);\n\n for (let i = 0; i < num.length; i++) {\n const [ni, ri] = [num[i], rem[i]];\n const p = Math.floor(prod / ni);\n sum += ri * p * mulInv(p, ni);\n }\n return sum % prod;\n}\n\nfunction mulInv(a, b) {\n const b0 = b;\n let [x0, x1] = [0, 1];\n\n if (b === 1) {\n return 1;\n }\n while (a > 1) {\n const q = Math.floor(a / b);\n [a, b] = [b, a % b];\n [x0, x1] = [x1 - q * x0, x0];\n }\n if (x1 < 0) {\n x1 += b0;\n }\n return x1;\n}\n\nconsole.log(crt([3,5,7], [2,3,2]))"} -{"title": "Chinese remainder theorem", "language": "Python", "task": "Suppose n_1, n_2, \\ldots, n_k are positive [[integer]]s that are pairwise co-prime. \n\nThen, for any given sequence of integers a_1, a_2, \\dots, a_k, there exists an integer x solving the following system of simultaneous congruences:\n\n::: \\begin{align}\n x &\\equiv a_1 \\pmod{n_1} \\\\\n x &\\equiv a_2 \\pmod{n_2} \\\\\n &{}\\ \\ \\vdots \\\\\n x &\\equiv a_k \\pmod{n_k}\n\\end{align}\n\nFurthermore, all solutions x of this system are congruent modulo the product, N=n_1n_2\\ldots n_k.\n\n\n;Task:\nWrite a program to solve a system of linear congruences by applying the Chinese Remainder Theorem. \n\nIf the system of equations cannot be solved, your program must somehow indicate this. \n\n(It may throw an exception or return a special false value.) \n\nSince there are infinitely many solutions, the program should return the unique solution s where 0 \\leq s \\leq n_1n_2\\ldots n_k.\n\n\n''Show the functionality of this program'' by printing the result such that the n's are [3,5,7] and the a's are [2,3,2].\n\n\n'''Algorithm''': The following algorithm only applies if the n_i's are pairwise co-prime. \n\nSuppose, as above, that a solution is required for the system of congruences:\n\n::: x \\equiv a_i \\pmod{n_i} \\quad\\mathrm{for}\\; i = 1, \\ldots, k\n\nAgain, to begin, the product N = n_1n_2 \\ldots n_k is defined. \n\nThen a solution x can be found as follows:\n\nFor each i, the integers n_i and N/n_i are co-prime. \n\nUsing the Extended Euclidean algorithm, we can find integers r_i and s_i such that r_i n_i + s_i N/n_i = 1. \n\nThen, one solution to the system of simultaneous congruences is:\n\n::: x = \\sum_{i=1}^k a_i s_i N/n_i\n\nand the minimal solution,\n\n::: x \\pmod{N}.\n\n", "solution": "# Python 2.7\ndef chinese_remainder(n, a):\n sum = 0\n prod = reduce(lambda a, b: a*b, n)\n\n for n_i, a_i in zip(n, a):\n p = prod / n_i\n sum += a_i * mul_inv(p, n_i) * p\n return sum % prod\n\n\ndef mul_inv(a, b):\n b0 = b\n x0, x1 = 0, 1\n if b == 1: return 1\n while a > 1:\n q = a / b\n a, b = b, a%b\n x0, x1 = x1 - q * x0, x0\n if x1 < 0: x1 += b0\n return x1\n\nif __name__ == '__main__':\n n = [3, 5, 7]\n a = [2, 3, 2]\n print chinese_remainder(n, a)"} -{"title": "Chinese remainder theorem", "language": "Python 3.7", "task": "Suppose n_1, n_2, \\ldots, n_k are positive [[integer]]s that are pairwise co-prime. \n\nThen, for any given sequence of integers a_1, a_2, \\dots, a_k, there exists an integer x solving the following system of simultaneous congruences:\n\n::: \\begin{align}\n x &\\equiv a_1 \\pmod{n_1} \\\\\n x &\\equiv a_2 \\pmod{n_2} \\\\\n &{}\\ \\ \\vdots \\\\\n x &\\equiv a_k \\pmod{n_k}\n\\end{align}\n\nFurthermore, all solutions x of this system are congruent modulo the product, N=n_1n_2\\ldots n_k.\n\n\n;Task:\nWrite a program to solve a system of linear congruences by applying the Chinese Remainder Theorem. \n\nIf the system of equations cannot be solved, your program must somehow indicate this. \n\n(It may throw an exception or return a special false value.) \n\nSince there are infinitely many solutions, the program should return the unique solution s where 0 \\leq s \\leq n_1n_2\\ldots n_k.\n\n\n''Show the functionality of this program'' by printing the result such that the n's are [3,5,7] and the a's are [2,3,2].\n\n\n'''Algorithm''': The following algorithm only applies if the n_i's are pairwise co-prime. \n\nSuppose, as above, that a solution is required for the system of congruences:\n\n::: x \\equiv a_i \\pmod{n_i} \\quad\\mathrm{for}\\; i = 1, \\ldots, k\n\nAgain, to begin, the product N = n_1n_2 \\ldots n_k is defined. \n\nThen a solution x can be found as follows:\n\nFor each i, the integers n_i and N/n_i are co-prime. \n\nUsing the Extended Euclidean algorithm, we can find integers r_i and s_i such that r_i n_i + s_i N/n_i = 1. \n\nThen, one solution to the system of simultaneous congruences is:\n\n::: x = \\sum_{i=1}^k a_i s_i N/n_i\n\nand the minimal solution,\n\n::: x \\pmod{N}.\n\n", "solution": "'''Chinese remainder theorem'''\n\nfrom operator import (add, mul)\nfrom functools import reduce\n\n\n# cnRemainder :: [Int] -> [Int] -> Either String Int\ndef cnRemainder(ms):\n '''Chinese remainder theorem.\n (moduli, residues) -> Either explanation or solution\n '''\n def go(ms, rs):\n mp = numericProduct(ms)\n cms = [(mp // x) for x in ms]\n\n def possibleSoln(invs):\n return Right(\n sum(map(\n mul,\n cms, map(mul, rs, invs)\n )) % mp\n )\n return bindLR(\n zipWithEither(modMultInv)(cms)(ms)\n )(possibleSoln)\n\n return lambda rs: go(ms, rs)\n\n\n# modMultInv :: Int -> Int -> Either String Int\ndef modMultInv(a, b):\n '''Modular multiplicative inverse.'''\n x, y = eGcd(a, b)\n return Right(x) if 1 == (a * x + b * y) else (\n Left('no modular inverse for ' + str(a) + ' and ' + str(b))\n )\n\n\n# egcd :: Int -> Int -> (Int, Int)\ndef eGcd(a, b):\n '''Extended greatest common divisor.'''\n def go(a, b):\n if 0 == b:\n return (1, 0)\n else:\n q, r = divmod(a, b)\n (s, t) = go(b, r)\n return (t, s - q * t)\n return go(a, b)\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Tests of soluble and insoluble cases.'''\n\n print(\n fTable(\n __doc__ + ':\\n\\n (moduli, residues) -> ' + (\n 'Either solution or explanation\\n'\n )\n )(repr)(\n either(compose(quoted(\"'\"))(curry(add)('No solution: ')))(\n compose(quoted(' '))(repr)\n )\n )(uncurry(cnRemainder))([\n ([10, 4, 12], [11, 12, 13]),\n ([11, 12, 13], [10, 4, 12]),\n ([10, 4, 9], [11, 22, 19]),\n ([3, 5, 7], [2, 3, 2]),\n ([2, 3, 2], [3, 5, 7])\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# any :: (a -> Bool) -> [a] -> Bool\n\n\ndef any_(p):\n '''True if p(x) holds for at least\n one item in xs.'''\n def go(xs):\n for x in xs:\n if p(x):\n return True\n return False\n return lambda xs: go(xs)\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 return lambda mf: (\n mf(m.get('Right')) if None is m.get('Left') else m\n )\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# 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# 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# fTable :: String -> (a -> String) ->\n# (b -> String) -> (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# numericProduct :: [Num] -> Num\ndef numericProduct(xs):\n '''The arithmetic product of all numbers in xs.'''\n return reduce(mul, xs, 1)\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# 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# uncurry :: (a -> b -> c) -> ((a, b) -> c)\ndef uncurry(f):\n '''A function over a tuple,\n derived from a curried function.'''\n return lambda xy: f(xy[0])(xy[1])\n\n\n# zipWithEither :: (a -> b -> Either String c)\n# -> [a] -> [b] -> Either String [c]\ndef zipWithEither(f):\n '''Either a list of results if f succeeds with every pair\n in the zip of xs and ys, or an explanatory string\n if any application of f returns no result.\n '''\n def go(xs, ys):\n ls, rs = partitionEithers(map(f, xs, ys))\n return Left(ls[0]) if ls else Right(rs)\n return lambda xs: lambda ys: go(xs, ys)\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} -{"title": "Chinese zodiac", "language": "C++", "task": "Determine the Chinese zodiac sign and related associations for a given year.\nTraditionally, the Chinese have counted years using two lists of labels, one of length 10 (the \"celestial stems\") and one of length 12 (the \"terrestrial branches\"). The labels do not really have any meaning outside their positions in the two lists; they're simply a traditional enumeration device, used much as Westerners use letters and numbers. They were historically used for months and days as well as years, and the stems are still sometimes used for school grades.\n\nYears cycle through both lists concurrently, so that both stem and branch advance each year; if we used Roman letters for the stems and numbers for the branches, consecutive years would be labeled A1, B2, C3, etc. Since the two lists are different lengths, they cycle back to their beginning at different points: after J10 we get A11, and then after B12 we get C1. The result is a repeating 60-year pattern within which each pair of names occurs only once.\n\nMapping the branches to twelve traditional animal deities results in the well-known \"Chinese zodiac\", assigning each year to a given animal. For example, Sunday, January 22, 2023 CE (in the common Gregorian calendar) began the lunisolar Year of the Rabbit.\n\nThe celestial stems do not have a one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems are each associated with one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element is assigned to yin, the other to yang.\n\nThus, the Chinese year beginning in 2023 CE is also the yin year of Water. Since 12 is an even number, the association between animals and yin/yang doesn't change; consecutive Years of the Rabbit will cycle through the five elements, but will always be yin.\n\n;Task: Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year.\n\nYou may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration).\n\n;Requisite information:\n* The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.\n* The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. \n* Each element gets two consecutive years; a yang followed by a yin.\n* The current 60-year cycle began in 1984; any multiple of 60 years from that point may be used to reckon from.\n\nThus, year 1 of a cycle is the year of the Wood Rat (yang), year 2 the Wood Ox (yin), and year 3 the Fire Tiger (yang). The year 2023 - which, as already noted, is the year of the Water Rabbit (yin) - is the 40th year of the current cycle. \n\n;Information for optional task:\n* The ten celestial stems are '''Jia ''' ''jia'', '''Yi ''' ''yi'', '''Bing ''' ''bing'', '''Ding ''' ''ding'', '''Wu ''' ''wu'', '''Ji ''' ''ji'', '''Geng ''' ''geng'', '''Xin ''' ''xin'', '''Ren ''' ''ren'', and '''Gui ''' ''gui''. With the ASCII version of Pinyin tones, the names are written \"jia3\", \"yi3\", \"bing3\", \"ding1\", \"wu4\", \"ji3\", \"geng1\", \"xin1\", \"ren2\", and \"gui3\".\n* The twelve terrestrial branches are '''Zi ''' ''zi'', '''Chou ''' ''chou'', '''Yin ''' ''yin'', '''Mao ''' ''mao'', '''Chen ''' ''chen'', '''Si ''' ''si'', '''Wu ''' ''wu'', '''Wei ''' ''wei'', '''Shen ''' ''shen'', '''You ''' ''you'', '''Xu ''' ''xu'', '''Hai ''' ''hai''. In ASCII Pinyin, those are \"zi3\", \"chou3\", \"yin2\", \"mao3\", \"chen2\", \"si4\", \"wu3\", \"wei4\", \"shen1\", \"you3\", \"xu1\", and \"hai4\".\n\nTherefore 1984 was '''Jia Zi ''' (''jia-zi'', or jia3-zi3). 2023 is '''Gui Mao ''' (''gui-mao'' or gui3-mao3).\n", "solution": "#include \n#include \n\nusing namespace std;\n\nconst string animals[]={\"Rat\",\"Ox\",\"Tiger\",\"Rabbit\",\"Dragon\",\"Snake\",\"Horse\",\"Goat\",\"Monkey\",\"Rooster\",\"Dog\",\"Pig\"};\nconst string elements[]={\"Wood\",\"Fire\",\"Earth\",\"Metal\",\"Water\"};\n\nstring getElement(int year)\n{\n int element = floor((year-4)%10/2);\n return elements[element];\n}\n\nstring getAnimal(int year)\n{\n return animals[(year-4)%12];\n}\n\nstring getYY(int year)\n{\n if(year%2==0)\n {\n return \"yang\";\n }\n else\n {\n return \"yin\";\n }\n}\n\nint main()\n{\n int years[]={1935,1938,1968,1972,1976,2017};\n //the zodiac cycle didnt start until 4 CE, so years <4 shouldnt be valid\n for(int i=0;i<6;i++)\n {\n cout << years[i] << \" is the year of the \" << getElement(years[i]) << \" \" << getAnimal(years[i]) << \" (\" << getYY(years[i]) << \").\" << endl;\n }\n return 0;\n}"} -{"title": "Chinese zodiac", "language": "JavaScript from Haskell", "task": "Determine the Chinese zodiac sign and related associations for a given year.\nTraditionally, the Chinese have counted years using two lists of labels, one of length 10 (the \"celestial stems\") and one of length 12 (the \"terrestrial branches\"). The labels do not really have any meaning outside their positions in the two lists; they're simply a traditional enumeration device, used much as Westerners use letters and numbers. They were historically used for months and days as well as years, and the stems are still sometimes used for school grades.\n\nYears cycle through both lists concurrently, so that both stem and branch advance each year; if we used Roman letters for the stems and numbers for the branches, consecutive years would be labeled A1, B2, C3, etc. Since the two lists are different lengths, they cycle back to their beginning at different points: after J10 we get A11, and then after B12 we get C1. The result is a repeating 60-year pattern within which each pair of names occurs only once.\n\nMapping the branches to twelve traditional animal deities results in the well-known \"Chinese zodiac\", assigning each year to a given animal. For example, Sunday, January 22, 2023 CE (in the common Gregorian calendar) began the lunisolar Year of the Rabbit.\n\nThe celestial stems do not have a one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems are each associated with one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element is assigned to yin, the other to yang.\n\nThus, the Chinese year beginning in 2023 CE is also the yin year of Water. Since 12 is an even number, the association between animals and yin/yang doesn't change; consecutive Years of the Rabbit will cycle through the five elements, but will always be yin.\n\n;Task: Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year.\n\nYou may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration).\n\n;Requisite information:\n* The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.\n* The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. \n* Each element gets two consecutive years; a yang followed by a yin.\n* The current 60-year cycle began in 1984; any multiple of 60 years from that point may be used to reckon from.\n\nThus, year 1 of a cycle is the year of the Wood Rat (yang), year 2 the Wood Ox (yin), and year 3 the Fire Tiger (yang). The year 2023 - which, as already noted, is the year of the Water Rabbit (yin) - is the 40th year of the current cycle. \n\n;Information for optional task:\n* The ten celestial stems are '''Jia ''' ''jia'', '''Yi ''' ''yi'', '''Bing ''' ''bing'', '''Ding ''' ''ding'', '''Wu ''' ''wu'', '''Ji ''' ''ji'', '''Geng ''' ''geng'', '''Xin ''' ''xin'', '''Ren ''' ''ren'', and '''Gui ''' ''gui''. With the ASCII version of Pinyin tones, the names are written \"jia3\", \"yi3\", \"bing3\", \"ding1\", \"wu4\", \"ji3\", \"geng1\", \"xin1\", \"ren2\", and \"gui3\".\n* The twelve terrestrial branches are '''Zi ''' ''zi'', '''Chou ''' ''chou'', '''Yin ''' ''yin'', '''Mao ''' ''mao'', '''Chen ''' ''chen'', '''Si ''' ''si'', '''Wu ''' ''wu'', '''Wei ''' ''wei'', '''Shen ''' ''shen'', '''You ''' ''you'', '''Xu ''' ''xu'', '''Hai ''' ''hai''. In ASCII Pinyin, those are \"zi3\", \"chou3\", \"yin2\", \"mao3\", \"chen2\", \"si4\", \"wu3\", \"wei4\", \"shen1\", \"you3\", \"xu1\", and \"hai4\".\n\nTherefore 1984 was '''Jia Zi ''' (''jia-zi'', or jia3-zi3). 2023 is '''Gui Mao ''' (''gui-mao'' or gui3-mao3).\n", "solution": "(() => {\n \"use strict\";\n\n // ---------- TRADITIONAL CALENDAR STRINGS -----------\n\n // ats :: Array Int (String, String)\n const ats = () =>\n // \u5929\u5e72 tiangan \u2013 10 heavenly stems\n zip(\n chars(\"\u7532\u4e59\u4e19\u4e01\u620a\u5df1\u5e9a\u8f9b\u58ec\u7678\")\n )(\n words(\"ji\u0103 y\u012d b\u012dng d\u012bng w\u00f9 j\u012d g\u0113ng x\u012bn r\u00e9n g\u016di\")\n );\n\n\n // ads :: Array Int (String, String)\n const ads = () =>\n // \u5730\u652f dizhi \u2013 12 terrestrial branches\n zip(\n chars(\"\u5b50\u4e11\u5bc5\u536f\u8fb0\u5df3\u5348\u672a\u7533\u9149\u620c\u4ea5\")\n )(\n words(\n \"z\u012d ch\u014fu y\u00edn m\u0103o ch\u00e9n s\u00ec \" + (\n \"w\u016d w\u00e8i sh\u0113n y\u014fu x\u016b h\u00e0i\"\n )\n )\n );\n\n\n // aws :: Array Int (String, String, String)\n const aws = () =>\n // \u4e94\u884c wuxing \u2013 5 elements\n zip3(\n chars(\"\u6728\u706b\u571f\u91d1\u6c34\")\n )(\n words(\"m\u00f9 hu\u01d2 t\u01d4 j\u012bn shu\u01d0\")\n )(\n words(\"wood fire earth metal water\")\n );\n\n\n // axs :: Array Int (String, String, String)\n const axs = () =>\n // \u5341\u4e8c\u751f\u8096 shengxiao \u2013 12 symbolic animals\n zip3(\n chars(\"\u9f20\u725b\u864e\u5154\u9f8d\u86c7\u99ac\u7f8a\u7334\u9e21\u72d7\u8c6c\")\n )(\n words(\n \"sh\u01d4 ni\u00fa h\u01d4 t\u00f9 l\u00f3ng sh\u00e9 \" + (\n \"m\u01ce y\u00e1ng h\u00f3u j\u012b g\u01d2u zh\u016b\"\n )\n )\n )(\n words(\n \"rat ox tiger rabbit dragon snake \" + (\n \"horse goat monkey rooster dog pig\"\n )\n )\n );\n\n\n // ays :: Array Int (String, String)\n const ays = () =>\n // \u9634\u9633 yinyang\n zip(\n chars(\"\u9633\u9634\")\n )(\n words(\"y\u00e1ng y\u012bn\")\n );\n\n\n // --------------- TRADITIONAL CYCLES ----------------\n const zodiac = y => {\n const\n iYear = y - 4,\n iStem = iYear % 10,\n iBranch = iYear % 12,\n [hStem, pStem] = ats()[iStem],\n [hBranch, pBranch] = ads()[iBranch],\n [hElem, pElem, eElem] = aws()[quot(iStem)(2)],\n [hAnimal, pAnimal, eAnimal] = axs()[iBranch],\n [hYinyang, pYinyang] = ays()[iYear % 2];\n\n return [\n [\n show(y), hStem + hBranch, hElem,\n hAnimal, hYinyang\n ],\n [\"\", pStem + pBranch, pElem, pAnimal, pYinyang],\n [\n \"\", `${show((iYear % 60) + 1)}/60`,\n eElem, eAnimal, \"\"\n ]\n ];\n };\n\n\n // ---------------------- TEST -----------------------\n const main = () => [\n 1935, 1938, 1968, 1972, 1976, 1984,\n new Date().getFullYear()\n ]\n .map(showYear)\n .join(\"\\n\\n\");\n\n\n // ------------------- FORMATTING --------------------\n // fieldWidths :: [[Int]]\n const fieldWidths = [\n [6, 10, 7, 8, 3],\n [6, 11, 8, 8, 4],\n [6, 11, 8, 8, 4]\n ];\n\n\n // showYear :: Int -> String\n const showYear = y =>\n zipWith(zip)(fieldWidths)(zodiac(y))\n .map(\n row => row.map(\n ([n, s]) => s.padEnd(n, \" \")\n )\n .join(\"\")\n )\n .join(\"\\n\");\n\n\n // ---------------- GENERIC FUNCTIONS ----------------\n\n // chars :: String -> [Char]\n const chars = s => [...s];\n\n\n // quot :: Integral a => a -> a -> a\n const quot = n =>\n m => Math.trunc(n / m);\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 ? [\n x[1], null, x[0]\n ] : x\n );\n\n\n // words :: String -> [String]\n const words = s =>\n // List of space-delimited sub-strings.\n s.split(/\\s+/u);\n\n\n // zip :: [a] -> [b] -> [(a, b)]\n const zip = xs =>\n // The paired members of xs and ys, up to\n // the length of the shorter of the two lists.\n ys => Array.from({\n length: Math.min(xs.length, ys.length)\n }, (_, i) => [xs[i], ys[i]]);\n\n\n // zip3 :: [a] -> [b] -> [c] -> [(a, b, c)]\n const zip3 = xs =>\n ys => zs => xs.slice(\n 0,\n Math.min(...[xs, ys, zs].map(x => x.length))\n )\n .map((x, i) => [x, ys[i], zs[i]]);\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\n // MAIN ---\n return main();\n})();"} -{"title": "Chinese zodiac", "language": "Python from Ruby", "task": "Determine the Chinese zodiac sign and related associations for a given year.\nTraditionally, the Chinese have counted years using two lists of labels, one of length 10 (the \"celestial stems\") and one of length 12 (the \"terrestrial branches\"). The labels do not really have any meaning outside their positions in the two lists; they're simply a traditional enumeration device, used much as Westerners use letters and numbers. They were historically used for months and days as well as years, and the stems are still sometimes used for school grades.\n\nYears cycle through both lists concurrently, so that both stem and branch advance each year; if we used Roman letters for the stems and numbers for the branches, consecutive years would be labeled A1, B2, C3, etc. Since the two lists are different lengths, they cycle back to their beginning at different points: after J10 we get A11, and then after B12 we get C1. The result is a repeating 60-year pattern within which each pair of names occurs only once.\n\nMapping the branches to twelve traditional animal deities results in the well-known \"Chinese zodiac\", assigning each year to a given animal. For example, Sunday, January 22, 2023 CE (in the common Gregorian calendar) began the lunisolar Year of the Rabbit.\n\nThe celestial stems do not have a one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems are each associated with one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element is assigned to yin, the other to yang.\n\nThus, the Chinese year beginning in 2023 CE is also the yin year of Water. Since 12 is an even number, the association between animals and yin/yang doesn't change; consecutive Years of the Rabbit will cycle through the five elements, but will always be yin.\n\n;Task: Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year.\n\nYou may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration).\n\n;Requisite information:\n* The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.\n* The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. \n* Each element gets two consecutive years; a yang followed by a yin.\n* The current 60-year cycle began in 1984; any multiple of 60 years from that point may be used to reckon from.\n\nThus, year 1 of a cycle is the year of the Wood Rat (yang), year 2 the Wood Ox (yin), and year 3 the Fire Tiger (yang). The year 2023 - which, as already noted, is the year of the Water Rabbit (yin) - is the 40th year of the current cycle. \n\n;Information for optional task:\n* The ten celestial stems are '''Jia ''' ''jia'', '''Yi ''' ''yi'', '''Bing ''' ''bing'', '''Ding ''' ''ding'', '''Wu ''' ''wu'', '''Ji ''' ''ji'', '''Geng ''' ''geng'', '''Xin ''' ''xin'', '''Ren ''' ''ren'', and '''Gui ''' ''gui''. With the ASCII version of Pinyin tones, the names are written \"jia3\", \"yi3\", \"bing3\", \"ding1\", \"wu4\", \"ji3\", \"geng1\", \"xin1\", \"ren2\", and \"gui3\".\n* The twelve terrestrial branches are '''Zi ''' ''zi'', '''Chou ''' ''chou'', '''Yin ''' ''yin'', '''Mao ''' ''mao'', '''Chen ''' ''chen'', '''Si ''' ''si'', '''Wu ''' ''wu'', '''Wei ''' ''wei'', '''Shen ''' ''shen'', '''You ''' ''you'', '''Xu ''' ''xu'', '''Hai ''' ''hai''. In ASCII Pinyin, those are \"zi3\", \"chou3\", \"yin2\", \"mao3\", \"chen2\", \"si4\", \"wu3\", \"wei4\", \"shen1\", \"you3\", \"xu1\", and \"hai4\".\n\nTherefore 1984 was '''Jia Zi ''' (''jia-zi'', or jia3-zi3). 2023 is '''Gui Mao ''' (''gui-mao'' or gui3-mao3).\n", "solution": "# coding: utf-8\n\nfrom __future__ import print_function\nfrom datetime import datetime\n\npinyin = {\n '\u7532': 'ji\u0103',\n '\u4e59': 'y\u012d',\n '\u4e19': 'b\u012dng',\n '\u4e01': 'd\u012bng',\n '\u620a': 'w\u00f9',\n '\u5df1': 'j\u012d',\n '\u5e9a': 'g\u0113ng',\n '\u8f9b': 'x\u012bn',\n '\u58ec': 'r\u00e9n',\n '\u7678': 'g\u016di',\n\n '\u5b50': 'z\u012d',\n '\u4e11': 'ch\u014fu',\n '\u5bc5': 'y\u00edn',\n '\u536f': 'm\u0103o',\n '\u8fb0': 'ch\u00e9n',\n '\u5df3': 's\u00ec',\n '\u5348': 'w\u016d',\n '\u672a': 'w\u00e8i',\n '\u7533': 'sh\u0113n',\n '\u9149': 'y\u014fu',\n '\u620c': 'x\u016b',\n '\u4ea5': 'h\u00e0i'\n}\n\nanimals = ['Rat', 'Ox', 'Tiger', 'Rabbit', 'Dragon', 'Snake',\n 'Horse', 'Goat', 'Monkey', 'Rooster', 'Dog', 'Pig']\nelements = ['Wood', 'Fire', 'Earth', 'Metal', 'Water']\n\ncelestial = ['\u7532', '\u4e59', '\u4e19', '\u4e01', '\u620a', '\u5df1', '\u5e9a', '\u8f9b', '\u58ec', '\u7678']\nterrestrial = ['\u5b50', '\u4e11', '\u5bc5', '\u536f', '\u8fb0', '\u5df3', '\u5348', '\u672a', '\u7533', '\u9149', '\u620c', '\u4ea5']\naspects = ['yang', 'yin']\n\n\ndef calculate(year):\n BASE = 4\n year = int(year)\n cycle_year = year - BASE\n stem_number = cycle_year % 10\n stem_han = celestial[stem_number]\n stem_pinyin = pinyin[stem_han]\n element_number = stem_number // 2\n element = elements[element_number]\n branch_number = cycle_year % 12\n branch_han = terrestrial[branch_number]\n branch_pinyin = pinyin[branch_han]\n animal = animals[branch_number]\n aspect_number = cycle_year % 2\n aspect = aspects[aspect_number]\n index = cycle_year % 60 + 1\n print(\"{}: {}{} ({}-{}, {} {}; {} - year {} of the cycle)\"\n .format(year, stem_han, branch_han,\n stem_pinyin, branch_pinyin, element, animal, aspect, index))\n\n\ncurrent_year = datetime.now().year\nyears = [1935, 1938, 1968, 1972, 1976, current_year]\nfor year in years:\n calculate(year)"} -{"title": "Chinese zodiac", "language": "Python 3.7", "task": "Determine the Chinese zodiac sign and related associations for a given year.\nTraditionally, the Chinese have counted years using two lists of labels, one of length 10 (the \"celestial stems\") and one of length 12 (the \"terrestrial branches\"). The labels do not really have any meaning outside their positions in the two lists; they're simply a traditional enumeration device, used much as Westerners use letters and numbers. They were historically used for months and days as well as years, and the stems are still sometimes used for school grades.\n\nYears cycle through both lists concurrently, so that both stem and branch advance each year; if we used Roman letters for the stems and numbers for the branches, consecutive years would be labeled A1, B2, C3, etc. Since the two lists are different lengths, they cycle back to their beginning at different points: after J10 we get A11, and then after B12 we get C1. The result is a repeating 60-year pattern within which each pair of names occurs only once.\n\nMapping the branches to twelve traditional animal deities results in the well-known \"Chinese zodiac\", assigning each year to a given animal. For example, Sunday, January 22, 2023 CE (in the common Gregorian calendar) began the lunisolar Year of the Rabbit.\n\nThe celestial stems do not have a one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems are each associated with one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element is assigned to yin, the other to yang.\n\nThus, the Chinese year beginning in 2023 CE is also the yin year of Water. Since 12 is an even number, the association between animals and yin/yang doesn't change; consecutive Years of the Rabbit will cycle through the five elements, but will always be yin.\n\n;Task: Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year.\n\nYou may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration).\n\n;Requisite information:\n* The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.\n* The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. \n* Each element gets two consecutive years; a yang followed by a yin.\n* The current 60-year cycle began in 1984; any multiple of 60 years from that point may be used to reckon from.\n\nThus, year 1 of a cycle is the year of the Wood Rat (yang), year 2 the Wood Ox (yin), and year 3 the Fire Tiger (yang). The year 2023 - which, as already noted, is the year of the Water Rabbit (yin) - is the 40th year of the current cycle. \n\n;Information for optional task:\n* The ten celestial stems are '''Jia ''' ''jia'', '''Yi ''' ''yi'', '''Bing ''' ''bing'', '''Ding ''' ''ding'', '''Wu ''' ''wu'', '''Ji ''' ''ji'', '''Geng ''' ''geng'', '''Xin ''' ''xin'', '''Ren ''' ''ren'', and '''Gui ''' ''gui''. With the ASCII version of Pinyin tones, the names are written \"jia3\", \"yi3\", \"bing3\", \"ding1\", \"wu4\", \"ji3\", \"geng1\", \"xin1\", \"ren2\", and \"gui3\".\n* The twelve terrestrial branches are '''Zi ''' ''zi'', '''Chou ''' ''chou'', '''Yin ''' ''yin'', '''Mao ''' ''mao'', '''Chen ''' ''chen'', '''Si ''' ''si'', '''Wu ''' ''wu'', '''Wei ''' ''wei'', '''Shen ''' ''shen'', '''You ''' ''you'', '''Xu ''' ''xu'', '''Hai ''' ''hai''. In ASCII Pinyin, those are \"zi3\", \"chou3\", \"yin2\", \"mao3\", \"chen2\", \"si4\", \"wu3\", \"wei4\", \"shen1\", \"you3\", \"xu1\", and \"hai4\".\n\nTherefore 1984 was '''Jia Zi ''' (''jia-zi'', or jia3-zi3). 2023 is '''Gui Mao ''' (''gui-mao'' or gui3-mao3).\n", "solution": "'''Chinese zodiac'''\n\nfrom functools import (reduce)\nfrom datetime import datetime\n\n\n# TRADITIONAL STRINGS -------------------------------------\n\n# zodiacNames :: Dict\ndef zodiacNames():\n '''\u5929\u5e72 tiangan \u2013 10 heavenly stems\n \u5730\u652f dizhi \u2013 12 terrestrial branches\n \u4e94\u884c wuxing \u2013 5 elements\n \u751f\u8096 shengxiao \u2013 12 symbolic animals\n \u9634\u9633 yinyang - dark and light\n '''\n return dict(\n zip(\n ['tian', 'di', 'wu', 'sx', 'yy'],\n map(\n lambda tpl: list(\n zip(* [tpl[0]] + list(\n map(\n lambda x: x.split(),\n tpl[1:])\n ))\n ),\n [\n # \u5929\u5e72 tiangan \u2013 10 heavenly stems\n ('\u7532\u4e59\u4e19\u4e01\u620a\u5df1\u5e9a\u8f9b\u58ec\u7678',\n 'ji\u0103 y\u012d b\u012dng d\u012bng w\u00f9 j\u012d g\u0113ng x\u012bn r\u00e9n g\u016di'),\n\n # \u5730\u652f dizhi \u2013 12 terrestrial branches\n ('\u5b50\u4e11\u5bc5\u536f\u8fb0\u5df3\u5348\u672a\u7533\u9149\u620c\u4ea5',\n 'z\u012d ch\u014fu y\u00edn m\u0103o ch\u00e9n s\u00ec w\u016d w\u00e8i sh\u0113n y\u014fu x\u016b h\u00e0i'),\n\n # \u4e94\u884c wuxing \u2013 5 elements\n ('\u6728\u706b\u571f\u91d1\u6c34',\n 'm\u00f9 hu\u01d2 t\u01d4 j\u012bn shu\u01d0',\n 'wood fire earth metal water'),\n\n # \u5341\u4e8c\u751f\u8096 shengxiao \u2013 12 symbolic animals\n ('\u9f20\u725b\u864e\u5154\u9f8d\u86c7\u99ac\u7f8a\u7334\u9e21\u72d7\u8c6c',\n 'sh\u01d4 ni\u00fa h\u01d4 t\u00f9 l\u00f3ng sh\u00e9 m\u01ce y\u00e1ng h\u00f3u j\u012b g\u01d2u zh\u016b',\n 'rat ox tiger rabbit dragon snake horse goat ' +\n 'monkey rooster dog pig'\n ),\n\n # \u9634\u9633 yinyang\n ('\u9633\u9634', 'y\u00e1ng y\u012bn')\n ]\n )))\n\n\n# zodiacYear :: Dict -> [[String]]\ndef zodiacYear(dct):\n '''A string of strings containing the\n Chinese zodiac tokens for a given year.\n '''\n def tokens(y):\n iYear = y - 4\n iStem = iYear % 10\n iBranch = iYear % 12\n (hStem, pStem) = dct['tian'][iStem]\n (hBranch, pBranch) = dct['di'][iBranch]\n yy = iYear % 2\n return [\n [str(y), '', ''],\n [\n hStem + hBranch,\n pStem + pBranch,\n str((iYear % 60) + 1) + '/60'\n ],\n list(dct['wu'][iStem // 2]),\n list(dct['sx'][iBranch]),\n list(dct['yy'][int(yy)]) + ['dark' if yy else 'light']\n ]\n return lambda year: tokens(year)\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Writing out wiki tables displaying Chinese zodiac\n details for a given list of years.\n '''\n print('\\n'.join(\n list(map(\n zodiacTable(zodiacNames()),\n [\n 1935, 1938, 1949,\n 1968, 1972, 1976,\n datetime.now().year\n ]\n ))\n ))\n\n\n# WIKI TABLES --------------------------------------------\n\n# zodiacTable :: Dict -> Int -> String\ndef zodiacTable(tokens):\n '''A wiki table displaying Chinese zodiac\n details for a a given year.\n '''\n return lambda y: wikiTable({\n 'class': 'wikitable',\n 'colwidth': '70px'\n })(transpose(zodiacYear(tokens)(y)))\n\n\n# wikiTable :: Dict -> [[a]] -> String\ndef wikiTable(opts):\n '''List of lists rendered as a wiki table string.'''\n def colWidth():\n return 'width:' + opts['colwidth'] + '; ' if (\n 'colwidth' in opts\n ) else ''\n\n def cellStyle():\n return opts['cell'] if 'cell' in opts else ''\n\n return lambda rows: '{| ' + reduce(\n lambda a, k: (\n a + k + '=\"' + opts[k] + '\" ' if k in opts else a\n ),\n ['class', 'style'],\n ''\n ) + '\\n' + '\\n|-\\n'.join(\n '\\n'.join(\n ('|' if (0 != i and ('cell' not in opts)) else (\n '|style=\"' + colWidth() + cellStyle() + '\"|'\n )) + (\n str(x) or ' '\n ) for x in row\n ) for i, row in enumerate(rows)\n ) + '\\n|}\\n\\n'\n\n\n# GENERIC -------------------------------------------------\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# MAIN ---\nif __name__ == '__main__':\n main()"} -{"title": "Church numerals", "language": "C++", "task": "In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.\n\n* '''Church zero''' always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.\n* '''Church one''' applies its first argument f just once to its second argument x, yielding '''f(x)'''\n* '''Church two''' applies its first argument f twice to its second argument x, yielding '''f(f(x))'''\n* and each successive Church numeral applies its first argument one additional time to its second argument, '''f(f(f(x)))''', '''f(f(f(f(x))))''' ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument.\n\n\nArithmetic operations on natural numbers can be similarly represented as functions on Church numerals.\n\nIn your language define:\n\n* Church Zero,\n* a Church successor function (a function on a Church numeral which returns the next Church numeral in the series),\n* functions for Addition, Multiplication and Exponentiation over Church numerals,\n* a function to convert integers to corresponding Church numerals,\n* and a function to convert Church numerals to corresponding integers.\n\n\nYou should:\n\n* Derive Church numerals three and four in terms of Church zero and a Church successor function.\n* use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4,\n* similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function,\n* convert each result back to an integer, and return it or print it to the console.\n\n\n", "solution": "#include \n\n// apply the function zero times (return an identity function)\nauto Zero = [](auto){ return [](auto x){ return x; }; };\n\n// define Church True and False\nauto True = [](auto a){ return [=](auto){ return a; }; };\nauto False = [](auto){ return [](auto b){ return b; }; };\n\n// apply the function f one more time\nauto Successor(auto a) {\n return [=](auto f) {\n return [=](auto x) {\n return a(f)(f(x));\n };\n };\n}\n\n// apply the function a times after b times\nauto Add(auto a, auto b) {\n return [=](auto f) {\n return [=](auto x) {\n return a(f)(b(f)(x));\n };\n };\n}\n\n// apply the function a times b times\nauto Multiply(auto a, auto b) {\n return [=](auto f) {\n return a(b(f));\n };\n}\n\n// apply the function a^b times\nauto Exp(auto a, auto b) {\n return b(a);\n}\n\n// check if a number is zero\nauto IsZero(auto a){\n return a([](auto){ return False; })(True);\n}\n\n// apply the function f one less time\nauto Predecessor(auto a) {\n return [=](auto f) {\n return [=](auto x) {\n return a(\n [=](auto g) {\n return [=](auto h){\n return h(g(f));\n };\n }\n )([=](auto){ return x; })([](auto y){ return y; });\n };\n };\n}\n\n// apply the Predecessor function b times to a\nauto Subtract(auto a, auto b) {\n {\n return b([](auto c){ return Predecessor(c); })(a);\n };\n}\n\nnamespace\n{\n // helper functions for division.\n\n // end the recusrion\n auto Divr(decltype(Zero), auto) {\n return Zero;\n }\n\n // count how many times b can be subtracted from a\n auto Divr(auto a, auto b) {\n auto a_minus_b = Subtract(a, b);\n auto isZero = IsZero(a_minus_b);\n\n // normalize all Church zeros to be the same (intensional equality).\n // In this implemetation, Church numerals have extensional equality\n // but not intensional equality. '6 - 3' and '4 - 1' have extensional\n // equality because they will both cause a function to be called\n // three times but due to the static type system they do not have\n // intensional equality. Internally the two numerals are represented\n // by different lambdas. Normalize all Church zeros (1 - 1, 2 - 2, etc.)\n // to the same zero (Zero) so it will match the function that end the\n // recursion.\n return isZero\n (Zero)\n (Successor(Divr(isZero(Zero)(a_minus_b), b)));\n }\n}\n\n// apply the function a / b times\nauto Divide(auto a, auto b) {\n return Divr(Successor(a), b);\n}\n\n// create a Church numeral from an integer at compile time\ntemplate constexpr auto ToChurch() {\n if constexpr(N<=0) return Zero;\n else return Successor(ToChurch());\n}\n\n// use an increment function to convert the Church number to an integer\nint ToInt(auto church) {\n return church([](int n){ return n + 1; })(0);\n}\n\nint main() {\n // show some examples\n auto three = Successor(Successor(Successor(Zero)));\n auto four = Successor(three);\n auto six = ToChurch<6>();\n auto ten = ToChurch<10>();\n auto thousand = Exp(ten, three);\n\n std::cout << \"\\n 3 + 4 = \" << ToInt(Add(three, four));\n std::cout << \"\\n 3 * 4 = \" << ToInt(Multiply(three, four));\n std::cout << \"\\n 3^4 = \" << ToInt(Exp(three, four));\n std::cout << \"\\n 4^3 = \" << ToInt(Exp(four, three));\n std::cout << \"\\n 0^0 = \" << ToInt(Exp(Zero, Zero));\n std::cout << \"\\n 4 - 3 = \" << ToInt(Subtract(four, three));\n std::cout << \"\\n 3 - 4 = \" << ToInt(Subtract(three, four));\n std::cout << \"\\n 6 / 3 = \" << ToInt(Divide(six, three));\n std::cout << \"\\n 3 / 6 = \" << ToInt(Divide(three, six));\n auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand));\n auto looloolool = Successor(looloolooo);\n std::cout << \"\\n 10^9 + 10^6 + 10^3 + 1 = \" << ToInt(looloolool);\n\n // calculate the golden ratio by using a Church numeral to\n // apply the funtion 'f(x) = 1 + 1/x' a thousand times\n std::cout << \"\\n golden ratio = \" <<\n thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << \"\\n\";\n}\n"} -{"title": "Church numerals", "language": "Python 3.7", "task": "In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.\n\n* '''Church zero''' always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.\n* '''Church one''' applies its first argument f just once to its second argument x, yielding '''f(x)'''\n* '''Church two''' applies its first argument f twice to its second argument x, yielding '''f(f(x))'''\n* and each successive Church numeral applies its first argument one additional time to its second argument, '''f(f(f(x)))''', '''f(f(f(f(x))))''' ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument.\n\n\nArithmetic operations on natural numbers can be similarly represented as functions on Church numerals.\n\nIn your language define:\n\n* Church Zero,\n* a Church successor function (a function on a Church numeral which returns the next Church numeral in the series),\n* functions for Addition, Multiplication and Exponentiation over Church numerals,\n* a function to convert integers to corresponding Church numerals,\n* and a function to convert Church numerals to corresponding integers.\n\n\nYou should:\n\n* Derive Church numerals three and four in terms of Church zero and a Church successor function.\n* use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4,\n* similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function,\n* convert each result back to an integer, and return it or print it to the console.\n\n\n", "solution": "'''Church numerals'''\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n# ----- CHURCH ENCODINGS OF NUMERALS AND OPERATIONS ------\n\ndef churchZero():\n '''The identity function.\n No applications of any supplied f\n to its argument.\n '''\n return lambda f: identity\n\n\ndef churchSucc(cn):\n '''The successor of a given\n Church numeral. One additional\n application of f. Equivalent to\n the arithmetic addition of one.\n '''\n return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n '''The arithmetic sum of two Church numerals.'''\n return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n '''The arithmetic product of two Church numerals.'''\n return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n '''Exponentiation of Church numerals. m^n'''\n return lambda n: n(m)\n\n\ndef churchFromInt(n):\n '''The Church numeral equivalent of\n a given integer.\n '''\n return lambda f: (\n foldl\n (compose)\n (identity)\n (replicate(n)(f))\n )\n\n\n# OR, alternatively:\ndef churchFromInt_(n):\n '''The Church numeral equivalent of a given\n integer, by explicit recursion.\n '''\n if 0 == n:\n return churchZero()\n else:\n return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n '''The integer equivalent of a\n given Church numeral.\n '''\n return cn(succ)(0)\n\n\n# ------------------------- TEST -------------------------\n# main :: IO ()\ndef main():\n 'Tests'\n\n cThree = churchFromInt(3)\n cFour = churchFromInt(4)\n\n print(list(map(intFromChurch, [\n churchAdd(cThree)(cFour),\n churchMult(cThree)(cFour),\n churchExp(cFour)(cThree),\n churchExp(cThree)(cFour),\n ])))\n\n\n# ------------------ GENERIC FUNCTIONS -------------------\n\n# compose (flip (.)) :: (a -> b) -> (b -> c) -> a -> c\ndef compose(f):\n '''A left to right composition of two\n functions f and g'''\n return lambda g: lambda x: g(f(x))\n\n\n# foldl :: (a -> b -> a) -> a -> [b] -> a\ndef foldl(f):\n '''Left to right reduction of a list,\n using the binary operator f, and\n starting with an initial value a.\n '''\n def go(acc, xs):\n return reduce(lambda a, x: f(a)(x), xs, acc)\n return lambda acc: lambda xs: go(acc, xs)\n\n\n# identity :: a -> a\ndef identity(x):\n '''The identity function.'''\n return x\n\n\n# replicate :: Int -> a -> [a]\ndef replicate(n):\n '''A list of length n in which every\n element has the value x.\n '''\n return lambda x: repeat(x, n)\n\n\n# succ :: Enum a => a -> a\ndef succ(x):\n '''The successor of a value.\n For numeric types, (1 +).\n '''\n return 1 + x if isinstance(x, int) else (\n chr(1 + ord(x))\n )\n\n\nif __name__ == '__main__':\n main()"} -{"title": "Circles of given radius through two points", "language": "C", "task": "2 circles with a given radius through 2 points in 2D space.\n\nGiven two points on a plane and a radius, usually two circles of given radius can be drawn through the points. \n;Exceptions:\n# r==0.0 should be treated as never describing circles (except in the case where the points are coincident).\n# If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.\n# If the points form a diameter then return two identical circles ''or'' return a single circle, according to which is the most natural mechanism for the implementation language.\n# If the points are too far apart then no circles can be drawn.\n\n\n;Task detail:\n* Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, ''or some indication of special cases where two, possibly equal, circles cannot be returned''.\n* Show here the output for the following inputs:\n\n p1 p2 r\n0.1234, 0.9876 0.8765, 0.2345 2.0\n0.0000, 2.0000 0.0000, 0.0000 1.0\n0.1234, 0.9876 0.1234, 0.9876 2.0\n0.1234, 0.9876 0.8765, 0.2345 0.5\n0.1234, 0.9876 0.1234, 0.9876 0.0\n\n\n\n;Related task:\n* [[Total circles area]].\n\n\n;See also:\n* Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel\n\n", "solution": "#include\n#include\n\ntypedef struct{\n\tdouble x,y;\n\t}point;\n\t\ndouble distance(point p1,point p2)\n{\n\treturn sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));\n}\n\t\nvoid findCircles(point p1,point p2,double radius)\n{\n\tdouble separation = distance(p1,p2),mirrorDistance;\n\t\n\tif(separation == 0.0)\n\t{\n\t\tradius == 0.0 ? printf(\"\\nNo circles can be drawn through (%.4f,%.4f)\",p1.x,p1.y):\n\t\t\t\t\t\t\t printf(\"\\nInfinitely many circles can be drawn through (%.4f,%.4f)\",p1.x,p1.y);\n\t}\n\t\n\telse if(separation == 2*radius)\n\t{\n\t\tprintf(\"\\nGiven points are opposite ends of a diameter of the circle with center (%.4f,%.4f) and radius %.4f\",(p1.x+p2.x)/2,(p1.y+p2.y)/2,radius); \n\t}\n\t\n\telse if(separation > 2*radius)\n\t{\n\t\tprintf(\"\\nGiven points are farther away from each other than a diameter of a circle with radius %.4f\",radius);\n\t} \n\t\n\telse\n\t{\n\t\tmirrorDistance =sqrt(pow(radius,2) - pow(separation/2,2));\n\t\t\n\t\tprintf(\"\\nTwo circles are possible.\");\n\t\tprintf(\"\\nCircle C1 with center (%.4f,%.4f), radius %.4f and Circle C2 with center (%.4f,%.4f), radius %.4f\",(p1.x+p2.x)/2 + mirrorDistance*(p1.y-p2.y)/separation,(p1.y+p2.y)/2 + mirrorDistance*(p2.x-p1.x)/separation,radius,(p1.x+p2.x)/2 - mirrorDistance*(p1.y-p2.y)/separation,(p1.y+p2.y)/2 - mirrorDistance*(p2.x-p1.x)/separation,radius);\n\t}\n}\n\nint main()\n{\n int i;\n\n point cases[] = \t\n {\t{0.1234, 0.9876}, {0.8765, 0.2345}, \n\t{0.0000, 2.0000}, {0.0000, 0.0000}, \n\t{0.1234, 0.9876}, {0.1234, 0.9876}, \n\t{0.1234, 0.9876}, {0.8765, 0.2345}, \n\t{0.1234, 0.9876}, {0.1234, 0.9876}\n };\n\n double radii[] = {2.0,1.0,2.0,0.5,0.0};\n\n for(i=0;i<5;i++)\n {\t\n\tprintf(\"\\nCase %d)\",i+1);\n\tfindCircles(cases[2*i],cases[2*i+1],radii[i]);\n }\n\n return 0;\n}\n"} -{"title": "Circles of given radius through two points", "language": "C++11", "task": "2 circles with a given radius through 2 points in 2D space.\n\nGiven two points on a plane and a radius, usually two circles of given radius can be drawn through the points. \n;Exceptions:\n# r==0.0 should be treated as never describing circles (except in the case where the points are coincident).\n# If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.\n# If the points form a diameter then return two identical circles ''or'' return a single circle, according to which is the most natural mechanism for the implementation language.\n# If the points are too far apart then no circles can be drawn.\n\n\n;Task detail:\n* Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, ''or some indication of special cases where two, possibly equal, circles cannot be returned''.\n* Show here the output for the following inputs:\n\n p1 p2 r\n0.1234, 0.9876 0.8765, 0.2345 2.0\n0.0000, 2.0000 0.0000, 0.0000 1.0\n0.1234, 0.9876 0.1234, 0.9876 2.0\n0.1234, 0.9876 0.8765, 0.2345 0.5\n0.1234, 0.9876 0.1234, 0.9876 0.0\n\n\n\n;Related task:\n* [[Total circles area]].\n\n\n;See also:\n* Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel\n\n", "solution": "#include \n#include \n#include \n\nstruct point { double x, y; };\n\nbool operator==(const point& lhs, const point& rhs)\n{ return std::tie(lhs.x, lhs.y) == std::tie(rhs.x, rhs.y); }\n\nenum result_category { NONE, ONE_COINCEDENT, ONE_DIAMETER, TWO, INFINITE };\n\nusing result_t = std::tuple;\n\ndouble distance(point l, point r)\n{ return std::hypot(l.x - r.x, l.y - r.y); }\n\nresult_t find_circles(point p1, point p2, double r)\n{\n point ans1 { 1/0., 1/0.}, ans2 { 1/0., 1/0.};\n if (p1 == p2) {\n if(r == 0.) return std::make_tuple(ONE_COINCEDENT, p1, p2 );\n else return std::make_tuple(INFINITE, ans1, ans2);\n }\n point center { p1.x/2 + p2.x/2, p1.y/2 + p2.y/2};\n double half_distance = distance(center, p1);\n if(half_distance > r) return std::make_tuple(NONE, ans1, ans2);\n if(half_distance - r == 0) return std::make_tuple(ONE_DIAMETER, center, ans2);\n double root = sqrt(pow(r, 2.l) - pow(half_distance, 2.l)) / distance(p1, p2);\n ans1.x = center.x + root * (p1.y - p2.y);\n ans1.y = center.y + root * (p2.x - p1.x);\n ans2.x = center.x - root * (p1.y - p2.y);\n ans2.y = center.y - root * (p2.x - p1.x);\n return std::make_tuple(TWO, ans1, ans2);\n}\n\nvoid print(result_t result, std::ostream& out = std::cout)\n{\n point r1, r2; result_category res;\n std::tie(res, r1, r2) = result;\n switch(res) {\n case NONE:\n out << \"There are no solutions, points are too far away\\n\"; break;\n case ONE_COINCEDENT: case ONE_DIAMETER:\n out << \"Only one solution: \" << r1.x << ' ' << r1.y << '\\n'; break;\n case INFINITE:\n out << \"Infinitely many circles can be drawn\\n\"; break;\n case TWO:\n out << \"Two solutions: \" << r1.x << ' ' << r1.y << \" and \" << r2.x << ' ' << r2.y << '\\n'; break;\n }\n}\n\nint main()\n{\n constexpr int size = 5;\n const point points[size*2] = {\n {0.1234, 0.9876}, {0.8765, 0.2345}, {0.0000, 2.0000}, {0.0000, 0.0000},\n {0.1234, 0.9876}, {0.1234, 0.9876}, {0.1234, 0.9876}, {0.8765, 0.2345},\n {0.1234, 0.9876}, {0.1234, 0.9876}\n };\n const double radius[size] = {2., 1., 2., .5, 0.};\n\n for(int i = 0; i < size; ++i)\n print(find_circles(points[i*2], points[i*2 + 1], radius[i]));\n}"} -{"title": "Circles of given radius through two points", "language": "JavaScript", "task": "2 circles with a given radius through 2 points in 2D space.\n\nGiven two points on a plane and a radius, usually two circles of given radius can be drawn through the points. \n;Exceptions:\n# r==0.0 should be treated as never describing circles (except in the case where the points are coincident).\n# If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.\n# If the points form a diameter then return two identical circles ''or'' return a single circle, according to which is the most natural mechanism for the implementation language.\n# If the points are too far apart then no circles can be drawn.\n\n\n;Task detail:\n* Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, ''or some indication of special cases where two, possibly equal, circles cannot be returned''.\n* Show here the output for the following inputs:\n\n p1 p2 r\n0.1234, 0.9876 0.8765, 0.2345 2.0\n0.0000, 2.0000 0.0000, 0.0000 1.0\n0.1234, 0.9876 0.1234, 0.9876 2.0\n0.1234, 0.9876 0.8765, 0.2345 0.5\n0.1234, 0.9876 0.1234, 0.9876 0.0\n\n\n\n;Related task:\n* [[Total circles area]].\n\n\n;See also:\n* Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel\n\n", "solution": "const hDist = (p1, p2) => Math.hypot(...p1.map((e, i) => e - p2[i])) / 2;\nconst pAng = (p1, p2) => Math.atan(p1.map((e, i) => e - p2[i]).reduce((p, c) => c / p, 1));\nconst solveF = (p, r) => t => [r*Math.cos(t) + p[0], r*Math.sin(t) + p[1]];\nconst diamPoints = (p1, p2) => p1.map((e, i) => e + (p2[i] - e) / 2);\n\nconst findC = (...args) => {\n const [p1, p2, s] = args;\n const solve = solveF(p1, s);\n const halfDist = hDist(p1, p2);\n\n let msg = `p1: ${p1}, p2: ${p2}, r:${s} Result: `;\n switch (Math.sign(s - halfDist)) {\n case 0:\n msg += s ? `Points on diameter. Circle at: ${diamPoints(p1, p2)}` :\n 'Radius Zero';\n break;\n case 1:\n if (!halfDist) {\n msg += 'Coincident point. Infinite solutions';\n }\n else {\n let theta = pAng(p1, p2);\n let theta2 = Math.acos(halfDist / s);\n [1, -1].map(e => solve(theta + e * theta2)).forEach(\n e => msg += `Circle at ${e} `);\n }\n break;\n case -1:\n msg += 'No intersection. Points further apart than circle diameter';\n break;\n }\n return msg;\n};\n\n\n[\n [[0.1234, 0.9876], [0.8765, 0.2345], 2.0],\n [[0.0000, 2.0000], [0.0000, 0.0000], 1.0],\n [[0.1234, 0.9876], [0.1234, 0.9876], 2.0],\n [[0.1234, 0.9876], [0.8765, 0.2345], 0.5],\n [[0.1234, 0.9876], [0.1234, 0.9876], 0.0]\n].forEach((t,i) => console.log(`Test: ${i}: ${findC(...t)}`));\n"} -{"title": "Circles of given radius through two points", "language": "Python", "task": "2 circles with a given radius through 2 points in 2D space.\n\nGiven two points on a plane and a radius, usually two circles of given radius can be drawn through the points. \n;Exceptions:\n# r==0.0 should be treated as never describing circles (except in the case where the points are coincident).\n# If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.\n# If the points form a diameter then return two identical circles ''or'' return a single circle, according to which is the most natural mechanism for the implementation language.\n# If the points are too far apart then no circles can be drawn.\n\n\n;Task detail:\n* Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, ''or some indication of special cases where two, possibly equal, circles cannot be returned''.\n* Show here the output for the following inputs:\n\n p1 p2 r\n0.1234, 0.9876 0.8765, 0.2345 2.0\n0.0000, 2.0000 0.0000, 0.0000 1.0\n0.1234, 0.9876 0.1234, 0.9876 2.0\n0.1234, 0.9876 0.8765, 0.2345 0.5\n0.1234, 0.9876 0.1234, 0.9876 0.0\n\n\n\n;Related task:\n* [[Total circles area]].\n\n\n;See also:\n* Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel\n\n", "solution": "from collections import namedtuple\nfrom math import sqrt\n\nPt = namedtuple('Pt', 'x, y')\nCircle = Cir = namedtuple('Circle', 'x, y, r')\n\ndef circles_from_p1p2r(p1, p2, r):\n 'Following explanation at http://mathforum.org/library/drmath/view/53027.html'\n if r == 0.0:\n raise ValueError('radius of zero')\n (x1, y1), (x2, y2) = p1, p2\n if p1 == p2:\n raise ValueError('coincident points gives infinite number of Circles')\n # delta x, delta y between points\n dx, dy = x2 - x1, y2 - y1\n # dist between points\n q = sqrt(dx**2 + dy**2)\n if q > 2.0*r:\n raise ValueError('separation of points > diameter')\n # halfway point\n x3, y3 = (x1+x2)/2, (y1+y2)/2\n # distance along the mirror line\n d = sqrt(r**2-(q/2)**2)\n # One answer\n c1 = Cir(x = x3 - d*dy/q,\n y = y3 + d*dx/q,\n r = abs(r))\n # The other answer\n c2 = Cir(x = x3 + d*dy/q,\n y = y3 - d*dx/q,\n r = abs(r))\n return c1, c2\n\nif __name__ == '__main__':\n for p1, p2, r in [(Pt(0.1234, 0.9876), Pt(0.8765, 0.2345), 2.0),\n (Pt(0.0000, 2.0000), Pt(0.0000, 0.0000), 1.0),\n (Pt(0.1234, 0.9876), Pt(0.1234, 0.9876), 2.0),\n (Pt(0.1234, 0.9876), Pt(0.8765, 0.2345), 0.5),\n (Pt(0.1234, 0.9876), Pt(0.1234, 0.9876), 0.0)]:\n print('Through points:\\n %r,\\n %r\\n and radius %f\\nYou can construct the following circles:'\n % (p1, p2, r))\n try:\n print(' %r\\n %r\\n' % circles_from_p1p2r(p1, p2, r))\n except ValueError as v:\n print(' ERROR: %s\\n' % (v.args[0],))"} -{"title": "Cistercian numerals", "language": "C++ from Go", "task": "Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from '''0''' to '''9999'''.\n\n;How they work\nAll Cistercian numerals begin with a vertical line segment, which by itself represents the number '''0'''. Then, glyphs representing the digits '''1''' through '''9''' are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number:\n\n:* The '''upper-right''' quadrant represents the '''ones''' place.\n:* The '''upper-left''' quadrant represents the '''tens''' place.\n:* The '''lower-right''' quadrant represents the '''hundreds''' place.\n:* The '''lower-left''' quadrant represents the '''thousands''' place.\n\nPlease consult the following image for examples of Cistercian numerals showing each glyph: [https://upload.wikimedia.org/wikipedia/commons/6/67/Cistercian_digits_%28vertical%29.svg]\n\n;Task\n\n:* Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile).\n\n:* Use the routine to show the following Cistercian numerals:\n\n::* 0\n::* 1\n::* 20\n::* 300\n::* 4000\n::* 5555\n::* 6789\n::* And a number of your choice!\n\n;Notes\nDue to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed -- especially for text output.\n\n;See also\n\n:* '''Numberphile - The Forgotten Number System'''\n:* '''dcode.fr - Online Cistercian numeral converter'''\n", "solution": "#include \n#include \n\ntemplate\nusing FixedSquareGrid = std::array, S>;\n\nstruct Cistercian {\npublic:\n Cistercian() {\n initN();\n }\n\n Cistercian(int v) {\n initN();\n draw(v);\n }\n\n Cistercian &operator=(int v) {\n initN();\n draw(v);\n }\n\n friend std::ostream &operator<<(std::ostream &, const Cistercian &);\n\nprivate:\n FixedSquareGrid canvas;\n\n void initN() {\n for (auto &row : canvas) {\n row.fill(' ');\n row[5] = 'x';\n }\n }\n\n void horizontal(size_t c1, size_t c2, size_t r) {\n for (size_t c = c1; c <= c2; c++) {\n canvas[r][c] = 'x';\n }\n }\n\n void vertical(size_t r1, size_t r2, size_t c) {\n for (size_t r = r1; r <= r2; r++) {\n canvas[r][c] = 'x';\n }\n }\n\n void diagd(size_t c1, size_t c2, size_t r) {\n for (size_t c = c1; c <= c2; c++) {\n canvas[r + c - c1][c] = 'x';\n }\n }\n\n void diagu(size_t c1, size_t c2, size_t r) {\n for (size_t c = c1; c <= c2; c++) {\n canvas[r - c + c1][c] = 'x';\n }\n }\n\n void drawOnes(int v) {\n switch (v) {\n case 1:\n horizontal(6, 10, 0);\n break;\n case 2:\n horizontal(6, 10, 4);\n break;\n case 3:\n diagd(6, 10, 0);\n break;\n case 4:\n diagu(6, 10, 4);\n break;\n case 5:\n drawOnes(1);\n drawOnes(4);\n break;\n case 6:\n vertical(0, 4, 10);\n break;\n case 7:\n drawOnes(1);\n drawOnes(6);\n break;\n case 8:\n drawOnes(2);\n drawOnes(6);\n break;\n case 9:\n drawOnes(1);\n drawOnes(8);\n break;\n default:\n break;\n }\n }\n\n void drawTens(int v) {\n switch (v) {\n case 1:\n horizontal(0, 4, 0);\n break;\n case 2:\n horizontal(0, 4, 4);\n break;\n case 3:\n diagu(0, 4, 4);\n break;\n case 4:\n diagd(0, 4, 0);\n break;\n case 5:\n drawTens(1);\n drawTens(4);\n break;\n case 6:\n vertical(0, 4, 0);\n break;\n case 7:\n drawTens(1);\n drawTens(6);\n break;\n case 8:\n drawTens(2);\n drawTens(6);\n break;\n case 9:\n drawTens(1);\n drawTens(8);\n break;\n default:\n break;\n }\n }\n\n void drawHundreds(int hundreds) {\n switch (hundreds) {\n case 1:\n horizontal(6, 10, 14);\n break;\n case 2:\n horizontal(6, 10, 10);\n break;\n case 3:\n diagu(6, 10, 14);\n break;\n case 4:\n diagd(6, 10, 10);\n break;\n case 5:\n drawHundreds(1);\n drawHundreds(4);\n break;\n case 6:\n vertical(10, 14, 10);\n break;\n case 7:\n drawHundreds(1);\n drawHundreds(6);\n break;\n case 8:\n drawHundreds(2);\n drawHundreds(6);\n break;\n case 9:\n drawHundreds(1);\n drawHundreds(8);\n break;\n default:\n break;\n }\n }\n\n void drawThousands(int thousands) {\n switch (thousands) {\n case 1:\n horizontal(0, 4, 14);\n break;\n case 2:\n horizontal(0, 4, 10);\n break;\n case 3:\n diagd(0, 4, 10);\n break;\n case 4:\n diagu(0, 4, 14);\n break;\n case 5:\n drawThousands(1);\n drawThousands(4);\n break;\n case 6:\n vertical(10, 14, 0);\n break;\n case 7:\n drawThousands(1);\n drawThousands(6);\n break;\n case 8:\n drawThousands(2);\n drawThousands(6);\n break;\n case 9:\n drawThousands(1);\n drawThousands(8);\n break;\n default:\n break;\n }\n }\n\n void draw(int v) {\n int thousands = v / 1000;\n v %= 1000;\n\n int hundreds = v / 100;\n v %= 100;\n\n int tens = v / 10;\n int ones = v % 10;\n\n if (thousands > 0) {\n drawThousands(thousands);\n }\n if (hundreds > 0) {\n drawHundreds(hundreds);\n }\n if (tens > 0) {\n drawTens(tens);\n }\n if (ones > 0) {\n drawOnes(ones);\n }\n }\n};\n\nstd::ostream &operator<<(std::ostream &os, const Cistercian &c) {\n for (auto &row : c.canvas) {\n for (auto cell : row) {\n os << cell;\n }\n os << '\\n';\n }\n return os;\n}\n\nint main() {\n for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) {\n std::cout << number << \":\\n\";\n\n Cistercian c(number);\n std::cout << c << '\\n';\n }\n\n return 0;\n}"} -{"title": "Cistercian numerals", "language": "JavaScript", "task": "Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from '''0''' to '''9999'''.\n\n;How they work\nAll Cistercian numerals begin with a vertical line segment, which by itself represents the number '''0'''. Then, glyphs representing the digits '''1''' through '''9''' are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number:\n\n:* The '''upper-right''' quadrant represents the '''ones''' place.\n:* The '''upper-left''' quadrant represents the '''tens''' place.\n:* The '''lower-right''' quadrant represents the '''hundreds''' place.\n:* The '''lower-left''' quadrant represents the '''thousands''' place.\n\nPlease consult the following image for examples of Cistercian numerals showing each glyph: [https://upload.wikimedia.org/wikipedia/commons/6/67/Cistercian_digits_%28vertical%29.svg]\n\n;Task\n\n:* Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile).\n\n:* Use the routine to show the following Cistercian numerals:\n\n::* 0\n::* 1\n::* 20\n::* 300\n::* 4000\n::* 5555\n::* 6789\n::* And a number of your choice!\n\n;Notes\nDue to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed -- especially for text output.\n\n;See also\n\n:* '''Numberphile - The Forgotten Number System'''\n:* '''dcode.fr - Online Cistercian numeral converter'''\n", "solution": "// html\ndocument.write(`\n

\n

\n

\n \n \n \n \n \n \n \n \n

\n`);\n\n// to show given examples\n// can be deleted for normal use\nfunction set(num) {\n document.getElementById('num').value = num;\n showCist();\n}\n\nconst SW = 10; // stroke width\nlet canvas = document.getElementById('cist'),\n cx = canvas.getContext('2d');\n\nfunction showCist() {\n // reset canvas\n cx.clearRect(0, 0, canvas.width, canvas.height);\n cx.lineWidth = SW;\n cx.beginPath();\n cx.moveTo(100, 0+.5*SW);\n cx.lineTo(100, 300-.5*SW);\n cx.stroke();\n\n let num = document.getElementById('num').value;\n while (num.length < 4) num = '0' + num; // fills leading zeros to $num\n\n /***********************\\\n | POINTS: |\n | ********************* |\n | |\n | a --- b --- c |\n | | | | |\n | d --- e --- f |\n | | | | |\n | g --- h --- i |\n | | | | |\n | j --- k --- l |\n | |\n \\***********************/\n let\n a = [0+SW, 0+SW], b = [100, 0+SW], c = [200-SW, 0+SW],\n d = [0+SW, 100], e = [100, 100], f = [200-SW, 100],\n g = [0+SW, 200], h = [100, 200], i = [200-SW, 200],\n j = [0+SW, 300-SW], k = [100, 300-SW], l = [200-SW, 300-SW];\n\n function draw() {\n let x = 1;\n cx.beginPath();\n cx.moveTo(arguments[0][0], arguments[0][1]);\n while (x < arguments.length) {\n cx.lineTo(arguments[x][0], arguments[x][1]);\n x++;\n }\n cx.stroke();\n }\n\n // 1000s\n switch (num[0]) {\n case '1': draw(j, k); break; case '2': draw(g, h); break;\n case '3': draw(g, k); break; case '4': draw(j, h); break;\n case '5': draw(k, j, h); break; case '6': draw(g, j); break;\n case '7': draw(g, j, k); break; case '8': draw(j, g, h); break;\n case '9': draw(h, g, j, k); break;\n }\n // 100s\n switch (num[1]) {\n case '1': draw(k, l); break; case '2': draw(h, i); break;\n case '3': draw(k, i); break; case '4': draw(h, l); break;\n case '5': draw(h, l, k); break; case '6': draw(i, l); break;\n case '7': draw(k, l, i); break; case '8': draw(h, i, l); break;\n case '9': draw(h, i, l, k); break;\n }\n // 10s\n switch (num[2]) {\n case '1': draw(a, b); break; case '2': draw(d, e); break;\n case '3': draw(d, b); break; case '4': draw(a, e); break;\n case '5': draw(b, a, e); break; case '6': draw(a, d); break;\n case '7': draw(d, a, b); break; case '8': draw(a, d, e); break;\n case '9': draw(b, a, d, e); break;\n }\n // 1s\n switch (num[3]) {\n case '1': draw(b, c); break; case '2': draw(e, f); break;\n case '3': draw(b, f); break; case '4': draw(e, c); break;\n case '5': draw(b, c, e); break; case '6': draw(c, f); break;\n case '7': draw(b, c, f); break; case '8': draw(e, f, c); break;\n case '9': draw(b, c, f, e); break;\n }\n}\n"} -{"title": "Cistercian numerals", "language": "Python", "task": "Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from '''0''' to '''9999'''.\n\n;How they work\nAll Cistercian numerals begin with a vertical line segment, which by itself represents the number '''0'''. Then, glyphs representing the digits '''1''' through '''9''' are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number:\n\n:* The '''upper-right''' quadrant represents the '''ones''' place.\n:* The '''upper-left''' quadrant represents the '''tens''' place.\n:* The '''lower-right''' quadrant represents the '''hundreds''' place.\n:* The '''lower-left''' quadrant represents the '''thousands''' place.\n\nPlease consult the following image for examples of Cistercian numerals showing each glyph: [https://upload.wikimedia.org/wikipedia/commons/6/67/Cistercian_digits_%28vertical%29.svg]\n\n;Task\n\n:* Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile).\n\n:* Use the routine to show the following Cistercian numerals:\n\n::* 0\n::* 1\n::* 20\n::* 300\n::* 4000\n::* 5555\n::* 6789\n::* And a number of your choice!\n\n;Notes\nDue to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed -- especially for text output.\n\n;See also\n\n:* '''Numberphile - The Forgotten Number System'''\n:* '''dcode.fr - Online Cistercian numeral converter'''\n", "solution": "# -*- coding: utf-8 -*-\n\"\"\"\nSome UTF-8 chars used:\n \n\u203e\t8254\t203E\t‾\tOVERLINE\n\u2503\t9475\t2503\t \tBOX DRAWINGS HEAVY VERTICAL\n\u2571\t9585\t2571\t \tBOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT\n\u2572\t9586\t2572\t \tBOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT\n\u25f8\t9720\t25F8\t \tUPPER LEFT TRIANGLE\n\u25f9\t9721\t25F9\t \tUPPER RIGHT TRIANGLE\n\u25fa\t9722\t25FA\t \tLOWER LEFT TRIANGLE\n\u25fb\t9723\t25FB\t \tWHITE MEDIUM SQUARE\n\u25ff\t9727\t25FF\t \tLOWER RIGHT TRIANGLE\n\n\"\"\"\n\n#%% digit sections\n\ndef _init():\n \"digit sections for forming numbers\"\n digi_bits = \"\"\"\n#0 1 2 3 4 5 6 7 8 9\n#\n . \u203e _ \u2572 \u2571 \u25f8 .| \u203e| _| \u25fb\n#\n . \u203e _ \u2571 \u2572 \u25f9 |. |\u203e |_ \u25fb\n#\n . _ \u203e \u2571 \u2572 \u25fa .| _| \u203e| \u25fb\n#\n . _ \u203e \u2572 \u2571 \u25ff |. |_ |\u203e \u25fb\n \n\"\"\".strip()\n\n lines = [[d.replace('.', ' ') for d in ln.strip().split()]\n for ln in digi_bits.strip().split('\\n')\n if '#' not in ln]\n formats = '<2 >2 <2 >2'.split()\n digits = [[f\"{dig:{f}}\" for dig in line]\n for f, line in zip(formats, lines)]\n\n return digits\n\n_digits = _init()\n\n\n#%% int to 3-line strings\ndef _to_digits(n):\n assert 0 <= n < 10_000 and int(n) == n\n \n return [int(digit) for digit in f\"{int(n):04}\"][::-1]\n\ndef num_to_lines(n):\n global _digits\n d = _to_digits(n)\n lines = [\n ''.join((_digits[1][d[1]], '\u2503', _digits[0][d[0]])),\n ''.join((_digits[0][ 0], '\u2503', _digits[0][ 0])),\n ''.join((_digits[3][d[3]], '\u2503', _digits[2][d[2]])),\n ]\n \n return lines\n\ndef cjoin(c1, c2, spaces=' '):\n return [spaces.join(by_row) for by_row in zip(c1, c2)]\n\n#%% main\nif __name__ == '__main__':\n #n = 6666\n #print(f\"Arabic {n} to Cistercian:\\n\")\n #print('\\n'.join(num_to_lines(n)))\n \n for pow10 in range(4): \n step = 10 ** pow10\n print(f'\\nArabic {step}-to-{9*step} by {step} in Cistercian:\\n')\n lines = num_to_lines(step)\n for n in range(step*2, step*10, step):\n lines = cjoin(lines, num_to_lines(n))\n print('\\n'.join(lines))\n \n\n numbers = [0, 5555, 6789, 6666]\n print(f'\\nArabic {str(numbers)[1:-1]} in Cistercian:\\n')\n lines = num_to_lines(numbers[0])\n for n in numbers[1:]:\n lines = cjoin(lines, num_to_lines(n))\n print('\\n'.join(lines))"} -{"title": "Closures/Value capture", "language": "C", "task": "Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index '' i '' (you may choose to start '' i '' from either '''0''' or '''1'''), when run, should return the square of the index, that is, '' i '' 2. \n\nDisplay the result of running any but the last function, to demonstrate that the function indeed remembers its value.\n\n\n;Goal:\nDemonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. \n\nIn imperative languages, one would generally use a loop with a mutable counter variable. \n\nFor each function to maintain the correct number, it has to capture the ''value'' of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.\n\nSee also: [[Multiple distinct objects]]\n", "solution": "#include \n#include \n#include \n#include \n\ntypedef int (*f_int)();\n \n#define TAG 0xdeadbeef\nint _tmpl() { \n\tvolatile int x = TAG;\n\treturn x * x;\n}\n\n#define PROT (PROT_EXEC | PROT_WRITE)\n#define FLAGS (MAP_PRIVATE | MAP_ANONYMOUS) \nf_int dupf(int v)\n{\n\tsize_t len = (void*)dupf - (void*)_tmpl;\n\tf_int ret = mmap(NULL, len, PROT, FLAGS, 0, 0);\n\tchar *p;\n\tif(ret == MAP_FAILED) {\n\t\tperror(\"mmap\");\n\t\texit(-1);\n\t}\n\tmemcpy(ret, _tmpl, len);\n\tfor (p = (char*)ret; p < (char*)ret + len - sizeof(int); p++)\n\t\tif (*(int *)p == TAG) *(int *)p = v;\n\treturn ret;\n}\n \nint main()\n{\n\tf_int funcs[10];\n\tint i;\n\tfor (i = 0; i < 10; i++) funcs[i] = dupf(i);\n \n\tfor (i = 0; i < 9; i++)\n\t\tprintf(\"func[%d]: %d\\n\", i, funcs[i]());\n \n\treturn 0;\n}"} -{"title": "Closures/Value capture", "language": "C++11", "task": "Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index '' i '' (you may choose to start '' i '' from either '''0''' or '''1'''), when run, should return the square of the index, that is, '' i '' 2. \n\nDisplay the result of running any but the last function, to demonstrate that the function indeed remembers its value.\n\n\n;Goal:\nDemonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. \n\nIn imperative languages, one would generally use a loop with a mutable counter variable. \n\nFor each function to maintain the correct number, it has to capture the ''value'' of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.\n\nSee also: [[Multiple distinct objects]]\n", "solution": "#include \n#include \n#include \n\nint main() {\n std::vector > funcs;\n for (int i = 0; i < 10; i++)\n funcs.push_back([=]() { return i * i; });\n for ( std::function f : funcs ) \n std::cout << f( ) << std::endl ; \n return 0;\n}"} -{"title": "Closures/Value capture", "language": "JavaScript", "task": "Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index '' i '' (you may choose to start '' i '' from either '''0''' or '''1'''), when run, should return the square of the index, that is, '' i '' 2. \n\nDisplay the result of running any but the last function, to demonstrate that the function indeed remembers its value.\n\n\n;Goal:\nDemonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. \n\nIn imperative languages, one would generally use a loop with a mutable counter variable. \n\nFor each function to maintain the correct number, it has to capture the ''value'' of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.\n\nSee also: [[Multiple distinct objects]]\n", "solution": "var funcs = [];\nfor (var i = 0; i < 10; i++) {\n funcs.push( (function(i) {\n return function() { return i * i; }\n })(i) );\n}\nwindow.alert(funcs[3]()); // alerts \"9\""} -{"title": "Closures/Value capture", "language": "JavaScript 1.7+", "task": "Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index '' i '' (you may choose to start '' i '' from either '''0''' or '''1'''), when run, should return the square of the index, that is, '' i '' 2. \n\nDisplay the result of running any but the last function, to demonstrate that the function indeed remembers its value.\n\n\n;Goal:\nDemonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. \n\nIn imperative languages, one would generally use a loop with a mutable counter variable. \n\nFor each function to maintain the correct number, it has to capture the ''value'' of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.\n\nSee also: [[Multiple distinct objects]]\n", "solution": ""} -{"title": "Closures/Value capture", "language": "JavaScript ES5", "task": "Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index '' i '' (you may choose to start '' i '' from either '''0''' or '''1'''), when run, should return the square of the index, that is, '' i '' 2. \n\nDisplay the result of running any but the last function, to demonstrate that the function indeed remembers its value.\n\n\n;Goal:\nDemonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. \n\nIn imperative languages, one would generally use a loop with a mutable counter variable. \n\nFor each function to maintain the correct number, it has to capture the ''value'' of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.\n\nSee also: [[Multiple distinct objects]]\n", "solution": "(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": "Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index '' i '' (you may choose to start '' i '' from either '''0''' or '''1'''), when run, should return the square of the index, that is, '' i '' 2. \n\nDisplay the result of running any but the last function, to demonstrate that the function indeed remembers its value.\n\n\n;Goal:\nDemonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. \n\nIn imperative languages, one would generally use a loop with a mutable counter variable. \n\nFor each function to maintain the correct number, it has to capture the ''value'' of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.\n\nSee also: [[Multiple distinct objects]]\n", "solution": "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, (2x4)8, (4x7)28, (7x5)35, (5x3)15, (2x4x7)56, (4x7x5)140, (7x5x3)105, (2x4x7x5)280, (4x7x5x3)420, (2x4x7x5x3)840\n\nEvery product is unique.\n\n\n2346 is '''not''' a colorful number. 2, 3, 4, '''6''', (2x3)'''6''', (3x4)12, (4x6)24, (2x3x4)48, (3x4x6)72, (2x3x4x6)144\n\nThe product '''6''' is repeated.\n\n\nSingle digit numbers '''are''' considered to be colorful. A colorful number larger than 9 cannot contain a repeated digit, the digit 0 or the digit 1. As a consequence, there is a firm upper limit for colorful numbers; no colorful number can have more than 8 digits.\n\n\n;Task\n\n* Write a routine (subroutine, function, procedure, whatever it may be called in your language) to test if a number is a colorful number or not.\n* Use that routine to find all of the colorful numbers less than 100.\n* Use that routine to find the largest possible colorful number.\n\n\n;Stretch\n\n* Find and display the count of colorful numbers in each order of magnitude.\n* Find and show the total count of '''all''' colorful numbers.\n\n\n''Colorful numbers have no real number theory application. They are more a recreational math puzzle than a useful tool.''\n\n", "solution": "#include \n#include \n#include \n#include \n\nbool colorful(int n) {\n // A colorful number cannot be greater than 98765432.\n if (n < 0 || n > 98765432)\n return false;\n int digit_count[10] = {};\n int digits[8] = {};\n int num_digits = 0;\n for (int m = n; m > 0; m /= 10) {\n int d = m % 10;\n if (n > 9 && (d == 0 || d == 1))\n return false;\n if (++digit_count[d] > 1)\n return false;\n digits[num_digits++] = d;\n }\n // Maximum number of products is (8 x 9) / 2.\n int products[36] = {};\n for (int i = 0, product_count = 0; i < num_digits; ++i) {\n for (int j = i, p = 1; j < num_digits; ++j) {\n p *= digits[j];\n for (int k = 0; k < product_count; ++k) {\n if (products[k] == p)\n return false;\n }\n products[product_count++] = p;\n }\n }\n return true;\n}\n\nstatic int count[8];\nstatic bool used[10];\nstatic int largest = 0;\n\nvoid count_colorful(int taken, int n, int digits) {\n if (taken == 0) {\n for (int d = 0; d < 10; ++d) {\n used[d] = true;\n count_colorful(d < 2 ? 9 : 1, d, 1);\n used[d] = false;\n }\n } else {\n if (colorful(n)) {\n ++count[digits - 1];\n if (n > largest)\n largest = n;\n }\n if (taken < 9) {\n for (int d = 2; d < 10; ++d) {\n if (!used[d]) {\n used[d] = true;\n count_colorful(taken + 1, n * 10 + d, digits + 1);\n used[d] = false;\n }\n }\n }\n }\n}\n\nint main() {\n setlocale(LC_ALL, \"\");\n\n clock_t start = clock();\n\n printf(\"Colorful numbers less than 100:\\n\");\n for (int n = 0, count = 0; n < 100; ++n) {\n if (colorful(n))\n printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n }\n\n count_colorful(0, 0, 0);\n printf(\"\\n\\nLargest colorful number: %'d\\n\", largest);\n\n printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n int total = 0;\n for (int d = 0; d < 8; ++d) {\n printf(\"%d %'d\\n\", d + 1, count[d]);\n total += count[d];\n }\n printf(\"\\nTotal: %'d\\n\", total);\n\n clock_t end = clock();\n printf(\"\\nElapsed time: %f seconds\\n\",\n (end - start + 0.0) / CLOCKS_PER_SEC);\n return 0;\n}"} -{"title": "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, (2x4)8, (4x7)28, (7x5)35, (5x3)15, (2x4x7)56, (4x7x5)140, (7x5x3)105, (2x4x7x5)280, (4x7x5x3)420, (2x4x7x5x3)840\n\nEvery product is unique.\n\n\n2346 is '''not''' a colorful number. 2, 3, 4, '''6''', (2x3)'''6''', (3x4)12, (4x6)24, (2x3x4)48, (3x4x6)72, (2x3x4x6)144\n\nThe product '''6''' is repeated.\n\n\nSingle digit numbers '''are''' considered to be colorful. A colorful number larger than 9 cannot contain a repeated digit, the digit 0 or the digit 1. As a consequence, there is a firm upper limit for colorful numbers; no colorful number can have more than 8 digits.\n\n\n;Task\n\n* Write a routine (subroutine, function, procedure, whatever it may be called in your language) to test if a number is a colorful number or not.\n* Use that routine to find all of the colorful numbers less than 100.\n* Use that routine to find the largest possible colorful number.\n\n\n;Stretch\n\n* Find and display the count of colorful numbers in each order of magnitude.\n* Find and show the total count of '''all''' colorful numbers.\n\n\n''Colorful numbers have no real number theory application. They are more a recreational math puzzle than a useful tool.''\n\n", "solution": "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": "Display a series of vertical color bars across the width of the display. \n\nThe color bars should either use:\n:::* the system palette, or \n:::* the sequence of colors: \n::::::* black\n::::::* red\n::::::* green\n::::::* blue\n::::::* magenta\n::::::* cyan\n::::::* yellow\n::::::* white\n\n", "solution": "#include\n\n#define COLOURS 8\n\nint main()\n{\n\tint colour=0,i,j,MAXROW,MAXCOL;\n\tstruct text_info tInfo;\n\tgettextinfo(&tInfo);\n\tMAXROW = tInfo.screenheight;\n\tMAXCOL = tInfo.screenwidth;\n\ttextbackground(BLACK); //8 colour constants are defined\n\tclrscr();\n\t\n\tfor(colour=0;colour\n#include \"colorbars.h\"\n\nMyWidget::MyWidget( ) :\n width( 640 ) ,\n height( 240 ) ,\n colornumber( 8 ) {\n setGeometry( 0, 0 , width , height ) ;\n}\n\nvoid MyWidget::paintEvent ( QPaintEvent * ) {\n int rgbtriplets[ ] = { 0 , 0 , 0 , 255 , 0 , 0 , 0 , 255 , 0 , \n 0 , 0 , 255 , 255 , 0 , 255 , 0 , 255 , 255 , 255 , 255 , 0 ,\n 255 , 255 , 255 } ; \n QPainter myPaint( this ) ;\n int rectwidth = width / colornumber ; //width of one rectangle\n int xstart = 1 ; //x coordinate of the first rectangle\n int offset = -1 ; //to allow for ++offset to define the red value even in the first run of the loop below\n for ( int i = 0 ; i < colornumber ; i++ ) {\n QColor rectColor ;\n rectColor.setRed( rgbtriplets[ ++offset ] ) ;\n rectColor.setGreen( rgbtriplets[ ++offset ] ) ;\n rectColor.setBlue( rgbtriplets[ ++offset ] ) ;\n myPaint.fillRect( xstart , 0 , rectwidth , height - 1 , rectColor ) ;\n xstart += rectwidth + 1 ;\n }\n}"} -{"title": "Colour bars/Display", "language": "Python", "task": "Display a series of vertical color bars across the width of the display. \n\nThe color bars should either use:\n:::* the system palette, or \n:::* the sequence of colors: \n::::::* black\n::::::* red\n::::::* green\n::::::* blue\n::::::* magenta\n::::::* cyan\n::::::* yellow\n::::::* white\n\n", "solution": "#!/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": "from 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 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": "C++", "task": "Comma quibbling is a task originally set by Eric Lippert in his 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\ntemplate\nvoid quibble(std::ostream& o, T i, T e) {\n o << \"{\";\n if (e != i) {\n T n = i++;\n const char* more = \"\";\n while (e != i) {\n o << more << *n;\n more = \", \";\n n = i++;\n }\n o << (*more?\" and \":\"\") << *n;\n }\n o << \"}\";\n}\n\nint main(int argc, char** argv) {\n char const* a[] = {\"ABC\",\"DEF\",\"G\",\"H\"};\n for (int i=0; i<5; i++) {\n quibble(std::cout, a, a+i);\n std::cout << std::endl;\n }\n return 0;\n}"} -{"title": "Comma quibbling", "language": "JavaScript", "task": "Comma quibbling is a task originally set by Eric Lippert in his 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": "JavaScript from Haskell", "task": "Comma quibbling is a task originally set by Eric Lippert in his 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": "(() => {\n 'use strict';\n\n // ----------------- COMMA QUIBBLING -----------------\n\n // quibble :: [String] -> String\n const quibble = xs =>\n 1 < xs.length ? (\n intercalate(' and ')(\n ap([\n compose(\n intercalate(', '), \n reverse, \n tail\n ),\n head\n ])([reverse(xs)])\n )\n ) : concat(xs);\n\n\n // ---------------------- TEST -----------------------\n const main = () =>\n unlines(\n map(compose(x => '{' + x + '}', quibble))(\n append([\n [],\n [\"ABC\"],\n [\"ABC\", \"DEF\"],\n [\"ABC\", \"DEF\", \"G\", \"H\"]\n ])(\n map(words)([\n \"One two three four\",\n \"Me myself I\",\n \"Jack Jill\",\n \"Loner\"\n ])\n )\n ));\n\n\n // ---------------- GENERIC FUNCTIONS ----------------\n\n // ap (<*>) :: [(a -> b)] -> [a] -> [b]\n const ap = fs =>\n // The sequential application of each of a list\n // of functions to each of a list of values.\n // apList([x => 2 * x, x => 20 + x])([1, 2, 3])\n // -> [2, 4, 6, 21, 22, 23]\n xs => fs.flatMap(f => xs.map(f));\n\n\n // append (++) :: [a] -> [a] -> [a]\n const append = xs =>\n // A list defined by the\n // concatenation of two others.\n ys => xs.concat(ys);\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 // concat :: [[a]] -> [a]\n // concat :: [String] -> String\n const concat = xs => (\n ys => 0 < ys.length ? (\n ys.every(Array.isArray) ? (\n []\n ) : ''\n ).concat(...ys) : ys\n )(xs);\n\n\n // head :: [a] -> a\n const head = xs => (\n ys => ys.length ? (\n ys[0]\n ) : undefined\n )(list(xs));\n\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\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 // 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 // reverse :: [a] -> [a]\n const reverse = xs =>\n 'string' !== typeof xs ? (\n xs.slice(0).reverse()\n ) : xs.split('').reverse().join('');\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 xs.slice(1);\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 // words :: String -> [String]\n const words = s =>\n // List of space-delimited sub-strings.\n s.split(/\\s+/);\n\n // MAIN ---\n return main();\n})();"} -{"title": "Comma quibbling", "language": "Python", "task": "Comma quibbling is a task originally set by Eric Lippert in his 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": "{{selection|Short Circuit|Console Program Basics}} Retrieve the list of command-line arguments given to the program. For programs that only print the arguments when run directly, see [[Scripted main]].\nSee also [[Program name]].\n\nFor parsing command line arguments intelligently, see [[Parsing command-line arguments]].\n\nExample command line:\n\n myprogram -c \"alpha beta\" -h \"gamma\"\n\n", "solution": "#include \n#include \n\nint main(int argc, char* argv[])\n{\n int i;\n (void) printf(\"This program is named %s.\\n\", argv[0]);\n for (i = 1; i < argc; ++i)\n (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n return EXIT_SUCCESS;\n}"} -{"title": "Command-line arguments", "language": "C++", "task": "{{selection|Short Circuit|Console Program Basics}} Retrieve the list of command-line arguments given to the program. For programs that only print the arguments when run directly, see [[Scripted main]].\nSee also [[Program name]].\n\nFor parsing command line arguments intelligently, see [[Parsing command-line arguments]].\n\nExample command line:\n\n myprogram -c \"alpha beta\" -h \"gamma\"\n\n", "solution": "#include \n\nint main(int argc, const char* argv[]) {\n std::cout << \"This program is named \" << argv[0] << '\\n'\n << \"There are \" << argc - 1 << \" arguments given.\\n\";\n for (int i = 1; i < argc; ++i)\n std::cout << \"The argument #\" << i << \" is \" << argv[i] << '\\n';\n}"} -{"title": "Command-line arguments", "language": "Python", "task": "{{selection|Short Circuit|Console Program Basics}} Retrieve the list of command-line arguments given to the program. For programs that only print the arguments when run directly, see [[Scripted main]].\nSee also [[Program name]].\n\nFor parsing command line arguments intelligently, see [[Parsing command-line arguments]].\n\nExample command line:\n\n myprogram -c \"alpha beta\" -h \"gamma\"\n\n", "solution": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)"} -{"title": "Compare a list of strings", "language": "C", "task": "Given a list of arbitrarily many strings, show how to:\n\n* test if they are all lexically '''equal'''\n* test if every string is lexically '''less than''' the one after it ''(i.e. whether the list is in strict ascending order)''\n\n\nEach of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar. \n\nIf the input list has less than two elements, the tests should always return true.\n\nThere is ''no'' need to provide a complete program and output.\n \nAssume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible.\n\nTry to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers.\n\nIf you need further guidance/clarification, see [[#Perl]] and [[#Python]] for solutions that use implicit short-circuiting loops, and [[#Raku]] for a solution that gets away with simply using a built-in language feature. \n\n", "solution": "#include \n#include \n\nstatic bool\nstrings_are_equal(const char **strings, size_t nstrings)\n{\n for (size_t i = 1; i < nstrings; i++)\n if (strcmp(strings[0], strings[i]) != 0)\n return false;\n return true;\n}\n\nstatic bool\nstrings_are_in_ascending_order(const char **strings, size_t nstrings)\n{\n for (size_t i = 1; i < nstrings; i++)\n if (strcmp(strings[i - 1], strings[i]) >= 0)\n return false;\n return true;\n}"} -{"title": "Compare a list of strings", "language": "C++", "task": "Given a list of arbitrarily many strings, show how to:\n\n* test if they are all lexically '''equal'''\n* test if every string is lexically '''less than''' the one after it ''(i.e. whether the list is in strict ascending order)''\n\n\nEach of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar. \n\nIf the input list has less than two elements, the tests should always return true.\n\nThere is ''no'' need to provide a complete program and output.\n \nAssume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible.\n\nTry to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers.\n\nIf you need further guidance/clarification, see [[#Perl]] and [[#Python]] for solutions that use implicit short-circuiting loops, and [[#Raku]] for a solution that gets away with simply using a built-in language feature. \n\n", "solution": "Assuming that the strings variable is of type T<std::string> where T is an ordered STL container such as std::vector:\n\n"} -{"title": "Compare a list of strings", "language": "C++ 11", "task": "Given a list of arbitrarily many strings, show how to:\n\n* test if they are all lexically '''equal'''\n* test if every string is lexically '''less than''' the one after it ''(i.e. whether the list is in strict ascending order)''\n\n\nEach of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar. \n\nIf the input list has less than two elements, the tests should always return true.\n\nThere is ''no'' need to provide a complete program and output.\n \nAssume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible.\n\nTry to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers.\n\nIf you need further guidance/clarification, see [[#Perl]] and [[#Python]] for solutions that use implicit short-circuiting loops, and [[#Raku]] for a solution that gets away with simply using a built-in language feature. \n\n", "solution": "#include \n#include \n\n// Bug: calling operator++ on an empty collection invokes undefined behavior.\nstd::all_of( ++(strings.begin()), strings.end(),\n [&](std::string a){ return a == strings.front(); } ) // All equal\n\nstd::is_sorted( strings.begin(), strings.end(),\n [](std::string a, std::string b){ return !(b < a); }) ) // Strictly ascending"} -{"title": "Compare a list of strings", "language": "JavaScript", "task": "Given a list of arbitrarily many strings, show how to:\n\n* test if they are all lexically '''equal'''\n* test if every string is lexically '''less than''' the one after it ''(i.e. whether the list is in strict ascending order)''\n\n\nEach of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar. \n\nIf the input list has less than two elements, the tests should always return true.\n\nThere is ''no'' need to provide a complete program and output.\n \nAssume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible.\n\nTry to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers.\n\nIf you need further guidance/clarification, see [[#Perl]] and [[#Python]] for solutions that use implicit short-circuiting loops, and [[#Raku]] for a solution that gets away with simply using a built-in language feature. \n\n", "solution": "(() => {\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})();"} -{"title": "Compare a list of strings", "language": "Python", "task": "Given a list of arbitrarily many strings, show how to:\n\n* test if they are all lexically '''equal'''\n* test if every string is lexically '''less than''' the one after it ''(i.e. whether the list is in strict ascending order)''\n\n\nEach of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar. \n\nIf the input list has less than two elements, the tests should always return true.\n\nThere is ''no'' need to provide a complete program and output.\n \nAssume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible.\n\nTry to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers.\n\nIf you need further guidance/clarification, see [[#Perl]] and [[#Python]] for solutions that use implicit short-circuiting loops, and [[#Raku]] for a solution that gets away with simply using a built-in language feature. \n\n", "solution": "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 10! (ten factorial) at compile time. \n\nPrint the result when the program is run.\n\nDiscuss what limitations apply to compile-time calculations in your language.\n\n", "solution": "#include \n#include \n\n#define ORDER_PP_DEF_8fac ORDER_PP_FN( \\\n8fn(8X, 8seq_fold(8times, 1, 8seq_iota(1, 8inc(8X)))) )\n\nint main(void) {\n\tprintf(\"10! = %d\\n\", ORDER_PP( 8to_lit( 8fac(10) ) ) );\n\treturn 0;\n}"} -{"title": "Compile-time calculation", "language": "C++", "task": "Some programming languages allow calculation of values at compile time. \n\n\n;Task:\nCalculate 10! (ten factorial) at compile time. \n\nPrint the result when the program is run.\n\nDiscuss what limitations apply to compile-time calculations in your language.\n\n", "solution": "#include \n\ntemplate struct Fac\n{\n static const int result = i * Fac::result;\n};\n\ntemplate<> struct Fac<1>\n{\n static const int result = 1;\n};\n\n\nint main()\n{\n std::cout << \"10! = \" << Fac<10>::result << \"\\n\";\n return 0;\n}"} -{"title": "Compile-time calculation", "language": "C++11", "task": "Some programming languages allow calculation of values at compile time. \n\n\n;Task:\nCalculate 10! (ten factorial) at compile time. \n\nPrint the result when the program is run.\n\nDiscuss what limitations apply to compile-time calculations in your language.\n\n", "solution": "#include \n\nconstexpr int factorial(int n) {\n return n ? (n * factorial(n - 1)) : 1;\n}\n\nconstexpr int f10 = factorial(10);\n\nint main() {\n printf(\"%d\\n\", f10);\n return 0;\n}"} -{"title": "Compiler/AST interpreter", "language": "C", "task": "The C and Python versions can be considered reference implementations.\n\n;Related Tasks\n\n* Lexical Analyzer task\n* Syntax Analyzer task\n* Code Generator task\n* Virtual Machine Interpreter task\n\n\n__TOC__\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\n#define da_dim(name, type) type *name = NULL; \\\n int _qy_ ## name ## _p = 0; \\\n int _qy_ ## name ## _max = 0\n#define da_rewind(name) _qy_ ## name ## _p = 0\n#define da_redim(name) do {if (_qy_ ## name ## _p >= _qy_ ## name ## _max) \\\n name = realloc(name, (_qy_ ## name ## _max += 32) * sizeof(name[0]));} while (0)\n#define da_append(name, x) do {da_redim(name); name[_qy_ ## name ## _p++] = x;} while (0)\n#define da_len(name) _qy_ ## name ## _p\n#define da_add(name) do {da_redim(name); _qy_ ## name ## _p++;} while (0)\n\ntypedef enum {\n nd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While,\n nd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq,\n nd_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or\n} NodeType;\n\ntypedef struct Tree Tree;\nstruct Tree {\n NodeType node_type;\n Tree *left;\n Tree *right;\n int value;\n};\n\n// dependency: Ordered by NodeType, must remain in same order as NodeType enum\n\nstruct {\n char *enum_text;\n NodeType node_type;\n} atr[] = {\n {\"Identifier\" , nd_Ident, }, {\"String\" , nd_String, },\n {\"Integer\" , nd_Integer,}, {\"Sequence\" , nd_Sequence,},\n {\"If\" , nd_If, }, {\"Prtc\" , nd_Prtc, },\n {\"Prts\" , nd_Prts, }, {\"Prti\" , nd_Prti, },\n {\"While\" , nd_While, }, {\"Assign\" , nd_Assign, },\n {\"Negate\" , nd_Negate, }, {\"Not\" , nd_Not, },\n {\"Multiply\" , nd_Mul, }, {\"Divide\" , nd_Div, },\n {\"Mod\" , nd_Mod, }, {\"Add\" , nd_Add, },\n {\"Subtract\" , nd_Sub, }, {\"Less\" , nd_Lss, },\n {\"LessEqual\" , nd_Leq, }, {\"Greater\" , nd_Gtr, },\n {\"GreaterEqual\", nd_Geq, }, {\"Equal\" , nd_Eql, },\n {\"NotEqual\" , nd_Neq, }, {\"And\" , nd_And, },\n {\"Or\" , nd_Or, },\n};\n\nFILE *source_fp;\nda_dim(string_pool, const char *);\nda_dim(global_names, const char *);\nda_dim(global_values, int);\n\nvoid error(const char *fmt, ... ) {\n va_list ap;\n char buf[1000];\n\n va_start(ap, fmt);\n vsprintf(buf, fmt, ap);\n printf(\"error: %s\\n\", buf);\n exit(1);\n}\n\nTree *make_node(NodeType node_type, Tree *left, Tree *right) {\n Tree *t = calloc(sizeof(Tree), 1);\n t->node_type = node_type;\n t->left = left;\n t->right = right;\n return t;\n}\n\nTree *make_leaf(NodeType node_type, int value) {\n Tree *t = calloc(sizeof(Tree), 1);\n t->node_type = node_type;\n t->value = value;\n return t;\n}\n\nint interp(Tree *x) { /* interpret the parse tree */\n if (!x) return 0;\n switch(x->node_type) {\n case nd_Integer: return x->value;\n case nd_Ident: return global_values[x->value];\n case nd_String: return x->value;\n\n case nd_Assign: return global_values[x->left->value] = interp(x->right);\n case nd_Add: return interp(x->left) + interp(x->right);\n case nd_Sub: return interp(x->left) - interp(x->right);\n case nd_Mul: return interp(x->left) * interp(x->right);\n case nd_Div: return interp(x->left) / interp(x->right);\n case nd_Mod: return interp(x->left) % interp(x->right);\n case nd_Lss: return interp(x->left) < interp(x->right);\n case nd_Gtr: return interp(x->left) > interp(x->right);\n case nd_Leq: return interp(x->left) <= interp(x->right);\n case nd_Eql: return interp(x->left) == interp(x->right);\n case nd_Neq: return interp(x->left) != interp(x->right);\n case nd_And: return interp(x->left) && interp(x->right);\n case nd_Or: return interp(x->left) || interp(x->right); \n case nd_Negate: return -interp(x->left);\n case nd_Not: return !interp(x->left);\n\n case nd_If: if (interp(x->left))\n interp(x->right->left);\n else\n interp(x->right->right);\n return 0;\n\n case nd_While: while (interp(x->left))\n interp(x->right);\n return 0;\n\n case nd_Prtc: printf(\"%c\", interp(x->left));\n return 0;\n case nd_Prti: printf(\"%d\", interp(x->left));\n return 0;\n case nd_Prts: printf(\"%s\", string_pool[interp(x->left)]);\n return 0;\n\n case nd_Sequence: interp(x->left);\n interp(x->right);\n return 0;\n\n default: error(\"interp: unknown tree type %d\\n\", x->node_type);\n }\n return 0;\n}\n\nvoid init_in(const char fn[]) {\n if (fn[0] == '\\0')\n source_fp = stdin;\n else {\n source_fp = fopen(fn, \"r\");\n if (source_fp == NULL)\n error(\"Can't open %s\\n\", fn);\n }\n}\n\nNodeType get_enum_value(const char name[]) {\n for (size_t i = 0; i < sizeof(atr) / sizeof(atr[0]); i++) {\n if (strcmp(atr[i].enum_text, name) == 0) {\n return atr[i].node_type;\n }\n }\n error(\"Unknown token %s\\n\", name);\n return -1;\n}\n\nchar *read_line(int *len) {\n static char *text = NULL;\n static int textmax = 0;\n\n for (*len = 0; ; (*len)++) {\n int ch = fgetc(source_fp);\n if (ch == EOF || ch == '\\n') {\n if (*len == 0)\n return NULL;\n break;\n }\n if (*len + 1 >= textmax) {\n textmax = (textmax == 0 ? 128 : textmax * 2);\n text = realloc(text, textmax);\n }\n text[*len] = ch;\n }\n text[*len] = '\\0';\n return text;\n}\n\nchar *rtrim(char *text, int *len) { // remove trailing spaces\n for (; *len > 0 && isspace(text[*len - 1]); --(*len))\n ;\n\n text[*len] = '\\0';\n return text;\n}\n\nint fetch_string_offset(char *st) {\n int len = strlen(st);\n st[len - 1] = '\\0';\n ++st;\n char *p, *q;\n p = q = st;\n\n while ((*p++ = *q++) != '\\0') {\n if (q[-1] == '\\\\') {\n if (q[0] == 'n') {\n p[-1] = '\\n';\n ++q;\n } else if (q[0] == '\\\\') {\n ++q;\n }\n }\n }\n\n for (int i = 0; i < da_len(string_pool); ++i) {\n if (strcmp(st, string_pool[i]) == 0) {\n return i;\n }\n }\n da_add(string_pool);\n int n = da_len(string_pool) - 1;\n string_pool[n] = strdup(st);\n return da_len(string_pool) - 1;\n}\n\nint fetch_var_offset(const char *name) {\n for (int i = 0; i < da_len(global_names); ++i) {\n if (strcmp(name, global_names[i]) == 0)\n return i;\n }\n da_add(global_names);\n int n = da_len(global_names) - 1;\n global_names[n] = strdup(name);\n da_append(global_values, 0);\n return n;\n}\n\nTree *load_ast() {\n int len;\n char *yytext = read_line(&len);\n yytext = rtrim(yytext, &len);\n\n // get first token\n char *tok = strtok(yytext, \" \");\n\n if (tok[0] == ';') {\n return NULL;\n }\n NodeType node_type = get_enum_value(tok);\n\n // if there is extra data, get it\n char *p = tok + strlen(tok);\n if (p != &yytext[len]) {\n int n;\n for (++p; isspace(*p); ++p)\n ;\n switch (node_type) {\n case nd_Ident: n = fetch_var_offset(p); break;\n case nd_Integer: n = strtol(p, NULL, 0); break;\n case nd_String: n = fetch_string_offset(p); break;\n default: error(\"Unknown node type: %s\\n\", p);\n }\n return make_leaf(node_type, n);\n }\n\n Tree *left = load_ast();\n Tree *right = load_ast();\n return make_node(node_type, left, right);\n}\n\nint main(int argc, char *argv[]) {\n init_in(argc > 1 ? argv[1] : \"\");\n\n Tree *x = load_ast();\n interp(x);\n\n return 0;\n}"} -{"title": "Compiler/AST interpreter", "language": "Python", "task": "The C and Python versions can be considered reference implementations.\n\n;Related Tasks\n\n* Lexical Analyzer task\n* Syntax Analyzer task\n* Code Generator task\n* Virtual Machine Interpreter task\n\n\n__TOC__\n\n", "solution": "from __future__ import print_function\nimport sys, 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\ninput_file = None\nglobals = {}\n\n#*** show error and exit\ndef error(msg):\n print(\"%s\" % (msg))\n exit(1)\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 fetch_var(var_name):\n n = globals.get(var_name, None)\n if n == None:\n globals[var_name] = n = 0\n return n\n\n#***\ndef interp(x):\n global globals\n\n if x == None: return None\n elif x.node_type == nd_Integer: return int(x.value)\n elif x.node_type == nd_Ident: return fetch_var(x.value)\n elif x.node_type == nd_String: return x.value\n\n elif x.node_type == nd_Assign:\n globals[x.left.value] = interp(x.right)\n return None\n elif x.node_type == nd_Add: return interp(x.left) + interp(x.right)\n elif x.node_type == nd_Sub: return interp(x.left) - interp(x.right)\n elif x.node_type == nd_Mul: return interp(x.left) * interp(x.right)\n # use C like division semantics\n # another way: abs(x) / abs(y) * cmp(x, 0) * cmp(y, 0)\n elif x.node_type == nd_Div: return int(float(interp(x.left)) / interp(x.right))\n elif x.node_type == nd_Mod: return int(float(interp(x.left)) % interp(x.right))\n elif x.node_type == nd_Lss: return interp(x.left) < interp(x.right)\n elif x.node_type == nd_Gtr: return interp(x.left) > 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": "The C and Python versions can be considered reference implementations.\n\n;Related Tasks\n\n* Lexical Analyzer task\n* Syntax Analyzer task\n* Virtual Machine Interpreter task\n* AST Interpreter task\n\n\n__TOC__\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n\ntypedef unsigned char uchar;\n\ntypedef enum {\n nd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While,\n nd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq,\n nd_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or\n} NodeType;\n\ntypedef enum { FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND,\n OR, NEG, NOT, JMP, JZ, PRTC, PRTS, PRTI, HALT\n} Code_t;\n\ntypedef uchar code;\n\ntypedef struct Tree {\n NodeType node_type;\n struct Tree *left;\n struct Tree *right;\n char *value;\n} Tree;\n\n#define da_dim(name, type) type *name = NULL; \\\n int _qy_ ## name ## _p = 0; \\\n int _qy_ ## name ## _max = 0\n\n#define da_redim(name) do {if (_qy_ ## name ## _p >= _qy_ ## name ## _max) \\\n name = realloc(name, (_qy_ ## name ## _max += 32) * sizeof(name[0]));} while (0)\n\n#define da_rewind(name) _qy_ ## name ## _p = 0\n\n#define da_append(name, x) do {da_redim(name); name[_qy_ ## name ## _p++] = x;} while (0)\n#define da_len(name) _qy_ ## name ## _p\n#define da_add(name) do {da_redim(name); _qy_ ## name ## _p++;} while (0)\n\nFILE *source_fp, *dest_fp;\nstatic int here;\nda_dim(object, code);\nda_dim(globals, const char *);\nda_dim(string_pool, const char *);\n\n// dependency: Ordered by NodeType, must remain in same order as NodeType enum\nstruct {\n char *enum_text;\n NodeType node_type;\n Code_t opcode;\n} atr[] = {\n {\"Identifier\" , nd_Ident, -1 },\n {\"String\" , nd_String, -1 },\n {\"Integer\" , nd_Integer, -1 },\n {\"Sequence\" , nd_Sequence, -1 },\n {\"If\" , nd_If, -1 },\n {\"Prtc\" , nd_Prtc, -1 },\n {\"Prts\" , nd_Prts, -1 },\n {\"Prti\" , nd_Prti, -1 },\n {\"While\" , nd_While, -1 },\n {\"Assign\" , nd_Assign, -1 },\n {\"Negate\" , nd_Negate, NEG},\n {\"Not\" , nd_Not, NOT},\n {\"Multiply\" , nd_Mul, MUL},\n {\"Divide\" , nd_Div, DIV},\n {\"Mod\" , nd_Mod, MOD},\n {\"Add\" , nd_Add, ADD},\n {\"Subtract\" , nd_Sub, SUB},\n {\"Less\" , nd_Lss, LT },\n {\"LessEqual\" , nd_Leq, LE },\n {\"Greater\" , nd_Gtr, GT },\n {\"GreaterEqual\", nd_Geq, GE },\n {\"Equal\" , nd_Eql, EQ },\n {\"NotEqual\" , nd_Neq, NE },\n {\"And\" , nd_And, AND},\n {\"Or\" , nd_Or, OR },\n};\n\nvoid error(const char *fmt, ... ) {\n va_list ap;\n char buf[1000];\n\n va_start(ap, fmt);\n vsprintf(buf, fmt, ap);\n va_end(ap);\n printf(\"error: %s\\n\", buf);\n exit(1);\n}\n\nCode_t type_to_op(NodeType type) {\n return atr[type].opcode;\n}\n\nTree *make_node(NodeType node_type, Tree *left, Tree *right) {\n Tree *t = calloc(sizeof(Tree), 1);\n t->node_type = node_type;\n t->left = left;\n t->right = right;\n return t;\n}\n\nTree *make_leaf(NodeType node_type, char *value) {\n Tree *t = calloc(sizeof(Tree), 1);\n t->node_type = node_type;\n t->value = strdup(value);\n return t;\n}\n\n/*** Code generator ***/\n\nvoid emit_byte(int c) {\n da_append(object, (uchar)c);\n ++here;\n}\n\nvoid emit_int(int32_t n) {\n union {\n int32_t n;\n unsigned char c[sizeof(int32_t)];\n } x;\n\n x.n = n;\n\n for (size_t i = 0; i < sizeof(x.n); ++i) {\n emit_byte(x.c[i]);\n }\n}\n\nint hole() {\n int t = here;\n emit_int(0);\n return t;\n}\n\nvoid fix(int src, int dst) {\n *(int32_t *)(object + src) = dst-src;\n}\n\nint fetch_var_offset(const char *id) {\n for (int i = 0; i < da_len(globals); ++i) {\n if (strcmp(id, globals[i]) == 0)\n return i;\n }\n da_add(globals);\n int n = da_len(globals) - 1;\n globals[n] = strdup(id);\n return n;\n}\n\nint fetch_string_offset(const char *st) {\n for (int i = 0; i < da_len(string_pool); ++i) {\n if (strcmp(st, string_pool[i]) == 0)\n return i;\n }\n da_add(string_pool);\n int n = da_len(string_pool) - 1;\n string_pool[n] = strdup(st);\n return n;\n}\n\nvoid code_gen(Tree *x) {\n int p1, p2, n;\n\n if (x == NULL) return;\n switch (x->node_type) {\n case nd_Ident:\n emit_byte(FETCH);\n n = fetch_var_offset(x->value);\n emit_int(n);\n break;\n case nd_Integer:\n emit_byte(PUSH);\n emit_int(atoi(x->value));\n break;\n case nd_String:\n emit_byte(PUSH);\n n = fetch_string_offset(x->value);\n emit_int(n);\n break;\n case nd_Assign:\n n = fetch_var_offset(x->left->value);\n code_gen(x->right);\n emit_byte(STORE);\n emit_int(n);\n break;\n case nd_If:\n code_gen(x->left); // if expr\n emit_byte(JZ); // if false, jump\n p1 = hole(); // make room for jump dest\n code_gen(x->right->left); // if true statements\n if (x->right->right != NULL) {\n emit_byte(JMP);\n p2 = hole();\n }\n fix(p1, here);\n if (x->right->right != NULL) {\n code_gen(x->right->right);\n fix(p2, here);\n }\n break;\n case nd_While:\n p1 = here;\n code_gen(x->left); // while expr\n emit_byte(JZ); // if false, jump\n p2 = hole(); // make room for jump dest\n code_gen(x->right); // statements\n emit_byte(JMP); // back to the top\n fix(hole(), p1); // plug the top\n fix(p2, here); // plug the 'if false, jump'\n break;\n case nd_Sequence:\n code_gen(x->left);\n code_gen(x->right);\n break;\n case nd_Prtc:\n code_gen(x->left);\n emit_byte(PRTC);\n break;\n case nd_Prti:\n code_gen(x->left);\n emit_byte(PRTI);\n break;\n case nd_Prts:\n code_gen(x->left);\n emit_byte(PRTS);\n break;\n case nd_Lss: case nd_Gtr: case nd_Leq: case nd_Geq: case nd_Eql: case nd_Neq:\n case nd_And: case nd_Or: case nd_Sub: case nd_Add: case nd_Div: case nd_Mul:\n case nd_Mod:\n code_gen(x->left);\n code_gen(x->right);\n emit_byte(type_to_op(x->node_type));\n break;\n case nd_Negate: case nd_Not:\n code_gen(x->left);\n emit_byte(type_to_op(x->node_type));\n break;\n default:\n error(\"error in code generator - found %d, expecting operator\\n\", x->node_type);\n }\n}\n\nvoid code_finish() {\n emit_byte(HALT);\n}\n\nvoid list_code() {\n fprintf(dest_fp, \"Datasize: %d Strings: %d\\n\", da_len(globals), da_len(string_pool));\n for (int i = 0; i < da_len(string_pool); ++i)\n fprintf(dest_fp, \"%s\\n\", string_pool[i]);\n\n code *pc = object;\n\n again: fprintf(dest_fp, \"%5d \", (int)(pc - object));\n switch (*pc++) {\n case FETCH: fprintf(dest_fp, \"fetch [%d]\\n\", *(int32_t *)pc);\n pc += sizeof(int32_t); goto again;\n case STORE: fprintf(dest_fp, \"store [%d]\\n\", *(int32_t *)pc);\n pc += sizeof(int32_t); goto again;\n case PUSH : fprintf(dest_fp, \"push %d\\n\", *(int32_t *)pc);\n pc += sizeof(int32_t); goto again;\n case ADD : fprintf(dest_fp, \"add\\n\"); goto again;\n case SUB : fprintf(dest_fp, \"sub\\n\"); goto again;\n case MUL : fprintf(dest_fp, \"mul\\n\"); goto again;\n case DIV : fprintf(dest_fp, \"div\\n\"); goto again;\n case MOD : fprintf(dest_fp, \"mod\\n\"); goto again;\n case LT : fprintf(dest_fp, \"lt\\n\"); goto again;\n case GT : fprintf(dest_fp, \"gt\\n\"); goto again;\n case LE : fprintf(dest_fp, \"le\\n\"); goto again;\n case GE : fprintf(dest_fp, \"ge\\n\"); goto again;\n case EQ : fprintf(dest_fp, \"eq\\n\"); goto again;\n case NE : fprintf(dest_fp, \"ne\\n\"); goto again;\n case AND : fprintf(dest_fp, \"and\\n\"); goto again;\n case OR : fprintf(dest_fp, \"or\\n\"); goto again;\n case NOT : fprintf(dest_fp, \"not\\n\"); goto again;\n case NEG : fprintf(dest_fp, \"neg\\n\"); goto again;\n case JMP : fprintf(dest_fp, \"jmp (%d) %d\\n\",\n *(int32_t *)pc, (int32_t)(pc + *(int32_t *)pc - object));\n pc += sizeof(int32_t); goto again;\n case JZ : fprintf(dest_fp, \"jz (%d) %d\\n\",\n *(int32_t *)pc, (int32_t)(pc + *(int32_t *)pc - object));\n pc += sizeof(int32_t); goto again;\n case PRTC : fprintf(dest_fp, \"prtc\\n\"); goto again;\n case PRTI : fprintf(dest_fp, \"prti\\n\"); goto again;\n case PRTS : fprintf(dest_fp, \"prts\\n\"); goto again;\n case HALT : fprintf(dest_fp, \"halt\\n\"); break;\n default:error(\"listcode:Unknown opcode %d\\n\", *(pc - 1));\n }\n}\n\nvoid init_io(FILE **fp, FILE *std, const char mode[], const char fn[]) {\n if (fn[0] == '\\0')\n *fp = std;\n else if ((*fp = fopen(fn, mode)) == NULL)\n error(0, 0, \"Can't open %s\\n\", fn);\n}\n\nNodeType get_enum_value(const char name[]) {\n for (size_t i = 0; i < sizeof(atr) / sizeof(atr[0]); i++) {\n if (strcmp(atr[i].enum_text, name) == 0) {\n return atr[i].node_type;\n }\n }\n error(\"Unknown token %s\\n\", name);\n return -1;\n}\n\nchar *read_line(int *len) {\n static char *text = NULL;\n static int textmax = 0;\n\n for (*len = 0; ; (*len)++) {\n int ch = fgetc(source_fp);\n if (ch == EOF || ch == '\\n') {\n if (*len == 0)\n return NULL;\n break;\n }\n if (*len + 1 >= textmax) {\n textmax = (textmax == 0 ? 128 : textmax * 2);\n text = realloc(text, textmax);\n }\n text[*len] = ch;\n }\n text[*len] = '\\0';\n return text;\n}\n\nchar *rtrim(char *text, int *len) { // remove trailing spaces\n for (; *len > 0 && isspace(text[*len - 1]); --(*len))\n ;\n\n text[*len] = '\\0';\n return text;\n}\n\nTree *load_ast() {\n int len;\n char *yytext = read_line(&len);\n yytext = rtrim(yytext, &len);\n\n // get first token\n char *tok = strtok(yytext, \" \");\n\n if (tok[0] == ';') {\n return NULL;\n }\n NodeType node_type = get_enum_value(tok);\n\n // if there is extra data, get it\n char *p = tok + strlen(tok);\n if (p != &yytext[len]) {\n for (++p; isspace(*p); ++p)\n ;\n return make_leaf(node_type, p);\n }\n\n Tree *left = load_ast();\n Tree *right = load_ast();\n return make_node(node_type, left, right);\n}\n\nint main(int argc, char *argv[]) {\n init_io(&source_fp, stdin, \"r\", argc > 1 ? argv[1] : \"\");\n init_io(&dest_fp, stdout, \"wb\", argc > 2 ? argv[2] : \"\");\n\n code_gen(load_ast());\n code_finish();\n list_code();\n\n return 0;\n}"} -{"title": "Compiler/code generator", "language": "Python", "task": "The C and Python versions can be considered reference implementations.\n\n;Related Tasks\n\n* Lexical Analyzer task\n* Syntax Analyzer task\n* Virtual Machine Interpreter task\n* AST Interpreter task\n\n\n__TOC__\n\n", "solution": "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": "The C and Python versions can be considered reference implementations.\n\n\n;Related Tasks\n* Syntax Analyzer task\n* Code Generator task\n* Virtual Machine Interpreter task\n* AST Interpreter task\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define NELEMS(arr) (sizeof(arr) / sizeof(arr[0]))\n\n#define da_dim(name, type) type *name = NULL; \\\n int _qy_ ## name ## _p = 0; \\\n int _qy_ ## name ## _max = 0\n#define da_rewind(name) _qy_ ## name ## _p = 0\n#define da_redim(name) do {if (_qy_ ## name ## _p >= _qy_ ## name ## _max) \\\n name = realloc(name, (_qy_ ## name ## _max += 32) * sizeof(name[0]));} while (0)\n#define da_append(name, x) do {da_redim(name); name[_qy_ ## name ## _p++] = x;} while (0)\n#define da_len(name) _qy_ ## name ## _p\n\ntypedef enum {\n tk_EOI, tk_Mul, tk_Div, tk_Mod, tk_Add, tk_Sub, tk_Negate, tk_Not, tk_Lss, tk_Leq,\n tk_Gtr, tk_Geq, tk_Eq, tk_Neq, tk_Assign, tk_And, tk_Or, tk_If, tk_Else, tk_While,\n tk_Print, tk_Putc, tk_Lparen, tk_Rparen, tk_Lbrace, tk_Rbrace, tk_Semi, tk_Comma,\n tk_Ident, tk_Integer, tk_String\n} TokenType;\n\ntypedef struct {\n TokenType tok;\n int err_ln, err_col;\n union {\n int n; /* value for constants */\n char *text; /* text for idents */\n };\n} tok_s;\n\nstatic FILE *source_fp, *dest_fp;\nstatic int line = 1, col = 0, the_ch = ' ';\nda_dim(text, char);\n\ntok_s gettok(void);\n\nstatic void error(int err_line, int err_col, const char *fmt, ... ) {\n char buf[1000];\n va_list ap;\n\n va_start(ap, fmt);\n vsprintf(buf, fmt, ap);\n va_end(ap);\n printf(\"(%d,%d) error: %s\\n\", err_line, err_col, buf);\n exit(1);\n}\n\nstatic int next_ch(void) { /* get next char from input */\n the_ch = getc(source_fp);\n ++col;\n if (the_ch == '\\n') {\n ++line;\n col = 0;\n }\n return the_ch;\n}\n\nstatic tok_s char_lit(int n, int err_line, int err_col) { /* 'x' */\n if (the_ch == '\\'')\n error(err_line, err_col, \"gettok: empty character constant\");\n if (the_ch == '\\\\') {\n next_ch();\n if (the_ch == 'n')\n n = 10;\n else if (the_ch == '\\\\')\n n = '\\\\';\n else error(err_line, err_col, \"gettok: unknown escape sequence \\\\%c\", the_ch);\n }\n if (next_ch() != '\\'')\n error(err_line, err_col, \"multi-character constant\");\n next_ch();\n return (tok_s){tk_Integer, err_line, err_col, {n}};\n}\n\nstatic tok_s div_or_cmt(int err_line, int err_col) { /* process divide or comments */\n if (the_ch != '*')\n return (tok_s){tk_Div, err_line, err_col, {0}};\n\n /* comment found */\n next_ch();\n for (;;) {\n if (the_ch == '*') {\n if (next_ch() == '/') {\n next_ch();\n return gettok();\n }\n } else if (the_ch == EOF)\n error(err_line, err_col, \"EOF in comment\");\n else\n next_ch();\n }\n}\n\nstatic tok_s string_lit(int start, int err_line, int err_col) { /* \"st\" */\n da_rewind(text);\n\n while (next_ch() != start) {\n if (the_ch == '\\n') error(err_line, err_col, \"EOL in string\");\n if (the_ch == EOF) error(err_line, err_col, \"EOF in string\");\n da_append(text, (char)the_ch);\n }\n da_append(text, '\\0');\n\n next_ch();\n return (tok_s){tk_String, err_line, err_col, {.text=text}};\n}\n\nstatic int kwd_cmp(const void *p1, const void *p2) {\n return strcmp(*(char **)p1, *(char **)p2);\n}\n\nstatic TokenType get_ident_type(const char *ident) {\n static struct {\n const char *s;\n TokenType sym;\n } kwds[] = {\n {\"else\", tk_Else},\n {\"if\", tk_If},\n {\"print\", tk_Print},\n {\"putc\", tk_Putc},\n {\"while\", tk_While},\n }, *kwp;\n\n return (kwp = bsearch(&ident, kwds, NELEMS(kwds), sizeof(kwds[0]), kwd_cmp)) == NULL ? tk_Ident : kwp->sym;\n}\n\nstatic tok_s ident_or_int(int err_line, int err_col) {\n int n, is_number = true;\n\n da_rewind(text);\n while (isalnum(the_ch) || the_ch == '_') {\n da_append(text, (char)the_ch);\n if (!isdigit(the_ch))\n is_number = false;\n next_ch();\n }\n if (da_len(text) == 0)\n error(err_line, err_col, \"gettok: unrecognized character (%d) '%c'\\n\", the_ch, the_ch);\n da_append(text, '\\0');\n if (isdigit(text[0])) {\n if (!is_number)\n error(err_line, err_col, \"invalid number: %s\\n\", text);\n n = strtol(text, NULL, 0);\n if (n == LONG_MAX && errno == ERANGE)\n error(err_line, err_col, \"Number exceeds maximum value\");\n return (tok_s){tk_Integer, err_line, err_col, {n}};\n }\n return (tok_s){get_ident_type(text), err_line, err_col, {.text=text}};\n}\n\nstatic tok_s follow(int expect, TokenType ifyes, TokenType ifno, int err_line, int err_col) { /* look ahead for '>=', etc. */\n if (the_ch == expect) {\n next_ch();\n return (tok_s){ifyes, err_line, err_col, {0}};\n }\n if (ifno == tk_EOI)\n error(err_line, err_col, \"follow: unrecognized character '%c' (%d)\\n\", the_ch, the_ch);\n return (tok_s){ifno, err_line, err_col, {0}};\n}\n\ntok_s gettok(void) { /* return the token type */\n /* skip white space */\n while (isspace(the_ch))\n next_ch();\n int err_line = line;\n int err_col = col;\n switch (the_ch) {\n case '{': next_ch(); return (tok_s){tk_Lbrace, err_line, err_col, {0}};\n case '}': next_ch(); return (tok_s){tk_Rbrace, err_line, err_col, {0}};\n case '(': next_ch(); return (tok_s){tk_Lparen, err_line, err_col, {0}};\n case ')': next_ch(); return (tok_s){tk_Rparen, err_line, err_col, {0}};\n case '+': next_ch(); return (tok_s){tk_Add, err_line, err_col, {0}};\n case '-': next_ch(); return (tok_s){tk_Sub, err_line, err_col, {0}};\n case '*': next_ch(); return (tok_s){tk_Mul, err_line, err_col, {0}};\n case '%': next_ch(); return (tok_s){tk_Mod, err_line, err_col, {0}};\n case ';': next_ch(); return (tok_s){tk_Semi, err_line, err_col, {0}};\n case ',': next_ch(); return (tok_s){tk_Comma,err_line, err_col, {0}};\n case '/': next_ch(); return div_or_cmt(err_line, err_col);\n case '\\'': next_ch(); return char_lit(the_ch, err_line, err_col);\n case '<': next_ch(); return follow('=', tk_Leq, tk_Lss, err_line, err_col);\n case '>': next_ch(); return follow('=', tk_Geq, tk_Gtr, err_line, err_col);\n case '=': next_ch(); return follow('=', tk_Eq, tk_Assign, err_line, err_col);\n case '!': next_ch(); return follow('=', tk_Neq, tk_Not, err_line, err_col);\n case '&': next_ch(); return follow('&', tk_And, tk_EOI, err_line, err_col);\n case '|': next_ch(); return follow('|', tk_Or, tk_EOI, err_line, err_col);\n case '\"' : return string_lit(the_ch, err_line, err_col);\n default: return ident_or_int(err_line, err_col);\n case EOF: return (tok_s){tk_EOI, err_line, err_col, {0}};\n }\n}\n\nvoid run(void) { /* tokenize the given input */\n tok_s tok;\n do {\n tok = gettok();\n fprintf(dest_fp, \"%5d %5d %.15s\",\n tok.err_ln, tok.err_col,\n &\"End_of_input Op_multiply Op_divide Op_mod Op_add \"\n \"Op_subtract Op_negate Op_not Op_less Op_lessequal \"\n \"Op_greater Op_greaterequal Op_equal Op_notequal Op_assign \"\n \"Op_and Op_or Keyword_if Keyword_else Keyword_while \"\n \"Keyword_print Keyword_putc LeftParen RightParen LeftBrace \"\n \"RightBrace Semicolon Comma Identifier Integer \"\n \"String \"\n [tok.tok * 16]);\n if (tok.tok == tk_Integer) fprintf(dest_fp, \" %4d\", tok.n);\n else if (tok.tok == tk_Ident) fprintf(dest_fp, \" %s\", tok.text);\n else if (tok.tok == tk_String) fprintf(dest_fp, \" \\\"%s\\\"\", tok.text);\n fprintf(dest_fp, \"\\n\");\n } while (tok.tok != tk_EOI);\n if (dest_fp != stdout)\n fclose(dest_fp);\n}\n\nvoid init_io(FILE **fp, FILE *std, const char mode[], const char fn[]) {\n if (fn[0] == '\\0')\n *fp = std;\n else if ((*fp = fopen(fn, mode)) == NULL)\n error(0, 0, \"Can't open %s\\n\", fn);\n}\n\nint main(int argc, char *argv[]) {\n init_io(&source_fp, stdin, \"r\", argc > 1 ? argv[1] : \"\");\n init_io(&dest_fp, stdout, \"wb\", argc > 2 ? argv[2] : \"\");\n run();\n return 0;\n}"} -{"title": "Compiler/lexical analyzer", "language": "C++", "task": "The C and Python versions can be considered reference implementations.\n\n\n;Related Tasks\n* Syntax Analyzer task\n* Code Generator task\n* Virtual Machine Interpreter task\n* AST Interpreter task\n\n\n", "solution": "#include // std::from_chars\n#include // file_to_string, string_to_file\n#include // std::invoke\n#include // std::setw\n#include // std::left\n#include \n#include // keywords\n#include \n#include \n#include // std::forward\n#include // TokenVal\n\nusing namespace std;\n\n// =====================================================================================================================\n// Machinery\n// =====================================================================================================================\nstring file_to_string (const string& path)\n{\n // Open file\n ifstream file {path, ios::in | ios::binary | ios::ate};\n if (!file) throw (errno);\n\n // Allocate string memory\n string contents;\n contents.resize(file.tellg());\n\n // Read file contents into string\n file.seekg(0);\n file.read(contents.data(), contents.size());\n\n return contents;\n}\n\nvoid string_to_file (const string& path, string contents)\n{\n ofstream file {path, ios::out | ios::binary};\n if (!file) throw (errno);\n\n file.write(contents.data(), contents.size());\n}\n\ntemplate \nvoid with_IO (string source, string destination, F&& f)\n{\n string input;\n\n if (source == \"stdin\") getline(cin, input);\n else input = file_to_string(source);\n\n string output = invoke(forward(f), input);\n\n if (destination == \"stdout\") cout << output;\n else string_to_file(destination, output);\n}\n\n// Add escaped newlines and backslashes back in for printing\nstring sanitize (string s)\n{\n for (auto i = 0u; i < s.size(); ++i)\n {\n if (s[i] == '\\n') s.replace(i++, 1, \"\\\\n\");\n else if (s[i] == '\\\\') s.replace(i++, 1, \"\\\\\\\\\");\n }\n\n return s;\n}\n\nclass Scanner\n{\npublic:\n const char* pos;\n int line = 1;\n int column = 1;\n\n Scanner (const char* source) : pos {source} {}\n\n inline char peek () { return *pos; }\n\n void advance ()\n {\n if (*pos == '\\n') { ++line; column = 1; }\n else ++column;\n\n ++pos;\n }\n\n char next ()\n {\n advance();\n return peek();\n }\n\n void skip_whitespace ()\n {\n while (isspace(static_cast(peek())))\n advance();\n }\n}; // class Scanner\n\n\n// =====================================================================================================================\n// Tokens\n// =====================================================================================================================\nenum class TokenName\n{\n OP_MULTIPLY, OP_DIVIDE, OP_MOD, OP_ADD, OP_SUBTRACT, OP_NEGATE,\n OP_LESS, OP_LESSEQUAL, OP_GREATER, OP_GREATEREQUAL, OP_EQUAL, OP_NOTEQUAL,\n OP_NOT, OP_ASSIGN, OP_AND, OP_OR,\n LEFTPAREN, RIGHTPAREN, LEFTBRACE, RIGHTBRACE, SEMICOLON, COMMA,\n KEYWORD_IF, KEYWORD_ELSE, KEYWORD_WHILE, KEYWORD_PRINT, KEYWORD_PUTC,\n IDENTIFIER, INTEGER, STRING,\n END_OF_INPUT, ERROR\n};\n\nusing TokenVal = variant;\n\nstruct Token\n{\n TokenName name;\n TokenVal value;\n int line;\n int column;\n};\n\n\nconst char* to_cstring (TokenName name)\n{\n static const char* s[] =\n {\n \"Op_multiply\", \"Op_divide\", \"Op_mod\", \"Op_add\", \"Op_subtract\", \"Op_negate\",\n \"Op_less\", \"Op_lessequal\", \"Op_greater\", \"Op_greaterequal\", \"Op_equal\", \"Op_notequal\",\n \"Op_not\", \"Op_assign\", \"Op_and\", \"Op_or\",\n \"LeftParen\", \"RightParen\", \"LeftBrace\", \"RightBrace\", \"Semicolon\", \"Comma\",\n \"Keyword_if\", \"Keyword_else\", \"Keyword_while\", \"Keyword_print\", \"Keyword_putc\",\n \"Identifier\", \"Integer\", \"String\",\n \"End_of_input\", \"Error\"\n };\n\n return s[static_cast(name)];\n}\n\n\nstring to_string (Token t)\n{\n ostringstream out;\n out << setw(2) << t.line << \" \" << setw(2) << t.column << \" \";\n\n switch (t.name)\n {\n case (TokenName::IDENTIFIER) : out << \"Identifier \" << get(t.value); break;\n case (TokenName::INTEGER) : out << \"Integer \" << left << get(t.value); break;\n case (TokenName::STRING) : out << \"String \\\"\" << sanitize(get(t.value)) << '\"'; break;\n case (TokenName::END_OF_INPUT) : out << \"End_of_input\"; break;\n case (TokenName::ERROR) : out << \"Error \" << get(t.value); break;\n default : out << to_cstring(t.name);\n }\n\n out << '\\n';\n\n return out.str();\n}\n\n\n// =====================================================================================================================\n// Lexer\n// =====================================================================================================================\nclass Lexer\n{\npublic:\n Lexer (const char* source) : s {source}, pre_state {s} {}\n\n bool has_more () { return s.peek() != '\\0'; }\n\n Token next_token ()\n {\n s.skip_whitespace();\n\n pre_state = s;\n\n switch (s.peek())\n {\n case '*' : return simply(TokenName::OP_MULTIPLY);\n case '%' : return simply(TokenName::OP_MOD);\n case '+' : return simply(TokenName::OP_ADD);\n case '-' : return simply(TokenName::OP_SUBTRACT);\n case '{' : return simply(TokenName::LEFTBRACE);\n case '}' : return simply(TokenName::RIGHTBRACE);\n case '(' : return simply(TokenName::LEFTPAREN);\n case ')' : return simply(TokenName::RIGHTPAREN);\n case ';' : return simply(TokenName::SEMICOLON);\n case ',' : return simply(TokenName::COMMA);\n case '&' : return expect('&', TokenName::OP_AND);\n case '|' : return expect('|', TokenName::OP_OR);\n case '<' : return follow('=', TokenName::OP_LESSEQUAL, TokenName::OP_LESS);\n case '>' : return follow('=', TokenName::OP_GREATEREQUAL, TokenName::OP_GREATER);\n case '=' : return follow('=', TokenName::OP_EQUAL, TokenName::OP_ASSIGN);\n case '!' : return follow('=', TokenName::OP_NOTEQUAL, TokenName::OP_NOT);\n case '/' : return divide_or_comment();\n case '\\'' : return char_lit();\n case '\"' : return string_lit();\n\n default : if (is_id_start(s.peek())) return identifier();\n if (is_digit(s.peek())) return integer_lit();\n return error(\"Unrecognized character '\", s.peek(), \"'\");\n\n case '\\0' : return make_token(TokenName::END_OF_INPUT);\n }\n }\n\n\nprivate:\n Scanner s;\n Scanner pre_state;\n static const map keywords;\n\n\n template \n Token error (Args&&... ostream_args)\n {\n string code {pre_state.pos, (string::size_type) s.column - pre_state.column};\n\n ostringstream msg;\n (msg << ... << forward(ostream_args)) << '\\n'\n << string(28, ' ') << \"(\" << s.line << \", \" << s.column << \"): \" << code;\n\n if (s.peek() != '\\0') s.advance();\n\n return make_token(TokenName::ERROR, msg.str());\n }\n\n\n inline Token make_token (TokenName name, TokenVal value = 0)\n {\n return {name, value, pre_state.line, pre_state.column};\n }\n\n\n Token simply (TokenName name)\n {\n s.advance();\n return make_token(name);\n }\n\n\n Token expect (char expected, TokenName name)\n {\n if (s.next() == expected) return simply(name);\n else return error(\"Unrecognized character '\", s.peek(), \"'\");\n }\n\n\n Token follow (char expected, TokenName ifyes, TokenName ifno)\n {\n if (s.next() == expected) return simply(ifyes);\n else return make_token(ifno);\n }\n\n\n Token divide_or_comment ()\n {\n if (s.next() != '*') return make_token(TokenName::OP_DIVIDE);\n\n while (s.next() != '\\0')\n {\n if (s.peek() == '*' && s.next() == '/')\n {\n s.advance();\n return next_token();\n }\n }\n\n return error(\"End-of-file in comment. Closing comment characters not found.\");\n }\n\n\n Token char_lit ()\n {\n int n = s.next();\n\n if (n == '\\'') return error(\"Empty character constant\");\n\n if (n == '\\\\') switch (s.next())\n {\n case 'n' : n = '\\n'; break;\n case '\\\\' : n = '\\\\'; break;\n default : return error(\"Unknown escape sequence \\\\\", s.peek());\n }\n\n if (s.next() != '\\'') return error(\"Multi-character constant\");\n\n s.advance();\n return make_token(TokenName::INTEGER, n);\n }\n\n\n Token string_lit ()\n {\n string text = \"\";\n\n while (s.next() != '\"')\n switch (s.peek())\n {\n case '\\\\' : switch (s.next())\n {\n case 'n' : text += '\\n'; continue;\n case '\\\\' : text += '\\\\'; continue;\n default : return error(\"Unknown escape sequence \\\\\", s.peek());\n }\n\n case '\\n' : return error(\"End-of-line while scanning string literal.\"\n \" Closing string character not found before end-of-line.\");\n\n case '\\0' : return error(\"End-of-file while scanning string literal.\"\n \" Closing string character not found.\");\n\n default : text += s.peek();\n }\n\n s.advance();\n return make_token(TokenName::STRING, text);\n }\n\n\n static inline bool is_id_start (char c) { return isalpha(static_cast(c)) || c == '_'; }\n static inline bool is_id_end (char c) { return isalnum(static_cast(c)) || c == '_'; }\n static inline bool is_digit (char c) { return isdigit(static_cast(c)); }\n\n\n Token identifier ()\n {\n string text (1, s.peek());\n\n while (is_id_end(s.next())) text += s.peek();\n\n auto i = keywords.find(text);\n if (i != keywords.end()) return make_token(i->second);\n\n return make_token(TokenName::IDENTIFIER, text);\n }\n\n\n Token integer_lit ()\n {\n while (is_digit(s.next()));\n\n if (is_id_start(s.peek()))\n return error(\"Invalid number. Starts like a number, but ends in non-numeric characters.\");\n\n int n;\n\n auto r = from_chars(pre_state.pos, s.pos, n);\n if (r.ec == errc::result_out_of_range) return error(\"Number exceeds maximum value\");\n\n return make_token(TokenName::INTEGER, n);\n }\n}; // class Lexer\n\n\nconst map Lexer::keywords =\n{\n {\"else\", TokenName::KEYWORD_ELSE},\n {\"if\", TokenName::KEYWORD_IF},\n {\"print\", TokenName::KEYWORD_PRINT},\n {\"putc\", TokenName::KEYWORD_PUTC},\n {\"while\", TokenName::KEYWORD_WHILE}\n};\n\n\nint main (int argc, char* argv[])\n{\n string in = (argc > 1) ? argv[1] : \"stdin\";\n string out = (argc > 2) ? argv[2] : \"stdout\";\n\n with_IO(in, out, [](string input)\n {\n Lexer lexer {input.data()};\n\n string s = \"Location Token name Value\\n\"\n \"--------------------------------------\\n\";\n\n while (lexer.has_more()) s += to_string(lexer.next_token());\n return s;\n });\n}\n"} -{"title": "Compiler/lexical analyzer", "language": "Python", "task": "The C and Python versions can be considered reference implementations.\n\n\n;Related Tasks\n* Syntax Analyzer task\n* Code Generator task\n* Virtual Machine Interpreter task\n* AST Interpreter task\n\n\n", "solution": "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": "The C and Python versions can be considered reference implementations.\n\n;Related Tasks\n\n* Lexical Analyzer task\n* Code Generator task\n* Virtual Machine Interpreter task\n* AST Interpreter task\n\n\n__TOC__\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n\n#define NELEMS(arr) (sizeof(arr) / sizeof(arr[0]))\n\ntypedef enum {\n tk_EOI, tk_Mul, tk_Div, tk_Mod, tk_Add, tk_Sub, tk_Negate, tk_Not, tk_Lss, tk_Leq, tk_Gtr,\n tk_Geq, tk_Eql, tk_Neq, tk_Assign, tk_And, tk_Or, tk_If, tk_Else, tk_While, tk_Print,\n tk_Putc, tk_Lparen, tk_Rparen, tk_Lbrace, tk_Rbrace, tk_Semi, tk_Comma, tk_Ident,\n tk_Integer, tk_String\n} TokenType;\n\ntypedef enum {\n nd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While,\n nd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq,\n nd_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or\n} NodeType;\n\ntypedef struct {\n TokenType tok;\n int err_ln;\n int err_col;\n char *text; /* ident or string literal or integer value */\n} tok_s;\n\ntypedef struct Tree {\n NodeType node_type;\n struct Tree *left;\n struct Tree *right;\n char *value;\n} Tree;\n\n// dependency: Ordered by tok, must remain in same order as TokenType enum\nstruct {\n char *text, *enum_text;\n TokenType tok;\n bool right_associative, is_binary, is_unary;\n int precedence;\n NodeType node_type;\n} atr[] = {\n {\"EOI\", \"End_of_input\" , tk_EOI, false, false, false, -1, -1 },\n {\"*\", \"Op_multiply\" , tk_Mul, false, true, false, 13, nd_Mul },\n {\"/\", \"Op_divide\" , tk_Div, false, true, false, 13, nd_Div },\n {\"%\", \"Op_mod\" , tk_Mod, false, true, false, 13, nd_Mod },\n {\"+\", \"Op_add\" , tk_Add, false, true, false, 12, nd_Add },\n {\"-\", \"Op_subtract\" , tk_Sub, false, true, false, 12, nd_Sub },\n {\"-\", \"Op_negate\" , tk_Negate, false, false, true, 14, nd_Negate },\n {\"!\", \"Op_not\" , tk_Not, false, false, true, 14, nd_Not },\n {\"<\", \"Op_less\" , tk_Lss, false, true, false, 10, nd_Lss },\n {\"<=\", \"Op_lessequal\" , tk_Leq, false, true, false, 10, nd_Leq },\n {\">\", \"Op_greater\" , tk_Gtr, false, true, false, 10, nd_Gtr },\n {\">=\", \"Op_greaterequal\", tk_Geq, false, true, false, 10, nd_Geq },\n {\"==\", \"Op_equal\" , tk_Eql, false, true, false, 9, nd_Eql },\n {\"!=\", \"Op_notequal\" , tk_Neq, false, true, false, 9, nd_Neq },\n {\"=\", \"Op_assign\" , tk_Assign, false, false, false, -1, nd_Assign },\n {\"&&\", \"Op_and\" , tk_And, false, true, false, 5, nd_And },\n {\"||\", \"Op_or\" , tk_Or, false, true, false, 4, nd_Or },\n {\"if\", \"Keyword_if\" , tk_If, false, false, false, -1, nd_If },\n {\"else\", \"Keyword_else\" , tk_Else, false, false, false, -1, -1 },\n {\"while\", \"Keyword_while\" , tk_While, false, false, false, -1, nd_While },\n {\"print\", \"Keyword_print\" , tk_Print, false, false, false, -1, -1 },\n {\"putc\", \"Keyword_putc\" , tk_Putc, false, false, false, -1, -1 },\n {\"(\", \"LeftParen\" , tk_Lparen, false, false, false, -1, -1 },\n {\")\", \"RightParen\" , tk_Rparen, false, false, false, -1, -1 },\n {\"{\", \"LeftBrace\" , tk_Lbrace, false, false, false, -1, -1 },\n {\"}\", \"RightBrace\" , tk_Rbrace, false, false, false, -1, -1 },\n {\";\", \"Semicolon\" , tk_Semi, false, false, false, -1, -1 },\n {\",\", \"Comma\" , tk_Comma, false, false, false, -1, -1 },\n {\"Ident\", \"Identifier\" , tk_Ident, false, false, false, -1, nd_Ident },\n {\"Integer literal\", \"Integer\" , tk_Integer, false, false, false, -1, nd_Integer},\n {\"String literal\", \"String\" , tk_String, false, false, false, -1, nd_String },\n};\n\nchar *Display_nodes[] = {\"Identifier\", \"String\", \"Integer\", \"Sequence\", \"If\", \"Prtc\",\n \"Prts\", \"Prti\", \"While\", \"Assign\", \"Negate\", \"Not\", \"Multiply\", \"Divide\", \"Mod\",\n \"Add\", \"Subtract\", \"Less\", \"LessEqual\", \"Greater\", \"GreaterEqual\", \"Equal\",\n \"NotEqual\", \"And\", \"Or\"};\n\nstatic tok_s tok;\nstatic FILE *source_fp, *dest_fp;\n\nTree *paren_expr();\n\nvoid error(int err_line, int err_col, const char *fmt, ... ) {\n va_list ap;\n char buf[1000];\n\n va_start(ap, fmt);\n vsprintf(buf, fmt, ap);\n va_end(ap);\n printf(\"(%d, %d) error: %s\\n\", err_line, err_col, buf);\n exit(1);\n}\n\nchar *read_line(int *len) {\n static char *text = NULL;\n static int textmax = 0;\n\n for (*len = 0; ; (*len)++) {\n int ch = fgetc(source_fp);\n if (ch == EOF || ch == '\\n') {\n if (*len == 0)\n return NULL;\n break;\n }\n if (*len + 1 >= textmax) {\n textmax = (textmax == 0 ? 128 : textmax * 2);\n text = realloc(text, textmax);\n }\n text[*len] = ch;\n }\n text[*len] = '\\0';\n return text;\n}\n\nchar *rtrim(char *text, int *len) { // remove trailing spaces\n for (; *len > 0 && isspace(text[*len - 1]); --(*len))\n ;\n\n text[*len] = '\\0';\n return text;\n}\n\nTokenType get_enum(const char *name) { // return internal version of name\n for (size_t i = 0; i < NELEMS(atr); i++) {\n if (strcmp(atr[i].enum_text, name) == 0)\n return atr[i].tok;\n }\n error(0, 0, \"Unknown token %s\\n\", name);\n return 0;\n}\n\ntok_s gettok() {\n int len;\n tok_s tok;\n char *yytext = read_line(&len);\n yytext = rtrim(yytext, &len);\n\n // [ ]*{lineno}[ ]+{colno}[ ]+token[ ]+optional\n\n // get line and column\n tok.err_ln = atoi(strtok(yytext, \" \"));\n tok.err_col = atoi(strtok(NULL, \" \"));\n\n // get the token name\n char *name = strtok(NULL, \" \");\n tok.tok = get_enum(name);\n\n // if there is extra data, get it\n char *p = name + strlen(name);\n if (p != &yytext[len]) {\n for (++p; isspace(*p); ++p)\n ;\n tok.text = strdup(p);\n }\n return tok;\n}\n\nTree *make_node(NodeType node_type, Tree *left, Tree *right) {\n Tree *t = calloc(sizeof(Tree), 1);\n t->node_type = node_type;\n t->left = left;\n t->right = right;\n return t;\n}\n\nTree *make_leaf(NodeType node_type, char *value) {\n Tree *t = calloc(sizeof(Tree), 1);\n t->node_type = node_type;\n t->value = strdup(value);\n return t;\n}\n\nvoid expect(const char msg[], TokenType s) {\n if (tok.tok == s) {\n tok = gettok();\n return;\n }\n error(tok.err_ln, tok.err_col, \"%s: Expecting '%s', found '%s'\\n\", msg, atr[s].text, atr[tok.tok].text);\n}\n\nTree *expr(int p) {\n Tree *x = NULL, *node;\n TokenType op;\n\n switch (tok.tok) {\n case tk_Lparen:\n x = paren_expr();\n break;\n case tk_Sub: case tk_Add:\n op = tok.tok;\n tok = gettok();\n node = expr(atr[tk_Negate].precedence);\n x = (op == tk_Sub) ? make_node(nd_Negate, node, NULL) : node;\n break;\n case tk_Not:\n tok = gettok();\n x = make_node(nd_Not, expr(atr[tk_Not].precedence), NULL);\n break;\n case tk_Ident:\n x = make_leaf(nd_Ident, tok.text);\n tok = gettok();\n break;\n case tk_Integer:\n x = make_leaf(nd_Integer, tok.text);\n tok = gettok();\n break;\n default:\n error(tok.err_ln, tok.err_col, \"Expecting a primary, found: %s\\n\", atr[tok.tok].text);\n }\n\n while (atr[tok.tok].is_binary && atr[tok.tok].precedence >= p) {\n TokenType op = tok.tok;\n\n tok = gettok();\n\n int q = atr[op].precedence;\n if (!atr[op].right_associative)\n q++;\n\n node = expr(q);\n x = make_node(atr[op].node_type, x, node);\n }\n return x;\n}\n\nTree *paren_expr() {\n expect(\"paren_expr\", tk_Lparen);\n Tree *t = expr(0);\n expect(\"paren_expr\", tk_Rparen);\n return t;\n}\n\nTree *stmt() {\n Tree *t = NULL, *v, *e, *s, *s2;\n\n switch (tok.tok) {\n case tk_If:\n tok = gettok();\n e = paren_expr();\n s = stmt();\n s2 = NULL;\n if (tok.tok == tk_Else) {\n tok = gettok();\n s2 = stmt();\n }\n t = make_node(nd_If, e, make_node(nd_If, s, s2));\n break;\n case tk_Putc:\n tok = gettok();\n e = paren_expr();\n t = make_node(nd_Prtc, e, NULL);\n expect(\"Putc\", tk_Semi);\n break;\n case tk_Print: /* print '(' expr {',' expr} ')' */\n tok = gettok();\n for (expect(\"Print\", tk_Lparen); ; expect(\"Print\", tk_Comma)) {\n if (tok.tok == tk_String) {\n e = make_node(nd_Prts, make_leaf(nd_String, tok.text), NULL);\n tok = gettok();\n } else\n e = make_node(nd_Prti, expr(0), NULL);\n\n t = make_node(nd_Sequence, t, e);\n\n if (tok.tok != tk_Comma)\n break;\n }\n expect(\"Print\", tk_Rparen);\n expect(\"Print\", tk_Semi);\n break;\n case tk_Semi:\n tok = gettok();\n break;\n case tk_Ident:\n v = make_leaf(nd_Ident, tok.text);\n tok = gettok();\n expect(\"assign\", tk_Assign);\n e = expr(0);\n t = make_node(nd_Assign, v, e);\n expect(\"assign\", tk_Semi);\n break;\n case tk_While:\n tok = gettok();\n e = paren_expr();\n s = stmt();\n t = make_node(nd_While, e, s);\n break;\n case tk_Lbrace: /* {stmt} */\n for (expect(\"Lbrace\", tk_Lbrace); tok.tok != tk_Rbrace && tok.tok != tk_EOI;)\n t = make_node(nd_Sequence, t, stmt());\n expect(\"Lbrace\", tk_Rbrace);\n break;\n case tk_EOI:\n break;\n default: error(tok.err_ln, tok.err_col, \"expecting start of statement, found '%s'\\n\", atr[tok.tok].text);\n }\n return t;\n}\n\nTree *parse() {\n Tree *t = NULL;\n\n tok = gettok();\n do {\n t = make_node(nd_Sequence, t, stmt());\n } while (t != NULL && tok.tok != tk_EOI);\n return t;\n}\n\nvoid prt_ast(Tree *t) {\n if (t == NULL)\n printf(\";\\n\");\n else {\n printf(\"%-14s \", Display_nodes[t->node_type]);\n if (t->node_type == nd_Ident || t->node_type == nd_Integer || t->node_type == nd_String) {\n printf(\"%s\\n\", t->value);\n } else {\n printf(\"\\n\");\n prt_ast(t->left);\n prt_ast(t->right);\n }\n }\n}\n\nvoid init_io(FILE **fp, FILE *std, const char mode[], const char fn[]) {\n if (fn[0] == '\\0')\n *fp = std;\n else if ((*fp = fopen(fn, mode)) == NULL)\n error(0, 0, \"Can't open %s\\n\", fn);\n}\n\nint main(int argc, char *argv[]) {\n init_io(&source_fp, stdin, \"r\", argc > 1 ? argv[1] : \"\");\n init_io(&dest_fp, stdout, \"wb\", argc > 2 ? argv[2] : \"\");\n prt_ast(parse());\n}"} -{"title": "Compiler/syntax analyzer", "language": "Python", "task": "The C and Python versions can be considered reference implementations.\n\n;Related Tasks\n\n* Lexical Analyzer task\n* Code Generator task\n* Virtual Machine Interpreter task\n* AST Interpreter task\n\n\n__TOC__\n\n", "solution": "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": "The C and Python versions can be considered reference implementations.\n\n;Related Tasks\n\n* Lexical Analyzer task\n* Syntax Analyzer task\n* Code Generator task\n* AST Interpreter task\n\n\n__TOC__\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n\n#define NELEMS(arr) (sizeof(arr) / sizeof(arr[0]))\n\n#define da_dim(name, type) type *name = NULL; \\\n int _qy_ ## name ## _p = 0; \\\n int _qy_ ## name ## _max = 0\n\n#define da_redim(name) do {if (_qy_ ## name ## _p >= _qy_ ## name ## _max) \\\n name = realloc(name, (_qy_ ## name ## _max += 32) * sizeof(name[0]));} while (0)\n\n#define da_rewind(name) _qy_ ## name ## _p = 0\n\n#define da_append(name, x) do {da_redim(name); name[_qy_ ## name ## _p++] = x;} while (0)\n\ntypedef unsigned char uchar;\ntypedef uchar code;\n\ntypedef enum { FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND,\n OR, NEG, NOT, JMP, JZ, PRTC, PRTS, PRTI, HALT\n} Code_t;\n\ntypedef struct Code_map {\n char *text;\n Code_t op;\n} Code_map;\n\nCode_map code_map[] = {\n {\"fetch\", FETCH},\n {\"store\", STORE},\n {\"push\", PUSH },\n {\"add\", ADD },\n {\"sub\", SUB },\n {\"mul\", MUL },\n {\"div\", DIV },\n {\"mod\", MOD },\n {\"lt\", LT },\n {\"gt\", GT },\n {\"le\", LE },\n {\"ge\", GE },\n {\"eq\", EQ },\n {\"ne\", NE },\n {\"and\", AND },\n {\"or\", OR },\n {\"neg\", NEG },\n {\"not\", NOT },\n {\"jmp\", JMP },\n {\"jz\", JZ },\n {\"prtc\", PRTC },\n {\"prts\", PRTS },\n {\"prti\", PRTI },\n {\"halt\", HALT },\n};\n\nFILE *source_fp;\nda_dim(object, code);\n\nvoid error(const char *fmt, ... ) {\n va_list ap;\n char buf[1000];\n\n va_start(ap, fmt);\n vsprintf(buf, fmt, ap);\n va_end(ap);\n printf(\"error: %s\\n\", buf);\n exit(1);\n}\n\n/*** Virtual Machine interpreter ***/\nvoid run_vm(const code obj[], int32_t data[], int g_size, char **string_pool) {\n int32_t *sp = &data[g_size + 1];\n const code *pc = obj;\n\n again:\n switch (*pc++) {\n case FETCH: *sp++ = data[*(int32_t *)pc]; pc += sizeof(int32_t); goto again;\n case STORE: data[*(int32_t *)pc] = *--sp; pc += sizeof(int32_t); goto again;\n case PUSH: *sp++ = *(int32_t *)pc; pc += sizeof(int32_t); goto again;\n case ADD: sp[-2] += sp[-1]; --sp; goto again;\n case SUB: sp[-2] -= sp[-1]; --sp; goto again;\n case MUL: sp[-2] *= sp[-1]; --sp; goto again;\n case DIV: sp[-2] /= sp[-1]; --sp; goto again;\n case MOD: sp[-2] %= sp[-1]; --sp; goto again;\n case LT: sp[-2] = sp[-2] < sp[-1]; --sp; goto again;\n case GT: sp[-2] = sp[-2] > sp[-1]; --sp; goto again;\n case LE: sp[-2] = sp[-2] <= sp[-1]; --sp; goto again;\n case GE: sp[-2] = sp[-2] >= sp[-1]; --sp; goto again;\n case EQ: sp[-2] = sp[-2] == sp[-1]; --sp; goto again;\n case NE: sp[-2] = sp[-2] != sp[-1]; --sp; goto again;\n case AND: sp[-2] = sp[-2] && sp[-1]; --sp; goto again;\n case OR: sp[-2] = sp[-2] || sp[-1]; --sp; goto again;\n case NEG: sp[-1] = -sp[-1]; goto again;\n case NOT: sp[-1] = !sp[-1]; goto again;\n case JMP: pc += *(int32_t *)pc; goto again;\n case JZ: pc += (*--sp == 0) ? *(int32_t *)pc : (int32_t)sizeof(int32_t); goto again;\n case PRTC: printf(\"%c\", sp[-1]); --sp; goto again;\n case PRTS: printf(\"%s\", string_pool[sp[-1]]); --sp; goto again;\n case PRTI: printf(\"%d\", sp[-1]); --sp; goto again;\n case HALT: break;\n default: error(\"Unknown opcode %d\\n\", *(pc - 1));\n }\n}\n\nchar *read_line(int *len) {\n static char *text = NULL;\n static int textmax = 0;\n\n for (*len = 0; ; (*len)++) {\n int ch = fgetc(source_fp);\n if (ch == EOF || ch == '\\n') {\n if (*len == 0)\n return NULL;\n break;\n }\n if (*len + 1 >= textmax) {\n textmax = (textmax == 0 ? 128 : textmax * 2);\n text = realloc(text, textmax);\n }\n text[*len] = ch;\n }\n text[*len] = '\\0';\n return text;\n}\n\nchar *rtrim(char *text, int *len) { // remove trailing spaces\n for (; *len > 0 && isspace(text[*len - 1]); --(*len))\n ;\n\n text[*len] = '\\0';\n return text;\n}\n\nchar *translate(char *st) {\n char *p, *q;\n if (st[0] == '\"') // skip leading \" if there\n ++st;\n p = q = st;\n\n while ((*p++ = *q++) != '\\0') {\n if (q[-1] == '\\\\') {\n if (q[0] == 'n') {\n p[-1] = '\\n';\n ++q;\n } else if (q[0] == '\\\\') {\n ++q;\n }\n }\n if (q[0] == '\"' && q[1] == '\\0') // skip trialing \" if there\n ++q;\n }\n\n return st;\n}\n\n/* convert an opcode string into its byte value */\nint findit(const char text[], int offset) {\n for (size_t i = 0; i < sizeof(code_map) / sizeof(code_map[0]); i++) {\n if (strcmp(code_map[i].text, text) == 0)\n return code_map[i].op;\n }\n error(\"Unknown instruction %s at %d\\n\", text, offset);\n return -1;\n}\n\nvoid emit_byte(int c) {\n da_append(object, (uchar)c);\n}\n\nvoid emit_int(int32_t n) {\n union {\n int32_t n;\n unsigned char c[sizeof(int32_t)];\n } x;\n\n x.n = n;\n\n for (size_t i = 0; i < sizeof(x.n); ++i) {\n emit_byte(x.c[i]);\n }\n}\n\n/*\nDatasize: 5 Strings: 3\n\" is prime\\n\"\n\"Total primes found: \"\n\"\\n\"\n 154 jmp (-73) 82\n 164 jz (32) 197\n 175 push 0\n 159 fetch [4]\n 149 store [3]\n */\n\n/* Load code into global array object, return the string pool and data size */\nchar **load_code(int *ds) {\n int line_len, n_strings;\n char **string_pool;\n char *text = read_line(&line_len);\n text = rtrim(text, &line_len);\n\n strtok(text, \" \"); // skip \"Datasize:\"\n *ds = atoi(strtok(NULL, \" \")); // get actual data_size\n strtok(NULL, \" \"); // skip \"Strings:\"\n n_strings = atoi(strtok(NULL, \" \")); // get number of strings\n\n string_pool = malloc(n_strings * sizeof(char *));\n for (int i = 0; i < n_strings; ++i) {\n text = read_line(&line_len);\n text = rtrim(text, &line_len);\n text = translate(text);\n string_pool[i] = strdup(text);\n }\n\n for (;;) {\n int len;\n\n text = read_line(&line_len);\n if (text == NULL)\n break;\n text = rtrim(text, &line_len);\n\n int offset = atoi(strtok(text, \" \")); // get the offset\n char *instr = strtok(NULL, \" \"); // get the instruction\n int opcode = findit(instr, offset);\n emit_byte(opcode);\n char *operand = strtok(NULL, \" \");\n\n switch (opcode) {\n case JMP: case JZ:\n operand++; // skip the '('\n len = strlen(operand);\n operand[len - 1] = '\\0'; // remove the ')'\n emit_int(atoi(operand));\n break;\n case PUSH:\n emit_int(atoi(operand));\n break;\n case FETCH: case STORE:\n operand++; // skip the '['\n len = strlen(operand);\n operand[len - 1] = '\\0'; // remove the ']'\n emit_int(atoi(operand));\n break;\n }\n }\n return string_pool;\n}\n\nvoid init_io(FILE **fp, FILE *std, const char mode[], const char fn[]) {\n if (fn[0] == '\\0')\n *fp = std;\n else if ((*fp = fopen(fn, mode)) == NULL)\n error(0, 0, \"Can't open %s\\n\", fn);\n}\n\nint main(int argc, char *argv[]) {\n init_io(&source_fp, stdin, \"r\", argc > 1 ? argv[1] : \"\");\n int data_size;\n char **string_pool = load_code(&data_size);\n int data[1000 + data_size];\n run_vm(object, data, data_size, string_pool);\n}"} -{"title": "Compiler/virtual machine interpreter", "language": "Python", "task": "The C and Python versions can be considered reference implementations.\n\n;Related Tasks\n\n* Lexical Analyzer task\n* Syntax Analyzer task\n* Code Generator task\n* AST Interpreter task\n\n\n__TOC__\n\n", "solution": "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": "Suppose that a conjugate transpose of M is a matrix M^H containing the [[complex conjugate]]s of the [[matrix transposition]] of M.\n\n::: (M^H)_{ji} = \\overline{M_{ij}}\n\n\nThis means that row j, column i of the conjugate transpose equals the \ncomplex conjugate of row i, column j of the original matrix.\n\n\nIn the next list, M must also be a square matrix.\n\n* A Hermitian matrix equals its own conjugate transpose: M^H = M.\n* A multiplication with its conjugate transpose: M^HM = MM^H.\n* A iff M^HM = I_n and iff MM^H = I_n, where I_n is the identity matrix.\n\n\n\n;Task:\nGiven some matrix of complex numbers, find its conjugate transpose. \n\nAlso determine if the matrix is a:\n::* Hermitian matrix,\n::* normal matrix, or \n::* unitary matrix.\n\n\n;See also:\n* MathWorld entry: conjugate transpose\n* MathWorld entry: Hermitian matrix\n* MathWorld entry: normal matrix\n* MathWorld entry: unitary matrix\n\n", "solution": "/* Uses C99 specified complex.h, complex datatype has to be defined and operation provided if used on non-C99 compilers */\n\n#include\n#include\n#include\n\ntypedef struct\n{\n int rows, cols;\n complex **z;\n} matrix;\n\nmatrix\ntranspose (matrix a)\n{\n int i, j;\n matrix b;\n\n b.rows = a.cols;\n b.cols = a.rows;\n\n b.z = malloc (b.rows * sizeof (complex *));\n\n for (i = 0; i < b.rows; i++)\n {\n b.z[i] = malloc (b.cols * sizeof (complex));\n for (j = 0; j < b.cols; j++)\n {\n b.z[i][j] = conj (a.z[j][i]);\n }\n }\n\n return b;\n}\n\nint\nisHermitian (matrix a)\n{\n int i, j;\n matrix b = transpose (a);\n\n if (b.rows == a.rows && b.cols == a.cols)\n {\n for (i = 0; i < b.rows; i++)\n {\n for (j = 0; j < b.cols; j++)\n {\n if (b.z[i][j] != a.z[i][j])\n return 0;\n }\n }\n }\n\n else\n return 0;\n\n return 1;\n}\n\nmatrix\nmultiply (matrix a, matrix b)\n{\n matrix c;\n int i, j;\n\n if (a.cols == b.rows)\n {\n c.rows = a.rows;\n c.cols = b.cols;\n\n c.z = malloc (c.rows * (sizeof (complex *)));\n\n for (i = 0; i < c.rows; i++)\n {\n c.z[i] = malloc (c.cols * sizeof (complex));\n c.z[i][j] = 0 + 0 * I;\n for (j = 0; j < b.cols; j++)\n {\n c.z[i][j] += a.z[i][j] * b.z[j][i];\n }\n }\n\n }\n\n return c;\n}\n\nint\nisNormal (matrix a)\n{\n int i, j;\n matrix a_ah, ah_a;\n\n if (a.rows != a.cols)\n return 0;\n\n a_ah = multiply (a, transpose (a));\n ah_a = multiply (transpose (a), a);\n\n for (i = 0; i < a.rows; i++)\n {\n for (j = 0; j < a.cols; j++)\n {\n if (a_ah.z[i][j] != ah_a.z[i][j])\n return 0;\n }\n }\n\n return 1;\n}\n\nint\nisUnitary (matrix a)\n{\n matrix b;\n int i, j;\n if (isNormal (a) == 1)\n {\n b = multiply (a, transpose(a));\n\n for (i = 0; i < b.rows; i++)\n {\n for (j = 0; j < b.cols; j++)\n {\n if ((i == j && b.z[i][j] != 1) || (i != j && b.z[i][j] != 0))\n return 0;\n }\n }\n return 1;\n }\n return 0;\n}\n\n\nint\nmain ()\n{\n complex z = 3 + 4 * I;\n matrix a, aT;\n int i, j;\n printf (\"Enter rows and columns :\");\n scanf (\"%d%d\", &a.rows, &a.cols);\n\n a.z = malloc (a.rows * sizeof (complex *));\n printf (\"Randomly Generated Complex Matrix A is : \");\n for (i = 0; i < a.rows; i++)\n {\n printf (\"\\n\");\n a.z[i] = malloc (a.cols * sizeof (complex));\n for (j = 0; j < a.cols; j++)\n {\n a.z[i][j] = rand () % 10 + rand () % 10 * I;\n printf (\"\\t%f + %fi\", creal (a.z[i][j]), cimag (a.z[i][j]));\n }\n }\n\n aT = transpose (a);\n\n printf (\"\\n\\nTranspose of Complex Matrix A is : \");\n for (i = 0; i < aT.rows; i++)\n {\n printf (\"\\n\");\n aT.z[i] = malloc (aT.cols * sizeof (complex));\n for (j = 0; j < aT.cols; j++)\n {\n aT.z[i][j] = rand () % 10 + rand () % 10 * I;\n printf (\"\\t%f + %fi\", creal (aT.z[i][j]), cimag (aT.z[i][j]));\n }\n }\n\n printf (\"\\n\\nComplex Matrix A %s hermitian\",\n isHermitian (a) == 1 ? \"is\" : \"is not\");\n printf (\"\\n\\nComplex Matrix A %s unitary\",\n isUnitary (a) == 1 ? \"is\" : \"is not\");\n printf (\"\\n\\nComplex Matrix A %s normal\",\n isNormal (a) == 1 ? \"is\" : \"is not\");\n\n\n\n return 0;\n}"} -{"title": "Conjugate transpose", "language": "C++", "task": "Suppose that a conjugate transpose of M is a matrix M^H containing the [[complex conjugate]]s of the [[matrix transposition]] of M.\n\n::: (M^H)_{ji} = \\overline{M_{ij}}\n\n\nThis means that row j, column i of the conjugate transpose equals the \ncomplex conjugate of row i, column j of the original matrix.\n\n\nIn the next list, M must also be a square matrix.\n\n* A Hermitian matrix equals its own conjugate transpose: M^H = M.\n* A multiplication with its conjugate transpose: M^HM = MM^H.\n* A iff M^HM = I_n and iff MM^H = I_n, where I_n is the identity matrix.\n\n\n\n;Task:\nGiven some matrix of complex numbers, find its conjugate transpose. \n\nAlso determine if the matrix is a:\n::* Hermitian matrix,\n::* normal matrix, or \n::* unitary matrix.\n\n\n;See also:\n* MathWorld entry: conjugate transpose\n* MathWorld entry: Hermitian matrix\n* MathWorld entry: normal matrix\n* MathWorld entry: unitary matrix\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ntemplate class complex_matrix {\npublic:\n using element_type = std::complex;\n\n complex_matrix(size_t rows, size_t columns)\n : rows_(rows), columns_(columns), elements_(rows * columns) {}\n\n complex_matrix(size_t rows, size_t columns, element_type value)\n : rows_(rows), columns_(columns), elements_(rows * columns, value) {}\n\n complex_matrix(size_t rows, size_t columns,\n const std::initializer_list>& values)\n : rows_(rows), columns_(columns), elements_(rows * columns) {\n assert(values.size() <= rows_);\n size_t i = 0;\n for (const auto& row : values) {\n assert(row.size() <= columns_);\n std::copy(begin(row), end(row), &elements_[i]);\n i += columns_;\n }\n }\n\n size_t rows() const { return rows_; }\n size_t columns() const { return columns_; }\n\n const element_type& operator()(size_t row, size_t column) const {\n assert(row < rows_);\n assert(column < columns_);\n return elements_[row * columns_ + column];\n }\n element_type& operator()(size_t row, size_t column) {\n assert(row < rows_);\n assert(column < columns_);\n return elements_[row * columns_ + column];\n }\n\n friend bool operator==(const complex_matrix& a, const complex_matrix& b) {\n return a.rows_ == b.rows_ && a.columns_ == b.columns_ &&\n a.elements_ == b.elements_;\n }\n\nprivate:\n size_t rows_;\n size_t columns_;\n std::vector elements_;\n};\n\ntemplate \ncomplex_matrix product(const complex_matrix& a,\n const complex_matrix& b) {\n assert(a.columns() == b.rows());\n size_t arows = a.rows();\n size_t bcolumns = b.columns();\n size_t n = a.columns();\n complex_matrix c(arows, bcolumns);\n for (size_t i = 0; i < arows; ++i) {\n for (size_t j = 0; j < n; ++j) {\n for (size_t k = 0; k < bcolumns; ++k)\n c(i, k) += a(i, j) * b(j, k);\n }\n }\n return c;\n}\n\ntemplate \ncomplex_matrix\nconjugate_transpose(const complex_matrix& a) {\n size_t rows = a.rows(), columns = a.columns();\n complex_matrix b(columns, rows);\n for (size_t i = 0; i < columns; i++) {\n for (size_t j = 0; j < rows; j++) {\n b(i, j) = std::conj(a(j, i));\n }\n }\n return b;\n}\n\ntemplate \nstd::string to_string(const std::complex& c) {\n std::ostringstream out;\n const int precision = 6;\n out << std::fixed << std::setprecision(precision);\n out << std::setw(precision + 3) << c.real();\n if (c.imag() > 0)\n out << \" + \" << std::setw(precision + 2) << c.imag() << 'i';\n else if (c.imag() == 0)\n out << \" + \" << std::setw(precision + 2) << 0.0 << 'i';\n else\n out << \" - \" << std::setw(precision + 2) << -c.imag() << 'i';\n return out.str();\n}\n\ntemplate \nvoid print(std::ostream& out, const complex_matrix& a) {\n size_t rows = a.rows(), columns = a.columns();\n for (size_t row = 0; row < rows; ++row) {\n for (size_t column = 0; column < columns; ++column) {\n if (column > 0)\n out << ' ';\n out << to_string(a(row, column));\n }\n out << '\\n';\n }\n}\n\ntemplate \nbool is_hermitian_matrix(const complex_matrix& matrix) {\n if (matrix.rows() != matrix.columns())\n return false;\n return matrix == conjugate_transpose(matrix);\n}\n\ntemplate \nbool is_normal_matrix(const complex_matrix& matrix) {\n if (matrix.rows() != matrix.columns())\n return false;\n auto c = conjugate_transpose(matrix);\n return product(c, matrix) == product(matrix, c);\n}\n\nbool is_equal(const std::complex& a, double b) {\n constexpr double e = 1e-15;\n return std::abs(a.imag()) < e && std::abs(a.real() - b) < e;\n}\n\ntemplate \nbool is_identity_matrix(const complex_matrix& matrix) {\n if (matrix.rows() != matrix.columns())\n return false;\n size_t rows = matrix.rows();\n for (size_t i = 0; i < rows; ++i) {\n for (size_t j = 0; j < rows; ++j) {\n if (!is_equal(matrix(i, j), scalar_type(i == j ? 1 : 0)))\n return false;\n }\n }\n return true;\n}\n\ntemplate \nbool is_unitary_matrix(const complex_matrix& matrix) {\n if (matrix.rows() != matrix.columns())\n return false;\n auto c = conjugate_transpose(matrix);\n auto p = product(c, matrix);\n return is_identity_matrix(p) && p == product(matrix, c);\n}\n\ntemplate \nvoid test(const complex_matrix& matrix) {\n std::cout << \"Matrix:\\n\";\n print(std::cout, matrix);\n std::cout << \"Conjugate transpose:\\n\";\n print(std::cout, conjugate_transpose(matrix));\n std::cout << std::boolalpha;\n std::cout << \"Hermitian: \" << is_hermitian_matrix(matrix) << '\\n';\n std::cout << \"Normal: \" << is_normal_matrix(matrix) << '\\n';\n std::cout << \"Unitary: \" << is_unitary_matrix(matrix) << '\\n';\n}\n\nint main() {\n using matrix = complex_matrix;\n\n matrix matrix1(3, 3, {{{2, 0}, {2, 1}, {4, 0}},\n {{2, -1}, {3, 0}, {0, 1}},\n {{4, 0}, {0, -1}, {1, 0}}});\n\n double n = std::sqrt(0.5);\n matrix matrix2(3, 3, {{{n, 0}, {n, 0}, {0, 0}},\n {{0, -n}, {0, n}, {0, 0}},\n {{0, 0}, {0, 0}, {0, 1}}});\n\n matrix matrix3(3, 3, {{{2, 2}, {3, 1}, {-3, 5}},\n {{2, -1}, {4, 1}, {0, 0}},\n {{7, -5}, {1, -4}, {1, 0}}});\n\n test(matrix1);\n std::cout << '\\n';\n test(matrix2);\n std::cout << '\\n';\n test(matrix3);\n return 0;\n}"} -{"title": "Conjugate transpose", "language": "Python", "task": "Suppose that a conjugate transpose of M is a matrix M^H containing the [[complex conjugate]]s of the [[matrix transposition]] of M.\n\n::: (M^H)_{ji} = \\overline{M_{ij}}\n\n\nThis means that row j, column i of the conjugate transpose equals the \ncomplex conjugate of row i, column j of the original matrix.\n\n\nIn the next list, M must also be a square matrix.\n\n* A Hermitian matrix equals its own conjugate transpose: M^H = M.\n* A multiplication with its conjugate transpose: M^HM = MM^H.\n* A iff M^HM = I_n and iff MM^H = I_n, where I_n is the identity matrix.\n\n\n\n;Task:\nGiven some matrix of complex numbers, find its conjugate transpose. \n\nAlso determine if the matrix is a:\n::* Hermitian matrix,\n::* normal matrix, or \n::* unitary matrix.\n\n\n;See also:\n* MathWorld entry: conjugate transpose\n* MathWorld entry: Hermitian matrix\n* MathWorld entry: normal matrix\n* MathWorld entry: unitary matrix\n\n", "solution": "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": "C++", "task": "A number may be represented as a continued fraction (see Mathworld for more information) as follows:\n: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:* [[Continued fraction/Arithmetic]] for tasks that do arithmetic over continued fractions.\n\n", "solution": "#include \n#include \n#include \n\ntypedef std::tuple coeff_t; // coefficients type\ntypedef coeff_t (*func_t)(int); // callback function type\n\ndouble calc(func_t func, int n)\n{\n double a, b, temp = 0;\n for (; n > 0; --n) {\n std::tie(a, b) = func(n);\n temp = b / (a + temp);\n }\n std::tie(a, b) = func(0);\n return a + temp;\n}\n\ncoeff_t sqrt2(int n)\n{\n return coeff_t(n > 0 ? 2 : 1, 1);\n}\n\ncoeff_t napier(int n)\n{\n return coeff_t(n > 0 ? n : 2, n > 1 ? n - 1 : 1);\n}\n\ncoeff_t pi(int n)\n{\n return coeff_t(n > 0 ? 6 : 3, (2 * n - 1) * (2 * n - 1));\n}\n\nint main()\n{\n std::streamsize old_prec = std::cout.precision(15); // set output digits\n std::cout \n << calc(sqrt2, 20) << '\\n'\n << calc(napier, 15) << '\\n'\n << calc(pi, 10000) << '\\n'\n << std::setprecision(old_prec); // reset precision\n}"} -{"title": "Continued fraction", "language": "Python 2.6+ and 3.x", "task": "A number may be represented as a continued fraction (see Mathworld for more information) as follows:\n: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:* [[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", "language": "Python from D", "task": "A number may be represented as a continued fraction (see Mathworld for more information) as follows:\n: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:* [[Continued fraction/Arithmetic]] for tasks that do arithmetic over continued fractions.\n\n", "solution": "from decimal import Decimal, getcontext\n\ndef calc(fun, n):\n temp = Decimal(\"0.0\")\n\n for ni in xrange(n+1, 0, -1):\n (a, b) = fun(ni)\n temp = Decimal(b) / (a + temp)\n\n return fun(0)[0] + temp\n\ndef fsqrt2(n):\n return (2 if n > 0 else 1, 1)\n\ndef fnapier(n):\n return (n if n > 0 else 2, (n - 1) if n > 1 else 1)\n\ndef fpi(n):\n return (6 if n > 0 else 3, (2 * n - 1) ** 2)\n\ngetcontext().prec = 50\nprint calc(fsqrt2, 200)\nprint calc(fnapier, 200)\nprint calc(fpi, 200)"} -{"title": "Continued fraction/Arithmetic/Construct from rational number", "language": "C", "task": "To understand this task in context please see [[Continued fraction arithmetic]]\nThe purpose of this task is to write a function \\mathit{r2cf}(\\mathrm{int} N_1, \\mathrm{int} N_2), or \\mathit{r2cf}(\\mathrm{Fraction} N), which will output a continued fraction assuming:\n:N_1 is the numerator\n:N_2 is the denominator\n \nThe function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.\n\nTo achieve this it must determine: the integer part; and remainder part, of N_1 divided by N_2. It then sets N_1 to N_2 and N_2 to the determined remainder part. It then outputs the determined integer part. It does this until \\mathrm{abs}(N_2) is zero.\n\nDemonstrate the function by outputing the continued fraction for:\n: 1/2\n: 3\n: 23/8\n: 13/11\n: 22/7\n: -151/77\n\\sqrt 2 should approach [1; 2, 2, 2, 2, \\ldots] try ever closer rational approximations until boredom gets the better of you:\n: 14142,10000\n: 141421,100000\n: 1414214,1000000\n: 14142136,10000000\n\nTry :\n: 31,10\n: 314,100\n: 3142,1000\n: 31428,10000\n: 314285,100000\n: 3142857,1000000\n: 31428571,10000000\n: 314285714,100000000\n\nObserve how this rational number behaves differently to \\sqrt 2 and convince yourself that, in the same way as 3.7 may be represented as 3.70 when an extra decimal place is required, [3;7] may be represented as [3;7,\\infty] when an extra term is required.\n\n", "solution": "#include\n\ntypedef struct{\n\tint num,den;\n\t}fraction;\n\nfraction examples[] = {{1,2}, {3,1}, {23,8}, {13,11}, {22,7}, {-151,77}}; \nfraction sqrt2[] = {{14142,10000}, {141421,100000}, {1414214,1000000}, {14142136,10000000}};\nfraction pi[] = {{31,10}, {314,100}, {3142,1000}, {31428,10000}, {314285,100000}, {3142857,1000000}, {31428571,10000000}, {314285714,100000000}};\n\nint r2cf(int *numerator,int *denominator)\n{\n\tint quotient=0,temp;\n\t\n\tif(denominator != 0)\n\t{\n\t\tquotient = *numerator / *denominator;\n\t\t\n\t\ttemp = *numerator;\n\t\t\n\t\t*numerator = *denominator;\n\t\t\n\t\t*denominator = temp % *denominator;\n\t}\n\t\n\treturn quotient;\n}\n\nint main()\n{\n\tint i;\n\t\n\tprintf(\"Running the examples :\");\n\t\n\tfor(i=0;i\n/* Interface for all Continued Fractions\n Nigel Galloway, February 9th., 2013.\n*/\nclass ContinuedFraction {\n\tpublic:\n\tvirtual const int nextTerm(){};\n\tvirtual const bool moreTerms(){};\n};\n/* Create a continued fraction from a rational number\n Nigel Galloway, February 9th., 2013.\n*/\nclass r2cf : public ContinuedFraction {\n\tprivate: int n1, n2;\n\tpublic:\n\tr2cf(const int numerator, const int denominator): n1(numerator), n2(denominator){}\n\tconst int nextTerm() {\n\t\tconst int thisTerm = n1/n2;\n\t\tconst int t2 = n2; n2 = n1 - thisTerm * n2; n1 = t2;\n\t\treturn thisTerm;\n\t}\n\tconst bool moreTerms() {return fabs(n2) > 0;}\n};\n/* Generate a continued fraction for sqrt of 2\n Nigel Galloway, February 9th., 2013.\n*/\nclass SQRT2 : public ContinuedFraction {\n\tprivate: bool first=true;\n\tpublic:\n\tconst int nextTerm() {if (first) {first = false; return 1;} else return 2;}\n\tconst bool moreTerms() {return true;}\n};"} -{"title": "Continued fraction/Arithmetic/Construct from rational number", "language": "Python from Ruby", "task": "To understand this task in context please see [[Continued fraction arithmetic]]\nThe purpose of this task is to write a function \\mathit{r2cf}(\\mathrm{int} N_1, \\mathrm{int} N_2), or \\mathit{r2cf}(\\mathrm{Fraction} N), which will output a continued fraction assuming:\n:N_1 is the numerator\n:N_2 is the denominator\n \nThe function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.\n\nTo achieve this it must determine: the integer part; and remainder part, of N_1 divided by N_2. It then sets N_1 to N_2 and N_2 to the determined remainder part. It then outputs the determined integer part. It does this until \\mathrm{abs}(N_2) is zero.\n\nDemonstrate the function by outputing the continued fraction for:\n: 1/2\n: 3\n: 23/8\n: 13/11\n: 22/7\n: -151/77\n\\sqrt 2 should approach [1; 2, 2, 2, 2, \\ldots] try ever closer rational approximations until boredom gets the better of you:\n: 14142,10000\n: 141421,100000\n: 1414214,1000000\n: 14142136,10000000\n\nTry :\n: 31,10\n: 314,100\n: 3142,1000\n: 31428,10000\n: 314285,100000\n: 3142857,1000000\n: 31428571,10000000\n: 314285714,100000000\n\nObserve how this rational number behaves differently to \\sqrt 2 and convince yourself that, in the same way as 3.7 may be represented as 3.70 when an extra decimal place is required, [3;7] may be represented as [3;7,\\infty] when an extra term is required.\n\n", "solution": "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": "/* Interface for all matrixNG classes\n Nigel Galloway, February 10th., 2013.\n*/\nclass matrixNG {\n private:\n virtual void consumeTerm(){}\n virtual void consumeTerm(int n){}\n virtual const bool needTerm(){}\n protected: int cfn = 0, thisTerm;\n bool haveTerm = false;\n friend class NG;\n};\n/* Implement the babyNG matrix\n Nigel Galloway, February 10th., 2013.\n*/\nclass NG_4 : public matrixNG {\n private: int a1, a, b1, b, t;\n const bool needTerm() {\n if (b1==0 and b==0) return false;\n if (b1==0 or b==0) return true; else thisTerm = a/b;\n if (thisTerm==(int)(a1/b1)){\n t=a; a=b; b=t-b*thisTerm; t=a1; a1=b1; b1=t-b1*thisTerm;\n haveTerm=true; return false;\n }\n return true;\n }\n void consumeTerm(){a=a1; b=b1;}\n void consumeTerm(int n){t=a; a=a1; a1=t+a1*n; t=b; b=b1; b1=t+b1*n;}\n public:\n NG_4(int a1, int a, int b1, int b): a1(a1), a(a), b1(b1), b(b){}\n};\n/* Implement a Continued Fraction which returns the result of an arithmetic operation on\n 1 or more Continued Fractions (Currently 1 or 2).\n Nigel Galloway, February 10th., 2013.\n*/\nclass NG : public ContinuedFraction {\n private:\n matrixNG* ng;\n ContinuedFraction* n[2];\n public:\n NG(NG_4* ng, ContinuedFraction* n1): ng(ng){n[0] = n1;}\n NG(NG_8* ng, ContinuedFraction* n1, ContinuedFraction* n2): ng(ng){n[0] = n1; n[1] = n2;}\n const int nextTerm() {ng->haveTerm = false; return ng->thisTerm;}\n const bool moreTerms(){\n while(ng->needTerm()) if(n[ng->cfn]->moreTerms()) ng->consumeTerm(n[ng->cfn]->nextTerm()); else ng->consumeTerm();\n return ng->haveTerm;\n }\n};"} -{"title": "Continued fraction/Arithmetic/G(matrix ng, continued fraction n)", "language": "Python from Ruby", "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 - 4527027 / 5000000\n* 0.518518 - 259259 / 500000\n\nFinite decimals are of course no problem:\n\n* 0.75 - 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 - 4527027 / 5000000\n* 0.518518 - 259259 / 500000\n\nFinite decimals are of course no problem:\n\n* 0.75 - 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 - 4527027 / 5000000\n* 0.518518 - 259259 / 500000\n\nFinite decimals are of course no problem:\n\n* 0.75 - 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 - 4527027 / 5000000\n* 0.518518 - 259259 / 500000\n\nFinite decimals are of course no problem:\n\n* 0.75 - 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": "Write a function or program which:\n* takes a positive integer representing a duration in seconds as input (e.g., 100), and\n* returns a string which shows the same duration decomposed into:\n:::* weeks,\n:::* days, \n:::* hours, \n:::* minutes, and \n:::* seconds.\n\nThis is detailed below (e.g., \"2 hr, 59 sec\").\n\n\nDemonstrate that it passes the following three test-cases:\n\n'''''Test Cases'''''\n\n:::::{| class=\"wikitable\"\n|-\n! input number\n! output string\n|-\n| 7259\n| 2 hr, 59 sec\n|-\n| 86400\n| 1 d\n|-\n| 6000000\n| 9 wk, 6 d, 10 hr, 40 min\n|}\n\n'''''Details'''''\n\nThe following five units should be used:\n:::::{| class=\"wikitable\"\n|-\n! unit\n! suffix used in output\n! conversion\n|-\n| week\n| wk\n| 1 week = 7 days\n|-\n| day\n| d\n| 1 day = 24 hours\n|-\n| hour\n| hr\n| 1 hour = 60 minutes\n|-\n| minute\n| min\n| 1 minute = 60 seconds\n|-\n| second\n| sec\n| \n|}\n\nHowever, '''only''' include quantities with non-zero values in the output (e.g., return \"1 d\" and not \"0 wk, 1 d, 0 hr, 0 min, 0 sec\").\n\nGive larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)\n\nMimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).\n\n\n", "solution": "#include /* requires c99 */\n#include /* requires c99 */\n#include \n#include \n\n#define N_EL 5\n\nuintmax_t sec_to_week(uintmax_t);\nuintmax_t sec_to_day(uintmax_t);\nuintmax_t sec_to_hour(uintmax_t);\nuintmax_t sec_to_min(uintmax_t);\n\nuintmax_t week_to_sec(uintmax_t);\nuintmax_t day_to_sec(uintmax_t);\nuintmax_t hour_to_sec(uintmax_t);\nuintmax_t min_to_sec(uintmax_t);\n\nchar *format_sec(uintmax_t);\n /* the primary function */\n\n\nint main(int argc, char *argv[])\n{\n uintmax_t input;\n char *a;\n \n if(argc<2) {\n printf(\"usage: %s #seconds\\n\", argv[0]);\n return 1;\n }\n input = strtoumax(argv[1],(void *)0, 10 /*base 10*/);\n if(input<1) {\n printf(\"Bad input: %s\\n\", argv[1]);\n printf(\"usage: %s #seconds\\n\", argv[0]);\n return 1;\n }\n printf(\"Number entered: %\" PRIuMAX \"\\n\", input);\n a = format_sec(input);\n printf(a);\n free(a);\n \n return 0;\n}\n\n/* note: must free memory \n * after using this function */\nchar *format_sec(uintmax_t input)\n{\n int i;\n bool first;\n uintmax_t weeks, days, hours, mins; \n /*seconds kept in input*/\n \n char *retval;\n FILE *stream;\n size_t size;\n uintmax_t *traverse[N_EL]={&weeks,&days,\n &hours,&mins,&input};\n char *labels[N_EL]={\"wk\",\"d\",\"hr\",\"min\",\"sec\"};\n\n weeks = sec_to_week(input);\n input = input - week_to_sec(weeks);\n\n days = sec_to_day(input);\n input = input - day_to_sec(days);\n\n hours = sec_to_hour(input);\n input = input - hour_to_sec(hours);\n\n mins = sec_to_min(input);\n input = input - min_to_sec(mins); \n /* input now has the remaining seconds */\n\n /* open stream */\n stream = open_memstream(&retval,&size);\n if(stream == 0) {\n fprintf(stderr,\"Unable to allocate memory\");\n return 0;\n }\n\n /* populate stream */\n first = true;\n for(i=0;i\n#include \n\nusing entry = std::pair;\n\nvoid print(const std::vector& entries, std::ostream& out = std::cout)\n{\n bool first = true;\n for(const auto& e: entries) {\n if(!first) out << \", \";\n first = false;\n out << e.first << \" \" << e.second;\n }\n out << '\\n';\n}\n\nstd::vector convert(int seconds)\n{\n static const entry time_table[] = {\n {7*24*60*60, \"wk\"}, {24*60*60, \"d\"}, {60*60, \"hr\"}, {60, \"min\"}, {1, \"sec\"}\n };\n std::vector result;\n for(const auto& e: time_table) {\n int time = seconds / e.first;\n if(time != 0) result.emplace_back(time, e.second);\n seconds %= e.first;\n }\n return result;\n}\n\nint main()\n{\n std::cout << \" 7259 sec is \"; print(convert( 7259));\n std::cout << \" 86400 sec is \"; print(convert( 86400));\n std::cout << \"6000000 sec is \"; print(convert(6000000));\n}"} -{"title": "Convert seconds to compound duration", "language": "JavaScript", "task": "Write a function or program which:\n* takes a positive integer representing a duration in seconds as input (e.g., 100), and\n* returns a string which shows the same duration decomposed into:\n:::* weeks,\n:::* days, \n:::* hours, \n:::* minutes, and \n:::* seconds.\n\nThis is detailed below (e.g., \"2 hr, 59 sec\").\n\n\nDemonstrate that it passes the following three test-cases:\n\n'''''Test Cases'''''\n\n:::::{| class=\"wikitable\"\n|-\n! input number\n! output string\n|-\n| 7259\n| 2 hr, 59 sec\n|-\n| 86400\n| 1 d\n|-\n| 6000000\n| 9 wk, 6 d, 10 hr, 40 min\n|}\n\n'''''Details'''''\n\nThe following five units should be used:\n:::::{| class=\"wikitable\"\n|-\n! unit\n! suffix used in output\n! conversion\n|-\n| week\n| wk\n| 1 week = 7 days\n|-\n| day\n| d\n| 1 day = 24 hours\n|-\n| hour\n| hr\n| 1 hour = 60 minutes\n|-\n| minute\n| min\n| 1 minute = 60 seconds\n|-\n| second\n| sec\n| \n|}\n\nHowever, '''only''' include quantities with non-zero values in the output (e.g., return \"1 d\" and not \"0 wk, 1 d, 0 hr, 0 min, 0 sec\").\n\nGive larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)\n\nMimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).\n\n\n", "solution": "(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": "Write a function or program which:\n* takes a positive integer representing a duration in seconds as input (e.g., 100), and\n* returns a string which shows the same duration decomposed into:\n:::* weeks,\n:::* days, \n:::* hours, \n:::* minutes, and \n:::* seconds.\n\nThis is detailed below (e.g., \"2 hr, 59 sec\").\n\n\nDemonstrate that it passes the following three test-cases:\n\n'''''Test Cases'''''\n\n:::::{| class=\"wikitable\"\n|-\n! input number\n! output string\n|-\n| 7259\n| 2 hr, 59 sec\n|-\n| 86400\n| 1 d\n|-\n| 6000000\n| 9 wk, 6 d, 10 hr, 40 min\n|}\n\n'''''Details'''''\n\nThe following five units should be used:\n:::::{| class=\"wikitable\"\n|-\n! unit\n! suffix used in output\n! conversion\n|-\n| week\n| wk\n| 1 week = 7 days\n|-\n| day\n| d\n| 1 day = 24 hours\n|-\n| hour\n| hr\n| 1 hour = 60 minutes\n|-\n| minute\n| min\n| 1 minute = 60 seconds\n|-\n| second\n| sec\n| \n|}\n\nHowever, '''only''' include quantities with non-zero values in the output (e.g., return \"1 d\" and not \"0 wk, 1 d, 0 hr, 0 min, 0 sec\").\n\nGive larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)\n\nMimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).\n\n\n", "solution": "'''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": "#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": "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": "#include \n#include \n\nint main() {\n using namespace std;\n noskipws(cin);\n copy(\n istream_iterator(cin),\n istream_iterator(),\n ostream_iterator(cout)\n );\n return 0;\n}"} -{"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 US currency: \n:::# quarters (25 cents)\n:::# dimes (10 cents)\n:::# nickels (5 cents), and \n:::# pennies (1 cent) \n\n\nThere are six ways to make change for 15 cents:\n:::# A dime and a nickel \n:::# A dime and 5 pennies\n:::# 3 nickels\n:::# 2 nickels and 5 pennies\n:::# A nickel and 10 pennies\n:::# 15 pennies\n\n\n;Task:\nHow many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).\n\n\n;Optional:\nLess common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000? \n\n(Note: the answer is larger than 232).\n\n\n;References:\n* an algorithm from the book ''Structure and Interpretation of Computer Programs''.\n* an article in the algorithmist.\n* Change-making problem on Wikipedia.\n\n", "solution": "#include \n#include \n#include \n\n// ad hoc 128 bit integer type; faster than using GMP because of low\n// overhead\ntypedef struct { uint64_t x[2]; } i128;\n\n// display in decimal\nvoid show(i128 v) {\n\tuint32_t x[4] = {v.x[0], v.x[0] >> 32, v.x[1], v.x[1] >> 32};\n\tint i, j = 0, len = 4;\n\tchar buf[100];\n\tdo {\n\t\tuint64_t c = 0;\n\t\tfor (i = len; i--; ) {\n\t\t\tc = (c << 32) + x[i];\n\t\t\tx[i] = c / 10, c %= 10;\n\t\t}\n\n\t\tbuf[j++] = c + '0';\n\t\tfor (len = 4; !x[len - 1]; len--);\n\t} while (len);\n\n\twhile (j--) putchar(buf[j]);\n\tputchar('\\n');\n}\n\ni128 count(int sum, int *coins)\n{\n\tint n, i, k;\n\tfor (n = 0; coins[n]; n++);\n\n\ti128 **v = malloc(sizeof(int*) * n);\n\tint *idx = malloc(sizeof(int) * n);\n\n\tfor (i = 0; i < n; i++) {\n\t\tidx[i] = coins[i];\n\t\t// each v[i] is a cyclic buffer\n\t\tv[i] = calloc(sizeof(i128), coins[i]);\n\t}\n\n\tv[0][coins[0] - 1] = (i128) {{1, 0}};\n\n\tfor (k = 0; k <= sum; k++) {\n\t\tfor (i = 0; i < n; i++)\n\t\t\tif (!idx[i]--) idx[i] = coins[i] - 1;\n\n\t\ti128 c = v[0][ idx[0] ];\n\n\t\tfor (i = 1; i < n; i++) {\n\t\t\ti128 *p = v[i] + idx[i];\n\n\t\t\t// 128 bit addition\n\t\t\tp->x[0] += c.x[0];\n\t\t\tp->x[1] += c.x[1];\n\t\t\tif (p->x[0] < c.x[0]) // carry\n\t\t\t\tp->x[1] ++;\n\t\t\tc = *p;\n\t\t}\n\t}\n\n\ti128 r = v[n - 1][idx[n-1]];\n\n\tfor (i = 0; i < n; i++) free(v[i]);\n\tfree(v);\n\tfree(idx);\n\n\treturn r;\n}\n\n// simple recursive method; slow\nint count2(int sum, int *coins)\n{\n\tif (!*coins || sum < 0) return 0;\n\tif (!sum) return 1;\n\treturn count2(sum - *coins, coins) + count2(sum, coins + 1);\n}\n\nint main(void)\n{\n\tint us_coins[] = { 100, 50, 25, 10, 5, 1, 0 };\n\tint eu_coins[] = { 200, 100, 50, 20, 10, 5, 2, 1, 0 };\n\n\tshow(count( 100, us_coins + 2));\n\tshow(count( 1000, us_coins));\n\n\tshow(count( 1000 * 100, us_coins));\n\tshow(count( 10000 * 100, us_coins));\n\tshow(count(100000 * 100, us_coins));\n\n\tputchar('\\n');\n\n\tshow(count( 1 * 100, eu_coins));\n\tshow(count( 1000 * 100, eu_coins));\n\tshow(count( 10000 * 100, eu_coins));\n\tshow(count(100000 * 100, eu_coins));\n\n\treturn 0;\n}"} -{"title": "Count the coins", "language": "C++", "task": "There are four types of common coins in US currency: \n:::# quarters (25 cents)\n:::# dimes (10 cents)\n:::# nickels (5 cents), and \n:::# pennies (1 cent) \n\n\nThere are six ways to make change for 15 cents:\n:::# A dime and a nickel \n:::# A dime and 5 pennies\n:::# 3 nickels\n:::# 2 nickels and 5 pennies\n:::# A nickel and 10 pennies\n:::# 15 pennies\n\n\n;Task:\nHow many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).\n\n\n;Optional:\nLess common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000? \n\n(Note: the answer is larger than 232).\n\n\n;References:\n* an algorithm from the book ''Structure and Interpretation of Computer Programs''.\n* an article in the algorithmist.\n* Change-making problem on Wikipedia.\n\n", "solution": "#include \n#include \n#include \n\nstruct DataFrame {\n int sum;\n std::vector coins;\n std::vector avail_coins;\n};\n\nint main() {\n std::stack s;\n s.push({ 100, {}, { 25, 10, 5, 1 } });\n int ways = 0;\n while (!s.empty()) {\n DataFrame top = s.top();\n s.pop();\n if (top.sum < 0) continue;\n if (top.sum == 0) {\n ++ways;\n continue;\n }\n if (top.avail_coins.empty()) continue;\n DataFrame d = top;\n d.sum -= top.avail_coins[0];\n d.coins.push_back(top.avail_coins[0]);\n s.push(d);\n d = top;\n d.avail_coins.erase(std::begin(d.avail_coins));\n s.push(d);\n }\n std::cout << ways << std::endl;\n return 0;\n}"} -{"title": "Count the coins", "language": "JavaScript", "task": "There are four types of common coins in US currency: \n:::# quarters (25 cents)\n:::# dimes (10 cents)\n:::# nickels (5 cents), and \n:::# pennies (1 cent) \n\n\nThere are six ways to make change for 15 cents:\n:::# A dime and a nickel \n:::# A dime and 5 pennies\n:::# 3 nickels\n:::# 2 nickels and 5 pennies\n:::# A nickel and 10 pennies\n:::# 15 pennies\n\n\n;Task:\nHow many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).\n\n\n;Optional:\nLess common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000? \n\n(Note: the answer is larger than 232).\n\n\n;References:\n* an algorithm from the book ''Structure and Interpretation of Computer Programs''.\n* an article in the algorithmist.\n* Change-making problem on Wikipedia.\n\n", "solution": "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": "JavaScript from C#", "task": "There are four types of common coins in US currency: \n:::# quarters (25 cents)\n:::# dimes (10 cents)\n:::# nickels (5 cents), and \n:::# pennies (1 cent) \n\n\nThere are six ways to make change for 15 cents:\n:::# A dime and a nickel \n:::# A dime and 5 pennies\n:::# 3 nickels\n:::# 2 nickels and 5 pennies\n:::# A nickel and 10 pennies\n:::# 15 pennies\n\n\n;Task:\nHow many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).\n\n\n;Optional:\nLess common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000? \n\n(Note: the answer is larger than 232).\n\n\n;References:\n* an algorithm from the book ''Structure and Interpretation of Computer Programs''.\n* an article in the algorithmist.\n* Change-making problem on Wikipedia.\n\n", "solution": "var amount = 100,\n coin = [1, 5, 10, 25]\nvar t = [1];\nfor (t[amount] = 0, a = 1; a < amount; a++) t[a] = 0 // initialise t[0..amount]=[1,0,...,0]\nfor (var i = 0, e = coin.length; i < e; i++)\n for (var ci = coin[i], a = ci; a <= amount; a++)\n t[a] += t[a - ci]\ndocument.write(t[amount])"} -{"title": "Count the coins", "language": "Python from Go", "task": "There are four types of common coins in US currency: \n:::# quarters (25 cents)\n:::# dimes (10 cents)\n:::# nickels (5 cents), and \n:::# pennies (1 cent) \n\n\nThere are six ways to make change for 15 cents:\n:::# A dime and a nickel \n:::# A dime and 5 pennies\n:::# 3 nickels\n:::# 2 nickels and 5 pennies\n:::# A nickel and 10 pennies\n:::# 15 pennies\n\n\n;Task:\nHow many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).\n\n\n;Optional:\nLess common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000? \n\n(Note: the answer is larger than 232).\n\n\n;References:\n* an algorithm from the book ''Structure and Interpretation of Computer Programs''.\n* an article in the algorithmist.\n* Change-making problem on Wikipedia.\n\n", "solution": "def changes(amount, coins):\n ways = [0] * (amount + 1)\n ways[0] = 1\n for coin in coins:\n for j in xrange(coin, amount + 1):\n ways[j] += ways[j - coin]\n return ways[amount]\n\nprint changes(100, [1, 5, 10, 25])\nprint changes(100000, [1, 5, 10, 25, 50, 100])"} -{"title": "Count the coins", "language": "Python from C", "task": "There are four types of common coins in US currency: \n:::# quarters (25 cents)\n:::# dimes (10 cents)\n:::# nickels (5 cents), and \n:::# pennies (1 cent) \n\n\nThere are six ways to make change for 15 cents:\n:::# A dime and a nickel \n:::# A dime and 5 pennies\n:::# 3 nickels\n:::# 2 nickels and 5 pennies\n:::# A nickel and 10 pennies\n:::# 15 pennies\n\n\n;Task:\nHow many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).\n\n\n;Optional:\nLess common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000? \n\n(Note: the answer is larger than 232).\n\n\n;References:\n* an algorithm from the book ''Structure and Interpretation of Computer Programs''.\n* an article in the algorithmist.\n* Change-making problem on Wikipedia.\n\n", "solution": "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\"\");\n\tfor (i = 0; i < 4; i++) {\n\t\tprintf(\"\", i,\n\t\t\trand() % 10000, rand() % 10000, rand() % 10000);\n\t}\n\tprintf(\"
XYZ
%d%d%d%d
\");\n\n\treturn 0;\n}"} -{"title": "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#include \n#include \n#include \n#include \n\nvoid makeGap( int gap , std::string & text ) {\n for ( int i = 0 ; i < gap ; i++ ) \n text.append( \" \" ) ;\n}\n\nint main( ) {\n boost::array chars = { 'X' , 'Y' , 'Z' } ;\n int headgap = 3 ;\n int bodygap = 3 ;\n int tablegap = 6 ;\n int rowgap = 9 ;\n std::string tabletext( \"\\n\" ) ;\n makeGap( headgap , tabletext ) ;\n tabletext += \"\\n\" ;\n makeGap( bodygap , tabletext ) ;\n tabletext += \"\\n\" ;\n makeGap( tablegap , tabletext ) ;\n tabletext += \"\\n\" ;\n makeGap( tablegap + 1 , tabletext ) ;\n tabletext += \"\\n\" ;\n makeGap( tablegap, tabletext ) ;\n tabletext += \"\" ;\n for ( int i = 0 ; i < 3 ; i++ ) {\n tabletext += \"\" ;\n }\n tabletext += \"\\n\" ;\n makeGap( tablegap + 1 , tabletext ) ;\n tabletext += \"\" ;\n makeGap( tablegap + 1 , tabletext ) ;\n tabletext += \"\\n\" ;\n srand( time( 0 ) ) ;\n for ( int row = 0 ; row < 5 ; row++ ) {\n makeGap( rowgap , tabletext ) ;\n std::ostringstream oss ;\n tabletext += \"\" ;\n }\n tabletext += \"\\n\" ;\n }\n makeGap( tablegap + 1 , tabletext ) ;\n tabletext += \"\\n\" ;\n makeGap( tablegap , tabletext ) ;\n tabletext += \"
\" ;\n tabletext += *(chars.begin( ) + i ) ;\n tabletext += \"
\" ;\n oss << row ;\n tabletext += oss.str( ) ;\n for ( int col = 0 ; col < 3 ; col++ ) {\n\t oss.str( \"\" ) ;\n\t int randnumber = rand( ) % 10000 ;\n\t oss << randnumber ;\n\t tabletext += \"\" ;\n\t tabletext.append( oss.str( ) ) ;\n\t tabletext += \"
\\n\" ;\n makeGap( bodygap , tabletext ) ;\n tabletext += \"\\n\" ;\n tabletext += \"\\n\" ;\n std::ofstream htmltable( \"testtable.html\" , std::ios::out | std::ios::trunc ) ;\n htmltable << tabletext ;\n htmltable.close( ) ;\n return 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": "import 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": "Create an HTML table", "language": "Python 3.6", "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": "from functools import (reduce)\nimport itertools\nimport random\n\n\n# HTML RENDERING ----------------------------------------\n\n# treeHTML :: tree\n# {tag :: String, text :: String, kvs :: Dict}\n# -> HTML String\ndef treeHTML(tree):\n return foldTree(\n lambda x: lambda xs: (\n f\"<{x['tag'] + attribString(x)}>\" + (\n str(x['text']) if 'text' in x else '\\n'\n ) + ''.join(xs) + f\"\\n\"\n )\n )(tree)\n\n\n# attribString :: Dict -> String\ndef attribString(dct):\n kvs = dct['kvs'] if 'kvs' in dct else None\n return ' ' + reduce(\n lambda a, k: a + k + '=\"' + kvs[k] + '\" ',\n kvs.keys(), ''\n ).strip() if kvs else ''\n\n\n# HTML TABLE FROM GENERATED DATA ------------------------\n\n\ndef main():\n # Number of columns and rows to generate.\n n = 3\n\n # Table details -------------------------------------\n strCaption = 'Table generated with Python'\n colNames = take(n)(enumFrom('A'))\n dataRows = map(\n lambda x: (x, map(\n lambda _: random.randint(100, 9999),\n colNames\n )), take(n)(enumFrom(1)))\n tableStyle = {\n 'style': \"width:25%; border:2px solid silver;\"\n }\n trStyle = {\n 'style': \"border:1px solid silver;text-align:right;\"\n }\n\n # TREE STRUCTURE OF TABLE ---------------------------\n tableTree = Node({'tag': 'table', 'kvs': tableStyle})([\n Node({\n 'tag': 'caption',\n 'text': strCaption\n })([]),\n\n # HEADER ROW --------------------------------\n (Node({'tag': 'tr'})(\n Node({\n 'tag': 'th',\n 'kvs': {'style': 'text-align:right;'},\n 'text': k\n })([]) for k in ([''] + colNames)\n ))\n ] +\n # DATA ROWS ---------------------------------\n list(Node({'tag': 'tr', 'kvs': trStyle})(\n [Node({'tag': 'th', 'text': tpl[0]})([])] +\n list(Node(\n {'tag': 'td', 'text': str(v)})([]) for v in tpl[1]\n )\n ) for tpl in dataRows)\n )\n\n print(\n treeHTML(tableTree)\n # dataRows\n )\n\n\n# GENERIC -----------------------------------------------\n\n# Node :: a -> [Tree a] -> Tree a\ndef Node(v):\n return lambda xs: {'type': 'Node', 'root': v, 'nest': xs}\n\n\n# enumFrom :: Enum a => a -> [a]\ndef enumFrom(x):\n return itertools.count(x) if type(x) is int else (\n map(chr, itertools.count(ord(x)))\n )\n\n\n# foldTree :: (a -> [b] -> b) -> Tree a -> b\ndef foldTree(f):\n def go(node):\n return f(node['root'])(\n list(map(go, node['nest']))\n )\n return lambda tree: go(tree)\n\n\n# take :: Int -> [a] -> [a]\n# take :: Int -> String -> String\ndef take(n):\n return lambda xs: (\n xs[0:n]\n if isinstance(xs, list)\n else list(itertools.islice(xs, n))\n )\n\n\nif __name__ == '__main__':\n main()"} -{"title": "Cullen and Woodall numbers", "language": "Python", "task": "A Cullen number is a number of the form '''n x 2n + 1''' where '''n''' is a natural number.\n\nA Woodall number is very similar. It is a number of the form '''n x 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": "print(\"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": "Cullen and Woodall numbers", "language": "Python from Quackery", "task": "A Cullen number is a number of the form '''n x 2n + 1''' where '''n''' is a natural number.\n\nA Woodall number is very similar. It is a number of the form '''n x 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": "def cullen(n): return((n<\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": "C++", "task": "{{Wikipedia|Currying}}\n\n\n;Task:\nCreate a simple demonstrative example of Currying in a specific language. \n\nAdd any historic details as to how the feature made its way into the language.\n\n\n\n", "solution": "Currying may be achieved in [[C++]] using the [[wp:Standard Template Library|Standard Template Library]] function object adapters (binder1st and binder2nd), and more generically using the [[wp:Boost library|Boost]] bind mechanism.\n\n"} -{"title": "Currying", "language": "JavaScript", "task": "{{Wikipedia|Currying}}\n\n\n;Task:\nCreate a simple demonstrative example of Currying in a specific language. \n\nAdd any historic details as to how the feature made its way into the language.\n\n\n\n", "solution": "(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": "{{Wikipedia|Currying}}\n\n\n;Task:\nCreate a simple demonstrative example of Currying in a specific language. \n\nAdd any historic details as to how the feature made its way into the language.\n\n\n\n", "solution": "# 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 x 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 x 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;* 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)\n return 0;\n uint64_t result = 1;\n base %= mod;\n for (; exp > 0; exp >>= 1) {\n if ((exp & 1) == 1)\n result = (result * base) % mod;\n base = (base * base) % mod;\n }\n return result;\n}\n\nbool is_curzon(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 for (uint64_t k = 2; k <= 10; k += 2) {\n std::cout << \"Curzon numbers with base \" << k << \":\\n\";\n uint64_t count = 0, n = 1;\n for (; count < 50; ++n) {\n if (is_curzon(n, k)) {\n std::cout << std::setw(4) << n\n << (++count % 10 == 0 ? '\\n' : ' ');\n }\n }\n for (;;) {\n if (is_curzon(n, k))\n ++count;\n if (count == 1000)\n break;\n ++n;\n }\n std::cout << \"1000th Curzon number with base \" << k << \": \" << n\n << \"\\n\\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 x 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 x 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;* 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'' x ''n'' squares. If ''m'' and ''n'' are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180deg). All such paths for 2 x 2 and 4 x 3 rectangles are shown below.\n\n[[file:rect-cut.svg]]\n\nWrite a program that calculates the number of different ways to cut an ''m'' x ''n'' rectangle. Optionally, show each of the cuts.\n\nPossibly related task: [[Maze generation]] for depth-first search.\n\n", "solution": "#include \n#include \n\ntypedef unsigned char byte;\nint w = 0, h = 0, verbose = 0;\nunsigned long count = 0;\n\nbyte **hor, **ver, **vis;\nbyte **c = 0;\n\nenum { U = 1, D = 2, L = 4, R = 8 };\n\nbyte ** alloc2(int w, int h)\n{\n\tint i;\n\tbyte **x = calloc(1, sizeof(byte*) * h + h * w);\n\tx[0] = (byte *)&x[h];\n\tfor (i = 1; i < h; i++)\n\t\tx[i] = x[i - 1] + w;\n\treturn x;\n}\n\nvoid show()\n{\n\tint i, j, v, last_v;\n\tprintf(\"%ld\\n\", count);\n#if 0\n\tfor (i = 0; i <= h; i++) {\n\t\tfor (j = 0; j <= w; j++)\n\t\t\tprintf(\"%d \", hor[i][j]);\n\t\tputs(\"\");\n\t}\n\tputs(\"\");\n\n\tfor (i = 0; i <= h; i++) {\n\t\tfor (j = 0; j <= w; j++)\n\t\t\tprintf(\"%d \", ver[i][j]);\n\t\tputs(\"\");\n\t}\n\tputs(\"\");\n#endif\n\tfor (i = 0; i < h; i++) {\n\t\tif (!i) v = last_v = 0;\n\t\telse last_v = v = hor[i][0] ? !last_v : last_v;\n\n\t\tfor (j = 0; j < w; v = ver[i][++j] ? !v : v)\n\t\t\tprintf(v ? \"\\033[31m[]\" : \"\\033[33m{}\");\n\t\tputs(\"\\033[m\");\n\t}\n\tputchar('\\n');\n}\n\nvoid walk(int y, int x)\n{\n\tif (x < 0 || y < 0 || x > w || y > h) return;\n\n\tif (!x || !y || x == w || y == h) {\n\t\t++count;\n\t\tif (verbose) show();\n\t\treturn;\n\t}\n\n\tif (vis[y][x]) return;\n\tvis[y][x]++; vis[h - y][w - x]++;\n\n\tif (x && !hor[y][x - 1]) {\n\t\thor[y][x - 1] = hor[h - y][w - x] = 1;\n\t\twalk(y, x - 1);\n\t\thor[y][x - 1] = hor[h - y][w - x] = 0;\n\t}\n\tif (x < w && !hor[y][x]) {\n\t\thor[y][x] = hor[h - y][w - x - 1] = 1;\n\t\twalk(y, x + 1);\n\t\thor[y][x] = hor[h - y][w - x - 1] = 0;\n\t}\n\n\tif (y && !ver[y - 1][x]) {\n\t\tver[y - 1][x] = ver[h - y][w - x] = 1;\n\t\twalk(y - 1, x);\n\t\tver[y - 1][x] = ver[h - y][w - x] = 0;\n\t}\n\n\tif (y < h && !ver[y][x]) {\n\t\tver[y][x] = ver[h - y - 1][w - x] = 1;\n\t\twalk(y + 1, x);\n\t\tver[y][x] = ver[h - y - 1][w - x] = 0;\n\t}\n\n\tvis[y][x]--; vis[h - y][w - x]--;\n}\n\nvoid cut(void)\n{\n\tif (1 & (h * w)) return;\n\n\thor = alloc2(w + 1, h + 1);\n\tver = alloc2(w + 1, h + 1);\n\tvis = alloc2(w + 1, h + 1);\n\n\tif (h & 1) {\n\t\tver[h/2][w/2] = 1;\n\t\twalk(h / 2, w / 2);\n\t} else if (w & 1) {\n\t\thor[h/2][w/2] = 1;\n\t\twalk(h / 2, w / 2);\n\t} else {\n\t\tvis[h/2][w/2] = 1;\n\n\t\thor[h/2][w/2-1] = hor[h/2][w/2] = 1;\n\t\twalk(h / 2, w / 2 - 1);\n\t\thor[h/2][w/2-1] = hor[h/2][w/2] = 0;\n\n\t\tver[h/2 - 1][w/2] = ver[h/2][w/2] = 1;\n\t\twalk(h / 2 - 1, w/2);\n\t}\n}\n\nvoid cwalk(int y, int x, int d)\n{\n\tif (!y || y == h || !x || x == w) {\n\t\t++count;\n\t\treturn;\n\t}\n\tvis[y][x] = vis[h-y][w-x] = 1;\n\n\tif (x && !vis[y][x-1])\n\t\tcwalk(y, x - 1, d|1);\n\tif ((d&1) && x < w && !vis[y][x+1])\n\t\tcwalk(y, x + 1, d|1);\n\tif (y && !vis[y-1][x])\n\t\tcwalk(y - 1, x, d|2);\n\tif ((d&2) && y < h && !vis[y + 1][x])\n\t\tcwalk(y + 1, x, d|2);\n\n\tvis[y][x] = vis[h-y][w-x] = 0;\n}\n\nvoid count_only(void)\n{\n\tint t;\n\tlong res;\n\tif (h * w & 1) return;\n\tif (h & 1) t = h, h = w, w = t;\n\n\tvis = alloc2(w + 1, h + 1);\n\tvis[h/2][w/2] = 1;\n\n\tif (w & 1) vis[h/2][w/2 + 1] = 1;\n\tif (w > 1) {\n\t\tcwalk(h/2, w/2 - 1, 1);\n\t\tres = 2 * count - 1;\n\t\tcount = 0;\n\t\tif (w != h)\n\t\t\tcwalk(h/2+1, w/2, (w & 1) ? 3 : 2);\n\n\t\tres += 2 * count - !(w & 1);\n\t} else {\n\t\tres = 1;\n\t}\n\tif (w == h) res = 2 * res + 2;\n\tcount = res;\n}\n\nint main(int c, char **v)\n{\n\tint i;\n\n\tfor (i = 1; i < c; i++) {\n\t\tif (v[i][0] == '-' && v[i][1] == 'v' && !v[i][2]) {\n\t\t\tverbose = 1;\n\t\t} else if (!w) {\n\t\t\tw = atoi(v[i]);\n\t\t\tif (w <= 0) goto bail;\n\t\t} else if (!h) {\n\t\t\th = atoi(v[i]);\n\t\t\tif (h <= 0) goto bail;\n\t\t} else\n\t\t\tgoto bail;\n\t}\n\tif (!w) goto bail;\n\tif (!h) h = w;\n\n\tif (verbose) cut();\n\telse count_only();\n\n\tprintf(\"Total: %ld\\n\", count);\n\treturn 0;\n\nbail:\tfprintf(stderr, \"bad args\\n\");\n\treturn 1;\n}"} -{"title": "Cut a rectangle", "language": "C++ from Java", "task": "A given rectangle is made from ''m'' x ''n'' squares. If ''m'' and ''n'' are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180deg). All such paths for 2 x 2 and 4 x 3 rectangles are shown below.\n\n[[file:rect-cut.svg]]\n\nWrite a program that calculates the number of different ways to cut an ''m'' x ''n'' rectangle. Optionally, show each of the cuts.\n\nPossibly related task: [[Maze generation]] for depth-first search.\n\n", "solution": "#include \n#include \n#include \n#include \n\nconst std::array, 4> DIRS = {\n std::make_pair(0, -1),\n std::make_pair(-1, 0),\n std::make_pair(0, 1),\n std::make_pair(1, 0),\n};\n\nvoid printResult(const std::vector> &v) {\n for (auto &row : v) {\n auto it = row.cbegin();\n auto end = row.cend();\n\n std::cout << '[';\n if (it != end) {\n std::cout << *it;\n it = std::next(it);\n }\n while (it != end) {\n std::cout << \", \" << *it;\n it = std::next(it);\n }\n std::cout << \"]\\n\";\n }\n}\n\nvoid cutRectangle(int w, int h) {\n if (w % 2 == 1 && h % 2 == 1) {\n return;\n }\n\n std::vector> grid(h, std::vector(w));\n std::stack stack;\n\n int half = (w * h) / 2;\n long bits = (long)pow(2, half) - 1;\n\n for (; bits > 0; bits -= 2) {\n for (int i = 0; i < half; i++) {\n int r = i / w;\n int c = i % w;\n grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n }\n\n stack.push(0);\n grid[0][0] = 2;\n int count = 1;\n while (!stack.empty()) {\n int pos = stack.top();\n stack.pop();\n\n int r = pos / w;\n int c = pos % w;\n for (auto dir : DIRS) {\n int nextR = r + dir.first;\n int nextC = c + dir.second;\n\n if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n if (grid[nextR][nextC] == 1) {\n stack.push(nextR * w + nextC);\n grid[nextR][nextC] = 2;\n count++;\n }\n }\n }\n }\n if (count == half) {\n printResult(grid);\n std::cout << '\\n';\n }\n }\n}\n\nint main() {\n cutRectangle(2, 2);\n cutRectangle(4, 3);\n\n return 0;\n}"} -{"title": "Cut a rectangle", "language": "Python from D", "task": "A given rectangle is made from ''m'' x ''n'' squares. If ''m'' and ''n'' are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180deg). All such paths for 2 x 2 and 4 x 3 rectangles are shown below.\n\n[[file:rect-cut.svg]]\n\nWrite a program that calculates the number of different ways to cut an ''m'' x ''n'' rectangle. Optionally, show each of the cuts.\n\nPossibly related task: [[Maze generation]] for depth-first search.\n\n", "solution": "try:\n import psyco\nexcept ImportError:\n pass\nelse:\n psyco.full()\n\nw, h = 0, 0\ncount = 0\nvis = []\n\ndef cwalk(y, x, d):\n global vis, count, w, h\n if not y or y == h or not x or x == w:\n count += 1\n return\n\n vis[y][x] = vis[h - y][w - x] = 1\n\n if x and not vis[y][x - 1]:\n cwalk(y, x - 1, d | 1)\n if (d & 1) and x < w and not vis[y][x+1]:\n cwalk(y, x + 1, d|1)\n if y and not vis[y - 1][x]:\n cwalk(y - 1, x, d | 2)\n if (d & 2) and y < h and not vis[y + 1][x]:\n cwalk(y + 1, x, d | 2)\n\n vis[y][x] = vis[h - y][w - x] = 0\n\ndef count_only(x, y):\n global vis, count, w, h\n count = 0\n w = x\n h = y\n\n if (h * w) & 1:\n return count\n if h & 1:\n w, h = h, w\n\n vis = [[0] * (w + 1) for _ in xrange(h + 1)]\n vis[h // 2][w // 2] = 1\n\n if w & 1:\n vis[h // 2][w // 2 + 1] = 1\n\n res = 0\n if w > 1:\n cwalk(h // 2, w // 2 - 1, 1)\n res = 2 * count - 1\n count = 0\n if w != h:\n cwalk(h // 2 + 1, w // 2, 3 if (w & 1) else 2)\n\n res += 2 * count - (not (w & 1))\n else:\n res = 1\n\n if w == h:\n res = 2 * res + 2\n return res\n\ndef main():\n for y in xrange(1, 10):\n for x in xrange(1, y + 1):\n if not (x & 1) or not (y & 1):\n print \"%d x %d: %d\" % (y, x, count_only(x, y))\n\nmain()"} -{"title": "Cyclotomic polynomial", "language": "C++ from Java", "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 - 1, and is not a divisor of x^k - 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": "#include \n#include \n#include \n#include \n#include \n\nconst int MAX_ALL_FACTORS = 100000;\nconst int algorithm = 2;\nint divisions = 0;\n\n//Note: Cyclotomic Polynomials have small coefficients. Not appropriate for general polynomial usage.\nclass Term {\nprivate:\n long m_coefficient;\n long m_exponent;\n\npublic:\n Term(long c, long e) : m_coefficient(c), m_exponent(e) {\n // empty\n }\n\n Term(const Term &t) : m_coefficient(t.m_coefficient), m_exponent(t.m_exponent) {\n // empty\n }\n\n long coefficient() const {\n return m_coefficient;\n }\n\n long degree() const {\n return m_exponent;\n }\n\n Term operator -() const {\n return { -m_coefficient, m_exponent };\n }\n\n Term operator *(const Term &rhs) const {\n return { m_coefficient * rhs.m_coefficient, m_exponent + rhs.m_exponent };\n }\n\n Term operator +(const Term &rhs) const {\n if (m_exponent != rhs.m_exponent) {\n throw std::runtime_error(\"Exponents not equal\");\n }\n return { m_coefficient + rhs.m_coefficient, m_exponent };\n }\n\n friend std::ostream &operator<<(std::ostream &, const Term &);\n};\n\nstd::ostream &operator<<(std::ostream &os, const Term &t) {\n if (t.m_coefficient == 0) {\n return os << '0';\n }\n if (t.m_exponent == 0) {\n return os << t.m_coefficient;\n }\n if (t.m_coefficient == 1) {\n if (t.m_exponent == 1) {\n return os << 'x';\n }\n return os << \"x^\" << t.m_exponent;\n }\n if (t.m_coefficient == -1) {\n if (t.m_exponent == 1) {\n return os << \"-x\";\n }\n return os << \"-x^\" << t.m_exponent;\n }\n if (t.m_exponent == 1) {\n return os << t.m_coefficient << 'x';\n }\n return os << t.m_coefficient << \"x^\" << t.m_exponent;\n}\n\nclass Polynomial {\npublic:\n std::vector polynomialTerms;\n\n Polynomial() {\n polynomialTerms.push_back({ 0, 0 });\n }\n\n Polynomial(std::initializer_list values) {\n if (values.size() % 2 != 0) {\n throw std::runtime_error(\"Length must be even.\");\n }\n\n bool ready = false;\n long t;\n for (auto v : values) {\n if (ready) {\n polynomialTerms.push_back({ t, v });\n } else {\n t = v;\n }\n ready = !ready;\n }\n std::sort(\n polynomialTerms.begin(), polynomialTerms.end(),\n [](const Term &t, const Term &u) {\n return u.degree() < t.degree();\n }\n );\n }\n\n Polynomial(const std::vector &termList) {\n if (termList.size() == 0) {\n polynomialTerms.push_back({ 0, 0 });\n } else {\n for (auto t : termList) {\n if (t.coefficient() != 0) {\n polynomialTerms.push_back(t);\n }\n }\n if (polynomialTerms.size() == 0) {\n polynomialTerms.push_back({ 0, 0 });\n }\n std::sort(\n polynomialTerms.begin(), polynomialTerms.end(),\n [](const Term &t, const Term &u) {\n return u.degree() < t.degree();\n }\n );\n }\n }\n\n Polynomial(const Polynomial &p) : Polynomial(p.polynomialTerms) {\n // empty\n }\n\n long leadingCoefficient() const {\n return polynomialTerms[0].coefficient();\n }\n\n long degree() const {\n return polynomialTerms[0].degree();\n }\n\n bool hasCoefficientAbs(int coeff) {\n for (auto term : polynomialTerms) {\n if (abs(term.coefficient()) == coeff) {\n return true;\n }\n }\n return false;\n }\n\n Polynomial operator+(const Term &term) const {\n std::vector termList;\n bool added = false;\n for (size_t index = 0; index < polynomialTerms.size(); index++) {\n auto currentTerm = polynomialTerms[index];\n if (currentTerm.degree() == term.degree()) {\n added = true;\n if (currentTerm.coefficient() + term.coefficient() != 0) {\n termList.push_back(currentTerm + term);\n }\n } else {\n termList.push_back(currentTerm);\n }\n }\n if (!added) {\n termList.push_back(term);\n }\n return Polynomial(termList);\n }\n\n Polynomial operator*(const Term &term) const {\n std::vector termList;\n for (size_t index = 0; index < polynomialTerms.size(); index++) {\n auto currentTerm = polynomialTerms[index];\n termList.push_back(currentTerm * term);\n }\n return Polynomial(termList);\n }\n\n Polynomial operator+(const Polynomial &p) const {\n std::vector termList;\n int thisCount = polynomialTerms.size();\n int polyCount = p.polynomialTerms.size();\n while (thisCount > 0 || polyCount > 0) {\n if (thisCount == 0) {\n auto polyTerm = p.polynomialTerms[polyCount - 1];\n termList.push_back(polyTerm);\n polyCount--;\n } else if (polyCount == 0) {\n auto thisTerm = polynomialTerms[thisCount - 1];\n termList.push_back(thisTerm);\n thisCount--;\n } else {\n auto polyTerm = p.polynomialTerms[polyCount - 1];\n auto thisTerm = polynomialTerms[thisCount - 1];\n if (thisTerm.degree() == polyTerm.degree()) {\n auto t = thisTerm + polyTerm;\n if (t.coefficient() != 0) {\n termList.push_back(t);\n }\n thisCount--;\n polyCount--;\n } else if (thisTerm.degree() < polyTerm.degree()) {\n termList.push_back(thisTerm);\n thisCount--;\n } else {\n termList.push_back(polyTerm);\n polyCount--;\n }\n }\n }\n return Polynomial(termList);\n }\n\n Polynomial operator/(const Polynomial &v) {\n divisions++;\n\n Polynomial q;\n Polynomial r(*this);\n long lcv = v.leadingCoefficient();\n long dv = v.degree();\n while (r.degree() >= v.degree()) {\n long lcr = r.leadingCoefficient();\n long s = lcr / lcv;\n Term term(s, r.degree() - dv);\n q = q + term;\n r = r + v * -term;\n }\n\n return q;\n }\n\n friend std::ostream &operator<<(std::ostream &, const Polynomial &);\n};\n\nstd::ostream &operator<<(std::ostream &os, const Polynomial &p) {\n auto it = p.polynomialTerms.cbegin();\n auto end = p.polynomialTerms.cend();\n if (it != end) {\n os << *it;\n it = std::next(it);\n }\n while (it != end) {\n if (it->coefficient() > 0) {\n os << \" + \" << *it;\n } else {\n os << \" - \" << -*it;\n }\n it = std::next(it);\n }\n return os;\n}\n\nstd::vector getDivisors(int number) {\n std::vector divisiors;\n long root = (long)sqrt(number);\n for (int i = 1; i <= root; i++) {\n if (number % i == 0) {\n divisiors.push_back(i);\n int div = number / i;\n if (div != i && div != number) {\n divisiors.push_back(div);\n }\n }\n }\n return divisiors;\n}\n\nstd::map> allFactors;\n\nstd::map getFactors(int number) {\n if (allFactors.find(number) != allFactors.end()) {\n return allFactors[number];\n }\n\n std::map factors;\n if (number % 2 == 0) {\n auto factorsDivTwo = getFactors(number / 2);\n factors.insert(factorsDivTwo.begin(), factorsDivTwo.end());\n if (factors.find(2) != factors.end()) {\n factors[2]++;\n } else {\n factors.insert(std::make_pair(2, 1));\n }\n if (number < MAX_ALL_FACTORS) {\n allFactors.insert(std::make_pair(number, factors));\n }\n return factors;\n }\n long root = (long)sqrt(number);\n long i = 3;\n while (i <= root) {\n if (number % i == 0) {\n auto factorsDivI = getFactors(number / i);\n factors.insert(factorsDivI.begin(), factorsDivI.end());\n if (factors.find(i) != factors.end()) {\n factors[i]++;\n } else {\n factors.insert(std::make_pair(i, 1));\n }\n if (number < MAX_ALL_FACTORS) {\n allFactors.insert(std::make_pair(number, factors));\n }\n return factors;\n }\n i += 2;\n }\n factors.insert(std::make_pair(number, 1));\n if (number < MAX_ALL_FACTORS) {\n allFactors.insert(std::make_pair(number, factors));\n }\n return factors;\n}\n\nstd::map COMPUTED;\nPolynomial cyclotomicPolynomial(int n) {\n if (COMPUTED.find(n) != COMPUTED.end()) {\n return COMPUTED[n];\n }\n\n if (n == 1) {\n // Polynomial: x - 1\n Polynomial p({ 1, 1, -1, 0 });\n COMPUTED.insert(std::make_pair(1, p));\n return p;\n }\n\n auto factors = getFactors(n);\n if (factors.find(n) != factors.end()) {\n // n prime\n std::vector termList;\n for (int index = 0; index < n; index++) {\n termList.push_back({ 1, index });\n }\n\n Polynomial cyclo(termList);\n COMPUTED.insert(std::make_pair(n, cyclo));\n return cyclo;\n } else if (factors.size() == 2 && factors.find(2) != factors.end() && factors[2] == 1 && factors.find(n / 2) != factors.end() && factors[n / 2] == 1) {\n // n = 2p\n int prime = n / 2;\n std::vector termList;\n int coeff = -1;\n\n for (int index = 0; index < prime; index++) {\n coeff *= -1;\n termList.push_back({ coeff, index });\n }\n\n Polynomial cyclo(termList);\n COMPUTED.insert(std::make_pair(n, cyclo));\n return cyclo;\n } else if (factors.size() == 1 && factors.find(2) != factors.end()) {\n // n = 2^h\n int h = factors[2];\n std::vector termList;\n termList.push_back({ 1, (int)pow(2, h - 1) });\n termList.push_back({ 1, 0 });\n\n Polynomial cyclo(termList);\n COMPUTED.insert(std::make_pair(n, cyclo));\n return cyclo;\n } else if (factors.size() == 1 && factors.find(n) != factors.end()) {\n // n = p^k\n int p = 0;\n int k = 0;\n for (auto iter = factors.begin(); iter != factors.end(); ++iter) {\n p = iter->first;\n k = iter->second;\n }\n std::vector termList;\n for (int index = 0; index < p; index++) {\n termList.push_back({ 1, index * (int)pow(p, k - 1) });\n }\n\n Polynomial cyclo(termList);\n COMPUTED.insert(std::make_pair(n, cyclo));\n return cyclo;\n } else if (factors.size() == 2 && factors.find(2) != factors.end()) {\n // n = 2^h * p^k\n int p = 0;\n for (auto iter = factors.begin(); iter != factors.end(); ++iter) {\n if (iter->first != 2) {\n p = iter->first;\n }\n }\n\n std::vector termList;\n int coeff = -1;\n int twoExp = (int)pow(2, factors[2] - 1);\n int k = factors[p];\n for (int index = 0; index < p; index++) {\n coeff *= -1;\n termList.push_back({ coeff, index * twoExp * (int)pow(p, k - 1) });\n }\n\n Polynomial cyclo(termList);\n COMPUTED.insert(std::make_pair(n, cyclo));\n return cyclo;\n } else if (factors.find(2) != factors.end() && ((n / 2) % 2 == 1) && (n / 2) > 1) {\n // CP(2m)[x] = CP(-m)[x], n odd integer > 1\n auto cycloDiv2 = cyclotomicPolynomial(n / 2);\n std::vector termList;\n for (auto term : cycloDiv2.polynomialTerms) {\n if (term.degree() % 2 == 0) {\n termList.push_back(term);\n } else {\n termList.push_back(-term);\n }\n }\n\n Polynomial cyclo(termList);\n COMPUTED.insert(std::make_pair(n, cyclo));\n return cyclo;\n }\n\n // General Case\n\n if (algorithm == 0) {\n // slow - uses basic definition\n auto divisors = getDivisors(n);\n // Polynomial: (x^n - 1)\n Polynomial cyclo({ 1, n, -1, 0 });\n for (auto i : divisors) {\n auto p = cyclotomicPolynomial(i);\n cyclo = cyclo / p;\n }\n\n COMPUTED.insert(std::make_pair(n, cyclo));\n return cyclo;\n } else if (algorithm == 1) {\n // Faster. Remove Max divisor (and all divisors of max divisor) - only one divide for all divisors of Max Divisor\n auto divisors = getDivisors(n);\n int maxDivisor = INT_MIN;\n for (auto div : divisors) {\n maxDivisor = std::max(maxDivisor, div);\n }\n std::vector divisorExceptMax;\n for (auto div : divisors) {\n if (maxDivisor % div != 0) {\n divisorExceptMax.push_back(div);\n }\n }\n\n // Polynomial: ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor\n auto cyclo = Polynomial({ 1, n, -1, 0 }) / Polynomial({ 1, maxDivisor, -1, 0 });\n for (int i : divisorExceptMax) {\n auto p = cyclotomicPolynomial(i);\n cyclo = cyclo / p;\n }\n\n COMPUTED.insert(std::make_pair(n, cyclo));\n return cyclo;\n } else if (algorithm == 2) {\n // Fastest\n // Let p ; q be primes such that p does not divide n, and q q divides n.\n // Then CP(np)[x] = CP(n)[x^p] / CP(n)[x]\n int m = 1;\n auto cyclo = cyclotomicPolynomial(m);\n std::vector primes;\n for (auto iter = factors.begin(); iter != factors.end(); ++iter) {\n primes.push_back(iter->first);\n }\n std::sort(primes.begin(), primes.end());\n for (auto prime : primes) {\n // CP(m)[x]\n auto cycloM = cyclo;\n // Compute CP(m)[x^p].\n std::vector termList;\n for (auto t : cycloM.polynomialTerms) {\n termList.push_back({ t.coefficient(), t.degree() * prime });\n }\n cyclo = Polynomial(termList) / cycloM;\n m = m * prime;\n }\n // Now, m is the largest square free divisor of n\n int s = n / m;\n // Compute CP(n)[x] = CP(m)[x^s]\n std::vector termList;\n for (auto t : cyclo.polynomialTerms) {\n termList.push_back({ t.coefficient(), t.degree() * s });\n }\n\n cyclo = Polynomial(termList);\n COMPUTED.insert(std::make_pair(n, cyclo));\n return cyclo;\n } else {\n throw std::runtime_error(\"Invalid algorithm\");\n }\n}\n\nint main() {\n // initialization\n std::map factors;\n factors.insert(std::make_pair(2, 1));\n allFactors.insert(std::make_pair(2, factors));\n\n // rest of main\n std::cout << \"Task 1: cyclotomic polynomials for n <= 30:\\n\";\n for (int i = 1; i <= 30; i++) {\n auto p = cyclotomicPolynomial(i);\n std::cout << \"CP[\" << i << \"] = \" << p << '\\n';\n }\n\n std::cout << \"Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:\\n\";\n int n = 0;\n for (int i = 1; i <= 10; i++) {\n while (true) {\n n++;\n auto cyclo = cyclotomicPolynomial(n);\n if (cyclo.hasCoefficientAbs(i)) {\n std::cout << \"CP[\" << n << \"] has coefficient with magnitude = \" << i << '\\n';\n n--;\n break;\n }\n }\n }\n\n return 0;\n}"} -{"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 - 1, and is not a divisor of x^k - 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": "C++ from 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\n#include \n\ninline constexper int TABLE[][10] = {\n\t{0, 3, 1, 7, 5, 9, 8, 6, 4, 2},\n\t{7, 0, 9, 2, 1, 5, 4, 8, 6, 3},\n\t{4, 2, 0, 6, 8, 7, 1, 3, 5, 9},\n\t{1, 7, 5, 0, 9, 8, 3, 4, 2, 6},\n\t{6, 1, 2, 3, 0, 4, 5, 9, 7, 8},\n\t{3, 6, 7, 4, 2, 0, 9, 5, 8, 1},\n\t{5, 8, 6, 9, 7, 2, 0, 1, 3, 4},\n\t{8, 9, 4, 5, 3, 6, 2, 0, 1, 7},\n\t{9, 4, 3, 8, 6, 1, 7, 2, 0, 5},\n\t{2, 5, 8, 1, 4, 3, 6, 7, 9, 0},\n};\n\n[[nodiscard]] bool damm(std::string s) noexcept {\n\tint interim = 0;\n\tfor (const auto c : s) {\n\t\tinterim = TABLE[interim][c - '0'];\n\t}\n\treturn interim == 0;\n}\n\nint main() {\n\tfor (const auto num : { 5724, 5727, 112946, 112949 }) {\n\t\tif (damm(std::to_string(num))) {\n\t \t \tstd::printf(\"%6d is valid\\n\", num);\n\t\t}\t\n\t\telse std::printf(\"%6d is invalid\\n\", num);\n\t}\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": "C++ from D", "task": "{{DISPLAYTITLE:de Bruijn sequences}}\nThe sequences are named after the Dutch mathematician Nicolaas Govert de Bruijn.\n\n\nA note on Dutch capitalization: Nicolaas' last name is '''de Bruijn''', the '''de''' isn't normally capitalized\nunless it's the first word in a sentence. 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, a '''de Bruijn sequence''' of order ''n'' on\na size-''k'' alphabet (computer science) ''A'' is a cyclic sequence in which every\npossible length-''n'' string (computer science, formal theory) on ''A'' occurs\nexactly once as a contiguous substring.\n\n\nSuch a sequence is denoted by ''B''(''k'', ''n'') and has\nlength ''k''''n'', which is also the number of distinct substrings of\nlength ''n'' on ''A''; \nde Bruijn sequences are therefore optimally short.\n\n\nThere are:\n (k!)k(n-1) / kn\ndistinct de Bruijn sequences ''B''(''k'', ''n''). \n\n\n;Task:\nFor this Rosetta Code task, a '''de Bruijn''' sequence is to be generated that can be used to shorten a brute-force attack on\na PIN-like code lock that does not have an \"enter\"\nkey and accepts the last ''n'' digits entered.\n\n\nNote: automated teller machines (ATMs) used to work like\nthis, but their software has been updated to not allow a brute-force attack.\n\n\n;Example:\nA digital door lock with a 4-digit code would\nhave ''B'' (10, 4) solutions, with a length of '''10,000''' (digits).\n\nTherefore, only at most '''10,000 + 3''' (as the solutions are cyclic or ''wrap-around'') presses are needed to\nopen the lock.\n\nTrying all 4-digit codes separately would require '''4 x 10,000''' or '''40,000''' presses.\n\n\n;Task requirements:\n:* Generate a de Bruijn sequence for a 4-digit (decimal) PIN code.\n:::* Show the length of the generated de Bruijn sequence.\n:::* (There are many possible de Bruijn sequences that solve this task, one solution is shown on the ''discussion'' page).\n:::* Show the first and last '''130''' digits of the de Bruijn sequence.\n:* Verify that all four-digit (decimal) '''1,000''' PIN codes are contained within the de Bruijn sequence.\n:::* 0000, 0001, 0002, 0003, ... 9996, 9997, 9998, 9999 (note the leading zeros).\n:* Reverse the de Bruijn sequence.\n:* Again, perform the (above) verification test.\n:* Replace the 4,444th digit with a period (.) in the original de Bruijn sequence.\n:::* Perform the verification test (again). There should be four PIN codes missing.\n\n\n(The last requirement is to ensure that the verification tests performs correctly. 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:* Wikipedia entry: de Bruijn sequence.\n:* MathWorld entry: de Bruijn sequence.\n:* An OEIS entry: A166315 lexicographically earliest binary de Bruijn sequences, B(2,n) --- Not B(10,4), but possibly relevant.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ntypedef unsigned char byte;\n\nstd::string deBruijn(int k, int n) {\n std::vector a(k * n, 0);\n std::vector seq;\n\n std::function db;\n db = [&](int t, int p) {\n if (t > n) {\n if (n % p == 0) {\n for (int i = 1; i < p + 1; i++) {\n seq.push_back(a[i]);\n }\n }\n } else {\n a[t] = a[t - p];\n db(t + 1, p);\n auto j = a[t - p] + 1;\n while (j < k) {\n a[t] = j & 0xFF;\n db(t + 1, t);\n j++;\n }\n }\n };\n\n db(1, 1);\n std::string buf;\n for (auto i : seq) {\n buf.push_back('0' + i);\n }\n return buf + buf.substr(0, n - 1);\n}\n\nbool allDigits(std::string s) {\n for (auto c : s) {\n if (c < '0' || '9' < c) {\n return false;\n }\n }\n return true;\n}\n\nvoid validate(std::string db) {\n auto le = db.size();\n std::vector found(10000, 0);\n std::vector errs;\n\n // Check all strings of 4 consecutive digits within 'db'\n // to see if all 10,000 combinations occur without duplication.\n for (size_t i = 0; i < le - 3; i++) {\n auto s = db.substr(i, 4);\n if (allDigits(s)) {\n auto n = stoi(s);\n found[n]++;\n }\n }\n\n for (int i = 0; i < 10000; i++) {\n if (found[i] == 0) {\n std::stringstream ss;\n ss << \" PIN number \" << i << \" missing\";\n errs.push_back(ss.str());\n } else if (found[i] > 1) {\n std::stringstream ss;\n ss << \" PIN number \" << i << \" occurs \" << found[i] << \" times\";\n errs.push_back(ss.str());\n }\n }\n\n if (errs.empty()) {\n std::cout << \" No errors found\\n\";\n } else {\n auto pl = (errs.size() == 1) ? \"\" : \"s\";\n std::cout << \" \" << errs.size() << \" error\" << pl << \" found:\\n\";\n for (auto e : errs) {\n std::cout << e << '\\n';\n }\n }\n}\n\nint main() {\n std::ostream_iterator oi(std::cout, \"\");\n auto db = deBruijn(10, 4);\n\n std::cout << \"The length of the de Bruijn sequence is \" << db.size() << \"\\n\\n\";\n std::cout << \"The first 130 digits of the de Bruijn sequence are: \";\n std::copy_n(db.cbegin(), 130, oi);\n std::cout << \"\\n\\nThe last 130 digits of the de Bruijn sequence are: \";\n std::copy(db.cbegin() + (db.size() - 130), db.cend(), oi);\n std::cout << \"\\n\";\n\n std::cout << \"\\nValidating the de Bruijn sequence:\\n\";\n validate(db);\n\n std::cout << \"\\nValidating the reversed de Bruijn sequence:\\n\";\n auto rdb = db;\n std::reverse(rdb.begin(), rdb.end());\n validate(rdb);\n\n auto by = db;\n by[4443] = '.';\n std::cout << \"\\nValidating the overlaid de Bruijn sequence:\\n\";\n validate(by);\n\n return 0;\n}"} -{"title": "De Bruijn sequences", "language": "Python", "task": "{{DISPLAYTITLE:de Bruijn sequences}}\nThe sequences are named after the Dutch mathematician Nicolaas Govert de Bruijn.\n\n\nA note on Dutch capitalization: Nicolaas' last name is '''de Bruijn''', the '''de''' isn't normally capitalized\nunless it's the first word in a sentence. 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, a '''de Bruijn sequence''' of order ''n'' on\na size-''k'' alphabet (computer science) ''A'' is a cyclic sequence in which every\npossible length-''n'' string (computer science, formal theory) on ''A'' occurs\nexactly once as a contiguous substring.\n\n\nSuch a sequence is denoted by ''B''(''k'', ''n'') and has\nlength ''k''''n'', which is also the number of distinct substrings of\nlength ''n'' on ''A''; \nde Bruijn sequences are therefore optimally short.\n\n\nThere are:\n (k!)k(n-1) / kn\ndistinct de Bruijn sequences ''B''(''k'', ''n''). \n\n\n;Task:\nFor this Rosetta Code task, a '''de Bruijn''' sequence is to be generated that can be used to shorten a brute-force attack on\na PIN-like code lock that does not have an \"enter\"\nkey and accepts the last ''n'' digits entered.\n\n\nNote: automated teller machines (ATMs) used to work like\nthis, but their software has been updated to not allow a brute-force attack.\n\n\n;Example:\nA digital door lock with a 4-digit code would\nhave ''B'' (10, 4) solutions, with a length of '''10,000''' (digits).\n\nTherefore, only at most '''10,000 + 3''' (as the solutions are cyclic or ''wrap-around'') presses are needed to\nopen the lock.\n\nTrying all 4-digit codes separately would require '''4 x 10,000''' or '''40,000''' presses.\n\n\n;Task requirements:\n:* Generate a de Bruijn sequence for a 4-digit (decimal) PIN code.\n:::* Show the length of the generated de Bruijn sequence.\n:::* (There are many possible de Bruijn sequences that solve this task, one solution is shown on the ''discussion'' page).\n:::* Show the first and last '''130''' digits of the de Bruijn sequence.\n:* Verify that all four-digit (decimal) '''1,000''' PIN codes are contained within the de Bruijn sequence.\n:::* 0000, 0001, 0002, 0003, ... 9996, 9997, 9998, 9999 (note the leading zeros).\n:* Reverse the de Bruijn sequence.\n:* Again, perform the (above) verification test.\n:* Replace the 4,444th digit with a period (.) in the original de Bruijn sequence.\n:::* Perform the verification test (again). There should be four PIN codes missing.\n\n\n(The last requirement is to ensure that the verification tests performs correctly. 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:* Wikipedia entry: de Bruijn sequence.\n:* MathWorld entry: de Bruijn sequence.\n:* An OEIS entry: A166315 lexicographically earliest binary de Bruijn sequences, B(2,n) --- Not B(10,4), but possibly relevant.\n\n", "solution": "# 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;* 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;* 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": "Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. \n\nThis is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects.\n\nIf this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure.\n\n\nThe task should show:\n\n* Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles.\n\n* Any limitations of the method.\n\n* That the structure and its copy are different.\n\n* Suitable links to external documentation for common libraries.\n\n", "solution": "#include\n#include\n\ntypedef struct elem{\n\tint data;\n\tstruct elem* next;\n}cell;\n\ntypedef cell* list;\n\nvoid addToList(list *a,int num){\n\tlist temp, holder;\n\t\n\tif(*a==NULL){\n\t\t*a = (list)malloc(sizeof(cell));\n\t\t(*a)->data = num;\n\t\t(*a)->next = NULL;\n\t}\n\telse{\n\t\ttemp = *a;\n\t\t\n\t\twhile(temp->next!=NULL)\n\t\t\ttemp = temp->next;\n\t\t\n\t\tholder = (list)malloc(sizeof(cell));\n\t\tholder->data = num;\n\t\tholder->next = NULL;\n\t\t\n\t\ttemp->next = holder;\n\t}\n}\n\nlist copyList(list a){\n\tlist b, tempA, tempB, temp;\n\t\n\tif(a!=NULL){\n\t\tb = (list)malloc(sizeof(cell));\n\t\tb->data = a->data;\n\t\tb->next = NULL;\n\t\t\n\t\ttempA = a->next;\n\t\ttempB = b;\n\t\t\n\t\twhile(tempA!=NULL){\n\t\t\ttemp = (list)malloc(sizeof(cell));\n\t\t\ttemp->data = tempA->data;\n\t\t\ttemp->next = NULL;\n\t\t\n\t\t\ttempB->next = temp;\n\t\t\ttempB = temp;\n\t\t\n\t\t\ttempA = tempA->next;\n\t\t}\n\t}\n\t\n\treturn b;\n}\n\nvoid printList(list a){\n\tlist temp = a;\n\t\n\twhile(temp!=NULL){\n\t\tprintf(\"%d,\",temp->data);\n\t\ttemp = temp->next;\n\t}\n\tprintf(\"\\b\");\n}\n\nint main()\n{\n\tlist a,b;\n\tint i;\n\t\n\tfor(i=1;i<=5;i++)\n\t\taddToList(&a,i);\n\t\n\tprintf(\"List a is : \");\n\t\n\tprintList(a);\n\t\n\tb = copyList(a);\n\t\n\tfree(a);\n\t\n\tprintf(\"\\nList a destroyed, List b is : \");\n\t\n\tprintList(b);\n\t\n\treturn 0;\n}\n"} -{"title": "Deepcopy", "language": "C++", "task": "Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. \n\nThis is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects.\n\nIf this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure.\n\n\nThe task should show:\n\n* Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles.\n\n* Any limitations of the method.\n\n* That the structure and its copy are different.\n\n* Suitable links to external documentation for common libraries.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nint main()\n{\n // make a nested structure to copy - a map of arrays containing vectors of strings\n auto myNumbers = std::vector{\"one\", \"two\", \"three\", \"four\"};\n auto myColors = std::vector{\"red\", \"green\", \"blue\"};\n auto myArray = std::array, 2>{myNumbers, myColors};\n auto myMap = std::map {{3, myArray}, {7, myArray}};\n\n // make a deep copy of the map\n auto mapCopy = myMap;\n\n // modify the copy\n mapCopy[3][0][1] = \"2\";\n mapCopy[7][1][2] = \"purple\";\n \n std::cout << \"the original values:\\n\";\n std::cout << myMap[3][0][1] << \"\\n\";\n std::cout << myMap[7][1][2] << \"\\n\\n\";\n\n std::cout << \"the modified copy:\\n\";\n std::cout << mapCopy[3][0][1] << \"\\n\";\n std::cout << mapCopy[7][1][2] << \"\\n\"; \n}"} -{"title": "Deepcopy", "language": "JavaScript", "task": "Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. \n\nThis is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects.\n\nIf this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure.\n\n\nThe task should show:\n\n* Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles.\n\n* Any limitations of the method.\n\n* That the structure and its copy are different.\n\n* Suitable links to external documentation for common libraries.\n\n", "solution": "var 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 from Racket", "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 explanation and interpretation\n* 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::* police department\n::* sanitation department\n::* fire department \n\n\nEach department can have a number between '''1''' and '''7''' (inclusive).\n\nThe three department numbers are to be unique (different from each other) and must add up to '''12'''.\n\nThe Chief of the Police doesn't like odd numbers and wants to have an even number for his department.\n\n\n;Task:\nWrite a computer program which outputs all valid combinations.\n\n\nPossible output (for the 1st and 14th solutions):\n \n --police-- --sanitation-- --fire-- \n 2 3 7 \n 6 5 1\n\n", "solution": "#include\n\nint main()\n{\n\tint police,sanitation,fire;\n\t\n\tprintf(\"Police Sanitation Fire\\n\");\n\tprintf(\"----------------------------------\");\n\t\n\tfor(police=2;police<=6;police+=2){\n\t\tfor(sanitation=1;sanitation<=7;sanitation++){\n\t\t\tfor(fire=1;fire<=7;fire++){\n\t\t\t\tif(police!=sanitation && sanitation!=fire && fire!=police && police+fire+sanitation==12){\n\t\t\t\t\tprintf(\"\\n%d\\t\\t%d\\t\\t%d\",police,sanitation,fire);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n"} -{"title": "Department numbers", "language": "C++", "task": "There is a highly organized city that has decided to assign a number to each of their departments:\n::* police department\n::* sanitation department\n::* fire department \n\n\nEach department can have a number between '''1''' and '''7''' (inclusive).\n\nThe three department numbers are to be unique (different from each other) and must add up to '''12'''.\n\nThe Chief of the Police doesn't like odd numbers and wants to have an even number for his department.\n\n\n;Task:\nWrite a computer program which outputs all valid combinations.\n\n\nPossible output (for the 1st and 14th solutions):\n \n --police-- --sanitation-- --fire-- \n 2 3 7 \n 6 5 1\n\n", "solution": "#include \n#include \n\nint main( int argc, char* argv[] ) {\n int sol = 1;\n std::cout << \"\\t\\tFIRE\\t\\tPOLICE\\t\\tSANITATION\\n\";\n for( int f = 1; f < 8; f++ ) {\n for( int p = 1; p < 8; p++ ) {\n for( int s = 1; s < 8; s++ ) {\n if( f != p && f != s && p != s && !( p & 1 ) && ( f + s + p == 12 ) ) {\n std::cout << \"SOLUTION #\" << std::setw( 2 ) << sol++ << std::setw( 2 ) \n << \":\\t\" << std::setw( 2 ) << f << \"\\t\\t \" << std::setw( 3 ) << p \n << \"\\t\\t\" << std::setw( 6 ) << s << \"\\n\";\n }\n }\n }\n }\n return 0;\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::* police department\n::* sanitation department\n::* fire department \n\n\nEach department can have a number between '''1''' and '''7''' (inclusive).\n\nThe three department numbers are to be unique (different from each other) and must add up to '''12'''.\n\nThe Chief of the Police doesn't like odd numbers and wants to have an even number for his department.\n\n\n;Task:\nWrite a computer program which outputs all valid combinations.\n\n\nPossible output (for the 1st and 14th solutions):\n \n --police-- --sanitation-- --fire-- \n 2 3 7 \n 6 5 1\n\n", "solution": "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": "Department numbers", "language": "Python 3", "task": "There is a highly organized city that has decided to assign a number to each of their departments:\n::* police department\n::* sanitation department\n::* fire department \n\n\nEach department can have a number between '''1''' and '''7''' (inclusive).\n\nThe three department numbers are to be unique (different from each other) and must add up to '''12'''.\n\nThe Chief of the Police doesn't like odd numbers and wants to have an even number for his department.\n\n\n;Task:\nWrite a computer program which outputs all valid combinations.\n\n\nPossible output (for the 1st and 14th solutions):\n \n --police-- --sanitation-- --fire-- \n 2 3 7 \n 6 5 1\n\n", "solution": "'''Department numbers'''\n\nfrom itertools import (chain)\nfrom operator import (ne)\n\n\n# options :: Int -> Int -> Int -> [(Int, Int, Int)]\ndef options(lo, hi, total):\n '''Eligible integer triples.'''\n ds = enumFromTo(lo)(hi)\n return bind(filter(even, ds))(\n lambda x: bind(filter(curry(ne)(x), ds))(\n lambda y: bind([total - (x + y)])(\n lambda z: [(x, y, z)] if (\n z != y and lo <= z <= hi\n ) else []\n )\n )\n )\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Test'''\n\n xs = options(1, 7, 12)\n print(('Police', 'Sanitation', 'Fire'))\n for tpl in xs:\n print(tpl)\n print('\\nNo. of options: ' + str(len(xs)))\n\n\n# GENERIC ABSTRACTIONS ------------------------------------\n\n# bind (>>=) :: [a] -> (a -> [b]) -> [b]\ndef bind(xs):\n '''List 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 return lambda f: list(\n chain.from_iterable(\n map(f, xs)\n )\n )\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# 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# even :: Int -> Bool\ndef even(x):\n '''True if x is an integer\n multiple of two.'''\n return 0 == x % 2\n\n\nif __name__ == '__main__':\n main()"} -{"title": "Department numbers", "language": "Python 3.7", "task": "There is a highly organized city that has decided to assign a number to each of their departments:\n::* police department\n::* sanitation department\n::* fire department \n\n\nEach department can have a number between '''1''' and '''7''' (inclusive).\n\nThe three department numbers are to be unique (different from each other) and must add up to '''12'''.\n\nThe Chief of the Police doesn't like odd numbers and wants to have an even number for his department.\n\n\n;Task:\nWrite a computer program which outputs all valid combinations.\n\n\nPossible output (for the 1st and 14th solutions):\n \n --police-- --sanitation-- --fire-- \n 2 3 7 \n 6 5 1\n\n", "solution": "'''Department numbers'''\n\nfrom operator import ne\n\n\n# options :: Int -> Int -> Int -> [(Int, Int, Int)]\ndef options(lo, hi, total):\n '''Eligible triples.'''\n ds = enumFromTo(lo)(hi)\n return [\n (x, y, z)\n for x in filter(even, ds)\n for y in filter(curry(ne)(x), ds)\n for z in [total - (x + y)]\n if y != z and lo <= z <= hi\n ]\n\n\n# Or with less tightly-constrained generation,\n# and more winnowing work downstream:\n\n# options2 :: Int -> Int -> Int -> [(Int, Int, Int)]\ndef options2(lo, hi, total):\n '''Eligible triples.'''\n ds = enumFromTo(lo)(hi)\n return [\n (x, y, z)\n for x in ds\n for y in ds\n for z in [total - (x + y)]\n if even(x) and y not in [x, z] and lo <= z <= hi\n ]\n\n\n# GENERIC -------------------------------------------------\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# 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# even :: Int -> Bool\ndef even(x):\n '''True if x is an integer\n multiple of two.'''\n return 0 == x % 2\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# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Test'''\n\n xs = options(1, 7, 12)\n print(('Police', 'Sanitation', 'Fire'))\n print(unlines(map(str, xs)))\n print('\\nNo. of options: ' + str(len(xs)))\n\n\nif __name__ == '__main__':\n main()"} -{"title": "Descending primes", "language": "C++ from 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\nbool 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 false; return true; }\n\nint main() {\n unsigned int c = 0, nc, pc = 9, i, a, b, l,\n ps[128]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, nxt[128];\n while (true) {\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": "Write a function to detect a ''divide by zero error'' without checking if the denominator is zero.\n\n", "solution": "#include \t/* INT_MIN */\n#include \t/* siglongjmp(), sigsetjmp() */\n#include \t/* perror(), printf() */\n#include \t/* exit() */\n#include \t/* sigaction(), sigemptyset() */\n\nstatic sigjmp_buf fpe_env;\n\n/*\n * This SIGFPE handler jumps to fpe_env.\n *\n * A SIGFPE handler must not return, because the program might retry\n * the division, which might cause an infinite loop. The only safe\n * options are to _exit() the program or to siglongjmp() out.\n */\nstatic void\nfpe_handler(int signal, siginfo_t *w, void *a)\n{\n\tsiglongjmp(fpe_env, w->si_code);\n\t/* NOTREACHED */\n}\n\n/*\n * Try to do x / y, but catch attempts to divide by zero.\n */\nvoid\ntry_division(int x, int y)\n{\n\tstruct sigaction act, old;\n\tint code;\n\t/*\n\t * The result must be volatile, else C compiler might delay\n\t * division until after sigaction() restores old handler.\n\t */\n\tvolatile int result;\n\n\t/*\n\t * Save fpe_env so that fpe_handler() can jump back here.\n\t * sigsetjmp() returns zero.\n\t */\n\tcode = sigsetjmp(fpe_env, 1);\n\tif (code == 0) {\n\t\t/* Install fpe_handler() to trap SIGFPE. */\n\t\tact.sa_sigaction = fpe_handler;\n\t\tsigemptyset(&act.sa_mask);\n\t\tact.sa_flags = SA_SIGINFO;\n\t\tif (sigaction(SIGFPE, &act, &old) < 0) {\n\t\t\tperror(\"sigaction\");\n\t\t\texit(1);\n\t\t}\n\n\t\t/* Do division. */\n\t\tresult = x / y;\n\n\t\t/*\n\t\t * Restore old hander, so that SIGFPE cannot jump out\n\t\t * of a call to printf(), which might cause trouble.\n\t\t */\n\t\tif (sigaction(SIGFPE, &old, NULL) < 0) {\n\t\t\tperror(\"sigaction\");\n\t\t\texit(1);\n\t\t}\n\n\t\tprintf(\"%d / %d is %d\\n\", x, y, result);\n\t} else {\n\t\t/*\n\t\t * We caught SIGFPE. Our fpe_handler() jumped to our\n\t\t * sigsetjmp() and passes a nonzero code.\n\t\t *\n\t\t * But first, restore old handler.\n\t\t */\n\t\tif (sigaction(SIGFPE, &old, NULL) < 0) {\n\t\t\tperror(\"sigaction\");\n\t\t\texit(1);\n\t\t}\n\n\t\t/* FPE_FLTDIV should never happen with integers. */\n\t\tswitch (code) {\n\t\tcase FPE_INTDIV: /* integer division by zero */\n\t\tcase FPE_FLTDIV: /* float division by zero */\n\t\t\tprintf(\"%d / %d: caught division by zero!\\n\", x, y);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tprintf(\"%d / %d: caught mysterious error!\\n\", x, y);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n/* Try some division. */\nint\nmain()\n{\n\ttry_division(-44, 0);\n\ttry_division(-44, 5);\n\ttry_division(0, 5);\n\ttry_division(0, 0);\n\ttry_division(INT_MIN, -1);\n\treturn 0;\n}"} -{"title": "Detect division by zero", "language": "C++", "task": "Write a function to detect a ''divide by zero error'' without checking if the denominator is zero.\n\n", "solution": "#include\n#include /* for signal */\n#include\n\nusing namespace std;\n\nvoid fpe_handler(int signal)\n{\n cerr << \"Floating Point Exception: division by zero\" << endl;\n exit(signal);\n}\n\nint main()\n{\n // Register floating-point exception handler.\n signal(SIGFPE, fpe_handler);\n\n int a = 1;\n int b = 0;\n cout << a/b << endl;\n\n return 0;\n}\n"} -{"title": "Detect division by zero", "language": "JavaScript", "task": "Write a function to detect a ''divide by zero error'' 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": "Write a function to detect a ''divide by zero error'' 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": "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": "C++ from Java", "task": "permanent of the matrix.\n\nThe determinant is given by\n:: \\det(A) = \\sum_\\sigma\\sgn(\\sigma)\\prod_{i=1}^n M_{i,\\sigma_i}\nwhile the permanent is given by\n:: \\operatorname{perm}(A)=\\sum_\\sigma\\prod_{i=1}^n M_{i,\\sigma_i}\nIn both cases the sum is over the permutations \\sigma of the permutations of 1, 2, ..., ''n''. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)\n\nMore efficient algorithms for the determinant are known: [[LU decomposition]], see for example [[wp:LU decomposition#Computing the determinant]]. Efficient methods for calculating the permanent are not known.\n\n\n;Related task:\n* [[Permutations by swapping]]\n\n", "solution": "#include \n#include \n\ntemplate \nstd::ostream &operator<<(std::ostream &os, const std::vector &v) {\n auto it = v.cbegin();\n auto end = v.cend();\n\n os << '[';\n if (it != end) {\n os << *it;\n it = std::next(it);\n }\n while (it != end) {\n os << \", \" << *it;\n it = std::next(it);\n }\n return os << ']';\n}\n\nusing Matrix = std::vector>;\n\nMatrix squareMatrix(size_t n) {\n Matrix m;\n for (size_t i = 0; i < n; i++) {\n std::vector inner;\n for (size_t j = 0; j < n; j++) {\n inner.push_back(nan(\"\"));\n }\n m.push_back(inner);\n }\n return m;\n}\n\nMatrix minor(const Matrix &a, int x, int y) {\n auto length = a.size() - 1;\n auto result = squareMatrix(length);\n for (int i = 0; i < length; i++) {\n for (int j = 0; j < length; j++) {\n if (i < x && j < y) {\n result[i][j] = a[i][j];\n } else if (i >= x && j < y) {\n result[i][j] = a[i + 1][j];\n } else if (i < x && j >= y) {\n result[i][j] = a[i][j + 1];\n } else {\n result[i][j] = a[i + 1][j + 1];\n }\n }\n }\n return result;\n}\n\ndouble det(const Matrix &a) {\n if (a.size() == 1) {\n return a[0][0];\n }\n\n int sign = 1;\n double sum = 0;\n for (size_t i = 0; i < a.size(); i++) {\n sum += sign * a[0][i] * det(minor(a, 0, i));\n sign *= -1;\n }\n return sum;\n}\n\ndouble perm(const Matrix &a) {\n if (a.size() == 1) {\n return a[0][0];\n }\n\n double sum = 0;\n for (size_t i = 0; i < a.size(); i++) {\n sum += a[0][i] * perm(minor(a, 0, i));\n }\n return sum;\n}\n\nvoid test(const Matrix &m) {\n auto p = perm(m);\n auto d = det(m);\n\n std::cout << m << '\\n';\n std::cout << \"Permanent: \" << p << \", determinant: \" << d << \"\\n\\n\";\n}\n\nint main() {\n test({ {1, 2}, {3, 4} });\n test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} });\n test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} });\n\n return 0;\n}"} -{"title": "Determinant and permanent", "language": "JavaScript", "task": "permanent of the matrix.\n\nThe determinant is given by\n:: \\det(A) = \\sum_\\sigma\\sgn(\\sigma)\\prod_{i=1}^n M_{i,\\sigma_i}\nwhile the permanent is given by\n:: \\operatorname{perm}(A)=\\sum_\\sigma\\prod_{i=1}^n M_{i,\\sigma_i}\nIn both cases the sum is over the permutations \\sigma of the permutations of 1, 2, ..., ''n''. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)\n\nMore efficient algorithms for the determinant are known: [[LU decomposition]], see for example [[wp:LU decomposition#Computing the determinant]]. Efficient methods for calculating the permanent are not known.\n\n\n;Related task:\n* [[Permutations by swapping]]\n\n", "solution": "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": "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": "Given a character string (which may be empty, or have a length of zero characters):\n::* create a function/procedure/routine to:\n::::* determine if all the characters in the string are the same\n::::* indicate if or which character is different from the previous character\n::* display each string and its length (as the strings are being examined)\n::* a zero-length (empty) string shall be considered as all the same character(s)\n::* process the strings from left-to-right\n::* if all the same character, display a message saying such\n::* if not all the same character, then:\n::::* display a message saying such\n::::* display what character is different\n::::* only the 1st different character need be displayed\n::::* display where the different character is in the string\n::::* the above messages can be part of a single message\n::::* display the hexadecimal value of the different character\n\n\nUse (at least) these seven test values (strings):\n:::* a string of length 0 (an empty string)\n:::* a string of length 3 which contains three blanks\n:::* a string of length 1 which contains: '''2'''\n:::* a string of length 3 which contains: '''333'''\n:::* a string of length 3 which contains: '''.55'''\n:::* a string of length 6 which contains: '''tttTTT'''\n:::* a string of length 9 with a blank in the middle: '''4444 444k'''\n\n\n\nShow all output here on this page.\n\n\n", "solution": "/**\n * An example for RossetaCode - an example of string operation with wchar_t and\n * with old 8-bit characters. Anyway, it seem that C is not very UTF-8 friendly,\n * thus C# or C++ may be a better choice.\n */\n\n#include \n#include \n#include \n\n/*\n * The wide character version of the program is compiled if WIDE_CHAR is defined\n */\n#define WIDE_CHAR\n\n#ifdef WIDE_CHAR\n#define CHAR wchar_t\n#else\n#define CHAR char\n#endif\n\n/**\n * Find a character different from the preceding characters in the given string.\n * \n * @param s the given string, NULL terminated.\n * \n * @return the pointer to the occurence of the different character \n * or a pointer to NULL if all characters in the string\n * are exactly the same.\n * \n * @notice This function return a pointer to NULL also for empty strings.\n * Returning NULL-or-CHAR would not enable to compute the position\n * of the non-matching character.\n * \n * @warning This function compare characters (single-bytes, unicode etc.).\n * Therefore this is not designed to compare bytes. The NULL character\n * is always treated as the end-of-string marker, thus this function\n * cannot be used to scan strings with NULL character inside string,\n * for an example \"aaa\\0aaa\\0\\0\".\n */\nconst CHAR* find_different_char(const CHAR* s)\n{\n /* The code just below is almost the same regardles \n char or wchar_t is used. */\n\n const CHAR c = *s;\n while (*s && c == *s)\n {\n s++;\n }\n return s;\n}\n\n/**\n * Apply find_different_char function to a given string and output the raport.\n * \n * @param s the given NULL terminated string.\n */\nvoid report_different_char(const CHAR* s)\n{\n#ifdef WIDE_CHAR\n wprintf(L\"\\n\");\n wprintf(L\"string: \\\"%s\\\"\\n\", s);\n wprintf(L\"length: %d\\n\", wcslen(s));\n const CHAR* d = find_different_char(s);\n if (d)\n {\n /*\n * We have got the famous pointers arithmetics and we can compute\n * difference of pointers pointing to the same array.\n */\n wprintf(L\"character '%wc' (%#x) at %d\\n\", *d, *d, (int)(d - s));\n }\n else\n {\n wprintf(L\"all characters are the same\\n\");\n }\n wprintf(L\"\\n\");\n#else\n putchar('\\n');\n printf(\"string: \\\"%s\\\"\\n\", s);\n printf(\"length: %d\\n\", strlen(s));\n const CHAR* d = find_different_char(s);\n if (d)\n { \n /*\n * We have got the famous pointers arithmetics and we can compute\n * difference of pointers pointing to the same array.\n */\n printf(\"character '%c' (%#x) at %d\\n\", *d, *d, (int)(d - s));\n }\n else\n {\n printf(\"all characters are the same\\n\");\n }\n putchar('\\n');\n#endif\n}\n\n/* There is a wmain function as an entry point when argv[] points to wchar_t */\n\n#ifdef WIDE_CHAR\nint wmain(int argc, wchar_t* argv[])\n#else\nint main(int argc, char* argv[])\n#endif\n{\n if (argc < 2)\n {\n report_different_char(L\"\");\n report_different_char(L\" \");\n report_different_char(L\"2\");\n report_different_char(L\"333\");\n report_different_char(L\".55\");\n report_different_char(L\"tttTTT\");\n report_different_char(L\"4444 444k\");\n }\n else\n {\n report_different_char(argv[1]);\n }\n\n return EXIT_SUCCESS;\n}"} -{"title": "Determine if a string has all the same characters", "language": "C++", "task": "Given a character string (which may be empty, or have a length of zero characters):\n::* create a function/procedure/routine to:\n::::* determine if all the characters in the string are the same\n::::* indicate if or which character is different from the previous character\n::* display each string and its length (as the strings are being examined)\n::* a zero-length (empty) string shall be considered as all the same character(s)\n::* process the strings from left-to-right\n::* if all the same character, display a message saying such\n::* if not all the same character, then:\n::::* display a message saying such\n::::* display what character is different\n::::* only the 1st different character need be displayed\n::::* display where the different character is in the string\n::::* the above messages can be part of a single message\n::::* display the hexadecimal value of the different character\n\n\nUse (at least) these seven test values (strings):\n:::* a string of length 0 (an empty string)\n:::* a string of length 3 which contains three blanks\n:::* a string of length 1 which contains: '''2'''\n:::* a string of length 3 which contains: '''333'''\n:::* a string of length 3 which contains: '''.55'''\n:::* a string of length 6 which contains: '''tttTTT'''\n:::* a string of length 9 with a blank in the middle: '''4444 444k'''\n\n\n\nShow all output here on this page.\n\n\n", "solution": "#include \n#include \n\nvoid all_characters_are_the_same(const std::string& str) {\n size_t len = str.length();\n std::cout << \"input: \\\"\" << str << \"\\\", length: \" << len << '\\n';\n if (len > 0) {\n char ch = str[0];\n for (size_t i = 1; i < len; ++i) {\n if (str[i] != ch) {\n std::cout << \"Not all characters are the same.\\n\";\n std::cout << \"Character '\" << str[i]\n << \"' (hex \" << std::hex << static_cast(str[i])\n << \") at position \" << std::dec << i + 1\n << \" is not the same as '\" << ch << \"'.\\n\\n\";\n return;\n }\n }\n }\n std::cout << \"All characters are the same.\\n\\n\";\n}\n\nint main() {\n all_characters_are_the_same(\"\");\n all_characters_are_the_same(\" \");\n all_characters_are_the_same(\"2\");\n all_characters_are_the_same(\"333\");\n all_characters_are_the_same(\".55\");\n all_characters_are_the_same(\"tttTTT\");\n all_characters_are_the_same(\"4444 444k\");\n return 0;\n}"} -{"title": "Determine if a string has all the same characters", "language": "JavaScript", "task": "Given a character string (which may be empty, or have a length of zero characters):\n::* create a function/procedure/routine to:\n::::* determine if all the characters in the string are the same\n::::* indicate if or which character is different from the previous character\n::* display each string and its length (as the strings are being examined)\n::* a zero-length (empty) string shall be considered as all the same character(s)\n::* process the strings from left-to-right\n::* if all the same character, display a message saying such\n::* if not all the same character, then:\n::::* display a message saying such\n::::* display what character is different\n::::* only the 1st different character need be displayed\n::::* display where the different character is in the string\n::::* the above messages can be part of a single message\n::::* display the hexadecimal value of the different character\n\n\nUse (at least) these seven test values (strings):\n:::* a string of length 0 (an empty string)\n:::* a string of length 3 which contains three blanks\n:::* a string of length 1 which contains: '''2'''\n:::* a string of length 3 which contains: '''333'''\n:::* a string of length 3 which contains: '''.55'''\n:::* a string of length 6 which contains: '''tttTTT'''\n:::* a string of length 9 with a blank in the middle: '''4444 444k'''\n\n\n\nShow all output here on this page.\n\n\n", "solution": "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": "Given a character string (which may be empty, or have a length of zero characters):\n::* create a function/procedure/routine to:\n::::* determine if all the characters in the string are the same\n::::* indicate if or which character is different from the previous character\n::* display each string and its length (as the strings are being examined)\n::* a zero-length (empty) string shall be considered as all the same character(s)\n::* process the strings from left-to-right\n::* if all the same character, display a message saying such\n::* if not all the same character, then:\n::::* display a message saying such\n::::* display what character is different\n::::* only the 1st different character need be displayed\n::::* display where the different character is in the string\n::::* the above messages can be part of a single message\n::::* display the hexadecimal value of the different character\n\n\nUse (at least) these seven test values (strings):\n:::* a string of length 0 (an empty string)\n:::* a string of length 3 which contains three blanks\n:::* a string of length 1 which contains: '''2'''\n:::* a string of length 3 which contains: '''333'''\n:::* a string of length 3 which contains: '''.55'''\n:::* a string of length 6 which contains: '''tttTTT'''\n:::* a string of length 9 with a blank in the middle: '''4444 444k'''\n\n\n\nShow all output here on this page.\n\n\n", "solution": "===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": "Given a character string (which may be empty, or have a length of zero characters):\n::* create a function/procedure/routine to:\n::::* determine if all the characters in the string are the same\n::::* indicate if or which character is different from the previous character\n::* display each string and its length (as the strings are being examined)\n::* a zero-length (empty) string shall be considered as all the same character(s)\n::* process the strings from left-to-right\n::* if all the same character, display a message saying such\n::* if not all the same character, then:\n::::* display a message saying such\n::::* display what character is different\n::::* only the 1st different character need be displayed\n::::* display where the different character is in the string\n::::* the above messages can be part of a single message\n::::* display the hexadecimal value of the different character\n\n\nUse (at least) these seven test values (strings):\n:::* a string of length 0 (an empty string)\n:::* a string of length 3 which contains three blanks\n:::* a string of length 1 which contains: '''2'''\n:::* a string of length 3 which contains: '''333'''\n:::* a string of length 3 which contains: '''.55'''\n:::* a string of length 6 which contains: '''tttTTT'''\n:::* a string of length 9 with a blank in the middle: '''4444 444k'''\n\n\n\nShow all output here on this page.\n\n\n", "solution": "'''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": "Given a character string (which may be empty, or have a length of zero characters):\n::* create a function/procedure/routine to:\n::::* determine if all the characters in the string are unique\n::::* indicate if or which character is duplicated and where\n::* display each string and its length (as the strings are being examined)\n::* a zero-length (empty) string shall be considered as unique\n::* process the strings from left-to-right\n::* if unique, display a message saying such\n::* if not unique, then:\n::::* display a message saying such\n::::* display what character is duplicated\n::::* only the 1st non-unique character need be displayed\n::::* display where \"both\" duplicated characters are in the string\n::::* the above messages can be part of a single message\n::::* display the hexadecimal value of the duplicated character\n\n\n\nUse (at least) these five test values (strings):\n:::* a string of length 0 (an empty string)\n:::* a string of length 1 which is a single period ('''.''')\n:::* a string of length 6 which contains: '''abcABC'''\n:::* a string of length 7 which contains a blank in the middle: '''XYZ ZYX'''\n:::* a string of length 36 which ''doesn't'' contain the letter \"oh\":\n:::::::: '''1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ'''\n\n\n\nShow all output here on this page.\n\n\n", "solution": "#include\n#include\n#include\n#include\n\ntypedef struct positionList{\n int position;\n struct positionList *next;\n}positionList;\n\ntypedef struct letterList{\n char letter;\n int repititions;\n positionList* positions;\n struct letterList *next;\n}letterList;\n\nletterList* letterSet;\nbool duplicatesFound = false;\n\nvoid checkAndUpdateLetterList(char c,int pos){\n bool letterOccurs = false;\n letterList *letterIterator,*newLetter;\n positionList *positionIterator,*newPosition;\n\n if(letterSet==NULL){\n letterSet = (letterList*)malloc(sizeof(letterList));\n letterSet->letter = c;\n letterSet->repititions = 0;\n\n letterSet->positions = (positionList*)malloc(sizeof(positionList));\n letterSet->positions->position = pos;\n letterSet->positions->next = NULL;\n\n letterSet->next = NULL;\n }\n\n else{\n letterIterator = letterSet;\n\n while(letterIterator!=NULL){\n if(letterIterator->letter==c){\n letterOccurs = true;\n duplicatesFound = true;\n\n letterIterator->repititions++;\n positionIterator = letterIterator->positions;\n\n while(positionIterator->next!=NULL)\n positionIterator = positionIterator->next;\n \n newPosition = (positionList*)malloc(sizeof(positionList));\n newPosition->position = pos;\n newPosition->next = NULL;\n\n positionIterator->next = newPosition;\n }\n if(letterOccurs==false && letterIterator->next==NULL)\n break;\n else\n letterIterator = letterIterator->next;\n }\n\n if(letterOccurs==false){\n newLetter = (letterList*)malloc(sizeof(letterList));\n newLetter->letter = c;\n\n newLetter->repititions = 0;\n\n newLetter->positions = (positionList*)malloc(sizeof(positionList));\n newLetter->positions->position = pos;\n newLetter->positions->next = NULL;\n\n newLetter->next = NULL;\n\n letterIterator->next = newLetter;\n } \n }\n}\n\nvoid printLetterList(){\n positionList* positionIterator;\n letterList* letterIterator = letterSet;\n\n while(letterIterator!=NULL){\n if(letterIterator->repititions>0){\n printf(\"\\n'%c' (0x%x) at positions :\",letterIterator->letter,letterIterator->letter);\n\n positionIterator = letterIterator->positions;\n\n while(positionIterator!=NULL){\n printf(\"%3d\",positionIterator->position + 1);\n positionIterator = positionIterator->next;\n }\n }\n\n letterIterator = letterIterator->next;\n }\n printf(\"\\n\");\n}\n\nint main(int argc,char** argv)\n{\n int i,len;\n \n if(argc>2){\n printf(\"Usage : %s \\n\",argv[0]);\n return 0;\n }\n\n if(argc==1||strlen(argv[1])==1){\n printf(\"\\\"%s\\\" - Length %d - Contains only unique characters.\\n\",argc==1?\"\":argv[1],argc==1?0:1);\n return 0;\n }\n\n len = strlen(argv[1]);\n\n for(i=0;i\n#include \n\nvoid string_has_repeated_character(const std::string& str) {\n size_t len = str.length();\n std::cout << \"input: \\\"\" << str << \"\\\", length: \" << len << '\\n';\n for (size_t i = 0; i < len; ++i) {\n for (size_t j = i + 1; j < len; ++j) {\n if (str[i] == str[j]) {\n std::cout << \"String contains a repeated character.\\n\";\n std::cout << \"Character '\" << str[i]\n << \"' (hex \" << std::hex << static_cast(str[i])\n << \") occurs at positions \" << std::dec << i + 1\n << \" and \" << j + 1 << \".\\n\\n\";\n return;\n }\n }\n }\n std::cout << \"String contains no repeated characters.\\n\\n\";\n}\n\nint main() {\n string_has_repeated_character(\"\");\n string_has_repeated_character(\".\");\n string_has_repeated_character(\"abcABC\");\n string_has_repeated_character(\"XYZ ZYX\");\n string_has_repeated_character(\"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\");\n return 0;\n}"} -{"title": "Determine if a string has all unique characters", "language": "JavaScript", "task": "Given a character string (which may be empty, or have a length of zero characters):\n::* create a function/procedure/routine to:\n::::* determine if all the characters in the string are unique\n::::* indicate if or which character is duplicated and where\n::* display each string and its length (as the strings are being examined)\n::* a zero-length (empty) string shall be considered as unique\n::* process the strings from left-to-right\n::* if unique, display a message saying such\n::* if not unique, then:\n::::* display a message saying such\n::::* display what character is duplicated\n::::* only the 1st non-unique character need be displayed\n::::* display where \"both\" duplicated characters are in the string\n::::* the above messages can be part of a single message\n::::* display the hexadecimal value of the duplicated character\n\n\n\nUse (at least) these five test values (strings):\n:::* a string of length 0 (an empty string)\n:::* a string of length 1 which is a single period ('''.''')\n:::* a string of length 6 which contains: '''abcABC'''\n:::* a string of length 7 which contains a blank in the middle: '''XYZ ZYX'''\n:::* a string of length 36 which ''doesn't'' contain the letter \"oh\":\n:::::::: '''1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ'''\n\n\n\nShow all output here on this page.\n\n\n", "solution": "(() => {\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": "Given a character string (which may be empty, or have a length of zero characters):\n::* create a function/procedure/routine to:\n::::* determine if all the characters in the string are unique\n::::* indicate if or which character is duplicated and where\n::* display each string and its length (as the strings are being examined)\n::* a zero-length (empty) string shall be considered as unique\n::* process the strings from left-to-right\n::* if unique, display a message saying such\n::* if not unique, then:\n::::* display a message saying such\n::::* display what character is duplicated\n::::* only the 1st non-unique character need be displayed\n::::* display where \"both\" duplicated characters are in the string\n::::* the above messages can be part of a single message\n::::* display the hexadecimal value of the duplicated character\n\n\n\nUse (at least) these five test values (strings):\n:::* a string of length 0 (an empty string)\n:::* a string of length 1 which is a single period ('''.''')\n:::* a string of length 6 which contains: '''abcABC'''\n:::* a string of length 7 which contains a blank in the middle: '''XYZ ZYX'''\n:::* a string of length 36 which ''doesn't'' contain the letter \"oh\":\n:::::::: '''1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ'''\n\n\n\nShow all output here on this page.\n\n\n", "solution": "'''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 ''collapsible''.\n\nAnd if so, collapse the string (by removing ''immediately repeated'' characters).\n\n\n\nIf a character string has ''immediately repeated'' character(s), the repeated characters are to be\ndeleted (removed), but not the primary (1st) character(s).\n\n\nAn ''immediately repeated'' character is any character that is immediately followed by an\nidentical character (or characters). Another word choice could've been ''duplicated character'', but that\nmight have ruled out (to some readers) triplicated characters *** or more.\n\n\n{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) '''PL/I''' BIF: '''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 '''t''', '''e''', and '''l''' are repeated characters, indicated\nby underscores (above), 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*** to\nlocate ''repeated'' characters and ''collapse'' (delete) them from the character\nstring. The character string can be processed from either direction.\n\n\nShow all output here, on this page:\n:* the original string and its length\n:* the resultant string and its length\n:* the above strings should be \"bracketed\" with '''<<<''' and '''>>>''' (to delineate blanks)\n;* <<<<<>>>>>\n\n\n\n\nUse (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except\nthe 1st string:\n\n string\n number\n ++\n 1 |+-----------------------------------------------------------------------+ <###### a null string (length zero)\n 2 |\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln |\n 3 |..1111111111111111111111111111111111111111111111111111111111111117777888|\n 4 |I never give 'em hell, I just tell the truth, and they think it's hell. |\n 5 | --- Harry S Truman | <###### has many repeated blanks\n +------------------------------------------------------------------------+\n\n\n", "solution": "#include\n#include\n#include\n\n#define COLLAPSE 0\n#define SQUEEZE 1\n\ntypedef struct charList{\n char c;\n struct charList *next;\n} charList;\n\n/*\nImplementing strcmpi, the case insensitive string comparator, as it is not part of the C Standard Library.\n\nComment this out if testing on a compiler where it is already defined.\n*/\n\nint strcmpi(char* str1,char* str2){\n int len1 = strlen(str1), len2 = strlen(str2), i;\n\n if(len1!=len2){\n return 1;\n }\n\n else{\n for(i=0;i='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i]))\n return 1;\n else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i]))\n return 1;\n else if(str1[i]!=str2[i])\n return 1;\n }\n }\n\n return 0;\n}\n\ncharList *strToCharList(char* str){\n int len = strlen(str),i;\n\n charList *list, *iterator, *nextChar;\n\n list = (charList*)malloc(sizeof(charList));\n list->c = str[0];\n list->next = NULL;\n\n iterator = list;\n\n for(i=1;ic = str[i];\n nextChar->next = NULL;\n\n iterator->next = nextChar;\n iterator = nextChar;\n }\n\n return list;\n}\n\nchar* charListToString(charList* list){\n charList* iterator = list;\n int count = 0,i;\n char* str;\n\n while(iterator!=NULL){\n count++;\n iterator = iterator->next;\n }\n\n str = (char*)malloc((count+1)*sizeof(char));\n iterator = list;\n\n for(i=0;ic;\n iterator = iterator->next;\n }\n\n free(list);\n str[i] = '\\0';\n\n return str;\n}\n\nchar* processString(char str[100],int operation, char squeezeChar){\n charList *strList = strToCharList(str),*iterator = strList, *scout;\n\n if(operation==SQUEEZE){\n while(iterator!=NULL){\n if(iterator->c==squeezeChar){\n scout = iterator->next;\n\n while(scout!=NULL && scout->c==squeezeChar){\n iterator->next = scout->next;\n scout->next = NULL;\n free(scout);\n scout = iterator->next;\n }\n }\n iterator = iterator->next;\n }\n }\n\n else{\n while(iterator!=NULL && iterator->next!=NULL){\n if(iterator->c == (iterator->next)->c){\n scout = iterator->next;\n squeezeChar = iterator->c;\n\n while(scout!=NULL && scout->c==squeezeChar){\n iterator->next = scout->next;\n scout->next = NULL;\n free(scout);\n scout = iterator->next;\n }\n }\n iterator = iterator->next;\n }\n }\n\n return charListToString(strList);\n}\n\nvoid printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){\n if(operation==SQUEEZE){\n printf(\"Specified Operation : SQUEEZE\\nTarget Character : %c\",squeezeChar);\n }\n\n else\n printf(\"Specified Operation : COLLAPSE\");\n\n printf(\"\\nOriginal %c%c%c%s%c%c%c\\nLength : %d\",174,174,174,originalString,175,175,175,(int)strlen(originalString));\n printf(\"\\nFinal %c%c%c%s%c%c%c\\nLength : %d\\n\",174,174,174,finalString,175,175,175,(int)strlen(finalString));\n}\n\nint main(int argc, char** argv){\n int operation;\n char squeezeChar;\n\n if(argc<3||argc>4){\n printf(\"Usage : %s \\n\",argv[0]);\n return 0;\n }\n\n if(strcmpi(argv[1],\"SQUEEZE\")==0 && argc!=4){\n scanf(\"Please enter characted to be squeezed : %c\",&squeezeChar);\n operation = SQUEEZE;\n }\n\n else if(argc==4){\n operation = SQUEEZE;\n squeezeChar = argv[3][0];\n }\n\n else if(strcmpi(argv[1],\"COLLAPSE\")==0){\n operation = COLLAPSE;\n }\n\n if(strlen(argv[2])<2){\n printResults(argv[2],argv[2],operation,squeezeChar);\n }\n\n else{\n printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar);\n }\n \n return 0;\n}\n"} -{"title": "Determine if a string is collapsible", "language": "C++", "task": "Determine if a character string is ''collapsible''.\n\nAnd if so, collapse the string (by removing ''immediately repeated'' characters).\n\n\n\nIf a character string has ''immediately repeated'' character(s), the repeated characters are to be\ndeleted (removed), but not the primary (1st) character(s).\n\n\nAn ''immediately repeated'' character is any character that is immediately followed by an\nidentical character (or characters). Another word choice could've been ''duplicated character'', but that\nmight have ruled out (to some readers) triplicated characters *** or more.\n\n\n{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) '''PL/I''' BIF: '''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 '''t''', '''e''', and '''l''' are repeated characters, indicated\nby underscores (above), 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*** to\nlocate ''repeated'' characters and ''collapse'' (delete) them from the character\nstring. The character string can be processed from either direction.\n\n\nShow all output here, on this page:\n:* the original string and its length\n:* the resultant string and its length\n:* the above strings should be \"bracketed\" with '''<<<''' and '''>>>''' (to delineate blanks)\n;* <<<<<>>>>>\n\n\n\n\nUse (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except\nthe 1st string:\n\n string\n number\n ++\n 1 |+-----------------------------------------------------------------------+ <###### a null string (length zero)\n 2 |\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln |\n 3 |..1111111111111111111111111111111111111111111111111111111111111117777888|\n 4 |I never give 'em hell, I just tell the truth, and they think it's hell. |\n 5 | --- Harry S Truman | <###### has many repeated blanks\n +------------------------------------------------------------------------+\n\n\n", "solution": "#include \n#include \n#include \n\ntemplate\nstd::basic_string collapse(std::basic_string str) {\n auto i = std::unique(str.begin(), str.end());\n str.erase(i, str.end());\n return str;\n}\n\nvoid test(const std::string& str) {\n std::cout << \"original string: <<<\" << str << \">>>, length = \" << str.length() << '\\n';\n std::string collapsed(collapse(str));\n std::cout << \"result string: <<<\" << collapsed << \">>>, length = \" << collapsed.length() << '\\n';\n std::cout << '\\n';\n}\n\nint main(int argc, char** argv) {\n test(\"\");\n test(\"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \");\n test(\"..1111111111111111111111111111111111111111111111111111111111111117777888\");\n test(\"I never give 'em hell, I just tell the truth, and they think it's hell. \");\n test(\" --- Harry S Truman \");\n return 0;\n}"} -{"title": "Determine if a string is collapsible", "language": "JavaScript", "task": "Determine if a character string is ''collapsible''.\n\nAnd if so, collapse the string (by removing ''immediately repeated'' characters).\n\n\n\nIf a character string has ''immediately repeated'' character(s), the repeated characters are to be\ndeleted (removed), but not the primary (1st) character(s).\n\n\nAn ''immediately repeated'' character is any character that is immediately followed by an\nidentical character (or characters). Another word choice could've been ''duplicated character'', but that\nmight have ruled out (to some readers) triplicated characters *** or more.\n\n\n{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) '''PL/I''' BIF: '''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 '''t''', '''e''', and '''l''' are repeated characters, indicated\nby underscores (above), 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*** to\nlocate ''repeated'' characters and ''collapse'' (delete) them from the character\nstring. The character string can be processed from either direction.\n\n\nShow all output here, on this page:\n:* the original string and its length\n:* the resultant string and its length\n:* the above strings should be \"bracketed\" with '''<<<''' and '''>>>''' (to delineate blanks)\n;* <<<<<>>>>>\n\n\n\n\nUse (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except\nthe 1st string:\n\n string\n number\n ++\n 1 |+-----------------------------------------------------------------------+ <###### a null string (length zero)\n 2 |\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln |\n 3 |..1111111111111111111111111111111111111111111111111111111111111117777888|\n 4 |I never give 'em hell, I just tell the truth, and they think it's hell. |\n 5 | --- Harry S Truman | <###### has many repeated blanks\n +------------------------------------------------------------------------+\n\n\n", "solution": "String.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 ''collapsible''.\n\nAnd if so, collapse the string (by removing ''immediately repeated'' characters).\n\n\n\nIf a character string has ''immediately repeated'' character(s), the repeated characters are to be\ndeleted (removed), but not the primary (1st) character(s).\n\n\nAn ''immediately repeated'' character is any character that is immediately followed by an\nidentical character (or characters). Another word choice could've been ''duplicated character'', but that\nmight have ruled out (to some readers) triplicated characters *** or more.\n\n\n{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) '''PL/I''' BIF: '''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 '''t''', '''e''', and '''l''' are repeated characters, indicated\nby underscores (above), 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*** to\nlocate ''repeated'' characters and ''collapse'' (delete) them from the character\nstring. The character string can be processed from either direction.\n\n\nShow all output here, on this page:\n:* the original string and its length\n:* the resultant string and its length\n:* the above strings should be \"bracketed\" with '''<<<''' and '''>>>''' (to delineate blanks)\n;* <<<<<>>>>>\n\n\n\n\nUse (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except\nthe 1st string:\n\n string\n number\n ++\n 1 |+-----------------------------------------------------------------------+ <###### a null string (length zero)\n 2 |\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln |\n 3 |..1111111111111111111111111111111111111111111111111111111111111117777888|\n 4 |I never give 'em hell, I just tell the truth, and they think it's hell. |\n 5 | --- Harry S Truman | <###### has many repeated blanks\n +------------------------------------------------------------------------+\n\n\n", "solution": "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 ''squeezable''.\n\nAnd if so, squeeze the string (by removing any number of\na ''specified'' ''immediately repeated'' character).\n\n\nThis task is very similar to the task '''Determine if a character string is collapsible''' except\nthat only a specified character is ''squeezed'' instead of any character that is ''immediately repeated''.\n\n\nIf a character string has a specified ''immediately repeated'' character(s), the repeated characters are to be\ndeleted (removed), but not the primary (1st) character(s).\n\n\nA specified ''immediately repeated'' character is any specified character that is immediately \nfollowed by an identical character (or characters). Another word choice could've been ''duplicated\ncharacter'', but that might have ruled out (to some readers) triplicated characters *** or more.\n\n\n{This Rosetta Code task was inspired by a newly introduced (as of around\nNovember 2019) '''PL/I''' BIF: '''squeeze'''.}\n\n\n;Examples:\nIn the following character string with a specified ''immediately repeated'' character of '''e''':\n\n\n The better the 4-wheel drive, the further you'll be from help when ya get stuck! \n\n\nOnly the 2nd '''e''' is an specified repeated character, indicated by an underscore\n(above), even though they (the characters) appear elsewhere in the character string.\n\n\n\nSo, after ''squeezing'' the string, the result would be:\n\n The better the 4-whel drive, the further you'll be from help when ya get stuck! \n\n\n\n\nAnother example:\nIn the following character string, using a specified immediately repeated character '''s''':\n\n headmistressship \n\n\nThe \"squeezed\" string would be:\n\n headmistreship \n\n\n\n;Task:\nWrite a subroutine/function/procedure/routine*** to locate a ''specified immediately repeated'' character\nand ''squeeze'' (delete) them from the character string. The\ncharacter string can be processed from either direction.\n\n\nShow all output here, on this page:\n:* the specified repeated character (to be searched for and possibly ''squeezed''):\n:* the original string and its length\n:* the resultant string and its length\n:* the above strings should be \"bracketed\" with '''<<<''' and '''>>>''' (to delineate blanks)\n;* <<<<<>>>>>\n\n\n\nUse (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except\nthe 1st string:\n\n immediately\n string repeated\n number character\n ( | a blank, a minus, a seven, a period)\n ++\n 1 |+-----------------------------------------------------------------------+ ' ' <###### a null string (length zero)\n 2 |\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln | '-'\n 3 |..1111111111111111111111111111111111111111111111111111111111111117777888| '7'\n 4 |I never give 'em hell, I just tell the truth, and they think it's hell. | '.'\n 5 | --- Harry S Truman | (below) <###### has many repeated blanks\n +------------------------------------------------------------------------+ |\n |\n |\n For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:\n * a blank\n * a minus\n * a lowercase '''r'''\n\n\nNote: there should be seven results shown, one each for the 1st four strings, and three results for\nthe 5th string.\n\n\n", "solution": "#include\n#include\n#include\n\n#define COLLAPSE 0\n#define SQUEEZE 1\n\ntypedef struct charList{\n char c;\n struct charList *next;\n} charList;\n\n/*\nImplementing strcmpi, the case insensitive string comparator, as it is not part of the C Standard Library.\n\nComment this out if testing on a compiler where it is already defined.\n*/\n\nint strcmpi(char str1[100],char str2[100]){\n int len1 = strlen(str1), len2 = strlen(str2), i;\n\n if(len1!=len2){\n return 1;\n }\n\n else{\n for(i=0;i='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i]))\n return 1;\n else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i]))\n return 1;\n else if(str1[i]!=str2[i])\n return 1;\n }\n }\n\n return 0;\n}\n\ncharList *strToCharList(char* str){\n int len = strlen(str),i;\n\n charList *list, *iterator, *nextChar;\n\n list = (charList*)malloc(sizeof(charList));\n list->c = str[0];\n list->next = NULL;\n\n iterator = list;\n\n for(i=1;ic = str[i];\n nextChar->next = NULL;\n\n iterator->next = nextChar;\n iterator = nextChar;\n }\n\n return list;\n}\n\nchar* charListToString(charList* list){\n charList* iterator = list;\n int count = 0,i;\n char* str;\n\n while(iterator!=NULL){\n count++;\n iterator = iterator->next;\n }\n\n str = (char*)malloc((count+1)*sizeof(char));\n iterator = list;\n\n for(i=0;ic;\n iterator = iterator->next;\n }\n\n free(list);\n str[i] = '\\0';\n\n return str;\n}\n\nchar* processString(char str[100],int operation, char squeezeChar){\n charList *strList = strToCharList(str),*iterator = strList, *scout;\n\n if(operation==SQUEEZE){\n while(iterator!=NULL){\n if(iterator->c==squeezeChar){\n scout = iterator->next;\n\n while(scout!=NULL && scout->c==squeezeChar){\n iterator->next = scout->next;\n scout->next = NULL;\n free(scout);\n scout = iterator->next;\n }\n }\n iterator = iterator->next;\n }\n }\n\n else{\n while(iterator!=NULL && iterator->next!=NULL){\n if(iterator->c == (iterator->next)->c){\n scout = iterator->next;\n squeezeChar = iterator->c;\n\n while(scout!=NULL && scout->c==squeezeChar){\n iterator->next = scout->next;\n scout->next = NULL;\n free(scout);\n scout = iterator->next;\n }\n }\n iterator = iterator->next;\n }\n }\n\n return charListToString(strList);\n}\n\nvoid printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){\n if(operation==SQUEEZE){\n printf(\"Specified Operation : SQUEEZE\\nTarget Character : %c\",squeezeChar);\n }\n\n else\n printf(\"Specified Operation : COLLAPSE\");\n\n printf(\"\\nOriginal %c%c%c%s%c%c%c\\nLength : %d\",174,174,174,originalString,175,175,175,(int)strlen(originalString));\n printf(\"\\nFinal %c%c%c%s%c%c%c\\nLength : %d\\n\",174,174,174,finalString,175,175,175,(int)strlen(finalString));\n}\n\nint main(int argc, char** argv){\n int operation;\n char squeezeChar;\n\n if(argc<3||argc>4){\n printf(\"Usage : %s \\n\",argv[0]);\n return 0;\n }\n\n if(strcmpi(argv[1],\"SQUEEZE\")==0 && argc!=4){\n scanf(\"Please enter characted to be squeezed : %c\",&squeezeChar);\n operation = SQUEEZE;\n }\n\n else if(argc==4){\n operation = SQUEEZE;\n squeezeChar = argv[3][0];\n }\n\n else if(strcmpi(argv[1],\"COLLAPSE\")==0){\n operation = COLLAPSE;\n }\n\n if(strlen(argv[2])<2){\n printResults(argv[2],argv[2],operation,squeezeChar);\n }\n\n else{\n printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar);\n }\n \n return 0;\n}\n"} -{"title": "Determine if a string is squeezable", "language": "C++", "task": "Determine if a character string is ''squeezable''.\n\nAnd if so, squeeze the string (by removing any number of\na ''specified'' ''immediately repeated'' character).\n\n\nThis task is very similar to the task '''Determine if a character string is collapsible''' except\nthat only a specified character is ''squeezed'' instead of any character that is ''immediately repeated''.\n\n\nIf a character string has a specified ''immediately repeated'' character(s), the repeated characters are to be\ndeleted (removed), but not the primary (1st) character(s).\n\n\nA specified ''immediately repeated'' character is any specified character that is immediately \nfollowed by an identical character (or characters). Another word choice could've been ''duplicated\ncharacter'', but that might have ruled out (to some readers) triplicated characters *** or more.\n\n\n{This Rosetta Code task was inspired by a newly introduced (as of around\nNovember 2019) '''PL/I''' BIF: '''squeeze'''.}\n\n\n;Examples:\nIn the following character string with a specified ''immediately repeated'' character of '''e''':\n\n\n The better the 4-wheel drive, the further you'll be from help when ya get stuck! \n\n\nOnly the 2nd '''e''' is an specified repeated character, indicated by an underscore\n(above), even though they (the characters) appear elsewhere in the character string.\n\n\n\nSo, after ''squeezing'' the string, the result would be:\n\n The better the 4-whel drive, the further you'll be from help when ya get stuck! \n\n\n\n\nAnother example:\nIn the following character string, using a specified immediately repeated character '''s''':\n\n headmistressship \n\n\nThe \"squeezed\" string would be:\n\n headmistreship \n\n\n\n;Task:\nWrite a subroutine/function/procedure/routine*** to locate a ''specified immediately repeated'' character\nand ''squeeze'' (delete) them from the character string. The\ncharacter string can be processed from either direction.\n\n\nShow all output here, on this page:\n:* the specified repeated character (to be searched for and possibly ''squeezed''):\n:* the original string and its length\n:* the resultant string and its length\n:* the above strings should be \"bracketed\" with '''<<<''' and '''>>>''' (to delineate blanks)\n;* <<<<<>>>>>\n\n\n\nUse (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except\nthe 1st string:\n\n immediately\n string repeated\n number character\n ( | a blank, a minus, a seven, a period)\n ++\n 1 |+-----------------------------------------------------------------------+ ' ' <###### a null string (length zero)\n 2 |\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln | '-'\n 3 |..1111111111111111111111111111111111111111111111111111111111111117777888| '7'\n 4 |I never give 'em hell, I just tell the truth, and they think it's hell. | '.'\n 5 | --- Harry S Truman | (below) <###### has many repeated blanks\n +------------------------------------------------------------------------+ |\n |\n |\n For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:\n * a blank\n * a minus\n * a lowercase '''r'''\n\n\nNote: there should be seven results shown, one each for the 1st four strings, and three results for\nthe 5th string.\n\n\n", "solution": "#include \n#include \n#include \n\ntemplate\nstd::basic_string squeeze(std::basic_string str, char_type ch) {\n auto i = std::unique(str.begin(), str.end(),\n [ch](char_type a, char_type b) { return a == ch && b == ch; });\n str.erase(i, str.end());\n return str;\n}\n\nvoid test(const std::string& str, char ch) {\n std::cout << \"character: '\" << ch << \"'\\n\";\n std::cout << \"original: <<<\" << str << \">>>, length: \" << str.length() << '\\n';\n std::string squeezed(squeeze(str, ch));\n std::cout << \"result: <<<\" << squeezed << \">>>, length: \" << squeezed.length() << '\\n';\n std::cout << '\\n';\n}\n\nint main(int argc, char** argv) {\n test(\"\", ' ');\n test(\"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \", '-');\n test(\"..1111111111111111111111111111111111111111111111111111111111111117777888\", '7');\n test(\"I never give 'em hell, I just tell the truth, and they think it's hell. \", '.');\n std::string truman(\" --- Harry S Truman \");\n test(truman, ' ');\n test(truman, '-');\n test(truman, 'r');\n return 0;\n}"} -{"title": "Determine if a string is squeezable", "language": "Python", "task": "Determine if a character string is ''squeezable''.\n\nAnd if so, squeeze the string (by removing any number of\na ''specified'' ''immediately repeated'' character).\n\n\nThis task is very similar to the task '''Determine if a character string is collapsible''' except\nthat only a specified character is ''squeezed'' instead of any character that is ''immediately repeated''.\n\n\nIf a character string has a specified ''immediately repeated'' character(s), the repeated characters are to be\ndeleted (removed), but not the primary (1st) character(s).\n\n\nA specified ''immediately repeated'' character is any specified character that is immediately \nfollowed by an identical character (or characters). Another word choice could've been ''duplicated\ncharacter'', but that might have ruled out (to some readers) triplicated characters *** or more.\n\n\n{This Rosetta Code task was inspired by a newly introduced (as of around\nNovember 2019) '''PL/I''' BIF: '''squeeze'''.}\n\n\n;Examples:\nIn the following character string with a specified ''immediately repeated'' character of '''e''':\n\n\n The better the 4-wheel drive, the further you'll be from help when ya get stuck! \n\n\nOnly the 2nd '''e''' is an specified repeated character, indicated by an underscore\n(above), even though they (the characters) appear elsewhere in the character string.\n\n\n\nSo, after ''squeezing'' the string, the result would be:\n\n The better the 4-whel drive, the further you'll be from help when ya get stuck! \n\n\n\n\nAnother example:\nIn the following character string, using a specified immediately repeated character '''s''':\n\n headmistressship \n\n\nThe \"squeezed\" string would be:\n\n headmistreship \n\n\n\n;Task:\nWrite a subroutine/function/procedure/routine*** to locate a ''specified immediately repeated'' character\nand ''squeeze'' (delete) them from the character string. The\ncharacter string can be processed from either direction.\n\n\nShow all output here, on this page:\n:* the specified repeated character (to be searched for and possibly ''squeezed''):\n:* the original string and its length\n:* the resultant string and its length\n:* the above strings should be \"bracketed\" with '''<<<''' and '''>>>''' (to delineate blanks)\n;* <<<<<>>>>>\n\n\n\nUse (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except\nthe 1st string:\n\n immediately\n string repeated\n number character\n ( | a blank, a minus, a seven, a period)\n ++\n 1 |+-----------------------------------------------------------------------+ ' ' <###### a null string (length zero)\n 2 |\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln | '-'\n 3 |..1111111111111111111111111111111111111111111111111111111111111117777888| '7'\n 4 |I never give 'em hell, I just tell the truth, and they think it's hell. | '.'\n 5 | --- Harry S Truman | (below) <###### has many repeated blanks\n +------------------------------------------------------------------------+ |\n |\n |\n For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:\n * a blank\n * a minus\n * a lowercase '''r'''\n\n\nNote: there should be seven results shown, one each for the 1st four strings, and three results for\nthe 5th string.\n\n\n", "solution": "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:::* (0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)\n:::* (0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)\n:::* (0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)\n:::* (0,0),(5,0),(2.5,5) and (0,4),(2.5,-1),(5,4)\n:::* (0,0),(1,1),(0,2) and (2,1),(3,0),(3,2)\n:::* (0,0),(1,1),(0,2) and (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:::* (0,0),(1,0),(0,1) and (1,0),(2,0),(1,1)\n\n", "solution": "#include \n#include \n#include \nusing namespace std;\n\ntypedef std::pair TriPoint;\n\ninline double Det2D(TriPoint &p1, TriPoint &p2, TriPoint &p3) \n{\n\treturn +p1.first*(p2.second-p3.second)\n\t\t+p2.first*(p3.second-p1.second)\n\t\t+p3.first*(p1.second-p2.second);\n}\n\nvoid CheckTriWinding(TriPoint &p1, TriPoint &p2, TriPoint &p3, bool allowReversed)\n{\n\tdouble detTri = Det2D(p1, p2, p3);\n\tif(detTri < 0.0)\n\t{\n\t\tif (allowReversed)\n\t\t{\n\t\t\tTriPoint a = p3;\n\t\t\tp3 = p2;\n\t\t\tp2 = a;\n\t\t}\n\t\telse throw std::runtime_error(\"triangle has wrong winding direction\");\n\t}\n}\n\nbool BoundaryCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps)\n{\n\treturn Det2D(p1, p2, p3) < eps;\n}\n\nbool BoundaryDoesntCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps)\n{\n\treturn Det2D(p1, p2, p3) <= eps;\n}\n\nbool TriTri2D(TriPoint *t1,\n\tTriPoint *t2,\n\tdouble eps = 0.0, bool allowReversed = false, bool onBoundary = true)\n{\n\t//Trangles must be expressed anti-clockwise\n\tCheckTriWinding(t1[0], t1[1], t1[2], allowReversed);\n\tCheckTriWinding(t2[0], t2[1], t2[2], allowReversed);\n\n\tbool (*chkEdge)(TriPoint &, TriPoint &, TriPoint &, double) = NULL;\n\tif(onBoundary) //Points on the boundary are considered as colliding\n\t\tchkEdge = BoundaryCollideChk;\n\telse //Points on the boundary are not considered as colliding\n\t\tchkEdge = BoundaryDoesntCollideChk;\n\n\t//For edge E of trangle 1,\n\tfor(int i=0; i<3; i++)\n\t{\n\t\tint j=(i+1)%3;\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(t1[i], t1[j], t2[0], eps) &&\n\t\t\tchkEdge(t1[i], t1[j], t2[1], eps) &&\n\t\t\tchkEdge(t1[i], t1[j], t2[2], eps))\n\t\t\treturn false;\n\t}\n\n\t//For edge E of trangle 2,\n\tfor(int i=0; i<3; i++)\n\t{\n\t\tint j=(i+1)%3;\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(t2[i], t2[j], t1[0], eps) &&\n\t\t\tchkEdge(t2[i], t2[j], t1[1], eps) &&\n\t\t\tchkEdge(t2[i], t2[j], t1[2], eps))\n\t\t\treturn false;\n\t}\n\n\t//The triangles collide\n\treturn true;\n}\n\nint main()\n{\n\t{TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)};\n\tTriPoint t2[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,6)};\n\tcout << TriTri2D(t1, t2) << \",\" << true << endl;}\n\n\t{TriPoint t1[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)};\n\tTriPoint t2[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)};\n\tcout << TriTri2D(t1, t2, 0.0, true) << \",\" << true << endl;}\n\n\t{TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)};\n\tTriPoint t2[] = {TriPoint(-10,0),TriPoint(-5,0),TriPoint(-1,6)};\n\tcout << TriTri2D(t1, t2) << \",\" << false << endl;}\n\n\t{TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(2.5,5)};\n\tTriPoint t2[] = {TriPoint(0,4),TriPoint(2.5,-1),TriPoint(5,4)};\n\tcout << TriTri2D(t1, t2) << \",\" << true << endl;}\n\n\t{TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)};\n\tTriPoint t2[] = {TriPoint(2,1),TriPoint(3,0),TriPoint(3,2)};\n\tcout << TriTri2D(t1, t2) << \",\" << false << endl;}\n\n\t{TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)};\n\tTriPoint t2[] = {TriPoint(2,1),TriPoint(3,-2),TriPoint(3,4)};\n\tcout << TriTri2D(t1, t2) << \",\" << false << endl;}\n\n\t//Barely touching\n\t{TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)};\n\tTriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)};\n\tcout << TriTri2D(t1, t2, 0.0, false, true) << \",\" << true << endl;}\n\n\t//Barely touching\n\t{TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)};\n\tTriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)};\n\tcout << TriTri2D(t1, t2, 0.0, false, false) << \",\" << false << endl;}\n\n}"} -{"title": "Dice game probabilities", "language": "C", "task": "Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.\n\nThey roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?\n\nLater the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?\n\nThis task was adapted from the Project Euler Problem n.205:\nhttps://projecteuler.net/problem=205\n\n", "solution": "#include \n#include \n\ntypedef uint32_t uint;\ntypedef uint64_t ulong;\n\nulong ipow(const uint x, const uint y) {\n ulong result = 1;\n for (uint i = 1; i <= y; i++)\n result *= x;\n return result;\n}\n\nuint min(const uint x, const uint y) {\n return (x < y) ? x : y;\n}\n\nvoid throw_die(const uint n_sides, const uint n_dice, const uint s, uint counts[]) {\n if (n_dice == 0) {\n counts[s]++;\n return;\n }\n\n for (uint i = 1; i < n_sides + 1; i++)\n throw_die(n_sides, n_dice - 1, s + i, counts);\n}\n\ndouble beating_probability(const uint n_sides1, const uint n_dice1,\n const uint n_sides2, const uint n_dice2) {\n const uint len1 = (n_sides1 + 1) * n_dice1;\n uint C1[len1];\n for (uint i = 0; i < len1; i++)\n C1[i] = 0;\n throw_die(n_sides1, n_dice1, 0, C1);\n\n const uint len2 = (n_sides2 + 1) * n_dice2;\n uint C2[len2];\n for (uint j = 0; j < len2; j++)\n C2[j] = 0;\n throw_die(n_sides2, n_dice2, 0, C2);\n\n const double p12 = (double)(ipow(n_sides1, n_dice1) * ipow(n_sides2, n_dice2));\n\n double tot = 0;\n for (uint i = 0; i < len1; i++)\n for (uint j = 0; j < min(i, len2); j++)\n tot += (double)C1[i] * C2[j] / p12;\n return tot;\n}\n\nint main() {\n printf(\"%1.16f\\n\", beating_probability(4, 9, 6, 6));\n printf(\"%1.16f\\n\", beating_probability(10, 5, 7, 6));\n return 0;\n}"} -{"title": "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#include \n#include \n#include \n\n// Returns map from sum of faces to number of ways it can happen\nstd::map get_totals(uint32_t dice, uint32_t faces) {\n std::map result;\n for (uint32_t i = 1; i <= faces; ++i)\n result.emplace(i, 1);\n for (uint32_t d = 2; d <= dice; ++d) {\n std::map tmp;\n for (const auto& p : result) {\n for (uint32_t i = 1; i <= faces; ++i)\n tmp[p.first + i] += p.second;\n }\n tmp.swap(result);\n }\n return result;\n}\n\ndouble probability(uint32_t dice1, uint32_t faces1, uint32_t dice2, uint32_t faces2) {\n auto totals1 = get_totals(dice1, faces1);\n auto totals2 = get_totals(dice2, faces2);\n double wins = 0;\n for (const auto& p1 : totals1) {\n for (const auto& p2 : totals2) {\n if (p2.first >= p1.first)\n break;\n wins += p1.second * p2.second;\n }\n }\n double total = std::pow(faces1, dice1) * std::pow(faces2, dice2);\n return wins/total;\n}\n\nint main() {\n std::cout << std::setprecision(10);\n std::cout << probability(9, 4, 6, 6) << '\\n';\n std::cout << probability(5, 10, 6, 7) << '\\n';\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": "let 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

\n Player 1 (${player1.dice} \u00d7 d${player1.faces}): ${res[0]} wins
\n Player 2 (${player2.dice} \u00d7 d${player2.faces}): ${res[1]} wins
\n Draws: ${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": "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": "// Calculate the Digital Root and Additive Persistance of an Integer - Compiles with gcc4.7\n//\n// Nigel Galloway. July 23rd., 2012\n//\n#include \n#include \n#include \n\ntemplate P_ IncFirst(const P_& src) {return P_(src.first + 1, src.second);}\n\nstd::pair DigitalRoot(unsigned long long digits, int base = 10) \n{\n int x = SumDigits(digits, base);\n return x < base ? std::make_pair(1, x) : IncFirst(DigitalRoot(x, base)); // x is implicitly converted to unsigned long long; this is lossless\n}\n\nint main() {\n const unsigned long long ip[] = {961038,923594037444,670033,448944221089};\n for (auto i:ip){\n auto res = DigitalRoot(i);\n std::cout << i << \" has digital root \" << res.second << \" and additive persistance \" << res.first << \"\\n\";\n }\n std::cout << \"\\n\";\n const unsigned long long hip[] = {0x7e0,0x14e344,0xd60141,0x12343210};\n for (auto i:hip){\n auto res = DigitalRoot(i,16);\n std::cout << std::hex << i << \" has digital root \" << res.second << \" and additive persistance \" << res.first << \"\\n\";\n }\n return 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;* 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": "C++", "task": "A '''Disarium number''' is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.\n\n\n;E.G.\n\n'''135''' is a '''Disarium number''':\n\n 11 + 32 + 53 == 1 + 9 + 125 == 135\n\nThere are a finite number of '''Disarium numbers'''.\n\n\n;Task\n\n* Find and display the first 18 '''Disarium numbers'''.\n\n\n;Stretch\n\n* Find and display all 20 '''Disarium numbers'''.\n\n\n;See also\n\n;* Geeks for Geeks - Disarium numbers\n;* OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...)\n;* Related task: Narcissistic decimal number\n;* Related task: Own digits power sum ''Which seems to be the same task as Narcissistic decimal number...''\n\n", "solution": "#include \n#include \n#include \n#include \n\nstd::vector decompose( int n ) {\n std::vector digits ;\n while ( n != 0 ) {\n digits.push_back( n % 10 ) ;\n n /= 10 ;\n }\n std::reverse( digits.begin( ) , digits.end( ) ) ;\n return digits ;\n}\n\nbool isDisarium( int n ) {\n std::vector digits( decompose( n ) ) ;\n int exposum = 0 ;\n for ( int i = 1 ; i < digits.size( ) + 1 ; i++ ) {\n exposum += static_cast( std::pow(\n static_cast(*(digits.begin( ) + i - 1 )) ,\n static_cast(i) )) ;\n }\n return exposum == n ;\n}\n\nint main( ) {\n std::vector disariums ;\n int current = 0 ;\n while ( disariums.size( ) != 18 ){\n if ( isDisarium( current ) ) \n disariums.push_back( current ) ;\n current++ ;\n }\n for ( int d : disariums ) \n std::cout << d << \" \" ;\n std::cout << std::endl ;\n return 0 ;\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;* 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": "function 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;* 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": "Display a finite linear combination in an infinite vector basis (e_1, e_2,\\ldots).\n\nWrite a function that, when given a finite list of scalars (\\alpha^1,\\alpha^2,\\ldots), creates a string representing the linear combination \\sum_i\\alpha^i e_i in an explicit format often used in mathematics, that is:\n\n:\\alpha^{i_1}e_{i_1}\\pm|\\alpha^{i_2}|e_{i_2}\\pm|\\alpha^{i_3}|e_{i_3}\\pm\\ldots\n\nwhere \\alpha^{i_k}\\neq 0\n\nThe output must comply to the following rules:\n* don't show null terms, unless the whole combination is null. \n::::::: '''e(1)''' is fine, '''e(1) + 0*e(3)''' or '''e(1) + 0''' is wrong.\n* don't show scalars when they are equal to one or minus one. \n::::::: '''e(3)''' is fine, '''1*e(3)''' is wrong.\n* don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction. \n::::::: '''e(4) - e(5)''' is fine, '''e(4) + -e(5)''' is wrong.\n\n\nShow here output for the following lists of scalars:\n\n 1) 1, 2, 3\n 2) 0, 1, 2, 3\n 3) 1, 0, 3, 4\n 4) 1, 2, 0\n 5) 0, 0, 0\n 6) 0\n 7) 1, 1, 1\n 8) -1, -1, -1\n 9) -1, -2, 0, -3\n10) -1\n\n\n", "solution": "#include\n#include\n#include /*Optional, but better if included as fabs, labs and abs functions are being used. */\n\nint main(int argC, char* argV[])\n{\n\t\n\tint i,zeroCount= 0,firstNonZero = -1;\n\tdouble* vector;\n\t\n\tif(argC == 1){\n\t\tprintf(\"Usage : %s \",argV[0]);\n\t}\n\t\n\telse{\n\t\t\n\t\tprintf(\"Vector for [\");\n\t\tfor(i=1;i \");\n\t\t\n\t\t\n\t\tvector = (double*)malloc((argC-1)*sizeof(double));\n\t\t\n\t\tfor(i=1;i<=argC;i++){\n\t\t\tvector[i-1] = atof(argV[i]);\n\t\t\tif(vector[i-1]==0.0)\n\t\t\t\tzeroCount++;\n\t\t\tif(vector[i-1]!=0.0 && firstNonZero==-1)\n\t\t\t\tfirstNonZero = i-1;\n\t\t}\n\n\t\tif(zeroCount == argC){\n\t\t\tprintf(\"0\");\n\t\t}\n\t\t\n\t\telse{\n\t\t\tfor(i=0;i0.0)\n\t\t\t\t\tprintf(\"- %lf e%d \",fabs(vector[i]),i+1);\n\t\t\t\telse if(i==firstNonZero && vector[i]<0 && fabs(vector[i])-abs(vector[i])==0.0)\n\t\t\t\t\tprintf(\"- %ld e%d \",labs(vector[i]),i+1);\n\t\t\t\telse if(i==firstNonZero && vector[i]>0 && fabs(vector[i])-abs(vector[i])>0.0)\n\t\t\t\t\tprintf(\"%lf e%d \",vector[i],i+1);\n\t\t\t\telse if(i==firstNonZero && vector[i]>0 && fabs(vector[i])-abs(vector[i])==0.0)\n\t\t\t\t\tprintf(\"%ld e%d \",vector[i],i+1);\n\t\t\t\telse if(fabs(vector[i])==1.0 && i!=0)\n\t\t\t\t\tprintf(\"%c e%d \",(vector[i]==-1)?'-':'+',i+1);\n\t\t\t\telse if(i!=0 && vector[i]!=0 && fabs(vector[i])-abs(vector[i])>0.0)\n\t\t\t\t\tprintf(\"%c %lf e%d \",(vector[i]<0)?'-':'+',fabs(vector[i]),i+1);\n\t\t\t\telse if(i!=0 && vector[i]!=0 && fabs(vector[i])-abs(vector[i])==0.0)\n\t\t\t\t\tprintf(\"%c %ld e%d \",(vector[i]<0)?'-':'+',labs(vector[i]),i+1);\t\t\t\t\n\t\t\t}\n\t\t}\n\t}\n\t\n\tfree(vector);\n\t\n\treturn 0;\n}\n"} -{"title": "Display a linear combination", "language": "C++ from D", "task": "Display a finite linear combination in an infinite vector basis (e_1, e_2,\\ldots).\n\nWrite a function that, when given a finite list of scalars (\\alpha^1,\\alpha^2,\\ldots), creates a string representing the linear combination \\sum_i\\alpha^i e_i in an explicit format often used in mathematics, that is:\n\n:\\alpha^{i_1}e_{i_1}\\pm|\\alpha^{i_2}|e_{i_2}\\pm|\\alpha^{i_3}|e_{i_3}\\pm\\ldots\n\nwhere \\alpha^{i_k}\\neq 0\n\nThe output must comply to the following rules:\n* don't show null terms, unless the whole combination is null. \n::::::: '''e(1)''' is fine, '''e(1) + 0*e(3)''' or '''e(1) + 0''' is wrong.\n* don't show scalars when they are equal to one or minus one. \n::::::: '''e(3)''' is fine, '''1*e(3)''' is wrong.\n* don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction. \n::::::: '''e(4) - e(5)''' is fine, '''e(4) + -e(5)''' is wrong.\n\n\nShow here output for the following lists of scalars:\n\n 1) 1, 2, 3\n 2) 0, 1, 2, 3\n 3) 1, 0, 3, 4\n 4) 1, 2, 0\n 5) 0, 0, 0\n 6) 0\n 7) 1, 1, 1\n 8) -1, -1, -1\n 9) -1, -2, 0, -3\n10) -1\n\n\n", "solution": "#include \n#include \n#include \n#include \n\ntemplate\nstd::ostream& operator<<(std::ostream& os, const std::vector& v) {\n auto it = v.cbegin();\n auto end = v.cend();\n\n os << '[';\n if (it != end) {\n os << *it;\n it = std::next(it);\n }\n while (it != end) {\n os << \", \" << *it;\n it = std::next(it);\n }\n return os << ']';\n}\n\nstd::ostream& operator<<(std::ostream& os, const std::string& s) {\n return os << s.c_str();\n}\n\nstd::string linearCombo(const std::vector& c) {\n std::stringstream ss;\n for (size_t i = 0; i < c.size(); i++) {\n int n = c[i];\n if (n < 0) {\n if (ss.tellp() == 0) {\n ss << '-';\n } else {\n ss << \" - \";\n }\n } else if (n > 0) {\n if (ss.tellp() != 0) {\n ss << \" + \";\n }\n } else {\n continue;\n }\n\n int av = abs(n);\n if (av != 1) {\n ss << av << '*';\n }\n ss << \"e(\" << i + 1 << ')';\n }\n if (ss.tellp() == 0) {\n return \"0\";\n }\n return ss.str();\n}\n\nint main() {\n using namespace std;\n\n vector> combos{\n {1, 2, 3},\n {0, 1, 2, 3},\n {1, 0, 3, 4},\n {1, 2, 0},\n {0, 0, 0},\n {0},\n {1, 1, 1},\n {-1, -1, -1},\n {-1, -2, 0, -3},\n {-1},\n };\n\n for (auto& c : combos) {\n stringstream ss;\n ss << c;\n cout << setw(15) << ss.str() << \" -> \";\n cout << linearCombo(c) << '\\n';\n }\n\n return 0;\n}"} -{"title": "Display a linear combination", "language": "Python", "task": "Display a finite linear combination in an infinite vector basis (e_1, e_2,\\ldots).\n\nWrite a function that, when given a finite list of scalars (\\alpha^1,\\alpha^2,\\ldots), creates a string representing the linear combination \\sum_i\\alpha^i e_i in an explicit format often used in mathematics, that is:\n\n:\\alpha^{i_1}e_{i_1}\\pm|\\alpha^{i_2}|e_{i_2}\\pm|\\alpha^{i_3}|e_{i_3}\\pm\\ldots\n\nwhere \\alpha^{i_k}\\neq 0\n\nThe output must comply to the following rules:\n* don't show null terms, unless the whole combination is null. \n::::::: '''e(1)''' is fine, '''e(1) + 0*e(3)''' or '''e(1) + 0''' is wrong.\n* don't show scalars when they are equal to one or minus one. \n::::::: '''e(3)''' is fine, '''1*e(3)''' is wrong.\n* don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction. \n::::::: '''e(4) - e(5)''' is fine, '''e(4) + -e(5)''' is wrong.\n\n\nShow here output for the following lists of scalars:\n\n 1) 1, 2, 3\n 2) 0, 1, 2, 3\n 3) 1, 0, 3, 4\n 4) 1, 2, 0\n 5) 0, 0, 0\n 6) 0\n 7) 1, 1, 1\n 8) -1, -1, -1\n 9) -1, -2, 0, -3\n10) -1\n\n\n", "solution": "def 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 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 (deg). 0deg = 360deg = north then clockwise 90deg = east, 180deg = south, 270deg = west. Resolution is 1deg.\n \n\n;See:\n:* openflights.org/data: Airport, airline and route data\n:* Movable Type Scripts: 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 ''wisdom of the crowd'' is the collective opinion of a group of individuals rather than that of a single expert.\n\nWisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other. \n\nThus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.\n\n\nScott E. Page introduced the diversity prediction theorem: \n: ''The squared error of the collective prediction equals the average squared error minus the predictive diversity''. \n\n\nTherefore, when the diversity in a group is large, the error of the crowd is small.\n\n\n;Definitions:\n::* Average Individual Error: Average of the individual squared errors\n::* Collective Error: Squared error of the collective prediction\n::* Prediction Diversity: Average squared distance from the individual predictions to the collective prediction\n::* Diversity Prediction Theorem: ''Given a crowd of predictive models'', then\n:::::: Collective Error = Average Individual Error - Prediction Diversity\n\n;Task:\nFor a given true value and a number of number of estimates (from a crowd), show (here on this page):\n:::* the true value and the crowd estimates\n:::* the average error\n:::* the crowd error\n:::* the prediction diversity\n\n\nUse (at least) these two examples:\n:::* a true value of '''49''' with crowd estimates of: ''' 48 47 51'''\n:::* a true value of '''49''' with crowd estimates of: ''' 48 47 51 42'''\n\n\n\n;Also see:\n:* Wikipedia entry: Wisdom of the crowd\n:* University of Michigan: PDF paper (exists on a web archive, the ''Wayback Machine'').\n\n", "solution": "#include\n#include\n#include\n\nfloat mean(float* arr,int size){\n\tint i = 0;\n\tfloat sum = 0;\n\t\n\twhile(i != size)\n\t\tsum += arr[i++];\n\t\n\treturn sum/size;\n}\n\nfloat variance(float reference,float* arr, int size){\n\tint i=0;\n\tfloat* newArr = (float*)malloc(size*sizeof(float));\n\t\n\tfor(;i \");\n\telse{\n\t\tarr = extractData(argV[2],&len);\n\t\t\n\t\treference = atof(argV[1]);\n\t\t\n\t\tmeanVal = mean(arr,len);\n\n\t\tprintf(\"Average Error : %.9f\\n\",variance(reference,arr,len));\n\t\tprintf(\"Crowd Error : %.9f\\n\",(reference - meanVal)*(reference - meanVal));\n\t\tprintf(\"Diversity : %.9f\",variance(meanVal,arr,len));\n\t}\n\t\n\treturn 0;\n}\n"} -{"title": "Diversity prediction theorem", "language": "C++", "task": "The ''wisdom of the crowd'' is the collective opinion of a group of individuals rather than that of a single expert.\n\nWisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other. \n\nThus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.\n\n\nScott E. Page introduced the diversity prediction theorem: \n: ''The squared error of the collective prediction equals the average squared error minus the predictive diversity''. \n\n\nTherefore, when the diversity in a group is large, the error of the crowd is small.\n\n\n;Definitions:\n::* Average Individual Error: Average of the individual squared errors\n::* Collective Error: Squared error of the collective prediction\n::* Prediction Diversity: Average squared distance from the individual predictions to the collective prediction\n::* Diversity Prediction Theorem: ''Given a crowd of predictive models'', then\n:::::: Collective Error = Average Individual Error - Prediction Diversity\n\n;Task:\nFor a given true value and a number of number of estimates (from a crowd), show (here on this page):\n:::* the true value and the crowd estimates\n:::* the average error\n:::* the crowd error\n:::* the prediction diversity\n\n\nUse (at least) these two examples:\n:::* a true value of '''49''' with crowd estimates of: ''' 48 47 51'''\n:::* a true value of '''49''' with crowd estimates of: ''' 48 47 51 42'''\n\n\n\n;Also see:\n:* Wikipedia entry: Wisdom of the crowd\n:* University of Michigan: PDF paper (exists on a web archive, the ''Wayback Machine'').\n\n", "solution": "#include \n#include \n#include \n\nfloat sum(const std::vector &array)\n{\n return std::accumulate(array.begin(), array.end(), 0.0);\n}\n\nfloat square(float x)\n{\n return x * x;\n}\n\nfloat mean(const std::vector &array)\n{\n return sum(array) / array.size();\n}\n\nfloat averageSquareDiff(float a, const std::vector &predictions)\n{\n std::vector results;\n for (float x : predictions)\n results.push_back(square(x - a));\n return mean(results);\n}\n\nvoid diversityTheorem(float truth, const std::vector &predictions)\n{\n float average = mean(predictions);\n std::cout\n << \"average-error: \" << averageSquareDiff(truth, predictions) << \"\\n\"\n << \"crowd-error: \" << square(truth - average) << \"\\n\"\n << \"diversity: \" << averageSquareDiff(average, predictions) << std::endl;\n}\n\nint main() {\n diversityTheorem(49, {48,47,51});\n diversityTheorem(49, {48,47,51,42});\n return 0;\n}\n"} -{"title": "Diversity prediction theorem", "language": "JavaScript", "task": "The ''wisdom of the crowd'' is the collective opinion of a group of individuals rather than that of a single expert.\n\nWisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other. \n\nThus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.\n\n\nScott E. Page introduced the diversity prediction theorem: \n: ''The squared error of the collective prediction equals the average squared error minus the predictive diversity''. \n\n\nTherefore, when the diversity in a group is large, the error of the crowd is small.\n\n\n;Definitions:\n::* Average Individual Error: Average of the individual squared errors\n::* Collective Error: Squared error of the collective prediction\n::* Prediction Diversity: Average squared distance from the individual predictions to the collective prediction\n::* Diversity Prediction Theorem: ''Given a crowd of predictive models'', then\n:::::: Collective Error = Average Individual Error - Prediction Diversity\n\n;Task:\nFor a given true value and a number of number of estimates (from a crowd), show (here on this page):\n:::* the true value and the crowd estimates\n:::* the average error\n:::* the crowd error\n:::* the prediction diversity\n\n\nUse (at least) these two examples:\n:::* a true value of '''49''' with crowd estimates of: ''' 48 47 51'''\n:::* a true value of '''49''' with crowd estimates of: ''' 48 47 51 42'''\n\n\n\n;Also see:\n:* Wikipedia entry: Wisdom of the crowd\n:* University of Michigan: PDF paper (exists on a web archive, the ''Wayback Machine'').\n\n", "solution": "'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 ''wisdom of the crowd'' is the collective opinion of a group of individuals rather than that of a single expert.\n\nWisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other. \n\nThus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.\n\n\nScott E. Page introduced the diversity prediction theorem: \n: ''The squared error of the collective prediction equals the average squared error minus the predictive diversity''. \n\n\nTherefore, when the diversity in a group is large, the error of the crowd is small.\n\n\n;Definitions:\n::* Average Individual Error: Average of the individual squared errors\n::* Collective Error: Squared error of the collective prediction\n::* Prediction Diversity: Average squared distance from the individual predictions to the collective prediction\n::* Diversity Prediction Theorem: ''Given a crowd of predictive models'', then\n:::::: Collective Error = Average Individual Error - Prediction Diversity\n\n;Task:\nFor a given true value and a number of number of estimates (from a crowd), show (here on this page):\n:::* the true value and the crowd estimates\n:::* the average error\n:::* the crowd error\n:::* the prediction diversity\n\n\nUse (at least) these two examples:\n:::* a true value of '''49''' with crowd estimates of: ''' 48 47 51'''\n:::* a true value of '''49''' with crowd estimates of: ''' 48 47 51 42'''\n\n\n\n;Also see:\n:* Wikipedia entry: Wisdom of the crowd\n:* University of Michigan: PDF paper (exists on a web archive, the ''Wayback Machine'').\n\n", "solution": "'''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": " About the task\nJohn Conway (1937-2020), was a mathematician who also invented several mathematically\noriented computer pastimes, such as the famous Game of Life cellular automaton program.\nDr. Conway invented a simple algorithm for finding the day of the week, given any date.\nThe algorithm was based on calculating the distance of a given date from certain\n\"anchor days\" which follow a pattern for the day of the week upon which they fall.\n\n; Algorithm\nThe formula is calculated assuming that Sunday is 0, Monday 1, and so forth with Saturday 7, and\n\n doomsday = (Tuesday(or 2) + 5(y mod 4) + 4(y mod 100) + 6(y mod 400)) % 7\n\nwhich, for 2021, is 0 (Sunday).\n\nTo calculate the day of the week, we then count days from a close doomsday,\nwith these as charted here by month, then add the doomsday for the year,\nthen get the remainder after dividing by 7. This should give us the number\ncorresponding to the day of the week for that date.\n\n Month\t Doomsday Dates for Month\n --------------------------------------------\n January (common years) 3, 10, 17, 24, 31\n January (leap years) 4, 11, 18, 25\n February (common years) 7, 14, 21, 28\n February (leap years) 1, 8, 15, 22, 29\n March 7, 14, 21, 28\n April 4, 11, 18, 25\n May 2, 9, 16, 23, 30\n June 6, 13, 20, 27\n July 4, 11, 18, 25\n August 1, 8, 15, 22, 29\n September 5, 12, 19, 26\n October 3, 10, 17, 24, 31\n November 7, 14, 21, 28\n December 5, 12, 19, 26\n\n; Task\n\nGiven the following dates:\n\n* 1800-01-06 (January 6, 1800)\n* 1875-03-29 (March 29, 1875)\n* 1915-12-07 (December 7, 1915)\n* 1970-12-23 (December 23, 1970)\n* 2043-05-14 (May 14, 2043)\n* 2077-02-12 (February 12, 2077)\n* 2101-04-02 (April 2, 2101)\n\n\nUse Conway's Doomsday rule to calculate the day of the week for each date.\n\n\n; see also\n* Doomsday rule\n* Tomorrow is the Day After Doomsday (p.28)\n\n\n\n\n", "solution": "#include \n#include \n#include \n\ntypedef struct { \n uint16_t year;\n uint8_t month;\n uint8_t day;\n} Date;\n\nbool leap(uint16_t year) {\n return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst char *weekday(Date date) {\n static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n static const char *days[] = {\n \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n \"Thursday\", \"Friday\", \"Saturday\"\n };\n \n unsigned c = date.year/100, r = date.year%100;\n unsigned s = r/12, t = r%12;\n \n unsigned c_anchor = (5 * (c%4) + 2) % 7;\n unsigned doom = (s + t + (t/4) + c_anchor) % 7;\n unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n const char *past = \"was\", *future = \"will be\";\n const char *months[] = { \"\",\n \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n };\n \n const Date dates[] = {\n {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n {2077,2,12}, {2101,4,2}\n };\n \n int i;\n for (i=0; i < sizeof(dates)/sizeof(Date); i++) {\n printf(\"%s %d, %d %s on a %s.\\n\",\n months[dates[i].month], dates[i].day, dates[i].year,\n dates[i].year > 2021 ? future : past,\n weekday(dates[i]));\n }\n \n return 0;\n}"} -{"title": "Doomsday rule", "language": "C++", "task": " About the task\nJohn Conway (1937-2020), was a mathematician who also invented several mathematically\noriented computer pastimes, such as the famous Game of Life cellular automaton program.\nDr. Conway invented a simple algorithm for finding the day of the week, given any date.\nThe algorithm was based on calculating the distance of a given date from certain\n\"anchor days\" which follow a pattern for the day of the week upon which they fall.\n\n; Algorithm\nThe formula is calculated assuming that Sunday is 0, Monday 1, and so forth with Saturday 7, and\n\n doomsday = (Tuesday(or 2) + 5(y mod 4) + 4(y mod 100) + 6(y mod 400)) % 7\n\nwhich, for 2021, is 0 (Sunday).\n\nTo calculate the day of the week, we then count days from a close doomsday,\nwith these as charted here by month, then add the doomsday for the year,\nthen get the remainder after dividing by 7. This should give us the number\ncorresponding to the day of the week for that date.\n\n Month\t Doomsday Dates for Month\n --------------------------------------------\n January (common years) 3, 10, 17, 24, 31\n January (leap years) 4, 11, 18, 25\n February (common years) 7, 14, 21, 28\n February (leap years) 1, 8, 15, 22, 29\n March 7, 14, 21, 28\n April 4, 11, 18, 25\n May 2, 9, 16, 23, 30\n June 6, 13, 20, 27\n July 4, 11, 18, 25\n August 1, 8, 15, 22, 29\n September 5, 12, 19, 26\n October 3, 10, 17, 24, 31\n November 7, 14, 21, 28\n December 5, 12, 19, 26\n\n; Task\n\nGiven the following dates:\n\n* 1800-01-06 (January 6, 1800)\n* 1875-03-29 (March 29, 1875)\n* 1915-12-07 (December 7, 1915)\n* 1970-12-23 (December 23, 1970)\n* 2043-05-14 (May 14, 2043)\n* 2077-02-12 (February 12, 2077)\n* 2101-04-02 (April 2, 2101)\n\n\nUse Conway's Doomsday rule to calculate the day of the week for each date.\n\n\n; see also\n* Doomsday rule\n* Tomorrow is the Day After Doomsday (p.28)\n\n\n\n\n", "solution": "#include \n#include \n\nstruct Date {\n std::uint16_t year;\n std::uint8_t month;\n std::uint8_t day;\n};\n\nconstexpr bool leap(int year) {\n return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst std::string& weekday(const Date& date) {\n static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n \n static const std::string days[] = {\n \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n \"Friday\", \"Saturday\"\n };\n \n unsigned const c = date.year/100, r = date.year%100;\n unsigned const s = r/12, t = r%12;\n \n unsigned const c_anchor = (5 * (c%4) + 2) % 7;\n unsigned const doom = (s + t + t/4 + c_anchor) % 7;\n unsigned const 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 std::string 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 for (const Date& d : dates) {\n std::cout << months[d.month] << \" \" << (int)d.day << \", \" << d.year;\n std::cout << (d.year > 2021 ? \" will be \" : \" was \");\n std::cout << \"on a \" << weekday(d) << std::endl;\n }\n \n return 0;\n}"} -{"title": "Doomsday rule", "language": "Python", "task": " About the task\nJohn Conway (1937-2020), was a mathematician who also invented several mathematically\noriented computer pastimes, such as the famous Game of Life cellular automaton program.\nDr. Conway invented a simple algorithm for finding the day of the week, given any date.\nThe algorithm was based on calculating the distance of a given date from certain\n\"anchor days\" which follow a pattern for the day of the week upon which they fall.\n\n; Algorithm\nThe formula is calculated assuming that Sunday is 0, Monday 1, and so forth with Saturday 7, and\n\n doomsday = (Tuesday(or 2) + 5(y mod 4) + 4(y mod 100) + 6(y mod 400)) % 7\n\nwhich, for 2021, is 0 (Sunday).\n\nTo calculate the day of the week, we then count days from a close doomsday,\nwith these as charted here by month, then add the doomsday for the year,\nthen get the remainder after dividing by 7. This should give us the number\ncorresponding to the day of the week for that date.\n\n Month\t Doomsday Dates for Month\n --------------------------------------------\n January (common years) 3, 10, 17, 24, 31\n January (leap years) 4, 11, 18, 25\n February (common years) 7, 14, 21, 28\n February (leap years) 1, 8, 15, 22, 29\n March 7, 14, 21, 28\n April 4, 11, 18, 25\n May 2, 9, 16, 23, 30\n June 6, 13, 20, 27\n July 4, 11, 18, 25\n August 1, 8, 15, 22, 29\n September 5, 12, 19, 26\n October 3, 10, 17, 24, 31\n November 7, 14, 21, 28\n December 5, 12, 19, 26\n\n; Task\n\nGiven the following dates:\n\n* 1800-01-06 (January 6, 1800)\n* 1875-03-29 (March 29, 1875)\n* 1915-12-07 (December 7, 1915)\n* 1970-12-23 (December 23, 1970)\n* 2043-05-14 (May 14, 2043)\n* 2077-02-12 (February 12, 2077)\n* 2101-04-02 (April 2, 2101)\n\n\nUse Conway's Doomsday rule to calculate the day of the week for each date.\n\n\n; see also\n* Doomsday rule\n* Tomorrow is the Day After Doomsday (p.28)\n\n\n\n\n", "solution": "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": "Create a function/use an in-built function, to compute the '''dot product''', also known as the '''scalar product''' of two vectors. \n\nIf possible, make the vectors of arbitrary length.\n\n\nAs an example, compute the dot product of the vectors:\n:::: [1, 3, -5] and \n:::: [4, -2, -1] \n\nIf implementing the dot product of two vectors directly:\n:::* each vector must be the same length\n:::* multiply corresponding terms from each vector\n:::* sum the products (to produce the answer)\n\n\n;Related task:\n* [[Vector products]]\n\n", "solution": "#include \n#include \n\nint dot_product(int *, int *, size_t);\n\nint\nmain(void)\n{\n int a[3] = {1, 3, -5};\n int b[3] = {4, -2, -1};\n\n printf(\"%d\\n\", dot_product(a, b, sizeof(a) / sizeof(a[0])));\n\n return EXIT_SUCCESS;\n}\n\nint\ndot_product(int *a, int *b, size_t n)\n{\n int sum = 0;\n size_t i;\n\n for (i = 0; i < n; i++) {\n sum += a[i] * b[i];\n }\n\n return sum;\n}"} -{"title": "Dot product", "language": "C++", "task": "Create a function/use an in-built function, to compute the '''dot product''', also known as the '''scalar product''' of two vectors. \n\nIf possible, make the vectors of arbitrary length.\n\n\nAs an example, compute the dot product of the vectors:\n:::: [1, 3, -5] and \n:::: [4, -2, -1] \n\nIf implementing the dot product of two vectors directly:\n:::* each vector must be the same length\n:::* multiply corresponding terms from each vector\n:::* sum the products (to produce the answer)\n\n\n;Related task:\n* [[Vector products]]\n\n", "solution": "#include \n#include \n\nint main()\n{\n int a[] = { 1, 3, -5 };\n int b[] = { 4, -2, -1 };\n\n std::cout << std::inner_product(a, a + sizeof(a) / sizeof(a[0]), b, 0) << std::endl;\n\n return 0;\n}"} -{"title": "Dot product", "language": "JavaScript", "task": "Create a function/use an in-built function, to compute the '''dot product''', also known as the '''scalar product''' of two vectors. \n\nIf possible, make the vectors of arbitrary length.\n\n\nAs an example, compute the dot product of the vectors:\n:::: [1, 3, -5] and \n:::: [4, -2, -1] \n\nIf implementing the dot product of two vectors directly:\n:::* each vector must be the same length\n:::* multiply corresponding terms from each vector\n:::* sum the products (to produce the answer)\n\n\n;Related task:\n* [[Vector products]]\n\n", "solution": "(() => {\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": "Create a function/use an in-built function, to compute the '''dot product''', also known as the '''scalar product''' of two vectors. \n\nIf possible, make the vectors of arbitrary length.\n\n\nAs an example, compute the dot product of the vectors:\n:::: [1, 3, -5] and \n:::: [4, -2, -1] \n\nIf implementing the dot product of two vectors directly:\n:::* each vector must be the same length\n:::* multiply corresponding terms from each vector\n:::* sum the products (to produce the answer)\n\n\n;Related task:\n* [[Vector products]]\n\n", "solution": "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": "Create a function/use an in-built function, to compute the '''dot product''', also known as the '''scalar product''' of two vectors. \n\nIf possible, make the vectors of arbitrary length.\n\n\nAs an example, compute the dot product of the vectors:\n:::: [1, 3, -5] and \n:::: [4, -2, -1] \n\nIf implementing the dot product of two vectors directly:\n:::* each vector must be the same length\n:::* multiply corresponding terms from each vector\n:::* sum the products (to produce the answer)\n\n\n;Related task:\n* [[Vector products]]\n\n", "solution": "'''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": "Draw a clock. \n\n\nMore specific:\n# Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting \"one thousand and one\", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be ''drawn''; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.\n# The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.\n# A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.\n# A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.\n\n\n;Key points\n* animate simple object\n* timed event \n* polling system resources \n* code clarity\n\n", "solution": "// clockrosetta.c - https://rosettacode.org/wiki/Draw_a_clock\n\n// # Makefile\n// CFLAGS = -O3 -Wall -Wfatal-errors -Wpedantic -Werror\n// LDLIBS = -lX11 -lXext -lm\n// all: clockrosetta\n\n#define SIZE 500\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstatic XdbeBackBuffer dbewindow = 0;\nstatic Display *display;\nstatic Window window;\nstatic int needseg = 1;\nstatic double d2r;\nstatic XSegment seg[61];\nstatic GC gc;\nstatic int mw = SIZE / 2;\nstatic int mh = SIZE / 2;\n\nstatic void\ndraw(void)\n {\n struct tm *ptm;\n int i;\n double angle;\n double delta;\n int radius = (mw < mh ? mw : mh) - 2;\n XPoint pt[3];\n double onetwenty = 3.1415926 * 2 / 3;\n XdbeSwapInfo swapi;\n time_t newtime;\n\n if(dbewindow == 0)\n {\n dbewindow = XdbeAllocateBackBufferName(display, window, XdbeBackground);\n XClearWindow(display, window);\n }\n\n time(&newtime);\n ptm = localtime(&newtime);\n\n if(needseg)\n {\n d2r = atan2(1.0, 0.0) / 90.0;\n for(i = 0; i < 60; i++)\n {\n angle = (double)i * 6.0 * d2r;\n delta = i % 5 ? 0.97 : 0.9;\n seg[i].x1 = mw + radius * delta * sin(angle);\n seg[i].y1 = mh - radius * delta * cos(angle);\n seg[i].x2 = mw + radius * sin(angle);\n seg[i].y2 = mh - radius * cos(angle);\n }\n needseg = 0;\n }\n\n angle = (double)(ptm->tm_sec) * 6.0 * d2r;\n seg[60].x1 = mw;\n seg[60].y1 = mh;\n seg[60].x2 = mw + radius * 0.9 * sin(angle);\n seg[60].y2 = mh - radius * 0.9 * cos(angle);\n XDrawSegments(display, dbewindow, gc, seg, 61);\n\n angle = (double)ptm->tm_min * 6.0 * d2r;\n pt[0].x = mw + radius * 3 / 4 * sin(angle);\n pt[0].y = mh - radius * 3 / 4 * cos(angle);\n pt[1].x = mw + 6 * sin(angle + onetwenty);\n pt[1].y = mh - 6 * cos(angle + onetwenty);\n pt[2].x = mw + 6 * sin(angle - onetwenty);\n pt[2].y = mh - 6 * cos(angle - onetwenty);\n XFillPolygon(display, dbewindow, gc, pt, 3, Nonconvex, CoordModeOrigin);\n\n angle = (double)(ptm->tm_hour * 60 + ptm->tm_min) / 2.0 * d2r;\n pt[0].x = mw + radius / 2 * sin(angle);\n pt[0].y = mh - radius / 2 * cos(angle);\n pt[1].x = mw + 6 * sin(angle + onetwenty);\n pt[1].y = mh - 6 * cos(angle + onetwenty);\n pt[2].x = mw + 6 * sin(angle - onetwenty);\n pt[2].y = mh - 6 * cos(angle - onetwenty);\n XFillPolygon(display, dbewindow, gc, pt, 3, Nonconvex, CoordModeOrigin);\n\n swapi.swap_window = window;\n swapi.swap_action = XdbeBackground;\n XdbeSwapBuffers(display, &swapi, 1);\n }\n\nint\nmain(int argc, char *argv[])\n {\n Atom wm_both_protocols[1];\n Atom wm_delete;\n Atom wm_protocols;\n Window root;\n XEvent event;\n XSetWindowAttributes attr;\n fd_set fd;\n int exposed = 0;\n int more = 1;\n struct timeval tv;\n\n display = XOpenDisplay(NULL);\n\n if(display == NULL)\n {\n fprintf(stderr,\"Error: The display cannot be opened\\n\");\n exit(1);\n }\n\n root = DefaultRootWindow(display);\n wm_delete = XInternAtom(display, \"WM_DELETE_WINDOW\", False);\n wm_protocols = XInternAtom(display, \"WM_PROTOCOLS\", False);\n\n attr.background_pixel = 0x000000;\n attr.event_mask = KeyPress | KeyRelease |\n ButtonPressMask | ButtonReleaseMask | ExposureMask;\n\n window = XCreateWindow(display, root,\n 0, 0, SIZE, SIZE, 0,\n CopyFromParent, InputOutput, CopyFromParent,\n CWBackPixel | CWEventMask,\n &attr\n );\n\n XStoreName(display, window, \"Clock for RosettaCode\");\n\n wm_both_protocols[0] = wm_delete;\n XSetWMProtocols(display, window, wm_both_protocols, 1);\n\n gc = XCreateGC(display, window, 0, NULL);\n XSetForeground(display, gc, 0xFFFF80);\n\n XMapWindow(display, window);\n\n while(more)\n {\n if(QLength(display) > 0)\n {\n XNextEvent(display, &event);\n }\n else\n {\n int maxfd = ConnectionNumber(display);\n\n XFlush(display);\n FD_ZERO(&fd);\n FD_SET(ConnectionNumber(display), &fd);\n\n event.type = LASTEvent;\n tv.tv_sec = 0;\n tv.tv_usec = 250000;\n if(select(maxfd + 1, &fd, NULL, NULL, &tv) > 0)\n {\n if(FD_ISSET(ConnectionNumber(display), &fd))\n {\n XNextEvent(display, &event);\n }\n }\n }\n\n switch(event.type)\n {\n case Expose:\n exposed = 1;\n draw();\n break;\n\n case ButtonRelease:\n case KeyRelease:\n more = 0;\n case ButtonPress: // ignore\n case KeyPress: // ignore\n break;\n\n case LASTEvent: // the timeout comes here\n if(exposed) draw();\n break;\n\n case ConfigureNotify:\n mw = event.xconfigure.width / 2;\n mh = event.xconfigure.height / 2;\n needseg = 1;\n break;\n\n\n case ClientMessage: // for close request from WM\n if(event.xclient.window == window &&\n event.xclient.message_type == wm_protocols &&\n event.xclient.format == 32 &&\n event.xclient.data.l[0] == wm_delete)\n {\n more = 0;\n }\n break;\n\n// default:\n// printf(\"unexpected event.type %d\\n\", event.type);;\n }\n }\n\n XCloseDisplay(display);\n exit(0);\n }\n\n// END"} -{"title": "Draw a clock", "language": "C++", "task": "Draw a clock. \n\n\nMore specific:\n# Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting \"one thousand and one\", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be ''drawn''; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.\n# The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.\n# A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.\n# A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.\n\n\n;Key points\n* animate simple object\n* timed event \n* polling system resources \n* code clarity\n\n", "solution": "#include \n#include \n#include \n\n//--------------------------------------------------------------------------------------------------\nusing namespace std;\n\n//--------------------------------------------------------------------------------------------------\nconst int BMP_SIZE = 300, MY_TIMER = 987654, CENTER = BMP_SIZE >> 1, SEC_LEN = CENTER - 20,\n MIN_LEN = SEC_LEN - 20, HOUR_LEN = MIN_LEN - 20;\nconst float PI = 3.1415926536f;\n\n//--------------------------------------------------------------------------------------------------\nclass vector2\n{\npublic:\n vector2() { x = y = 0; }\n vector2( int a, int b ) { x = a; y = b; }\n void set( int a, int b ) { x = a; y = b; }\n void rotate( float angle_r )\n {\n\tfloat _x = static_cast( x ),\n\t _y = static_cast( y ),\n\t s = sinf( angle_r ),\n\t c = cosf( angle_r ),\n\t a = _x * c - _y * s,\n\t b = _x * s + _y * c;\n\n\tx = static_cast( a );\n\ty = static_cast( b );\n }\n int x, y;\n};\n//--------------------------------------------------------------------------------------------------\nclass myBitmap\n{\npublic:\n myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n ~myBitmap()\n {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n }\n\n bool create( int w, int h )\n {\n\tBITMAPINFO bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes = 1;\n\tbi.bmiHeader.biWidth = w;\n\tbi.bmiHeader.biHeight = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n }\n\n void clear( BYTE clr = 0 )\n {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n }\n\n void setBrushColor( DWORD bClr )\n {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n }\n\n void setPenColor( DWORD c )\n {\n\tclr = c;\n\tcreatePen();\n }\n\n void setPenWidth( int w )\n {\n\twid = w;\n\tcreatePen();\n }\n\n void saveBitmap( string path )\n {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO infoheader;\n\tBITMAP bitmap;\n\tDWORD wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\t\n ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n }\n\n HDC getDC() const { return hdc; }\n int getWidth() const { return width; }\n int getHeight() const { return height; }\n\nprivate:\n void createPen()\n {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n }\n\n HBITMAP bmp;\n HDC hdc;\n HPEN pen;\n HBRUSH brush;\n void *pBits;\n int width, height, wid;\n DWORD clr;\n};\n//--------------------------------------------------------------------------------------------------\nclass clock\n{\npublic:\n clock() \n {\n\t_bmp.create( BMP_SIZE, BMP_SIZE );\n\t_bmp.clear( 100 );\n\t_bmp.setPenWidth( 2 );\n\t_ang = DegToRadian( 6 );\n }\n\t\n void setNow()\n {\n\tGetLocalTime( &_sysTime );\n\tdraw();\n }\n\n float DegToRadian( float degree ) { return degree * ( PI / 180.0f ); }\n\n void setHWND( HWND hwnd ) { _hwnd = hwnd; }\n\nprivate:\n void drawTicks( HDC dc )\n {\n\tvector2 line;\n\t_bmp.setPenWidth( 1 );\n\tfor( int x = 0; x < 60; x++ )\n\t{\n\t line.set( 0, 50 );\n\t line.rotate( static_cast( x + 30 ) * _ang );\n\t MoveToEx( dc, CENTER - static_cast( 2.5f * static_cast( line.x ) ), CENTER - static_cast( 2.5f * static_cast( line.y ) ), NULL );\n\t LineTo( dc, CENTER - static_cast( 2.81f * static_cast( line.x ) ), CENTER - static_cast( 2.81f * static_cast( line.y ) ) );\n\t}\n\n\t_bmp.setPenWidth( 3 );\n\tfor( int x = 0; x < 60; x += 5 )\n\t{\n\t line.set( 0, 50 );\n\t line.rotate( static_cast( x + 30 ) * _ang );\n\t MoveToEx( dc, CENTER - static_cast( 2.5f * static_cast( line.x ) ), CENTER - static_cast( 2.5f * static_cast( line.y ) ), NULL );\n\t LineTo( dc, CENTER - static_cast( 2.81f * static_cast( line.x ) ), CENTER - static_cast( 2.81f * static_cast( line.y ) ) );\n\t}\n }\n\n void drawHands( HDC dc )\n {\n\tfloat hp = DegToRadian( ( 30.0f * static_cast( _sysTime.wMinute ) ) / 60.0f );\n\tint h = ( _sysTime.wHour > 12 ? _sysTime.wHour - 12 : _sysTime.wHour ) * 5;\n\t\t\n\t_bmp.setPenWidth( 3 );\n\t_bmp.setPenColor( RGB( 0, 0, 255 ) );\n\tdrawHand( dc, HOUR_LEN, ( _ang * static_cast( 30 + h ) ) + hp );\n\n\t_bmp.setPenColor( RGB( 0, 128, 0 ) );\n\tdrawHand( dc, MIN_LEN, _ang * static_cast( 30 + _sysTime.wMinute ) );\n\n\t_bmp.setPenWidth( 2 );\n\t_bmp.setPenColor( RGB( 255, 0, 0 ) );\n\tdrawHand( dc, SEC_LEN, _ang * static_cast( 30 + _sysTime.wSecond ) );\n }\n\n void drawHand( HDC dc, int len, float ang )\n {\n\tvector2 line;\n\tline.set( 0, len );\n\tline.rotate( ang );\n\tMoveToEx( dc, CENTER, CENTER, NULL );\n\tLineTo( dc, line.x + CENTER, line.y + CENTER );\n }\n\n void draw()\n {\n\tHDC dc = _bmp.getDC();\n\n\t_bmp.setBrushColor( RGB( 250, 250, 250 ) );\n\tEllipse( dc, 0, 0, BMP_SIZE, BMP_SIZE );\n\t_bmp.setBrushColor( RGB( 230, 230, 230 ) );\n\tEllipse( dc, 10, 10, BMP_SIZE - 10, BMP_SIZE - 10 );\n\n\tdrawTicks( dc );\n\tdrawHands( dc );\n\n\t_bmp.setPenColor( 0 ); _bmp.setBrushColor( 0 );\n\tEllipse( dc, CENTER - 5, CENTER - 5, CENTER + 5, CENTER + 5 );\n\n\t_wdc = GetDC( _hwnd );\n\tBitBlt( _wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY );\n\tReleaseDC( _hwnd, _wdc );\n }\n\n myBitmap _bmp;\n HWND _hwnd;\n HDC _wdc;\n SYSTEMTIME _sysTime;\n float _ang;\n};\n//--------------------------------------------------------------------------------------------------\nclass wnd\n{\npublic:\n wnd() { _inst = this; }\n int wnd::Run( HINSTANCE hInst )\n {\n\t_hInst = hInst;\n\t_hwnd = InitAll();\n\tSetTimer( _hwnd, MY_TIMER, 1000, NULL );\n\t_clock.setHWND( _hwnd );\n\n\tShowWindow( _hwnd, SW_SHOW );\n\tUpdateWindow( _hwnd );\n\n\tMSG msg;\n\tZeroMemory( &msg, sizeof( msg ) );\n\twhile( msg.message != WM_QUIT )\n\t{\n\t if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )\n\t {\n\t\tTranslateMessage( &msg );\n\t\tDispatchMessage( &msg );\n\t }\n\t}\n\treturn UnregisterClass( \"_MY_CLOCK_\", _hInst );\n }\nprivate:\n void wnd::doPaint( HDC dc ) { _clock.setNow(); }\n void wnd::doTimer() { _clock.setNow(); }\n static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )\n {\n\tswitch( msg )\n\t{\n\t case WM_DESTROY: PostQuitMessage( 0 ); break;\n\t case WM_PAINT:\n\t {\n\t\tPAINTSTRUCT ps;\n\t\tHDC dc = BeginPaint( hWnd, &ps );\n\t\t_inst->doPaint( dc );\n\t\tEndPaint( hWnd, &ps );\n\t\treturn 0;\n\t }\n\t case WM_TIMER: _inst->doTimer(); break;\n\t default:\n\t\treturn DefWindowProc( hWnd, msg, wParam, lParam );\n\t}\n\treturn 0;\n }\n\n HWND InitAll()\n {\n\tWNDCLASSEX wcex;\n\tZeroMemory( &wcex, sizeof( wcex ) );\n\twcex.cbSize = sizeof( WNDCLASSEX );\n\twcex.style = CS_HREDRAW | CS_VREDRAW;\n\twcex.lpfnWndProc = ( WNDPROC )WndProc;\n\twcex.hInstance = _hInst;\n\twcex.hCursor = LoadCursor( NULL, IDC_ARROW );\n\twcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n\twcex.lpszClassName = \"_MY_CLOCK_\";\n\n\tRegisterClassEx( &wcex );\n\n\tRECT rc = { 0, 0, BMP_SIZE, BMP_SIZE };\n\tAdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n\tint w = rc.right - rc.left, h = rc.bottom - rc.top;\n\treturn CreateWindow( \"_MY_CLOCK_\", \".: Clock -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n }\n\n static wnd* _inst;\n HINSTANCE _hInst;\n HWND _hwnd;\n clock _clock;\n};\nwnd* wnd::_inst = 0;\n//--------------------------------------------------------------------------------------------------\nint APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )\n{\n wnd myWnd;\n return myWnd.Run( hInstance );\n}\n//--------------------------------------------------------------------------------------------------\n"} -{"title": "Draw a clock", "language": "JavaScript", "task": "Draw a clock. \n\n\nMore specific:\n# Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting \"one thousand and one\", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be ''drawn''; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.\n# The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.\n# A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.\n# A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.\n\n\n;Key points\n* animate simple object\n* timed event \n* polling system resources \n* code clarity\n\n", "solution": "\n\n\n \n \n\n\n \n \n\n\n"} -{"title": "Draw a clock", "language": "Python", "task": "Draw a clock. \n\n\nMore specific:\n# Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting \"one thousand and one\", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be ''drawn''; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.\n# The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.\n# A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.\n# A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.\n\n\n;Key points\n* animate simple object\n* timed event \n* polling system resources \n* code clarity\n\n", "solution": "[http://www.thinkgeek.com/gadgets/watches/6a17/ Think Geek Binary Clock]\n"} -{"title": "Draw a clock", "language": "Python 2.6+, 3.0+", "task": "Draw a clock. \n\n\nMore specific:\n# Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting \"one thousand and one\", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be ''drawn''; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.\n# The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.\n# A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.\n# A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.\n\n\n;Key points\n* animate simple object\n* timed event \n* polling system resources \n* code clarity\n\n", "solution": "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": "#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": "JavaScript from Java", "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\n\n \n \n\n\n \n \n\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": "{{requires|Graphics}}\n\n\n;Task:\nDraw a sphere. \n\nThe sphere can be represented graphically, or in ASCII art, depending on the language capabilities. \n\nEither static or rotational projection is acceptable for this task.\n\n\n;Related tasks:\n* draw a cuboid\n* draw a rotating cube\n* write language name in 3D ASCII\n* draw a Deathstar\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nconst char *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { 30, 30, -50 };\nvoid normalize(double * v)\n{\n double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n v[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n return d < 0 ? -d : 0;\n}\n\nvoid draw_sphere(double R, double k, double ambient)\n{\n int i, j, intensity;\n double b;\n double vec[3], x, y;\n for (i = floor(-R); i <= ceil(R); i++) {\n x = i + .5;\n for (j = floor(-2 * R); j <= ceil(2 * R); j++) {\n y = j / 2. + .5;\n if (x * x + y * y <= R * R) {\n vec[0] = x;\n vec[1] = y;\n vec[2] = sqrt(R * R - x * x - y * y);\n normalize(vec);\n b = pow(dot(light, vec), k) + ambient;\n intensity = (1 - b) * (sizeof(shades) - 1);\n if (intensity < 0) intensity = 0;\n if (intensity >= sizeof(shades) - 1)\n intensity = sizeof(shades) - 2;\n putchar(shades[intensity]);\n } else\n putchar(' ');\n }\n putchar('\\n');\n }\n}\n\n\nint main()\n{\n normalize(light);\n draw_sphere(20, 4, .1);\n draw_sphere(10, 2, .4);\n\n return 0;\n}"} -{"title": "Draw a sphere", "language": "JavaScript from C", "task": "{{requires|Graphics}}\n\n\n;Task:\nDraw a sphere. \n\nThe sphere can be represented graphically, or in ASCII art, depending on the language capabilities. \n\nEither static or rotational projection is acceptable for this task.\n\n\n;Related tasks:\n* draw a cuboid\n* draw a rotating cube\n* write language name in 3D ASCII\n* draw a Deathstar\n\n", "solution": "\n\n\n\nDraw a sphere\n\n\n\nR=\n
\nk=\n
\nambient=\n
\nUnsupportive browser...
\n\n"} -{"title": "Draw a sphere", "language": "Python from C", "task": "{{requires|Graphics}}\n\n\n;Task:\nDraw a sphere. \n\nThe sphere can be represented graphically, or in ASCII art, depending on the language capabilities. \n\nEither static or rotational projection is acceptable for this task.\n\n\n;Related tasks:\n* draw a cuboid\n* draw a rotating cube\n* write language name in 3D ASCII\n* draw a Deathstar\n\n", "solution": "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": "Draw a sphere", "language": "Python 2.7.5", "task": "{{requires|Graphics}}\n\n\n;Task:\nDraw a sphere. \n\nThe sphere can be represented graphically, or in ASCII art, depending on the language capabilities. \n\nEither static or rotational projection is acceptable for this task.\n\n\n;Related tasks:\n* draw a cuboid\n* draw a rotating cube\n* write language name in 3D ASCII\n* draw a Deathstar\n\n", "solution": "from __future__ import print_function, division\nfrom visual import *\n\ntitle = \"VPython: Draw a sphere\"\nscene.title = title\nprint( \"%s\\n\" % title )\n\nprint( 'Drag with right mousebutton to rotate view' )\nprint( 'Drag up+down with middle mousebutton to zoom')\n\nscene.autocenter = True\n\n# uncomment any (or all) of those variants:\nS1 = sphere(pos=(0.0, 0.0, 0.0), radius=1.0, color=color.blue)\n#S2 = sphere(pos=(2.0, 0.0, 0.0), radius=1.0, material=materials.earth)\n#S3 = sphere(pos=(0.0, 2.0, 0.0), radius=1.0, material=materials.BlueMarble)\n#S4 = sphere(pos=(0.0, 0.0, 2.0), radius=1.0,\n# color=color.orange, material=materials.marble)\n\nwhile True: # Animation-loop\n rate(100)\n pass # no animation in this demo\n"} -{"title": "Duffinian numbers", "language": "C++", "task": "A '''Duffinian number''' is a composite number '''k''' that is relatively prime to its sigma sum '''s'''.\n\n''The sigma sum of '''k''' is the sum of the divisors of '''k'''.''\n\n\n;E.G.\n\n'''161''' is a '''Duffinian number'''. \n* It is composite. (7 x 23)\n* The sigma sum '''192''' (1 + 7 + 23 + 161) is relatively prime to '''161'''. \n\n\nDuffinian numbers are very common.\n\nIt is not uncommon for two consecutive integers to be Duffinian (a Duffinian twin) (8, 9), (35, 36), (49, 50), etc.\n\nLess common are Duffinian triplets; three consecutive Duffinian numbers. (63, 64, 65), (323, 324, 325), etc.\n\nMuch, much less common are Duffinian quadruplets and quintuplets. The first Duffinian quintuplet is (202605639573839041, 202605639573839042, 202605639573839043, 202605639573839044, 202605639573839045).\n\nIt is not possible to have six consecutive Duffinian numbers\n\n\n;Task\n* Find and show the first 50 Duffinian numbers.\n* Find and show at least the first 15 Duffinian triplets.\n\n\n;See also\n;* Numbers Aplenty - Duffinian numbers\n;* OEIS:A003624 - Duffinian numbers: composite numbers k relatively prime to sigma(k)\n\n\n\n\n", "solution": "#include \n#include \n#include \n#include \n\nbool duffinian(int n) {\n if (n == 2)\n return false;\n int total = 1, power = 2, m = n;\n for (; (n & 1) == 0; power <<= 1, n >>= 1)\n total += power;\n for (int p = 3; p * p <= n; p += 2) {\n int sum = 1;\n for (power = p; n % p == 0; power *= p, n /= p)\n sum += power;\n total *= sum;\n }\n if (m == n)\n return false;\n if (n > 1)\n total *= n + 1;\n return std::gcd(total, m) == 1;\n}\n\nint main() {\n std::cout << \"First 50 Duffinian numbers:\\n\";\n for (int n = 1, count = 0; count < 50; ++n) {\n if (duffinian(n))\n std::cout << std::setw(3) << n << (++count % 10 == 0 ? '\\n' : ' ');\n }\n std::cout << \"\\nFirst 50 Duffinian triplets:\\n\";\n for (int n = 1, m = 0, count = 0; count < 50; ++n) {\n if (duffinian(n))\n ++m;\n else\n m = 0;\n if (m == 3) {\n std::ostringstream os;\n os << '(' << n - 2 << \", \" << n - 1 << \", \" << n << ')';\n std::cout << std::left << std::setw(24) << os.str()\n << (++count % 3 == 0 ? '\\n' : ' ');\n }\n }\n std::cout << '\\n';\n}"} -{"title": "Dutch national flag problem", "language": "C", "task": "The Dutch national flag is composed of three coloured bands in the order:\n::* red (top)\n::* then white, and\n::* lastly blue (at the bottom). \n\n\nThe problem posed by Edsger Dijkstra is:\n:Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag.\nWhen the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ...\n\n\n;Task\n# Generate a randomized order of balls ''ensuring that they are not in the order of the Dutch national flag''.\n# Sort the balls in a way idiomatic to your language.\n# Check the sorted balls ''are'' in the order of the Dutch national flag.\n\n\n;C.f.:\n* Dutch national flag problem\n* Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)\n\n", "solution": "#include //printf()\n#include //srand(), rand(), RAND_MAX, qsort()\n#include //true, false\n#include //time()\n\n#define NUMBALLS 5 //NUMBALLS>1\n\nint compar(const void *a, const void *b){\n\tchar c1=*(const char*)a, c2=*(const char*)b; //first cast void* to char*, then dereference\n\treturn c1-c2;\n}\n\n_Bool issorted(char *balls){\n\tint i,state;\n\tstate=0;\n\tfor(i=0;istate)state=balls[i];\n\t}\n\treturn true;\n}\n\nvoid printout(char *balls){\n\tint i;\n\tchar str[NUMBALLS+1];\n\tfor(i=0;i\n#include \n\n// Dutch national flag problem\ntemplate \nvoid dnf_partition(BidIt first, BidIt last, const T& low, const T& high)\n{\n for (BidIt next = first; next != last; ) {\n if (*next < low) {\n std::iter_swap(first++, next++);\n } else if (!(*next < high)) {\n std::iter_swap(next, --last);\n } else {\n ++next;\n }\n }\n}\n\nenum Colors { RED, WHITE, BLUE };\n\nvoid print(const Colors *balls, size_t size)\n{\n static const char *label[] = { \"red\", \"white\", \"blue\" };\n\n std::cout << \"Balls:\";\n for (size_t i = 0; i < size; ++i) {\n std::cout << ' ' << label[balls[i]];\n }\n std::cout << \"\\nSorted: \" << std::boolalpha << std::is_sorted(balls, balls + size) << '\\n';\n}\n\nint main()\n{\n Colors balls[] = { RED, WHITE, BLUE, RED, WHITE, BLUE, RED, WHITE, BLUE };\n\n std::random_shuffle(balls, balls + 9);\n print(balls, 9);\n\n dnf_partition(balls, balls + 9, WHITE, BLUE);\n print(balls, 9);\n}"} -{"title": "Dutch national flag problem", "language": "Python", "task": "The Dutch national flag is composed of three coloured bands in the order:\n::* red (top)\n::* then white, and\n::* lastly blue (at the bottom). \n\n\nThe problem posed by Edsger Dijkstra is:\n:Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag.\nWhen the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ...\n\n\n;Task\n# Generate a randomized order of balls ''ensuring that they are not in the order of the Dutch national flag''.\n# Sort the balls in a way idiomatic to your language.\n# Check the sorted balls ''are'' in the order of the Dutch national flag.\n\n\n;C.f.:\n* Dutch national flag problem\n* Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)\n\n", "solution": "import random\n\ncolours_in_order = 'Red White Blue'.split()\n\ndef dutch_flag_sort(items, order=colours_in_order):\n 'return sort of items using the given order'\n reverse_index = dict((x,i) for i,x in enumerate(order))\n return sorted(items, key=lambda x: reverse_index[x])\n\ndef dutch_flag_check(items, order=colours_in_order):\n 'Return True if each item of items is in the given order'\n reverse_index = dict((x,i) for i,x in enumerate(order))\n order_of_items = [reverse_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 True:\n balls = random_balls()\n if not dutch_flag_check(balls):\n break\n print(\"Original Ball order:\", balls)\n sorted_balls = dutch_flag_sort(balls)\n print(\"Sorted Ball Order:\", sorted_balls)\n assert dutch_flag_check(sorted_balls), 'Whoops. Not sorted!'\n\nif __name__ == '__main__':\n main()"} -{"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 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 ('''stretch goal''').\n\n;Related Tasks:\n# [[Greatest common divisor]]\n# [[Sieve of Eratosthenes]]\n\n;Reference:\n* 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 from Julia, Wren", "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 '''101''' through '''106''':\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 '''101'''; \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 < '''101''' 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 > '''101''' so this the earliest adjacent gap difference > '''101'''.\n\n\n;Stretch goal\n\n* Do the same for '''107''' and '''108''' (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++ from D", "task": "Definition:\nAn '''eban''' number is a number that has no letter '''e''' in it when the number is spelled in English.\n\nOr more literally, spelled numbers that contain the letter '''e''' are banned.\n\n\nThe American version of spelling numbers will be used here (as opposed to the British).\n\n'''2,000,000,000''' is two billion, ''not'' two milliard.\n\n\nOnly numbers less than '''one sextillion''' ('''1021''') will be considered in/for this task.\n\nThis will allow optimizations to be used.\n\n\n\n;Task:\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:::* show all output here.\n\n\n;See also:\n:* The MathWorld entry: eban numbers.\n:* The OEIS entry: A6933, eban numbers.\n:* [[Number names]].\n\n", "solution": "#include \n\nstruct Interval {\n int start, end;\n bool print;\n};\n\nint main() {\n 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\n for (auto intv : intervals) {\n if (intv.start == 2) {\n std::cout << \"eban numbers up to and including \" << intv.end << \":\\n\";\n } else {\n std::cout << \"eban numbers bwteen \" << intv.start << \" and \" << intv.end << \" (inclusive):\\n\";\n }\n\n int count = 0;\n for (int i = intv.start; i <= intv.end; i += 2) {\n int b = i / 1000000000;\n int r = i % 1000000000;\n int m = r / 1000000;\n r = i % 1000000;\n int 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) std::cout << i << ' ';\n count++;\n }\n }\n }\n }\n }\n if (intv.print) {\n std::cout << '\\n';\n }\n std::cout << \"count = \" << count << \"\\n\\n\";\n }\n\n return 0;\n}"} -{"title": "Eban numbers", "language": "Python", "task": "Definition:\nAn '''eban''' number is a number that has no letter '''e''' in it when the number is spelled in English.\n\nOr more literally, spelled numbers that contain the letter '''e''' are banned.\n\n\nThe American version of spelling numbers will be used here (as opposed to the British).\n\n'''2,000,000,000''' is two billion, ''not'' two milliard.\n\n\nOnly numbers less than '''one sextillion''' ('''1021''') will be considered in/for this task.\n\nThis will allow optimizations to be used.\n\n\n\n;Task:\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:::* show all output here.\n\n\n;See also:\n:* The MathWorld entry: eban numbers.\n:* The OEIS entry: A6933, eban numbers.\n:* [[Number names]].\n\n", "solution": "# 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": "C++ from D", "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 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* Wikipedia entry: trie.\n* Wikipedia entry: suffix tree \n* Cornell University Library, Computer Science, Data Structures and Algorithms ---> EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.\n\n", "solution": "#include \n#include \n#include \n#include \n\nstruct Node {\n int length;\n std::map edges;\n int suffix;\n\n Node(int l) : length(l), suffix(0) {\n /* empty */\n }\n\n Node(int l, const std::map& m, int s) : length(l), edges(m), suffix(s) {\n /* empty */\n }\n};\n\nconstexpr int evenRoot = 0;\nconstexpr int oddRoot = 1;\n\nstd::vector eertree(const std::string& s) {\n std::vector tree = {\n Node(0, {}, oddRoot),\n Node(-1, {}, oddRoot)\n };\n int suffix = oddRoot;\n int n, k;\n\n for (size_t i = 0; i < s.length(); ++i) {\n char c = s[i];\n for (n = suffix; ; n = tree[n].suffix) {\n k = tree[n].length;\n int b = i - k - 1;\n if (b >= 0 && s[b] == c) {\n break;\n }\n }\n\n auto it = tree[n].edges.find(c);\n auto end = tree[n].edges.end();\n if (it != end) {\n suffix = it->second;\n continue;\n }\n suffix = tree.size();\n tree.push_back(Node(k + 2));\n tree[n].edges[c] = suffix;\n if (tree[suffix].length == 1) {\n tree[suffix].suffix = 0;\n continue;\n }\n while (true) {\n n = tree[n].suffix;\n int b = i - tree[n].length - 1;\n if (b >= 0 && s[b] == c) {\n break;\n }\n }\n tree[suffix].suffix = tree[n].edges[c];\n }\n\n return tree;\n}\n\nstd::vector subPalindromes(const std::vector& tree) {\n std::vector s;\n\n std::function children;\n children = [&children, &tree, &s](int n, std::string p) {\n auto it = tree[n].edges.cbegin();\n auto end = tree[n].edges.cend();\n for (; it != end; it = std::next(it)) {\n auto c = it->first;\n auto m = it->second;\n\n std::string pl = c + p + c;\n s.push_back(pl);\n children(m, pl);\n }\n };\n children(0, \"\");\n\n auto it = tree[1].edges.cbegin();\n auto end = tree[1].edges.cend();\n for (; it != end; it = std::next(it)) {\n auto c = it->first;\n auto n = it->second;\n\n std::string ct(1, c);\n s.push_back(ct);\n\n children(n, ct);\n }\n\n return s;\n}\n\nint main() {\n using namespace std;\n\n auto tree = eertree(\"eertree\");\n auto pal = subPalindromes(tree);\n\n auto it = pal.cbegin();\n auto end = pal.cend();\n\n cout << \"[\";\n if (it != end) {\n cout << it->c_str();\n it++;\n }\n while (it != end) {\n cout << \", \" << it->c_str();\n it++;\n }\n cout << \"]\" << endl;\n\n return 0;\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 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* Wikipedia entry: trie.\n* Wikipedia entry: suffix tree \n* Cornell University Library, Computer Science, Data Structures and Algorithms ---> 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'th 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 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:* Egyptian fractions\n\n\n;References:\n:* Egyptian Number System\n\n", "solution": "#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": "C++ from 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'th 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 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:* Egyptian fractions\n\n\n;References:\n:* Egyptian Number System\n\n", "solution": "#include \n#include \n\ntypedef unsigned long ulong;\n\n/*\n * Remainder is an out paramerter. Use nullptr if the remainder is not needed.\n */\nulong egyptian_division(ulong dividend, ulong divisor, ulong* remainder) {\n constexpr int SIZE = 64;\n ulong powers[SIZE];\n ulong doublings[SIZE];\n int i = 0;\n\n for (; i < SIZE; ++i) {\n powers[i] = 1 << i;\n doublings[i] = divisor << i;\n if (doublings[i] > dividend) {\n break;\n }\n }\n\n ulong answer = 0;\n ulong accumulator = 0;\n\n for (i = i - 1; i >= 0; --i) {\n /*\n * If the current value of the accumulator added to the\n * doublings cell would be less than or equal to the\n * dividend then add it to the accumulator\n */\n if (accumulator + doublings[i] <= dividend) {\n accumulator += doublings[i];\n answer += powers[i];\n }\n }\n\n if (remainder) {\n *remainder = dividend - accumulator;\n }\n return answer;\n}\n\nvoid print(ulong a, ulong b) {\n using namespace std;\n\n ulong x, y;\n x = egyptian_division(a, b, &y);\n\n cout << a << \" / \" << b << \" = \" << x << \" remainder \" << y << endl;\n assert(a == b * x + y);\n}\n\nint main() {\n print(580, 34);\n\n return 0;\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'th 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 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:* Egyptian fractions\n\n\n;References:\n:* 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'th 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 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:* Egyptian fractions\n\n\n;References:\n:* Egyptian Number System\n\n", "solution": "from itertools import product\n\ndef egyptian_divmod(dividend, divisor):\n assert divisor != 0\n pwrs, dbls = [1], [divisor]\n while dbls[-1] <= dividend:\n pwrs.append(pwrs[-1] * 2)\n dbls.append(pwrs[-1] * divisor)\n ans, accum = 0, 0\n for pwr, dbl in zip(pwrs[-2::-1], dbls[-2::-1]):\n if accum + dbl <= dividend:\n accum += dbl\n ans += pwr\n return ans, abs(accum - dividend)\n\nif __name__ == \"__main__\":\n # Test it gives the same results as the divmod built-in\n for i, j in product(range(13), range(1, 13)):\n assert egyptian_divmod(i, j) == divmod(i, j)\n # Mandated result\n i, j = 580, 34\n print(f'{i} divided by {j} using the Egyption method is %i remainder %i'\n % egyptian_divmod(i, j))"} -{"title": "Egyptian division", "language": "Python from Haskell", "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'th 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 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:* Egyptian fractions\n\n\n;References:\n:* 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* 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": "C++", "task": "An '''cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits.\n\nThe rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101.\n\n\n;Task:\nCreate a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice.\n\nThe space state should ''wrap'': this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally.\n\nThis task is basically a generalization of [[one-dimensional cellular automata]].\n\n\n;See also\n* Cellular automata (natureofcode.com)\n\n", "solution": "#include \n#include \n\n#define SIZE\t 80\n#define RULE 30\n#define RULE_TEST(x) (RULE & 1 << (7 & (x)))\n\nvoid evolve(std::bitset &s) {\n int i;\n std::bitset t(0);\n t[SIZE-1] = RULE_TEST( s[0] << 2 | s[SIZE-1] << 1 | s[SIZE-2] );\n t[ 0] = RULE_TEST( s[1] << 2 | s[ 0] << 1 | s[SIZE-1] );\n for (i = 1; i < SIZE-1; i++)\n\tt[i] = RULE_TEST( s[i+1] << 2 | s[i] << 1 | s[i-1] );\n for (i = 0; i < SIZE; i++) s[i] = t[i];\n}\nvoid show(std::bitset s) {\n int i;\n for (i = SIZE; --i; ) printf(\"%c\", s[i] ? '#' : ' ');\n printf(\"\\n\");\n}\nint main() {\n int i;\n std::bitset state(1);\n state <<= SIZE / 2;\n for (i=0; i<10; i++) {\n\tshow(state);\n\tevolve(state);\n }\n return 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* 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* 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": "C++", "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": "#include \n#include \n#include \n\nclass oo {\npublic:\n void evolve( int l, int rule ) {\n std::string cells = \"O\";\n std::cout << \" Rule #\" << rule << \":\\n\";\n for( int x = 0; x < l; x++ ) {\n addNoCells( cells );\n std::cout << std::setw( 40 + ( static_cast( cells.length() ) >> 1 ) ) << cells << \"\\n\";\n step( cells, rule );\n }\n }\nprivate:\n void step( std::string& cells, int rule ) {\n int bin;\n std::string newCells;\n for( size_t i = 0; i < cells.length() - 2; i++ ) {\n bin = 0;\n for( size_t n = i, b = 2; n < i + 3; n++, b >>= 1 ) {\n bin += ( ( cells[n] == 'O' ? 1 : 0 ) << b );\n }\n newCells.append( 1, rule & ( 1 << bin ) ? 'O' : '.' );\n }\n cells = newCells;\n }\n void addNoCells( std::string& s ) {\n char l = s.at( 0 ) == 'O' ? '.' : 'O',\n r = s.at( s.length() - 1 ) == 'O' ? '.' : 'O';\n s = l + s + r;\n s = l + s + r;\n }\n};\nint main( int argc, char* argv[] ) {\n oo o;\n o.evolve( 35, 90 );\n std::cout << \"\\n\";\n return 0;\n}\n"} -{"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* 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": "C++", "task": "Mathematica software for its default random number generator.\n\nSteven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state.\n\nThe purpose of this task is to demonstrate this. With the code written in the most significant.\n\nYou can pick which ever length you want for the initial array but it should be visible in the code so that your output can be reproduced with an other language.\n\nFor extra-credits, you will make this algorithm run as fast as possible in your language, for instance with an extensive use of bitwise logic.\n\n;Reference:\n* Cellular automata: Is Rule 30 random? (PDF).\n\n\n", "solution": "#include \n#include \n\n#define SIZE\t 80\n#define RULE 30\n#define RULE_TEST(x) (RULE & 1 << (7 & (x)))\n\nvoid evolve(std::bitset &s) {\n int i;\n std::bitset t(0);\n t[SIZE-1] = RULE_TEST( s[0] << 2 | s[SIZE-1] << 1 | s[SIZE-2] );\n t[ 0] = RULE_TEST( s[1] << 2 | s[ 0] << 1 | s[SIZE-1] );\n for (i = 1; i < SIZE-1; i++)\n\tt[i] = RULE_TEST( s[i+1] << 2 | s[i] << 1 | s[i-1] );\n for (i = 0; i < SIZE; i++) s[i] = t[i];\n}\nvoid show(std::bitset s) {\n int i;\n for (i = SIZE; i--; ) printf(\"%c\", s[i] ? '#' : ' ');\n printf(\"|\\n\");\n}\nunsigned char byte(std::bitset &s) {\n unsigned char b = 0;\n int i;\n for (i=8; i--; ) {\n\tb |= s[0] << i; \n\tevolve(s);\n }\n return b;\n}\n\nint main() {\n int i;\n std::bitset state(1);\n for (i=10; i--; )\n\tprintf(\"%u%c\", byte(state), i ? ' ' : '\\n');\n return 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* 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 elliptic curve DSA protocol. \n\nIn a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the '''x''' and '''y''' coordinates of any point on the curve:\n\n:::: y^2 = x^3 + a x + b\n\n'''a''' and '''b''' are arbitrary parameters that define the specific curve which is used. \n\nFor this particular task, we'll use the following parameters:\n\n:::: a=0, b=7 \n\nThe most interesting thing about elliptic curves is the fact that it is possible to define a group structure on it. \n\nTo do so we define an internal composition rule with an additive notation '''+''', such that for any three distinct points '''P''', '''Q''' and '''R''' on the curve, whenever these points are aligned, we have:\n\n:::: P + Q + R = 0 \n\nHere '''0''' (zero) is the ''infinity point'', for which the '''x''' and '''y''' values are not defined. It's basically the same kind of point which defines the horizon in projective geometry. \n\nWe'll also assume here that this infinity point is unique and defines the neutral element of the addition.\n\nThis was not the definition of the addition, but only its desired property. For a more accurate definition, we proceed as such:\n\nGiven any three aligned points '''P''', '''Q''' and '''R''', we define the sum '''S = P + Q''' as the point (possibly the infinity point) such that '''S''', '''R''' and the infinity point are aligned.\n\nConsidering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points '''S''' and '''R''' can be aligned with the infinity point if and only if '''S''' and '''R''' are symmetric of one another towards the x-axis (because in that case there is no other candidate than the infinity point to complete the alignment triplet).\n\n'''S''' is thus defined as the symmetric of '''R''' towards the '''x''' axis.\n\nThe task consists in defining the addition which, for any two points of the curve, returns the sum of these two points. You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points. \n\nYou will use the '''a''' and '''b''' parameters of secp256k1, i.e. respectively zero and seven.\n\n''Hint'': You might need to define a \"doubling\" function, that returns '''P+P''' for any given point '''P'''.\n\n''Extra credit'': define the full elliptic curve arithmetic (still not modular, though) by defining a \"multiply\" function that returns, \nfor any point '''P''' and integer '''n''', the point '''P + P + ... + P''' ('''n''' times).\n\n", "solution": "#include \n#include \n\n#define C 7\ntypedef struct { double x, y; } pt;\n\npt zero(void) { return (pt){ INFINITY, INFINITY }; }\n\n// should be INFINITY, but numeric precision is very much in the way\nint is_zero(pt p) { return p.x > 1e20 || p.x < -1e20; }\n\npt neg(pt p) { return (pt){ p.x, -p.y }; }\n\npt dbl(pt p) {\n\tif (is_zero(p)) return p;\n\n\tpt r;\n\tdouble L = (3 * p.x * p.x) / (2 * p.y);\n\tr.x = L * L - 2 * p.x;\n\tr.y = L * (p.x - r.x) - p.y;\n\treturn r;\n}\n\npt add(pt p, pt q) {\n\tif (p.x == q.x && p.y == q.y) return dbl(p);\n\tif (is_zero(p)) return q;\n\tif (is_zero(q)) return p;\n\n\tpt r;\n\tdouble L = (q.y - p.y) / (q.x - p.x);\n\tr.x = L * L - p.x - q.x;\n\tr.y = L * (p.x - r.x) - p.y;\n\treturn r;\n}\n\npt mul(pt p, int n) {\n\tint i;\n\tpt r = zero();\n\n\tfor (i = 1; i <= n; i <<= 1) {\n\t\tif (i & n) r = add(r, p);\n\t\tp = dbl(p);\n\t}\n\treturn r;\n}\n\nvoid show(const char *s, pt p) {\n\tprintf(\"%s\", s);\n\tprintf(is_zero(p) ? \"Zero\\n\" : \"(%.3f, %.3f)\\n\", p.x, p.y);\n}\n\npt from_y(double y) {\n\tpt r;\n\tr.x = pow(y * y - C, 1.0/3);\n\tr.y = y;\n\treturn r;\n}\n\nint main(void) {\n\tpt a, b, c, d;\n\n\ta = from_y(1);\n\tb = from_y(2);\n\n\tshow(\"a = \", a);\n\tshow(\"b = \", b);\n\tshow(\"c = a + b = \", c = add(a, b));\n\tshow(\"d = -c = \", d = neg(c));\n\tshow(\"c + d = \", add(c, d));\n\tshow(\"a + b + d = \", add(a, add(b, d)));\n\tshow(\"a * 12345 = \", mul(a, 12345));\n\n\treturn 0;\n}"} -{"title": "Elliptic curve arithmetic", "language": "C++", "task": "digital signatures. \n\nThe purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the elliptic curve DSA protocol. \n\nIn a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the '''x''' and '''y''' coordinates of any point on the curve:\n\n:::: y^2 = x^3 + a x + b\n\n'''a''' and '''b''' are arbitrary parameters that define the specific curve which is used. \n\nFor this particular task, we'll use the following parameters:\n\n:::: a=0, b=7 \n\nThe most interesting thing about elliptic curves is the fact that it is possible to define a group structure on it. \n\nTo do so we define an internal composition rule with an additive notation '''+''', such that for any three distinct points '''P''', '''Q''' and '''R''' on the curve, whenever these points are aligned, we have:\n\n:::: P + Q + R = 0 \n\nHere '''0''' (zero) is the ''infinity point'', for which the '''x''' and '''y''' values are not defined. It's basically the same kind of point which defines the horizon in projective geometry. \n\nWe'll also assume here that this infinity point is unique and defines the neutral element of the addition.\n\nThis was not the definition of the addition, but only its desired property. For a more accurate definition, we proceed as such:\n\nGiven any three aligned points '''P''', '''Q''' and '''R''', we define the sum '''S = P + Q''' as the point (possibly the infinity point) such that '''S''', '''R''' and the infinity point are aligned.\n\nConsidering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points '''S''' and '''R''' can be aligned with the infinity point if and only if '''S''' and '''R''' are symmetric of one another towards the x-axis (because in that case there is no other candidate than the infinity point to complete the alignment triplet).\n\n'''S''' is thus defined as the symmetric of '''R''' towards the '''x''' axis.\n\nThe task consists in defining the addition which, for any two points of the curve, returns the sum of these two points. You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points. \n\nYou will use the '''a''' and '''b''' parameters of secp256k1, i.e. respectively zero and seven.\n\n''Hint'': You might need to define a \"doubling\" function, that returns '''P+P''' for any given point '''P'''.\n\n''Extra credit'': define the full elliptic curve arithmetic (still not modular, though) by defining a \"multiply\" function that returns, \nfor any point '''P''' and integer '''n''', the point '''P + P + ... + P''' ('''n''' times).\n\n", "solution": "#include \n#include \n\nusing namespace std;\n\n// define a type for the points on the elliptic curve that behaves\n// like a built in type. \nclass EllipticPoint\n{\n double m_x, m_y;\n static constexpr double ZeroThreshold = 1e20;\n static constexpr double B = 7; // the 'b' in y^2 = x^3 + a * x + b\n // 'a' is 0\n \n void Double() noexcept\n {\n if(IsZero())\n {\n // doubling zero is still zero\n return;\n }\n // based on the property of the curve, the line going through the\n // current point and the negative doubled point is tangent to the\n // curve at the current point. wikipedia has a nice diagram.\n if(m_y == 0)\n {\n // at this point the tangent to the curve is vertical.\n // this point doubled is 0\n *this = EllipticPoint();\n }\n else\n {\n double L = (3 * m_x * m_x) / (2 * m_y);\n double newX = L * L - 2 * m_x;\n m_y = L * (m_x - newX) - m_y;\n m_x = newX;\n }\n }\n \npublic:\n friend std::ostream& operator<<(std::ostream&, const EllipticPoint&);\n\n // Create a point that is initialized to Zero\n constexpr EllipticPoint() noexcept : m_x(0), m_y(ZeroThreshold * 1.01) {}\n\n // Create a point based on the yCoordiante. For a curve with a = 0 and b = 7\n // there is only one x for each y\n explicit EllipticPoint(double yCoordinate) noexcept\n {\n m_y = yCoordinate;\n m_x = cbrt(m_y * m_y - B);\n }\n\n // Check if the point is 0\n bool IsZero() const noexcept\n {\n // when the elliptic point is at 0, y = +/- infinity\n bool isNotZero = abs(m_y) < ZeroThreshold;\n return !isNotZero;\n }\n\n // make a negative version of the point (p = -q)\n EllipticPoint operator-() const noexcept\n {\n EllipticPoint negPt;\n negPt.m_x = m_x;\n negPt.m_y = -m_y;\n \n return negPt;\n }\n\n // add a point to this one ( p+=q )\n EllipticPoint& operator+=(const EllipticPoint& rhs) noexcept\n {\n if(IsZero())\n {\n *this = rhs;\n }\n else if (rhs.IsZero())\n {\n // since rhs is zero this point does not need to be\n // modified\n }\n else\n {\n double L = (rhs.m_y - m_y) / (rhs.m_x - m_x);\n if(isfinite(L))\n {\n double newX = L * L - m_x - rhs.m_x;\n m_y = L * (m_x - newX) - m_y;\n m_x = newX;\n }\n else\n {\n if(signbit(m_y) != signbit(rhs.m_y))\n {\n // in this case rhs == -lhs, the result should be 0\n *this = EllipticPoint();\n }\n else\n {\n // in this case rhs == lhs.\n Double();\n }\n }\n }\n\n return *this;\n }\n\n // subtract a point from this one (p -= q)\n EllipticPoint& operator-=(const EllipticPoint& rhs) noexcept\n {\n *this+= -rhs;\n return *this;\n }\n \n // multiply the point by an integer (p *= 3)\n EllipticPoint& operator*=(int rhs) noexcept\n {\n EllipticPoint r;\n EllipticPoint p = *this;\n\n if(rhs < 0)\n {\n // change p * -rhs to -p * rhs\n rhs = -rhs;\n p = -p;\n }\n \n for (int i = 1; i <= rhs; i <<= 1) \n {\n if (i & rhs) r += p;\n p.Double();\n }\n\n *this = r;\n return *this;\n }\n};\n\n// add points (p + q)\ninline EllipticPoint operator+(EllipticPoint lhs, const EllipticPoint& rhs) noexcept\n{\n lhs += rhs;\n return lhs;\n}\n\n// subtract points (p - q)\ninline EllipticPoint operator-(EllipticPoint lhs, const EllipticPoint& rhs) noexcept\n{\n lhs += -rhs;\n return lhs;\n}\n\n// multiply by an integer (p * 3)\ninline EllipticPoint operator*(EllipticPoint lhs, const int rhs) noexcept\n{\n lhs *= rhs;\n return lhs;\n}\n\n// multiply by an integer (3 * p)\ninline EllipticPoint operator*(const int lhs, EllipticPoint rhs) noexcept\n{\n rhs *= lhs;\n return rhs;\n}\n\n\n// print the point\nostream& operator<<(ostream& os, const EllipticPoint& pt)\n{\n if(pt.IsZero()) cout << \"(Zero)\\n\";\n else cout << \"(\" << pt.m_x << \", \" << pt.m_y << \")\\n\";\n return os;\n}\n\nint main(void) {\n const EllipticPoint a(1), b(2);\n cout << \"a = \" << a;\n cout << \"b = \" << b;\n const EllipticPoint c = a + b;\n cout << \"c = a + b = \" << c;\n cout << \"a + b - c = \" << a + b - c;\n cout << \"a + b - (b + a) = \" << a + b - (b + a) << \"\\n\";\n\n cout << \"a + a + a + a + a - 5 * a = \" << a + a + a + a + a - 5 * a;\n cout << \"a * 12345 = \" << a * 12345;\n cout << \"a * -12345 = \" << a * -12345;\n cout << \"a * 12345 + a * -12345 = \" << a * 12345 + a * -12345;\n cout << \"a * 12345 - (a * 12000 + a * 345) = \" << a * 12345 - (a * 12000 + a * 345);\n cout << \"a * 12345 - (a * 12001 + a * 345) = \" << a * 12345 - (a * 12000 + a * 344) << \"\\n\";\n\n const EllipticPoint zero;\n EllipticPoint g;\n cout << \"g = zero = \" << g;\n cout << \"g += a = \" << (g+=a);\n cout << \"g += zero = \" << (g+=zero);\n cout << \"g += b = \" << (g+=b);\n cout << \"b + b - b * 2 = \" << (b + b - b * 2) << \"\\n\";\n\n EllipticPoint special(0); // the point where the curve crosses the x-axis\n cout << \"special = \" << special; // this has the minimum possible value for x\n cout << \"special *= 2 = \" << (special*=2); // doubling it gives zero\n \n return 0;\n}"} -{"title": "Elliptic curve arithmetic", "language": "Python from C", "task": "digital signatures. \n\nThe purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the elliptic curve DSA protocol. \n\nIn a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the '''x''' and '''y''' coordinates of any point on the curve:\n\n:::: y^2 = x^3 + a x + b\n\n'''a''' and '''b''' are arbitrary parameters that define the specific curve which is used. \n\nFor this particular task, we'll use the following parameters:\n\n:::: a=0, b=7 \n\nThe most interesting thing about elliptic curves is the fact that it is possible to define a group structure on it. \n\nTo do so we define an internal composition rule with an additive notation '''+''', such that for any three distinct points '''P''', '''Q''' and '''R''' on the curve, whenever these points are aligned, we have:\n\n:::: P + Q + R = 0 \n\nHere '''0''' (zero) is the ''infinity point'', for which the '''x''' and '''y''' values are not defined. It's basically the same kind of point which defines the horizon in projective geometry. \n\nWe'll also assume here that this infinity point is unique and defines the neutral element of the addition.\n\nThis was not the definition of the addition, but only its desired property. For a more accurate definition, we proceed as such:\n\nGiven any three aligned points '''P''', '''Q''' and '''R''', we define the sum '''S = P + Q''' as the point (possibly the infinity point) such that '''S''', '''R''' and the infinity point are aligned.\n\nConsidering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points '''S''' and '''R''' can be aligned with the infinity point if and only if '''S''' and '''R''' are symmetric of one another towards the x-axis (because in that case there is no other candidate than the infinity point to complete the alignment triplet).\n\n'''S''' is thus defined as the symmetric of '''R''' towards the '''x''' axis.\n\nThe task consists in defining the addition which, for any two points of the curve, returns the sum of these two points. You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points. \n\nYou will use the '''a''' and '''b''' parameters of secp256k1, i.e. respectively zero and seven.\n\n''Hint'': You might need to define a \"doubling\" function, that returns '''P+P''' for any given point '''P'''.\n\n''Extra credit'': define the full elliptic curve arithmetic (still not modular, though) by defining a \"multiply\" function that returns, \nfor any point '''P''' and integer '''n''', the point '''P + P + ... + P''' ('''n''' times).\n\n", "solution": "#!/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 \".\" and almost every directory contains \"..\" (except for a root directory); an empty directory contains no other entries.\n\n", "solution": "#include \n#include \n#include \n\nint dir_empty(const char *path)\n{\n\tstruct dirent *ent;\n\tint ret = 1;\n\n\tDIR *d = opendir(path);\n\tif (!d) {\n\t\tfprintf(stderr, \"%s: \", path);\n\t\tperror(\"\");\n\t\treturn -1;\n\t}\n\n\twhile ((ent = readdir(d))) {\n\t\tif (!strcmp(ent->d_name, \".\") || !(strcmp(ent->d_name, \"..\")))\n\t\t\tcontinue;\n\t\tret = 0;\n\t\tbreak;\n\t}\n\n\tclosedir(d);\n\treturn ret;\n}\n\nint main(int c, char **v)\n{\n\tint ret = 0, i;\n\tif (c < 2) return -1;\n\n\tfor (i = 1; i < c; i++) {\n\t\tret = dir_empty(v[i]);\n\t\tif (ret >= 0)\n\t\t\tprintf(\"%s: %sempty\\n\", v[i], ret ? \"\" : \"not \");\n\t}\n\n\treturn 0;\n}"} -{"title": "Empty 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 \".\" and almost every directory contains \"..\" (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": "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 \".\" and almost every directory contains \"..\" (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": "Languages may have features for dealing specifically with empty strings \n(those containing no characters).\n\n\n;Task:\n::* Demonstrate how to assign an empty string to a variable.\n::* Demonstrate how to check that a string is empty.\n::* Demonstrate how to check that a string is not empty.\n\n\n\n", "solution": "#include \n\n/* ... */\n\n/* assign an empty string */\nconst char *str = \"\";\n\n/* to test a null string */\nif (str) { ... }\n\n/* to test if string is empty */\nif (str[0] == '\\0') { ... }\n\n/* or equivalently use strlen function \n strlen will seg fault on NULL pointer, so check first */\nif ( (str == NULL) || (strlen(str) == 0)) { ... }\n\n/* or compare to a known empty string, same thing. \"== 0\" means strings are equal */\nif (strcmp(str, \"\") == 0) { ... } \n"} -{"title": "Empty string", "language": "C++", "task": "Languages may have features for dealing specifically with empty strings \n(those containing no characters).\n\n\n;Task:\n::* Demonstrate how to assign an empty string to a variable.\n::* Demonstrate how to check that a string is empty.\n::* Demonstrate how to check that a string is not empty.\n\n\n\n", "solution": "#include \n\n// ...\n\n\n // empty string declaration\nstd::string str; // (default constructed)\nstd::string str(); // (default constructor, no parameters)\nstd::string str{}; // (default initialized)\nstd::string str(\"\"); // (const char[] conversion)\nstd::string str{\"\"}; // (const char[] initializer list)\n\n\n\nif (str.empty()) { ... } // to test if string is empty\n\n// we could also use the following\nif (str.length() == 0) { ... }\nif (str == \"\") { ... }\n\n// make a std::string empty\nstr.clear(); // (builtin clear function)\nstr = \"\"; // replace contents with empty string\nstr = {}; // swap contents with temp string (empty),then destruct temp\n\n // swap with empty string\nstd::string tmp{}; // temp empty string \nstr.swap(tmp); // (builtin swap function)\nstd::swap(str, tmp); // swap contents with tmp\n\n\n// create an array of empty strings\nstd::string s_array[100]; // 100 initialized to \"\" (fixed size) \nstd::array arr; // 100 initialized to \"\" (fixed size)\nstd::vector(100,\"\"); // 100 initialized to \"\" (variable size, 100 starting size)\n\n// create empty string as default parameter\nvoid func( std::string& s = {} ); // {} generated default std:string instance\n"} -{"title": "Empty string", "language": "Python", "task": "Languages may have features for dealing specifically with empty strings \n(those containing no characters).\n\n\n;Task:\n::* Demonstrate how to assign an empty string to a variable.\n::* Demonstrate how to check that a string is empty.\n::* Demonstrate how to check that a string is not empty.\n\n\n\n", "solution": "s = ''\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": "Write a computer program that computes and shows its own [[entropy]].\n\n\n;Related Tasks: \n:* [[Fibonacci_word]]\n:* [[Entropy]]\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\n#define MAXLEN 961 //maximum string length\n\nint makehist(char *S,int *hist,int len){\n\tint wherechar[256];\n\tint i,histlen;\n\thistlen=0;\n\tfor(i=0;i<256;i++)wherechar[i]=-1;\n\tfor(i=0;i\n#include \n#include \n\nusing namespace std;\n\nstring readFile (string path) {\n string contents;\n string line;\n ifstream inFile(path);\n while (getline (inFile, line)) {\n contents.append(line);\n contents.append(\"\\n\");\n }\n inFile.close();\n return contents;\n}\n\ndouble entropy (string X) {\n const int MAXCHAR = 127;\n int N = X.length();\n int count[MAXCHAR];\n double count_i;\n char ch;\n double sum = 0.0;\n for (int i = 0; i < MAXCHAR; i++) count[i] = 0;\n for (int pos = 0; pos < N; pos++) {\n ch = X[pos];\n count[(int)ch]++;\n }\n for (int n_i = 0; n_i < MAXCHAR; n_i++) {\n count_i = count[n_i];\n if (count_i > 0) sum -= count_i / N * log2(count_i / N);\n }\n return sum;\n}\n\nint main () {\n cout<\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": "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 A:\n\n::::: A_0 = -7\n::::: A_1 = 1\n::::: A_2 = 5\n::::: A_3 = 2\n::::: A_4 = -4\n::::: A_5 = 3\n::::: A_6 = 0\n\n3 is an equilibrium index, because:\n\n::::: A_0 + A_1 + A_2 = A_4 + A_5 + A_6\n\n6 is also an equilibrium index, because:\n\n::::: A_0 + A_1 + A_2 + A_3 + A_4 + A_5 = 0\n\n(sum of zero elements is zero) \n\n7 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#include \n#include \n\ntemplate \nstd::vector equilibrium(T first, T last)\n{\n typedef typename std::iterator_traits::value_type value_t;\n\n value_t left = 0;\n value_t right = std::accumulate(first, last, value_t(0));\n std::vector result;\n\n for (size_t index = 0; first != last; ++first, ++index)\n {\n right -= *first;\n if (left == right)\n {\n result.push_back(index);\n }\n left += *first;\n }\n return result;\n}\n\ntemplate \nvoid print(const T& value)\n{\n std::cout << value << \"\\n\";\n}\n\nint main() \n{\n const int data[] = { -7, 1, 5, 2, -4, 3, 0 };\n\n std::vector indices(equilibrium(data, data + 7));\n\n std::for_each(indices.begin(), indices.end(), print);\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 A:\n\n::::: A_0 = -7\n::::: A_1 = 1\n::::: A_2 = 5\n::::: A_3 = 2\n::::: A_4 = -4\n::::: A_5 = 3\n::::: A_6 = 0\n\n3 is an equilibrium index, because:\n\n::::: A_0 + A_1 + A_2 = A_4 + A_5 + A_6\n\n6 is also an equilibrium index, because:\n\n::::: A_0 + A_1 + A_2 + A_3 + A_4 + A_5 = 0\n\n(sum of zero elements is zero) \n\n7 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 %r\" % (func.__name__, list(func(data))))"} -{"title": "Erd\u0151s-Nicolas numbers", "language": "C++ from ALGOL 68", "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 Erdos-Nicolas 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 Erdos-Nicolas number because it is perfect (1 + 2 + 3 = 6).\n\n48 is not an Erdos-Nicolas 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 Erdos-Nicolas 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 Erdos-Nicolas numbers which you have the patience for.\n\n;Note\nAs all known Erdos-Nicolas 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 - Erdos-Nicolas numbers\n\n", "solution": "#include \n#include \n#include \n\nint main() {\n const int max_number = 100000000;\n std::vector dsum(max_number + 1, 1);\n std::vector dcount(max_number + 1, 1);\n for (int i = 2; i <= max_number; ++i) {\n for (int j = i + i; j <= max_number; j += i) {\n if (dsum[j] == j) {\n std::cout << std::setw(8) << j\n << \" equals the sum of its first \" << dcount[j]\n << \" divisors\\n\";\n }\n dsum[j] += i;\n ++dcount[j];\n }\n }\n}"} -{"title": "Esthetic numbers", "language": "C++ from D", "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 x 4)''' through index '''(base x 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* 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:;*Numbers Aplenty - Esthetic numbers\n:;*Geeks for Geeks - Stepping numbers\n\n", "solution": "#include \n#include \n#include \n#include \n\nstd::string to(int n, int b) {\n static auto BASE = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n std::stringstream ss;\n while (n > 0) {\n auto rem = n % b;\n n = n / b;\n ss << BASE[rem];\n }\n\n auto fwd = ss.str();\n return std::string(fwd.rbegin(), fwd.rend());\n}\n\nuint64_t uabs(uint64_t a, uint64_t b) {\n if (a < b) {\n return b - a;\n }\n return a - b;\n}\n\nbool isEsthetic(uint64_t n, uint64_t b) {\n if (n == 0) {\n return false;\n }\n auto i = n % b;\n n /= b;\n while (n > 0) {\n auto j = n % b;\n if (uabs(i, j) != 1) {\n return false;\n }\n n /= b;\n i = j;\n }\n return true;\n}\n\nvoid listEsths(uint64_t n, uint64_t n2, uint64_t m, uint64_t m2, int perLine, bool all) {\n std::vector esths;\n const auto dfs = [&esths](uint64_t n, uint64_t m, uint64_t i) {\n auto dfs_impl = [&esths](uint64_t n, uint64_t m, uint64_t i, auto &dfs_ref) {\n if (i >= n && i <= m) {\n esths.push_back(i);\n }\n if (i == 0 || i > m) {\n return;\n }\n auto d = i % 10;\n auto i1 = i * 10 + d - 1;\n auto i2 = i1 + 2;\n if (d == 0) {\n dfs_ref(n, m, i2, dfs_ref);\n } else if (d == 9) {\n dfs_ref(n, m, i1, dfs_ref);\n } else {\n dfs_ref(n, m, i1, dfs_ref);\n dfs_ref(n, m, i2, dfs_ref);\n }\n };\n dfs_impl(n, m, i, dfs_impl);\n };\n\n for (int i = 0; i < 10; i++) {\n dfs(n2, m2, i);\n }\n auto le = esths.size();\n printf(\"Base 10: %d esthetic numbers between %llu and %llu:\\n\", le, n, m);\n if (all) {\n for (size_t c = 0; c < esths.size(); c++) {\n auto esth = esths[c];\n printf(\"%llu \", esth);\n if ((c + 1) % perLine == 0) {\n printf(\"\\n\");\n }\n }\n printf(\"\\n\");\n } else {\n for (int c = 0; c < perLine; c++) {\n auto esth = esths[c];\n printf(\"%llu \", esth);\n }\n printf(\"\\n............\\n\");\n for (size_t i = le - perLine; i < le; i++) {\n auto esth = esths[i];\n printf(\"%llu \", esth);\n }\n printf(\"\\n\");\n }\n printf(\"\\n\");\n}\n\nint main() {\n for (int b = 2; b <= 16; b++) {\n printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4 * b, 6 * b);\n for (int n = 1, c = 0; c < 6 * b; n++) {\n if (isEsthetic(n, b)) {\n c++;\n if (c >= 4 * b) {\n std::cout << to(n, b) << ' ';\n }\n }\n }\n printf(\"\\n\");\n }\n printf(\"\\n\");\n\n // the following all use the obvious range limitations for the numbers in question\n listEsths(1000, 1010, 9999, 9898, 16, true);\n listEsths((uint64_t)1e8, 101'010'101, 13 * (uint64_t)1e7, 123'456'789, 9, true);\n listEsths((uint64_t)1e11, 101'010'101'010, 13 * (uint64_t)1e10, 123'456'789'898, 7, false);\n listEsths((uint64_t)1e14, 101'010'101'010'101, 13 * (uint64_t)1e13, 123'456'789'898'989, 5, false);\n listEsths((uint64_t)1e17, 101'010'101'010'101'010, 13 * (uint64_t)1e16, 123'456'789'898'989'898, 4, false);\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 x 4)''' through index '''(base x 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* 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:;*Numbers Aplenty - Esthetic numbers\n:;*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": "JavaScript from Haskell", "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 x 4)''' through index '''(base x 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* 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:;*Numbers Aplenty - Esthetic numbers\n:;*Geeks for Geeks - Stepping numbers\n\n", "solution": "(() => {\n \"use strict\";\n\n // -------- ESTHETIC NUMBERS IN A GIVEN BASE ---------\n\n // estheticNumbersInBase :: Int -> [Int]\n const estheticNumbersInBase = b =>\n // An infinite sequence of numbers which\n // are esthetic in the given base.\n\n tail(fmapGen(x => x[0])(\n iterate(([, queue]) => {\n const [num, lsd] = queue[0];\n const\n newDigits = [lsd - 1, lsd + 1]\n .flatMap(\n d => (d < b && d >= 0) ? (\n [d]\n ) : []\n );\n\n return Tuple(num)(\n queue.slice(1).concat(\n newDigits.flatMap(d => [\n Tuple((num * b) + d)(d)\n ])\n )\n );\n })(\n Tuple()(\n enumFromTo(1)(b - 1).flatMap(\n d => [Tuple(d)(d)]\n )\n )\n )\n ));\n\n // ---------------------- TESTS ----------------------\n const main = () => {\n\n const samples = b => {\n const\n i = b * 4,\n j = b * 6;\n\n return unlines([\n `Esthetics [${i}..${j}] for base ${b}:`,\n ...chunksOf(10)(\n compose(drop(i - 1), take(j))(\n estheticNumbersInBase(b)\n ).map(n => n.toString(b))\n )\n .map(unwords)\n ]);\n };\n\n const takeInRange = ([a, b]) =>\n compose(\n dropWhile(x => x < a),\n takeWhileGen(x => x <= b)\n );\n\n return [\n enumFromTo(2)(16)\n .map(samples)\n .join(\"\\n\\n\"),\n [\n Tuple(1000)(9999),\n Tuple(100000000)(130000000)\n ]\n .map(\n ([lo, hi]) => unlines([\n `Base 10 Esthetics in range [${lo}..${hi}]:`,\n unlines(\n chunksOf(6)(\n takeInRange([lo, hi])(\n estheticNumbersInBase(10)\n )\n )\n .map(unwords)\n )\n ])\n ).join(\"\\n\\n\")\n ].join(\"\\n\\n\");\n };\n\n // --------------------- GENERIC ---------------------\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\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 // 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 // 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 // dropWhile :: (a -> Bool) -> [a] -> [a]\n // dropWhile :: (Char -> Bool) -> String -> String\n const dropWhile = p =>\n // The suffix remaining after takeWhile p xs.\n xs => {\n const n = xs.length;\n\n return xs.slice(\n 0 < n ? until(\n i => n === i || !p(xs[i])\n )(i => 1 + i)(0) : 0\n );\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 // fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]\n const fmapGen = f =>\n // The map of f over a stream of generator values.\n function* (gen) {\n let v = gen.next();\n\n while (!v.done) {\n yield f(v.value);\n v = gen.next();\n }\n };\n\n\n // iterate :: (a -> a) -> a -> Gen [a]\n const iterate = f =>\n // An infinite list of repeated\n // applications of f to x.\n function* (x) {\n let v = x;\n\n while (true) {\n yield v;\n v = f(v);\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 // 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 ) : Array.from({\n length: n\n }, () => {\n const x = xs.next();\n\n return x.done ? [] : [x.value];\n }).flat();\n\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\n while (!nxt.done && p(v)) {\n ys.push(v);\n nxt = xs.next();\n v = nxt.value;\n }\n\n return ys;\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\n // until :: (a -> Bool) -> (a -> a) -> a -> a\n const until = p =>\n // The value resulting from repeated applications\n // of f to the seed value x, terminating when\n // that result returns true for the predicate p.\n f => x => {\n let v = x;\n\n while (!p(v)) {\n v = f(v);\n }\n\n return v;\n };\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 // MAIN ---\n return main();\n})();"} -{"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 x 4)''' through index '''(base x 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* 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:;*Numbers Aplenty - Esthetic numbers\n:;*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": "Esthetic numbers", "language": "Python from Haskell", "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 x 4)''' through index '''(base x 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* 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:;*Numbers Aplenty - Esthetic numbers\n:;*Geeks for Geeks - Stepping numbers\n\n", "solution": "'''Esthetic numbers'''\n\nfrom functools import reduce\nfrom itertools import (\n accumulate, chain, count, dropwhile,\n islice, product, takewhile\n)\nfrom operator import add\nfrom string import digits, ascii_lowercase\nfrom textwrap import wrap\n\n\n# estheticNumbersInBase :: Int -> [Int]\ndef estheticNumbersInBase(b):\n '''Infinite stream of numbers which are\n esthetic in a given base.\n '''\n return concatMap(\n compose(\n lambda deltas: concatMap(\n lambda headDigit: concatMap(\n compose(\n fromBaseDigits(b),\n scanl(add)(headDigit)\n )\n )(deltas)\n )(range(1, b)),\n replicateList([-1, 1])\n )\n )(count(0))\n\n\n# ------------------------ TESTS -------------------------\ndef main():\n '''Specified tests'''\n def samples(b):\n i, j = b * 4, b * 6\n return '\\n'.join([\n f'Esthetics [{i}..{j}] for base {b}:',\n unlines(wrap(\n unwords([\n showInBase(b)(n) for n in compose(\n drop(i - 1), take(j)\n )(\n estheticNumbersInBase(b)\n )\n ]), 60\n ))\n ])\n\n def takeInRange(a, b):\n return compose(\n dropWhile(lambda x: x < a),\n takeWhile(lambda x: x <= b)\n )\n\n print(\n '\\n\\n'.join([\n samples(b) for b in range(2, 1 + 16)\n ])\n )\n for (lo, hi) in [(1000, 9999), (100_000_000, 130_000_000)]:\n print(f'\\nBase 10 Esthetics in range [{lo}..{hi}]:')\n print(\n unlines(wrap(\n unwords(\n str(x) for x in takeInRange(lo, hi)(\n estheticNumbersInBase(10)\n )\n ), 60\n ))\n )\n\n\n# ------------------- BASES AND DIGITS -------------------\n\n# fromBaseDigits :: Int -> [Int] -> [Int]\ndef fromBaseDigits(b):\n '''An empty list if any digits are out of range for\n the base. Otherwise a list containing an integer.\n '''\n def go(digitList):\n maybeNum = reduce(\n lambda r, d: None if r is None or (\n 0 > d or d >= b\n ) else r * b + d,\n digitList, 0\n )\n return [] if None is maybeNum else [maybeNum]\n return go\n\n\n# toBaseDigits :: Int -> Int -> [Int]\ndef toBaseDigits(b):\n '''A list of the digits of n in base b.\n '''\n def f(x):\n return None if 0 == x else (\n divmod(x, b)[::-1]\n )\n return lambda n: list(reversed(unfoldr(f)(n)))\n\n\n# showInBase :: Int -> Int -> String\ndef showInBase(b):\n '''String representation of n in base b.\n '''\n charSet = digits + ascii_lowercase\n return lambda n: ''.join([\n charSet[i] for i in toBaseDigits(b)(n)\n ])\n\n\n# ----------------------- GENERIC ------------------------\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# concatMap :: (a -> [b]) -> [a] -> [b]\ndef concatMap(f):\n '''A concatenated list over which a function has been\n mapped.\n The list monad can be derived by using a function f\n which wraps its output in a list, (using an empty\n list to represent computational failure).\n '''\n def go(xs):\n return chain.from_iterable(map(f, xs))\n return go\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 '''\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 go\n\n\n# dropWhile :: (a -> Bool) -> [a] -> [a]\n# dropWhile :: (Char -> Bool) -> String -> String\ndef dropWhile(p):\n '''The suffix remainining after takeWhile p xs.\n '''\n return lambda xs: list(\n dropwhile(p, xs)\n )\n\n\n# replicateList :: [a] -> Int -> [[a]]\ndef replicateList(xs):\n '''All distinct lists of length n that\n consist of elements drawn from xs.\n '''\n def rep(n):\n def go(x):\n return [[]] if 1 > x else [\n ([a] + b) for (a, b) in product(\n xs, go(x - 1)\n )\n ]\n return go(n)\n return rep\n\n\n# scanl :: (b -> a -> b) -> b -> [a] -> [b]\ndef scanl(f):\n '''scanl is like reduce, but defines a succession of\n intermediate values, building from the left.\n '''\n def go(a):\n def g(xs):\n return accumulate(chain([a], xs), f)\n return g\n return go\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 def go(xs):\n return list(islice(xs, n))\n return go\n\n\n# takeWhile :: (a -> Bool) -> [a] -> [a]\n# takeWhile :: (Char -> Bool) -> String -> String\ndef takeWhile(p):\n '''The longest (possibly empty) prefix of xs\n in which all elements satisfy p.\n '''\n return lambda xs: list(\n takewhile(p, xs)\n )\n\n\n# unfoldr :: (b -> Maybe (a, b)) -> b -> [a]\ndef unfoldr(f):\n '''Dual to reduce or foldr.\n Where catamorphism reduces a list to a summary value,\n the anamorphic unfoldr builds a list from a seed value.\n As long as f returns (a, b) a is prepended to the list,\n and the residual b is used as the argument for the next\n application of f.\n When f returns None, the completed list is returned.\n '''\n def go(v):\n xr = v, v\n xs = []\n while True:\n xr = f(xr[1])\n if None is not xr:\n xs.append(xr[0])\n else:\n return xs\n return go\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# unwords :: [String] -> String\ndef unwords(xs):\n '''A space-separated string derived\n from a list of words.\n '''\n return ' '.join(xs)\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} -{"title": "Euclid-Mullin sequence", "language": "Python", "task": "Definition\nThe Euclid-Mullin 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\nOEIS 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": "{{Wikipedia|Euler's_identity}}\n\n\nIn mathematics, ''Euler's identity'' is the equality:\n\n ei\\pi + 1 = 0\n\nwhere\n\n e is Euler's number, the base of natural logarithms,\n ''i'' is the imaginary unit, which satisfies ''i''2 = -1, and\n \\pi is pi, the ratio of the circumference of a circle to its diameter.\n\nEuler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:\n\n The number 0.\n The number 1.\n The number \\pi (\\pi = 3.14159+),\n The number e (e = 2.71828+), which occurs widely in mathematical analysis.\n The number ''i'', the imaginary unit of the complex numbers.\n\n;Task\nShow in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation. \n\nMost languages are limited to IEEE 754 floating point calculations so will have some error in the calculation. \n\nIf that is the case, or there is some other limitation, show \nthat ei\\pi + 1 is ''approximately'' equal to zero and \nshow the amount of error in the calculation.\n\nIf your language is capable of symbolic calculations, show \nthat ei\\pi + 1 is ''exactly'' equal to zero for bonus kudos points.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nint main() {\n wchar_t pi = L'\\u03c0'; /* Small pi symbol */\n wchar_t ae = L'\\u2245'; /* Approximately equals symbol */\n double complex e = cexp(M_PI * I) + 1.0;\n setlocale(LC_CTYPE, \"\");\n printf(\"e ^ %lci + 1 = [%.16f, %.16f] %lc 0\\n\", pi, creal(e), cimag(e), ae);\n return 0;\n}"} -{"title": "Euler's identity", "language": "C++", "task": "{{Wikipedia|Euler's_identity}}\n\n\nIn mathematics, ''Euler's identity'' is the equality:\n\n ei\\pi + 1 = 0\n\nwhere\n\n e is Euler's number, the base of natural logarithms,\n ''i'' is the imaginary unit, which satisfies ''i''2 = -1, and\n \\pi is pi, the ratio of the circumference of a circle to its diameter.\n\nEuler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:\n\n The number 0.\n The number 1.\n The number \\pi (\\pi = 3.14159+),\n The number e (e = 2.71828+), which occurs widely in mathematical analysis.\n The number ''i'', the imaginary unit of the complex numbers.\n\n;Task\nShow in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation. \n\nMost languages are limited to IEEE 754 floating point calculations so will have some error in the calculation. \n\nIf that is the case, or there is some other limitation, show \nthat ei\\pi + 1 is ''approximately'' equal to zero and \nshow the amount of error in the calculation.\n\nIf your language is capable of symbolic calculations, show \nthat ei\\pi + 1 is ''exactly'' equal to zero for bonus kudos points.\n\n", "solution": "#include \n#include \n\nint main() {\n std::cout << std::exp(std::complex(0.0, M_PI)) + 1.0 << std::endl;\n return 0;\n}"} -{"title": "Euler's identity", "language": "Python", "task": "{{Wikipedia|Euler's_identity}}\n\n\nIn mathematics, ''Euler's identity'' is the equality:\n\n ei\\pi + 1 = 0\n\nwhere\n\n e is Euler's number, the base of natural logarithms,\n ''i'' is the imaginary unit, which satisfies ''i''2 = -1, and\n \\pi is pi, the ratio of the circumference of a circle to its diameter.\n\nEuler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:\n\n The number 0.\n The number 1.\n The number \\pi (\\pi = 3.14159+),\n The number e (e = 2.71828+), which occurs widely in mathematical analysis.\n The number ''i'', the imaginary unit of the complex numbers.\n\n;Task\nShow in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation. \n\nMost languages are limited to IEEE 754 floating point calculations so will have some error in the calculation. \n\nIf that is the case, or there is some other limitation, show \nthat ei\\pi + 1 is ''approximately'' equal to zero and \nshow the amount of error in the calculation.\n\nIf your language is capable of symbolic calculations, show \nthat ei\\pi + 1 is ''exactly'' equal to zero for bonus kudos points.\n\n", "solution": ">>> 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 Lander and Parkin.\n\nThis conjecture is called Euler's sum of powers conjecture and can be stated as such:\n\n:At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk.\n\nIn 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.\n\nThe task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here.\n\nRelated tasks are:\n* [[Pythagorean quadruples]]. \n* [[Pythagorean triples]].\n\n\n\n", "solution": "// Alexander Maximov, July 2nd, 2015\n#include \n#include \ntypedef long long mylong;\n\nvoid compute(int N, char find_only_one_solution)\n{\tconst int M = 30; /* x^5 == x modulo M=2*3*5 */\n\tint a, b, c, d, e;\n\tmylong s, t, max, *p5 = (mylong*)malloc(sizeof(mylong)*(N+M));\n \n\tfor(s=0; s < N; ++s)\n\t\tp5[s] = s * s, p5[s] *= p5[s] * s;\n\tfor(max = p5[N - 1]; s < (N + M); p5[s++] = max + 1);\n \n\tfor(a = 1; a < N; ++a)\n\tfor(b = a + 1; b < N; ++b)\n\tfor(c = b + 1; c < N; ++c)\n\tfor(d = c + 1, e = d + ((t = p5[a] + p5[b] + p5[c]) % M); ((s = t + p5[d]) <= max); ++d, ++e)\n\t{\tfor(e -= M; p5[e + M] <= s; e += M); /* jump over M=30 values for e>d */\n\t\tif(p5[e] == s)\n\t\t{\tprintf(\"%d %d %d %d %d\\r\\n\", a, b, c, d, e);\n\t\t\tif(find_only_one_solution) goto onexit;\n\t\t}\n\t}\nonexit:\n\tfree(p5);\n}\n\nint main(void)\n{\n\tint tm = clock();\n\tcompute(250, 0);\n\tprintf(\"time=%d milliseconds\\r\\n\", (int)((clock() - tm) * 1000 / CLOCKS_PER_SEC));\n\treturn 0;\n}"} -{"title": "Euler's sum of powers conjecture", "language": "C++", "task": "There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.\n\nThis conjecture is called Euler's sum of powers conjecture and can be stated as such:\n\n:At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk.\n\nIn 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.\n\nThe task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here.\n\nRelated tasks are:\n* [[Pythagorean quadruples]]. \n* [[Pythagorean triples]].\n\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nbool find()\n{\n const auto MAX = 250;\n vector pow5(MAX);\n for (auto i = 1; i < MAX; i++)\n pow5[i] = (double)i * i * i * i * i;\n for (auto x0 = 1; x0 < MAX; x0++) {\n for (auto x1 = 1; x1 < x0; x1++) {\n for (auto x2 = 1; x2 < x1; x2++) {\n for (auto x3 = 1; x3 < x2; x3++) {\n auto sum = pow5[x0] + pow5[x1] + pow5[x2] + pow5[x3];\n if (binary_search(pow5.begin(), pow5.end(), sum))\n {\n cout << x0 << \" \" << x1 << \" \" << x2 << \" \" << x3 << \" \" << pow(sum, 1.0 / 5.0) << endl;\n return true;\n }\n }\n }\n }\n }\n // not found\n return false;\n}\n\nint main(void)\n{\n int tm = clock();\n if (!find())\n cout << \"Nothing found!\\n\";\n cout << \"time=\" << (int)((clock() - tm) * 1000 / CLOCKS_PER_SEC) << \" milliseconds\\r\\n\";\n return 0;\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 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": "JavaScript from Haskell", "task": "There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.\n\nThis conjecture is called Euler's sum of powers conjecture and can be stated as such:\n\n:At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk.\n\nIn 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.\n\nThe task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here.\n\nRelated tasks are:\n* [[Pythagorean quadruples]]. \n* [[Pythagorean triples]].\n\n\n\n", "solution": "(() => {\n 'use strict';\n\n const main = () => {\n\n const\n iFrom = 1,\n iTo = 249,\n xs = enumFromTo(1, 249),\n p5 = x => Math.pow(x, 5);\n\n const\n // powerMap :: Dict Int Int\n powerMap = mapFromList(\n zip(map(p5, xs), xs)\n ),\n // sumMap :: Dict Int (Int, Int)\n sumMap = mapFromList(\n bind(\n xs,\n x => bind(\n tail(xs),\n y => Tuple(\n p5(x) + p5(y),\n Tuple(x, y)\n )\n )\n )\n );\n\n // mbExample :: Maybe (Int, Int)\n const mbExample = find(\n tpl => member(fst(tpl) - snd(tpl), sumMap),\n bind(\n map(x => parseInt(x, 10),\n keys(powerMap)\n ),\n p => bind(\n takeWhile(\n x => x < p,\n map(x => parseInt(x, 10),\n keys(sumMap)\n )\n ),\n s => [Tuple(p, s)]\n )\n )\n );\n\n // showExample :: (Int, Int) -> String\n const showExample = tpl => {\n const [p, s] = Array.from(tpl);\n const [a, b] = Array.from(sumMap[p - s]);\n const [c, d] = Array.from(sumMap[s]);\n return 'Counter-example found:\\n' + intercalate(\n '^5 + ',\n map(str, [a, b, c, d])\n ) + '^5 = ' + str(powerMap[p]) + '^5';\n };\n\n return maybe(\n 'No counter-example found',\n showExample,\n mbExample\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 // bind (>>=) :: [a] -> (a -> [b]) -> [b]\n const bind = (xs, mf) => [].concat.apply([], xs.map(mf));\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 // find :: (a -> Bool) -> [a] -> Maybe a\n const find = (p, xs) => {\n for (let i = 0, lng = xs.length; i < lng; i++) {\n if (p(xs[i])) return Just(xs[i]);\n }\n return Nothing();\n };\n\n // fst :: (a, b) -> a\n const fst = tpl => tpl[0];\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 // keys :: Dict -> [String]\n const keys = Object.keys;\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 // mapFromList :: [(k, v)] -> Dict\n const mapFromList = kvs =>\n kvs.reduce(\n (a, kv) => {\n const k = kv[0];\n return Object.assign(a, {\n [\n (('string' === typeof k) && k) || JSON.stringify(k)\n ]: kv[1]\n });\n }, {}\n );\n\n // Default value (v) if m.Nothing, or f(m.Just)\n\n // maybe :: b -> (a -> b) -> Maybe a -> b\n const maybe = (v, f, m) =>\n m.Nothing ? v : f(m.Just);\n\n // member :: Key -> Dict -> Bool\n const member = (k, dct) => k in dct;\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 // 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 // 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\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 // MAIN ---\n return main();\n})();"} -{"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 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": "Euler's sum of powers conjecture", "language": "Python 2.6+", "task": "There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.\n\nThis conjecture is called Euler's sum of powers conjecture and can be stated as such:\n\n:At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk.\n\nIn 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.\n\nThe task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here.\n\nRelated tasks are:\n* [[Pythagorean quadruples]]. \n* [[Pythagorean triples]].\n\n\n\n", "solution": "from itertools import combinations\n\ndef 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, x1, x2, x3 in combinations(range(1, max_n), 4):\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": "Euler's sum of powers conjecture", "language": "Python 3.7", "task": "There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.\n\nThis conjecture is called Euler's sum of powers conjecture and can be stated as such:\n\n:At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk.\n\nIn 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.\n\nThe task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here.\n\nRelated tasks are:\n* [[Pythagorean quadruples]]. \n* [[Pythagorean triples]].\n\n\n\n", "solution": "'''Euler's sum of powers conjecture'''\n\nfrom itertools import (chain, takewhile)\n\n\n# main :: IO ()\ndef main():\n '''Search for counter-example'''\n\n xs = enumFromTo(1)(249)\n\n powerMap = {x**5: x for x in xs}\n sumMap = {\n x**5 + y**5: (x, y)\n for x in xs[1:]\n for y in xs if x > y\n }\n\n # isExample :: (Int, Int) -> Bool\n def isExample(ps):\n p, s = ps\n return p - s in sumMap\n\n # display :: (Int, Int) -> String\n def display(ps):\n p, s = ps\n a, b = sumMap[p - s]\n c, d = sumMap[s]\n return '^5 + '.join([str(n) for n in [a, b, c, d]]) + (\n '^5 = ' + str(powerMap[p]) + '^5'\n )\n\n print(__doc__ + ' \u2013 counter-example:\\n')\n print(\n maybe('No counter-example found.')(display)(\n find(isExample)(\n bind(powerMap.keys())(\n lambda p: bind(\n takewhile(\n lambda x: p > x,\n sumMap.keys()\n )\n )(lambda s: [(p, s)])\n )\n )\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 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# bind (>>=) :: [a] -> (a -> [b]) -> [b]\ndef bind(xs):\n '''List 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(f):\n return chain.from_iterable(map(f, xs))\n return go\n\n\n# enumFromTo :: (Int, Int) -> [Int]\ndef enumFromTo(m):\n '''Integer enumeration from m to n.'''\n return lambda n: range(m, 1 + n)\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 try:\n return Just(next(x for x in xs if p(x)))\n except StopIteration:\n return Nothing()\n return go\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# MAIN ---\nif __name__ == '__main__':\n main()"} -{"title": "Even or odd", "language": "C", "task": "Test whether an integer is even or odd.\n\nThere is more than one way to solve this task:\n\n* Use the even and odd predicates, if the language provides them.\n* Check the least significant digit. With binary integers, ''i iff ''i'' is even, or equals 1 iff ''i'' is odd.\n* Divide ''i'' by 2. The remainder equals 0 iff ''i'' is even. The remainder equals +1 or -1 iff ''i'' is odd.\n* Use modular congruences:\n** ''i'' 0 (mod 2) iff ''i'' is even.\n** ''i'' 1 (mod 2) iff ''i'' is odd.\n\n", "solution": "mpz_t x;\n...\nif (mpz_even_p(x)) { /* x is even */ }\nif (mpz_odd_p(x)) { /* x is odd */ }"} -{"title": "Even or odd", "language": "C++", "task": "Test whether an integer is even or odd.\n\nThere is more than one way to solve this task:\n\n* Use the even and odd predicates, if the language provides them.\n* Check the least significant digit. With binary integers, ''i iff ''i'' is even, or equals 1 iff ''i'' is odd.\n* Divide ''i'' by 2. The remainder equals 0 iff ''i'' is even. The remainder equals +1 or -1 iff ''i'' is odd.\n* Use modular congruences:\n** ''i'' 0 (mod 2) iff ''i'' is even.\n** ''i'' 1 (mod 2) iff ''i'' is odd.\n\n", "solution": "template < typename T >\nconstexpr inline bool isEven( const T& v )\n{\n return isEven( int( v ) );\n}\n\ntemplate <>\nconstexpr inline bool isEven< int >( const int& v )\n{\n return (v & 1) == 0;\n}\n\ntemplate < typename T >\nconstexpr inline bool isOdd( const T& v )\n{\n return !isEven(v);\n}\n"} -{"title": "Even or odd", "language": "JavaScript", "task": "Test whether an integer is even or odd.\n\nThere is more than one way to solve this task:\n\n* Use the even and odd predicates, if the language provides them.\n* Check the least significant digit. With binary integers, ''i iff ''i'' is even, or equals 1 iff ''i'' is odd.\n* Divide ''i'' by 2. The remainder equals 0 iff ''i'' is even. The remainder equals +1 or -1 iff ''i'' is odd.\n* Use modular congruences:\n** ''i'' 0 (mod 2) iff ''i'' is even.\n** ''i'' 1 (mod 2) iff ''i'' is odd.\n\n", "solution": "(() => {\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": "Test whether an integer is even or odd.\n\nThere is more than one way to solve this task:\n\n* Use the even and odd predicates, if the language provides them.\n* Check the least significant digit. With binary integers, ''i iff ''i'' is even, or equals 1 iff ''i'' is odd.\n* Divide ''i'' by 2. The remainder equals 0 iff ''i'' is even. The remainder equals +1 or -1 iff ''i'' is odd.\n* Use modular congruences:\n** ''i'' 0 (mod 2) iff ''i'' is even.\n** ''i'' 1 (mod 2) iff ''i'' is odd.\n\n", "solution": ">>> 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 'closeness' of its argument to the target string.\n* A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated.\n* While the parent is not yet the target:\n:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.\n:* Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others.\n:* repeat until the parent converges, (hopefully), to the target.\n\n\n;See also:\n* Wikipedia entry: Weasel algorithm.\n* Wikipedia entry: Evolutionary algorithm.\n\n\nNote: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions\n\nA cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically,\n* While the parent is not yet the target:\n:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.\n\nNote that some of the the solutions given retain characters in the mutated string that are ''correct'' in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of \"converges\"\n\n (:* repeat until the parent converges, (hopefully), to the target.\n\nStrictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by ''not'' being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent!\n\nAs illustration of this error, the code for 8th has the following remark.\n\n Create a new string based on the TOS, '''changing randomly any characters which\n don't already match the target''':\n\n''NOTE:'' this has been changed, the 8th version is completely random now\n\nClearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters!\n\nTo ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.\n\n", "solution": "#include \n#include \n#include \n\nconst char target[] = \"METHINKS IT IS LIKE A WEASEL\";\nconst char tbl[] = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ \";\n\n#define CHOICE (sizeof(tbl) - 1)\n#define MUTATE 15\n#define COPIES 30\n\n/* returns random integer from 0 to n - 1 */\nint irand(int n)\n{\n\tint r, rand_max = RAND_MAX - (RAND_MAX % n);\n\twhile((r = rand()) >= rand_max);\n\treturn r / (rand_max / n);\n}\n\n/* number of different chars between a and b */\nint unfitness(const char *a, const char *b)\n{\n\tint i, sum = 0;\n\tfor (i = 0; a[i]; i++)\n\t\tsum += (a[i] != b[i]);\n\treturn sum;\n}\n\n/* each char of b has 1/MUTATE chance of differing from a */\nvoid mutate(const char *a, char *b)\n{\n\tint i;\n\tfor (i = 0; a[i]; i++)\n\t\tb[i] = irand(MUTATE) ? a[i] : tbl[irand(CHOICE)];\n\n\tb[i] = '\\0';\n}\n\nint main()\n{\n\tint i, best_i, unfit, best, iters = 0;\n\tchar specimen[COPIES][sizeof(target) / sizeof(char)];\n\n\t/* init rand string */\n\tfor (i = 0; target[i]; i++)\n\t\tspecimen[0][i] = tbl[irand(CHOICE)];\n\tspecimen[0][i] = 0;\n\n\tdo {\n\t\tfor (i = 1; i < COPIES; i++)\n\t\t\tmutate(specimen[0], specimen[i]);\n\n\t\t/* find best fitting string */\n\t\tfor (best_i = i = 0; i < COPIES; i++) {\n\t\t\tunfit = unfitness(target, specimen[i]);\n\t\t\tif(unfit < best || !i) {\n\t\t\t\tbest = unfit;\n\t\t\t\tbest_i = i;\n\t\t\t}\n\t\t}\n\n\t\tif (best_i) strcpy(specimen[0], specimen[best_i]);\n\t\tprintf(\"iter %d, score %d: %s\\n\", iters++, best, specimen[0]);\n\t} while (best);\n\n\treturn 0;\n}"} -{"title": "Evolutionary algorithm", "language": "C++", "task": "Starting with:\n* The target string: \"METHINKS IT IS LIKE A WEASEL\".\n* An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent).\n* A fitness function that computes the 'closeness' of its argument to the target string.\n* A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated.\n* While the parent is not yet the target:\n:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.\n:* Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others.\n:* repeat until the parent converges, (hopefully), to the target.\n\n\n;See also:\n* Wikipedia entry: Weasel algorithm.\n* Wikipedia entry: Evolutionary algorithm.\n\n\nNote: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions\n\nA cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically,\n* While the parent is not yet the target:\n:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.\n\nNote that some of the the solutions given retain characters in the mutated string that are ''correct'' in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of \"converges\"\n\n (:* repeat until the parent converges, (hopefully), to the target.\n\nStrictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by ''not'' being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent!\n\nAs illustration of this error, the code for 8th has the following remark.\n\n Create a new string based on the TOS, '''changing randomly any characters which\n don't already match the target''':\n\n''NOTE:'' this has been changed, the 8th version is completely random now\n\nClearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters!\n\nTo ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstd::string allowed_chars = \" ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n// class selection contains the fitness function, encapsulates the\n// target string and allows access to it's length. The class is only\n// there for access control, therefore everything is static. The\n// string target isn't defined in the function because that way the\n// length couldn't be accessed outside.\nclass selection\n{\npublic:\n // this function returns 0 for the destination string, and a\n // negative fitness for a non-matching string. The fitness is\n // calculated as the negated sum of the circular distances of the\n // string letters with the destination letters.\n static int fitness(std::string candidate)\n {\n assert(target.length() == candidate.length());\n\n int fitness_so_far = 0;\n\n for (int i = 0; i < target.length(); ++i)\n {\n int target_pos = allowed_chars.find(target[i]);\n int candidate_pos = allowed_chars.find(candidate[i]);\n int diff = std::abs(target_pos - candidate_pos);\n fitness_so_far -= std::min(diff, int(allowed_chars.length()) - diff);\n }\n\n return fitness_so_far;\n }\n\n // get the target string length\n static int target_length() { return target.length(); }\nprivate:\n static std::string target;\n};\n\nstd::string selection::target = \"METHINKS IT IS LIKE A WEASEL\";\n\n// helper function: cyclically move a character through allowed_chars\nvoid move_char(char& c, int distance)\n{\n while (distance < 0)\n distance += allowed_chars.length();\n int char_pos = allowed_chars.find(c);\n c = allowed_chars[(char_pos + distance) % allowed_chars.length()];\n}\n\n// mutate the string by moving the characters by a small random\n// distance with the given probability\nstd::string mutate(std::string parent, double mutation_rate)\n{\n for (int i = 0; i < parent.length(); ++i)\n if (std::rand()/(RAND_MAX + 1.0) < mutation_rate)\n {\n int distance = std::rand() % 3 + 1;\n if(std::rand()%2 == 0)\n move_char(parent[i], distance);\n else\n move_char(parent[i], -distance);\n }\n return parent;\n}\n\n// helper function: tell if the first argument is less fit than the\n// second\nbool less_fit(std::string const& s1, std::string const& s2)\n{\n return selection::fitness(s1) < selection::fitness(s2);\n}\n\nint main()\n{\n int const C = 100;\n\n std::srand(time(0));\n\n std::string parent;\n for (int i = 0; i < selection::target_length(); ++i)\n {\n parent += allowed_chars[std::rand() % allowed_chars.length()];\n }\n\n int const initial_fitness = selection::fitness(parent);\n\n for(int fitness = initial_fitness;\n fitness < 0;\n fitness = selection::fitness(parent))\n {\n std::cout << parent << \": \" << fitness << \"\\n\";\n double const mutation_rate = 0.02 + (0.9*fitness)/initial_fitness;\n std::vector childs;\n childs.reserve(C+1);\n\n childs.push_back(parent);\n for (int i = 0; i < C; ++i)\n childs.push_back(mutate(parent, mutation_rate));\n\n parent = *std::max_element(childs.begin(), childs.end(), less_fit);\n }\n std::cout << \"final string: \" << parent << \"\\n\";\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 'closeness' of its argument to the target string.\n* A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated.\n* While the parent is not yet the target:\n:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.\n:* Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others.\n:* repeat until the parent converges, (hopefully), to the target.\n\n\n;See also:\n* Wikipedia entry: Weasel algorithm.\n* Wikipedia entry: Evolutionary algorithm.\n\n\nNote: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions\n\nA cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically,\n* While the parent is not yet the target:\n:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.\n\nNote that some of the the solutions given retain characters in the mutated string that are ''correct'' in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of \"converges\"\n\n (:* repeat until the parent converges, (hopefully), to the target.\n\nStrictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by ''not'' being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent!\n\nAs illustration of this error, the code for 8th has the following remark.\n\n Create a new string based on the TOS, '''changing randomly any characters which\n don't already match the target''':\n\n''NOTE:'' this has been changed, the 8th version is completely random now\n\nClearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters!\n\nTo ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.\n\n", "solution": "// ------------------------------------- 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 'closeness' of its argument to the target string.\n* A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated.\n* While the parent is not yet the target:\n:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.\n:* Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others.\n:* repeat until the parent converges, (hopefully), to the target.\n\n\n;See also:\n* Wikipedia entry: Weasel algorithm.\n* Wikipedia entry: Evolutionary algorithm.\n\n\nNote: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions\n\nA cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically,\n* While the parent is not yet the target:\n:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.\n\nNote that some of the the solutions given retain characters in the mutated string that are ''correct'' in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of \"converges\"\n\n (:* repeat until the parent converges, (hopefully), to the target.\n\nStrictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by ''not'' being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent!\n\nAs illustration of this error, the code for 8th has the following remark.\n\n Create a new string based on the TOS, '''changing randomly any characters which\n don't already match the target''':\n\n''NOTE:'' this has been changed, the 8th version is completely random now\n\nClearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters!\n\nTo ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.\n\n", "solution": "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 <= 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 <= 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": "Computer/zero Assembly}}\n\n;Task:\nCreate a [[Computer/zero Assembly emulator. You may consider this webpage as a reference implementation. Output the results of the sample programs \"2+2\" and \"7*8\" found there.\n\n:* 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:* 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